Threads.cpp revision 32f37c22f60b7a1a6ccfa351700f80c03918d4fe
1/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9**     http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21#define ATRACE_TAG ATRACE_TAG_AUDIO
22
23#include "Configuration.h"
24#include <math.h>
25#include <fcntl.h>
26#include <linux/futex.h>
27#include <sys/stat.h>
28#include <sys/syscall.h>
29#include <cutils/properties.h>
30#include <media/AudioParameter.h>
31#include <media/AudioResamplerPublic.h>
32#include <utils/Log.h>
33#include <utils/Trace.h>
34
35#include <private/media/AudioTrackShared.h>
36#include <hardware/audio.h>
37#include <audio_effects/effect_ns.h>
38#include <audio_effects/effect_aec.h>
39#include <audio_utils/conversion.h>
40#include <audio_utils/primitives.h>
41#include <audio_utils/format.h>
42#include <audio_utils/minifloat.h>
43
44// NBAIO implementations
45#include <media/nbaio/AudioStreamInSource.h>
46#include <media/nbaio/AudioStreamOutSink.h>
47#include <media/nbaio/MonoPipe.h>
48#include <media/nbaio/MonoPipeReader.h>
49#include <media/nbaio/Pipe.h>
50#include <media/nbaio/PipeReader.h>
51#include <media/nbaio/SourceAudioBufferProvider.h>
52#include <mediautils/BatteryNotifier.h>
53
54#include <powermanager/PowerManager.h>
55
56#include "AudioFlinger.h"
57#include "AudioMixer.h"
58#include "BufferProviders.h"
59#include "FastMixer.h"
60#include "FastCapture.h"
61#include "ServiceUtilities.h"
62#include "mediautils/SchedulingPolicyService.h"
63
64#ifdef ADD_BATTERY_DATA
65#include <media/IMediaPlayerService.h>
66#include <media/IMediaDeathNotifier.h>
67#endif
68
69#ifdef DEBUG_CPU_USAGE
70#include <cpustats/CentralTendencyStatistics.h>
71#include <cpustats/ThreadCpuUsage.h>
72#endif
73
74#include "AutoPark.h"
75
76// ----------------------------------------------------------------------------
77
78// Note: the following macro is used for extremely verbose logging message.  In
79// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
80// 0; but one side effect of this is to turn all LOGV's as well.  Some messages
81// are so verbose that we want to suppress them even when we have ALOG_ASSERT
82// turned on.  Do not uncomment the #def below unless you really know what you
83// are doing and want to see all of the extremely verbose messages.
84//#define VERY_VERY_VERBOSE_LOGGING
85#ifdef VERY_VERY_VERBOSE_LOGGING
86#define ALOGVV ALOGV
87#else
88#define ALOGVV(a...) do { } while(0)
89#endif
90
91// TODO: Move these macro/inlines to a header file.
92#define max(a, b) ((a) > (b) ? (a) : (b))
93template <typename T>
94static inline T min(const T& a, const T& b)
95{
96    return a < b ? a : b;
97}
98
99#ifndef ARRAY_SIZE
100#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
101#endif
102
103namespace android {
104
105// retry counts for buffer fill timeout
106// 50 * ~20msecs = 1 second
107static const int8_t kMaxTrackRetries = 50;
108static const int8_t kMaxTrackStartupRetries = 50;
109// allow less retry attempts on direct output thread.
110// direct outputs can be a scarce resource in audio hardware and should
111// be released as quickly as possible.
112static const int8_t kMaxTrackRetriesDirect = 2;
113// retry count before removing active track in case of underrun on offloaded thread:
114// we need to make sure that AudioTrack client has enough time to send large buffers
115//FIXME may be more appropriate if expressed in time units. Need to revise how underrun is handled
116// for offloaded tracks
117static const int8_t kMaxTrackRetriesOffload = 10;
118static const int8_t kMaxTrackStartupRetriesOffload = 100;
119
120
121// don't warn about blocked writes or record buffer overflows more often than this
122static const nsecs_t kWarningThrottleNs = seconds(5);
123
124// RecordThread loop sleep time upon application overrun or audio HAL read error
125static const int kRecordThreadSleepUs = 5000;
126
127// maximum time to wait in sendConfigEvent_l() for a status to be received
128static const nsecs_t kConfigEventTimeoutNs = seconds(2);
129
130// minimum sleep time for the mixer thread loop when tracks are active but in underrun
131static const uint32_t kMinThreadSleepTimeUs = 5000;
132// maximum divider applied to the active sleep time in the mixer thread loop
133static const uint32_t kMaxThreadSleepTimeShift = 2;
134
135// minimum normal sink buffer size, expressed in milliseconds rather than frames
136// FIXME This should be based on experimentally observed scheduling jitter
137static const uint32_t kMinNormalSinkBufferSizeMs = 20;
138// maximum normal sink buffer size
139static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
140
141// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
142// FIXME This should be based on experimentally observed scheduling jitter
143static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
144
145// Offloaded output thread standby delay: allows track transition without going to standby
146static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
147
148// Direct output thread minimum sleep time in idle or active(underrun) state
149static const nsecs_t kDirectMinSleepTimeUs = 10000;
150
151// Offloaded output bit rate in bits per second when unknown.
152// Used for sleep time calculation, so use a high default bitrate to be conservative on sleep time.
153static const uint32_t kOffloadDefaultBitRateBps = 1500000;
154
155
156// Whether to use fast mixer
157static const enum {
158    FastMixer_Never,    // never initialize or use: for debugging only
159    FastMixer_Always,   // always initialize and use, even if not needed: for debugging only
160                        // normal mixer multiplier is 1
161    FastMixer_Static,   // initialize if needed, then use all the time if initialized,
162                        // multiplier is calculated based on min & max normal mixer buffer size
163    FastMixer_Dynamic,  // initialize if needed, then use dynamically depending on track load,
164                        // multiplier is calculated based on min & max normal mixer buffer size
165    // FIXME for FastMixer_Dynamic:
166    //  Supporting this option will require fixing HALs that can't handle large writes.
167    //  For example, one HAL implementation returns an error from a large write,
168    //  and another HAL implementation corrupts memory, possibly in the sample rate converter.
169    //  We could either fix the HAL implementations, or provide a wrapper that breaks
170    //  up large writes into smaller ones, and the wrapper would need to deal with scheduler.
171} kUseFastMixer = FastMixer_Static;
172
173// Whether to use fast capture
174static const enum {
175    FastCapture_Never,  // never initialize or use: for debugging only
176    FastCapture_Always, // always initialize and use, even if not needed: for debugging only
177    FastCapture_Static, // initialize if needed, then use all the time if initialized
178} kUseFastCapture = FastCapture_Static;
179
180// Priorities for requestPriority
181static const int kPriorityAudioApp = 2;
182static const int kPriorityFastMixer = 3;
183static const int kPriorityFastCapture = 3;
184
185// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
186// for the track.  The client then sub-divides this into smaller buffers for its use.
187// Currently the client uses N-buffering by default, but doesn't tell us about the value of N.
188// So for now we just assume that client is double-buffered for fast tracks.
189// FIXME It would be better for client to tell AudioFlinger the value of N,
190// so AudioFlinger could allocate the right amount of memory.
191// See the client's minBufCount and mNotificationFramesAct calculations for details.
192
193// This is the default value, if not specified by property.
194static const int kFastTrackMultiplier = 2;
195
196// The minimum and maximum allowed values
197static const int kFastTrackMultiplierMin = 1;
198static const int kFastTrackMultiplierMax = 2;
199
200// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
201static int sFastTrackMultiplier = kFastTrackMultiplier;
202
203// See Thread::readOnlyHeap().
204// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
205// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
206// and that all "fast" AudioRecord clients read from.  In either case, the size can be small.
207static const size_t kRecordThreadReadOnlyHeapSize = 0x2000;
208
209// ----------------------------------------------------------------------------
210
211static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
212
213static void sFastTrackMultiplierInit()
214{
215    char value[PROPERTY_VALUE_MAX];
216    if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
217        char *endptr;
218        unsigned long ul = strtoul(value, &endptr, 0);
219        if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
220            sFastTrackMultiplier = (int) ul;
221        }
222    }
223}
224
225// ----------------------------------------------------------------------------
226
227#ifdef ADD_BATTERY_DATA
228// To collect the amplifier usage
229static void addBatteryData(uint32_t params) {
230    sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
231    if (service == NULL) {
232        // it already logged
233        return;
234    }
235
236    service->addBatteryData(params);
237}
238#endif
239
240// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
241struct {
242    // call when you acquire a partial wakelock
243    void acquire(const sp<IBinder> &wakeLockToken) {
244        pthread_mutex_lock(&mLock);
245        if (wakeLockToken.get() == nullptr) {
246            adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
247        } else {
248            if (mCount == 0) {
249                adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
250            }
251            ++mCount;
252        }
253        pthread_mutex_unlock(&mLock);
254    }
255
256    // call when you release a partial wakelock.
257    void release(const sp<IBinder> &wakeLockToken) {
258        if (wakeLockToken.get() == nullptr) {
259            return;
260        }
261        pthread_mutex_lock(&mLock);
262        if (--mCount < 0) {
263            ALOGE("negative wakelock count");
264            mCount = 0;
265        }
266        pthread_mutex_unlock(&mLock);
267    }
268
269    // retrieves the boottime timebase offset from monotonic.
270    int64_t getBoottimeOffset() {
271        pthread_mutex_lock(&mLock);
272        int64_t boottimeOffset = mBoottimeOffset;
273        pthread_mutex_unlock(&mLock);
274        return boottimeOffset;
275    }
276
277    // Adjusts the timebase offset between TIMEBASE_MONOTONIC
278    // and the selected timebase.
279    // Currently only TIMEBASE_BOOTTIME is allowed.
280    //
281    // This only needs to be called upon acquiring the first partial wakelock
282    // after all other partial wakelocks are released.
283    //
284    // We do an empirical measurement of the offset rather than parsing
285    // /proc/timer_list since the latter is not a formal kernel ABI.
286    static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
287        int clockbase;
288        switch (timebase) {
289        case ExtendedTimestamp::TIMEBASE_BOOTTIME:
290            clockbase = SYSTEM_TIME_BOOTTIME;
291            break;
292        default:
293            LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
294            break;
295        }
296        // try three times to get the clock offset, choose the one
297        // with the minimum gap in measurements.
298        const int tries = 3;
299        nsecs_t bestGap, measured;
300        for (int i = 0; i < tries; ++i) {
301            const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
302            const nsecs_t tbase = systemTime(clockbase);
303            const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
304            const nsecs_t gap = tmono2 - tmono;
305            if (i == 0 || gap < bestGap) {
306                bestGap = gap;
307                measured = tbase - ((tmono + tmono2) >> 1);
308            }
309        }
310
311        // to avoid micro-adjusting, we don't change the timebase
312        // unless it is significantly different.
313        //
314        // Assumption: It probably takes more than toleranceNs to
315        // suspend and resume the device.
316        static int64_t toleranceNs = 10000; // 10 us
317        if (llabs(*offset - measured) > toleranceNs) {
318            ALOGV("Adjusting timebase offset old: %lld  new: %lld",
319                    (long long)*offset, (long long)measured);
320            *offset = measured;
321        }
322    }
323
324    pthread_mutex_t mLock;
325    int32_t mCount;
326    int64_t mBoottimeOffset;
327} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
328
329// ----------------------------------------------------------------------------
330//      CPU Stats
331// ----------------------------------------------------------------------------
332
333class CpuStats {
334public:
335    CpuStats();
336    void sample(const String8 &title);
337#ifdef DEBUG_CPU_USAGE
338private:
339    ThreadCpuUsage mCpuUsage;           // instantaneous thread CPU usage in wall clock ns
340    CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
341
342    CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
343
344    int mCpuNum;                        // thread's current CPU number
345    int mCpukHz;                        // frequency of thread's current CPU in kHz
346#endif
347};
348
349CpuStats::CpuStats()
350#ifdef DEBUG_CPU_USAGE
351    : mCpuNum(-1), mCpukHz(-1)
352#endif
353{
354}
355
356void CpuStats::sample(const String8 &title
357#ifndef DEBUG_CPU_USAGE
358                __unused
359#endif
360        ) {
361#ifdef DEBUG_CPU_USAGE
362    // get current thread's delta CPU time in wall clock ns
363    double wcNs;
364    bool valid = mCpuUsage.sampleAndEnable(wcNs);
365
366    // record sample for wall clock statistics
367    if (valid) {
368        mWcStats.sample(wcNs);
369    }
370
371    // get the current CPU number
372    int cpuNum = sched_getcpu();
373
374    // get the current CPU frequency in kHz
375    int cpukHz = mCpuUsage.getCpukHz(cpuNum);
376
377    // check if either CPU number or frequency changed
378    if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
379        mCpuNum = cpuNum;
380        mCpukHz = cpukHz;
381        // ignore sample for purposes of cycles
382        valid = false;
383    }
384
385    // if no change in CPU number or frequency, then record sample for cycle statistics
386    if (valid && mCpukHz > 0) {
387        double cycles = wcNs * cpukHz * 0.000001;
388        mHzStats.sample(cycles);
389    }
390
391    unsigned n = mWcStats.n();
392    // mCpuUsage.elapsed() is expensive, so don't call it every loop
393    if ((n & 127) == 1) {
394        long long elapsed = mCpuUsage.elapsed();
395        if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
396            double perLoop = elapsed / (double) n;
397            double perLoop100 = perLoop * 0.01;
398            double perLoop1k = perLoop * 0.001;
399            double mean = mWcStats.mean();
400            double stddev = mWcStats.stddev();
401            double minimum = mWcStats.minimum();
402            double maximum = mWcStats.maximum();
403            double meanCycles = mHzStats.mean();
404            double stddevCycles = mHzStats.stddev();
405            double minCycles = mHzStats.minimum();
406            double maxCycles = mHzStats.maximum();
407            mCpuUsage.resetElapsed();
408            mWcStats.reset();
409            mHzStats.reset();
410            ALOGD("CPU usage for %s over past %.1f secs\n"
411                "  (%u mixer loops at %.1f mean ms per loop):\n"
412                "  us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
413                "  %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
414                "  MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
415                    title.string(),
416                    elapsed * .000000001, n, perLoop * .000001,
417                    mean * .001,
418                    stddev * .001,
419                    minimum * .001,
420                    maximum * .001,
421                    mean / perLoop100,
422                    stddev / perLoop100,
423                    minimum / perLoop100,
424                    maximum / perLoop100,
425                    meanCycles / perLoop1k,
426                    stddevCycles / perLoop1k,
427                    minCycles / perLoop1k,
428                    maxCycles / perLoop1k);
429
430        }
431    }
432#endif
433};
434
435// ----------------------------------------------------------------------------
436//      ThreadBase
437// ----------------------------------------------------------------------------
438
439// static
440const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
441{
442    switch (type) {
443    case MIXER:
444        return "MIXER";
445    case DIRECT:
446        return "DIRECT";
447    case DUPLICATING:
448        return "DUPLICATING";
449    case RECORD:
450        return "RECORD";
451    case OFFLOAD:
452        return "OFFLOAD";
453    default:
454        return "unknown";
455    }
456}
457
458String8 devicesToString(audio_devices_t devices)
459{
460    static const struct mapping {
461        audio_devices_t mDevices;
462        const char *    mString;
463    } mappingsOut[] = {
464        {AUDIO_DEVICE_OUT_EARPIECE,         "EARPIECE"},
465        {AUDIO_DEVICE_OUT_SPEAKER,          "SPEAKER"},
466        {AUDIO_DEVICE_OUT_WIRED_HEADSET,    "WIRED_HEADSET"},
467        {AUDIO_DEVICE_OUT_WIRED_HEADPHONE,  "WIRED_HEADPHONE"},
468        {AUDIO_DEVICE_OUT_BLUETOOTH_SCO,    "BLUETOOTH_SCO"},
469        {AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET,    "BLUETOOTH_SCO_HEADSET"},
470        {AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT,     "BLUETOOTH_SCO_CARKIT"},
471        {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,           "BLUETOOTH_A2DP"},
472        {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,"BLUETOOTH_A2DP_HEADPHONES"},
473        {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER,   "BLUETOOTH_A2DP_SPEAKER"},
474        {AUDIO_DEVICE_OUT_AUX_DIGITAL,      "AUX_DIGITAL"},
475        {AUDIO_DEVICE_OUT_HDMI,             "HDMI"},
476        {AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET,"ANLG_DOCK_HEADSET"},
477        {AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET,"DGTL_DOCK_HEADSET"},
478        {AUDIO_DEVICE_OUT_USB_ACCESSORY,    "USB_ACCESSORY"},
479        {AUDIO_DEVICE_OUT_USB_DEVICE,       "USB_DEVICE"},
480        {AUDIO_DEVICE_OUT_TELEPHONY_TX,     "TELEPHONY_TX"},
481        {AUDIO_DEVICE_OUT_LINE,             "LINE"},
482        {AUDIO_DEVICE_OUT_HDMI_ARC,         "HDMI_ARC"},
483        {AUDIO_DEVICE_OUT_SPDIF,            "SPDIF"},
484        {AUDIO_DEVICE_OUT_FM,               "FM"},
485        {AUDIO_DEVICE_OUT_AUX_LINE,         "AUX_LINE"},
486        {AUDIO_DEVICE_OUT_SPEAKER_SAFE,     "SPEAKER_SAFE"},
487        {AUDIO_DEVICE_OUT_IP,               "IP"},
488        {AUDIO_DEVICE_OUT_BUS,              "BUS"},
489        {AUDIO_DEVICE_NONE,                 "NONE"},       // must be last
490    }, mappingsIn[] = {
491        {AUDIO_DEVICE_IN_COMMUNICATION,     "COMMUNICATION"},
492        {AUDIO_DEVICE_IN_AMBIENT,           "AMBIENT"},
493        {AUDIO_DEVICE_IN_BUILTIN_MIC,       "BUILTIN_MIC"},
494        {AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET, "BLUETOOTH_SCO_HEADSET"},
495        {AUDIO_DEVICE_IN_WIRED_HEADSET,     "WIRED_HEADSET"},
496        {AUDIO_DEVICE_IN_AUX_DIGITAL,       "AUX_DIGITAL"},
497        {AUDIO_DEVICE_IN_VOICE_CALL,        "VOICE_CALL"},
498        {AUDIO_DEVICE_IN_TELEPHONY_RX,      "TELEPHONY_RX"},
499        {AUDIO_DEVICE_IN_BACK_MIC,          "BACK_MIC"},
500        {AUDIO_DEVICE_IN_REMOTE_SUBMIX,     "REMOTE_SUBMIX"},
501        {AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET, "ANLG_DOCK_HEADSET"},
502        {AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET, "DGTL_DOCK_HEADSET"},
503        {AUDIO_DEVICE_IN_USB_ACCESSORY,     "USB_ACCESSORY"},
504        {AUDIO_DEVICE_IN_USB_DEVICE,        "USB_DEVICE"},
505        {AUDIO_DEVICE_IN_FM_TUNER,          "FM_TUNER"},
506        {AUDIO_DEVICE_IN_TV_TUNER,          "TV_TUNER"},
507        {AUDIO_DEVICE_IN_LINE,              "LINE"},
508        {AUDIO_DEVICE_IN_SPDIF,             "SPDIF"},
509        {AUDIO_DEVICE_IN_BLUETOOTH_A2DP,    "BLUETOOTH_A2DP"},
510        {AUDIO_DEVICE_IN_LOOPBACK,          "LOOPBACK"},
511        {AUDIO_DEVICE_IN_IP,                "IP"},
512        {AUDIO_DEVICE_IN_BUS,               "BUS"},
513        {AUDIO_DEVICE_NONE,                 "NONE"},        // must be last
514    };
515    String8 result;
516    audio_devices_t allDevices = AUDIO_DEVICE_NONE;
517    const mapping *entry;
518    if (devices & AUDIO_DEVICE_BIT_IN) {
519        devices &= ~AUDIO_DEVICE_BIT_IN;
520        entry = mappingsIn;
521    } else {
522        entry = mappingsOut;
523    }
524    for ( ; entry->mDevices != AUDIO_DEVICE_NONE; entry++) {
525        allDevices = (audio_devices_t) (allDevices | entry->mDevices);
526        if (devices & entry->mDevices) {
527            if (!result.isEmpty()) {
528                result.append("|");
529            }
530            result.append(entry->mString);
531        }
532    }
533    if (devices & ~allDevices) {
534        if (!result.isEmpty()) {
535            result.append("|");
536        }
537        result.appendFormat("0x%X", devices & ~allDevices);
538    }
539    if (result.isEmpty()) {
540        result.append(entry->mString);
541    }
542    return result;
543}
544
545String8 inputFlagsToString(audio_input_flags_t flags)
546{
547    static const struct mapping {
548        audio_input_flags_t     mFlag;
549        const char *            mString;
550    } mappings[] = {
551        {AUDIO_INPUT_FLAG_FAST,             "FAST"},
552        {AUDIO_INPUT_FLAG_HW_HOTWORD,       "HW_HOTWORD"},
553        {AUDIO_INPUT_FLAG_RAW,              "RAW"},
554        {AUDIO_INPUT_FLAG_SYNC,             "SYNC"},
555        {AUDIO_INPUT_FLAG_NONE,             "NONE"},        // must be last
556    };
557    String8 result;
558    audio_input_flags_t allFlags = AUDIO_INPUT_FLAG_NONE;
559    const mapping *entry;
560    for (entry = mappings; entry->mFlag != AUDIO_INPUT_FLAG_NONE; entry++) {
561        allFlags = (audio_input_flags_t) (allFlags | entry->mFlag);
562        if (flags & entry->mFlag) {
563            if (!result.isEmpty()) {
564                result.append("|");
565            }
566            result.append(entry->mString);
567        }
568    }
569    if (flags & ~allFlags) {
570        if (!result.isEmpty()) {
571            result.append("|");
572        }
573        result.appendFormat("0x%X", flags & ~allFlags);
574    }
575    if (result.isEmpty()) {
576        result.append(entry->mString);
577    }
578    return result;
579}
580
581String8 outputFlagsToString(audio_output_flags_t flags)
582{
583    static const struct mapping {
584        audio_output_flags_t    mFlag;
585        const char *            mString;
586    } mappings[] = {
587        {AUDIO_OUTPUT_FLAG_DIRECT,          "DIRECT"},
588        {AUDIO_OUTPUT_FLAG_PRIMARY,         "PRIMARY"},
589        {AUDIO_OUTPUT_FLAG_FAST,            "FAST"},
590        {AUDIO_OUTPUT_FLAG_DEEP_BUFFER,     "DEEP_BUFFER"},
591        {AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,"COMPRESS_OFFLOAD"},
592        {AUDIO_OUTPUT_FLAG_NON_BLOCKING,    "NON_BLOCKING"},
593        {AUDIO_OUTPUT_FLAG_HW_AV_SYNC,      "HW_AV_SYNC"},
594        {AUDIO_OUTPUT_FLAG_RAW,             "RAW"},
595        {AUDIO_OUTPUT_FLAG_SYNC,            "SYNC"},
596        {AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO, "IEC958_NONAUDIO"},
597        {AUDIO_OUTPUT_FLAG_NONE,            "NONE"},        // must be last
598    };
599    String8 result;
600    audio_output_flags_t allFlags = AUDIO_OUTPUT_FLAG_NONE;
601    const mapping *entry;
602    for (entry = mappings; entry->mFlag != AUDIO_OUTPUT_FLAG_NONE; entry++) {
603        allFlags = (audio_output_flags_t) (allFlags | entry->mFlag);
604        if (flags & entry->mFlag) {
605            if (!result.isEmpty()) {
606                result.append("|");
607            }
608            result.append(entry->mString);
609        }
610    }
611    if (flags & ~allFlags) {
612        if (!result.isEmpty()) {
613            result.append("|");
614        }
615        result.appendFormat("0x%X", flags & ~allFlags);
616    }
617    if (result.isEmpty()) {
618        result.append(entry->mString);
619    }
620    return result;
621}
622
623const char *sourceToString(audio_source_t source)
624{
625    switch (source) {
626    case AUDIO_SOURCE_DEFAULT:              return "default";
627    case AUDIO_SOURCE_MIC:                  return "mic";
628    case AUDIO_SOURCE_VOICE_UPLINK:         return "voice uplink";
629    case AUDIO_SOURCE_VOICE_DOWNLINK:       return "voice downlink";
630    case AUDIO_SOURCE_VOICE_CALL:           return "voice call";
631    case AUDIO_SOURCE_CAMCORDER:            return "camcorder";
632    case AUDIO_SOURCE_VOICE_RECOGNITION:    return "voice recognition";
633    case AUDIO_SOURCE_VOICE_COMMUNICATION:  return "voice communication";
634    case AUDIO_SOURCE_REMOTE_SUBMIX:        return "remote submix";
635    case AUDIO_SOURCE_UNPROCESSED:          return "unprocessed";
636    case AUDIO_SOURCE_FM_TUNER:             return "FM tuner";
637    case AUDIO_SOURCE_HOTWORD:              return "hotword";
638    default:                                return "unknown";
639    }
640}
641
642AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
643        audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady)
644    :   Thread(false /*canCallJava*/),
645        mType(type),
646        mAudioFlinger(audioFlinger),
647        // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
648        // are set by PlaybackThread::readOutputParameters_l() or
649        // RecordThread::readInputParameters_l()
650        //FIXME: mStandby should be true here. Is this some kind of hack?
651        mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
652        mPrevOutDevice(AUDIO_DEVICE_NONE), mPrevInDevice(AUDIO_DEVICE_NONE),
653        mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
654        // mName will be set by concrete (non-virtual) subclass
655        mDeathRecipient(new PMDeathRecipient(this)),
656        mSystemReady(systemReady),
657        mNotifiedBatteryStart(false)
658{
659    memset(&mPatch, 0, sizeof(struct audio_patch));
660}
661
662AudioFlinger::ThreadBase::~ThreadBase()
663{
664    // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
665    mConfigEvents.clear();
666
667    // do not lock the mutex in destructor
668    releaseWakeLock_l();
669    if (mPowerManager != 0) {
670        sp<IBinder> binder = IInterface::asBinder(mPowerManager);
671        binder->unlinkToDeath(mDeathRecipient);
672    }
673}
674
675status_t AudioFlinger::ThreadBase::readyToRun()
676{
677    status_t status = initCheck();
678    if (status == NO_ERROR) {
679        ALOGI("AudioFlinger's thread %p ready to run", this);
680    } else {
681        ALOGE("No working audio driver found.");
682    }
683    return status;
684}
685
686void AudioFlinger::ThreadBase::exit()
687{
688    ALOGV("ThreadBase::exit");
689    // do any cleanup required for exit to succeed
690    preExit();
691    {
692        // This lock prevents the following race in thread (uniprocessor for illustration):
693        //  if (!exitPending()) {
694        //      // context switch from here to exit()
695        //      // exit() calls requestExit(), what exitPending() observes
696        //      // exit() calls signal(), which is dropped since no waiters
697        //      // context switch back from exit() to here
698        //      mWaitWorkCV.wait(...);
699        //      // now thread is hung
700        //  }
701        AutoMutex lock(mLock);
702        requestExit();
703        mWaitWorkCV.broadcast();
704    }
705    // When Thread::requestExitAndWait is made virtual and this method is renamed to
706    // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
707    requestExitAndWait();
708}
709
710status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
711{
712    ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
713    Mutex::Autolock _l(mLock);
714
715    return sendSetParameterConfigEvent_l(keyValuePairs);
716}
717
718// sendConfigEvent_l() must be called with ThreadBase::mLock held
719// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
720status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
721{
722    status_t status = NO_ERROR;
723
724    if (event->mRequiresSystemReady && !mSystemReady) {
725        event->mWaitStatus = false;
726        mPendingConfigEvents.add(event);
727        return status;
728    }
729    mConfigEvents.add(event);
730    ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
731    mWaitWorkCV.signal();
732    mLock.unlock();
733    {
734        Mutex::Autolock _l(event->mLock);
735        while (event->mWaitStatus) {
736            if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
737                event->mStatus = TIMED_OUT;
738                event->mWaitStatus = false;
739            }
740        }
741        status = event->mStatus;
742    }
743    mLock.lock();
744    return status;
745}
746
747void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid)
748{
749    Mutex::Autolock _l(mLock);
750    sendIoConfigEvent_l(event, pid);
751}
752
753// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
754void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid)
755{
756    sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid);
757    sendConfigEvent_l(configEvent);
758}
759
760void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio)
761{
762    Mutex::Autolock _l(mLock);
763    sendPrioConfigEvent_l(pid, tid, prio);
764}
765
766// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
767void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
768{
769    sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
770    sendConfigEvent_l(configEvent);
771}
772
773// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
774status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
775{
776    sp<ConfigEvent> configEvent;
777    AudioParameter param(keyValuePair);
778    int value;
779    if (param.getInt(String8(AUDIO_PARAMETER_MONO_OUTPUT), value) == NO_ERROR) {
780        setMasterMono_l(value != 0);
781        if (param.size() == 1) {
782            return NO_ERROR; // should be a solo parameter - we don't pass down
783        }
784        param.remove(String8(AUDIO_PARAMETER_MONO_OUTPUT));
785        configEvent = new SetParameterConfigEvent(param.toString());
786    } else {
787        configEvent = new SetParameterConfigEvent(keyValuePair);
788    }
789    return sendConfigEvent_l(configEvent);
790}
791
792status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
793                                                        const struct audio_patch *patch,
794                                                        audio_patch_handle_t *handle)
795{
796    Mutex::Autolock _l(mLock);
797    sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
798    status_t status = sendConfigEvent_l(configEvent);
799    if (status == NO_ERROR) {
800        CreateAudioPatchConfigEventData *data =
801                                        (CreateAudioPatchConfigEventData *)configEvent->mData.get();
802        *handle = data->mHandle;
803    }
804    return status;
805}
806
807status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
808                                                                const audio_patch_handle_t handle)
809{
810    Mutex::Autolock _l(mLock);
811    sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
812    return sendConfigEvent_l(configEvent);
813}
814
815
816// post condition: mConfigEvents.isEmpty()
817void AudioFlinger::ThreadBase::processConfigEvents_l()
818{
819    bool configChanged = false;
820
821    while (!mConfigEvents.isEmpty()) {
822        ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
823        sp<ConfigEvent> event = mConfigEvents[0];
824        mConfigEvents.removeAt(0);
825        switch (event->mType) {
826        case CFG_EVENT_PRIO: {
827            PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
828            // FIXME Need to understand why this has to be done asynchronously
829            int err = requestPriority(data->mPid, data->mTid, data->mPrio,
830                    true /*asynchronous*/);
831            if (err != 0) {
832                ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
833                      data->mPrio, data->mPid, data->mTid, err);
834            }
835        } break;
836        case CFG_EVENT_IO: {
837            IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
838            ioConfigChanged(data->mEvent, data->mPid);
839        } break;
840        case CFG_EVENT_SET_PARAMETER: {
841            SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
842            if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
843                configChanged = true;
844            }
845        } break;
846        case CFG_EVENT_CREATE_AUDIO_PATCH: {
847            CreateAudioPatchConfigEventData *data =
848                                            (CreateAudioPatchConfigEventData *)event->mData.get();
849            event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
850        } break;
851        case CFG_EVENT_RELEASE_AUDIO_PATCH: {
852            ReleaseAudioPatchConfigEventData *data =
853                                            (ReleaseAudioPatchConfigEventData *)event->mData.get();
854            event->mStatus = releaseAudioPatch_l(data->mHandle);
855        } break;
856        default:
857            ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
858            break;
859        }
860        {
861            Mutex::Autolock _l(event->mLock);
862            if (event->mWaitStatus) {
863                event->mWaitStatus = false;
864                event->mCond.signal();
865            }
866        }
867        ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
868    }
869
870    if (configChanged) {
871        cacheParameters_l();
872    }
873}
874
875String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
876    String8 s;
877    const audio_channel_representation_t representation =
878            audio_channel_mask_get_representation(mask);
879
880    switch (representation) {
881    case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
882        if (output) {
883            if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
884            if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
885            if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
886            if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
887            if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
888            if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
889            if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
890            if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
891            if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
892            if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
893            if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
894            if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
895            if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
896            if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
897            if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
898            if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
899            if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
900            if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
901            if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown,  ");
902        } else {
903            if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
904            if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
905            if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
906            if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
907            if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
908            if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
909            if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
910            if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
911            if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
912            if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
913            if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
914            if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
915            if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
916            if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
917            if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown,  ");
918        }
919        const int len = s.length();
920        if (len > 2) {
921            (void) s.lockBuffer(len);      // needed?
922            s.unlockBuffer(len - 2);       // remove trailing ", "
923        }
924        return s;
925    }
926    case AUDIO_CHANNEL_REPRESENTATION_INDEX:
927        s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
928        return s;
929    default:
930        s.appendFormat("unknown mask, representation:%d  bits:%#x",
931                representation, audio_channel_mask_get_bits(mask));
932        return s;
933    }
934}
935
936void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
937{
938    const size_t SIZE = 256;
939    char buffer[SIZE];
940    String8 result;
941
942    bool locked = AudioFlinger::dumpTryLock(mLock);
943    if (!locked) {
944        dprintf(fd, "thread %p may be deadlocked\n", this);
945    }
946
947    dprintf(fd, "  Thread name: %s\n", mThreadName);
948    dprintf(fd, "  I/O handle: %d\n", mId);
949    dprintf(fd, "  TID: %d\n", getTid());
950    dprintf(fd, "  Standby: %s\n", mStandby ? "yes" : "no");
951    dprintf(fd, "  Sample rate: %u Hz\n", mSampleRate);
952    dprintf(fd, "  HAL frame count: %zu\n", mFrameCount);
953    dprintf(fd, "  HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat));
954    dprintf(fd, "  HAL buffer size: %zu bytes\n", mBufferSize);
955    dprintf(fd, "  Channel count: %u\n", mChannelCount);
956    dprintf(fd, "  Channel mask: 0x%08x (%s)\n", mChannelMask,
957            channelMaskToString(mChannelMask, mType != RECORD).string());
958    dprintf(fd, "  Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
959    dprintf(fd, "  Processing frame size: %zu bytes\n", mFrameSize);
960    dprintf(fd, "  Pending config events:");
961    size_t numConfig = mConfigEvents.size();
962    if (numConfig) {
963        for (size_t i = 0; i < numConfig; i++) {
964            mConfigEvents[i]->dump(buffer, SIZE);
965            dprintf(fd, "\n    %s", buffer);
966        }
967        dprintf(fd, "\n");
968    } else {
969        dprintf(fd, " none\n");
970    }
971    dprintf(fd, "  Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).string());
972    dprintf(fd, "  Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).string());
973    dprintf(fd, "  Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
974
975    if (locked) {
976        mLock.unlock();
977    }
978}
979
980void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
981{
982    const size_t SIZE = 256;
983    char buffer[SIZE];
984    String8 result;
985
986    size_t numEffectChains = mEffectChains.size();
987    snprintf(buffer, SIZE, "  %zu Effect Chains\n", numEffectChains);
988    write(fd, buffer, strlen(buffer));
989
990    for (size_t i = 0; i < numEffectChains; ++i) {
991        sp<EffectChain> chain = mEffectChains[i];
992        if (chain != 0) {
993            chain->dump(fd, args);
994        }
995    }
996}
997
998void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
999{
1000    Mutex::Autolock _l(mLock);
1001    acquireWakeLock_l(uid);
1002}
1003
1004String16 AudioFlinger::ThreadBase::getWakeLockTag()
1005{
1006    switch (mType) {
1007    case MIXER:
1008        return String16("AudioMix");
1009    case DIRECT:
1010        return String16("AudioDirectOut");
1011    case DUPLICATING:
1012        return String16("AudioDup");
1013    case RECORD:
1014        return String16("AudioIn");
1015    case OFFLOAD:
1016        return String16("AudioOffload");
1017    default:
1018        ALOG_ASSERT(false);
1019        return String16("AudioUnknown");
1020    }
1021}
1022
1023void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
1024{
1025    getPowerManager_l();
1026    if (mPowerManager != 0) {
1027        sp<IBinder> binder = new BBinder();
1028        status_t status;
1029        if (uid >= 0) {
1030            status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
1031                    binder,
1032                    getWakeLockTag(),
1033                    String16("audioserver"),
1034                    uid,
1035                    true /* FIXME force oneway contrary to .aidl */);
1036        } else {
1037            status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1038                    binder,
1039                    getWakeLockTag(),
1040                    String16("audioserver"),
1041                    true /* FIXME force oneway contrary to .aidl */);
1042        }
1043        if (status == NO_ERROR) {
1044            mWakeLockToken = binder;
1045        }
1046        ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
1047    }
1048
1049    if (!mNotifiedBatteryStart) {
1050        BatteryNotifier::getInstance().noteStartAudio();
1051        mNotifiedBatteryStart = true;
1052    }
1053    gBoottime.acquire(mWakeLockToken);
1054    mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1055            gBoottime.getBoottimeOffset();
1056}
1057
1058void AudioFlinger::ThreadBase::releaseWakeLock()
1059{
1060    Mutex::Autolock _l(mLock);
1061    releaseWakeLock_l();
1062}
1063
1064void AudioFlinger::ThreadBase::releaseWakeLock_l()
1065{
1066    gBoottime.release(mWakeLockToken);
1067    if (mWakeLockToken != 0) {
1068        ALOGV("releaseWakeLock_l() %s", mThreadName);
1069        if (mPowerManager != 0) {
1070            mPowerManager->releaseWakeLock(mWakeLockToken, 0,
1071                    true /* FIXME force oneway contrary to .aidl */);
1072        }
1073        mWakeLockToken.clear();
1074    }
1075
1076    if (mNotifiedBatteryStart) {
1077        BatteryNotifier::getInstance().noteStopAudio();
1078        mNotifiedBatteryStart = false;
1079    }
1080}
1081
1082void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
1083    Mutex::Autolock _l(mLock);
1084    updateWakeLockUids_l(uids);
1085}
1086
1087void AudioFlinger::ThreadBase::getPowerManager_l() {
1088    if (mSystemReady && mPowerManager == 0) {
1089        // use checkService() to avoid blocking if power service is not up yet
1090        sp<IBinder> binder =
1091            defaultServiceManager()->checkService(String16("power"));
1092        if (binder == 0) {
1093            ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
1094        } else {
1095            mPowerManager = interface_cast<IPowerManager>(binder);
1096            binder->linkToDeath(mDeathRecipient);
1097        }
1098    }
1099}
1100
1101void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
1102    getPowerManager_l();
1103    if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1104        if (mSystemReady) {
1105            ALOGE("no wake lock to update, but system ready!");
1106        } else {
1107            ALOGW("no wake lock to update, system not ready yet");
1108        }
1109        return;
1110    }
1111    if (mPowerManager != 0) {
1112        sp<IBinder> binder = new BBinder();
1113        status_t status;
1114        status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array(),
1115                    true /* FIXME force oneway contrary to .aidl */);
1116        ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status);
1117    }
1118}
1119
1120void AudioFlinger::ThreadBase::clearPowerManager()
1121{
1122    Mutex::Autolock _l(mLock);
1123    releaseWakeLock_l();
1124    mPowerManager.clear();
1125}
1126
1127void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
1128{
1129    sp<ThreadBase> thread = mThread.promote();
1130    if (thread != 0) {
1131        thread->clearPowerManager();
1132    }
1133    ALOGW("power manager service died !!!");
1134}
1135
1136void AudioFlinger::ThreadBase::setEffectSuspended(
1137        const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
1138{
1139    Mutex::Autolock _l(mLock);
1140    setEffectSuspended_l(type, suspend, sessionId);
1141}
1142
1143void AudioFlinger::ThreadBase::setEffectSuspended_l(
1144        const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
1145{
1146    sp<EffectChain> chain = getEffectChain_l(sessionId);
1147    if (chain != 0) {
1148        if (type != NULL) {
1149            chain->setEffectSuspended_l(type, suspend);
1150        } else {
1151            chain->setEffectSuspendedAll_l(suspend);
1152        }
1153    }
1154
1155    updateSuspendedSessions_l(type, suspend, sessionId);
1156}
1157
1158void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1159{
1160    ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1161    if (index < 0) {
1162        return;
1163    }
1164
1165    const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1166            mSuspendedSessions.valueAt(index);
1167
1168    for (size_t i = 0; i < sessionEffects.size(); i++) {
1169        sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1170        for (int j = 0; j < desc->mRefCount; j++) {
1171            if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1172                chain->setEffectSuspendedAll_l(true);
1173            } else {
1174                ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1175                    desc->mType.timeLow);
1176                chain->setEffectSuspended_l(&desc->mType, true);
1177            }
1178        }
1179    }
1180}
1181
1182void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1183                                                         bool suspend,
1184                                                         audio_session_t sessionId)
1185{
1186    ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1187
1188    KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1189
1190    if (suspend) {
1191        if (index >= 0) {
1192            sessionEffects = mSuspendedSessions.valueAt(index);
1193        } else {
1194            mSuspendedSessions.add(sessionId, sessionEffects);
1195        }
1196    } else {
1197        if (index < 0) {
1198            return;
1199        }
1200        sessionEffects = mSuspendedSessions.valueAt(index);
1201    }
1202
1203
1204    int key = EffectChain::kKeyForSuspendAll;
1205    if (type != NULL) {
1206        key = type->timeLow;
1207    }
1208    index = sessionEffects.indexOfKey(key);
1209
1210    sp<SuspendedSessionDesc> desc;
1211    if (suspend) {
1212        if (index >= 0) {
1213            desc = sessionEffects.valueAt(index);
1214        } else {
1215            desc = new SuspendedSessionDesc();
1216            if (type != NULL) {
1217                desc->mType = *type;
1218            }
1219            sessionEffects.add(key, desc);
1220            ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1221        }
1222        desc->mRefCount++;
1223    } else {
1224        if (index < 0) {
1225            return;
1226        }
1227        desc = sessionEffects.valueAt(index);
1228        if (--desc->mRefCount == 0) {
1229            ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1230            sessionEffects.removeItemsAt(index);
1231            if (sessionEffects.isEmpty()) {
1232                ALOGV("updateSuspendedSessions_l() restore removing session %d",
1233                                 sessionId);
1234                mSuspendedSessions.removeItem(sessionId);
1235            }
1236        }
1237    }
1238    if (!sessionEffects.isEmpty()) {
1239        mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1240    }
1241}
1242
1243void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1244                                                            bool enabled,
1245                                                            audio_session_t sessionId)
1246{
1247    Mutex::Autolock _l(mLock);
1248    checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1249}
1250
1251void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1252                                                            bool enabled,
1253                                                            audio_session_t sessionId)
1254{
1255    if (mType != RECORD) {
1256        // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1257        // another session. This gives the priority to well behaved effect control panels
1258        // and applications not using global effects.
1259        // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1260        // global effects
1261        if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1262            setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1263        }
1264    }
1265
1266    sp<EffectChain> chain = getEffectChain_l(sessionId);
1267    if (chain != 0) {
1268        chain->checkSuspendOnEffectEnabled(effect, enabled);
1269    }
1270}
1271
1272// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1273sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1274        const sp<AudioFlinger::Client>& client,
1275        const sp<IEffectClient>& effectClient,
1276        int32_t priority,
1277        audio_session_t sessionId,
1278        effect_descriptor_t *desc,
1279        int *enabled,
1280        status_t *status)
1281{
1282    sp<EffectModule> effect;
1283    sp<EffectHandle> handle;
1284    status_t lStatus;
1285    sp<EffectChain> chain;
1286    bool chainCreated = false;
1287    bool effectCreated = false;
1288    bool effectRegistered = false;
1289
1290    lStatus = initCheck();
1291    if (lStatus != NO_ERROR) {
1292        ALOGW("createEffect_l() Audio driver not initialized.");
1293        goto Exit;
1294    }
1295
1296    // Reject any effect on Direct output threads for now, since the format of
1297    // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1298    if (mType == DIRECT) {
1299        ALOGW("createEffect_l() Cannot add effect %s on Direct output type thread %s",
1300                desc->name, mThreadName);
1301        lStatus = BAD_VALUE;
1302        goto Exit;
1303    }
1304
1305    // Reject any effect on mixer or duplicating multichannel sinks.
1306    // TODO: fix both format and multichannel issues with effects.
1307    if ((mType == MIXER || mType == DUPLICATING) && mChannelCount != FCC_2) {
1308        ALOGW("createEffect_l() Cannot add effect %s for multichannel(%d) %s threads",
1309                desc->name, mChannelCount, mType == MIXER ? "MIXER" : "DUPLICATING");
1310        lStatus = BAD_VALUE;
1311        goto Exit;
1312    }
1313
1314    // Allow global effects only on offloaded and mixer threads
1315    if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1316        switch (mType) {
1317        case MIXER:
1318        case OFFLOAD:
1319            break;
1320        case DIRECT:
1321        case DUPLICATING:
1322        case RECORD:
1323        default:
1324            ALOGW("createEffect_l() Cannot add global effect %s on thread %s",
1325                    desc->name, mThreadName);
1326            lStatus = BAD_VALUE;
1327            goto Exit;
1328        }
1329    }
1330
1331    // Only Pre processor effects are allowed on input threads and only on input threads
1332    if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
1333        ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
1334                desc->name, desc->flags, mType);
1335        lStatus = BAD_VALUE;
1336        goto Exit;
1337    }
1338
1339    ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1340
1341    { // scope for mLock
1342        Mutex::Autolock _l(mLock);
1343
1344        // check for existing effect chain with the requested audio session
1345        chain = getEffectChain_l(sessionId);
1346        if (chain == 0) {
1347            // create a new chain for this session
1348            ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1349            chain = new EffectChain(this, sessionId);
1350            addEffectChain_l(chain);
1351            chain->setStrategy(getStrategyForSession_l(sessionId));
1352            chainCreated = true;
1353        } else {
1354            effect = chain->getEffectFromDesc_l(desc);
1355        }
1356
1357        ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1358
1359        if (effect == 0) {
1360            audio_unique_id_t id = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
1361            // Check CPU and memory usage
1362            lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1363            if (lStatus != NO_ERROR) {
1364                goto Exit;
1365            }
1366            effectRegistered = true;
1367            // create a new effect module if none present in the chain
1368            effect = new EffectModule(this, chain, desc, id, sessionId);
1369            lStatus = effect->status();
1370            if (lStatus != NO_ERROR) {
1371                goto Exit;
1372            }
1373            effect->setOffloaded(mType == OFFLOAD, mId);
1374
1375            lStatus = chain->addEffect_l(effect);
1376            if (lStatus != NO_ERROR) {
1377                goto Exit;
1378            }
1379            effectCreated = true;
1380
1381            effect->setDevice(mOutDevice);
1382            effect->setDevice(mInDevice);
1383            effect->setMode(mAudioFlinger->getMode());
1384            effect->setAudioSource(mAudioSource);
1385        }
1386        // create effect handle and connect it to effect module
1387        handle = new EffectHandle(effect, client, effectClient, priority);
1388        lStatus = handle->initCheck();
1389        if (lStatus == OK) {
1390            lStatus = effect->addHandle(handle.get());
1391        }
1392        if (enabled != NULL) {
1393            *enabled = (int)effect->isEnabled();
1394        }
1395    }
1396
1397Exit:
1398    if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1399        Mutex::Autolock _l(mLock);
1400        if (effectCreated) {
1401            chain->removeEffect_l(effect);
1402        }
1403        if (effectRegistered) {
1404            AudioSystem::unregisterEffect(effect->id());
1405        }
1406        if (chainCreated) {
1407            removeEffectChain_l(chain);
1408        }
1409        handle.clear();
1410    }
1411
1412    *status = lStatus;
1413    return handle;
1414}
1415
1416sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1417        int effectId)
1418{
1419    Mutex::Autolock _l(mLock);
1420    return getEffect_l(sessionId, effectId);
1421}
1422
1423sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1424        int effectId)
1425{
1426    sp<EffectChain> chain = getEffectChain_l(sessionId);
1427    return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1428}
1429
1430// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1431// PlaybackThread::mLock held
1432status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1433{
1434    // check for existing effect chain with the requested audio session
1435    audio_session_t sessionId = effect->sessionId();
1436    sp<EffectChain> chain = getEffectChain_l(sessionId);
1437    bool chainCreated = false;
1438
1439    ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1440             "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1441                    this, effect->desc().name, effect->desc().flags);
1442
1443    if (chain == 0) {
1444        // create a new chain for this session
1445        ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1446        chain = new EffectChain(this, sessionId);
1447        addEffectChain_l(chain);
1448        chain->setStrategy(getStrategyForSession_l(sessionId));
1449        chainCreated = true;
1450    }
1451    ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1452
1453    if (chain->getEffectFromId_l(effect->id()) != 0) {
1454        ALOGW("addEffect_l() %p effect %s already present in chain %p",
1455                this, effect->desc().name, chain.get());
1456        return BAD_VALUE;
1457    }
1458
1459    effect->setOffloaded(mType == OFFLOAD, mId);
1460
1461    status_t status = chain->addEffect_l(effect);
1462    if (status != NO_ERROR) {
1463        if (chainCreated) {
1464            removeEffectChain_l(chain);
1465        }
1466        return status;
1467    }
1468
1469    effect->setDevice(mOutDevice);
1470    effect->setDevice(mInDevice);
1471    effect->setMode(mAudioFlinger->getMode());
1472    effect->setAudioSource(mAudioSource);
1473    return NO_ERROR;
1474}
1475
1476void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1477
1478    ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1479    effect_descriptor_t desc = effect->desc();
1480    if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1481        detachAuxEffect_l(effect->id());
1482    }
1483
1484    sp<EffectChain> chain = effect->chain().promote();
1485    if (chain != 0) {
1486        // remove effect chain if removing last effect
1487        if (chain->removeEffect_l(effect) == 0) {
1488            removeEffectChain_l(chain);
1489        }
1490    } else {
1491        ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1492    }
1493}
1494
1495void AudioFlinger::ThreadBase::lockEffectChains_l(
1496        Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1497{
1498    effectChains = mEffectChains;
1499    for (size_t i = 0; i < mEffectChains.size(); i++) {
1500        mEffectChains[i]->lock();
1501    }
1502}
1503
1504void AudioFlinger::ThreadBase::unlockEffectChains(
1505        const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1506{
1507    for (size_t i = 0; i < effectChains.size(); i++) {
1508        effectChains[i]->unlock();
1509    }
1510}
1511
1512sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
1513{
1514    Mutex::Autolock _l(mLock);
1515    return getEffectChain_l(sessionId);
1516}
1517
1518sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1519        const
1520{
1521    size_t size = mEffectChains.size();
1522    for (size_t i = 0; i < size; i++) {
1523        if (mEffectChains[i]->sessionId() == sessionId) {
1524            return mEffectChains[i];
1525        }
1526    }
1527    return 0;
1528}
1529
1530void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1531{
1532    Mutex::Autolock _l(mLock);
1533    size_t size = mEffectChains.size();
1534    for (size_t i = 0; i < size; i++) {
1535        mEffectChains[i]->setMode_l(mode);
1536    }
1537}
1538
1539void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1540{
1541    config->type = AUDIO_PORT_TYPE_MIX;
1542    config->ext.mix.handle = mId;
1543    config->sample_rate = mSampleRate;
1544    config->format = mFormat;
1545    config->channel_mask = mChannelMask;
1546    config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1547                            AUDIO_PORT_CONFIG_FORMAT;
1548}
1549
1550void AudioFlinger::ThreadBase::systemReady()
1551{
1552    Mutex::Autolock _l(mLock);
1553    if (mSystemReady) {
1554        return;
1555    }
1556    mSystemReady = true;
1557
1558    for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1559        sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1560    }
1561    mPendingConfigEvents.clear();
1562}
1563
1564
1565// ----------------------------------------------------------------------------
1566//      Playback
1567// ----------------------------------------------------------------------------
1568
1569AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1570                                             AudioStreamOut* output,
1571                                             audio_io_handle_t id,
1572                                             audio_devices_t device,
1573                                             type_t type,
1574                                             bool systemReady,
1575                                             uint32_t bitRate)
1576    :   ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
1577        mNormalFrameCount(0), mSinkBuffer(NULL),
1578        mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
1579        mMixerBuffer(NULL),
1580        mMixerBufferSize(0),
1581        mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1582        mMixerBufferValid(false),
1583        mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
1584        mEffectBuffer(NULL),
1585        mEffectBufferSize(0),
1586        mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1587        mEffectBufferValid(false),
1588        mSuspended(0), mBytesWritten(0),
1589        mFramesWritten(0),
1590        mActiveTracksGeneration(0),
1591        // mStreamTypes[] initialized in constructor body
1592        mOutput(output),
1593        mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1594        mMixerStatus(MIXER_IDLE),
1595        mMixerStatusIgnoringFastTracks(MIXER_IDLE),
1596        mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
1597        mBytesRemaining(0),
1598        mCurrentWriteLength(0),
1599        mUseAsyncWrite(false),
1600        mWriteAckSequence(0),
1601        mDrainSequence(0),
1602        mSignalPending(false),
1603        mScreenState(AudioFlinger::mScreenState),
1604        // index 0 is reserved for normal mixer's submix
1605        mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
1606        mHwSupportsPause(false), mHwPaused(false), mFlushPending(false)
1607{
1608    snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1609    mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
1610
1611    // Assumes constructor is called by AudioFlinger with it's mLock held, but
1612    // it would be safer to explicitly pass initial masterVolume/masterMute as
1613    // parameter.
1614    //
1615    // If the HAL we are using has support for master volume or master mute,
1616    // then do not attenuate or mute during mixing (just leave the volume at 1.0
1617    // and the mute set to false).
1618    mMasterVolume = audioFlinger->masterVolume_l();
1619    mMasterMute = audioFlinger->masterMute_l();
1620    if (mOutput && mOutput->audioHwDev) {
1621        if (mOutput->audioHwDev->canSetMasterVolume()) {
1622            mMasterVolume = 1.0;
1623        }
1624
1625        if (mOutput->audioHwDev->canSetMasterMute()) {
1626            mMasterMute = false;
1627        }
1628    }
1629
1630    readOutputParameters_l();
1631
1632    // ++ operator does not compile
1633    for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
1634            stream = (audio_stream_type_t) (stream + 1)) {
1635        mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1636        mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1637    }
1638
1639    if (audio_has_proportional_frames(mFormat)) {
1640        mBufferDurationUs = (uint32_t)((mNormalFrameCount * 1000000LL) / mSampleRate);
1641    } else {
1642        bitRate = bitRate != 0 ? bitRate : kOffloadDefaultBitRateBps;
1643        mBufferDurationUs = (uint32_t)((mBufferSize * 8 * 1000000LL) / bitRate);
1644    }
1645}
1646
1647AudioFlinger::PlaybackThread::~PlaybackThread()
1648{
1649    mAudioFlinger->unregisterWriter(mNBLogWriter);
1650    free(mSinkBuffer);
1651    free(mMixerBuffer);
1652    free(mEffectBuffer);
1653}
1654
1655void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1656{
1657    dumpInternals(fd, args);
1658    dumpTracks(fd, args);
1659    dumpEffectChains(fd, args);
1660}
1661
1662void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
1663{
1664    const size_t SIZE = 256;
1665    char buffer[SIZE];
1666    String8 result;
1667
1668    result.appendFormat("  Stream volumes in dB: ");
1669    for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1670        const stream_type_t *st = &mStreamTypes[i];
1671        if (i > 0) {
1672            result.appendFormat(", ");
1673        }
1674        result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1675        if (st->mute) {
1676            result.append("M");
1677        }
1678    }
1679    result.append("\n");
1680    write(fd, result.string(), result.length());
1681    result.clear();
1682
1683    // These values are "raw"; they will wrap around.  See prepareTracks_l() for a better way.
1684    FastTrackUnderruns underruns = getFastTrackUnderruns(0);
1685    dprintf(fd, "  Normal mixer raw underrun counters: partial=%u empty=%u\n",
1686            underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
1687
1688    size_t numtracks = mTracks.size();
1689    size_t numactive = mActiveTracks.size();
1690    dprintf(fd, "  %zu Tracks", numtracks);
1691    size_t numactiveseen = 0;
1692    if (numtracks) {
1693        dprintf(fd, " of which %zu are active\n", numactive);
1694        Track::appendDumpHeader(result);
1695        for (size_t i = 0; i < numtracks; ++i) {
1696            sp<Track> track = mTracks[i];
1697            if (track != 0) {
1698                bool active = mActiveTracks.indexOf(track) >= 0;
1699                if (active) {
1700                    numactiveseen++;
1701                }
1702                track->dump(buffer, SIZE, active);
1703                result.append(buffer);
1704            }
1705        }
1706    } else {
1707        result.append("\n");
1708    }
1709    if (numactiveseen != numactive) {
1710        // some tracks in the active list were not in the tracks list
1711        snprintf(buffer, SIZE, "  The following tracks are in the active list but"
1712                " not in the track list\n");
1713        result.append(buffer);
1714        Track::appendDumpHeader(result);
1715        for (size_t i = 0; i < numactive; ++i) {
1716            sp<Track> track = mActiveTracks[i].promote();
1717            if (track != 0 && mTracks.indexOf(track) < 0) {
1718                track->dump(buffer, SIZE, true);
1719                result.append(buffer);
1720            }
1721        }
1722    }
1723
1724    write(fd, result.string(), result.size());
1725}
1726
1727void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1728{
1729    dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
1730
1731    dumpBase(fd, args);
1732
1733    dprintf(fd, "  Normal frame count: %zu\n", mNormalFrameCount);
1734    dprintf(fd, "  Last write occurred (msecs): %llu\n",
1735            (unsigned long long) ns2ms(systemTime() - mLastWriteTime));
1736    dprintf(fd, "  Total writes: %d\n", mNumWrites);
1737    dprintf(fd, "  Delayed writes: %d\n", mNumDelayedWrites);
1738    dprintf(fd, "  Blocked in write: %s\n", mInWrite ? "yes" : "no");
1739    dprintf(fd, "  Suspend count: %d\n", mSuspended);
1740    dprintf(fd, "  Sink buffer : %p\n", mSinkBuffer);
1741    dprintf(fd, "  Mixer buffer: %p\n", mMixerBuffer);
1742    dprintf(fd, "  Effect buffer: %p\n", mEffectBuffer);
1743    dprintf(fd, "  Fast track availMask=%#x\n", mFastTrackAvailMask);
1744    dprintf(fd, "  Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
1745    AudioStreamOut *output = mOutput;
1746    audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
1747    String8 flagsAsString = outputFlagsToString(flags);
1748    dprintf(fd, "  AudioStreamOut: %p flags %#x (%s)\n", output, flags, flagsAsString.string());
1749}
1750
1751// Thread virtuals
1752
1753void AudioFlinger::PlaybackThread::onFirstRef()
1754{
1755    run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
1756}
1757
1758// ThreadBase virtuals
1759void AudioFlinger::PlaybackThread::preExit()
1760{
1761    ALOGV("  preExit()");
1762    // FIXME this is using hard-coded strings but in the future, this functionality will be
1763    //       converted to use audio HAL extensions required to support tunneling
1764    mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1765}
1766
1767// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1768sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1769        const sp<AudioFlinger::Client>& client,
1770        audio_stream_type_t streamType,
1771        uint32_t sampleRate,
1772        audio_format_t format,
1773        audio_channel_mask_t channelMask,
1774        size_t *pFrameCount,
1775        const sp<IMemory>& sharedBuffer,
1776        audio_session_t sessionId,
1777        IAudioFlinger::track_flags_t *flags,
1778        pid_t tid,
1779        int uid,
1780        status_t *status)
1781{
1782    size_t frameCount = *pFrameCount;
1783    sp<Track> track;
1784    status_t lStatus;
1785
1786    // client expresses a preference for FAST, but we get the final say
1787    if (*flags & IAudioFlinger::TRACK_FAST) {
1788      if (
1789            // PCM data
1790            audio_is_linear_pcm(format) &&
1791            // TODO: extract as a data library function that checks that a computationally
1792            // expensive downmixer is not required: isFastOutputChannelConversion()
1793            (channelMask == mChannelMask ||
1794                    mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1795                    (channelMask == AUDIO_CHANNEL_OUT_MONO
1796                            /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
1797            // hardware sample rate
1798            (sampleRate == mSampleRate) &&
1799            // normal mixer has an associated fast mixer
1800            hasFastMixer() &&
1801            // there are sufficient fast track slots available
1802            (mFastTrackAvailMask != 0)
1803            // FIXME test that MixerThread for this fast track has a capable output HAL
1804            // FIXME add a permission test also?
1805        ) {
1806        // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1807        if (sharedBuffer == 0) {
1808            // read the fast track multiplier property the first time it is needed
1809            int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1810            if (ok != 0) {
1811                ALOGE("%s pthread_once failed: %d", __func__, ok);
1812            }
1813            frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
1814        }
1815        ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
1816                frameCount, mFrameCount);
1817      } else {
1818        ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1819                "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
1820                "sampleRate=%u mSampleRate=%u "
1821                "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1822                sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
1823                audio_is_linear_pcm(format),
1824                channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1825        *flags &= ~IAudioFlinger::TRACK_FAST;
1826      }
1827    }
1828    // For normal PCM streaming tracks, update minimum frame count.
1829    // For compatibility with AudioTrack calculation, buffer depth is forced
1830    // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1831    // This is probably too conservative, but legacy application code may depend on it.
1832    // If you change this calculation, also review the start threshold which is related.
1833    if (!(*flags & IAudioFlinger::TRACK_FAST)
1834            && audio_has_proportional_frames(format) && sharedBuffer == 0) {
1835        // this must match AudioTrack.cpp calculateMinFrameCount().
1836        // TODO: Move to a common library
1837        uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1838        uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1839        if (minBufCount < 2) {
1840            minBufCount = 2;
1841        }
1842        // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1843        // or the client should compute and pass in a larger buffer request.
1844        size_t minFrameCount =
1845                minBufCount * sourceFramesNeededWithTimestretch(
1846                        sampleRate, mNormalFrameCount,
1847                        mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
1848        if (frameCount < minFrameCount) { // including frameCount == 0
1849            frameCount = minFrameCount;
1850        }
1851    }
1852    *pFrameCount = frameCount;
1853
1854    switch (mType) {
1855
1856    case DIRECT:
1857        if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
1858            if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1859                ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1860                        "for output %p with format %#x",
1861                        sampleRate, format, channelMask, mOutput, mFormat);
1862                lStatus = BAD_VALUE;
1863                goto Exit;
1864            }
1865        }
1866        break;
1867
1868    case OFFLOAD:
1869        if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1870            ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1871                    "for output %p with format %#x",
1872                    sampleRate, format, channelMask, mOutput, mFormat);
1873            lStatus = BAD_VALUE;
1874            goto Exit;
1875        }
1876        break;
1877
1878    default:
1879        if (!audio_is_linear_pcm(format)) {
1880                ALOGE("createTrack_l() Bad parameter: format %#x \""
1881                        "for output %p with format %#x",
1882                        format, mOutput, mFormat);
1883                lStatus = BAD_VALUE;
1884                goto Exit;
1885        }
1886        if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
1887            ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1888            lStatus = BAD_VALUE;
1889            goto Exit;
1890        }
1891        break;
1892
1893    }
1894
1895    lStatus = initCheck();
1896    if (lStatus != NO_ERROR) {
1897        ALOGE("createTrack_l() audio driver not initialized");
1898        goto Exit;
1899    }
1900
1901    { // scope for mLock
1902        Mutex::Autolock _l(mLock);
1903
1904        // all tracks in same audio session must share the same routing strategy otherwise
1905        // conflicts will happen when tracks are moved from one output to another by audio policy
1906        // manager
1907        uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1908        for (size_t i = 0; i < mTracks.size(); ++i) {
1909            sp<Track> t = mTracks[i];
1910            if (t != 0 && t->isExternalTrack()) {
1911                uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1912                if (sessionId == t->sessionId() && strategy != actual) {
1913                    ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1914                            strategy, actual);
1915                    lStatus = BAD_VALUE;
1916                    goto Exit;
1917                }
1918            }
1919        }
1920
1921        track = new Track(this, client, streamType, sampleRate, format,
1922                          channelMask, frameCount, NULL, sharedBuffer,
1923                          sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
1924
1925        lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1926        if (lStatus != NO_ERROR) {
1927            ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
1928            // track must be cleared from the caller as the caller has the AF lock
1929            goto Exit;
1930        }
1931        mTracks.add(track);
1932
1933        sp<EffectChain> chain = getEffectChain_l(sessionId);
1934        if (chain != 0) {
1935            ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1936            track->setMainBuffer(chain->inBuffer());
1937            chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1938            chain->incTrackCnt();
1939        }
1940
1941        if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1942            pid_t callingPid = IPCThreadState::self()->getCallingPid();
1943            // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1944            // so ask activity manager to do this on our behalf
1945            sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1946        }
1947    }
1948
1949    lStatus = NO_ERROR;
1950
1951Exit:
1952    *status = lStatus;
1953    return track;
1954}
1955
1956uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1957{
1958    return latency;
1959}
1960
1961uint32_t AudioFlinger::PlaybackThread::latency() const
1962{
1963    Mutex::Autolock _l(mLock);
1964    return latency_l();
1965}
1966uint32_t AudioFlinger::PlaybackThread::latency_l() const
1967{
1968    if (initCheck() == NO_ERROR) {
1969        return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1970    } else {
1971        return 0;
1972    }
1973}
1974
1975void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1976{
1977    Mutex::Autolock _l(mLock);
1978    // Don't apply master volume in SW if our HAL can do it for us.
1979    if (mOutput && mOutput->audioHwDev &&
1980        mOutput->audioHwDev->canSetMasterVolume()) {
1981        mMasterVolume = 1.0;
1982    } else {
1983        mMasterVolume = value;
1984    }
1985}
1986
1987void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1988{
1989    Mutex::Autolock _l(mLock);
1990    // Don't apply master mute in SW if our HAL can do it for us.
1991    if (mOutput && mOutput->audioHwDev &&
1992        mOutput->audioHwDev->canSetMasterMute()) {
1993        mMasterMute = false;
1994    } else {
1995        mMasterMute = muted;
1996    }
1997}
1998
1999void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2000{
2001    Mutex::Autolock _l(mLock);
2002    mStreamTypes[stream].volume = value;
2003    broadcast_l();
2004}
2005
2006void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2007{
2008    Mutex::Autolock _l(mLock);
2009    mStreamTypes[stream].mute = muted;
2010    broadcast_l();
2011}
2012
2013float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2014{
2015    Mutex::Autolock _l(mLock);
2016    return mStreamTypes[stream].volume;
2017}
2018
2019// addTrack_l() must be called with ThreadBase::mLock held
2020status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2021{
2022    status_t status = ALREADY_EXISTS;
2023
2024    if (mActiveTracks.indexOf(track) < 0) {
2025        // the track is newly added, make sure it fills up all its
2026        // buffers before playing. This is to ensure the client will
2027        // effectively get the latency it requested.
2028        if (track->isExternalTrack()) {
2029            TrackBase::track_state state = track->mState;
2030            mLock.unlock();
2031            status = AudioSystem::startOutput(mId, track->streamType(),
2032                                              track->sessionId());
2033            mLock.lock();
2034            // abort track was stopped/paused while we released the lock
2035            if (state != track->mState) {
2036                if (status == NO_ERROR) {
2037                    mLock.unlock();
2038                    AudioSystem::stopOutput(mId, track->streamType(),
2039                                            track->sessionId());
2040                    mLock.lock();
2041                }
2042                return INVALID_OPERATION;
2043            }
2044            // abort if start is rejected by audio policy manager
2045            if (status != NO_ERROR) {
2046                return PERMISSION_DENIED;
2047            }
2048#ifdef ADD_BATTERY_DATA
2049            // to track the speaker usage
2050            addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2051#endif
2052        }
2053
2054        // set retry count for buffer fill
2055        if (track->isOffloaded()) {
2056            track->mRetryCount = kMaxTrackStartupRetriesOffload;
2057        } else {
2058            track->mRetryCount = kMaxTrackStartupRetries;
2059        }
2060
2061        track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
2062        track->mResetDone = false;
2063        track->mPresentationCompleteFrames = 0;
2064        mActiveTracks.add(track);
2065        mWakeLockUids.add(track->uid());
2066        mActiveTracksGeneration++;
2067        mLatestActiveTrack = track;
2068        sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2069        if (chain != 0) {
2070            ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2071                    track->sessionId());
2072            chain->incActiveTrackCnt();
2073        }
2074
2075        status = NO_ERROR;
2076    }
2077
2078    onAddNewTrack_l();
2079    return status;
2080}
2081
2082bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
2083{
2084    track->terminate();
2085    // active tracks are removed by threadLoop()
2086    bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2087    track->mState = TrackBase::STOPPED;
2088    if (!trackActive) {
2089        removeTrack_l(track);
2090    } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
2091        track->mState = TrackBase::STOPPING_1;
2092    }
2093
2094    return trackActive;
2095}
2096
2097void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2098{
2099    track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
2100    mTracks.remove(track);
2101    deleteTrackName_l(track->name());
2102    // redundant as track is about to be destroyed, for dumpsys only
2103    track->mName = -1;
2104    if (track->isFastTrack()) {
2105        int index = track->mFastIndex;
2106        ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
2107        ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2108        mFastTrackAvailMask |= 1 << index;
2109        // redundant as track is about to be destroyed, for dumpsys only
2110        track->mFastIndex = -1;
2111    }
2112    sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2113    if (chain != 0) {
2114        chain->decTrackCnt();
2115    }
2116}
2117
2118void AudioFlinger::PlaybackThread::broadcast_l()
2119{
2120    // Thread could be blocked waiting for async
2121    // so signal it to handle state changes immediately
2122    // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2123    // be lost so we also flag to prevent it blocking on mWaitWorkCV
2124    mSignalPending = true;
2125    mWaitWorkCV.broadcast();
2126}
2127
2128String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2129{
2130    Mutex::Autolock _l(mLock);
2131    if (initCheck() != NO_ERROR) {
2132        return String8();
2133    }
2134
2135    char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
2136    const String8 out_s8(s);
2137    free(s);
2138    return out_s8;
2139}
2140
2141void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
2142    sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2143    ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
2144
2145    desc->mIoHandle = mId;
2146
2147    switch (event) {
2148    case AUDIO_OUTPUT_OPENED:
2149    case AUDIO_OUTPUT_CONFIG_CHANGED:
2150        desc->mPatch = mPatch;
2151        desc->mChannelMask = mChannelMask;
2152        desc->mSamplingRate = mSampleRate;
2153        desc->mFormat = mFormat;
2154        desc->mFrameCount = mNormalFrameCount; // FIXME see
2155                                             // AudioFlinger::frameCount(audio_io_handle_t)
2156        desc->mLatency = latency_l();
2157        break;
2158
2159    case AUDIO_OUTPUT_CLOSED:
2160    default:
2161        break;
2162    }
2163    mAudioFlinger->ioConfigChanged(event, desc, pid);
2164}
2165
2166void AudioFlinger::PlaybackThread::writeCallback()
2167{
2168    ALOG_ASSERT(mCallbackThread != 0);
2169    mCallbackThread->resetWriteBlocked();
2170}
2171
2172void AudioFlinger::PlaybackThread::drainCallback()
2173{
2174    ALOG_ASSERT(mCallbackThread != 0);
2175    mCallbackThread->resetDraining();
2176}
2177
2178void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
2179{
2180    Mutex::Autolock _l(mLock);
2181    // reject out of sequence requests
2182    if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2183        mWriteAckSequence &= ~1;
2184        mWaitWorkCV.signal();
2185    }
2186}
2187
2188void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
2189{
2190    Mutex::Autolock _l(mLock);
2191    // reject out of sequence requests
2192    if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2193        mDrainSequence &= ~1;
2194        mWaitWorkCV.signal();
2195    }
2196}
2197
2198// static
2199int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
2200                                                void *param __unused,
2201                                                void *cookie)
2202{
2203    AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
2204    ALOGV("asyncCallback() event %d", event);
2205    switch (event) {
2206    case STREAM_CBK_EVENT_WRITE_READY:
2207        me->writeCallback();
2208        break;
2209    case STREAM_CBK_EVENT_DRAIN_READY:
2210        me->drainCallback();
2211        break;
2212    default:
2213        ALOGW("asyncCallback() unknown event %d", event);
2214        break;
2215    }
2216    return 0;
2217}
2218
2219void AudioFlinger::PlaybackThread::readOutputParameters_l()
2220{
2221    // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
2222    mSampleRate = mOutput->getSampleRate();
2223    mChannelMask = mOutput->getChannelMask();
2224    if (!audio_is_output_channel(mChannelMask)) {
2225        LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
2226    }
2227    if ((mType == MIXER || mType == DUPLICATING)
2228            && !isValidPcmSinkChannelMask(mChannelMask)) {
2229        LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2230                mChannelMask);
2231    }
2232    mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
2233
2234    // Get actual HAL format.
2235    mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
2236    // Get format from the shim, which will be different than the HAL format
2237    // if playing compressed audio over HDMI passthrough.
2238    mFormat = mOutput->getFormat();
2239    if (!audio_is_valid_format(mFormat)) {
2240        LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
2241    }
2242    if ((mType == MIXER || mType == DUPLICATING)
2243            && !isValidPcmSinkFormat(mFormat)) {
2244        LOG_FATAL("HAL format %#x not supported for mixed output",
2245                mFormat);
2246    }
2247    mFrameSize = mOutput->getFrameSize();
2248    mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
2249    mFrameCount = mBufferSize / mFrameSize;
2250    if (mFrameCount & 15) {
2251        ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
2252                mFrameCount);
2253    }
2254
2255    if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
2256            (mOutput->stream->set_callback != NULL)) {
2257        if (mOutput->stream->set_callback(mOutput->stream,
2258                                      AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
2259            mUseAsyncWrite = true;
2260            mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
2261        }
2262    }
2263
2264    mHwSupportsPause = false;
2265    if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
2266        if (mOutput->stream->pause != NULL) {
2267            if (mOutput->stream->resume != NULL) {
2268                mHwSupportsPause = true;
2269            } else {
2270                ALOGW("direct output implements pause but not resume");
2271            }
2272        } else if (mOutput->stream->resume != NULL) {
2273            ALOGW("direct output implements resume but not pause");
2274        }
2275    }
2276    if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2277        LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2278    }
2279
2280    if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2281        // For best precision, we use float instead of the associated output
2282        // device format (typically PCM 16 bit).
2283
2284        mFormat = AUDIO_FORMAT_PCM_FLOAT;
2285        mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2286        mBufferSize = mFrameSize * mFrameCount;
2287
2288        // TODO: We currently use the associated output device channel mask and sample rate.
2289        // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2290        // (if a valid mask) to avoid premature downmix.
2291        // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2292        // instead of the output device sample rate to avoid loss of high frequency information.
2293        // This may need to be updated as MixerThread/OutputTracks are added and not here.
2294    }
2295
2296    // Calculate size of normal sink buffer relative to the HAL output buffer size
2297    double multiplier = 1.0;
2298    if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2299            kUseFastMixer == FastMixer_Dynamic)) {
2300        size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2301        size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
2302        // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2303        minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2304        maxNormalFrameCount = maxNormalFrameCount & ~15;
2305        if (maxNormalFrameCount < minNormalFrameCount) {
2306            maxNormalFrameCount = minNormalFrameCount;
2307        }
2308        multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2309        if (multiplier <= 1.0) {
2310            multiplier = 1.0;
2311        } else if (multiplier <= 2.0) {
2312            if (2 * mFrameCount <= maxNormalFrameCount) {
2313                multiplier = 2.0;
2314            } else {
2315                multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2316            }
2317        } else {
2318            // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
2319            // SRC (it would be unusual for the normal sink buffer size to not be a multiple of fast
2320            // track, but we sometimes have to do this to satisfy the maximum frame count
2321            // constraint)
2322            // FIXME this rounding up should not be done if no HAL SRC
2323            uint32_t truncMult = (uint32_t) multiplier;
2324            if ((truncMult & 1)) {
2325                if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2326                    ++truncMult;
2327                }
2328            }
2329            multiplier = (double) truncMult;
2330        }
2331    }
2332    mNormalFrameCount = multiplier * mFrameCount;
2333    // round up to nearest 16 frames to satisfy AudioMixer
2334    if (mType == MIXER || mType == DUPLICATING) {
2335        mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2336    }
2337    ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
2338            mNormalFrameCount);
2339
2340    // Check if we want to throttle the processing to no more than 2x normal rate
2341    mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
2342    mThreadThrottleTimeMs = 0;
2343    mThreadThrottleEndMs = 0;
2344    mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2345
2346    // mSinkBuffer is the sink buffer.  Size is always multiple-of-16 frames.
2347    // Originally this was int16_t[] array, need to remove legacy implications.
2348    free(mSinkBuffer);
2349    mSinkBuffer = NULL;
2350    // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2351    // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2352    const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
2353    (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
2354
2355    // We resize the mMixerBuffer according to the requirements of the sink buffer which
2356    // drives the output.
2357    free(mMixerBuffer);
2358    mMixerBuffer = NULL;
2359    if (mMixerBufferEnabled) {
2360        mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2361        mMixerBufferSize = mNormalFrameCount * mChannelCount
2362                * audio_bytes_per_sample(mMixerBufferFormat);
2363        (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2364    }
2365    free(mEffectBuffer);
2366    mEffectBuffer = NULL;
2367    if (mEffectBufferEnabled) {
2368        mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2369        mEffectBufferSize = mNormalFrameCount * mChannelCount
2370                * audio_bytes_per_sample(mEffectBufferFormat);
2371        (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2372    }
2373
2374    // force reconfiguration of effect chains and engines to take new buffer size and audio
2375    // parameters into account
2376    // Note that mLock is not held when readOutputParameters_l() is called from the constructor
2377    // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2378    // matter.
2379    // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2380    Vector< sp<EffectChain> > effectChains = mEffectChains;
2381    for (size_t i = 0; i < effectChains.size(); i ++) {
2382        mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2383    }
2384}
2385
2386
2387status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
2388{
2389    if (halFrames == NULL || dspFrames == NULL) {
2390        return BAD_VALUE;
2391    }
2392    Mutex::Autolock _l(mLock);
2393    if (initCheck() != NO_ERROR) {
2394        return INVALID_OPERATION;
2395    }
2396    int64_t framesWritten = mBytesWritten / mFrameSize;
2397    *halFrames = framesWritten;
2398
2399    if (isSuspended()) {
2400        // return an estimation of rendered frames when the output is suspended
2401        size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
2402        *dspFrames = (uint32_t)
2403                (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
2404        return NO_ERROR;
2405    } else {
2406        status_t status;
2407        uint32_t frames;
2408        status = mOutput->getRenderPosition(&frames);
2409        *dspFrames = (size_t)frames;
2410        return status;
2411    }
2412}
2413
2414uint32_t AudioFlinger::PlaybackThread::hasAudioSession(audio_session_t sessionId) const
2415{
2416    Mutex::Autolock _l(mLock);
2417    uint32_t result = 0;
2418    if (getEffectChain_l(sessionId) != 0) {
2419        result = EFFECT_SESSION;
2420    }
2421
2422    for (size_t i = 0; i < mTracks.size(); ++i) {
2423        sp<Track> track = mTracks[i];
2424        if (sessionId == track->sessionId() && !track->isInvalid()) {
2425            result |= TRACK_SESSION;
2426            break;
2427        }
2428    }
2429
2430    return result;
2431}
2432
2433uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
2434{
2435    // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2436    // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2437    if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2438        return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2439    }
2440    for (size_t i = 0; i < mTracks.size(); i++) {
2441        sp<Track> track = mTracks[i];
2442        if (sessionId == track->sessionId() && !track->isInvalid()) {
2443            return AudioSystem::getStrategyForStream(track->streamType());
2444        }
2445    }
2446    return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2447}
2448
2449
2450AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
2451{
2452    Mutex::Autolock _l(mLock);
2453    return mOutput;
2454}
2455
2456AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2457{
2458    Mutex::Autolock _l(mLock);
2459    AudioStreamOut *output = mOutput;
2460    mOutput = NULL;
2461    // FIXME FastMixer might also have a raw ptr to mOutputSink;
2462    //       must push a NULL and wait for ack
2463    mOutputSink.clear();
2464    mPipeSink.clear();
2465    mNormalSink.clear();
2466    return output;
2467}
2468
2469// this method must always be called either with ThreadBase mLock held or inside the thread loop
2470audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2471{
2472    if (mOutput == NULL) {
2473        return NULL;
2474    }
2475    return &mOutput->stream->common;
2476}
2477
2478uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2479{
2480    return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2481}
2482
2483status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2484{
2485    if (!isValidSyncEvent(event)) {
2486        return BAD_VALUE;
2487    }
2488
2489    Mutex::Autolock _l(mLock);
2490
2491    for (size_t i = 0; i < mTracks.size(); ++i) {
2492        sp<Track> track = mTracks[i];
2493        if (event->triggerSession() == track->sessionId()) {
2494            (void) track->setSyncEvent(event);
2495            return NO_ERROR;
2496        }
2497    }
2498
2499    return NAME_NOT_FOUND;
2500}
2501
2502bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2503{
2504    return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2505}
2506
2507void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2508        const Vector< sp<Track> >& tracksToRemove)
2509{
2510    size_t count = tracksToRemove.size();
2511    if (count > 0) {
2512        for (size_t i = 0 ; i < count ; i++) {
2513            const sp<Track>& track = tracksToRemove.itemAt(i);
2514            if (track->isExternalTrack()) {
2515                AudioSystem::stopOutput(mId, track->streamType(),
2516                                        track->sessionId());
2517#ifdef ADD_BATTERY_DATA
2518                // to track the speaker usage
2519                addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2520#endif
2521                if (track->isTerminated()) {
2522                    AudioSystem::releaseOutput(mId, track->streamType(),
2523                                               track->sessionId());
2524                }
2525            }
2526        }
2527    }
2528}
2529
2530void AudioFlinger::PlaybackThread::checkSilentMode_l()
2531{
2532    if (!mMasterMute) {
2533        char value[PROPERTY_VALUE_MAX];
2534        if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2535            ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2536            return;
2537        }
2538        if (property_get("ro.audio.silent", value, "0") > 0) {
2539            char *endptr;
2540            unsigned long ul = strtoul(value, &endptr, 0);
2541            if (*endptr == '\0' && ul != 0) {
2542                ALOGD("Silence is golden");
2543                // The setprop command will not allow a property to be changed after
2544                // the first time it is set, so we don't have to worry about un-muting.
2545                setMasterMute_l(true);
2546            }
2547        }
2548    }
2549}
2550
2551// shared by MIXER and DIRECT, overridden by DUPLICATING
2552ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
2553{
2554    // FIXME rewrite to reduce number of system calls
2555    mLastWriteTime = systemTime();
2556    mInWrite = true;
2557    ssize_t bytesWritten;
2558    const size_t offset = mCurrentWriteLength - mBytesRemaining;
2559
2560    // If an NBAIO sink is present, use it to write the normal mixer's submix
2561    if (mNormalSink != 0) {
2562
2563        const size_t count = mBytesRemaining / mFrameSize;
2564
2565        ATRACE_BEGIN("write");
2566        // update the setpoint when AudioFlinger::mScreenState changes
2567        uint32_t screenState = AudioFlinger::mScreenState;
2568        if (screenState != mScreenState) {
2569            mScreenState = screenState;
2570            MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2571            if (pipe != NULL) {
2572                pipe->setAvgFrames((mScreenState & 1) ?
2573                        (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2574            }
2575        }
2576        ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
2577        ATRACE_END();
2578        if (framesWritten > 0) {
2579            bytesWritten = framesWritten * mFrameSize;
2580        } else {
2581            bytesWritten = framesWritten;
2582        }
2583    // otherwise use the HAL / AudioStreamOut directly
2584    } else {
2585        // Direct output and offload threads
2586
2587        if (mUseAsyncWrite) {
2588            ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2589            mWriteAckSequence += 2;
2590            mWriteAckSequence |= 1;
2591            ALOG_ASSERT(mCallbackThread != 0);
2592            mCallbackThread->setWriteBlocked(mWriteAckSequence);
2593        }
2594        // FIXME We should have an implementation of timestamps for direct output threads.
2595        // They are used e.g for multichannel PCM playback over HDMI.
2596        bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
2597
2598        if (mUseAsyncWrite &&
2599                ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2600            // do not wait for async callback in case of error of full write
2601            mWriteAckSequence &= ~1;
2602            ALOG_ASSERT(mCallbackThread != 0);
2603            mCallbackThread->setWriteBlocked(mWriteAckSequence);
2604        }
2605    }
2606
2607    mNumWrites++;
2608    mInWrite = false;
2609    mStandby = false;
2610    return bytesWritten;
2611}
2612
2613void AudioFlinger::PlaybackThread::threadLoop_drain()
2614{
2615    if (mOutput->stream->drain) {
2616        ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2617        if (mUseAsyncWrite) {
2618            ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2619            mDrainSequence |= 1;
2620            ALOG_ASSERT(mCallbackThread != 0);
2621            mCallbackThread->setDraining(mDrainSequence);
2622        }
2623        mOutput->stream->drain(mOutput->stream,
2624            (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2625                                                : AUDIO_DRAIN_ALL);
2626    }
2627}
2628
2629void AudioFlinger::PlaybackThread::threadLoop_exit()
2630{
2631    {
2632        Mutex::Autolock _l(mLock);
2633        for (size_t i = 0; i < mTracks.size(); i++) {
2634            sp<Track> track = mTracks[i];
2635            track->invalidate();
2636        }
2637    }
2638}
2639
2640/*
2641The derived values that are cached:
2642 - mSinkBufferSize from frame count * frame size
2643 - mActiveSleepTimeUs from activeSleepTimeUs()
2644 - mIdleSleepTimeUs from idleSleepTimeUs()
2645 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2646   kDefaultStandbyTimeInNsecs when connected to an A2DP device.
2647 - maxPeriod from frame count and sample rate (MIXER only)
2648
2649The parameters that affect these derived values are:
2650 - frame count
2651 - frame size
2652 - sample rate
2653 - device type: A2DP or not
2654 - device latency
2655 - format: PCM or not
2656 - active sleep time
2657 - idle sleep time
2658*/
2659
2660void AudioFlinger::PlaybackThread::cacheParameters_l()
2661{
2662    mSinkBufferSize = mNormalFrameCount * mFrameSize;
2663    mActiveSleepTimeUs = activeSleepTimeUs();
2664    mIdleSleepTimeUs = idleSleepTimeUs();
2665
2666    // make sure standby delay is not too short when connected to an A2DP sink to avoid
2667    // truncating audio when going to standby.
2668    mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2669    if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2670        if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2671            mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2672        }
2673    }
2674}
2675
2676void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2677{
2678    ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
2679            this,  streamType, mTracks.size());
2680    Mutex::Autolock _l(mLock);
2681
2682    size_t size = mTracks.size();
2683    for (size_t i = 0; i < size; i++) {
2684        sp<Track> t = mTracks[i];
2685        if (t->streamType() == streamType && t->isExternalTrack()) {
2686            t->invalidate();
2687        }
2688    }
2689}
2690
2691status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2692{
2693    audio_session_t session = chain->sessionId();
2694    int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2695            ? mEffectBuffer : mSinkBuffer);
2696    bool ownsBuffer = false;
2697
2698    ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2699    if (session > AUDIO_SESSION_OUTPUT_MIX) {
2700        // Only one effect chain can be present in direct output thread and it uses
2701        // the sink buffer as input
2702        if (mType != DIRECT) {
2703            size_t numSamples = mNormalFrameCount * mChannelCount;
2704            buffer = new int16_t[numSamples];
2705            memset(buffer, 0, numSamples * sizeof(int16_t));
2706            ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2707            ownsBuffer = true;
2708        }
2709
2710        // Attach all tracks with same session ID to this chain.
2711        for (size_t i = 0; i < mTracks.size(); ++i) {
2712            sp<Track> track = mTracks[i];
2713            if (session == track->sessionId()) {
2714                ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2715                        buffer);
2716                track->setMainBuffer(buffer);
2717                chain->incTrackCnt();
2718            }
2719        }
2720
2721        // indicate all active tracks in the chain
2722        for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2723            sp<Track> track = mActiveTracks[i].promote();
2724            if (track == 0) {
2725                continue;
2726            }
2727            if (session == track->sessionId()) {
2728                ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2729                chain->incActiveTrackCnt();
2730            }
2731        }
2732    }
2733    chain->setThread(this);
2734    chain->setInBuffer(buffer, ownsBuffer);
2735    chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2736            ? mEffectBuffer : mSinkBuffer));
2737    // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2738    // chains list in order to be processed last as it contains output stage effects.
2739    // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2740    // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2741    // after track specific effects and before output stage.
2742    // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2743    // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
2744    // Effect chain for other sessions are inserted at beginning of effect
2745    // chains list to be processed before output mix effects. Relative order between other
2746    // sessions is not important.
2747    static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
2748            AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
2749            "audio_session_t constants misdefined");
2750    size_t size = mEffectChains.size();
2751    size_t i = 0;
2752    for (i = 0; i < size; i++) {
2753        if (mEffectChains[i]->sessionId() < session) {
2754            break;
2755        }
2756    }
2757    mEffectChains.insertAt(chain, i);
2758    checkSuspendOnAddEffectChain_l(chain);
2759
2760    return NO_ERROR;
2761}
2762
2763size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2764{
2765    audio_session_t session = chain->sessionId();
2766
2767    ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2768
2769    for (size_t i = 0; i < mEffectChains.size(); i++) {
2770        if (chain == mEffectChains[i]) {
2771            mEffectChains.removeAt(i);
2772            // detach all active tracks from the chain
2773            for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2774                sp<Track> track = mActiveTracks[i].promote();
2775                if (track == 0) {
2776                    continue;
2777                }
2778                if (session == track->sessionId()) {
2779                    ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2780                            chain.get(), session);
2781                    chain->decActiveTrackCnt();
2782                }
2783            }
2784
2785            // detach all tracks with same session ID from this chain
2786            for (size_t i = 0; i < mTracks.size(); ++i) {
2787                sp<Track> track = mTracks[i];
2788                if (session == track->sessionId()) {
2789                    track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
2790                    chain->decTrackCnt();
2791                }
2792            }
2793            break;
2794        }
2795    }
2796    return mEffectChains.size();
2797}
2798
2799status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2800        const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2801{
2802    Mutex::Autolock _l(mLock);
2803    return attachAuxEffect_l(track, EffectId);
2804}
2805
2806status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2807        const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2808{
2809    status_t status = NO_ERROR;
2810
2811    if (EffectId == 0) {
2812        track->setAuxBuffer(0, NULL);
2813    } else {
2814        // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2815        sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2816        if (effect != 0) {
2817            if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2818                track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2819            } else {
2820                status = INVALID_OPERATION;
2821            }
2822        } else {
2823            status = BAD_VALUE;
2824        }
2825    }
2826    return status;
2827}
2828
2829void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2830{
2831    for (size_t i = 0; i < mTracks.size(); ++i) {
2832        sp<Track> track = mTracks[i];
2833        if (track->auxEffectId() == effectId) {
2834            attachAuxEffect_l(track, 0);
2835        }
2836    }
2837}
2838
2839bool AudioFlinger::PlaybackThread::threadLoop()
2840{
2841    Vector< sp<Track> > tracksToRemove;
2842
2843    mStandbyTimeNs = systemTime();
2844
2845    // MIXER
2846    nsecs_t lastWarning = 0;
2847
2848    // DUPLICATING
2849    // FIXME could this be made local to while loop?
2850    writeFrames = 0;
2851
2852    int lastGeneration = 0;
2853
2854    cacheParameters_l();
2855    mSleepTimeUs = mIdleSleepTimeUs;
2856
2857    if (mType == MIXER) {
2858        sleepTimeShift = 0;
2859    }
2860
2861    CpuStats cpuStats;
2862    const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2863
2864    acquireWakeLock();
2865
2866    // mNBLogWriter->log can only be called while thread mutex mLock is held.
2867    // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2868    // and then that string will be logged at the next convenient opportunity.
2869    const char *logString = NULL;
2870
2871    checkSilentMode_l();
2872
2873    while (!exitPending())
2874    {
2875        cpuStats.sample(myName);
2876
2877        Vector< sp<EffectChain> > effectChains;
2878
2879        { // scope for mLock
2880
2881            Mutex::Autolock _l(mLock);
2882
2883            processConfigEvents_l();
2884
2885            if (logString != NULL) {
2886                mNBLogWriter->logTimestamp();
2887                mNBLogWriter->log(logString);
2888                logString = NULL;
2889            }
2890
2891            // Gather the framesReleased counters for all active tracks,
2892            // and associate with the sink frames written out.  We need
2893            // this to convert the sink timestamp to the track timestamp.
2894            if (mNormalSink != 0) {
2895                // Note: The DuplicatingThread may not have a mNormalSink.
2896                // We always fetch the timestamp here because often the downstream
2897                // sink will block whie writing.
2898                ExtendedTimestamp timestamp; // use private copy to fetch
2899                (void) mNormalSink->getTimestamp(timestamp);
2900                // copy over kernel info
2901                mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
2902                        timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
2903                mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
2904                        timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
2905            }
2906            // mFramesWritten for non-offloaded tracks are contiguous
2907            // even after standby() is called. This is useful for the track frame
2908            // to sink frame mapping.
2909            mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
2910            mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
2911            const size_t size = mActiveTracks.size();
2912            for (size_t i = 0; i < size; ++i) {
2913                sp<Track> t = mActiveTracks[i].promote();
2914                if (t != 0 && !t->isFastTrack()) {
2915                    t->updateTrackFrameInfo(
2916                            t->mAudioTrackServerProxy->framesReleased(),
2917                            mFramesWritten,
2918                            mTimestamp);
2919                }
2920            }
2921
2922            saveOutputTracks();
2923            if (mSignalPending) {
2924                // A signal was raised while we were unlocked
2925                mSignalPending = false;
2926            } else if (waitingAsyncCallback_l()) {
2927                if (exitPending()) {
2928                    break;
2929                }
2930                bool released = false;
2931                // The following works around a bug in the offload driver. Ideally we would release
2932                // the wake lock every time, but that causes the last offload buffer(s) to be
2933                // dropped while the device is on battery, so we need to hold a wake lock during
2934                // the drain phase.
2935                if (mBytesRemaining && !(mDrainSequence & 1)) {
2936                    releaseWakeLock_l();
2937                    released = true;
2938                }
2939                mWakeLockUids.clear();
2940                mActiveTracksGeneration++;
2941                ALOGV("wait async completion");
2942                mWaitWorkCV.wait(mLock);
2943                ALOGV("async completion/wake");
2944                if (released) {
2945                    acquireWakeLock_l();
2946                }
2947                mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2948                mSleepTimeUs = 0;
2949
2950                continue;
2951            }
2952            if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
2953                                   isSuspended()) {
2954                // put audio hardware into standby after short delay
2955                if (shouldStandby_l()) {
2956
2957                    threadLoop_standby();
2958
2959                    mStandby = true;
2960                }
2961
2962                if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2963                    // we're about to wait, flush the binder command buffer
2964                    IPCThreadState::self()->flushCommands();
2965
2966                    clearOutputTracks();
2967
2968                    if (exitPending()) {
2969                        break;
2970                    }
2971
2972                    releaseWakeLock_l();
2973                    mWakeLockUids.clear();
2974                    mActiveTracksGeneration++;
2975                    // wait until we have something to do...
2976                    ALOGV("%s going to sleep", myName.string());
2977                    mWaitWorkCV.wait(mLock);
2978                    ALOGV("%s waking up", myName.string());
2979                    acquireWakeLock_l();
2980
2981                    mMixerStatus = MIXER_IDLE;
2982                    mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2983                    mBytesWritten = 0;
2984                    mBytesRemaining = 0;
2985                    checkSilentMode_l();
2986
2987                    mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2988                    mSleepTimeUs = mIdleSleepTimeUs;
2989                    if (mType == MIXER) {
2990                        sleepTimeShift = 0;
2991                    }
2992
2993                    continue;
2994                }
2995            }
2996            // mMixerStatusIgnoringFastTracks is also updated internally
2997            mMixerStatus = prepareTracks_l(&tracksToRemove);
2998
2999            // compare with previously applied list
3000            if (lastGeneration != mActiveTracksGeneration) {
3001                // update wakelock
3002                updateWakeLockUids_l(mWakeLockUids);
3003                lastGeneration = mActiveTracksGeneration;
3004            }
3005
3006            // prevent any changes in effect chain list and in each effect chain
3007            // during mixing and effect process as the audio buffers could be deleted
3008            // or modified if an effect is created or deleted
3009            lockEffectChains_l(effectChains);
3010        } // mLock scope ends
3011
3012        if (mBytesRemaining == 0) {
3013            mCurrentWriteLength = 0;
3014            if (mMixerStatus == MIXER_TRACKS_READY) {
3015                // threadLoop_mix() sets mCurrentWriteLength
3016                threadLoop_mix();
3017            } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3018                        && (mMixerStatus != MIXER_DRAIN_ALL)) {
3019                // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
3020                // must be written to HAL
3021                threadLoop_sleepTime();
3022                if (mSleepTimeUs == 0) {
3023                    mCurrentWriteLength = mSinkBufferSize;
3024                }
3025            }
3026            // Either threadLoop_mix() or threadLoop_sleepTime() should have set
3027            // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
3028            // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3029            // or mSinkBuffer (if there are no effects).
3030            //
3031            // This is done pre-effects computation; if effects change to
3032            // support higher precision, this needs to move.
3033            //
3034            // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
3035            // TODO use mSleepTimeUs == 0 as an additional condition.
3036            if (mMixerBufferValid) {
3037                void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3038                audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3039
3040                // mono blend occurs for mixer threads only (not direct or offloaded)
3041                // and is handled here if we're going directly to the sink.
3042                if (requireMonoBlend() && !mEffectBufferValid) {
3043                    mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3044                               true /*limit*/);
3045                }
3046
3047                memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3048                        mNormalFrameCount * mChannelCount);
3049            }
3050
3051            mBytesRemaining = mCurrentWriteLength;
3052            if (isSuspended()) {
3053                mSleepTimeUs = suspendSleepTimeUs();
3054                // simulate write to HAL when suspended
3055                mBytesWritten += mSinkBufferSize;
3056                mFramesWritten += mSinkBufferSize / mFrameSize;
3057                mBytesRemaining = 0;
3058            }
3059
3060            // only process effects if we're going to write
3061            if (mSleepTimeUs == 0 && mType != OFFLOAD) {
3062                for (size_t i = 0; i < effectChains.size(); i ++) {
3063                    effectChains[i]->process_l();
3064                }
3065            }
3066        }
3067        // Process effect chains for offloaded thread even if no audio
3068        // was read from audio track: process only updates effect state
3069        // and thus does have to be synchronized with audio writes but may have
3070        // to be called while waiting for async write callback
3071        if (mType == OFFLOAD) {
3072            for (size_t i = 0; i < effectChains.size(); i ++) {
3073                effectChains[i]->process_l();
3074            }
3075        }
3076
3077        // Only if the Effects buffer is enabled and there is data in the
3078        // Effects buffer (buffer valid), we need to
3079        // copy into the sink buffer.
3080        // TODO use mSleepTimeUs == 0 as an additional condition.
3081        if (mEffectBufferValid) {
3082            //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
3083
3084            if (requireMonoBlend()) {
3085                mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3086                           true /*limit*/);
3087            }
3088
3089            memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3090                    mNormalFrameCount * mChannelCount);
3091        }
3092
3093        // enable changes in effect chain
3094        unlockEffectChains(effectChains);
3095
3096        if (!waitingAsyncCallback()) {
3097            // mSleepTimeUs == 0 means we must write to audio hardware
3098            if (mSleepTimeUs == 0) {
3099                ssize_t ret = 0;
3100                if (mBytesRemaining) {
3101                    ret = threadLoop_write();
3102                    if (ret < 0) {
3103                        mBytesRemaining = 0;
3104                    } else {
3105                        mBytesWritten += ret;
3106                        mBytesRemaining -= ret;
3107                        mFramesWritten += ret / mFrameSize;
3108                    }
3109                } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3110                        (mMixerStatus == MIXER_DRAIN_ALL)) {
3111                    threadLoop_drain();
3112                }
3113                if (mType == MIXER && !mStandby) {
3114                    // write blocked detection
3115                    nsecs_t now = systemTime();
3116                    nsecs_t delta = now - mLastWriteTime;
3117                    if (delta > maxPeriod) {
3118                        mNumDelayedWrites++;
3119                        if ((now - lastWarning) > kWarningThrottleNs) {
3120                            ATRACE_NAME("underrun");
3121                            ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
3122                                    (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
3123                            lastWarning = now;
3124                        }
3125                    }
3126
3127                    if (mThreadThrottle
3128                            && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3129                            && ret > 0) {                         // we wrote something
3130                        // Limit MixerThread data processing to no more than twice the
3131                        // expected processing rate.
3132                        //
3133                        // This helps prevent underruns with NuPlayer and other applications
3134                        // which may set up buffers that are close to the minimum size, or use
3135                        // deep buffers, and rely on a double-buffering sleep strategy to fill.
3136                        //
3137                        // The throttle smooths out sudden large data drains from the device,
3138                        // e.g. when it comes out of standby, which often causes problems with
3139                        // (1) mixer threads without a fast mixer (which has its own warm-up)
3140                        // (2) minimum buffer sized tracks (even if the track is full,
3141                        //     the app won't fill fast enough to handle the sudden draw).
3142
3143                        const int32_t deltaMs = delta / 1000000;
3144                        const int32_t throttleMs = mHalfBufferMs - deltaMs;
3145                        if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3146                            usleep(throttleMs * 1000);
3147                            // notify of throttle start on verbose log
3148                            ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3149                                    "mixer(%p) throttle begin:"
3150                                    " ret(%zd) deltaMs(%d) requires sleep %d ms",
3151                                    this, ret, deltaMs, throttleMs);
3152                            mThreadThrottleTimeMs += throttleMs;
3153                        } else {
3154                            uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3155                            if (diff > 0) {
3156                                // notify of throttle end on debug log
3157                                ALOGD("mixer(%p) throttle end: throttle time(%u)", this, diff);
3158                                mThreadThrottleEndMs = mThreadThrottleTimeMs;
3159                            }
3160                        }
3161                    }
3162                }
3163
3164            } else {
3165                ATRACE_BEGIN("sleep");
3166                if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
3167                    Mutex::Autolock _l(mLock);
3168                    if (!mSignalPending && !exitPending()) {
3169                        // Do not sleep more than one buffer duration since last write and not
3170                        // less than kDirectMinSleepTimeUs
3171                        // Wake up if a command is received
3172                        nsecs_t now = systemTime();
3173                        uint32_t deltaUs = (uint32_t)((now - mLastWriteTime) / 1000);
3174                        uint32_t timeoutUs = mSleepTimeUs;
3175                        if (timeoutUs + deltaUs > mBufferDurationUs) {
3176                            if (mBufferDurationUs > deltaUs) {
3177                                timeoutUs = mBufferDurationUs - deltaUs;
3178                                if (timeoutUs < kDirectMinSleepTimeUs) {
3179                                    timeoutUs = kDirectMinSleepTimeUs;
3180                                }
3181                            } else {
3182                                timeoutUs = kDirectMinSleepTimeUs;
3183                            }
3184                        }
3185                        mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)timeoutUs));
3186                    }
3187                } else {
3188                    usleep(mSleepTimeUs);
3189                }
3190                ATRACE_END();
3191            }
3192        }
3193
3194        // Finally let go of removed track(s), without the lock held
3195        // since we can't guarantee the destructors won't acquire that
3196        // same lock.  This will also mutate and push a new fast mixer state.
3197        threadLoop_removeTracks(tracksToRemove);
3198        tracksToRemove.clear();
3199
3200        // FIXME I don't understand the need for this here;
3201        //       it was in the original code but maybe the
3202        //       assignment in saveOutputTracks() makes this unnecessary?
3203        clearOutputTracks();
3204
3205        // Effect chains will be actually deleted here if they were removed from
3206        // mEffectChains list during mixing or effects processing
3207        effectChains.clear();
3208
3209        // FIXME Note that the above .clear() is no longer necessary since effectChains
3210        // is now local to this block, but will keep it for now (at least until merge done).
3211    }
3212
3213    threadLoop_exit();
3214
3215    if (!mStandby) {
3216        threadLoop_standby();
3217        mStandby = true;
3218    }
3219
3220    releaseWakeLock();
3221    mWakeLockUids.clear();
3222    mActiveTracksGeneration++;
3223
3224    ALOGV("Thread %p type %d exiting", this, mType);
3225    return false;
3226}
3227
3228// removeTracks_l() must be called with ThreadBase::mLock held
3229void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3230{
3231    size_t count = tracksToRemove.size();
3232    if (count > 0) {
3233        for (size_t i=0 ; i<count ; i++) {
3234            const sp<Track>& track = tracksToRemove.itemAt(i);
3235            mActiveTracks.remove(track);
3236            mWakeLockUids.remove(track->uid());
3237            mActiveTracksGeneration++;
3238            ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3239            sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3240            if (chain != 0) {
3241                ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3242                        track->sessionId());
3243                chain->decActiveTrackCnt();
3244            }
3245            if (track->isTerminated()) {
3246                removeTrack_l(track);
3247            }
3248        }
3249    }
3250
3251}
3252
3253status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3254{
3255    if (mNormalSink != 0) {
3256        ExtendedTimestamp ets;
3257        status_t status = mNormalSink->getTimestamp(ets);
3258        if (status == NO_ERROR) {
3259            status = ets.getBestTimestamp(&timestamp);
3260        }
3261        return status;
3262    }
3263    if ((mType == OFFLOAD || mType == DIRECT)
3264            && mOutput != NULL && mOutput->stream->get_presentation_position) {
3265        uint64_t position64;
3266        int ret = mOutput->getPresentationPosition(&position64, &timestamp.mTime);
3267        if (ret == 0) {
3268            timestamp.mPosition = (uint32_t)position64;
3269            return NO_ERROR;
3270        }
3271    }
3272    return INVALID_OPERATION;
3273}
3274
3275status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3276                                                          audio_patch_handle_t *handle)
3277{
3278    AutoPark<FastMixer> park(mFastMixer);
3279
3280    status_t status = PlaybackThread::createAudioPatch_l(patch, handle);
3281
3282    return status;
3283}
3284
3285status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3286                                                          audio_patch_handle_t *handle)
3287{
3288    status_t status = NO_ERROR;
3289
3290    // store new device and send to effects
3291    audio_devices_t type = AUDIO_DEVICE_NONE;
3292    for (unsigned int i = 0; i < patch->num_sinks; i++) {
3293        type |= patch->sinks[i].ext.device.type;
3294    }
3295
3296#ifdef ADD_BATTERY_DATA
3297    // when changing the audio output device, call addBatteryData to notify
3298    // the change
3299    if (mOutDevice != type) {
3300        uint32_t params = 0;
3301        // check whether speaker is on
3302        if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3303            params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3304        }
3305
3306        audio_devices_t deviceWithoutSpeaker
3307            = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3308        // check if any other device (except speaker) is on
3309        if (type & deviceWithoutSpeaker) {
3310            params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3311        }
3312
3313        if (params != 0) {
3314            addBatteryData(params);
3315        }
3316    }
3317#endif
3318
3319    for (size_t i = 0; i < mEffectChains.size(); i++) {
3320        mEffectChains[i]->setDevice_l(type);
3321    }
3322
3323    // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3324    // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3325    bool configChanged = mPrevOutDevice != type;
3326    mOutDevice = type;
3327    mPatch = *patch;
3328
3329    if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
3330        audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3331        status = hwDevice->create_audio_patch(hwDevice,
3332                                               patch->num_sources,
3333                                               patch->sources,
3334                                               patch->num_sinks,
3335                                               patch->sinks,
3336                                               handle);
3337    } else {
3338        char *address;
3339        if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3340            //FIXME: we only support address on first sink with HAL version < 3.0
3341            address = audio_device_address_to_parameter(
3342                                                        patch->sinks[0].ext.device.type,
3343                                                        patch->sinks[0].ext.device.address);
3344        } else {
3345            address = (char *)calloc(1, 1);
3346        }
3347        AudioParameter param = AudioParameter(String8(address));
3348        free(address);
3349        param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), (int)type);
3350        status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3351                param.toString().string());
3352        *handle = AUDIO_PATCH_HANDLE_NONE;
3353    }
3354    if (configChanged) {
3355        mPrevOutDevice = type;
3356        sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3357    }
3358    return status;
3359}
3360
3361status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3362{
3363    AutoPark<FastMixer> park(mFastMixer);
3364
3365    status_t status = PlaybackThread::releaseAudioPatch_l(handle);
3366
3367    return status;
3368}
3369
3370status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3371{
3372    status_t status = NO_ERROR;
3373
3374    mOutDevice = AUDIO_DEVICE_NONE;
3375
3376    if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
3377        audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3378        status = hwDevice->release_audio_patch(hwDevice, handle);
3379    } else {
3380        AudioParameter param;
3381        param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
3382        status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3383                param.toString().string());
3384    }
3385    return status;
3386}
3387
3388void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3389{
3390    Mutex::Autolock _l(mLock);
3391    mTracks.add(track);
3392}
3393
3394void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3395{
3396    Mutex::Autolock _l(mLock);
3397    destroyTrack_l(track);
3398}
3399
3400void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3401{
3402    ThreadBase::getAudioPortConfig(config);
3403    config->role = AUDIO_PORT_ROLE_SOURCE;
3404    config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3405    config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3406}
3407
3408// ----------------------------------------------------------------------------
3409
3410AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
3411        audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3412    :   PlaybackThread(audioFlinger, output, id, device, type, systemReady),
3413        // mAudioMixer below
3414        // mFastMixer below
3415        mFastMixerFutex(0),
3416        mMasterMono(false)
3417        // mOutputSink below
3418        // mPipeSink below
3419        // mNormalSink below
3420{
3421    ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
3422    ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%zu, "
3423            "mFrameCount=%zu, mNormalFrameCount=%zu",
3424            mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3425            mNormalFrameCount);
3426    mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3427
3428    if (type == DUPLICATING) {
3429        // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3430        // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3431        // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3432        return;
3433    }
3434    // create an NBAIO sink for the HAL output stream, and negotiate
3435    mOutputSink = new AudioStreamOutSink(output->stream);
3436    size_t numCounterOffers = 0;
3437    const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
3438#if !LOG_NDEBUG
3439    ssize_t index =
3440#else
3441    (void)
3442#endif
3443            mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
3444    ALOG_ASSERT(index == 0);
3445
3446    // initialize fast mixer depending on configuration
3447    bool initFastMixer;
3448    switch (kUseFastMixer) {
3449    case FastMixer_Never:
3450        initFastMixer = false;
3451        break;
3452    case FastMixer_Always:
3453        initFastMixer = true;
3454        break;
3455    case FastMixer_Static:
3456    case FastMixer_Dynamic:
3457        initFastMixer = mFrameCount < mNormalFrameCount;
3458        break;
3459    }
3460    if (initFastMixer) {
3461        audio_format_t fastMixerFormat;
3462        if (mMixerBufferEnabled && mEffectBufferEnabled) {
3463            fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3464        } else {
3465            fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3466        }
3467        if (mFormat != fastMixerFormat) {
3468            // change our Sink format to accept our intermediate precision
3469            mFormat = fastMixerFormat;
3470            free(mSinkBuffer);
3471            mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3472            const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3473            (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3474        }
3475
3476        // create a MonoPipe to connect our submix to FastMixer
3477        NBAIO_Format format = mOutputSink->format();
3478#ifdef TEE_SINK
3479        NBAIO_Format origformat = format;
3480#endif
3481        // adjust format to match that of the Fast Mixer
3482        ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
3483        format.mFormat = fastMixerFormat;
3484        format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3485
3486        // This pipe depth compensates for scheduling latency of the normal mixer thread.
3487        // When it wakes up after a maximum latency, it runs a few cycles quickly before
3488        // finally blocking.  Note the pipe implementation rounds up the request to a power of 2.
3489        MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3490        const NBAIO_Format offers[1] = {format};
3491        size_t numCounterOffers = 0;
3492#if !LOG_NDEBUG
3493        ssize_t index =
3494#else
3495        (void)
3496#endif
3497                monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
3498        ALOG_ASSERT(index == 0);
3499        monoPipe->setAvgFrames((mScreenState & 1) ?
3500                (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3501        mPipeSink = monoPipe;
3502
3503#ifdef TEE_SINK
3504        if (mTeeSinkOutputEnabled) {
3505            // create a Pipe to archive a copy of FastMixer's output for dumpsys
3506            Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3507            const NBAIO_Format offers2[1] = {origformat};
3508            numCounterOffers = 0;
3509            index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
3510            ALOG_ASSERT(index == 0);
3511            mTeeSink = teeSink;
3512            PipeReader *teeSource = new PipeReader(*teeSink);
3513            numCounterOffers = 0;
3514            index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
3515            ALOG_ASSERT(index == 0);
3516            mTeeSource = teeSource;
3517        }
3518#endif
3519
3520        // create fast mixer and configure it initially with just one fast track for our submix
3521        mFastMixer = new FastMixer();
3522        FastMixerStateQueue *sq = mFastMixer->sq();
3523#ifdef STATE_QUEUE_DUMP
3524        sq->setObserverDump(&mStateQueueObserverDump);
3525        sq->setMutatorDump(&mStateQueueMutatorDump);
3526#endif
3527        FastMixerState *state = sq->begin();
3528        FastTrack *fastTrack = &state->mFastTracks[0];
3529        // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3530        fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3531        fastTrack->mVolumeProvider = NULL;
3532        fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3533        fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
3534        fastTrack->mGeneration++;
3535        state->mFastTracksGen++;
3536        state->mTrackMask = 1;
3537        // fast mixer will use the HAL output sink
3538        state->mOutputSink = mOutputSink.get();
3539        state->mOutputSinkGen++;
3540        state->mFrameCount = mFrameCount;
3541        state->mCommand = FastMixerState::COLD_IDLE;
3542        // already done in constructor initialization list
3543        //mFastMixerFutex = 0;
3544        state->mColdFutexAddr = &mFastMixerFutex;
3545        state->mColdGen++;
3546        state->mDumpState = &mFastMixerDumpState;
3547#ifdef TEE_SINK
3548        state->mTeeSink = mTeeSink.get();
3549#endif
3550        mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3551        state->mNBLogWriter = mFastMixerNBLogWriter.get();
3552        sq->end();
3553        sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3554
3555        // start the fast mixer
3556        mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3557        pid_t tid = mFastMixer->getTid();
3558        sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
3559
3560#ifdef AUDIO_WATCHDOG
3561        // create and start the watchdog
3562        mAudioWatchdog = new AudioWatchdog();
3563        mAudioWatchdog->setDump(&mAudioWatchdogDump);
3564        mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3565        tid = mAudioWatchdog->getTid();
3566        sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
3567#endif
3568
3569    }
3570
3571    switch (kUseFastMixer) {
3572    case FastMixer_Never:
3573    case FastMixer_Dynamic:
3574        mNormalSink = mOutputSink;
3575        break;
3576    case FastMixer_Always:
3577        mNormalSink = mPipeSink;
3578        break;
3579    case FastMixer_Static:
3580        mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3581        break;
3582    }
3583}
3584
3585AudioFlinger::MixerThread::~MixerThread()
3586{
3587    if (mFastMixer != 0) {
3588        FastMixerStateQueue *sq = mFastMixer->sq();
3589        FastMixerState *state = sq->begin();
3590        if (state->mCommand == FastMixerState::COLD_IDLE) {
3591            int32_t old = android_atomic_inc(&mFastMixerFutex);
3592            if (old == -1) {
3593                (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
3594            }
3595        }
3596        state->mCommand = FastMixerState::EXIT;
3597        sq->end();
3598        sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3599        mFastMixer->join();
3600        // Though the fast mixer thread has exited, it's state queue is still valid.
3601        // We'll use that extract the final state which contains one remaining fast track
3602        // corresponding to our sub-mix.
3603        state = sq->begin();
3604        ALOG_ASSERT(state->mTrackMask == 1);
3605        FastTrack *fastTrack = &state->mFastTracks[0];
3606        ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3607        delete fastTrack->mBufferProvider;
3608        sq->end(false /*didModify*/);
3609        mFastMixer.clear();
3610#ifdef AUDIO_WATCHDOG
3611        if (mAudioWatchdog != 0) {
3612            mAudioWatchdog->requestExit();
3613            mAudioWatchdog->requestExitAndWait();
3614            mAudioWatchdog.clear();
3615        }
3616#endif
3617    }
3618    mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
3619    delete mAudioMixer;
3620}
3621
3622
3623uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3624{
3625    if (mFastMixer != 0) {
3626        MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3627        latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3628    }
3629    return latency;
3630}
3631
3632
3633void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3634{
3635    PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3636}
3637
3638ssize_t AudioFlinger::MixerThread::threadLoop_write()
3639{
3640    // FIXME we should only do one push per cycle; confirm this is true
3641    // Start the fast mixer if it's not already running
3642    if (mFastMixer != 0) {
3643        FastMixerStateQueue *sq = mFastMixer->sq();
3644        FastMixerState *state = sq->begin();
3645        if (state->mCommand != FastMixerState::MIX_WRITE &&
3646                (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3647            if (state->mCommand == FastMixerState::COLD_IDLE) {
3648
3649                // FIXME workaround for first HAL write being CPU bound on some devices
3650                ATRACE_BEGIN("write");
3651                mOutput->write((char *)mSinkBuffer, 0);
3652                ATRACE_END();
3653
3654                int32_t old = android_atomic_inc(&mFastMixerFutex);
3655                if (old == -1) {
3656                    (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
3657                }
3658#ifdef AUDIO_WATCHDOG
3659                if (mAudioWatchdog != 0) {
3660                    mAudioWatchdog->resume();
3661                }
3662#endif
3663            }
3664            state->mCommand = FastMixerState::MIX_WRITE;
3665#ifdef FAST_THREAD_STATISTICS
3666            mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
3667                FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
3668#endif
3669            sq->end();
3670            sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3671            if (kUseFastMixer == FastMixer_Dynamic) {
3672                mNormalSink = mPipeSink;
3673            }
3674        } else {
3675            sq->end(false /*didModify*/);
3676        }
3677    }
3678    return PlaybackThread::threadLoop_write();
3679}
3680
3681void AudioFlinger::MixerThread::threadLoop_standby()
3682{
3683    // Idle the fast mixer if it's currently running
3684    if (mFastMixer != 0) {
3685        FastMixerStateQueue *sq = mFastMixer->sq();
3686        FastMixerState *state = sq->begin();
3687        if (!(state->mCommand & FastMixerState::IDLE)) {
3688            state->mCommand = FastMixerState::COLD_IDLE;
3689            state->mColdFutexAddr = &mFastMixerFutex;
3690            state->mColdGen++;
3691            mFastMixerFutex = 0;
3692            sq->end();
3693            // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3694            sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3695            if (kUseFastMixer == FastMixer_Dynamic) {
3696                mNormalSink = mOutputSink;
3697            }
3698#ifdef AUDIO_WATCHDOG
3699            if (mAudioWatchdog != 0) {
3700                mAudioWatchdog->pause();
3701            }
3702#endif
3703        } else {
3704            sq->end(false /*didModify*/);
3705        }
3706    }
3707    PlaybackThread::threadLoop_standby();
3708}
3709
3710bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3711{
3712    return false;
3713}
3714
3715bool AudioFlinger::PlaybackThread::shouldStandby_l()
3716{
3717    return !mStandby;
3718}
3719
3720bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3721{
3722    Mutex::Autolock _l(mLock);
3723    return waitingAsyncCallback_l();
3724}
3725
3726// shared by MIXER and DIRECT, overridden by DUPLICATING
3727void AudioFlinger::PlaybackThread::threadLoop_standby()
3728{
3729    ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
3730    mOutput->standby();
3731    if (mUseAsyncWrite != 0) {
3732        // discard any pending drain or write ack by incrementing sequence
3733        mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3734        mDrainSequence = (mDrainSequence + 2) & ~1;
3735        ALOG_ASSERT(mCallbackThread != 0);
3736        mCallbackThread->setWriteBlocked(mWriteAckSequence);
3737        mCallbackThread->setDraining(mDrainSequence);
3738    }
3739    mHwPaused = false;
3740}
3741
3742void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3743{
3744    ALOGV("signal playback thread");
3745    broadcast_l();
3746}
3747
3748void AudioFlinger::MixerThread::threadLoop_mix()
3749{
3750    // mix buffers...
3751    mAudioMixer->process();
3752    mCurrentWriteLength = mSinkBufferSize;
3753    // increase sleep time progressively when application underrun condition clears.
3754    // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3755    // that a steady state of alternating ready/not ready conditions keeps the sleep time
3756    // such that we would underrun the audio HAL.
3757    if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
3758        sleepTimeShift--;
3759    }
3760    mSleepTimeUs = 0;
3761    mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3762    //TODO: delay standby when effects have a tail
3763
3764}
3765
3766void AudioFlinger::MixerThread::threadLoop_sleepTime()
3767{
3768    // If no tracks are ready, sleep once for the duration of an output
3769    // buffer size, then write 0s to the output
3770    if (mSleepTimeUs == 0) {
3771        if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3772            mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3773            if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3774                mSleepTimeUs = kMinThreadSleepTimeUs;
3775            }
3776            // reduce sleep time in case of consecutive application underruns to avoid
3777            // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3778            // duration we would end up writing less data than needed by the audio HAL if
3779            // the condition persists.
3780            if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3781                sleepTimeShift++;
3782            }
3783        } else {
3784            mSleepTimeUs = mIdleSleepTimeUs;
3785        }
3786    } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
3787        // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3788        // before effects processing or output.
3789        if (mMixerBufferValid) {
3790            memset(mMixerBuffer, 0, mMixerBufferSize);
3791        } else {
3792            memset(mSinkBuffer, 0, mSinkBufferSize);
3793        }
3794        mSleepTimeUs = 0;
3795        ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3796                "anticipated start");
3797    }
3798    // TODO add standby time extension fct of effect tail
3799}
3800
3801// prepareTracks_l() must be called with ThreadBase::mLock held
3802AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3803        Vector< sp<Track> > *tracksToRemove)
3804{
3805
3806    mixer_state mixerStatus = MIXER_IDLE;
3807    // find out which tracks need to be processed
3808    size_t count = mActiveTracks.size();
3809    size_t mixedTracks = 0;
3810    size_t tracksWithEffect = 0;
3811    // counts only _active_ fast tracks
3812    size_t fastTracks = 0;
3813    uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3814
3815    float masterVolume = mMasterVolume;
3816    bool masterMute = mMasterMute;
3817
3818    if (masterMute) {
3819        masterVolume = 0;
3820    }
3821    // Delegate master volume control to effect in output mix effect chain if needed
3822    sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3823    if (chain != 0) {
3824        uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3825        chain->setVolume_l(&v, &v);
3826        masterVolume = (float)((v + (1 << 23)) >> 24);
3827        chain.clear();
3828    }
3829
3830    // prepare a new state to push
3831    FastMixerStateQueue *sq = NULL;
3832    FastMixerState *state = NULL;
3833    bool didModify = false;
3834    FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
3835    if (mFastMixer != 0) {
3836        sq = mFastMixer->sq();
3837        state = sq->begin();
3838    }
3839
3840    mMixerBufferValid = false;  // mMixerBuffer has no valid data until appropriate tracks found.
3841    mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
3842
3843    for (size_t i=0 ; i<count ; i++) {
3844        const sp<Track> t = mActiveTracks[i].promote();
3845        if (t == 0) {
3846            continue;
3847        }
3848
3849        // this const just means the local variable doesn't change
3850        Track* const track = t.get();
3851
3852        // process fast tracks
3853        if (track->isFastTrack()) {
3854
3855            // It's theoretically possible (though unlikely) for a fast track to be created
3856            // and then removed within the same normal mix cycle.  This is not a problem, as
3857            // the track never becomes active so it's fast mixer slot is never touched.
3858            // The converse, of removing an (active) track and then creating a new track
3859            // at the identical fast mixer slot within the same normal mix cycle,
3860            // is impossible because the slot isn't marked available until the end of each cycle.
3861            int j = track->mFastIndex;
3862            ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3863            ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3864            FastTrack *fastTrack = &state->mFastTracks[j];
3865
3866            // Determine whether the track is currently in underrun condition,
3867            // and whether it had a recent underrun.
3868            FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3869            FastTrackUnderruns underruns = ftDump->mUnderruns;
3870            uint32_t recentFull = (underruns.mBitFields.mFull -
3871                    track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3872            uint32_t recentPartial = (underruns.mBitFields.mPartial -
3873                    track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3874            uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3875                    track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3876            uint32_t recentUnderruns = recentPartial + recentEmpty;
3877            track->mObservedUnderruns = underruns;
3878            // don't count underruns that occur while stopping or pausing
3879            // or stopped which can occur when flush() is called while active
3880            if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3881                    recentUnderruns > 0) {
3882                // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3883                track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
3884            } else {
3885                track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
3886            }
3887
3888            // This is similar to the state machine for normal tracks,
3889            // with a few modifications for fast tracks.
3890            bool isActive = true;
3891            switch (track->mState) {
3892            case TrackBase::STOPPING_1:
3893                // track stays active in STOPPING_1 state until first underrun
3894                if (recentUnderruns > 0 || track->isTerminated()) {
3895                    track->mState = TrackBase::STOPPING_2;
3896                }
3897                break;
3898            case TrackBase::PAUSING:
3899                // ramp down is not yet implemented
3900                track->setPaused();
3901                break;
3902            case TrackBase::RESUMING:
3903                // ramp up is not yet implemented
3904                track->mState = TrackBase::ACTIVE;
3905                break;
3906            case TrackBase::ACTIVE:
3907                if (recentFull > 0 || recentPartial > 0) {
3908                    // track has provided at least some frames recently: reset retry count
3909                    track->mRetryCount = kMaxTrackRetries;
3910                }
3911                if (recentUnderruns == 0) {
3912                    // no recent underruns: stay active
3913                    break;
3914                }
3915                // there has recently been an underrun of some kind
3916                if (track->sharedBuffer() == 0) {
3917                    // were any of the recent underruns "empty" (no frames available)?
3918                    if (recentEmpty == 0) {
3919                        // no, then ignore the partial underruns as they are allowed indefinitely
3920                        break;
3921                    }
3922                    // there has recently been an "empty" underrun: decrement the retry counter
3923                    if (--(track->mRetryCount) > 0) {
3924                        break;
3925                    }
3926                    // indicate to client process that the track was disabled because of underrun;
3927                    // it will then automatically call start() when data is available
3928                    track->disable();
3929                    // remove from active list, but state remains ACTIVE [confusing but true]
3930                    isActive = false;
3931                    break;
3932                }
3933                // fall through
3934            case TrackBase::STOPPING_2:
3935            case TrackBase::PAUSED:
3936            case TrackBase::STOPPED:
3937            case TrackBase::FLUSHED:   // flush() while active
3938                // Check for presentation complete if track is inactive
3939                // We have consumed all the buffers of this track.
3940                // This would be incomplete if we auto-paused on underrun
3941                {
3942                    size_t audioHALFrames =
3943                            (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3944                    int64_t framesWritten = mBytesWritten / mFrameSize;
3945                    if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3946                        // track stays in active list until presentation is complete
3947                        break;
3948                    }
3949                }
3950                if (track->isStopping_2()) {
3951                    track->mState = TrackBase::STOPPED;
3952                }
3953                if (track->isStopped()) {
3954                    // Can't reset directly, as fast mixer is still polling this track
3955                    //   track->reset();
3956                    // So instead mark this track as needing to be reset after push with ack
3957                    resetMask |= 1 << i;
3958                }
3959                isActive = false;
3960                break;
3961            case TrackBase::IDLE:
3962            default:
3963                LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
3964            }
3965
3966            if (isActive) {
3967                // was it previously inactive?
3968                if (!(state->mTrackMask & (1 << j))) {
3969                    ExtendedAudioBufferProvider *eabp = track;
3970                    VolumeProvider *vp = track;
3971                    fastTrack->mBufferProvider = eabp;
3972                    fastTrack->mVolumeProvider = vp;
3973                    fastTrack->mChannelMask = track->mChannelMask;
3974                    fastTrack->mFormat = track->mFormat;
3975                    fastTrack->mGeneration++;
3976                    state->mTrackMask |= 1 << j;
3977                    didModify = true;
3978                    // no acknowledgement required for newly active tracks
3979                }
3980                // cache the combined master volume and stream type volume for fast mixer; this
3981                // lacks any synchronization or barrier so VolumeProvider may read a stale value
3982                track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
3983                ++fastTracks;
3984            } else {
3985                // was it previously active?
3986                if (state->mTrackMask & (1 << j)) {
3987                    fastTrack->mBufferProvider = NULL;
3988                    fastTrack->mGeneration++;
3989                    state->mTrackMask &= ~(1 << j);
3990                    didModify = true;
3991                    // If any fast tracks were removed, we must wait for acknowledgement
3992                    // because we're about to decrement the last sp<> on those tracks.
3993                    block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3994                } else {
3995                    LOG_ALWAYS_FATAL("fast track %d should have been active; "
3996                            "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
3997                            j, track->mState, state->mTrackMask, recentUnderruns,
3998                            track->sharedBuffer() != 0);
3999                }
4000                tracksToRemove->add(track);
4001                // Avoids a misleading display in dumpsys
4002                track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4003            }
4004            continue;
4005        }
4006
4007        {   // local variable scope to avoid goto warning
4008
4009        audio_track_cblk_t* cblk = track->cblk();
4010
4011        // The first time a track is added we wait
4012        // for all its buffers to be filled before processing it
4013        int name = track->name();
4014        // make sure that we have enough frames to mix one full buffer.
4015        // enforce this condition only once to enable draining the buffer in case the client
4016        // app does not call stop() and relies on underrun to stop:
4017        // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4018        // during last round
4019        size_t desiredFrames;
4020        const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
4021        AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
4022
4023        desiredFrames = sourceFramesNeededWithTimestretch(
4024                sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
4025        // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4026        // add frames already consumed but not yet released by the resampler
4027        // because mAudioTrackServerProxy->framesReady() will include these frames
4028        desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4029
4030        uint32_t minFrames = 1;
4031        if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4032                (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
4033            minFrames = desiredFrames;
4034        }
4035
4036        size_t framesReady = track->framesReady();
4037        if (ATRACE_ENABLED()) {
4038            // I wish we had formatted trace names
4039            char traceName[16];
4040            strcpy(traceName, "nRdy");
4041            int name = track->name();
4042            if (AudioMixer::TRACK0 <= name &&
4043                    name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
4044                name -= AudioMixer::TRACK0;
4045                traceName[4] = (name / 10) + '0';
4046                traceName[5] = (name % 10) + '0';
4047            } else {
4048                traceName[4] = '?';
4049                traceName[5] = '?';
4050            }
4051            traceName[6] = '\0';
4052            ATRACE_INT(traceName, framesReady);
4053        }
4054        if ((framesReady >= minFrames) && track->isReady() &&
4055                !track->isPaused() && !track->isTerminated())
4056        {
4057            ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
4058
4059            mixedTracks++;
4060
4061            // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4062            // there is an effect chain connected to the track
4063            chain.clear();
4064            if (track->mainBuffer() != mSinkBuffer &&
4065                    track->mainBuffer() != mMixerBuffer) {
4066                if (mEffectBufferEnabled) {
4067                    mEffectBufferValid = true; // Later can set directly.
4068                }
4069                chain = getEffectChain_l(track->sessionId());
4070                // Delegate volume control to effect in track effect chain if needed
4071                if (chain != 0) {
4072                    tracksWithEffect++;
4073                } else {
4074                    ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4075                            "session %d",
4076                            name, track->sessionId());
4077                }
4078            }
4079
4080
4081            int param = AudioMixer::VOLUME;
4082            if (track->mFillingUpStatus == Track::FS_FILLED) {
4083                // no ramp for the first volume setting
4084                track->mFillingUpStatus = Track::FS_ACTIVE;
4085                if (track->mState == TrackBase::RESUMING) {
4086                    track->mState = TrackBase::ACTIVE;
4087                    param = AudioMixer::RAMP_VOLUME;
4088                }
4089                mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
4090            // FIXME should not make a decision based on mServer
4091            } else if (cblk->mServer != 0) {
4092                // If the track is stopped before the first frame was mixed,
4093                // do not apply ramp
4094                param = AudioMixer::RAMP_VOLUME;
4095            }
4096
4097            // compute volume for this track
4098            uint32_t vl, vr;       // in U8.24 integer format
4099            float vlf, vrf, vaf;   // in [0.0, 1.0] float format
4100            if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
4101                vl = vr = 0;
4102                vlf = vrf = vaf = 0.;
4103                if (track->isPausing()) {
4104                    track->setPaused();
4105                }
4106            } else {
4107
4108                // read original volumes with volume control
4109                float typeVolume = mStreamTypes[track->streamType()].volume;
4110                float v = masterVolume * typeVolume;
4111                AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
4112                gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4113                vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4114                vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
4115                // track volumes come from shared memory, so can't be trusted and must be clamped
4116                if (vlf > GAIN_FLOAT_UNITY) {
4117                    ALOGV("Track left volume out of range: %.3g", vlf);
4118                    vlf = GAIN_FLOAT_UNITY;
4119                }
4120                if (vrf > GAIN_FLOAT_UNITY) {
4121                    ALOGV("Track right volume out of range: %.3g", vrf);
4122                    vrf = GAIN_FLOAT_UNITY;
4123                }
4124                // now apply the master volume and stream type volume
4125                vlf *= v;
4126                vrf *= v;
4127                // assuming master volume and stream type volume each go up to 1.0,
4128                // then derive vl and vr as U8.24 versions for the effect chain
4129                const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4130                vl = (uint32_t) (scaleto8_24 * vlf);
4131                vr = (uint32_t) (scaleto8_24 * vrf);
4132                // vl and vr are now in U8.24 format
4133                uint16_t sendLevel = proxy->getSendLevel_U4_12();
4134                // send level comes from shared memory and so may be corrupt
4135                if (sendLevel > MAX_GAIN_INT) {
4136                    ALOGV("Track send level out of range: %04X", sendLevel);
4137                    sendLevel = MAX_GAIN_INT;
4138                }
4139                // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4140                vaf = v * sendLevel * (1. / MAX_GAIN_INT);
4141            }
4142
4143            // Delegate volume control to effect in track effect chain if needed
4144            if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4145                // Do not ramp volume if volume is controlled by effect
4146                param = AudioMixer::VOLUME;
4147                // Update remaining floating point volume levels
4148                vlf = (float)vl / (1 << 24);
4149                vrf = (float)vr / (1 << 24);
4150                track->mHasVolumeController = true;
4151            } else {
4152                // force no volume ramp when volume controller was just disabled or removed
4153                // from effect chain to avoid volume spike
4154                if (track->mHasVolumeController) {
4155                    param = AudioMixer::VOLUME;
4156                }
4157                track->mHasVolumeController = false;
4158            }
4159
4160            // XXX: these things DON'T need to be done each time
4161            mAudioMixer->setBufferProvider(name, track);
4162            mAudioMixer->enable(name);
4163
4164            mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4165            mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4166            mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
4167            mAudioMixer->setParameter(
4168                name,
4169                AudioMixer::TRACK,
4170                AudioMixer::FORMAT, (void *)track->format());
4171            mAudioMixer->setParameter(
4172                name,
4173                AudioMixer::TRACK,
4174                AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
4175            mAudioMixer->setParameter(
4176                name,
4177                AudioMixer::TRACK,
4178                AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
4179            // limit track sample rate to 2 x output sample rate, which changes at re-configuration
4180            uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
4181            uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
4182            if (reqSampleRate == 0) {
4183                reqSampleRate = mSampleRate;
4184            } else if (reqSampleRate > maxSampleRate) {
4185                reqSampleRate = maxSampleRate;
4186            }
4187            mAudioMixer->setParameter(
4188                name,
4189                AudioMixer::RESAMPLE,
4190                AudioMixer::SAMPLE_RATE,
4191                (void *)(uintptr_t)reqSampleRate);
4192
4193            AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
4194            mAudioMixer->setParameter(
4195                name,
4196                AudioMixer::TIMESTRETCH,
4197                AudioMixer::PLAYBACK_RATE,
4198                &playbackRate);
4199
4200            /*
4201             * Select the appropriate output buffer for the track.
4202             *
4203             * Tracks with effects go into their own effects chain buffer
4204             * and from there into either mEffectBuffer or mSinkBuffer.
4205             *
4206             * Other tracks can use mMixerBuffer for higher precision
4207             * channel accumulation.  If this buffer is enabled
4208             * (mMixerBufferEnabled true), then selected tracks will accumulate
4209             * into it.
4210             *
4211             */
4212            if (mMixerBufferEnabled
4213                    && (track->mainBuffer() == mSinkBuffer
4214                            || track->mainBuffer() == mMixerBuffer)) {
4215                mAudioMixer->setParameter(
4216                        name,
4217                        AudioMixer::TRACK,
4218                        AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
4219                mAudioMixer->setParameter(
4220                        name,
4221                        AudioMixer::TRACK,
4222                        AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4223                // TODO: override track->mainBuffer()?
4224                mMixerBufferValid = true;
4225            } else {
4226                mAudioMixer->setParameter(
4227                        name,
4228                        AudioMixer::TRACK,
4229                        AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
4230                mAudioMixer->setParameter(
4231                        name,
4232                        AudioMixer::TRACK,
4233                        AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4234            }
4235            mAudioMixer->setParameter(
4236                name,
4237                AudioMixer::TRACK,
4238                AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4239
4240            // reset retry count
4241            track->mRetryCount = kMaxTrackRetries;
4242
4243            // If one track is ready, set the mixer ready if:
4244            //  - the mixer was not ready during previous round OR
4245            //  - no other track is not ready
4246            if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4247                    mixerStatus != MIXER_TRACKS_ENABLED) {
4248                mixerStatus = MIXER_TRACKS_READY;
4249            }
4250        } else {
4251            if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
4252                ALOGV("track(%p) underrun,  framesReady(%zu) < framesDesired(%zd)",
4253                        track, framesReady, desiredFrames);
4254                track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
4255            } else {
4256                track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
4257            }
4258
4259            // clear effect chain input buffer if an active track underruns to avoid sending
4260            // previous audio buffer again to effects
4261            chain = getEffectChain_l(track->sessionId());
4262            if (chain != 0) {
4263                chain->clearInputBuffer();
4264            }
4265
4266            ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
4267            if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4268                    track->isStopped() || track->isPaused()) {
4269                // We have consumed all the buffers of this track.
4270                // Remove it from the list of active tracks.
4271                // TODO: use actual buffer filling status instead of latency when available from
4272                // audio HAL
4273                size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
4274                int64_t framesWritten = mBytesWritten / mFrameSize;
4275                if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4276                    if (track->isStopped()) {
4277                        track->reset();
4278                    }
4279                    tracksToRemove->add(track);
4280                }
4281            } else {
4282                // No buffers for this track. Give it a few chances to
4283                // fill a buffer, then remove it from active list.
4284                if (--(track->mRetryCount) <= 0) {
4285                    ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
4286                    tracksToRemove->add(track);
4287                    // indicate to client process that the track was disabled because of underrun;
4288                    // it will then automatically call start() when data is available
4289                    track->disable();
4290                // If one track is not ready, mark the mixer also not ready if:
4291                //  - the mixer was ready during previous round OR
4292                //  - no other track is ready
4293                } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4294                                mixerStatus != MIXER_TRACKS_READY) {
4295                    mixerStatus = MIXER_TRACKS_ENABLED;
4296                }
4297            }
4298            mAudioMixer->disable(name);
4299        }
4300
4301        }   // local variable scope to avoid goto warning
4302
4303    }
4304
4305    // Push the new FastMixer state if necessary
4306    bool pauseAudioWatchdog = false;
4307    if (didModify) {
4308        state->mFastTracksGen++;
4309        // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4310        if (kUseFastMixer == FastMixer_Dynamic &&
4311                state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4312            state->mCommand = FastMixerState::COLD_IDLE;
4313            state->mColdFutexAddr = &mFastMixerFutex;
4314            state->mColdGen++;
4315            mFastMixerFutex = 0;
4316            if (kUseFastMixer == FastMixer_Dynamic) {
4317                mNormalSink = mOutputSink;
4318            }
4319            // If we go into cold idle, need to wait for acknowledgement
4320            // so that fast mixer stops doing I/O.
4321            block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4322            pauseAudioWatchdog = true;
4323        }
4324    }
4325    if (sq != NULL) {
4326        sq->end(didModify);
4327        sq->push(block);
4328    }
4329#ifdef AUDIO_WATCHDOG
4330    if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4331        mAudioWatchdog->pause();
4332    }
4333#endif
4334
4335    // Now perform the deferred reset on fast tracks that have stopped
4336    while (resetMask != 0) {
4337        size_t i = __builtin_ctz(resetMask);
4338        ALOG_ASSERT(i < count);
4339        resetMask &= ~(1 << i);
4340        sp<Track> t = mActiveTracks[i].promote();
4341        if (t == 0) {
4342            continue;
4343        }
4344        Track* track = t.get();
4345        ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4346        track->reset();
4347    }
4348
4349    // remove all the tracks that need to be...
4350    removeTracks_l(*tracksToRemove);
4351
4352    if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4353        mEffectBufferValid = true;
4354    }
4355
4356    if (mEffectBufferValid) {
4357        // as long as there are effects we should clear the effects buffer, to avoid
4358        // passing a non-clean buffer to the effect chain
4359        memset(mEffectBuffer, 0, mEffectBufferSize);
4360    }
4361    // sink or mix buffer must be cleared if all tracks are connected to an
4362    // effect chain as in this case the mixer will not write to the sink or mix buffer
4363    // and track effects will accumulate into it
4364    if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4365            (mixedTracks == 0 && fastTracks > 0))) {
4366        // FIXME as a performance optimization, should remember previous zero status
4367        if (mMixerBufferValid) {
4368            memset(mMixerBuffer, 0, mMixerBufferSize);
4369            // TODO: In testing, mSinkBuffer below need not be cleared because
4370            // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4371            // after mixing.
4372            //
4373            // To enforce this guarantee:
4374            // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4375            // (mixedTracks == 0 && fastTracks > 0))
4376            // must imply MIXER_TRACKS_READY.
4377            // Later, we may clear buffers regardless, and skip much of this logic.
4378        }
4379        // FIXME as a performance optimization, should remember previous zero status
4380        memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
4381    }
4382
4383    // if any fast tracks, then status is ready
4384    mMixerStatusIgnoringFastTracks = mixerStatus;
4385    if (fastTracks > 0) {
4386        mixerStatus = MIXER_TRACKS_READY;
4387    }
4388    return mixerStatus;
4389}
4390
4391// getTrackName_l() must be called with ThreadBase::mLock held
4392int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
4393        audio_format_t format, audio_session_t sessionId)
4394{
4395    return mAudioMixer->getTrackName(channelMask, format, sessionId);
4396}
4397
4398// deleteTrackName_l() must be called with ThreadBase::mLock held
4399void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4400{
4401    ALOGV("remove track (%d) and delete from mixer", name);
4402    mAudioMixer->deleteTrackName(name);
4403}
4404
4405// checkForNewParameter_l() must be called with ThreadBase::mLock held
4406bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4407                                                       status_t& status)
4408{
4409    bool reconfig = false;
4410    bool a2dpDeviceChanged = false;
4411
4412    status = NO_ERROR;
4413
4414    AutoPark<FastMixer> park(mFastMixer);
4415
4416    AudioParameter param = AudioParameter(keyValuePair);
4417    int value;
4418    if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4419        reconfig = true;
4420    }
4421    if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
4422        if (!isValidPcmSinkFormat((audio_format_t) value)) {
4423            status = BAD_VALUE;
4424        } else {
4425            // no need to save value, since it's constant
4426            reconfig = true;
4427        }
4428    }
4429    if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
4430        if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
4431            status = BAD_VALUE;
4432        } else {
4433            // no need to save value, since it's constant
4434            reconfig = true;
4435        }
4436    }
4437    if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4438        // do not accept frame count changes if tracks are open as the track buffer
4439        // size depends on frame count and correct behavior would not be guaranteed
4440        // if frame count is changed after track creation
4441        if (!mTracks.isEmpty()) {
4442            status = INVALID_OPERATION;
4443        } else {
4444            reconfig = true;
4445        }
4446    }
4447    if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4448#ifdef ADD_BATTERY_DATA
4449        // when changing the audio output device, call addBatteryData to notify
4450        // the change
4451        if (mOutDevice != value) {
4452            uint32_t params = 0;
4453            // check whether speaker is on
4454            if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4455                params |= IMediaPlayerService::kBatteryDataSpeakerOn;
4456            }
4457
4458            audio_devices_t deviceWithoutSpeaker
4459                = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4460            // check if any other device (except speaker) is on
4461            if (value & deviceWithoutSpeaker) {
4462                params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4463            }
4464
4465            if (params != 0) {
4466                addBatteryData(params);
4467            }
4468        }
4469#endif
4470
4471        // forward device change to effects that have requested to be
4472        // aware of attached audio device.
4473        if (value != AUDIO_DEVICE_NONE) {
4474            a2dpDeviceChanged =
4475                    (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
4476            mOutDevice = value;
4477            for (size_t i = 0; i < mEffectChains.size(); i++) {
4478                mEffectChains[i]->setDevice_l(mOutDevice);
4479            }
4480        }
4481    }
4482
4483    if (status == NO_ERROR) {
4484        status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4485                                                keyValuePair.string());
4486        if (!mStandby && status == INVALID_OPERATION) {
4487            mOutput->standby();
4488            mStandby = true;
4489            mBytesWritten = 0;
4490            status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4491                                                   keyValuePair.string());
4492        }
4493        if (status == NO_ERROR && reconfig) {
4494            readOutputParameters_l();
4495            delete mAudioMixer;
4496            mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4497            for (size_t i = 0; i < mTracks.size() ; i++) {
4498                int name = getTrackName_l(mTracks[i]->mChannelMask,
4499                        mTracks[i]->mFormat, mTracks[i]->mSessionId);
4500                if (name < 0) {
4501                    break;
4502                }
4503                mTracks[i]->mName = name;
4504            }
4505            sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4506        }
4507    }
4508
4509    return reconfig || a2dpDeviceChanged;
4510}
4511
4512
4513void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4514{
4515    PlaybackThread::dumpInternals(fd, args);
4516    dprintf(fd, "  Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
4517    dprintf(fd, "  AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
4518    dprintf(fd, "  Master mono: %s\n", mMasterMono ? "on" : "off");
4519
4520    // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
4521    // while we are dumping it.  It may be inconsistent, but it won't mutate!
4522    // This is a large object so we place it on the heap.
4523    // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4524    const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4525    copy->dump(fd);
4526    delete copy;
4527
4528#ifdef STATE_QUEUE_DUMP
4529    // Similar for state queue
4530    StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4531    observerCopy.dump(fd);
4532    StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4533    mutatorCopy.dump(fd);
4534#endif
4535
4536#ifdef TEE_SINK
4537    // Write the tee output to a .wav file
4538    dumpTee(fd, mTeeSource, mId);
4539#endif
4540
4541#ifdef AUDIO_WATCHDOG
4542    if (mAudioWatchdog != 0) {
4543        // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4544        AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4545        wdCopy.dump(fd);
4546    }
4547#endif
4548}
4549
4550uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4551{
4552    return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4553}
4554
4555uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4556{
4557    return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4558}
4559
4560void AudioFlinger::MixerThread::cacheParameters_l()
4561{
4562    PlaybackThread::cacheParameters_l();
4563
4564    // FIXME: Relaxed timing because of a certain device that can't meet latency
4565    // Should be reduced to 2x after the vendor fixes the driver issue
4566    // increase threshold again due to low power audio mode. The way this warning
4567    // threshold is calculated and its usefulness should be reconsidered anyway.
4568    maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4569}
4570
4571// ----------------------------------------------------------------------------
4572
4573AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4574        AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady,
4575        uint32_t bitRate)
4576    :   PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady, bitRate)
4577        // mLeftVolFloat, mRightVolFloat
4578{
4579}
4580
4581AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4582        AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
4583        ThreadBase::type_t type, bool systemReady, uint32_t bitRate)
4584    :   PlaybackThread(audioFlinger, output, id, device, type, systemReady, bitRate)
4585        // mLeftVolFloat, mRightVolFloat
4586{
4587}
4588
4589AudioFlinger::DirectOutputThread::~DirectOutputThread()
4590{
4591}
4592
4593void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4594{
4595    float left, right;
4596
4597    if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4598        left = right = 0;
4599    } else {
4600        float typeVolume = mStreamTypes[track->streamType()].volume;
4601        float v = mMasterVolume * typeVolume;
4602        AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
4603        gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4604        left = float_from_gain(gain_minifloat_unpack_left(vlr));
4605        if (left > GAIN_FLOAT_UNITY) {
4606            left = GAIN_FLOAT_UNITY;
4607        }
4608        left *= v;
4609        right = float_from_gain(gain_minifloat_unpack_right(vlr));
4610        if (right > GAIN_FLOAT_UNITY) {
4611            right = GAIN_FLOAT_UNITY;
4612        }
4613        right *= v;
4614    }
4615
4616    if (lastTrack) {
4617        if (left != mLeftVolFloat || right != mRightVolFloat) {
4618            mLeftVolFloat = left;
4619            mRightVolFloat = right;
4620
4621            // Convert volumes from float to 8.24
4622            uint32_t vl = (uint32_t)(left * (1 << 24));
4623            uint32_t vr = (uint32_t)(right * (1 << 24));
4624
4625            // Delegate volume control to effect in track effect chain if needed
4626            // only one effect chain can be present on DirectOutputThread, so if
4627            // there is one, the track is connected to it
4628            if (!mEffectChains.isEmpty()) {
4629                mEffectChains[0]->setVolume_l(&vl, &vr);
4630                left = (float)vl / (1 << 24);
4631                right = (float)vr / (1 << 24);
4632            }
4633            if (mOutput->stream->set_volume) {
4634                mOutput->stream->set_volume(mOutput->stream, left, right);
4635            }
4636        }
4637    }
4638}
4639
4640void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4641{
4642    sp<Track> previousTrack = mPreviousTrack.promote();
4643    sp<Track> latestTrack = mLatestActiveTrack.promote();
4644
4645    if (previousTrack != 0 && latestTrack != 0) {
4646        if (mType == DIRECT) {
4647            if (previousTrack.get() != latestTrack.get()) {
4648                mFlushPending = true;
4649            }
4650        } else /* mType == OFFLOAD */ {
4651            if (previousTrack->sessionId() != latestTrack->sessionId()) {
4652                mFlushPending = true;
4653            }
4654        }
4655    }
4656    PlaybackThread::onAddNewTrack_l();
4657}
4658
4659AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4660    Vector< sp<Track> > *tracksToRemove
4661)
4662{
4663    size_t count = mActiveTracks.size();
4664    mixer_state mixerStatus = MIXER_IDLE;
4665    bool doHwPause = false;
4666    bool doHwResume = false;
4667
4668    // find out which tracks need to be processed
4669    for (size_t i = 0; i < count; i++) {
4670        sp<Track> t = mActiveTracks[i].promote();
4671        // The track died recently
4672        if (t == 0) {
4673            continue;
4674        }
4675
4676        if (t->isInvalid()) {
4677            ALOGW("An invalidated track shouldn't be in active list");
4678            tracksToRemove->add(t);
4679            continue;
4680        }
4681
4682        Track* const track = t.get();
4683#ifdef VERY_VERY_VERBOSE_LOGGING
4684        audio_track_cblk_t* cblk = track->cblk();
4685#endif
4686        // Only consider last track started for volume and mixer state control.
4687        // In theory an older track could underrun and restart after the new one starts
4688        // but as we only care about the transition phase between two tracks on a
4689        // direct output, it is not a problem to ignore the underrun case.
4690        sp<Track> l = mLatestActiveTrack.promote();
4691        bool last = l.get() == track;
4692
4693        if (track->isPausing()) {
4694            track->setPaused();
4695            if (mHwSupportsPause && last && !mHwPaused) {
4696                doHwPause = true;
4697                mHwPaused = true;
4698            }
4699            tracksToRemove->add(track);
4700        } else if (track->isFlushPending()) {
4701            track->flushAck();
4702            if (last) {
4703                mFlushPending = true;
4704            }
4705        } else if (track->isResumePending()) {
4706            track->resumeAck();
4707            if (last && mHwPaused) {
4708                doHwResume = true;
4709                mHwPaused = false;
4710            }
4711        }
4712
4713        // The first time a track is added we wait
4714        // for all its buffers to be filled before processing it.
4715        // Allow draining the buffer in case the client
4716        // app does not call stop() and relies on underrun to stop:
4717        // hence the test on (track->mRetryCount > 1).
4718        // If retryCount<=1 then track is about to underrun and be removed.
4719        // Do not use a high threshold for compressed audio.
4720        uint32_t minFrames;
4721        if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
4722            && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
4723            minFrames = mNormalFrameCount;
4724        } else {
4725            minFrames = 1;
4726        }
4727
4728        if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4729                !track->isStopping_2() && !track->isStopped())
4730        {
4731            ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
4732
4733            if (track->mFillingUpStatus == Track::FS_FILLED) {
4734                track->mFillingUpStatus = Track::FS_ACTIVE;
4735                // make sure processVolume_l() will apply new volume even if 0
4736                mLeftVolFloat = mRightVolFloat = -1.0;
4737                if (!mHwSupportsPause) {
4738                    track->resumeAck();
4739                }
4740            }
4741
4742            // compute volume for this track
4743            processVolume_l(track, last);
4744            if (last) {
4745                sp<Track> previousTrack = mPreviousTrack.promote();
4746                if (previousTrack != 0) {
4747                    if (track != previousTrack.get()) {
4748                        // Flush any data still being written from last track
4749                        mBytesRemaining = 0;
4750                        // Invalidate previous track to force a seek when resuming.
4751                        previousTrack->invalidate();
4752                    }
4753                }
4754                mPreviousTrack = track;
4755
4756                // reset retry count
4757                track->mRetryCount = kMaxTrackRetriesDirect;
4758                mActiveTrack = t;
4759                mixerStatus = MIXER_TRACKS_READY;
4760                if (mHwPaused) {
4761                    doHwResume = true;
4762                    mHwPaused = false;
4763                }
4764            }
4765        } else {
4766            // clear effect chain input buffer if the last active track started underruns
4767            // to avoid sending previous audio buffer again to effects
4768            if (!mEffectChains.isEmpty() && last) {
4769                mEffectChains[0]->clearInputBuffer();
4770            }
4771            if (track->isStopping_1()) {
4772                track->mState = TrackBase::STOPPING_2;
4773                if (last && mHwPaused) {
4774                     doHwResume = true;
4775                     mHwPaused = false;
4776                 }
4777            }
4778            if ((track->sharedBuffer() != 0) || track->isStopped() ||
4779                    track->isStopping_2() || track->isPaused()) {
4780                // We have consumed all the buffers of this track.
4781                // Remove it from the list of active tracks.
4782                size_t audioHALFrames;
4783                if (audio_has_proportional_frames(mFormat)) {
4784                    audioHALFrames = (latency_l() * mSampleRate) / 1000;
4785                } else {
4786                    audioHALFrames = 0;
4787                }
4788
4789                int64_t framesWritten = mBytesWritten / mFrameSize;
4790                if (mStandby || !last ||
4791                        track->presentationComplete(framesWritten, audioHALFrames)) {
4792                    if (track->isStopping_2()) {
4793                        track->mState = TrackBase::STOPPED;
4794                    }
4795                    if (track->isStopped()) {
4796                        track->reset();
4797                    }
4798                    tracksToRemove->add(track);
4799                }
4800            } else {
4801                // No buffers for this track. Give it a few chances to
4802                // fill a buffer, then remove it from active list.
4803                // Only consider last track started for mixer state control
4804                if (--(track->mRetryCount) <= 0) {
4805                    ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
4806                    tracksToRemove->add(track);
4807                    // indicate to client process that the track was disabled because of underrun;
4808                    // it will then automatically call start() when data is available
4809                    track->disable();
4810                } else if (last) {
4811                    ALOGW("pause because of UNDERRUN, framesReady = %zu,"
4812                            "minFrames = %u, mFormat = %#x",
4813                            track->framesReady(), minFrames, mFormat);
4814                    mixerStatus = MIXER_TRACKS_ENABLED;
4815                    if (mHwSupportsPause && !mHwPaused && !mStandby) {
4816                        doHwPause = true;
4817                        mHwPaused = true;
4818                    }
4819                }
4820            }
4821        }
4822    }
4823
4824    // if an active track did not command a flush, check for pending flush on stopped tracks
4825    if (!mFlushPending) {
4826        for (size_t i = 0; i < mTracks.size(); i++) {
4827            if (mTracks[i]->isFlushPending()) {
4828                mTracks[i]->flushAck();
4829                mFlushPending = true;
4830            }
4831        }
4832    }
4833
4834    // make sure the pause/flush/resume sequence is executed in the right order.
4835    // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4836    // before flush and then resume HW. This can happen in case of pause/flush/resume
4837    // if resume is received before pause is executed.
4838    if (mHwSupportsPause && !mStandby &&
4839            (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
4840        mOutput->stream->pause(mOutput->stream);
4841    }
4842    if (mFlushPending) {
4843        flushHw_l();
4844    }
4845    if (mHwSupportsPause && !mStandby && doHwResume) {
4846        mOutput->stream->resume(mOutput->stream);
4847    }
4848    // remove all the tracks that need to be...
4849    removeTracks_l(*tracksToRemove);
4850
4851    return mixerStatus;
4852}
4853
4854void AudioFlinger::DirectOutputThread::threadLoop_mix()
4855{
4856    size_t frameCount = mFrameCount;
4857    int8_t *curBuf = (int8_t *)mSinkBuffer;
4858    // output audio to hardware
4859    while (frameCount) {
4860        AudioBufferProvider::Buffer buffer;
4861        buffer.frameCount = frameCount;
4862        status_t status = mActiveTrack->getNextBuffer(&buffer);
4863        if (status != NO_ERROR || buffer.raw == NULL) {
4864            // no need to pad with 0 for compressed audio
4865            if (audio_has_proportional_frames(mFormat)) {
4866                memset(curBuf, 0, frameCount * mFrameSize);
4867            }
4868            break;
4869        }
4870        memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4871        frameCount -= buffer.frameCount;
4872        curBuf += buffer.frameCount * mFrameSize;
4873        mActiveTrack->releaseBuffer(&buffer);
4874    }
4875    mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
4876    mSleepTimeUs = 0;
4877    mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4878    mActiveTrack.clear();
4879}
4880
4881void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4882{
4883    // do not write to HAL when paused
4884    if (mHwPaused || (usesHwAvSync() && mStandby)) {
4885        mSleepTimeUs = mIdleSleepTimeUs;
4886        return;
4887    }
4888    if (mSleepTimeUs == 0) {
4889        if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4890            // For compressed offload, use faster sleep time when underruning until more than an
4891            // entire buffer was written to the audio HAL
4892            if (!audio_has_proportional_frames(mFormat) &&
4893                    (mType == OFFLOAD) && (mBytesWritten < (int64_t) mBufferSize)) {
4894                mSleepTimeUs = kDirectMinSleepTimeUs;
4895            } else {
4896                mSleepTimeUs = mActiveSleepTimeUs;
4897            }
4898        } else {
4899            mSleepTimeUs = mIdleSleepTimeUs;
4900        }
4901    } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
4902        memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
4903        mSleepTimeUs = 0;
4904    }
4905}
4906
4907void AudioFlinger::DirectOutputThread::threadLoop_exit()
4908{
4909    {
4910        Mutex::Autolock _l(mLock);
4911        for (size_t i = 0; i < mTracks.size(); i++) {
4912            if (mTracks[i]->isFlushPending()) {
4913                mTracks[i]->flushAck();
4914                mFlushPending = true;
4915            }
4916        }
4917        if (mFlushPending) {
4918            flushHw_l();
4919        }
4920    }
4921    PlaybackThread::threadLoop_exit();
4922}
4923
4924// must be called with thread mutex locked
4925bool AudioFlinger::DirectOutputThread::shouldStandby_l()
4926{
4927    bool trackPaused = false;
4928    bool trackStopped = false;
4929
4930    if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
4931        return !mStandby;
4932    }
4933
4934    // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4935    // after a timeout and we will enter standby then.
4936    if (mTracks.size() > 0) {
4937        trackPaused = mTracks[mTracks.size() - 1]->isPaused();
4938        trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
4939                           mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
4940    }
4941
4942    return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
4943}
4944
4945// getTrackName_l() must be called with ThreadBase::mLock held
4946int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
4947        audio_format_t format __unused, audio_session_t sessionId __unused)
4948{
4949    return 0;
4950}
4951
4952// deleteTrackName_l() must be called with ThreadBase::mLock held
4953void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
4954{
4955}
4956
4957// checkForNewParameter_l() must be called with ThreadBase::mLock held
4958bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4959                                                              status_t& status)
4960{
4961    bool reconfig = false;
4962    bool a2dpDeviceChanged = false;
4963
4964    status = NO_ERROR;
4965
4966    AudioParameter param = AudioParameter(keyValuePair);
4967    int value;
4968    if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4969        // forward device change to effects that have requested to be
4970        // aware of attached audio device.
4971        if (value != AUDIO_DEVICE_NONE) {
4972            a2dpDeviceChanged =
4973                    (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
4974            mOutDevice = value;
4975            for (size_t i = 0; i < mEffectChains.size(); i++) {
4976                mEffectChains[i]->setDevice_l(mOutDevice);
4977            }
4978        }
4979    }
4980    if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4981        // do not accept frame count changes if tracks are open as the track buffer
4982        // size depends on frame count and correct behavior would not be garantied
4983        // if frame count is changed after track creation
4984        if (!mTracks.isEmpty()) {
4985            status = INVALID_OPERATION;
4986        } else {
4987            reconfig = true;
4988        }
4989    }
4990    if (status == NO_ERROR) {
4991        status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4992                                                keyValuePair.string());
4993        if (!mStandby && status == INVALID_OPERATION) {
4994            mOutput->standby();
4995            mStandby = true;
4996            mBytesWritten = 0;
4997            status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4998                                                   keyValuePair.string());
4999        }
5000        if (status == NO_ERROR && reconfig) {
5001            readOutputParameters_l();
5002            sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
5003        }
5004    }
5005
5006    return reconfig || a2dpDeviceChanged;
5007}
5008
5009uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5010{
5011    uint32_t time;
5012    if (audio_has_proportional_frames(mFormat)) {
5013        time = PlaybackThread::activeSleepTimeUs();
5014    } else {
5015        time = kDirectMinSleepTimeUs;
5016    }
5017    return time;
5018}
5019
5020uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5021{
5022    uint32_t time;
5023    if (audio_has_proportional_frames(mFormat)) {
5024        time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5025    } else {
5026        time = kDirectMinSleepTimeUs;
5027    }
5028    return time;
5029}
5030
5031uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5032{
5033    uint32_t time;
5034    if (audio_has_proportional_frames(mFormat)) {
5035        time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5036    } else {
5037        time = kDirectMinSleepTimeUs;
5038    }
5039    return time;
5040}
5041
5042void AudioFlinger::DirectOutputThread::cacheParameters_l()
5043{
5044    PlaybackThread::cacheParameters_l();
5045
5046    // use shorter standby delay as on normal output to release
5047    // hardware resources as soon as possible
5048    // no delay on outputs with HW A/V sync
5049    if (usesHwAvSync()) {
5050        mStandbyDelayNs = 0;
5051    } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
5052        mStandbyDelayNs = kOffloadStandbyDelayNs;
5053    } else {
5054        mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
5055    }
5056}
5057
5058void AudioFlinger::DirectOutputThread::flushHw_l()
5059{
5060    mOutput->flush();
5061    mHwPaused = false;
5062    mFlushPending = false;
5063}
5064
5065// ----------------------------------------------------------------------------
5066
5067AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
5068        const wp<AudioFlinger::PlaybackThread>& playbackThread)
5069    :   Thread(false /*canCallJava*/),
5070        mPlaybackThread(playbackThread),
5071        mWriteAckSequence(0),
5072        mDrainSequence(0)
5073{
5074}
5075
5076AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5077{
5078}
5079
5080void AudioFlinger::AsyncCallbackThread::onFirstRef()
5081{
5082    run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5083}
5084
5085bool AudioFlinger::AsyncCallbackThread::threadLoop()
5086{
5087    while (!exitPending()) {
5088        uint32_t writeAckSequence;
5089        uint32_t drainSequence;
5090
5091        {
5092            Mutex::Autolock _l(mLock);
5093            while (!((mWriteAckSequence & 1) ||
5094                     (mDrainSequence & 1) ||
5095                     exitPending())) {
5096                mWaitWorkCV.wait(mLock);
5097            }
5098
5099            if (exitPending()) {
5100                break;
5101            }
5102            ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5103                  mWriteAckSequence, mDrainSequence);
5104            writeAckSequence = mWriteAckSequence;
5105            mWriteAckSequence &= ~1;
5106            drainSequence = mDrainSequence;
5107            mDrainSequence &= ~1;
5108        }
5109        {
5110            sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5111            if (playbackThread != 0) {
5112                if (writeAckSequence & 1) {
5113                    playbackThread->resetWriteBlocked(writeAckSequence >> 1);
5114                }
5115                if (drainSequence & 1) {
5116                    playbackThread->resetDraining(drainSequence >> 1);
5117                }
5118            }
5119        }
5120    }
5121    return false;
5122}
5123
5124void AudioFlinger::AsyncCallbackThread::exit()
5125{
5126    ALOGV("AsyncCallbackThread::exit");
5127    Mutex::Autolock _l(mLock);
5128    requestExit();
5129    mWaitWorkCV.broadcast();
5130}
5131
5132void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
5133{
5134    Mutex::Autolock _l(mLock);
5135    // bit 0 is cleared
5136    mWriteAckSequence = sequence << 1;
5137}
5138
5139void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5140{
5141    Mutex::Autolock _l(mLock);
5142    // ignore unexpected callbacks
5143    if (mWriteAckSequence & 2) {
5144        mWriteAckSequence |= 1;
5145        mWaitWorkCV.signal();
5146    }
5147}
5148
5149void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
5150{
5151    Mutex::Autolock _l(mLock);
5152    // bit 0 is cleared
5153    mDrainSequence = sequence << 1;
5154}
5155
5156void AudioFlinger::AsyncCallbackThread::resetDraining()
5157{
5158    Mutex::Autolock _l(mLock);
5159    // ignore unexpected callbacks
5160    if (mDrainSequence & 2) {
5161        mDrainSequence |= 1;
5162        mWaitWorkCV.signal();
5163    }
5164}
5165
5166
5167// ----------------------------------------------------------------------------
5168AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
5169        AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady,
5170        uint32_t bitRate)
5171    :   DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady, bitRate),
5172        mPausedBytesRemaining(0)
5173{
5174    //FIXME: mStandby should be set to true by ThreadBase constructor
5175    mStandby = true;
5176}
5177
5178void AudioFlinger::OffloadThread::threadLoop_exit()
5179{
5180    if (mFlushPending || mHwPaused) {
5181        // If a flush is pending or track was paused, just discard buffered data
5182        flushHw_l();
5183    } else {
5184        mMixerStatus = MIXER_DRAIN_ALL;
5185        threadLoop_drain();
5186    }
5187    if (mUseAsyncWrite) {
5188        ALOG_ASSERT(mCallbackThread != 0);
5189        mCallbackThread->exit();
5190    }
5191    PlaybackThread::threadLoop_exit();
5192}
5193
5194AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5195    Vector< sp<Track> > *tracksToRemove
5196)
5197{
5198    size_t count = mActiveTracks.size();
5199
5200    mixer_state mixerStatus = MIXER_IDLE;
5201    bool doHwPause = false;
5202    bool doHwResume = false;
5203
5204    ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
5205
5206    // find out which tracks need to be processed
5207    for (size_t i = 0; i < count; i++) {
5208        sp<Track> t = mActiveTracks[i].promote();
5209        // The track died recently
5210        if (t == 0) {
5211            continue;
5212        }
5213        Track* const track = t.get();
5214#ifdef VERY_VERY_VERBOSE_LOGGING
5215        audio_track_cblk_t* cblk = track->cblk();
5216#endif
5217        // Only consider last track started for volume and mixer state control.
5218        // In theory an older track could underrun and restart after the new one starts
5219        // but as we only care about the transition phase between two tracks on a
5220        // direct output, it is not a problem to ignore the underrun case.
5221        sp<Track> l = mLatestActiveTrack.promote();
5222        bool last = l.get() == track;
5223
5224        if (track->isInvalid()) {
5225            ALOGW("An invalidated track shouldn't be in active list");
5226            tracksToRemove->add(track);
5227            continue;
5228        }
5229
5230        if (track->mState == TrackBase::IDLE) {
5231            ALOGW("An idle track shouldn't be in active list");
5232            continue;
5233        }
5234
5235        if (track->isPausing()) {
5236            track->setPaused();
5237            if (last) {
5238                if (mHwSupportsPause && !mHwPaused) {
5239                    doHwPause = true;
5240                    mHwPaused = true;
5241                }
5242                // If we were part way through writing the mixbuffer to
5243                // the HAL we must save this until we resume
5244                // BUG - this will be wrong if a different track is made active,
5245                // in that case we want to discard the pending data in the
5246                // mixbuffer and tell the client to present it again when the
5247                // track is resumed
5248                mPausedWriteLength = mCurrentWriteLength;
5249                mPausedBytesRemaining = mBytesRemaining;
5250                mBytesRemaining = 0;    // stop writing
5251            }
5252            tracksToRemove->add(track);
5253        } else if (track->isFlushPending()) {
5254            track->mRetryCount = kMaxTrackRetriesOffload;
5255            track->flushAck();
5256            if (last) {
5257                mFlushPending = true;
5258            }
5259        } else if (track->isResumePending()){
5260            track->resumeAck();
5261            if (last) {
5262                if (mPausedBytesRemaining) {
5263                    // Need to continue write that was interrupted
5264                    mCurrentWriteLength = mPausedWriteLength;
5265                    mBytesRemaining = mPausedBytesRemaining;
5266                    mPausedBytesRemaining = 0;
5267                }
5268                if (mHwPaused) {
5269                    doHwResume = true;
5270                    mHwPaused = false;
5271                    // threadLoop_mix() will handle the case that we need to
5272                    // resume an interrupted write
5273                }
5274                // enable write to audio HAL
5275                mSleepTimeUs = 0;
5276
5277                // Do not handle new data in this iteration even if track->framesReady()
5278                mixerStatus = MIXER_TRACKS_ENABLED;
5279            }
5280        }  else if (track->framesReady() && track->isReady() &&
5281                !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
5282            ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
5283            if (track->mFillingUpStatus == Track::FS_FILLED) {
5284                track->mFillingUpStatus = Track::FS_ACTIVE;
5285                // make sure processVolume_l() will apply new volume even if 0
5286                mLeftVolFloat = mRightVolFloat = -1.0;
5287            }
5288
5289            if (last) {
5290                sp<Track> previousTrack = mPreviousTrack.promote();
5291                if (previousTrack != 0) {
5292                    if (track != previousTrack.get()) {
5293                        // Flush any data still being written from last track
5294                        mBytesRemaining = 0;
5295                        if (mPausedBytesRemaining) {
5296                            // Last track was paused so we also need to flush saved
5297                            // mixbuffer state and invalidate track so that it will
5298                            // re-submit that unwritten data when it is next resumed
5299                            mPausedBytesRemaining = 0;
5300                            // Invalidate is a bit drastic - would be more efficient
5301                            // to have a flag to tell client that some of the
5302                            // previously written data was lost
5303                            previousTrack->invalidate();
5304                        }
5305                        // flush data already sent to the DSP if changing audio session as audio
5306                        // comes from a different source. Also invalidate previous track to force a
5307                        // seek when resuming.
5308                        if (previousTrack->sessionId() != track->sessionId()) {
5309                            previousTrack->invalidate();
5310                        }
5311                    }
5312                }
5313                mPreviousTrack = track;
5314                // reset retry count
5315                track->mRetryCount = kMaxTrackRetriesOffload;
5316                mActiveTrack = t;
5317                mixerStatus = MIXER_TRACKS_READY;
5318            }
5319        } else {
5320            ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
5321            if (track->isStopping_1()) {
5322                // Hardware buffer can hold a large amount of audio so we must
5323                // wait for all current track's data to drain before we say
5324                // that the track is stopped.
5325                if (mBytesRemaining == 0) {
5326                    // Only start draining when all data in mixbuffer
5327                    // has been written
5328                    ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5329                    track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
5330                    // do not drain if no data was ever sent to HAL (mStandby == true)
5331                    if (last && !mStandby) {
5332                        // do not modify drain sequence if we are already draining. This happens
5333                        // when resuming from pause after drain.
5334                        if ((mDrainSequence & 1) == 0) {
5335                            mSleepTimeUs = 0;
5336                            mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5337                            mixerStatus = MIXER_DRAIN_TRACK;
5338                            mDrainSequence += 2;
5339                        }
5340                        if (mHwPaused) {
5341                            // It is possible to move from PAUSED to STOPPING_1 without
5342                            // a resume so we must ensure hardware is running
5343                            doHwResume = true;
5344                            mHwPaused = false;
5345                        }
5346                    }
5347                }
5348            } else if (track->isStopping_2()) {
5349                // Drain has completed or we are in standby, signal presentation complete
5350                if (!(mDrainSequence & 1) || !last || mStandby) {
5351                    track->mState = TrackBase::STOPPED;
5352                    size_t audioHALFrames =
5353                            (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
5354                    int64_t framesWritten =
5355                            mBytesWritten / mOutput->getFrameSize();
5356                    track->presentationComplete(framesWritten, audioHALFrames);
5357                    track->reset();
5358                    tracksToRemove->add(track);
5359                }
5360            } else {
5361                // No buffers for this track. Give it a few chances to
5362                // fill a buffer, then remove it from active list.
5363                if (--(track->mRetryCount) <= 0) {
5364                    ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5365                          track->name());
5366                    tracksToRemove->add(track);
5367                    // indicate to client process that the track was disabled because of underrun;
5368                    // it will then automatically call start() when data is available
5369                    track->disable();
5370                } else if (last){
5371                    mixerStatus = MIXER_TRACKS_ENABLED;
5372                }
5373            }
5374        }
5375        // compute volume for this track
5376        processVolume_l(track, last);
5377    }
5378
5379    // make sure the pause/flush/resume sequence is executed in the right order.
5380    // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5381    // before flush and then resume HW. This can happen in case of pause/flush/resume
5382    // if resume is received before pause is executed.
5383    if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
5384        mOutput->stream->pause(mOutput->stream);
5385    }
5386    if (mFlushPending) {
5387        flushHw_l();
5388    }
5389    if (!mStandby && doHwResume) {
5390        mOutput->stream->resume(mOutput->stream);
5391    }
5392
5393    // remove all the tracks that need to be...
5394    removeTracks_l(*tracksToRemove);
5395
5396    return mixerStatus;
5397}
5398
5399// must be called with thread mutex locked
5400bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5401{
5402    ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5403          mWriteAckSequence, mDrainSequence);
5404    if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
5405        return true;
5406    }
5407    return false;
5408}
5409
5410bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5411{
5412    Mutex::Autolock _l(mLock);
5413    return waitingAsyncCallback_l();
5414}
5415
5416void AudioFlinger::OffloadThread::flushHw_l()
5417{
5418    DirectOutputThread::flushHw_l();
5419    // Flush anything still waiting in the mixbuffer
5420    mCurrentWriteLength = 0;
5421    mBytesRemaining = 0;
5422    mPausedWriteLength = 0;
5423    mPausedBytesRemaining = 0;
5424
5425    if (mUseAsyncWrite) {
5426        // discard any pending drain or write ack by incrementing sequence
5427        mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5428        mDrainSequence = (mDrainSequence + 2) & ~1;
5429        ALOG_ASSERT(mCallbackThread != 0);
5430        mCallbackThread->setWriteBlocked(mWriteAckSequence);
5431        mCallbackThread->setDraining(mDrainSequence);
5432    }
5433}
5434
5435uint32_t AudioFlinger::OffloadThread::activeSleepTimeUs() const
5436{
5437    uint32_t time;
5438    if (audio_has_proportional_frames(mFormat)) {
5439        time = PlaybackThread::activeSleepTimeUs();
5440    } else {
5441        // sleep time is half the duration of an audio HAL buffer.
5442        // Note: This can be problematic in case of underrun with variable bit rate and
5443        // current rate is much less than initial rate.
5444        time = (uint32_t)max(kDirectMinSleepTimeUs, mBufferDurationUs / 2);
5445    }
5446    return time;
5447}
5448
5449// ----------------------------------------------------------------------------
5450
5451AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
5452        AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
5453    :   MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
5454                    systemReady, DUPLICATING),
5455        mWaitTimeMs(UINT_MAX)
5456{
5457    addOutputTrack(mainThread);
5458}
5459
5460AudioFlinger::DuplicatingThread::~DuplicatingThread()
5461{
5462    for (size_t i = 0; i < mOutputTracks.size(); i++) {
5463        mOutputTracks[i]->destroy();
5464    }
5465}
5466
5467void AudioFlinger::DuplicatingThread::threadLoop_mix()
5468{
5469    // mix buffers...
5470    if (outputsReady(outputTracks)) {
5471        mAudioMixer->process();
5472    } else {
5473        if (mMixerBufferValid) {
5474            memset(mMixerBuffer, 0, mMixerBufferSize);
5475        } else {
5476            memset(mSinkBuffer, 0, mSinkBufferSize);
5477        }
5478    }
5479    mSleepTimeUs = 0;
5480    writeFrames = mNormalFrameCount;
5481    mCurrentWriteLength = mSinkBufferSize;
5482    mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5483}
5484
5485void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5486{
5487    if (mSleepTimeUs == 0) {
5488        if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5489            mSleepTimeUs = mActiveSleepTimeUs;
5490        } else {
5491            mSleepTimeUs = mIdleSleepTimeUs;
5492        }
5493    } else if (mBytesWritten != 0) {
5494        if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5495            writeFrames = mNormalFrameCount;
5496            memset(mSinkBuffer, 0, mSinkBufferSize);
5497        } else {
5498            // flush remaining overflow buffers in output tracks
5499            writeFrames = 0;
5500        }
5501        mSleepTimeUs = 0;
5502    }
5503}
5504
5505ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
5506{
5507    for (size_t i = 0; i < outputTracks.size(); i++) {
5508        outputTracks[i]->write(mSinkBuffer, writeFrames);
5509    }
5510    mStandby = false;
5511    return (ssize_t)mSinkBufferSize;
5512}
5513
5514void AudioFlinger::DuplicatingThread::threadLoop_standby()
5515{
5516    // DuplicatingThread implements standby by stopping all tracks
5517    for (size_t i = 0; i < outputTracks.size(); i++) {
5518        outputTracks[i]->stop();
5519    }
5520}
5521
5522void AudioFlinger::DuplicatingThread::saveOutputTracks()
5523{
5524    outputTracks = mOutputTracks;
5525}
5526
5527void AudioFlinger::DuplicatingThread::clearOutputTracks()
5528{
5529    outputTracks.clear();
5530}
5531
5532void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5533{
5534    Mutex::Autolock _l(mLock);
5535    // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5536    // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5537    // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5538    const size_t frameCount =
5539            3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5540    // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5541    // from different OutputTracks and their associated MixerThreads (e.g. one may
5542    // nearly empty and the other may be dropping data).
5543
5544    sp<OutputTrack> outputTrack = new OutputTrack(thread,
5545                                            this,
5546                                            mSampleRate,
5547                                            mFormat,
5548                                            mChannelMask,
5549                                            frameCount,
5550                                            IPCThreadState::self()->getCallingUid());
5551    if (outputTrack->cblk() != NULL) {
5552        thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
5553        mOutputTracks.add(outputTrack);
5554        ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
5555        updateWaitTime_l();
5556    }
5557}
5558
5559void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5560{
5561    Mutex::Autolock _l(mLock);
5562    for (size_t i = 0; i < mOutputTracks.size(); i++) {
5563        if (mOutputTracks[i]->thread() == thread) {
5564            mOutputTracks[i]->destroy();
5565            mOutputTracks.removeAt(i);
5566            updateWaitTime_l();
5567            if (thread->getOutput() == mOutput) {
5568                mOutput = NULL;
5569            }
5570            return;
5571        }
5572    }
5573    ALOGV("removeOutputTrack(): unknown thread: %p", thread);
5574}
5575
5576// caller must hold mLock
5577void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5578{
5579    mWaitTimeMs = UINT_MAX;
5580    for (size_t i = 0; i < mOutputTracks.size(); i++) {
5581        sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5582        if (strong != 0) {
5583            uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5584            if (waitTimeMs < mWaitTimeMs) {
5585                mWaitTimeMs = waitTimeMs;
5586            }
5587        }
5588    }
5589}
5590
5591
5592bool AudioFlinger::DuplicatingThread::outputsReady(
5593        const SortedVector< sp<OutputTrack> > &outputTracks)
5594{
5595    for (size_t i = 0; i < outputTracks.size(); i++) {
5596        sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5597        if (thread == 0) {
5598            ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5599                    outputTracks[i].get());
5600            return false;
5601        }
5602        PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5603        // see note at standby() declaration
5604        if (playbackThread->standby() && !playbackThread->isSuspended()) {
5605            ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5606                    thread.get());
5607            return false;
5608        }
5609    }
5610    return true;
5611}
5612
5613uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5614{
5615    return (mWaitTimeMs * 1000) / 2;
5616}
5617
5618void AudioFlinger::DuplicatingThread::cacheParameters_l()
5619{
5620    // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5621    updateWaitTime_l();
5622
5623    MixerThread::cacheParameters_l();
5624}
5625
5626// ----------------------------------------------------------------------------
5627//      Record
5628// ----------------------------------------------------------------------------
5629
5630AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5631                                         AudioStreamIn *input,
5632                                         audio_io_handle_t id,
5633                                         audio_devices_t outDevice,
5634                                         audio_devices_t inDevice,
5635                                         bool systemReady
5636#ifdef TEE_SINK
5637                                         , const sp<NBAIO_Sink>& teeSink
5638#endif
5639                                         ) :
5640    ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
5641    mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
5642    // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
5643    mRsmpInRear(0)
5644#ifdef TEE_SINK
5645    , mTeeSink(teeSink)
5646#endif
5647    , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5648            "RecordThreadRO", MemoryHeapBase::READ_ONLY))
5649    // mFastCapture below
5650    , mFastCaptureFutex(0)
5651    // mInputSource
5652    // mPipeSink
5653    // mPipeSource
5654    , mPipeFramesP2(0)
5655    // mPipeMemory
5656    // mFastCaptureNBLogWriter
5657    , mFastTrackAvail(false)
5658{
5659    snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5660    mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
5661
5662    readInputParameters_l();
5663
5664    // create an NBAIO source for the HAL input stream, and negotiate
5665    mInputSource = new AudioStreamInSource(input->stream);
5666    size_t numCounterOffers = 0;
5667    const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
5668#if !LOG_NDEBUG
5669    ssize_t index =
5670#else
5671    (void)
5672#endif
5673            mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
5674    ALOG_ASSERT(index == 0);
5675
5676    // initialize fast capture depending on configuration
5677    bool initFastCapture;
5678    switch (kUseFastCapture) {
5679    case FastCapture_Never:
5680        initFastCapture = false;
5681        break;
5682    case FastCapture_Always:
5683        initFastCapture = true;
5684        break;
5685    case FastCapture_Static:
5686        initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
5687        break;
5688    // case FastCapture_Dynamic:
5689    }
5690
5691    if (initFastCapture) {
5692        // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
5693        NBAIO_Format format = mInputSource->format();
5694        size_t pipeFramesP2 = roundup(mSampleRate / 25);    // double-buffering of 20 ms each
5695        size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5696        void *pipeBuffer;
5697        const sp<MemoryDealer> roHeap(readOnlyHeap());
5698        sp<IMemory> pipeMemory;
5699        if ((roHeap == 0) ||
5700                (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5701                (pipeBuffer = pipeMemory->pointer()) == NULL) {
5702            ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5703            goto failed;
5704        }
5705        // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5706        memset(pipeBuffer, 0, pipeSize);
5707        Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5708        const NBAIO_Format offers[1] = {format};
5709        size_t numCounterOffers = 0;
5710        ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5711        ALOG_ASSERT(index == 0);
5712        mPipeSink = pipe;
5713        PipeReader *pipeReader = new PipeReader(*pipe);
5714        numCounterOffers = 0;
5715        index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5716        ALOG_ASSERT(index == 0);
5717        mPipeSource = pipeReader;
5718        mPipeFramesP2 = pipeFramesP2;
5719        mPipeMemory = pipeMemory;
5720
5721        // create fast capture
5722        mFastCapture = new FastCapture();
5723        FastCaptureStateQueue *sq = mFastCapture->sq();
5724#ifdef STATE_QUEUE_DUMP
5725        // FIXME
5726#endif
5727        FastCaptureState *state = sq->begin();
5728        state->mCblk = NULL;
5729        state->mInputSource = mInputSource.get();
5730        state->mInputSourceGen++;
5731        state->mPipeSink = pipe;
5732        state->mPipeSinkGen++;
5733        state->mFrameCount = mFrameCount;
5734        state->mCommand = FastCaptureState::COLD_IDLE;
5735        // already done in constructor initialization list
5736        //mFastCaptureFutex = 0;
5737        state->mColdFutexAddr = &mFastCaptureFutex;
5738        state->mColdGen++;
5739        state->mDumpState = &mFastCaptureDumpState;
5740#ifdef TEE_SINK
5741        // FIXME
5742#endif
5743        mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5744        state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5745        sq->end();
5746        sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5747
5748        // start the fast capture
5749        mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5750        pid_t tid = mFastCapture->getTid();
5751        sendPrioConfigEvent(getpid_cached, tid, kPriorityFastCapture);
5752#ifdef AUDIO_WATCHDOG
5753        // FIXME
5754#endif
5755
5756        mFastTrackAvail = true;
5757    }
5758failed: ;
5759
5760    // FIXME mNormalSource
5761}
5762
5763AudioFlinger::RecordThread::~RecordThread()
5764{
5765    if (mFastCapture != 0) {
5766        FastCaptureStateQueue *sq = mFastCapture->sq();
5767        FastCaptureState *state = sq->begin();
5768        if (state->mCommand == FastCaptureState::COLD_IDLE) {
5769            int32_t old = android_atomic_inc(&mFastCaptureFutex);
5770            if (old == -1) {
5771                (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5772            }
5773        }
5774        state->mCommand = FastCaptureState::EXIT;
5775        sq->end();
5776        sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5777        mFastCapture->join();
5778        mFastCapture.clear();
5779    }
5780    mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
5781    mAudioFlinger->unregisterWriter(mNBLogWriter);
5782    free(mRsmpInBuffer);
5783}
5784
5785void AudioFlinger::RecordThread::onFirstRef()
5786{
5787    run(mThreadName, PRIORITY_URGENT_AUDIO);
5788}
5789
5790bool AudioFlinger::RecordThread::threadLoop()
5791{
5792    nsecs_t lastWarning = 0;
5793
5794    inputStandBy();
5795
5796reacquire_wakelock:
5797    sp<RecordTrack> activeTrack;
5798    int activeTracksGen;
5799    {
5800        Mutex::Autolock _l(mLock);
5801        size_t size = mActiveTracks.size();
5802        activeTracksGen = mActiveTracksGen;
5803        if (size > 0) {
5804            // FIXME an arbitrary choice
5805            activeTrack = mActiveTracks[0];
5806            acquireWakeLock_l(activeTrack->uid());
5807            if (size > 1) {
5808                SortedVector<int> tmp;
5809                for (size_t i = 0; i < size; i++) {
5810                    tmp.add(mActiveTracks[i]->uid());
5811                }
5812                updateWakeLockUids_l(tmp);
5813            }
5814        } else {
5815            acquireWakeLock_l(-1);
5816        }
5817    }
5818
5819    // used to request a deferred sleep, to be executed later while mutex is unlocked
5820    uint32_t sleepUs = 0;
5821
5822    // loop while there is work to do
5823    for (;;) {
5824        Vector< sp<EffectChain> > effectChains;
5825
5826        // sleep with mutex unlocked
5827        if (sleepUs > 0) {
5828            ATRACE_BEGIN("sleep");
5829            usleep(sleepUs);
5830            ATRACE_END();
5831            sleepUs = 0;
5832        }
5833
5834        // activeTracks accumulates a copy of a subset of mActiveTracks
5835        Vector< sp<RecordTrack> > activeTracks;
5836
5837        // reference to the (first and only) active fast track
5838        sp<RecordTrack> fastTrack;
5839
5840        // reference to a fast track which is about to be removed
5841        sp<RecordTrack> fastTrackToRemove;
5842
5843        { // scope for mLock
5844            Mutex::Autolock _l(mLock);
5845
5846            processConfigEvents_l();
5847
5848            // check exitPending here because checkForNewParameters_l() and
5849            // checkForNewParameters_l() can temporarily release mLock
5850            if (exitPending()) {
5851                break;
5852            }
5853
5854            // if no active track(s), then standby and release wakelock
5855            size_t size = mActiveTracks.size();
5856            if (size == 0) {
5857                standbyIfNotAlreadyInStandby();
5858                // exitPending() can't become true here
5859                releaseWakeLock_l();
5860                ALOGV("RecordThread: loop stopping");
5861                // go to sleep
5862                mWaitWorkCV.wait(mLock);
5863                ALOGV("RecordThread: loop starting");
5864                goto reacquire_wakelock;
5865            }
5866
5867            if (mActiveTracksGen != activeTracksGen) {
5868                activeTracksGen = mActiveTracksGen;
5869                SortedVector<int> tmp;
5870                for (size_t i = 0; i < size; i++) {
5871                    tmp.add(mActiveTracks[i]->uid());
5872                }
5873                updateWakeLockUids_l(tmp);
5874            }
5875
5876            bool doBroadcast = false;
5877            for (size_t i = 0; i < size; ) {
5878
5879                activeTrack = mActiveTracks[i];
5880                if (activeTrack->isTerminated()) {
5881                    if (activeTrack->isFastTrack()) {
5882                        ALOG_ASSERT(fastTrackToRemove == 0);
5883                        fastTrackToRemove = activeTrack;
5884                    }
5885                    removeTrack_l(activeTrack);
5886                    mActiveTracks.remove(activeTrack);
5887                    mActiveTracksGen++;
5888                    size--;
5889                    continue;
5890                }
5891
5892                TrackBase::track_state activeTrackState = activeTrack->mState;
5893                switch (activeTrackState) {
5894
5895                case TrackBase::PAUSING:
5896                    mActiveTracks.remove(activeTrack);
5897                    mActiveTracksGen++;
5898                    doBroadcast = true;
5899                    size--;
5900                    continue;
5901
5902                case TrackBase::STARTING_1:
5903                    sleepUs = 10000;
5904                    i++;
5905                    continue;
5906
5907                case TrackBase::STARTING_2:
5908                    doBroadcast = true;
5909                    mStandby = false;
5910                    activeTrack->mState = TrackBase::ACTIVE;
5911                    break;
5912
5913                case TrackBase::ACTIVE:
5914                    break;
5915
5916                case TrackBase::IDLE:
5917                    i++;
5918                    continue;
5919
5920                default:
5921                    LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
5922                }
5923
5924                activeTracks.add(activeTrack);
5925                i++;
5926
5927                if (activeTrack->isFastTrack()) {
5928                    ALOG_ASSERT(!mFastTrackAvail);
5929                    ALOG_ASSERT(fastTrack == 0);
5930                    fastTrack = activeTrack;
5931                }
5932            }
5933            if (doBroadcast) {
5934                mStartStopCond.broadcast();
5935            }
5936
5937            // sleep if there are no active tracks to process
5938            if (activeTracks.size() == 0) {
5939                if (sleepUs == 0) {
5940                    sleepUs = kRecordThreadSleepUs;
5941                }
5942                continue;
5943            }
5944            sleepUs = 0;
5945
5946            lockEffectChains_l(effectChains);
5947        }
5948
5949        // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
5950
5951        size_t size = effectChains.size();
5952        for (size_t i = 0; i < size; i++) {
5953            // thread mutex is not locked, but effect chain is locked
5954            effectChains[i]->process_l();
5955        }
5956
5957        // Push a new fast capture state if fast capture is not already running, or cblk change
5958        if (mFastCapture != 0) {
5959            FastCaptureStateQueue *sq = mFastCapture->sq();
5960            FastCaptureState *state = sq->begin();
5961            bool didModify = false;
5962            FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
5963            if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5964                    (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5965                if (state->mCommand == FastCaptureState::COLD_IDLE) {
5966                    int32_t old = android_atomic_inc(&mFastCaptureFutex);
5967                    if (old == -1) {
5968                        (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5969                    }
5970                }
5971                state->mCommand = FastCaptureState::READ_WRITE;
5972#if 0   // FIXME
5973                mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
5974                        FastThreadDumpState::kSamplingNforLowRamDevice :
5975                        FastThreadDumpState::kSamplingN);
5976#endif
5977                didModify = true;
5978            }
5979            audio_track_cblk_t *cblkOld = state->mCblk;
5980            audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
5981            if (cblkNew != cblkOld) {
5982                state->mCblk = cblkNew;
5983                // block until acked if removing a fast track
5984                if (cblkOld != NULL) {
5985                    block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
5986                }
5987                didModify = true;
5988            }
5989            sq->end(didModify);
5990            if (didModify) {
5991                sq->push(block);
5992#if 0
5993                if (kUseFastCapture == FastCapture_Dynamic) {
5994                    mNormalSource = mPipeSource;
5995                }
5996#endif
5997            }
5998        }
5999
6000        // now run the fast track destructor with thread mutex unlocked
6001        fastTrackToRemove.clear();
6002
6003        // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6004        // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6005        // slow, then this RecordThread will overrun by not calling HAL read often enough.
6006        // If destination is non-contiguous, first read past the nominal end of buffer, then
6007        // copy to the right place.  Permitted because mRsmpInBuffer was over-allocated.
6008
6009        int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
6010        ssize_t framesRead;
6011
6012        // If an NBAIO source is present, use it to read the normal capture's data
6013        if (mPipeSource != 0) {
6014            size_t framesToRead = mBufferSize / mFrameSize;
6015            framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
6016                    framesToRead);
6017            if (framesRead == 0) {
6018                // since pipe is non-blocking, simulate blocking input
6019                sleepUs = (framesToRead * 1000000LL) / mSampleRate;
6020            }
6021        // otherwise use the HAL / AudioStreamIn directly
6022        } else {
6023            ATRACE_BEGIN("read");
6024            ssize_t bytesRead = mInput->stream->read(mInput->stream,
6025                    (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize);
6026            ATRACE_END();
6027            if (bytesRead < 0) {
6028                framesRead = bytesRead;
6029            } else {
6030                framesRead = bytesRead / mFrameSize;
6031            }
6032        }
6033
6034        // Update server timestamp with server stats
6035        // systemTime() is optional if the hardware supports timestamps.
6036        mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6037        mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6038
6039        // Update server timestamp with kernel stats
6040        if (mInput->stream->get_capture_position != nullptr) {
6041            int64_t position, time;
6042            int ret = mInput->stream->get_capture_position(mInput->stream, &position, &time);
6043            if (ret == NO_ERROR) {
6044                mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6045                mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6046                // Note: In general record buffers should tend to be empty in
6047                // a properly running pipeline.
6048                //
6049                // Also, it is not advantageous to call get_presentation_position during the read
6050                // as the read obtains a lock, preventing the timestamp call from executing.
6051            }
6052        }
6053        // Use this to track timestamp information
6054        // ALOGD("%s", mTimestamp.toString().c_str());
6055
6056        if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
6057            ALOGE("read failed: framesRead=%zd", framesRead);
6058            // Force input into standby so that it tries to recover at next read attempt
6059            inputStandBy();
6060            sleepUs = kRecordThreadSleepUs;
6061        }
6062        if (framesRead <= 0) {
6063            goto unlock;
6064        }
6065        ALOG_ASSERT(framesRead > 0);
6066
6067        if (mTeeSink != 0) {
6068            (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
6069        }
6070        // If destination is non-contiguous, we now correct for reading past end of buffer.
6071        {
6072            size_t part1 = mRsmpInFramesP2 - rear;
6073            if ((size_t) framesRead > part1) {
6074                memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
6075                        (framesRead - part1) * mFrameSize);
6076            }
6077        }
6078        rear = mRsmpInRear += framesRead;
6079
6080        size = activeTracks.size();
6081        // loop over each active track
6082        for (size_t i = 0; i < size; i++) {
6083            activeTrack = activeTracks[i];
6084
6085            // skip fast tracks, as those are handled directly by FastCapture
6086            if (activeTrack->isFastTrack()) {
6087                continue;
6088            }
6089
6090            // TODO: This code probably should be moved to RecordTrack.
6091            // TODO: Update the activeTrack buffer converter in case of reconfigure.
6092
6093            enum {
6094                OVERRUN_UNKNOWN,
6095                OVERRUN_TRUE,
6096                OVERRUN_FALSE
6097            } overrun = OVERRUN_UNKNOWN;
6098
6099            // loop over getNextBuffer to handle circular sink
6100            for (;;) {
6101
6102                activeTrack->mSink.frameCount = ~0;
6103                status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6104                size_t framesOut = activeTrack->mSink.frameCount;
6105                LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6106
6107                // check available frames and handle overrun conditions
6108                // if the record track isn't draining fast enough.
6109                bool hasOverrun;
6110                size_t framesIn;
6111                activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6112                if (hasOverrun) {
6113                    overrun = OVERRUN_TRUE;
6114                }
6115                if (framesOut == 0 || framesIn == 0) {
6116                    break;
6117                }
6118
6119                // Don't allow framesOut to be larger than what is possible with resampling
6120                // from framesIn.
6121                // This isn't strictly necessary but helps limit buffer resizing in
6122                // RecordBufferConverter.  TODO: remove when no longer needed.
6123                framesOut = min(framesOut,
6124                        destinationFramesPossible(
6125                                framesIn, mSampleRate, activeTrack->mSampleRate));
6126                // process frames from the RecordThread buffer provider to the RecordTrack buffer
6127                framesOut = activeTrack->mRecordBufferConverter->convert(
6128                        activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
6129
6130                if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6131                    overrun = OVERRUN_FALSE;
6132                }
6133
6134                if (activeTrack->mFramesToDrop == 0) {
6135                    if (framesOut > 0) {
6136                        activeTrack->mSink.frameCount = framesOut;
6137                        activeTrack->releaseBuffer(&activeTrack->mSink);
6138                    }
6139                } else {
6140                    // FIXME could do a partial drop of framesOut
6141                    if (activeTrack->mFramesToDrop > 0) {
6142                        activeTrack->mFramesToDrop -= framesOut;
6143                        if (activeTrack->mFramesToDrop <= 0) {
6144                            activeTrack->clearSyncStartEvent();
6145                        }
6146                    } else {
6147                        activeTrack->mFramesToDrop += framesOut;
6148                        if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6149                                activeTrack->mSyncStartEvent->isCancelled()) {
6150                            ALOGW("Synced record %s, session %d, trigger session %d",
6151                                  (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6152                                  activeTrack->sessionId(),
6153                                  (activeTrack->mSyncStartEvent != 0) ?
6154                                          activeTrack->mSyncStartEvent->triggerSession() :
6155                                          AUDIO_SESSION_NONE);
6156                            activeTrack->clearSyncStartEvent();
6157                        }
6158                    }
6159                }
6160
6161                if (framesOut == 0) {
6162                    break;
6163                }
6164            }
6165
6166            switch (overrun) {
6167            case OVERRUN_TRUE:
6168                // client isn't retrieving buffers fast enough
6169                if (!activeTrack->setOverflow()) {
6170                    nsecs_t now = systemTime();
6171                    // FIXME should lastWarning per track?
6172                    if ((now - lastWarning) > kWarningThrottleNs) {
6173                        ALOGW("RecordThread: buffer overflow");
6174                        lastWarning = now;
6175                    }
6176                }
6177                break;
6178            case OVERRUN_FALSE:
6179                activeTrack->clearOverflow();
6180                break;
6181            case OVERRUN_UNKNOWN:
6182                break;
6183            }
6184
6185            // update frame information and push timestamp out
6186            activeTrack->updateTrackFrameInfo(
6187                    activeTrack->mServerProxy->framesReleased(),
6188                    mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6189                    mSampleRate, mTimestamp);
6190        }
6191
6192unlock:
6193        // enable changes in effect chain
6194        unlockEffectChains(effectChains);
6195        // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
6196    }
6197
6198    standbyIfNotAlreadyInStandby();
6199
6200    {
6201        Mutex::Autolock _l(mLock);
6202        for (size_t i = 0; i < mTracks.size(); i++) {
6203            sp<RecordTrack> track = mTracks[i];
6204            track->invalidate();
6205        }
6206        mActiveTracks.clear();
6207        mActiveTracksGen++;
6208        mStartStopCond.broadcast();
6209    }
6210
6211    releaseWakeLock();
6212
6213    ALOGV("RecordThread %p exiting", this);
6214    return false;
6215}
6216
6217void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
6218{
6219    if (!mStandby) {
6220        inputStandBy();
6221        mStandby = true;
6222    }
6223}
6224
6225void AudioFlinger::RecordThread::inputStandBy()
6226{
6227    // Idle the fast capture if it's currently running
6228    if (mFastCapture != 0) {
6229        FastCaptureStateQueue *sq = mFastCapture->sq();
6230        FastCaptureState *state = sq->begin();
6231        if (!(state->mCommand & FastCaptureState::IDLE)) {
6232            state->mCommand = FastCaptureState::COLD_IDLE;
6233            state->mColdFutexAddr = &mFastCaptureFutex;
6234            state->mColdGen++;
6235            mFastCaptureFutex = 0;
6236            sq->end();
6237            // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6238            sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6239#if 0
6240            if (kUseFastCapture == FastCapture_Dynamic) {
6241                // FIXME
6242            }
6243#endif
6244#ifdef AUDIO_WATCHDOG
6245            // FIXME
6246#endif
6247        } else {
6248            sq->end(false /*didModify*/);
6249        }
6250    }
6251    mInput->stream->common.standby(&mInput->stream->common);
6252}
6253
6254// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
6255sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
6256        const sp<AudioFlinger::Client>& client,
6257        uint32_t sampleRate,
6258        audio_format_t format,
6259        audio_channel_mask_t channelMask,
6260        size_t *pFrameCount,
6261        audio_session_t sessionId,
6262        size_t *notificationFrames,
6263        int uid,
6264        IAudioFlinger::track_flags_t *flags,
6265        pid_t tid,
6266        status_t *status)
6267{
6268    size_t frameCount = *pFrameCount;
6269    sp<RecordTrack> track;
6270    status_t lStatus;
6271
6272    // client expresses a preference for FAST, but we get the final say
6273    if (*flags & IAudioFlinger::TRACK_FAST) {
6274      if (
6275            // we formerly checked for a callback handler (non-0 tid),
6276            // but that is no longer required for TRANSFER_OBTAIN mode
6277            //
6278            // frame count is not specified, or is exactly the pipe depth
6279            ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
6280            // PCM data
6281            audio_is_linear_pcm(format) &&
6282            // hardware format
6283            (format == mFormat) &&
6284            // hardware channel mask
6285            (channelMask == mChannelMask) &&
6286            // hardware sample rate
6287            (sampleRate == mSampleRate) &&
6288            // record thread has an associated fast capture
6289            hasFastCapture() &&
6290            // there are sufficient fast track slots available
6291            mFastTrackAvail
6292        ) {
6293        ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
6294                frameCount, mFrameCount);
6295      } else {
6296        ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
6297                "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
6298                "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
6299                frameCount, mFrameCount, mPipeFramesP2,
6300                format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6301                hasFastCapture(), tid, mFastTrackAvail);
6302        *flags &= ~IAudioFlinger::TRACK_FAST;
6303      }
6304    }
6305
6306    // compute track buffer size in frames, and suggest the notification frame count
6307    if (*flags & IAudioFlinger::TRACK_FAST) {
6308        // fast track: frame count is exactly the pipe depth
6309        frameCount = mPipeFramesP2;
6310        // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6311        *notificationFrames = mFrameCount;
6312    } else {
6313        // not fast track: max notification period is resampled equivalent of one HAL buffer time
6314        //                 or 20 ms if there is a fast capture
6315        // TODO This could be a roundupRatio inline, and const
6316        size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6317                * sampleRate + mSampleRate - 1) / mSampleRate;
6318        // minimum number of notification periods is at least kMinNotifications,
6319        // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6320        static const size_t kMinNotifications = 3;
6321        static const uint32_t kMinMs = 30;
6322        // TODO This could be a roundupRatio inline
6323        const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6324        // TODO This could be a roundupRatio inline
6325        const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6326                maxNotificationFrames;
6327        const size_t minFrameCount = maxNotificationFrames *
6328                max(kMinNotifications, minNotificationsByMs);
6329        frameCount = max(frameCount, minFrameCount);
6330        if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6331            *notificationFrames = maxNotificationFrames;
6332        }
6333    }
6334    *pFrameCount = frameCount;
6335
6336    lStatus = initCheck();
6337    if (lStatus != NO_ERROR) {
6338        ALOGE("createRecordTrack_l() audio driver not initialized");
6339        goto Exit;
6340    }
6341
6342    { // scope for mLock
6343        Mutex::Autolock _l(mLock);
6344
6345        track = new RecordTrack(this, client, sampleRate,
6346                      format, channelMask, frameCount, NULL, sessionId, uid,
6347                      *flags, TrackBase::TYPE_DEFAULT);
6348
6349        lStatus = track->initCheck();
6350        if (lStatus != NO_ERROR) {
6351            ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
6352            // track must be cleared from the caller as the caller has the AF lock
6353            goto Exit;
6354        }
6355        mTracks.add(track);
6356
6357        // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6358        bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6359                        mAudioFlinger->btNrecIsOff();
6360        setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6361        setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
6362
6363        if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
6364            pid_t callingPid = IPCThreadState::self()->getCallingPid();
6365            // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6366            // so ask activity manager to do this on our behalf
6367            sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6368        }
6369    }
6370
6371    lStatus = NO_ERROR;
6372
6373Exit:
6374    *status = lStatus;
6375    return track;
6376}
6377
6378status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6379                                           AudioSystem::sync_event_t event,
6380                                           audio_session_t triggerSession)
6381{
6382    ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6383    sp<ThreadBase> strongMe = this;
6384    status_t status = NO_ERROR;
6385
6386    if (event == AudioSystem::SYNC_EVENT_NONE) {
6387        recordTrack->clearSyncStartEvent();
6388    } else if (event != AudioSystem::SYNC_EVENT_SAME) {
6389        recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
6390                                       triggerSession,
6391                                       recordTrack->sessionId(),
6392                                       syncStartEventCallback,
6393                                       recordTrack);
6394        // Sync event can be cancelled by the trigger session if the track is not in a
6395        // compatible state in which case we start record immediately
6396        if (recordTrack->mSyncStartEvent->isCancelled()) {
6397            recordTrack->clearSyncStartEvent();
6398        } else {
6399            // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
6400            recordTrack->mFramesToDrop = -
6401                    ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
6402        }
6403    }
6404
6405    {
6406        // This section is a rendezvous between binder thread executing start() and RecordThread
6407        AutoMutex lock(mLock);
6408        if (mActiveTracks.indexOf(recordTrack) >= 0) {
6409            if (recordTrack->mState == TrackBase::PAUSING) {
6410                ALOGV("active record track PAUSING -> ACTIVE");
6411                recordTrack->mState = TrackBase::ACTIVE;
6412            } else {
6413                ALOGV("active record track state %d", recordTrack->mState);
6414            }
6415            return status;
6416        }
6417
6418        // TODO consider other ways of handling this, such as changing the state to :STARTING and
6419        //      adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6420        //      or using a separate command thread
6421        recordTrack->mState = TrackBase::STARTING_1;
6422        mActiveTracks.add(recordTrack);
6423        mActiveTracksGen++;
6424        status_t status = NO_ERROR;
6425        if (recordTrack->isExternalTrack()) {
6426            mLock.unlock();
6427            status = AudioSystem::startInput(mId, recordTrack->sessionId());
6428            mLock.lock();
6429            // FIXME should verify that recordTrack is still in mActiveTracks
6430            if (status != NO_ERROR) {
6431                mActiveTracks.remove(recordTrack);
6432                mActiveTracksGen++;
6433                recordTrack->clearSyncStartEvent();
6434                ALOGV("RecordThread::start error %d", status);
6435                return status;
6436            }
6437        }
6438        // Catch up with current buffer indices if thread is already running.
6439        // This is what makes a new client discard all buffered data.  If the track's mRsmpInFront
6440        // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6441        // see previously buffered data before it called start(), but with greater risk of overrun.
6442
6443        recordTrack->mResamplerBufferProvider->reset();
6444        // clear any converter state as new data will be discontinuous
6445        recordTrack->mRecordBufferConverter->reset();
6446        recordTrack->mState = TrackBase::STARTING_2;
6447        // signal thread to start
6448        mWaitWorkCV.broadcast();
6449        if (mActiveTracks.indexOf(recordTrack) < 0) {
6450            ALOGV("Record failed to start");
6451            status = BAD_VALUE;
6452            goto startError;
6453        }
6454        return status;
6455    }
6456
6457startError:
6458    if (recordTrack->isExternalTrack()) {
6459        AudioSystem::stopInput(mId, recordTrack->sessionId());
6460    }
6461    recordTrack->clearSyncStartEvent();
6462    // FIXME I wonder why we do not reset the state here?
6463    return status;
6464}
6465
6466void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6467{
6468    sp<SyncEvent> strongEvent = event.promote();
6469
6470    if (strongEvent != 0) {
6471        sp<RefBase> ptr = strongEvent->cookie().promote();
6472        if (ptr != 0) {
6473            RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6474            recordTrack->handleSyncStartEvent(strongEvent);
6475        }
6476    }
6477}
6478
6479bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
6480    ALOGV("RecordThread::stop");
6481    AutoMutex _l(mLock);
6482    if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
6483        return false;
6484    }
6485    // note that threadLoop may still be processing the track at this point [without lock]
6486    recordTrack->mState = TrackBase::PAUSING;
6487    // do not wait for mStartStopCond if exiting
6488    if (exitPending()) {
6489        return true;
6490    }
6491    // FIXME incorrect usage of wait: no explicit predicate or loop
6492    mStartStopCond.wait(mLock);
6493    // if we have been restarted, recordTrack is in mActiveTracks here
6494    if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
6495        ALOGV("Record stopped OK");
6496        return true;
6497    }
6498    return false;
6499}
6500
6501bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
6502{
6503    return false;
6504}
6505
6506status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
6507{
6508#if 0   // This branch is currently dead code, but is preserved in case it will be needed in future
6509    if (!isValidSyncEvent(event)) {
6510        return BAD_VALUE;
6511    }
6512
6513    audio_session_t eventSession = event->triggerSession();
6514    status_t ret = NAME_NOT_FOUND;
6515
6516    Mutex::Autolock _l(mLock);
6517
6518    for (size_t i = 0; i < mTracks.size(); i++) {
6519        sp<RecordTrack> track = mTracks[i];
6520        if (eventSession == track->sessionId()) {
6521            (void) track->setSyncEvent(event);
6522            ret = NO_ERROR;
6523        }
6524    }
6525    return ret;
6526#else
6527    return BAD_VALUE;
6528#endif
6529}
6530
6531// destroyTrack_l() must be called with ThreadBase::mLock held
6532void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6533{
6534    track->terminate();
6535    track->mState = TrackBase::STOPPED;
6536    // active tracks are removed by threadLoop()
6537    if (mActiveTracks.indexOf(track) < 0) {
6538        removeTrack_l(track);
6539    }
6540}
6541
6542void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6543{
6544    mTracks.remove(track);
6545    // need anything related to effects here?
6546    if (track->isFastTrack()) {
6547        ALOG_ASSERT(!mFastTrackAvail);
6548        mFastTrackAvail = true;
6549    }
6550}
6551
6552void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6553{
6554    dumpInternals(fd, args);
6555    dumpTracks(fd, args);
6556    dumpEffectChains(fd, args);
6557}
6558
6559void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6560{
6561    dprintf(fd, "\nInput thread %p:\n", this);
6562
6563    dumpBase(fd, args);
6564
6565    if (mActiveTracks.size() == 0) {
6566        dprintf(fd, "  No active record clients\n");
6567    }
6568    dprintf(fd, "  Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
6569    dprintf(fd, "  Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
6570
6571    // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6572    // while we are dumping it.  It may be inconsistent, but it won't mutate!
6573    // This is a large object so we place it on the heap.
6574    // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6575    const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6576    copy->dump(fd);
6577    delete copy;
6578}
6579
6580void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
6581{
6582    const size_t SIZE = 256;
6583    char buffer[SIZE];
6584    String8 result;
6585
6586    size_t numtracks = mTracks.size();
6587    size_t numactive = mActiveTracks.size();
6588    size_t numactiveseen = 0;
6589    dprintf(fd, "  %zu Tracks", numtracks);
6590    if (numtracks) {
6591        dprintf(fd, " of which %zu are active\n", numactive);
6592        RecordTrack::appendDumpHeader(result);
6593        for (size_t i = 0; i < numtracks ; ++i) {
6594            sp<RecordTrack> track = mTracks[i];
6595            if (track != 0) {
6596                bool active = mActiveTracks.indexOf(track) >= 0;
6597                if (active) {
6598                    numactiveseen++;
6599                }
6600                track->dump(buffer, SIZE, active);
6601                result.append(buffer);
6602            }
6603        }
6604    } else {
6605        dprintf(fd, "\n");
6606    }
6607
6608    if (numactiveseen != numactive) {
6609        snprintf(buffer, SIZE, "  The following tracks are in the active list but"
6610                " not in the track list\n");
6611        result.append(buffer);
6612        RecordTrack::appendDumpHeader(result);
6613        for (size_t i = 0; i < numactive; ++i) {
6614            sp<RecordTrack> track = mActiveTracks[i];
6615            if (mTracks.indexOf(track) < 0) {
6616                track->dump(buffer, SIZE, true);
6617                result.append(buffer);
6618            }
6619        }
6620
6621    }
6622    write(fd, result.string(), result.size());
6623}
6624
6625
6626void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6627{
6628    sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6629    RecordThread *recordThread = (RecordThread *) threadBase.get();
6630    mRsmpInFront = recordThread->mRsmpInRear;
6631    mRsmpInUnrel = 0;
6632}
6633
6634void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6635        size_t *framesAvailable, bool *hasOverrun)
6636{
6637    sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6638    RecordThread *recordThread = (RecordThread *) threadBase.get();
6639    const int32_t rear = recordThread->mRsmpInRear;
6640    const int32_t front = mRsmpInFront;
6641    const ssize_t filled = rear - front;
6642
6643    size_t framesIn;
6644    bool overrun = false;
6645    if (filled < 0) {
6646        // should not happen, but treat like a massive overrun and re-sync
6647        framesIn = 0;
6648        mRsmpInFront = rear;
6649        overrun = true;
6650    } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6651        framesIn = (size_t) filled;
6652    } else {
6653        // client is not keeping up with server, but give it latest data
6654        framesIn = recordThread->mRsmpInFrames;
6655        mRsmpInFront = /* front = */ rear - framesIn;
6656        overrun = true;
6657    }
6658    if (framesAvailable != NULL) {
6659        *framesAvailable = framesIn;
6660    }
6661    if (hasOverrun != NULL) {
6662        *hasOverrun = overrun;
6663    }
6664}
6665
6666// AudioBufferProvider interface
6667status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
6668        AudioBufferProvider::Buffer* buffer)
6669{
6670    sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6671    if (threadBase == 0) {
6672        buffer->frameCount = 0;
6673        buffer->raw = NULL;
6674        return NOT_ENOUGH_DATA;
6675    }
6676    RecordThread *recordThread = (RecordThread *) threadBase.get();
6677    int32_t rear = recordThread->mRsmpInRear;
6678    int32_t front = mRsmpInFront;
6679    ssize_t filled = rear - front;
6680    // FIXME should not be P2 (don't want to increase latency)
6681    // FIXME if client not keeping up, discard
6682    LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
6683    // 'filled' may be non-contiguous, so return only the first contiguous chunk
6684    front &= recordThread->mRsmpInFramesP2 - 1;
6685    size_t part1 = recordThread->mRsmpInFramesP2 - front;
6686    if (part1 > (size_t) filled) {
6687        part1 = filled;
6688    }
6689    size_t ask = buffer->frameCount;
6690    ALOG_ASSERT(ask > 0);
6691    if (part1 > ask) {
6692        part1 = ask;
6693    }
6694    if (part1 == 0) {
6695        // out of data is fine since the resampler will return a short-count.
6696        buffer->raw = NULL;
6697        buffer->frameCount = 0;
6698        mRsmpInUnrel = 0;
6699        return NOT_ENOUGH_DATA;
6700    }
6701
6702    buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
6703    buffer->frameCount = part1;
6704    mRsmpInUnrel = part1;
6705    return NO_ERROR;
6706}
6707
6708// AudioBufferProvider interface
6709void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6710        AudioBufferProvider::Buffer* buffer)
6711{
6712    size_t stepCount = buffer->frameCount;
6713    if (stepCount == 0) {
6714        return;
6715    }
6716    ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6717    mRsmpInUnrel -= stepCount;
6718    mRsmpInFront += stepCount;
6719    buffer->raw = NULL;
6720    buffer->frameCount = 0;
6721}
6722
6723AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
6724        audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6725        uint32_t srcSampleRate,
6726        audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6727        uint32_t dstSampleRate) :
6728            mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
6729            // mSrcFormat
6730            // mSrcSampleRate
6731            // mDstChannelMask
6732            // mDstFormat
6733            // mDstSampleRate
6734            // mSrcChannelCount
6735            // mDstChannelCount
6736            // mDstFrameSize
6737            mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
6738            mResampler(NULL),
6739            mIsLegacyDownmix(false),
6740            mIsLegacyUpmix(false),
6741            mRequiresFloat(false),
6742            mInputConverterProvider(NULL)
6743{
6744    (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
6745            dstChannelMask, dstFormat, dstSampleRate);
6746}
6747
6748AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
6749    free(mBuf);
6750    delete mResampler;
6751    delete mInputConverterProvider;
6752}
6753
6754size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
6755        AudioBufferProvider *provider, size_t frames)
6756{
6757    if (mInputConverterProvider != NULL) {
6758        mInputConverterProvider->setBufferProvider(provider);
6759        provider = mInputConverterProvider;
6760    }
6761
6762    if (mResampler == NULL) {
6763        ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6764                mSrcSampleRate, mSrcFormat, mDstFormat);
6765
6766        AudioBufferProvider::Buffer buffer;
6767        for (size_t i = frames; i > 0; ) {
6768            buffer.frameCount = i;
6769            status_t status = provider->getNextBuffer(&buffer);
6770            if (status != OK || buffer.frameCount == 0) {
6771                frames -= i; // cannot fill request.
6772                break;
6773            }
6774            // format convert to destination buffer
6775            convertNoResampler(dst, buffer.raw, buffer.frameCount);
6776
6777            dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
6778            i -= buffer.frameCount;
6779            provider->releaseBuffer(&buffer);
6780        }
6781    } else {
6782         ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6783                 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
6784
6785         // reallocate buffer if needed
6786         if (mBufFrameSize != 0 && mBufFrames < frames) {
6787             free(mBuf);
6788             mBufFrames = frames;
6789             (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6790         }
6791        // resampler accumulates, but we only have one source track
6792        memset(mBuf, 0, frames * mBufFrameSize);
6793        frames = mResampler->resample((int32_t*)mBuf, frames, provider);
6794        // format convert to destination buffer
6795        convertResampler(dst, mBuf, frames);
6796    }
6797    return frames;
6798}
6799
6800status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
6801        audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6802        uint32_t srcSampleRate,
6803        audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6804        uint32_t dstSampleRate)
6805{
6806    // quick evaluation if there is any change.
6807    if (mSrcFormat == srcFormat
6808            && mSrcChannelMask == srcChannelMask
6809            && mSrcSampleRate == srcSampleRate
6810            && mDstFormat == dstFormat
6811            && mDstChannelMask == dstChannelMask
6812            && mDstSampleRate == dstSampleRate) {
6813        return NO_ERROR;
6814    }
6815
6816    ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x"
6817            "  srcFormat:%#x dstFormat:%#x  srcRate:%u dstRate:%u",
6818            srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate);
6819    const bool valid =
6820            audio_is_input_channel(srcChannelMask)
6821            && audio_is_input_channel(dstChannelMask)
6822            && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
6823            && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
6824            && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
6825            ; // no upsampling checks for now
6826    if (!valid) {
6827        return BAD_VALUE;
6828    }
6829
6830    mSrcFormat = srcFormat;
6831    mSrcChannelMask = srcChannelMask;
6832    mSrcSampleRate = srcSampleRate;
6833    mDstFormat = dstFormat;
6834    mDstChannelMask = dstChannelMask;
6835    mDstSampleRate = dstSampleRate;
6836
6837    // compute derived parameters
6838    mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
6839    mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
6840    mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
6841
6842    // do we need to resample?
6843    delete mResampler;
6844    mResampler = NULL;
6845    if (mSrcSampleRate != mDstSampleRate) {
6846        mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
6847                mSrcChannelCount, mDstSampleRate);
6848        mResampler->setSampleRate(mSrcSampleRate);
6849        mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
6850    }
6851
6852    // are we running legacy channel conversion modes?
6853    mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
6854                            || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
6855                   && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
6856    mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
6857                   && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
6858                            || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
6859
6860    // do we need to process in float?
6861    mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
6862
6863    // do we need a staging buffer to convert for destination (we can still optimize this)?
6864    // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
6865    if (mResampler != NULL) {
6866        mBufFrameSize = max(mSrcChannelCount, FCC_2)
6867                * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
6868    } else if (mIsLegacyUpmix || mIsLegacyDownmix) { // legacy modes always float
6869        mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
6870    } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
6871        mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
6872    } else {
6873        mBufFrameSize = 0;
6874    }
6875    mBufFrames = 0; // force the buffer to be resized.
6876
6877    // do we need an input converter buffer provider to give us float?
6878    delete mInputConverterProvider;
6879    mInputConverterProvider = NULL;
6880    if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
6881        mInputConverterProvider = new ReformatBufferProvider(
6882                audio_channel_count_from_in_mask(mSrcChannelMask),
6883                mSrcFormat,
6884                AUDIO_FORMAT_PCM_FLOAT,
6885                256 /* provider buffer frame count */);
6886    }
6887
6888    // do we need a remixer to do channel mask conversion
6889    if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
6890        (void) memcpy_by_index_array_initialization_from_channel_mask(
6891                mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
6892    }
6893    return NO_ERROR;
6894}
6895
6896void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
6897        void *dst, const void *src, size_t frames)
6898{
6899    // src is native type unless there is legacy upmix or downmix, whereupon it is float.
6900    if (mBufFrameSize != 0 && mBufFrames < frames) {
6901        free(mBuf);
6902        mBufFrames = frames;
6903        (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6904    }
6905    // do we need to do legacy upmix and downmix?
6906    if (mIsLegacyUpmix || mIsLegacyDownmix) {
6907        void *dstBuf = mBuf != NULL ? mBuf : dst;
6908        if (mIsLegacyUpmix) {
6909            upmix_to_stereo_float_from_mono_float((float *)dstBuf,
6910                    (const float *)src, frames);
6911        } else /*mIsLegacyDownmix */ {
6912            downmix_to_mono_float_from_stereo_float((float *)dstBuf,
6913                    (const float *)src, frames);
6914        }
6915        if (mBuf != NULL) {
6916            memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
6917                    frames * mDstChannelCount);
6918        }
6919        return;
6920    }
6921    // do we need to do channel mask conversion?
6922    if (mSrcChannelMask != mDstChannelMask) {
6923        void *dstBuf = mBuf != NULL ? mBuf : dst;
6924        memcpy_by_index_array(dstBuf, mDstChannelCount,
6925                src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
6926        if (dstBuf == dst) {
6927            return; // format is the same
6928        }
6929    }
6930    // convert to destination buffer
6931    const void *convertBuf = mBuf != NULL ? mBuf : src;
6932    memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
6933            frames * mDstChannelCount);
6934}
6935
6936void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
6937        void *dst, /*not-a-const*/ void *src, size_t frames)
6938{
6939    // src buffer format is ALWAYS float when entering this routine
6940    if (mIsLegacyUpmix) {
6941        ; // mono to stereo already handled by resampler
6942    } else if (mIsLegacyDownmix
6943            || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
6944        // the resampler outputs stereo for mono input channel (a feature?)
6945        // must convert to mono
6946        downmix_to_mono_float_from_stereo_float((float *)src,
6947                (const float *)src, frames);
6948    } else if (mSrcChannelMask != mDstChannelMask) {
6949        // convert to mono channel again for channel mask conversion (could be skipped
6950        // with further optimization).
6951        if (mSrcChannelCount == 1) {
6952            downmix_to_mono_float_from_stereo_float((float *)src,
6953                (const float *)src, frames);
6954        }
6955        // convert to destination format (in place, OK as float is larger than other types)
6956        if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
6957            memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6958                    frames * mSrcChannelCount);
6959        }
6960        // channel convert and save to dst
6961        memcpy_by_index_array(dst, mDstChannelCount,
6962                src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
6963        return;
6964    }
6965    // convert to destination format and save to dst
6966    memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6967            frames * mDstChannelCount);
6968}
6969
6970bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
6971                                                        status_t& status)
6972{
6973    bool reconfig = false;
6974
6975    status = NO_ERROR;
6976
6977    audio_format_t reqFormat = mFormat;
6978    uint32_t samplingRate = mSampleRate;
6979    // TODO this may change if we want to support capture from HDMI PCM multi channel (e.g on TVs).
6980    audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
6981
6982    AudioParameter param = AudioParameter(keyValuePair);
6983    int value;
6984
6985    // scope for AutoPark extends to end of method
6986    AutoPark<FastCapture> park(mFastCapture);
6987
6988    // TODO Investigate when this code runs. Check with audio policy when a sample rate and
6989    //      channel count change can be requested. Do we mandate the first client defines the
6990    //      HAL sampling rate and channel count or do we allow changes on the fly?
6991    if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6992        samplingRate = value;
6993        reconfig = true;
6994    }
6995    if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
6996        if (!audio_is_linear_pcm((audio_format_t) value)) {
6997            status = BAD_VALUE;
6998        } else {
6999            reqFormat = (audio_format_t) value;
7000            reconfig = true;
7001        }
7002    }
7003    if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7004        audio_channel_mask_t mask = (audio_channel_mask_t) value;
7005        if (!audio_is_input_channel(mask) ||
7006                audio_channel_count_from_in_mask(mask) > FCC_8) {
7007            status = BAD_VALUE;
7008        } else {
7009            channelMask = mask;
7010            reconfig = true;
7011        }
7012    }
7013    if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7014        // do not accept frame count changes if tracks are open as the track buffer
7015        // size depends on frame count and correct behavior would not be guaranteed
7016        // if frame count is changed after track creation
7017        if (mActiveTracks.size() > 0) {
7018            status = INVALID_OPERATION;
7019        } else {
7020            reconfig = true;
7021        }
7022    }
7023    if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7024        // forward device change to effects that have requested to be
7025        // aware of attached audio device.
7026        for (size_t i = 0; i < mEffectChains.size(); i++) {
7027            mEffectChains[i]->setDevice_l(value);
7028        }
7029
7030        // store input device and output device but do not forward output device to audio HAL.
7031        // Note that status is ignored by the caller for output device
7032        // (see AudioFlinger::setParameters()
7033        if (audio_is_output_devices(value)) {
7034            mOutDevice = value;
7035            status = BAD_VALUE;
7036        } else {
7037            mInDevice = value;
7038            if (value != AUDIO_DEVICE_NONE) {
7039                mPrevInDevice = value;
7040            }
7041            // disable AEC and NS if the device is a BT SCO headset supporting those
7042            // pre processings
7043            if (mTracks.size() > 0) {
7044                bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7045                                    mAudioFlinger->btNrecIsOff();
7046                for (size_t i = 0; i < mTracks.size(); i++) {
7047                    sp<RecordTrack> track = mTracks[i];
7048                    setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7049                    setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7050                }
7051            }
7052        }
7053    }
7054    if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7055            mAudioSource != (audio_source_t)value) {
7056        // forward device change to effects that have requested to be
7057        // aware of attached audio device.
7058        for (size_t i = 0; i < mEffectChains.size(); i++) {
7059            mEffectChains[i]->setAudioSource_l((audio_source_t)value);
7060        }
7061        mAudioSource = (audio_source_t)value;
7062    }
7063
7064    if (status == NO_ERROR) {
7065        status = mInput->stream->common.set_parameters(&mInput->stream->common,
7066                keyValuePair.string());
7067        if (status == INVALID_OPERATION) {
7068            inputStandBy();
7069            status = mInput->stream->common.set_parameters(&mInput->stream->common,
7070                    keyValuePair.string());
7071        }
7072        if (reconfig) {
7073            if (status == BAD_VALUE &&
7074                audio_is_linear_pcm(mInput->stream->common.get_format(&mInput->stream->common)) &&
7075                audio_is_linear_pcm(reqFormat) &&
7076                (mInput->stream->common.get_sample_rate(&mInput->stream->common)
7077                        <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate)) &&
7078                audio_channel_count_from_in_mask(
7079                        mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_8) {
7080                status = NO_ERROR;
7081            }
7082            if (status == NO_ERROR) {
7083                readInputParameters_l();
7084                sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7085            }
7086        }
7087    }
7088
7089    return reconfig;
7090}
7091
7092String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7093{
7094    Mutex::Autolock _l(mLock);
7095    if (initCheck() != NO_ERROR) {
7096        return String8();
7097    }
7098
7099    char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
7100    const String8 out_s8(s);
7101    free(s);
7102    return out_s8;
7103}
7104
7105void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
7106    sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7107
7108    desc->mIoHandle = mId;
7109
7110    switch (event) {
7111    case AUDIO_INPUT_OPENED:
7112    case AUDIO_INPUT_CONFIG_CHANGED:
7113        desc->mPatch = mPatch;
7114        desc->mChannelMask = mChannelMask;
7115        desc->mSamplingRate = mSampleRate;
7116        desc->mFormat = mFormat;
7117        desc->mFrameCount = mFrameCount;
7118        desc->mLatency = 0;
7119        break;
7120
7121    case AUDIO_INPUT_CLOSED:
7122    default:
7123        break;
7124    }
7125    mAudioFlinger->ioConfigChanged(event, desc, pid);
7126}
7127
7128void AudioFlinger::RecordThread::readInputParameters_l()
7129{
7130    mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
7131    mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
7132    mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
7133    if (mChannelCount > FCC_8) {
7134        ALOGE("HAL channel count %d > %d", mChannelCount, FCC_8);
7135    }
7136    mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
7137    mFormat = mHALFormat;
7138    if (!audio_is_linear_pcm(mFormat)) {
7139        ALOGE("HAL format %#x is not linear pcm", mFormat);
7140    }
7141    mFrameSize = audio_stream_in_frame_size(mInput->stream);
7142    mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
7143    mFrameCount = mBufferSize / mFrameSize;
7144    // This is the formula for calculating the temporary buffer size.
7145    // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
7146    // 1 full output buffer, regardless of the alignment of the available input.
7147    // The value is somewhat arbitrary, and could probably be even larger.
7148    // A larger value should allow more old data to be read after a track calls start(),
7149    // without increasing latency.
7150    //
7151    // Note this is independent of the maximum downsampling ratio permitted for capture.
7152    mRsmpInFrames = mFrameCount * 7;
7153    mRsmpInFramesP2 = roundup(mRsmpInFrames);
7154    free(mRsmpInBuffer);
7155    mRsmpInBuffer = NULL;
7156
7157    // TODO optimize audio capture buffer sizes ...
7158    // Here we calculate the size of the sliding buffer used as a source
7159    // for resampling.  mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7160    // For current HAL frame counts, this is usually 2048 = 40 ms.  It would
7161    // be better to have it derived from the pipe depth in the long term.
7162    // The current value is higher than necessary.  However it should not add to latency.
7163
7164    // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
7165    size_t bufferSize = (mRsmpInFramesP2 + mFrameCount - 1) * mFrameSize;
7166    (void)posix_memalign(&mRsmpInBuffer, 32, bufferSize);
7167    memset(mRsmpInBuffer, 0, bufferSize); // if posix_memalign fails, will segv here.
7168
7169    // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7170    // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
7171}
7172
7173uint32_t AudioFlinger::RecordThread::getInputFramesLost()
7174{
7175    Mutex::Autolock _l(mLock);
7176    if (initCheck() != NO_ERROR) {
7177        return 0;
7178    }
7179
7180    return mInput->stream->get_input_frames_lost(mInput->stream);
7181}
7182
7183uint32_t AudioFlinger::RecordThread::hasAudioSession(audio_session_t sessionId) const
7184{
7185    Mutex::Autolock _l(mLock);
7186    uint32_t result = 0;
7187    if (getEffectChain_l(sessionId) != 0) {
7188        result = EFFECT_SESSION;
7189    }
7190
7191    for (size_t i = 0; i < mTracks.size(); ++i) {
7192        if (sessionId == mTracks[i]->sessionId()) {
7193            result |= TRACK_SESSION;
7194            break;
7195        }
7196    }
7197
7198    return result;
7199}
7200
7201KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
7202{
7203    KeyedVector<audio_session_t, bool> ids;
7204    Mutex::Autolock _l(mLock);
7205    for (size_t j = 0; j < mTracks.size(); ++j) {
7206        sp<RecordThread::RecordTrack> track = mTracks[j];
7207        audio_session_t sessionId = track->sessionId();
7208        if (ids.indexOfKey(sessionId) < 0) {
7209            ids.add(sessionId, true);
7210        }
7211    }
7212    return ids;
7213}
7214
7215AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7216{
7217    Mutex::Autolock _l(mLock);
7218    AudioStreamIn *input = mInput;
7219    mInput = NULL;
7220    return input;
7221}
7222
7223// this method must always be called either with ThreadBase mLock held or inside the thread loop
7224audio_stream_t* AudioFlinger::RecordThread::stream() const
7225{
7226    if (mInput == NULL) {
7227        return NULL;
7228    }
7229    return &mInput->stream->common;
7230}
7231
7232status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7233{
7234    // only one chain per input thread
7235    if (mEffectChains.size() != 0) {
7236        ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
7237        return INVALID_OPERATION;
7238    }
7239    ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
7240    chain->setThread(this);
7241    chain->setInBuffer(NULL);
7242    chain->setOutBuffer(NULL);
7243
7244    checkSuspendOnAddEffectChain_l(chain);
7245
7246    // make sure enabled pre processing effects state is communicated to the HAL as we
7247    // just moved them to a new input stream.
7248    chain->syncHalEffectsState();
7249
7250    mEffectChains.add(chain);
7251
7252    return NO_ERROR;
7253}
7254
7255size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7256{
7257    ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7258    ALOGW_IF(mEffectChains.size() != 1,
7259            "removeEffectChain_l() %p invalid chain size %zu on thread %p",
7260            chain.get(), mEffectChains.size(), this);
7261    if (mEffectChains.size() == 1) {
7262        mEffectChains.removeAt(0);
7263    }
7264    return 0;
7265}
7266
7267status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7268                                                          audio_patch_handle_t *handle)
7269{
7270    status_t status = NO_ERROR;
7271
7272    // store new device and send to effects
7273    mInDevice = patch->sources[0].ext.device.type;
7274    mPatch = *patch;
7275    for (size_t i = 0; i < mEffectChains.size(); i++) {
7276        mEffectChains[i]->setDevice_l(mInDevice);
7277    }
7278
7279    // disable AEC and NS if the device is a BT SCO headset supporting those
7280    // pre processings
7281    if (mTracks.size() > 0) {
7282        bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7283                            mAudioFlinger->btNrecIsOff();
7284        for (size_t i = 0; i < mTracks.size(); i++) {
7285            sp<RecordTrack> track = mTracks[i];
7286            setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7287            setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7288        }
7289    }
7290
7291    // store new source and send to effects
7292    if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7293        mAudioSource = patch->sinks[0].ext.mix.usecase.source;
7294        for (size_t i = 0; i < mEffectChains.size(); i++) {
7295            mEffectChains[i]->setAudioSource_l(mAudioSource);
7296        }
7297    }
7298
7299    if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
7300        audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7301        status = hwDevice->create_audio_patch(hwDevice,
7302                                               patch->num_sources,
7303                                               patch->sources,
7304                                               patch->num_sinks,
7305                                               patch->sinks,
7306                                               handle);
7307    } else {
7308        char *address;
7309        if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7310            address = audio_device_address_to_parameter(
7311                                                patch->sources[0].ext.device.type,
7312                                                patch->sources[0].ext.device.address);
7313        } else {
7314            address = (char *)calloc(1, 1);
7315        }
7316        AudioParameter param = AudioParameter(String8(address));
7317        free(address);
7318        param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING),
7319                     (int)patch->sources[0].ext.device.type);
7320        param.addInt(String8(AUDIO_PARAMETER_STREAM_INPUT_SOURCE),
7321                                         (int)patch->sinks[0].ext.mix.usecase.source);
7322        status = mInput->stream->common.set_parameters(&mInput->stream->common,
7323                param.toString().string());
7324        *handle = AUDIO_PATCH_HANDLE_NONE;
7325    }
7326
7327    if (mInDevice != mPrevInDevice) {
7328        sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7329        mPrevInDevice = mInDevice;
7330    }
7331
7332    return status;
7333}
7334
7335status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7336{
7337    status_t status = NO_ERROR;
7338
7339    mInDevice = AUDIO_DEVICE_NONE;
7340
7341    if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
7342        audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7343        status = hwDevice->release_audio_patch(hwDevice, handle);
7344    } else {
7345        AudioParameter param;
7346        param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
7347        status = mInput->stream->common.set_parameters(&mInput->stream->common,
7348                param.toString().string());
7349    }
7350    return status;
7351}
7352
7353void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7354{
7355    Mutex::Autolock _l(mLock);
7356    mTracks.add(record);
7357}
7358
7359void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7360{
7361    Mutex::Autolock _l(mLock);
7362    destroyTrack_l(record);
7363}
7364
7365void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7366{
7367    ThreadBase::getAudioPortConfig(config);
7368    config->role = AUDIO_PORT_ROLE_SINK;
7369    config->ext.mix.hw_module = mInput->audioHwDev->handle();
7370    config->ext.mix.usecase.source = mAudioSource;
7371}
7372
7373} // namespace android
7374