181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent/*
281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent**
381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent** Copyright 2012, The Android Open Source Project
481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent**
581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent** Licensed under the Apache License, Version 2.0 (the "License");
681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent** you may not use this file except in compliance with the License.
781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent** You may obtain a copy of the License at
881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent**
981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent**     http://www.apache.org/licenses/LICENSE-2.0
1081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent**
1181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent** Unless required by applicable law or agreed to in writing, software
1281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent** distributed under the License is distributed on an "AS IS" BASIS,
1381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent** See the License for the specific language governing permissions and
1581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent** limitations under the License.
1681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent*/
1781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
1881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
1981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#define LOG_TAG "AudioFlinger"
2081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent//#define LOG_NDEBUG 0
21371eb9756c32109ea572b91216b19bb623f6d3fdAlex Ray#define ATRACE_TAG ATRACE_TAG_AUDIO
2281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
23153b9fe667e6e78e0218ff0159353097428c7657Glenn Kasten#include "Configuration.h"
2481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#include <math.h>
2581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#include <fcntl.h>
26ad8510a339ffab330c2c46e5c247dd1cf9e15c22Glenn Kasten#include <linux/futex.h>
2781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#include <sys/stat.h>
28ad8510a339ffab330c2c46e5c247dd1cf9e15c22Glenn Kasten#include <sys/syscall.h>
2981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#include <cutils/properties.h>
301ab85ec401801ef9a9184650d0f5a1639b45eeb9Glenn Kasten#include <media/AudioParameter.h>
31cd04484f4837b8ca0041d118286ab6a98e84fc75Andy Hung#include <media/AudioResamplerPublic.h>
3281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#include <utils/Log.h>
33371eb9756c32109ea572b91216b19bb623f6d3fdAlex Ray#include <utils/Trace.h>
3481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
3581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#include <private/media/AudioTrackShared.h>
3681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#include <hardware/audio.h>
3781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#include <audio_effects/effect_ns.h>
3881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#include <audio_effects/effect_aec.h>
3981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#include <audio_utils/primitives.h>
4098ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung#include <audio_utils/format.h>
41c56f3426099a3cf2d07ccff8886050c7fbce140fGlenn Kasten#include <audio_utils/minifloat.h>
4281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
4381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// NBAIO implementations
446dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten#include <media/nbaio/AudioStreamInSource.h>
4581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#include <media/nbaio/AudioStreamOutSink.h>
4681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#include <media/nbaio/MonoPipe.h>
4781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#include <media/nbaio/MonoPipeReader.h>
4881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#include <media/nbaio/Pipe.h>
4981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#include <media/nbaio/PipeReader.h>
5081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#include <media/nbaio/SourceAudioBufferProvider.h>
5181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
5281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#include <powermanager/PowerManager.h>
5381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
5481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#include <common_time/cc_helper.h>
5581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#include <common_time/local_clock.h>
5681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
5781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#include "AudioFlinger.h"
5881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#include "AudioMixer.h"
59d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung#include "BufferProviders.h"
6081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#include "FastMixer.h"
616dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten#include "FastCapture.h"
6281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#include "ServiceUtilities.h"
6381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#include "SchedulingPolicyService.h"
6481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
6581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#ifdef ADD_BATTERY_DATA
6681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#include <media/IMediaPlayerService.h>
6781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#include <media/IMediaDeathNotifier.h>
6881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#endif
6981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
7081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#ifdef DEBUG_CPU_USAGE
7181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#include <cpustats/CentralTendencyStatistics.h>
7281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#include <cpustats/ThreadCpuUsage.h>
7381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#endif
7481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
7581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// ----------------------------------------------------------------------------
7681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
7781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// Note: the following macro is used for extremely verbose logging message.  In
7881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
7981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// 0; but one side effect of this is to turn all LOGV's as well.  Some messages
8081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// are so verbose that we want to suppress them even when we have ALOG_ASSERT
8181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// turned on.  Do not uncomment the #def below unless you really know what you
8281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// are doing and want to see all of the extremely verbose messages.
8381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent//#define VERY_VERY_VERBOSE_LOGGING
8481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#ifdef VERY_VERY_VERBOSE_LOGGING
8581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#define ALOGVV ALOGV
8681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#else
8781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#define ALOGVV(a...) do { } while(0)
8881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#endif
8981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
906770c6faa3467c92eabc5ec9b23d60eb556a0d03Andy Hung// TODO: Move these macro/inlines to a header file.
9149d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten#define max(a, b) ((a) > (b) ? (a) : (b))
926770c6faa3467c92eabc5ec9b23d60eb556a0d03Andy Hungtemplate <typename T>
936770c6faa3467c92eabc5ec9b23d60eb556a0d03Andy Hungstatic inline T min(const T& a, const T& b)
946770c6faa3467c92eabc5ec9b23d60eb556a0d03Andy Hung{
956770c6faa3467c92eabc5ec9b23d60eb556a0d03Andy Hung    return a < b ? a : b;
966770c6faa3467c92eabc5ec9b23d60eb556a0d03Andy Hung}
9749d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten
98d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung#ifndef ARRAY_SIZE
99d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
100d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung#endif
101d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung
10281784c37c61b09289654b979567a42bf73cd2b12Eric Laurentnamespace android {
10381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
10481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// retry counts for buffer fill timeout
10581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// 50 * ~20msecs = 1 second
10681784c37c61b09289654b979567a42bf73cd2b12Eric Laurentstatic const int8_t kMaxTrackRetries = 50;
10781784c37c61b09289654b979567a42bf73cd2b12Eric Laurentstatic const int8_t kMaxTrackStartupRetries = 50;
10881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// allow less retry attempts on direct output thread.
10981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// direct outputs can be a scarce resource in audio hardware and should
11081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// be released as quickly as possible.
11181784c37c61b09289654b979567a42bf73cd2b12Eric Laurentstatic const int8_t kMaxTrackRetriesDirect = 2;
11281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
11381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// don't warn about blocked writes or record buffer overflows more often than this
11481784c37c61b09289654b979567a42bf73cd2b12Eric Laurentstatic const nsecs_t kWarningThrottleNs = seconds(5);
11581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
11681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// RecordThread loop sleep time upon application overrun or audio HAL read error
11781784c37c61b09289654b979567a42bf73cd2b12Eric Laurentstatic const int kRecordThreadSleepUs = 5000;
11881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
1191035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent// maximum time to wait in sendConfigEvent_l() for a status to be received
1201035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurentstatic const nsecs_t kConfigEventTimeoutNs = seconds(2);
12181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
12281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// minimum sleep time for the mixer thread loop when tracks are active but in underrun
12381784c37c61b09289654b979567a42bf73cd2b12Eric Laurentstatic const uint32_t kMinThreadSleepTimeUs = 5000;
12481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// maximum divider applied to the active sleep time in the mixer thread loop
12581784c37c61b09289654b979567a42bf73cd2b12Eric Laurentstatic const uint32_t kMaxThreadSleepTimeShift = 2;
12681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
12709a5007b17acb49d25cfa386a2e2534d942e8854Andy Hung// minimum normal sink buffer size, expressed in milliseconds rather than frames
128eb9487e10294a4e73977f460f30eeaff503acd21Glenn Kasten// FIXME This should be based on experimentally observed scheduling jitter
12909a5007b17acb49d25cfa386a2e2534d942e8854Andy Hungstatic const uint32_t kMinNormalSinkBufferSizeMs = 20;
13009a5007b17acb49d25cfa386a2e2534d942e8854Andy Hung// maximum normal sink buffer size
13109a5007b17acb49d25cfa386a2e2534d942e8854Andy Hungstatic const uint32_t kMaxNormalSinkBufferSizeMs = 24;
13281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
133eb9487e10294a4e73977f460f30eeaff503acd21Glenn Kasten// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
134eb9487e10294a4e73977f460f30eeaff503acd21Glenn Kasten// FIXME This should be based on experimentally observed scheduling jitter
135eb9487e10294a4e73977f460f30eeaff503acd21Glenn Kastenstatic const uint32_t kMinNormalCaptureBufferSizeMs = 12;
136eb9487e10294a4e73977f460f30eeaff503acd21Glenn Kasten
137972a173d7d1de1a3b5a617aae3e2abb6e05ae02dEric Laurent// Offloaded output thread standby delay: allows track transition without going to standby
138972a173d7d1de1a3b5a617aae3e2abb6e05ae02dEric Laurentstatic const nsecs_t kOffloadStandbyDelayNs = seconds(1);
139972a173d7d1de1a3b5a617aae3e2abb6e05ae02dEric Laurent
14081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// Whether to use fast mixer
14181784c37c61b09289654b979567a42bf73cd2b12Eric Laurentstatic const enum {
14281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    FastMixer_Never,    // never initialize or use: for debugging only
14381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    FastMixer_Always,   // always initialize and use, even if not needed: for debugging only
14481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                        // normal mixer multiplier is 1
14581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    FastMixer_Static,   // initialize if needed, then use all the time if initialized,
14681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                        // multiplier is calculated based on min & max normal mixer buffer size
14781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    FastMixer_Dynamic,  // initialize if needed, then use dynamically depending on track load,
14881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                        // multiplier is calculated based on min & max normal mixer buffer size
14981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // FIXME for FastMixer_Dynamic:
15081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    //  Supporting this option will require fixing HALs that can't handle large writes.
15181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    //  For example, one HAL implementation returns an error from a large write,
15281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    //  and another HAL implementation corrupts memory, possibly in the sample rate converter.
15381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    //  We could either fix the HAL implementations, or provide a wrapper that breaks
15481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    //  up large writes into smaller ones, and the wrapper would need to deal with scheduler.
15581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent} kUseFastMixer = FastMixer_Static;
15681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
1576dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten// Whether to use fast capture
1586dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kastenstatic const enum {
1596dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    FastCapture_Never,  // never initialize or use: for debugging only
1606dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    FastCapture_Always, // always initialize and use, even if not needed: for debugging only
1616dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    FastCapture_Static, // initialize if needed, then use all the time if initialized
1626dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten} kUseFastCapture = FastCapture_Static;
1636dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten
16481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// Priorities for requestPriority
16581784c37c61b09289654b979567a42bf73cd2b12Eric Laurentstatic const int kPriorityAudioApp = 2;
16681784c37c61b09289654b979567a42bf73cd2b12Eric Laurentstatic const int kPriorityFastMixer = 3;
1676dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kastenstatic const int kPriorityFastCapture = 3;
16881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
16981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
17081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// for the track.  The client then sub-divides this into smaller buffers for its use.
171b5fed68bcdd6f44424c9e4d12bfe9a3ff51bd62eGlenn Kasten// Currently the client uses N-buffering by default, but doesn't tell us about the value of N.
172b5fed68bcdd6f44424c9e4d12bfe9a3ff51bd62eGlenn Kasten// So for now we just assume that client is double-buffered for fast tracks.
173b5fed68bcdd6f44424c9e4d12bfe9a3ff51bd62eGlenn Kasten// FIXME It would be better for client to tell AudioFlinger the value of N,
174b5fed68bcdd6f44424c9e4d12bfe9a3ff51bd62eGlenn Kasten// so AudioFlinger could allocate the right amount of memory.
17581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// See the client's minBufCount and mNotificationFramesAct calculations for details.
1760349009fd19f89f8414c428f6b71b369f7546085Glenn Kasten
1770349009fd19f89f8414c428f6b71b369f7546085Glenn Kasten// This is the default value, if not specified by property.
178b5fed68bcdd6f44424c9e4d12bfe9a3ff51bd62eGlenn Kastenstatic const int kFastTrackMultiplier = 2;
17981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
1800349009fd19f89f8414c428f6b71b369f7546085Glenn Kasten// The minimum and maximum allowed values
1810349009fd19f89f8414c428f6b71b369f7546085Glenn Kastenstatic const int kFastTrackMultiplierMin = 1;
1820349009fd19f89f8414c428f6b71b369f7546085Glenn Kastenstatic const int kFastTrackMultiplierMax = 2;
1830349009fd19f89f8414c428f6b71b369f7546085Glenn Kasten
1840349009fd19f89f8414c428f6b71b369f7546085Glenn Kasten// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
1850349009fd19f89f8414c428f6b71b369f7546085Glenn Kastenstatic int sFastTrackMultiplier = kFastTrackMultiplier;
1860349009fd19f89f8414c428f6b71b369f7546085Glenn Kasten
187b880f5e5fc07397ddd09a94ba18bdf4fa62aae00Glenn Kasten// See Thread::readOnlyHeap().
188b880f5e5fc07397ddd09a94ba18bdf4fa62aae00Glenn Kasten// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
189b880f5e5fc07397ddd09a94ba18bdf4fa62aae00Glenn Kasten// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
190b880f5e5fc07397ddd09a94ba18bdf4fa62aae00Glenn Kasten// and that all "fast" AudioRecord clients read from.  In either case, the size can be small.
1919f81de3452dfb2385bd57dc05456a045174a1ab1Glenn Kastenstatic const size_t kRecordThreadReadOnlyHeapSize = 0x2000;
192b880f5e5fc07397ddd09a94ba18bdf4fa62aae00Glenn Kasten
19381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// ----------------------------------------------------------------------------
19481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
1950349009fd19f89f8414c428f6b71b369f7546085Glenn Kastenstatic pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
1960349009fd19f89f8414c428f6b71b369f7546085Glenn Kasten
1970349009fd19f89f8414c428f6b71b369f7546085Glenn Kastenstatic void sFastTrackMultiplierInit()
1980349009fd19f89f8414c428f6b71b369f7546085Glenn Kasten{
1990349009fd19f89f8414c428f6b71b369f7546085Glenn Kasten    char value[PROPERTY_VALUE_MAX];
2000349009fd19f89f8414c428f6b71b369f7546085Glenn Kasten    if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
2010349009fd19f89f8414c428f6b71b369f7546085Glenn Kasten        char *endptr;
2020349009fd19f89f8414c428f6b71b369f7546085Glenn Kasten        unsigned long ul = strtoul(value, &endptr, 0);
2030349009fd19f89f8414c428f6b71b369f7546085Glenn Kasten        if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
2040349009fd19f89f8414c428f6b71b369f7546085Glenn Kasten            sFastTrackMultiplier = (int) ul;
2050349009fd19f89f8414c428f6b71b369f7546085Glenn Kasten        }
2060349009fd19f89f8414c428f6b71b369f7546085Glenn Kasten    }
2070349009fd19f89f8414c428f6b71b369f7546085Glenn Kasten}
2080349009fd19f89f8414c428f6b71b369f7546085Glenn Kasten
2090349009fd19f89f8414c428f6b71b369f7546085Glenn Kasten// ----------------------------------------------------------------------------
2100349009fd19f89f8414c428f6b71b369f7546085Glenn Kasten
21181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#ifdef ADD_BATTERY_DATA
21281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// To collect the amplifier usage
21381784c37c61b09289654b979567a42bf73cd2b12Eric Laurentstatic void addBatteryData(uint32_t params) {
21481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
21581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (service == NULL) {
21681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // it already logged
21781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        return;
21881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
21981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
22081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    service->addBatteryData(params);
22181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
22281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#endif
22381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
22481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
22581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// ----------------------------------------------------------------------------
22681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent//      CPU Stats
22781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// ----------------------------------------------------------------------------
22881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
22981784c37c61b09289654b979567a42bf73cd2b12Eric Laurentclass CpuStats {
23081784c37c61b09289654b979567a42bf73cd2b12Eric Laurentpublic:
23181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    CpuStats();
23281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    void sample(const String8 &title);
23381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#ifdef DEBUG_CPU_USAGE
23481784c37c61b09289654b979567a42bf73cd2b12Eric Laurentprivate:
23581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    ThreadCpuUsage mCpuUsage;           // instantaneous thread CPU usage in wall clock ns
23681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
23781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
23881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
23981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
24081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    int mCpuNum;                        // thread's current CPU number
24181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    int mCpukHz;                        // frequency of thread's current CPU in kHz
24281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#endif
24381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent};
24481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
24581784c37c61b09289654b979567a42bf73cd2b12Eric LaurentCpuStats::CpuStats()
24681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#ifdef DEBUG_CPU_USAGE
24781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    : mCpuNum(-1), mCpukHz(-1)
24881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#endif
24981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
25081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
25181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
2520f11b51a57bc9062c4fe8af73747319cedabc5d6Glenn Kastenvoid CpuStats::sample(const String8 &title
2530f11b51a57bc9062c4fe8af73747319cedabc5d6Glenn Kasten#ifndef DEBUG_CPU_USAGE
2540f11b51a57bc9062c4fe8af73747319cedabc5d6Glenn Kasten                __unused
2550f11b51a57bc9062c4fe8af73747319cedabc5d6Glenn Kasten#endif
2560f11b51a57bc9062c4fe8af73747319cedabc5d6Glenn Kasten        ) {
25781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#ifdef DEBUG_CPU_USAGE
25881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // get current thread's delta CPU time in wall clock ns
25981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    double wcNs;
26081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    bool valid = mCpuUsage.sampleAndEnable(wcNs);
26181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
26281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // record sample for wall clock statistics
26381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (valid) {
26481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mWcStats.sample(wcNs);
26581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
26681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
26781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // get the current CPU number
26881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    int cpuNum = sched_getcpu();
26981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
27081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // get the current CPU frequency in kHz
27181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    int cpukHz = mCpuUsage.getCpukHz(cpuNum);
27281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
27381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // check if either CPU number or frequency changed
27481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
27581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mCpuNum = cpuNum;
27681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mCpukHz = cpukHz;
27781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // ignore sample for purposes of cycles
27881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        valid = false;
27981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
28081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
28181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // if no change in CPU number or frequency, then record sample for cycle statistics
28281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (valid && mCpukHz > 0) {
28381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        double cycles = wcNs * cpukHz * 0.000001;
28481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mHzStats.sample(cycles);
28581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
28681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
28781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    unsigned n = mWcStats.n();
28881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // mCpuUsage.elapsed() is expensive, so don't call it every loop
28981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if ((n & 127) == 1) {
29081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        long long elapsed = mCpuUsage.elapsed();
29181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
29281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            double perLoop = elapsed / (double) n;
29381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            double perLoop100 = perLoop * 0.01;
29481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            double perLoop1k = perLoop * 0.001;
29581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            double mean = mWcStats.mean();
29681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            double stddev = mWcStats.stddev();
29781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            double minimum = mWcStats.minimum();
29881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            double maximum = mWcStats.maximum();
29981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            double meanCycles = mHzStats.mean();
30081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            double stddevCycles = mHzStats.stddev();
30181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            double minCycles = mHzStats.minimum();
30281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            double maxCycles = mHzStats.maximum();
30381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mCpuUsage.resetElapsed();
30481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mWcStats.reset();
30581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mHzStats.reset();
30681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            ALOGD("CPU usage for %s over past %.1f secs\n"
30781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                "  (%u mixer loops at %.1f mean ms per loop):\n"
30881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                "  us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
30981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                "  %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
31081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                "  MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
31181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    title.string(),
31281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    elapsed * .000000001, n, perLoop * .000001,
31381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    mean * .001,
31481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    stddev * .001,
31581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    minimum * .001,
31681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    maximum * .001,
31781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    mean / perLoop100,
31881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    stddev / perLoop100,
31981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    minimum / perLoop100,
32081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    maximum / perLoop100,
32181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    meanCycles / perLoop1k,
32281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    stddevCycles / perLoop1k,
32381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    minCycles / perLoop1k,
32481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    maxCycles / perLoop1k);
32581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
32681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
32781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
32881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#endif
32981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent};
33081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
33181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// ----------------------------------------------------------------------------
33281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent//      ThreadBase
33381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// ----------------------------------------------------------------------------
33481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
33597b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten// static
33697b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kastenconst char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
33797b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten{
33897b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    switch (type) {
33997b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    case MIXER:
34097b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten        return "MIXER";
34197b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    case DIRECT:
34297b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten        return "DIRECT";
34397b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    case DUPLICATING:
34497b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten        return "DUPLICATING";
34597b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    case RECORD:
34697b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten        return "RECORD";
34797b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    case OFFLOAD:
34897b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten        return "OFFLOAD";
34997b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    default:
35097b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten        return "unknown";
35197b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    }
35297b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten}
35397b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten
3540f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn KastenString8 devicesToString(audio_devices_t devices)
3550f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten{
3560f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    static const struct mapping {
3570f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        audio_devices_t mDevices;
3580f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        const char *    mString;
3590f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    } mappingsOut[] = {
3600f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        AUDIO_DEVICE_OUT_EARPIECE,          "EARPIECE",
3610f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        AUDIO_DEVICE_OUT_SPEAKER,           "SPEAKER",
3620f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        AUDIO_DEVICE_OUT_WIRED_HEADSET,     "WIRED_HEADSET",
3630f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        AUDIO_DEVICE_OUT_WIRED_HEADPHONE,   "WIRED_HEADPHONE",
36484d61caa6040e346df68dbe6f8e4fe339906de08Glenn Kasten        AUDIO_DEVICE_OUT_BLUETOOTH_SCO,     "BLUETOOTH_SCO",
36584d61caa6040e346df68dbe6f8e4fe339906de08Glenn Kasten        AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET,     "BLUETOOTH_SCO_HEADSET",
36684d61caa6040e346df68dbe6f8e4fe339906de08Glenn Kasten        AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT,      "BLUETOOTH_SCO_CARKIT",
36784d61caa6040e346df68dbe6f8e4fe339906de08Glenn Kasten        AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,            "BLUETOOTH_A2DP",
36884d61caa6040e346df68dbe6f8e4fe339906de08Glenn Kasten        AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES, "BLUETOOTH_A2DP_HEADPHONES",
36984d61caa6040e346df68dbe6f8e4fe339906de08Glenn Kasten        AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER,    "BLUETOOTH_A2DP_SPEAKER",
37084d61caa6040e346df68dbe6f8e4fe339906de08Glenn Kasten        AUDIO_DEVICE_OUT_AUX_DIGITAL,       "AUX_DIGITAL",
37184d61caa6040e346df68dbe6f8e4fe339906de08Glenn Kasten        AUDIO_DEVICE_OUT_HDMI,              "HDMI",
37284d61caa6040e346df68dbe6f8e4fe339906de08Glenn Kasten        AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET, "ANLG_DOCK_HEADSET",
37384d61caa6040e346df68dbe6f8e4fe339906de08Glenn Kasten        AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET, "DGTL_DOCK_HEADSET",
37484d61caa6040e346df68dbe6f8e4fe339906de08Glenn Kasten        AUDIO_DEVICE_OUT_USB_ACCESSORY,     "USB_ACCESSORY",
37584d61caa6040e346df68dbe6f8e4fe339906de08Glenn Kasten        AUDIO_DEVICE_OUT_USB_DEVICE,        "USB_DEVICE",
3760f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        AUDIO_DEVICE_OUT_TELEPHONY_TX,      "TELEPHONY_TX",
37784d61caa6040e346df68dbe6f8e4fe339906de08Glenn Kasten        AUDIO_DEVICE_OUT_LINE,              "LINE",
37884d61caa6040e346df68dbe6f8e4fe339906de08Glenn Kasten        AUDIO_DEVICE_OUT_HDMI_ARC,          "HDMI_ARC",
37984d61caa6040e346df68dbe6f8e4fe339906de08Glenn Kasten        AUDIO_DEVICE_OUT_SPDIF,             "SPDIF",
38084d61caa6040e346df68dbe6f8e4fe339906de08Glenn Kasten        AUDIO_DEVICE_OUT_FM,                "FM",
38184d61caa6040e346df68dbe6f8e4fe339906de08Glenn Kasten        AUDIO_DEVICE_OUT_AUX_LINE,          "AUX_LINE",
38284d61caa6040e346df68dbe6f8e4fe339906de08Glenn Kasten        AUDIO_DEVICE_OUT_SPEAKER_SAFE,      "SPEAKER_SAFE",
383b9d73333cce3f9da3a7a0b33589f6bbe0f992a92Eric Laurent        AUDIO_DEVICE_OUT_IP,                "IP",
3840f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        AUDIO_DEVICE_NONE,                  "NONE",         // must be last
3850f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    }, mappingsIn[] = {
38684d61caa6040e346df68dbe6f8e4fe339906de08Glenn Kasten        AUDIO_DEVICE_IN_COMMUNICATION,      "COMMUNICATION",
38784d61caa6040e346df68dbe6f8e4fe339906de08Glenn Kasten        AUDIO_DEVICE_IN_AMBIENT,            "AMBIENT",
3880f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        AUDIO_DEVICE_IN_BUILTIN_MIC,        "BUILTIN_MIC",
38984d61caa6040e346df68dbe6f8e4fe339906de08Glenn Kasten        AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET,  "BLUETOOTH_SCO_HEADSET",
3900f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        AUDIO_DEVICE_IN_WIRED_HEADSET,      "WIRED_HEADSET",
39184d61caa6040e346df68dbe6f8e4fe339906de08Glenn Kasten        AUDIO_DEVICE_IN_AUX_DIGITAL,        "AUX_DIGITAL",
3920f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        AUDIO_DEVICE_IN_VOICE_CALL,         "VOICE_CALL",
39384d61caa6040e346df68dbe6f8e4fe339906de08Glenn Kasten        AUDIO_DEVICE_IN_TELEPHONY_RX,       "TELEPHONY_RX",
39484d61caa6040e346df68dbe6f8e4fe339906de08Glenn Kasten        AUDIO_DEVICE_IN_BACK_MIC,           "BACK_MIC",
3950f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        AUDIO_DEVICE_IN_REMOTE_SUBMIX,      "REMOTE_SUBMIX",
39684d61caa6040e346df68dbe6f8e4fe339906de08Glenn Kasten        AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET,  "ANLG_DOCK_HEADSET",
39784d61caa6040e346df68dbe6f8e4fe339906de08Glenn Kasten        AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET,  "DGTL_DOCK_HEADSET",
39884d61caa6040e346df68dbe6f8e4fe339906de08Glenn Kasten        AUDIO_DEVICE_IN_USB_ACCESSORY,      "USB_ACCESSORY",
39984d61caa6040e346df68dbe6f8e4fe339906de08Glenn Kasten        AUDIO_DEVICE_IN_USB_DEVICE,         "USB_DEVICE",
40084d61caa6040e346df68dbe6f8e4fe339906de08Glenn Kasten        AUDIO_DEVICE_IN_FM_TUNER,           "FM_TUNER",
40184d61caa6040e346df68dbe6f8e4fe339906de08Glenn Kasten        AUDIO_DEVICE_IN_TV_TUNER,           "TV_TUNER",
40284d61caa6040e346df68dbe6f8e4fe339906de08Glenn Kasten        AUDIO_DEVICE_IN_LINE,               "LINE",
40384d61caa6040e346df68dbe6f8e4fe339906de08Glenn Kasten        AUDIO_DEVICE_IN_SPDIF,              "SPDIF",
40484d61caa6040e346df68dbe6f8e4fe339906de08Glenn Kasten        AUDIO_DEVICE_IN_BLUETOOTH_A2DP,     "BLUETOOTH_A2DP",
40584d61caa6040e346df68dbe6f8e4fe339906de08Glenn Kasten        AUDIO_DEVICE_IN_LOOPBACK,           "LOOPBACK",
406b9d73333cce3f9da3a7a0b33589f6bbe0f992a92Eric Laurent        AUDIO_DEVICE_IN_IP,                 "IP",
4070f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        AUDIO_DEVICE_NONE,                  "NONE",         // must be last
4080f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    };
4090f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    String8 result;
4100f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    audio_devices_t allDevices = AUDIO_DEVICE_NONE;
4110f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    const mapping *entry;
4120f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    if (devices & AUDIO_DEVICE_BIT_IN) {
4130f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        devices &= ~AUDIO_DEVICE_BIT_IN;
4140f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        entry = mappingsIn;
4150f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    } else {
4160f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        entry = mappingsOut;
4170f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    }
4180f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    for ( ; entry->mDevices != AUDIO_DEVICE_NONE; entry++) {
4190f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        allDevices = (audio_devices_t) (allDevices | entry->mDevices);
4200f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        if (devices & entry->mDevices) {
4210f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten            if (!result.isEmpty()) {
4220f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten                result.append("|");
4230f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten            }
4240f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten            result.append(entry->mString);
4250f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        }
4260f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    }
4270f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    if (devices & ~allDevices) {
4280f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        if (!result.isEmpty()) {
4290f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten            result.append("|");
4300f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        }
4310f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        result.appendFormat("0x%X", devices & ~allDevices);
4320f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    }
4330f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    if (result.isEmpty()) {
4340f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        result.append(entry->mString);
4350f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    }
4360f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    return result;
4370f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten}
4380f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten
4390f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn KastenString8 inputFlagsToString(audio_input_flags_t flags)
4400f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten{
4410f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    static const struct mapping {
4420f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        audio_input_flags_t     mFlag;
4430f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        const char *            mString;
4440f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    } mappings[] = {
4450f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        AUDIO_INPUT_FLAG_FAST,              "FAST",
4460f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        AUDIO_INPUT_FLAG_HW_HOTWORD,        "HW_HOTWORD",
4470f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        AUDIO_INPUT_FLAG_NONE,              "NONE",         // must be last
4480f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    };
4490f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    String8 result;
4500f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    audio_input_flags_t allFlags = AUDIO_INPUT_FLAG_NONE;
4510f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    const mapping *entry;
4520f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    for (entry = mappings; entry->mFlag != AUDIO_INPUT_FLAG_NONE; entry++) {
4530f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        allFlags = (audio_input_flags_t) (allFlags | entry->mFlag);
4540f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        if (flags & entry->mFlag) {
4550f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten            if (!result.isEmpty()) {
4560f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten                result.append("|");
4570f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten            }
4580f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten            result.append(entry->mString);
4590f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        }
4600f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    }
4610f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    if (flags & ~allFlags) {
4620f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        if (!result.isEmpty()) {
4630f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten            result.append("|");
4640f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        }
4650f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        result.appendFormat("0x%X", flags & ~allFlags);
4660f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    }
4670f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    if (result.isEmpty()) {
4680f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        result.append(entry->mString);
4690f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    }
4700f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    return result;
4710f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten}
4720f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten
4730f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn KastenString8 outputFlagsToString(audio_output_flags_t flags)
47497b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten{
47597b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    static const struct mapping {
47697b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten        audio_output_flags_t    mFlag;
47797b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten        const char *            mString;
47897b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    } mappings[] = {
47997b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten        AUDIO_OUTPUT_FLAG_DIRECT,           "DIRECT",
48097b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten        AUDIO_OUTPUT_FLAG_PRIMARY,          "PRIMARY",
48197b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten        AUDIO_OUTPUT_FLAG_FAST,             "FAST",
48297b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten        AUDIO_OUTPUT_FLAG_DEEP_BUFFER,      "DEEP_BUFFER",
483dfb0e115d827887e2f56a8877fe41b256d24360eGlenn Kasten        AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD, "COMPRESS_OFFLOAD",
48497b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten        AUDIO_OUTPUT_FLAG_NON_BLOCKING,     "NON_BLOCKING",
48597b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten        AUDIO_OUTPUT_FLAG_HW_AV_SYNC,       "HW_AV_SYNC",
48697b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten        AUDIO_OUTPUT_FLAG_NONE,             "NONE",         // must be last
48797b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    };
48897b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    String8 result;
48997b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    audio_output_flags_t allFlags = AUDIO_OUTPUT_FLAG_NONE;
49097b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    const mapping *entry;
49197b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    for (entry = mappings; entry->mFlag != AUDIO_OUTPUT_FLAG_NONE; entry++) {
49297b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten        allFlags = (audio_output_flags_t) (allFlags | entry->mFlag);
49397b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten        if (flags & entry->mFlag) {
49497b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten            if (!result.isEmpty()) {
49597b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten                result.append("|");
49697b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten            }
49797b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten            result.append(entry->mString);
49897b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten        }
49997b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    }
50097b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    if (flags & ~allFlags) {
50197b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten        if (!result.isEmpty()) {
50297b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten            result.append("|");
50397b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten        }
50497b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten        result.appendFormat("0x%X", flags & ~allFlags);
50597b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    }
50697b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    if (result.isEmpty()) {
50797b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten        result.append(entry->mString);
50897b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    }
50997b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    return result;
51097b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten}
51197b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten
5120f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kastenconst char *sourceToString(audio_source_t source)
5130f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten{
5140f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    switch (source) {
5150f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    case AUDIO_SOURCE_DEFAULT:              return "default";
5160f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    case AUDIO_SOURCE_MIC:                  return "mic";
5170f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    case AUDIO_SOURCE_VOICE_UPLINK:         return "voice uplink";
5180f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    case AUDIO_SOURCE_VOICE_DOWNLINK:       return "voice downlink";
5190f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    case AUDIO_SOURCE_VOICE_CALL:           return "voice call";
5200f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    case AUDIO_SOURCE_CAMCORDER:            return "camcorder";
5210f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    case AUDIO_SOURCE_VOICE_RECOGNITION:    return "voice recognition";
5220f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    case AUDIO_SOURCE_VOICE_COMMUNICATION:  return "voice communication";
5230f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    case AUDIO_SOURCE_REMOTE_SUBMIX:        return "remote submix";
5240f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    case AUDIO_SOURCE_FM_TUNER:             return "FM tuner";
5250f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    case AUDIO_SOURCE_HOTWORD:              return "hotword";
5260f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    default:                                return "unknown";
5270f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    }
5280f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten}
5290f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten
53081784c37c61b09289654b979567a42bf73cd2b12Eric LaurentAudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
53172e3f39146fce4686bd96f11057c051bea376dfbEric Laurent        audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady)
53281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    :   Thread(false /*canCallJava*/),
53381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mType(type),
5349b58f63e45ef2fdfb839b9b9bb3411d81eb96128Glenn Kasten        mAudioFlinger(audioFlinger),
53570949c47fbae3f836d15f040551d7631be3ed7c2Glenn Kasten        // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
536deca2ae0a7cf8bc54ff3f30b7dc39bbc78b94c0dGlenn Kasten        // are set by PlaybackThread::readOutputParameters_l() or
537deca2ae0a7cf8bc54ff3f30b7dc39bbc78b94c0dGlenn Kasten        // RecordThread::readInputParameters_l()
538fd4779740ec3e9e865d5514464df26d015354388Eric Laurent        //FIXME: mStandby should be true here. Is this some kind of hack?
53981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
5407c1ec5f038e63a5eb8b04434577c25bc23f5f410Eric Laurent        mPrevOutDevice(AUDIO_DEVICE_NONE), mPrevInDevice(AUDIO_DEVICE_NONE),
5417c1ec5f038e63a5eb8b04434577c25bc23f5f410Eric Laurent        mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
54281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // mName will be set by concrete (non-virtual) subclass
54372e3f39146fce4686bd96f11057c051bea376dfbEric Laurent        mDeathRecipient(new PMDeathRecipient(this)),
54472e3f39146fce4686bd96f11057c051bea376dfbEric Laurent        mSystemReady(systemReady)
54581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
546296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent    memset(&mPatch, 0, sizeof(struct audio_patch));
54781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
54881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
54981784c37c61b09289654b979567a42bf73cd2b12Eric LaurentAudioFlinger::ThreadBase::~ThreadBase()
55081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
551c6ae3c8a261794fd4445e4e152d1ada074a3f92fGlenn Kasten    // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
552c6ae3c8a261794fd4445e4e152d1ada074a3f92fGlenn Kasten    mConfigEvents.clear();
553c6ae3c8a261794fd4445e4e152d1ada074a3f92fGlenn Kasten
55481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // do not lock the mutex in destructor
55581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    releaseWakeLock_l();
55681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (mPowerManager != 0) {
55706b46062d2f8bc82ca3061a23d197734ae51918bMarco Nelissen        sp<IBinder> binder = IInterface::asBinder(mPowerManager);
55881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        binder->unlinkToDeath(mDeathRecipient);
55981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
56081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
56181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
562cf04c2cb8e031acc03c1c91cb1ccab15098c89b6Glenn Kastenstatus_t AudioFlinger::ThreadBase::readyToRun()
563cf04c2cb8e031acc03c1c91cb1ccab15098c89b6Glenn Kasten{
564cf04c2cb8e031acc03c1c91cb1ccab15098c89b6Glenn Kasten    status_t status = initCheck();
565cf04c2cb8e031acc03c1c91cb1ccab15098c89b6Glenn Kasten    if (status == NO_ERROR) {
566cf04c2cb8e031acc03c1c91cb1ccab15098c89b6Glenn Kasten        ALOGI("AudioFlinger's thread %p ready to run", this);
567cf04c2cb8e031acc03c1c91cb1ccab15098c89b6Glenn Kasten    } else {
568cf04c2cb8e031acc03c1c91cb1ccab15098c89b6Glenn Kasten        ALOGE("No working audio driver found.");
569cf04c2cb8e031acc03c1c91cb1ccab15098c89b6Glenn Kasten    }
570cf04c2cb8e031acc03c1c91cb1ccab15098c89b6Glenn Kasten    return status;
571cf04c2cb8e031acc03c1c91cb1ccab15098c89b6Glenn Kasten}
572cf04c2cb8e031acc03c1c91cb1ccab15098c89b6Glenn Kasten
57381784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::ThreadBase::exit()
57481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
57581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    ALOGV("ThreadBase::exit");
57681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // do any cleanup required for exit to succeed
57781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    preExit();
57881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    {
57981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // This lock prevents the following race in thread (uniprocessor for illustration):
58081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        //  if (!exitPending()) {
58181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        //      // context switch from here to exit()
58281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        //      // exit() calls requestExit(), what exitPending() observes
58381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        //      // exit() calls signal(), which is dropped since no waiters
58481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        //      // context switch back from exit() to here
58581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        //      mWaitWorkCV.wait(...);
58681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        //      // now thread is hung
58781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        //  }
58881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        AutoMutex lock(mLock);
58981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        requestExit();
59081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mWaitWorkCV.broadcast();
59181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
59281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // When Thread::requestExitAndWait is made virtual and this method is renamed to
59381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
59481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    requestExitAndWait();
59581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
59681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
59781784c37c61b09289654b979567a42bf73cd2b12Eric Laurentstatus_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
59881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
59981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    status_t status;
60081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
60181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
60281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
60381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
6041035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    return sendSetParameterConfigEvent_l(keyValuePairs);
6051035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent}
6061035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent
6071035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent// sendConfigEvent_l() must be called with ThreadBase::mLock held
6081035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
6091035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurentstatus_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
6101035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent{
6111035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    status_t status = NO_ERROR;
6121035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent
61372e3f39146fce4686bd96f11057c051bea376dfbEric Laurent    if (event->mRequiresSystemReady && !mSystemReady) {
61472e3f39146fce4686bd96f11057c051bea376dfbEric Laurent        event->mWaitStatus = false;
61572e3f39146fce4686bd96f11057c051bea376dfbEric Laurent        mPendingConfigEvents.add(event);
61672e3f39146fce4686bd96f11057c051bea376dfbEric Laurent        return status;
61772e3f39146fce4686bd96f11057c051bea376dfbEric Laurent    }
6181035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    mConfigEvents.add(event);
6191035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    ALOGV("sendConfigEvent_l() num events %d event %d", mConfigEvents.size(), event->mType);
62081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mWaitWorkCV.signal();
6211035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    mLock.unlock();
6221035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    {
6231035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        Mutex::Autolock _l(event->mLock);
6241035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        while (event->mWaitStatus) {
6251035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
6261035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                event->mStatus = TIMED_OUT;
6271035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                event->mWaitStatus = false;
6281035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            }
6291035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        }
6301035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        status = event->mStatus;
63181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
6321035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    mLock.lock();
63381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return status;
63481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
63581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
6367c1ec5f038e63a5eb8b04434577c25bc23f5f410Eric Laurentvoid AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid)
63781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
63881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
6397c1ec5f038e63a5eb8b04434577c25bc23f5f410Eric Laurent    sendIoConfigEvent_l(event, pid);
64081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
64181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
64281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
6437c1ec5f038e63a5eb8b04434577c25bc23f5f410Eric Laurentvoid AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid)
64481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
6457c1ec5f038e63a5eb8b04434577c25bc23f5f410Eric Laurent    sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid);
6461035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    sendConfigEvent_l(configEvent);
64781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
64881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
64972e3f39146fce4686bd96f11057c051bea376dfbEric Laurentvoid AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio)
65072e3f39146fce4686bd96f11057c051bea376dfbEric Laurent{
65172e3f39146fce4686bd96f11057c051bea376dfbEric Laurent    Mutex::Autolock _l(mLock);
65272e3f39146fce4686bd96f11057c051bea376dfbEric Laurent    sendPrioConfigEvent_l(pid, tid, prio);
65372e3f39146fce4686bd96f11057c051bea376dfbEric Laurent}
65472e3f39146fce4686bd96f11057c051bea376dfbEric Laurent
65581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
65681784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
65781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
6581035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
6591035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    sendConfigEvent_l(configEvent);
66081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
66181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
6621035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
6631035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurentstatus_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
66481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
6651035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    sp<ConfigEvent> configEvent = (ConfigEvent *)new SetParameterConfigEvent(keyValuePair);
6661035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    return sendConfigEvent_l(configEvent);
667f777331418a86cd9fd709af898ef24a69967aeb4Glenn Kasten}
668f777331418a86cd9fd709af898ef24a69967aeb4Glenn Kasten
6691c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurentstatus_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
6701c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent                                                        const struct audio_patch *patch,
6711c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent                                                        audio_patch_handle_t *handle)
6721c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent{
6731c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent    Mutex::Autolock _l(mLock);
6741c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent    sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
6751c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent    status_t status = sendConfigEvent_l(configEvent);
6761c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent    if (status == NO_ERROR) {
6771c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent        CreateAudioPatchConfigEventData *data =
6781c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent                                        (CreateAudioPatchConfigEventData *)configEvent->mData.get();
6791c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent        *handle = data->mHandle;
6801c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent    }
6811c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent    return status;
6821c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent}
6831c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent
6841c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurentstatus_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
6851c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent                                                                const audio_patch_handle_t handle)
6861c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent{
6871c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent    Mutex::Autolock _l(mLock);
6881c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent    sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
6891c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent    return sendConfigEvent_l(configEvent);
6901c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent}
6911c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent
6921c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent
6932cfbf88b89854f30b295e8ae26a031edb8d712f8Glenn Kasten// post condition: mConfigEvents.isEmpty()
694021cf9634ab09c0753a40b7c9ef4ba603be5c3daEric Laurentvoid AudioFlinger::ThreadBase::processConfigEvents_l()
695f777331418a86cd9fd709af898ef24a69967aeb4Glenn Kasten{
6961035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    bool configChanged = false;
6971035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent
69881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    while (!mConfigEvents.isEmpty()) {
6991035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        ALOGV("processConfigEvents_l() remaining events %d", mConfigEvents.size());
7001035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        sp<ConfigEvent> event = mConfigEvents[0];
70181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mConfigEvents.removeAt(0);
7021035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        switch (event->mType) {
7033468e8a4d79cc6a7bb0f03f8382426195bed44dfGlenn Kasten        case CFG_EVENT_PRIO: {
7041035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
7051035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            // FIXME Need to understand why this has to be done asynchronously
7061035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            int err = requestPriority(data->mPid, data->mTid, data->mPrio,
7073468e8a4d79cc6a7bb0f03f8382426195bed44dfGlenn Kasten                    true /*asynchronous*/);
7083468e8a4d79cc6a7bb0f03f8382426195bed44dfGlenn Kasten            if (err != 0) {
7093468e8a4d79cc6a7bb0f03f8382426195bed44dfGlenn Kasten                ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
7101035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                      data->mPrio, data->mPid, data->mTid, err);
7113468e8a4d79cc6a7bb0f03f8382426195bed44dfGlenn Kasten            }
7123468e8a4d79cc6a7bb0f03f8382426195bed44dfGlenn Kasten        } break;
7133468e8a4d79cc6a7bb0f03f8382426195bed44dfGlenn Kasten        case CFG_EVENT_IO: {
7141035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
7157c1ec5f038e63a5eb8b04434577c25bc23f5f410Eric Laurent            ioConfigChanged(data->mEvent, data->mPid);
7161035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        } break;
7171035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        case CFG_EVENT_SET_PARAMETER: {
7181035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
7191035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
7201035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                configChanged = true;
721d5418eb594435c958d6c37fa9938161a0112adbdGlenn Kasten            }
7223468e8a4d79cc6a7bb0f03f8382426195bed44dfGlenn Kasten        } break;
7231c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent        case CFG_EVENT_CREATE_AUDIO_PATCH: {
7241c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent            CreateAudioPatchConfigEventData *data =
7251c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent                                            (CreateAudioPatchConfigEventData *)event->mData.get();
7261c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent            event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
7271c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent        } break;
7281c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent        case CFG_EVENT_RELEASE_AUDIO_PATCH: {
7291c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent            ReleaseAudioPatchConfigEventData *data =
7301c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent                                            (ReleaseAudioPatchConfigEventData *)event->mData.get();
7311c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent            event->mStatus = releaseAudioPatch_l(data->mHandle);
7321c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent        } break;
7333468e8a4d79cc6a7bb0f03f8382426195bed44dfGlenn Kasten        default:
7341035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
7353468e8a4d79cc6a7bb0f03f8382426195bed44dfGlenn Kasten            break;
73681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
7371035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        {
7381035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            Mutex::Autolock _l(event->mLock);
7391035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            if (event->mWaitStatus) {
7401035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                event->mWaitStatus = false;
7411035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                event->mCond.signal();
7421035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            }
7431035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        }
7441035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
7451035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    }
7461035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent
7471035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    if (configChanged) {
7481035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        cacheParameters_l();
74981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
75081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
75181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
752b220884bf3129253cc5bc8d030bc475411ea4911Marco NelissenString8 channelMaskToString(audio_channel_mask_t mask, bool output) {
753b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen    String8 s;
754e1635ec096d1110c33a5aa46847af59c261fb7faGlenn Kasten    const audio_channel_representation_t representation =
755e1635ec096d1110c33a5aa46847af59c261fb7faGlenn Kasten            audio_channel_mask_get_representation(mask);
756f98ec8d0d42e6952c0a7cc5027935851073f7426Andy Hung
757f98ec8d0d42e6952c0a7cc5027935851073f7426Andy Hung    switch (representation) {
758f98ec8d0d42e6952c0a7cc5027935851073f7426Andy Hung    case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
759f98ec8d0d42e6952c0a7cc5027935851073f7426Andy Hung        if (output) {
760f98ec8d0d42e6952c0a7cc5027935851073f7426Andy Hung            if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
761f98ec8d0d42e6952c0a7cc5027935851073f7426Andy Hung            if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
762f98ec8d0d42e6952c0a7cc5027935851073f7426Andy Hung            if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
763f98ec8d0d42e6952c0a7cc5027935851073f7426Andy Hung            if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
764f98ec8d0d42e6952c0a7cc5027935851073f7426Andy Hung            if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
765f98ec8d0d42e6952c0a7cc5027935851073f7426Andy Hung            if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
766f98ec8d0d42e6952c0a7cc5027935851073f7426Andy Hung            if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
767f98ec8d0d42e6952c0a7cc5027935851073f7426Andy Hung            if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
768f98ec8d0d42e6952c0a7cc5027935851073f7426Andy Hung            if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
769f98ec8d0d42e6952c0a7cc5027935851073f7426Andy Hung            if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
770f98ec8d0d42e6952c0a7cc5027935851073f7426Andy Hung            if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
771f98ec8d0d42e6952c0a7cc5027935851073f7426Andy Hung            if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
772f98ec8d0d42e6952c0a7cc5027935851073f7426Andy Hung            if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
773f98ec8d0d42e6952c0a7cc5027935851073f7426Andy Hung            if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
774f98ec8d0d42e6952c0a7cc5027935851073f7426Andy Hung            if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
775f98ec8d0d42e6952c0a7cc5027935851073f7426Andy Hung            if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
776f98ec8d0d42e6952c0a7cc5027935851073f7426Andy Hung            if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
777f98ec8d0d42e6952c0a7cc5027935851073f7426Andy Hung            if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
778f98ec8d0d42e6952c0a7cc5027935851073f7426Andy Hung            if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown,  ");
779f98ec8d0d42e6952c0a7cc5027935851073f7426Andy Hung        } else {
780f98ec8d0d42e6952c0a7cc5027935851073f7426Andy Hung            if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
781f98ec8d0d42e6952c0a7cc5027935851073f7426Andy Hung            if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
782f98ec8d0d42e6952c0a7cc5027935851073f7426Andy Hung            if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
783f98ec8d0d42e6952c0a7cc5027935851073f7426Andy Hung            if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
784f98ec8d0d42e6952c0a7cc5027935851073f7426Andy Hung            if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
785f98ec8d0d42e6952c0a7cc5027935851073f7426Andy Hung            if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
786f98ec8d0d42e6952c0a7cc5027935851073f7426Andy Hung            if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
787f98ec8d0d42e6952c0a7cc5027935851073f7426Andy Hung            if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
788f98ec8d0d42e6952c0a7cc5027935851073f7426Andy Hung            if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
789f98ec8d0d42e6952c0a7cc5027935851073f7426Andy Hung            if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
790f98ec8d0d42e6952c0a7cc5027935851073f7426Andy Hung            if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
791f98ec8d0d42e6952c0a7cc5027935851073f7426Andy Hung            if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
792f98ec8d0d42e6952c0a7cc5027935851073f7426Andy Hung            if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
793f98ec8d0d42e6952c0a7cc5027935851073f7426Andy Hung            if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
794f98ec8d0d42e6952c0a7cc5027935851073f7426Andy Hung            if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown,  ");
795f98ec8d0d42e6952c0a7cc5027935851073f7426Andy Hung        }
796f98ec8d0d42e6952c0a7cc5027935851073f7426Andy Hung        const int len = s.length();
797f98ec8d0d42e6952c0a7cc5027935851073f7426Andy Hung        if (len > 2) {
798f98ec8d0d42e6952c0a7cc5027935851073f7426Andy Hung            char *str = s.lockBuffer(len); // needed?
799f98ec8d0d42e6952c0a7cc5027935851073f7426Andy Hung            s.unlockBuffer(len - 2);       // remove trailing ", "
800f98ec8d0d42e6952c0a7cc5027935851073f7426Andy Hung        }
801f98ec8d0d42e6952c0a7cc5027935851073f7426Andy Hung        return s;
802b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen    }
803f98ec8d0d42e6952c0a7cc5027935851073f7426Andy Hung    case AUDIO_CHANNEL_REPRESENTATION_INDEX:
804f98ec8d0d42e6952c0a7cc5027935851073f7426Andy Hung        s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
805f98ec8d0d42e6952c0a7cc5027935851073f7426Andy Hung        return s;
806f98ec8d0d42e6952c0a7cc5027935851073f7426Andy Hung    default:
807f98ec8d0d42e6952c0a7cc5027935851073f7426Andy Hung        s.appendFormat("unknown mask, representation:%d  bits:%#x",
808f98ec8d0d42e6952c0a7cc5027935851073f7426Andy Hung                representation, audio_channel_mask_get_bits(mask));
809f98ec8d0d42e6952c0a7cc5027935851073f7426Andy Hung        return s;
810b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen    }
811b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen}
812b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen
8130f11b51a57bc9062c4fe8af73747319cedabc5d6Glenn Kastenvoid AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
81481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
81581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    const size_t SIZE = 256;
81681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    char buffer[SIZE];
81781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    String8 result;
81881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
81981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    bool locked = AudioFlinger::dumpTryLock(mLock);
82081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (!locked) {
82197b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten        dprintf(fd, "thread %p may be deadlocked\n", this);
822b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen    }
823b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen
8240b89bc0d285b8fd4798df1ff0ba9f93851a3bd48Glenn Kasten    dprintf(fd, "  Thread name: %s\n", mThreadName);
82587cebadd48710e42474756fc3513df678de045ceElliott Hughes    dprintf(fd, "  I/O handle: %d\n", mId);
82687cebadd48710e42474756fc3513df678de045ceElliott Hughes    dprintf(fd, "  TID: %d\n", getTid());
82787cebadd48710e42474756fc3513df678de045ceElliott Hughes    dprintf(fd, "  Standby: %s\n", mStandby ? "yes" : "no");
82897b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    dprintf(fd, "  Sample rate: %u Hz\n", mSampleRate);
82987cebadd48710e42474756fc3513df678de045ceElliott Hughes    dprintf(fd, "  HAL frame count: %zu\n", mFrameCount);
83097b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    dprintf(fd, "  HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat));
83187cebadd48710e42474756fc3513df678de045ceElliott Hughes    dprintf(fd, "  HAL buffer size: %u bytes\n", mBufferSize);
83297b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    dprintf(fd, "  Channel count: %u\n", mChannelCount);
83397b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    dprintf(fd, "  Channel mask: 0x%08x (%s)\n", mChannelMask,
834b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen            channelMaskToString(mChannelMask, mType != RECORD).string());
83597b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    dprintf(fd, "  Format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
83697b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    dprintf(fd, "  Frame size: %zu bytes\n", mFrameSize);
83787cebadd48710e42474756fc3513df678de045ceElliott Hughes    dprintf(fd, "  Pending config events:");
838b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen    size_t numConfig = mConfigEvents.size();
839b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen    if (numConfig) {
840b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        for (size_t i = 0; i < numConfig; i++) {
841b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen            mConfigEvents[i]->dump(buffer, SIZE);
84287cebadd48710e42474756fc3513df678de045ceElliott Hughes            dprintf(fd, "\n    %s", buffer);
843b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        }
84487cebadd48710e42474756fc3513df678de045ceElliott Hughes        dprintf(fd, "\n");
845b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen    } else {
84687cebadd48710e42474756fc3513df678de045ceElliott Hughes        dprintf(fd, " none\n");
84781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
8480b89bc0d285b8fd4798df1ff0ba9f93851a3bd48Glenn Kasten    dprintf(fd, "  Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).string());
8490b89bc0d285b8fd4798df1ff0ba9f93851a3bd48Glenn Kasten    dprintf(fd, "  Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).string());
8500b89bc0d285b8fd4798df1ff0ba9f93851a3bd48Glenn Kasten    dprintf(fd, "  Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
85181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
85281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (locked) {
85381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mLock.unlock();
85481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
85581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
85681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
85781784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
85881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
85981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    const size_t SIZE = 256;
86081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    char buffer[SIZE];
86181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    String8 result;
86281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
863b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen    size_t numEffectChains = mEffectChains.size();
8641d6fa7af1288b550faabe4ec2cf98684236723dbNarayan Kamath    snprintf(buffer, SIZE, "  %zu Effect Chains\n", numEffectChains);
86581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    write(fd, buffer, strlen(buffer));
86681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
867b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen    for (size_t i = 0; i < numEffectChains; ++i) {
86881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sp<EffectChain> chain = mEffectChains[i];
86981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (chain != 0) {
87081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            chain->dump(fd, args);
87181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
87281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
87381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
87481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
875e14a5d6d2cc91dd2fc09ffdf7aa670b37da0795dMarco Nelissenvoid AudioFlinger::ThreadBase::acquireWakeLock(int uid)
87681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
87781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
878e14a5d6d2cc91dd2fc09ffdf7aa670b37da0795dMarco Nelissen    acquireWakeLock_l(uid);
87981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
88081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
881014e7fa2e90827d911c37bb0ce4d2e10e14d0bb3Narayan KamathString16 AudioFlinger::ThreadBase::getWakeLockTag()
882014e7fa2e90827d911c37bb0ce4d2e10e14d0bb3Narayan Kamath{
883014e7fa2e90827d911c37bb0ce4d2e10e14d0bb3Narayan Kamath    switch (mType) {
884bcb1486d052e329ae4790d93055d1c51017286c3Glenn Kasten    case MIXER:
885bcb1486d052e329ae4790d93055d1c51017286c3Glenn Kasten        return String16("AudioMix");
886bcb1486d052e329ae4790d93055d1c51017286c3Glenn Kasten    case DIRECT:
887bcb1486d052e329ae4790d93055d1c51017286c3Glenn Kasten        return String16("AudioDirectOut");
888bcb1486d052e329ae4790d93055d1c51017286c3Glenn Kasten    case DUPLICATING:
889bcb1486d052e329ae4790d93055d1c51017286c3Glenn Kasten        return String16("AudioDup");
890bcb1486d052e329ae4790d93055d1c51017286c3Glenn Kasten    case RECORD:
891bcb1486d052e329ae4790d93055d1c51017286c3Glenn Kasten        return String16("AudioIn");
892bcb1486d052e329ae4790d93055d1c51017286c3Glenn Kasten    case OFFLOAD:
893bcb1486d052e329ae4790d93055d1c51017286c3Glenn Kasten        return String16("AudioOffload");
894bcb1486d052e329ae4790d93055d1c51017286c3Glenn Kasten    default:
895bcb1486d052e329ae4790d93055d1c51017286c3Glenn Kasten        ALOG_ASSERT(false);
896bcb1486d052e329ae4790d93055d1c51017286c3Glenn Kasten        return String16("AudioUnknown");
897014e7fa2e90827d911c37bb0ce4d2e10e14d0bb3Narayan Kamath    }
898014e7fa2e90827d911c37bb0ce4d2e10e14d0bb3Narayan Kamath}
899014e7fa2e90827d911c37bb0ce4d2e10e14d0bb3Narayan Kamath
900e14a5d6d2cc91dd2fc09ffdf7aa670b37da0795dMarco Nelissenvoid AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
90181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
902462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen    getPowerManager_l();
90381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (mPowerManager != 0) {
90481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sp<IBinder> binder = new BBinder();
905e14a5d6d2cc91dd2fc09ffdf7aa670b37da0795dMarco Nelissen        status_t status;
906e14a5d6d2cc91dd2fc09ffdf7aa670b37da0795dMarco Nelissen        if (uid >= 0) {
907547789d25dc6bd6561553bcf6b384fb0d4fee834Eric Laurent            status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
908e14a5d6d2cc91dd2fc09ffdf7aa670b37da0795dMarco Nelissen                    binder,
909014e7fa2e90827d911c37bb0ce4d2e10e14d0bb3Narayan Kamath                    getWakeLockTag(),
910e14a5d6d2cc91dd2fc09ffdf7aa670b37da0795dMarco Nelissen                    String16("media"),
9113abc2ded40066f3b1df23aceb553f22d569c5cd3Glenn Kasten                    uid,
9123abc2ded40066f3b1df23aceb553f22d569c5cd3Glenn Kasten                    true /* FIXME force oneway contrary to .aidl */);
913e14a5d6d2cc91dd2fc09ffdf7aa670b37da0795dMarco Nelissen        } else {
914547789d25dc6bd6561553bcf6b384fb0d4fee834Eric Laurent            status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
915e14a5d6d2cc91dd2fc09ffdf7aa670b37da0795dMarco Nelissen                    binder,
916014e7fa2e90827d911c37bb0ce4d2e10e14d0bb3Narayan Kamath                    getWakeLockTag(),
9173abc2ded40066f3b1df23aceb553f22d569c5cd3Glenn Kasten                    String16("media"),
9183abc2ded40066f3b1df23aceb553f22d569c5cd3Glenn Kasten                    true /* FIXME force oneway contrary to .aidl */);
919e14a5d6d2cc91dd2fc09ffdf7aa670b37da0795dMarco Nelissen        }
92081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (status == NO_ERROR) {
92181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mWakeLockToken = binder;
92281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
923d7dca050c630bddbd73a6623271b34b4290460eeGlenn Kasten        ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
92481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
92581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
92681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
92781784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::ThreadBase::releaseWakeLock()
92881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
92981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
93081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    releaseWakeLock_l();
93181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
93281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
93381784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::ThreadBase::releaseWakeLock_l()
93481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
93581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (mWakeLockToken != 0) {
936d7dca050c630bddbd73a6623271b34b4290460eeGlenn Kasten        ALOGV("releaseWakeLock_l() %s", mThreadName);
93781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (mPowerManager != 0) {
9383abc2ded40066f3b1df23aceb553f22d569c5cd3Glenn Kasten            mPowerManager->releaseWakeLock(mWakeLockToken, 0,
9393abc2ded40066f3b1df23aceb553f22d569c5cd3Glenn Kasten                    true /* FIXME force oneway contrary to .aidl */);
94081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
94181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mWakeLockToken.clear();
94281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
94381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
94481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
945462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissenvoid AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
946462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen    Mutex::Autolock _l(mLock);
947462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen    updateWakeLockUids_l(uids);
948462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen}
949462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen
950462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissenvoid AudioFlinger::ThreadBase::getPowerManager_l() {
95172e3f39146fce4686bd96f11057c051bea376dfbEric Laurent    if (mSystemReady && mPowerManager == 0) {
952462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen        // use checkService() to avoid blocking if power service is not up yet
953462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen        sp<IBinder> binder =
954462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen            defaultServiceManager()->checkService(String16("power"));
955462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen        if (binder == 0) {
956d7dca050c630bddbd73a6623271b34b4290460eeGlenn Kasten            ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
957462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen        } else {
958462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen            mPowerManager = interface_cast<IPowerManager>(binder);
959462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen            binder->linkToDeath(mDeathRecipient);
960462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen        }
961462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen    }
962462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen}
963462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen
964462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissenvoid AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
965462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen    getPowerManager_l();
966462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen    if (mWakeLockToken == NULL) {
967462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen        ALOGE("no wake lock to update!");
968462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen        return;
969462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen    }
970462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen    if (mPowerManager != 0) {
971462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen        sp<IBinder> binder = new BBinder();
972462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen        status_t status;
9733abc2ded40066f3b1df23aceb553f22d569c5cd3Glenn Kasten        status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array(),
9743abc2ded40066f3b1df23aceb553f22d569c5cd3Glenn Kasten                    true /* FIXME force oneway contrary to .aidl */);
975d7dca050c630bddbd73a6623271b34b4290460eeGlenn Kasten        ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
976462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen    }
977462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen}
978462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen
97981784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::ThreadBase::clearPowerManager()
98081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
98181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
98281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    releaseWakeLock_l();
98381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mPowerManager.clear();
98481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
98581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
9860f11b51a57bc9062c4fe8af73747319cedabc5d6Glenn Kastenvoid AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
98781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
98881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    sp<ThreadBase> thread = mThread.promote();
98981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (thread != 0) {
99081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        thread->clearPowerManager();
99181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
99281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    ALOGW("power manager service died !!!");
99381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
99481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
99581784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::ThreadBase::setEffectSuspended(
99681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        const effect_uuid_t *type, bool suspend, int sessionId)
99781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
99881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
99981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    setEffectSuspended_l(type, suspend, sessionId);
100081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
100181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
100281784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::ThreadBase::setEffectSuspended_l(
100381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        const effect_uuid_t *type, bool suspend, int sessionId)
100481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
100581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    sp<EffectChain> chain = getEffectChain_l(sessionId);
100681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (chain != 0) {
100781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (type != NULL) {
100881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            chain->setEffectSuspended_l(type, suspend);
100981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        } else {
101081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            chain->setEffectSuspendedAll_l(suspend);
101181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
101281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
101381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
101481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    updateSuspendedSessions_l(type, suspend, sessionId);
101581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
101681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
101781784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
101881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
101981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
102081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (index < 0) {
102181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        return;
102281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
102381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
102481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
102581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mSuspendedSessions.valueAt(index);
102681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
102781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    for (size_t i = 0; i < sessionEffects.size(); i++) {
102881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
102981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        for (int j = 0; j < desc->mRefCount; j++) {
103081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
103181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                chain->setEffectSuspendedAll_l(true);
103281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            } else {
103381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
103481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    desc->mType.timeLow);
103581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                chain->setEffectSuspended_l(&desc->mType, true);
103681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
103781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
103881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
103981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
104081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
104181784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
104281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                                                         bool suspend,
104381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                                                         int sessionId)
104481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
104581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
104681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
104781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
104881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
104981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (suspend) {
105081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (index >= 0) {
105181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            sessionEffects = mSuspendedSessions.valueAt(index);
105281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        } else {
105381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mSuspendedSessions.add(sessionId, sessionEffects);
105481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
105581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    } else {
105681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (index < 0) {
105781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            return;
105881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
105981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sessionEffects = mSuspendedSessions.valueAt(index);
106081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
106181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
106281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
106381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    int key = EffectChain::kKeyForSuspendAll;
106481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (type != NULL) {
106581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        key = type->timeLow;
106681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
106781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    index = sessionEffects.indexOfKey(key);
106881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
106981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    sp<SuspendedSessionDesc> desc;
107081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (suspend) {
107181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (index >= 0) {
107281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            desc = sessionEffects.valueAt(index);
107381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        } else {
107481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            desc = new SuspendedSessionDesc();
107581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if (type != NULL) {
107681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                desc->mType = *type;
107781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
107881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            sessionEffects.add(key, desc);
107981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
108081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
108181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        desc->mRefCount++;
108281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    } else {
108381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (index < 0) {
108481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            return;
108581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
108681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        desc = sessionEffects.valueAt(index);
108781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (--desc->mRefCount == 0) {
108881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
108981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            sessionEffects.removeItemsAt(index);
109081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if (sessionEffects.isEmpty()) {
109181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                ALOGV("updateSuspendedSessions_l() restore removing session %d",
109281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                                 sessionId);
109381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                mSuspendedSessions.removeItem(sessionId);
109481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
109581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
109681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
109781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (!sessionEffects.isEmpty()) {
109881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
109981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
110081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
110181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
110281784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
110381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                                                            bool enabled,
110481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                                                            int sessionId)
110581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
110681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
110781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
110881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
110981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
111081784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
111181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                                                            bool enabled,
111281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                                                            int sessionId)
111381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
111481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (mType != RECORD) {
111581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
111681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // another session. This gives the priority to well behaved effect control panels
111781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // and applications not using global effects.
111881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
111981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // global effects
112081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
112181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
112281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
112381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
112481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
112581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    sp<EffectChain> chain = getEffectChain_l(sessionId);
112681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (chain != 0) {
112781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        chain->checkSuspendOnEffectEnabled(effect, enabled);
112881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
112981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
113081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
113181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
113281784c37c61b09289654b979567a42bf73cd2b12Eric Laurentsp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
113381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        const sp<AudioFlinger::Client>& client,
113481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        const sp<IEffectClient>& effectClient,
113581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        int32_t priority,
113681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        int sessionId,
113781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        effect_descriptor_t *desc,
113881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        int *enabled,
11399156ef3e11b68cc4b6d3cea77f1f63673855a6d1Glenn Kasten        status_t *status)
114081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
114181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    sp<EffectModule> effect;
114281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    sp<EffectHandle> handle;
114381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    status_t lStatus;
114481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    sp<EffectChain> chain;
114581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    bool chainCreated = false;
114681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    bool effectCreated = false;
114781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    bool effectRegistered = false;
114881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
114981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    lStatus = initCheck();
115081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (lStatus != NO_ERROR) {
115181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        ALOGW("createEffect_l() Audio driver not initialized.");
115281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        goto Exit;
115381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
115481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
115598ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung    // Reject any effect on Direct output threads for now, since the format of
115698ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung    // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
115798ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung    if (mType == DIRECT) {
115898ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung        ALOGW("createEffect_l() Cannot add effect %s on Direct output type thread %s",
1159d7dca050c630bddbd73a6623271b34b4290460eeGlenn Kasten                desc->name, mThreadName);
116098ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung        lStatus = BAD_VALUE;
116198ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung        goto Exit;
116298ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung    }
116398ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung
1164389cfdbb9a92a438a0d7710321c2964c7ad55ecaAndy Hung    // Reject any effect on mixer or duplicating multichannel sinks.
11659a59276fb465e492138e0576523b54079671e8f4Andy Hung    // TODO: fix both format and multichannel issues with effects.
1166389cfdbb9a92a438a0d7710321c2964c7ad55ecaAndy Hung    if ((mType == MIXER || mType == DUPLICATING) && mChannelCount != FCC_2) {
1167389cfdbb9a92a438a0d7710321c2964c7ad55ecaAndy Hung        ALOGW("createEffect_l() Cannot add effect %s for multichannel(%d) %s threads",
1168389cfdbb9a92a438a0d7710321c2964c7ad55ecaAndy Hung                desc->name, mChannelCount, mType == MIXER ? "MIXER" : "DUPLICATING");
11699a59276fb465e492138e0576523b54079671e8f4Andy Hung        lStatus = BAD_VALUE;
11709a59276fb465e492138e0576523b54079671e8f4Andy Hung        goto Exit;
11719a59276fb465e492138e0576523b54079671e8f4Andy Hung    }
11729a59276fb465e492138e0576523b54079671e8f4Andy Hung
11735baf2af52cd186633b7173196c1e4a4cd3435f22Eric Laurent    // Allow global effects only on offloaded and mixer threads
11745baf2af52cd186633b7173196c1e4a4cd3435f22Eric Laurent    if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
11755baf2af52cd186633b7173196c1e4a4cd3435f22Eric Laurent        switch (mType) {
11765baf2af52cd186633b7173196c1e4a4cd3435f22Eric Laurent        case MIXER:
11775baf2af52cd186633b7173196c1e4a4cd3435f22Eric Laurent        case OFFLOAD:
11785baf2af52cd186633b7173196c1e4a4cd3435f22Eric Laurent            break;
11795baf2af52cd186633b7173196c1e4a4cd3435f22Eric Laurent        case DIRECT:
11805baf2af52cd186633b7173196c1e4a4cd3435f22Eric Laurent        case DUPLICATING:
11815baf2af52cd186633b7173196c1e4a4cd3435f22Eric Laurent        case RECORD:
11825baf2af52cd186633b7173196c1e4a4cd3435f22Eric Laurent        default:
1183d7dca050c630bddbd73a6623271b34b4290460eeGlenn Kasten            ALOGW("createEffect_l() Cannot add global effect %s on thread %s",
1184d7dca050c630bddbd73a6623271b34b4290460eeGlenn Kasten                    desc->name, mThreadName);
11855baf2af52cd186633b7173196c1e4a4cd3435f22Eric Laurent            lStatus = BAD_VALUE;
11865baf2af52cd186633b7173196c1e4a4cd3435f22Eric Laurent            goto Exit;
11875baf2af52cd186633b7173196c1e4a4cd3435f22Eric Laurent        }
118881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
11895baf2af52cd186633b7173196c1e4a4cd3435f22Eric Laurent
119081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // Only Pre processor effects are allowed on input threads and only on input threads
119181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
119281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
119381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                desc->name, desc->flags, mType);
119481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        lStatus = BAD_VALUE;
119581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        goto Exit;
119681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
119781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
119881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
119981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
120081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    { // scope for mLock
120181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        Mutex::Autolock _l(mLock);
120281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
120381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // check for existing effect chain with the requested audio session
120481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        chain = getEffectChain_l(sessionId);
120581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (chain == 0) {
120681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // create a new chain for this session
120781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            ALOGV("createEffect_l() new effect chain for session %d", sessionId);
120881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            chain = new EffectChain(this, sessionId);
120981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            addEffectChain_l(chain);
121081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            chain->setStrategy(getStrategyForSession_l(sessionId));
121181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            chainCreated = true;
121281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        } else {
121381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            effect = chain->getEffectFromDesc_l(desc);
121481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
121581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
121681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
121781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
121881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (effect == 0) {
121981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            int id = mAudioFlinger->nextUniqueId();
122081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // Check CPU and memory usage
122181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
122281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if (lStatus != NO_ERROR) {
122381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                goto Exit;
122481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
122581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            effectRegistered = true;
122681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // create a new effect module if none present in the chain
122781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            effect = new EffectModule(this, chain, desc, id, sessionId);
122881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            lStatus = effect->status();
122981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if (lStatus != NO_ERROR) {
123081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                goto Exit;
123181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
12325baf2af52cd186633b7173196c1e4a4cd3435f22Eric Laurent            effect->setOffloaded(mType == OFFLOAD, mId);
12335baf2af52cd186633b7173196c1e4a4cd3435f22Eric Laurent
123481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            lStatus = chain->addEffect_l(effect);
123581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if (lStatus != NO_ERROR) {
123681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                goto Exit;
123781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
123881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            effectCreated = true;
123981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
124081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            effect->setDevice(mOutDevice);
124181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            effect->setDevice(mInDevice);
124281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            effect->setMode(mAudioFlinger->getMode());
124381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            effect->setAudioSource(mAudioSource);
124481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
124581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // create effect handle and connect it to effect module
124681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        handle = new EffectHandle(effect, client, effectClient, priority);
1247e75da4004b2c814987aa2adf8a76190f92d99c65Glenn Kasten        lStatus = handle->initCheck();
1248e75da4004b2c814987aa2adf8a76190f92d99c65Glenn Kasten        if (lStatus == OK) {
1249e75da4004b2c814987aa2adf8a76190f92d99c65Glenn Kasten            lStatus = effect->addHandle(handle.get());
1250e75da4004b2c814987aa2adf8a76190f92d99c65Glenn Kasten        }
125181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (enabled != NULL) {
125281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            *enabled = (int)effect->isEnabled();
125381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
125481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
125581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
125681784c37c61b09289654b979567a42bf73cd2b12Eric LaurentExit:
125781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
125881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        Mutex::Autolock _l(mLock);
125981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (effectCreated) {
126081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            chain->removeEffect_l(effect);
126181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
126281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (effectRegistered) {
126381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            AudioSystem::unregisterEffect(effect->id());
126481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
126581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (chainCreated) {
126681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            removeEffectChain_l(chain);
126781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
126881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        handle.clear();
126981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
127081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
12719156ef3e11b68cc4b6d3cea77f1f63673855a6d1Glenn Kasten    *status = lStatus;
127281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return handle;
127381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
127481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
127581784c37c61b09289654b979567a42bf73cd2b12Eric Laurentsp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
127681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
127781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
127881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return getEffect_l(sessionId, effectId);
127981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
128081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
128181784c37c61b09289654b979567a42bf73cd2b12Eric Laurentsp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
128281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
128381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    sp<EffectChain> chain = getEffectChain_l(sessionId);
128481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
128581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
128681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
128781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
128881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// PlaybackThread::mLock held
128981784c37c61b09289654b979567a42bf73cd2b12Eric Laurentstatus_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
129081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
129181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // check for existing effect chain with the requested audio session
129281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    int sessionId = effect->sessionId();
129381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    sp<EffectChain> chain = getEffectChain_l(sessionId);
129481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    bool chainCreated = false;
129581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
12965baf2af52cd186633b7173196c1e4a4cd3435f22Eric Laurent    ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
12975baf2af52cd186633b7173196c1e4a4cd3435f22Eric Laurent             "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
12985baf2af52cd186633b7173196c1e4a4cd3435f22Eric Laurent                    this, effect->desc().name, effect->desc().flags);
12995baf2af52cd186633b7173196c1e4a4cd3435f22Eric Laurent
130081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (chain == 0) {
130181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // create a new chain for this session
130281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        ALOGV("addEffect_l() new effect chain for session %d", sessionId);
130381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        chain = new EffectChain(this, sessionId);
130481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        addEffectChain_l(chain);
130581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        chain->setStrategy(getStrategyForSession_l(sessionId));
130681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        chainCreated = true;
130781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
130881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
130981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
131081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (chain->getEffectFromId_l(effect->id()) != 0) {
131181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        ALOGW("addEffect_l() %p effect %s already present in chain %p",
131281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                this, effect->desc().name, chain.get());
131381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        return BAD_VALUE;
131481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
131581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
13165baf2af52cd186633b7173196c1e4a4cd3435f22Eric Laurent    effect->setOffloaded(mType == OFFLOAD, mId);
13175baf2af52cd186633b7173196c1e4a4cd3435f22Eric Laurent
131881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    status_t status = chain->addEffect_l(effect);
131981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (status != NO_ERROR) {
132081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (chainCreated) {
132181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            removeEffectChain_l(chain);
132281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
132381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        return status;
132481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
132581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
132681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    effect->setDevice(mOutDevice);
132781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    effect->setDevice(mInDevice);
132881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    effect->setMode(mAudioFlinger->getMode());
132981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    effect->setAudioSource(mAudioSource);
133081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return NO_ERROR;
133181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
133281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
133381784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
133481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
133581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    ALOGV("removeEffect_l() %p effect %p", this, effect.get());
133681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    effect_descriptor_t desc = effect->desc();
133781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
133881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        detachAuxEffect_l(effect->id());
133981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
134081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
134181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    sp<EffectChain> chain = effect->chain().promote();
134281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (chain != 0) {
134381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // remove effect chain if removing last effect
134481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (chain->removeEffect_l(effect) == 0) {
134581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            removeEffectChain_l(chain);
134681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
134781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    } else {
134881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
134981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
135081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
135181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
135281784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::ThreadBase::lockEffectChains_l(
135381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        Vector< sp<AudioFlinger::EffectChain> >& effectChains)
135481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
135581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    effectChains = mEffectChains;
135681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    for (size_t i = 0; i < mEffectChains.size(); i++) {
135781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mEffectChains[i]->lock();
135881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
135981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
136081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
136181784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::ThreadBase::unlockEffectChains(
136281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
136381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
136481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    for (size_t i = 0; i < effectChains.size(); i++) {
136581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        effectChains[i]->unlock();
136681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
136781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
136881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
136981784c37c61b09289654b979567a42bf73cd2b12Eric Laurentsp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
137081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
137181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
137281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return getEffectChain_l(sessionId);
137381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
137481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
137581784c37c61b09289654b979567a42bf73cd2b12Eric Laurentsp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
137681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
137781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    size_t size = mEffectChains.size();
137881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    for (size_t i = 0; i < size; i++) {
137981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (mEffectChains[i]->sessionId() == sessionId) {
138081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            return mEffectChains[i];
138181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
138281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
138381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return 0;
138481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
138581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
138681784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
138781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
138881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
138981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    size_t size = mEffectChains.size();
139081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    for (size_t i = 0; i < size; i++) {
139181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mEffectChains[i]->setMode_l(mode);
139281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
139381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
139481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
139583b8808faad1e91690c64d7007348be8d9ebde73Eric Laurentvoid AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
139683b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent{
139783b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent    config->type = AUDIO_PORT_TYPE_MIX;
139883b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent    config->ext.mix.handle = mId;
139983b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent    config->sample_rate = mSampleRate;
140083b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent    config->format = mFormat;
140183b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent    config->channel_mask = mChannelMask;
140283b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent    config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
140383b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent                            AUDIO_PORT_CONFIG_FORMAT;
140483b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent}
140583b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent
140672e3f39146fce4686bd96f11057c051bea376dfbEric Laurentvoid AudioFlinger::ThreadBase::systemReady()
140772e3f39146fce4686bd96f11057c051bea376dfbEric Laurent{
140872e3f39146fce4686bd96f11057c051bea376dfbEric Laurent    Mutex::Autolock _l(mLock);
140972e3f39146fce4686bd96f11057c051bea376dfbEric Laurent    if (mSystemReady) {
141072e3f39146fce4686bd96f11057c051bea376dfbEric Laurent        return;
141172e3f39146fce4686bd96f11057c051bea376dfbEric Laurent    }
141272e3f39146fce4686bd96f11057c051bea376dfbEric Laurent    mSystemReady = true;
141372e3f39146fce4686bd96f11057c051bea376dfbEric Laurent
141472e3f39146fce4686bd96f11057c051bea376dfbEric Laurent    for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
141572e3f39146fce4686bd96f11057c051bea376dfbEric Laurent        sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
141672e3f39146fce4686bd96f11057c051bea376dfbEric Laurent    }
141772e3f39146fce4686bd96f11057c051bea376dfbEric Laurent    mPendingConfigEvents.clear();
141872e3f39146fce4686bd96f11057c051bea376dfbEric Laurent}
141972e3f39146fce4686bd96f11057c051bea376dfbEric Laurent
142083b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent
142181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// ----------------------------------------------------------------------------
142281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent//      Playback
142381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// ----------------------------------------------------------------------------
142481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
142581784c37c61b09289654b979567a42bf73cd2b12Eric LaurentAudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
142681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                                             AudioStreamOut* output,
142781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                                             audio_io_handle_t id,
142881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                                             audio_devices_t device,
142972e3f39146fce4686bd96f11057c051bea376dfbEric Laurent                                             type_t type,
143072e3f39146fce4686bd96f11057c051bea376dfbEric Laurent                                             bool systemReady)
143172e3f39146fce4686bd96f11057c051bea376dfbEric Laurent    :   ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
14322098f2744cedf2dc3fa36f608aa965a34602e7c0Andy Hung        mNormalFrameCount(0), mSinkBuffer(NULL),
14336146c08f0c3dd8b9e5788063aa433f304a810602Andy Hung        mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
143469aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung        mMixerBuffer(NULL),
143569aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung        mMixerBufferSize(0),
143669aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung        mMixerBufferFormat(AUDIO_FORMAT_INVALID),
143769aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung        mMixerBufferValid(false),
14386146c08f0c3dd8b9e5788063aa433f304a810602Andy Hung        mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
143998ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung        mEffectBuffer(NULL),
144098ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung        mEffectBufferSize(0),
144198ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung        mEffectBufferFormat(AUDIO_FORMAT_INVALID),
144298ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung        mEffectBufferValid(false),
1443c1fac191069774c7bfcb062edbb821ea56e7dbc0Glenn Kasten        mSuspended(0), mBytesWritten(0),
1444462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen        mActiveTracksGeneration(0),
144581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // mStreamTypes[] initialized in constructor body
144681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mOutput(output),
144781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
144881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mMixerStatus(MIXER_IDLE),
144981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mMixerStatusIgnoringFastTracks(MIXER_IDLE),
1450ad9cb8b88e4f8face23f01d8dc89fa769dacb50fEric Laurent        mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
1451bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        mBytesRemaining(0),
1452bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        mCurrentWriteLength(0),
1453bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        mUseAsyncWrite(false),
14543b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent        mWriteAckSequence(0),
14553b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent        mDrainSequence(0),
1456ede6c3b8b1147bc425f7b923882f559a513fe23bEric Laurent        mSignalPending(false),
145781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mScreenState(AudioFlinger::mScreenState),
145881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // index 0 is reserved for normal mixer's submix
1459bd096fd9d8e5fc0e62f98807f4818a06f70d0812Glenn Kasten        mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
1460d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent        mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
1461bd096fd9d8e5fc0e62f98807f4818a06f70d0812Glenn Kasten        // mLatchD, mLatchQ,
1462bd096fd9d8e5fc0e62f98807f4818a06f70d0812Glenn Kasten        mLatchDValid(false), mLatchQValid(false)
146381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
1464d7dca050c630bddbd73a6623271b34b4290460eeGlenn Kasten    snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1465d7dca050c630bddbd73a6623271b34b4290460eeGlenn Kasten    mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
146681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
146781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // Assumes constructor is called by AudioFlinger with it's mLock held, but
146881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // it would be safer to explicitly pass initial masterVolume/masterMute as
146981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // parameter.
147081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    //
147181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // If the HAL we are using has support for master volume or master mute,
147281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // then do not attenuate or mute during mixing (just leave the volume at 1.0
147381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // and the mute set to false).
147481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mMasterVolume = audioFlinger->masterVolume_l();
147581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mMasterMute = audioFlinger->masterMute_l();
147681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (mOutput && mOutput->audioHwDev) {
147781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (mOutput->audioHwDev->canSetMasterVolume()) {
147881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mMasterVolume = 1.0;
147981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
148081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
148181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (mOutput->audioHwDev->canSetMasterMute()) {
148281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mMasterMute = false;
148381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
148481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
148581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
1486deca2ae0a7cf8bc54ff3f30b7dc39bbc78b94c0dGlenn Kasten    readOutputParameters_l();
148781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
1488223fd5c9738e9665e495904d37d4632414b68c1eEric Laurent    // ++ operator does not compile
148966e4635cb09fadcaccf912f37c387396c428378aGlenn Kasten    for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
149081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            stream = (audio_stream_type_t) (stream + 1)) {
149181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
149281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
149381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
149481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
149581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
149681784c37c61b09289654b979567a42bf73cd2b12Eric LaurentAudioFlinger::PlaybackThread::~PlaybackThread()
149781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
14989e58b552f51b00b3b674102876bd6c77ef3da806Glenn Kasten    mAudioFlinger->unregisterWriter(mNBLogWriter);
1499010a1a1a552cdaad362cea8a0333b8906402dbcbAndy Hung    free(mSinkBuffer);
150069aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung    free(mMixerBuffer);
150198ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung    free(mEffectBuffer);
150281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
150381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
150481784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
150581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
150681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    dumpInternals(fd, args);
150781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    dumpTracks(fd, args);
150881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    dumpEffectChains(fd, args);
150981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
151081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
15110f11b51a57bc9062c4fe8af73747319cedabc5d6Glenn Kastenvoid AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
151281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
151381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    const size_t SIZE = 256;
151481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    char buffer[SIZE];
151581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    String8 result;
151681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
1517b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen    result.appendFormat("  Stream volumes in dB: ");
151881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
151981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        const stream_type_t *st = &mStreamTypes[i];
152081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (i > 0) {
152181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            result.appendFormat(", ");
152281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
152381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
152481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (st->mute) {
152581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            result.append("M");
152681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
152781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
152881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    result.append("\n");
152981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    write(fd, result.string(), result.length());
153081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    result.clear();
153181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
1532b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen    // These values are "raw"; they will wrap around.  See prepareTracks_l() for a better way.
1533b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen    FastTrackUnderruns underruns = getFastTrackUnderruns(0);
153487cebadd48710e42474756fc3513df678de045ceElliott Hughes    dprintf(fd, "  Normal mixer raw underrun counters: partial=%u empty=%u\n",
1535b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen            underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
1536b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen
1537b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen    size_t numtracks = mTracks.size();
1538b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen    size_t numactive = mActiveTracks.size();
153987cebadd48710e42474756fc3513df678de045ceElliott Hughes    dprintf(fd, "  %d Tracks", numtracks);
1540b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen    size_t numactiveseen = 0;
1541b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen    if (numtracks) {
154287cebadd48710e42474756fc3513df678de045ceElliott Hughes        dprintf(fd, " of which %d are active\n", numactive);
1543b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        Track::appendDumpHeader(result);
1544b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        for (size_t i = 0; i < numtracks; ++i) {
1545b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen            sp<Track> track = mTracks[i];
1546b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen            if (track != 0) {
1547b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen                bool active = mActiveTracks.indexOf(track) >= 0;
1548b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen                if (active) {
1549b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen                    numactiveseen++;
1550b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen                }
1551b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen                track->dump(buffer, SIZE, active);
1552b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen                result.append(buffer);
1553b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen            }
155481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
1555b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen    } else {
1556b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        result.append("\n");
155781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
1558b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen    if (numactiveseen != numactive) {
1559b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        // some tracks in the active list were not in the tracks list
1560b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        snprintf(buffer, SIZE, "  The following tracks are in the active list but"
1561b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen                " not in the track list\n");
1562b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        result.append(buffer);
1563b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        Track::appendDumpHeader(result);
1564b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        for (size_t i = 0; i < numactive; ++i) {
1565b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen            sp<Track> track = mActiveTracks[i].promote();
1566b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen            if (track != 0 && mTracks.indexOf(track) < 0) {
1567b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen                track->dump(buffer, SIZE, true);
1568b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen                result.append(buffer);
1569b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen            }
157081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
157181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
1572b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen
157381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    write(fd, result.string(), result.size());
157481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
157581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
157681784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
157781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
157897b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
157944182c206f7c5584ef2cf504da6be98fab665dbfGlenn Kasten
158044182c206f7c5584ef2cf504da6be98fab665dbfGlenn Kasten    dumpBase(fd, args);
158144182c206f7c5584ef2cf504da6be98fab665dbfGlenn Kasten
158287cebadd48710e42474756fc3513df678de045ceElliott Hughes    dprintf(fd, "  Normal frame count: %zu\n", mNormalFrameCount);
158387cebadd48710e42474756fc3513df678de045ceElliott Hughes    dprintf(fd, "  Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
158487cebadd48710e42474756fc3513df678de045ceElliott Hughes    dprintf(fd, "  Total writes: %d\n", mNumWrites);
158587cebadd48710e42474756fc3513df678de045ceElliott Hughes    dprintf(fd, "  Delayed writes: %d\n", mNumDelayedWrites);
158687cebadd48710e42474756fc3513df678de045ceElliott Hughes    dprintf(fd, "  Blocked in write: %s\n", mInWrite ? "yes" : "no");
158787cebadd48710e42474756fc3513df678de045ceElliott Hughes    dprintf(fd, "  Suspend count: %d\n", mSuspended);
158887cebadd48710e42474756fc3513df678de045ceElliott Hughes    dprintf(fd, "  Sink buffer : %p\n", mSinkBuffer);
158987cebadd48710e42474756fc3513df678de045ceElliott Hughes    dprintf(fd, "  Mixer buffer: %p\n", mMixerBuffer);
159087cebadd48710e42474756fc3513df678de045ceElliott Hughes    dprintf(fd, "  Effect buffer: %p\n", mEffectBuffer);
159187cebadd48710e42474756fc3513df678de045ceElliott Hughes    dprintf(fd, "  Fast track availMask=%#x\n", mFastTrackAvailMask);
159297b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    AudioStreamOut *output = mOutput;
159397b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
159497b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    String8 flagsAsString = outputFlagsToString(flags);
159597b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    dprintf(fd, "  AudioStreamOut: %p flags %#x (%s)\n", output, flags, flagsAsString.string());
159681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
159781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
159881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// Thread virtuals
159981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
160081784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::PlaybackThread::onFirstRef()
160181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
1602d7dca050c630bddbd73a6623271b34b4290460eeGlenn Kasten    run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
160381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
160481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
160581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// ThreadBase virtuals
160681784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::PlaybackThread::preExit()
160781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
160881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    ALOGV("  preExit()");
160981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // FIXME this is using hard-coded strings but in the future, this functionality will be
161081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    //       converted to use audio HAL extensions required to support tunneling
161181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
161281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
161381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
161481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
161581784c37c61b09289654b979567a42bf73cd2b12Eric Laurentsp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
161681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        const sp<AudioFlinger::Client>& client,
161781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        audio_stream_type_t streamType,
161881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        uint32_t sampleRate,
161981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        audio_format_t format,
162081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        audio_channel_mask_t channelMask,
162174935e44734c1ec235c2b6677db3e0dbefa5ddb8Glenn Kasten        size_t *pFrameCount,
162281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        const sp<IMemory>& sharedBuffer,
162381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        int sessionId,
162481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        IAudioFlinger::track_flags_t *flags,
162581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        pid_t tid,
1626462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen        int uid,
162781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        status_t *status)
162881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
162974935e44734c1ec235c2b6677db3e0dbefa5ddb8Glenn Kasten    size_t frameCount = *pFrameCount;
163081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    sp<Track> track;
163181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    status_t lStatus;
163281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
163381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
163481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
163581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // client expresses a preference for FAST, but we get the final say
163681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (*flags & IAudioFlinger::TRACK_FAST) {
163781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent      if (
163881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // not timed
163981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            (!isTimed) &&
164081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // either of these use cases:
164181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            (
164281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent              // use case 1: shared buffer with any frame count
164381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent              (
164481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                (sharedBuffer != 0)
164581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent              ) ||
16461dfe2f9c2d03fc8d0ed0cdfe0b9fb894bc0bcc11Glenn Kasten              // use case 2: frame count is default or at least as large as HAL
164781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent              (
16481dfe2f9c2d03fc8d0ed0cdfe0b9fb894bc0bcc11Glenn Kasten                // we formerly checked for a callback handler (non-0 tid),
16491dfe2f9c2d03fc8d0ed0cdfe0b9fb894bc0bcc11Glenn Kasten                // but that is no longer required for TRANSFER_OBTAIN mode
165081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                ((frameCount == 0) ||
1651b5fed68bcdd6f44424c9e4d12bfe9a3ff51bd62eGlenn Kasten                (frameCount >= mFrameCount))
165281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent              )
165381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            ) &&
165481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // PCM data
165581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            audio_is_linear_pcm(format) &&
16561f439e1cf16a29347288ba9ddd06c0b6d086a145Andy Hung            // TODO: extract as a data library function that checks that a computationally
16571f439e1cf16a29347288ba9ddd06c0b6d086a145Andy Hung            // expensive downmixer is not required: isFastOutputChannelConversion()
16589a59276fb465e492138e0576523b54079671e8f4Andy Hung            (channelMask == mChannelMask ||
16591f439e1cf16a29347288ba9ddd06c0b6d086a145Andy Hung                    mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
16601f439e1cf16a29347288ba9ddd06c0b6d086a145Andy Hung                    (channelMask == AUDIO_CHANNEL_OUT_MONO
16611f439e1cf16a29347288ba9ddd06c0b6d086a145Andy Hung                            /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
166281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // hardware sample rate
166381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            (sampleRate == mSampleRate) &&
166481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // normal mixer has an associated fast mixer
166581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            hasFastMixer() &&
166681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // there are sufficient fast track slots available
166781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            (mFastTrackAvailMask != 0)
166881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // FIXME test that MixerThread for this fast track has a capable output HAL
166981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // FIXME add a permission test also?
167081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        ) {
167181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
167281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (frameCount == 0) {
16730349009fd19f89f8414c428f6b71b369f7546085Glenn Kasten            // read the fast track multiplier property the first time it is needed
16740349009fd19f89f8414c428f6b71b369f7546085Glenn Kasten            int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
16750349009fd19f89f8414c428f6b71b369f7546085Glenn Kasten            if (ok != 0) {
16760349009fd19f89f8414c428f6b71b369f7546085Glenn Kasten                ALOGE("%s pthread_once failed: %d", __func__, ok);
16770349009fd19f89f8414c428f6b71b369f7546085Glenn Kasten            }
16780349009fd19f89f8414c428f6b71b369f7546085Glenn Kasten            frameCount = mFrameCount * sFastTrackMultiplier;
167981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
168081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
168181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                frameCount, mFrameCount);
168281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent      } else {
168381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
16846146c08f0c3dd8b9e5788063aa433f304a810602Andy Hung                "mFrameCount=%d format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
16856146c08f0c3dd8b9e5788063aa433f304a810602Andy Hung                "sampleRate=%u mSampleRate=%u "
168681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
16876146c08f0c3dd8b9e5788063aa433f304a810602Andy Hung                isTimed, sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
168881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                audio_is_linear_pcm(format),
168981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
169081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        *flags &= ~IAudioFlinger::TRACK_FAST;
16910e48d25606c82def035ad10a5b3923767a765cddAndy Hung      }
16920e48d25606c82def035ad10a5b3923767a765cddAndy Hung    }
16930e48d25606c82def035ad10a5b3923767a765cddAndy Hung    // For normal PCM streaming tracks, update minimum frame count.
16940e48d25606c82def035ad10a5b3923767a765cddAndy Hung    // For compatibility with AudioTrack calculation, buffer depth is forced
16950e48d25606c82def035ad10a5b3923767a765cddAndy Hung    // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
16960e48d25606c82def035ad10a5b3923767a765cddAndy Hung    // This is probably too conservative, but legacy application code may depend on it.
16970e48d25606c82def035ad10a5b3923767a765cddAndy Hung    // If you change this calculation, also review the start threshold which is related.
16980e48d25606c82def035ad10a5b3923767a765cddAndy Hung    if (!(*flags & IAudioFlinger::TRACK_FAST)
16990e48d25606c82def035ad10a5b3923767a765cddAndy Hung            && audio_is_linear_pcm(format) && sharedBuffer == 0) {
17008edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung        // this must match AudioTrack.cpp calculateMinFrameCount().
17018edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung        // TODO: Move to a common library
170281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
170381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
170481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (minBufCount < 2) {
170581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            minBufCount = 2;
170681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
17078edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung        // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
17088edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung        // or the client should compute and pass in a larger buffer request.
17090e48d25606c82def035ad10a5b3923767a765cddAndy Hung        size_t minFrameCount =
17108edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung                minBufCount * sourceFramesNeededWithTimestretch(
17118edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung                        sampleRate, mNormalFrameCount,
17128edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung                        mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
17130e48d25606c82def035ad10a5b3923767a765cddAndy Hung        if (frameCount < minFrameCount) { // including frameCount == 0
171481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            frameCount = minFrameCount;
171581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
171681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
171774935e44734c1ec235c2b6677db3e0dbefa5ddb8Glenn Kasten    *pFrameCount = frameCount;
171881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
1719c3df838434b37d8400eea2438083cc01a4c1cc71Glenn Kasten    switch (mType) {
1720c3df838434b37d8400eea2438083cc01a4c1cc71Glenn Kasten
1721c3df838434b37d8400eea2438083cc01a4c1cc71Glenn Kasten    case DIRECT:
1722993fa0603707e94ce259e95e56838a85b5ccbdc5Glenn Kasten        if (audio_is_linear_pcm(format)) {
172381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1724cac3daa6332bf6d1f7d26adc4a9915f3d7992dd9Glenn Kasten                ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1725cac3daa6332bf6d1f7d26adc4a9915f3d7992dd9Glenn Kasten                        "for output %p with format %#x",
172681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                        sampleRate, format, channelMask, mOutput, mFormat);
172781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                lStatus = BAD_VALUE;
172881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                goto Exit;
172981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
173081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
1731c3df838434b37d8400eea2438083cc01a4c1cc71Glenn Kasten        break;
1732c3df838434b37d8400eea2438083cc01a4c1cc71Glenn Kasten
1733c3df838434b37d8400eea2438083cc01a4c1cc71Glenn Kasten    case OFFLOAD:
1734bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1735cac3daa6332bf6d1f7d26adc4a9915f3d7992dd9Glenn Kasten            ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1736cac3daa6332bf6d1f7d26adc4a9915f3d7992dd9Glenn Kasten                    "for output %p with format %#x",
1737bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                    sampleRate, format, channelMask, mOutput, mFormat);
1738bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            lStatus = BAD_VALUE;
1739bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            goto Exit;
1740bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        }
1741c3df838434b37d8400eea2438083cc01a4c1cc71Glenn Kasten        break;
1742c3df838434b37d8400eea2438083cc01a4c1cc71Glenn Kasten
1743c3df838434b37d8400eea2438083cc01a4c1cc71Glenn Kasten    default:
1744993fa0603707e94ce259e95e56838a85b5ccbdc5Glenn Kasten        if (!audio_is_linear_pcm(format)) {
1745cac3daa6332bf6d1f7d26adc4a9915f3d7992dd9Glenn Kasten                ALOGE("createTrack_l() Bad parameter: format %#x \""
1746cac3daa6332bf6d1f7d26adc4a9915f3d7992dd9Glenn Kasten                        "for output %p with format %#x",
1747bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                        format, mOutput, mFormat);
1748bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                lStatus = BAD_VALUE;
1749bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                goto Exit;
1750bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        }
1751cd04484f4837b8ca0041d118286ab6a98e84fc75Andy Hung        if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
175281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
175381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            lStatus = BAD_VALUE;
175481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            goto Exit;
175581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
1756c3df838434b37d8400eea2438083cc01a4c1cc71Glenn Kasten        break;
1757c3df838434b37d8400eea2438083cc01a4c1cc71Glenn Kasten
175881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
175981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
176081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    lStatus = initCheck();
176181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (lStatus != NO_ERROR) {
176215e5798908ccac14e10c84834eaf08c42931bd06Glenn Kasten        ALOGE("createTrack_l() audio driver not initialized");
176381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        goto Exit;
176481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
176581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
176681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    { // scope for mLock
176781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        Mutex::Autolock _l(mLock);
176881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
176981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // all tracks in same audio session must share the same routing strategy otherwise
177081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // conflicts will happen when tracks are moved from one output to another by audio policy
177181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // manager
177281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
177381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        for (size_t i = 0; i < mTracks.size(); ++i) {
177481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            sp<Track> t = mTracks[i];
177583b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent            if (t != 0 && t->isExternalTrack()) {
177681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
177781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                if (sessionId == t->sessionId() && strategy != actual) {
177881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
177981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                            strategy, actual);
178081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    lStatus = BAD_VALUE;
178181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    goto Exit;
178281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
178381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
178481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
178581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
178681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (!isTimed) {
178781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            track = new Track(this, client, streamType, sampleRate, format,
178883b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent                              channelMask, frameCount, NULL, sharedBuffer,
178983b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent                              sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
179081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        } else {
179181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            track = TimedTrack::create(this, client, streamType, sampleRate, format,
1792462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen                    channelMask, frameCount, sharedBuffer, sessionId, uid);
179381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
1794030033342a6ea17003e6af38a56c7edc6d2ead01Glenn Kasten
1795030033342a6ea17003e6af38a56c7edc6d2ead01Glenn Kasten        // new Track always returns non-NULL,
1796030033342a6ea17003e6af38a56c7edc6d2ead01Glenn Kasten        // but TimedTrack::create() is a factory that could fail by returning NULL
1797030033342a6ea17003e6af38a56c7edc6d2ead01Glenn Kasten        lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1798030033342a6ea17003e6af38a56c7edc6d2ead01Glenn Kasten        if (lStatus != NO_ERROR) {
17990cde076ddb283c84c3801a2df4cc3df99bd1577fGlenn Kasten            ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
180003e9e83c47ab4a518da0a1f36b8f702f59221c95Haynes Mathew George            // track must be cleared from the caller as the caller has the AF lock
180181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            goto Exit;
180281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
180381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mTracks.add(track);
180481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
180581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sp<EffectChain> chain = getEffectChain_l(sessionId);
180681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (chain != 0) {
180781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
180881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            track->setMainBuffer(chain->inBuffer());
180981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
181081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            chain->incTrackCnt();
181181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
181281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
181381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
181481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            pid_t callingPid = IPCThreadState::self()->getCallingPid();
181581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
181681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // so ask activity manager to do this on our behalf
181781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
181881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
181981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
182081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
182181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    lStatus = NO_ERROR;
182281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
182381784c37c61b09289654b979567a42bf73cd2b12Eric LaurentExit:
18249156ef3e11b68cc4b6d3cea77f1f63673855a6d1Glenn Kasten    *status = lStatus;
182581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return track;
182681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
182781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
182881784c37c61b09289654b979567a42bf73cd2b12Eric Laurentuint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
182981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
183081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return latency;
183181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
183281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
183381784c37c61b09289654b979567a42bf73cd2b12Eric Laurentuint32_t AudioFlinger::PlaybackThread::latency() const
183481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
183581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
183681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return latency_l();
183781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
183881784c37c61b09289654b979567a42bf73cd2b12Eric Laurentuint32_t AudioFlinger::PlaybackThread::latency_l() const
183981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
184081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (initCheck() == NO_ERROR) {
184181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
184281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    } else {
184381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        return 0;
184481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
184581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
184681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
184781784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::PlaybackThread::setMasterVolume(float value)
184881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
184981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
185081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // Don't apply master volume in SW if our HAL can do it for us.
185181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (mOutput && mOutput->audioHwDev &&
185281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mOutput->audioHwDev->canSetMasterVolume()) {
185381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mMasterVolume = 1.0;
185481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    } else {
185581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mMasterVolume = value;
185681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
185781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
185881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
185981784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::PlaybackThread::setMasterMute(bool muted)
186081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
186181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
186281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // Don't apply master mute in SW if our HAL can do it for us.
186381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (mOutput && mOutput->audioHwDev &&
186481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mOutput->audioHwDev->canSetMasterMute()) {
186581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mMasterMute = false;
186681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    } else {
186781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mMasterMute = muted;
186881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
186981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
187081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
187181784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
187281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
187381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
187481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mStreamTypes[stream].volume = value;
1875ede6c3b8b1147bc425f7b923882f559a513fe23bEric Laurent    broadcast_l();
187681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
187781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
187881784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
187981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
188081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
188181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mStreamTypes[stream].mute = muted;
1882ede6c3b8b1147bc425f7b923882f559a513fe23bEric Laurent    broadcast_l();
188381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
188481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
188581784c37c61b09289654b979567a42bf73cd2b12Eric Laurentfloat AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
188681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
188781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
188881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return mStreamTypes[stream].volume;
188981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
189081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
189181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// addTrack_l() must be called with ThreadBase::mLock held
189281784c37c61b09289654b979567a42bf73cd2b12Eric Laurentstatus_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
189381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
189481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    status_t status = ALREADY_EXISTS;
189581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
189681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // set retry count for buffer fill
189781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    track->mRetryCount = kMaxTrackStartupRetries;
189881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (mActiveTracks.indexOf(track) < 0) {
189981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // the track is newly added, make sure it fills up all its
190081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // buffers before playing. This is to ensure the client will
190181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // effectively get the latency it requested.
190283b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent        if (track->isExternalTrack()) {
1903bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            TrackBase::track_state state = track->mState;
1904bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            mLock.unlock();
1905e83b55dc29ca16092ba02f36f55fa6e0e37fd78cEric Laurent            status = AudioSystem::startOutput(mId, track->streamType(),
1906e83b55dc29ca16092ba02f36f55fa6e0e37fd78cEric Laurent                                              (audio_session_t)track->sessionId());
1907bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            mLock.lock();
1908bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            // abort track was stopped/paused while we released the lock
1909bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            if (state != track->mState) {
1910bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                if (status == NO_ERROR) {
1911bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                    mLock.unlock();
1912e83b55dc29ca16092ba02f36f55fa6e0e37fd78cEric Laurent                    AudioSystem::stopOutput(mId, track->streamType(),
1913e83b55dc29ca16092ba02f36f55fa6e0e37fd78cEric Laurent                                            (audio_session_t)track->sessionId());
1914bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                    mLock.lock();
1915bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                }
1916bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                return INVALID_OPERATION;
1917bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            }
1918bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            // abort if start is rejected by audio policy manager
1919bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            if (status != NO_ERROR) {
1920bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                return PERMISSION_DENIED;
1921bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            }
1922bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent#ifdef ADD_BATTERY_DATA
1923bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            // to track the speaker usage
1924bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1925bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent#endif
1926bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        }
1927bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
19289f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
192981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        track->mResetDone = false;
193081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        track->mPresentationCompleteFrames = 0;
193181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mActiveTracks.add(track);
1932462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen        mWakeLockUids.add(track->uid());
1933462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen        mActiveTracksGeneration++;
1934fd4779740ec3e9e865d5514464df26d015354388Eric Laurent        mLatestActiveTrack = track;
1935d0107bcd44fe608b0c00a8843d19fb6356c4cb69Eric Laurent        sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1936d0107bcd44fe608b0c00a8843d19fb6356c4cb69Eric Laurent        if (chain != 0) {
1937d0107bcd44fe608b0c00a8843d19fb6356c4cb69Eric Laurent            ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1938d0107bcd44fe608b0c00a8843d19fb6356c4cb69Eric Laurent                    track->sessionId());
1939d0107bcd44fe608b0c00a8843d19fb6356c4cb69Eric Laurent            chain->incActiveTrackCnt();
194081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
194181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
194281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        status = NO_ERROR;
194381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
194481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
19454c6a433d74d5ae8b9bc0557207e3ced43bf34a25Haynes Mathew George    onAddNewTrack_l();
194681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return status;
194781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
194881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
1949bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurentbool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
195081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
1951bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    track->terminate();
195281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // active tracks are removed by threadLoop()
1953bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1954bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    track->mState = TrackBase::STOPPED;
1955bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    if (!trackActive) {
195681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        removeTrack_l(track);
1957ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent    } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
1958bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        track->mState = TrackBase::STOPPING_1;
195981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
1960bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
1961bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    return trackActive;
196281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
196381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
196481784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
196581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
196681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
196781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mTracks.remove(track);
196881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    deleteTrackName_l(track->name());
196981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // redundant as track is about to be destroyed, for dumpsys only
197081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    track->mName = -1;
197181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (track->isFastTrack()) {
197281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        int index = track->mFastIndex;
197381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
197481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
197581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mFastTrackAvailMask |= 1 << index;
197681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // redundant as track is about to be destroyed, for dumpsys only
197781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        track->mFastIndex = -1;
197881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
197981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    sp<EffectChain> chain = getEffectChain_l(track->sessionId());
198081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (chain != 0) {
198181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        chain->decTrackCnt();
198281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
198381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
198481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
1985ede6c3b8b1147bc425f7b923882f559a513fe23bEric Laurentvoid AudioFlinger::PlaybackThread::broadcast_l()
1986bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent{
1987bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    // Thread could be blocked waiting for async
1988bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    // so signal it to handle state changes immediately
1989bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1990bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    // be lost so we also flag to prevent it blocking on mWaitWorkCV
1991bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    mSignalPending = true;
1992ede6c3b8b1147bc425f7b923882f559a513fe23bEric Laurent    mWaitWorkCV.broadcast();
1993bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent}
1994bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
199581784c37c61b09289654b979567a42bf73cd2b12Eric LaurentString8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
199681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
199781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
199881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (initCheck() != NO_ERROR) {
1999d8ea699dc8e7dac58bb32e9cdb31b0758da25817Glenn Kasten        return String8();
200081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
200181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
2002d8ea699dc8e7dac58bb32e9cdb31b0758da25817Glenn Kasten    char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
2003d8ea699dc8e7dac58bb32e9cdb31b0758da25817Glenn Kasten    const String8 out_s8(s);
200481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    free(s);
200581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return out_s8;
200681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
200781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
20087c1ec5f038e63a5eb8b04434577c25bc23f5f410Eric Laurentvoid AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
200973e26b661af50be2c0a4ff6c9ac85f7347a8b235Eric Laurent    sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
201073e26b661af50be2c0a4ff6c9ac85f7347a8b235Eric Laurent    ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
201181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
201273e26b661af50be2c0a4ff6c9ac85f7347a8b235Eric Laurent    desc->mIoHandle = mId;
201381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
201481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    switch (event) {
201573e26b661af50be2c0a4ff6c9ac85f7347a8b235Eric Laurent    case AUDIO_OUTPUT_OPENED:
201673e26b661af50be2c0a4ff6c9ac85f7347a8b235Eric Laurent    case AUDIO_OUTPUT_CONFIG_CHANGED:
2017296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent        desc->mPatch = mPatch;
201873e26b661af50be2c0a4ff6c9ac85f7347a8b235Eric Laurent        desc->mChannelMask = mChannelMask;
201973e26b661af50be2c0a4ff6c9ac85f7347a8b235Eric Laurent        desc->mSamplingRate = mSampleRate;
202073e26b661af50be2c0a4ff6c9ac85f7347a8b235Eric Laurent        desc->mFormat = mFormat;
202173e26b661af50be2c0a4ff6c9ac85f7347a8b235Eric Laurent        desc->mFrameCount = mNormalFrameCount; // FIXME see
202281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                                             // AudioFlinger::frameCount(audio_io_handle_t)
202373e26b661af50be2c0a4ff6c9ac85f7347a8b235Eric Laurent        desc->mLatency = latency_l();
202481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        break;
202581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
202673e26b661af50be2c0a4ff6c9ac85f7347a8b235Eric Laurent    case AUDIO_OUTPUT_CLOSED:
202781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    default:
202881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        break;
202981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
20307c1ec5f038e63a5eb8b04434577c25bc23f5f410Eric Laurent    mAudioFlinger->ioConfigChanged(event, desc, pid);
203181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
203281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
2033bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurentvoid AudioFlinger::PlaybackThread::writeCallback()
2034bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent{
2035bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    ALOG_ASSERT(mCallbackThread != 0);
20363b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent    mCallbackThread->resetWriteBlocked();
2037bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent}
2038bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
2039bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurentvoid AudioFlinger::PlaybackThread::drainCallback()
2040bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent{
2041bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    ALOG_ASSERT(mCallbackThread != 0);
20423b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent    mCallbackThread->resetDraining();
2043bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent}
2044bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
20453b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurentvoid AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
2046bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent{
2047bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    Mutex::Autolock _l(mLock);
20483b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent    // reject out of sequence requests
20493b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent    if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
20503b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent        mWriteAckSequence &= ~1;
2051bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        mWaitWorkCV.signal();
2052bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    }
2053bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent}
2054bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
20553b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurentvoid AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
2056bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent{
2057bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    Mutex::Autolock _l(mLock);
20583b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent    // reject out of sequence requests
20593b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent    if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
20603b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent        mDrainSequence &= ~1;
2061bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        mWaitWorkCV.signal();
2062bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    }
2063bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent}
2064bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
2065bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent// static
2066bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurentint AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
20670f11b51a57bc9062c4fe8af73747319cedabc5d6Glenn Kasten                                                void *param __unused,
2068bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                                                void *cookie)
2069bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent{
2070bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
2071bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    ALOGV("asyncCallback() event %d", event);
2072bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    switch (event) {
2073bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    case STREAM_CBK_EVENT_WRITE_READY:
2074bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        me->writeCallback();
2075bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        break;
2076bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    case STREAM_CBK_EVENT_DRAIN_READY:
2077bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        me->drainCallback();
2078bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        break;
2079bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    default:
2080bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        ALOGW("asyncCallback() unknown event %d", event);
2081bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        break;
2082bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    }
2083bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    return 0;
2084bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent}
2085bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
2086deca2ae0a7cf8bc54ff3f30b7dc39bbc78b94c0dGlenn Kastenvoid AudioFlinger::PlaybackThread::readOutputParameters_l()
208781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
2088adad3d7d935da176ff24941b4ae9edf7340e9b96Glenn Kasten    // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
2089ca5e6143740299c877d69e97f7968cd04476d32cPhil Burk    mSampleRate = mOutput->getSampleRate();
2090ca5e6143740299c877d69e97f7968cd04476d32cPhil Burk    mChannelMask = mOutput->getChannelMask();
20917fc97ba08e2850f3f16db704b78ce78e3dbe1ff0Glenn Kasten    if (!audio_is_output_channel(mChannelMask)) {
2092adad3d7d935da176ff24941b4ae9edf7340e9b96Glenn Kasten        LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
20937fc97ba08e2850f3f16db704b78ce78e3dbe1ff0Glenn Kasten    }
20949a59276fb465e492138e0576523b54079671e8f4Andy Hung    if ((mType == MIXER || mType == DUPLICATING)
20959a59276fb465e492138e0576523b54079671e8f4Andy Hung            && !isValidPcmSinkChannelMask(mChannelMask)) {
20969a59276fb465e492138e0576523b54079671e8f4Andy Hung        LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
20979a59276fb465e492138e0576523b54079671e8f4Andy Hung                mChannelMask);
20987fc97ba08e2850f3f16db704b78ce78e3dbe1ff0Glenn Kasten    }
2099e541269be94f3a1072932d51537905b120ef4733Andy Hung    mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
2100ca5e6143740299c877d69e97f7968cd04476d32cPhil Burk
2101ca5e6143740299c877d69e97f7968cd04476d32cPhil Burk    // Get actual HAL format.
2102463be250de73907965faa6a216c00312bf81e049Andy Hung    mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
2103ca5e6143740299c877d69e97f7968cd04476d32cPhil Burk    // Get format from the shim, which will be different than the HAL format
2104ca5e6143740299c877d69e97f7968cd04476d32cPhil Burk    // if playing compressed audio over HDMI passthrough.
2105ca5e6143740299c877d69e97f7968cd04476d32cPhil Burk    mFormat = mOutput->getFormat();
21067fc97ba08e2850f3f16db704b78ce78e3dbe1ff0Glenn Kasten    if (!audio_is_valid_format(mFormat)) {
2107adad3d7d935da176ff24941b4ae9edf7340e9b96Glenn Kasten        LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
21087fc97ba08e2850f3f16db704b78ce78e3dbe1ff0Glenn Kasten    }
21096146c08f0c3dd8b9e5788063aa433f304a810602Andy Hung    if ((mType == MIXER || mType == DUPLICATING)
21106146c08f0c3dd8b9e5788063aa433f304a810602Andy Hung            && !isValidPcmSinkFormat(mFormat)) {
21116146c08f0c3dd8b9e5788063aa433f304a810602Andy Hung        LOG_FATAL("HAL format %#x not supported for mixed output",
21126146c08f0c3dd8b9e5788063aa433f304a810602Andy Hung                mFormat);
21137fc97ba08e2850f3f16db704b78ce78e3dbe1ff0Glenn Kasten    }
2114062e67a26e0553dd142be622821f493df541f0c6Phil Burk    mFrameSize = mOutput->getFrameSize();
211570949c47fbae3f836d15f040551d7631be3ed7c2Glenn Kasten    mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
211670949c47fbae3f836d15f040551d7631be3ed7c2Glenn Kasten    mFrameCount = mBufferSize / mFrameSize;
211781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (mFrameCount & 15) {
211881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
211981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                mFrameCount);
212081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
212181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
2122bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
2123bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            (mOutput->stream->set_callback != NULL)) {
2124bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        if (mOutput->stream->set_callback(mOutput->stream,
2125bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                                      AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
2126bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            mUseAsyncWrite = true;
21274de95592980dba88a35b3dc8f3fd045588387a4fEric Laurent            mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
2128bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        }
2129bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    }
2130bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
2131d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    mHwSupportsPause = false;
2132d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
2133d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent        if (mOutput->stream->pause != NULL) {
2134d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent            if (mOutput->stream->resume != NULL) {
2135d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent                mHwSupportsPause = true;
2136d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent            } else {
2137d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent                ALOGW("direct output implements pause but not resume");
2138d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent            }
2139d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent        } else if (mOutput->stream->resume != NULL) {
2140d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent            ALOGW("direct output implements resume but not pause");
2141d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent        }
2142d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    }
21436fc2a7c81f62b1e21487ae37e11aae6241bc3eadPhil Burk    if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
21446fc2a7c81f62b1e21487ae37e11aae6241bc3eadPhil Burk        LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
21456fc2a7c81f62b1e21487ae37e11aae6241bc3eadPhil Burk    }
2146d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent
2147fbfc3959f4aac839445edc7075532067fef497c2Andy Hung    if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2148fbfc3959f4aac839445edc7075532067fef497c2Andy Hung        // For best precision, we use float instead of the associated output
2149fbfc3959f4aac839445edc7075532067fef497c2Andy Hung        // device format (typically PCM 16 bit).
2150fbfc3959f4aac839445edc7075532067fef497c2Andy Hung
2151fbfc3959f4aac839445edc7075532067fef497c2Andy Hung        mFormat = AUDIO_FORMAT_PCM_FLOAT;
2152fbfc3959f4aac839445edc7075532067fef497c2Andy Hung        mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2153fbfc3959f4aac839445edc7075532067fef497c2Andy Hung        mBufferSize = mFrameSize * mFrameCount;
2154fbfc3959f4aac839445edc7075532067fef497c2Andy Hung
2155fbfc3959f4aac839445edc7075532067fef497c2Andy Hung        // TODO: We currently use the associated output device channel mask and sample rate.
2156fbfc3959f4aac839445edc7075532067fef497c2Andy Hung        // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2157fbfc3959f4aac839445edc7075532067fef497c2Andy Hung        // (if a valid mask) to avoid premature downmix.
2158fbfc3959f4aac839445edc7075532067fef497c2Andy Hung        // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2159fbfc3959f4aac839445edc7075532067fef497c2Andy Hung        // instead of the output device sample rate to avoid loss of high frequency information.
2160fbfc3959f4aac839445edc7075532067fef497c2Andy Hung        // This may need to be updated as MixerThread/OutputTracks are added and not here.
2161fbfc3959f4aac839445edc7075532067fef497c2Andy Hung    }
2162fbfc3959f4aac839445edc7075532067fef497c2Andy Hung
216309a5007b17acb49d25cfa386a2e2534d942e8854Andy Hung    // Calculate size of normal sink buffer relative to the HAL output buffer size
216481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    double multiplier = 1.0;
216581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
216681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            kUseFastMixer == FastMixer_Dynamic)) {
216709a5007b17acb49d25cfa386a2e2534d942e8854Andy Hung        size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
216809a5007b17acb49d25cfa386a2e2534d942e8854Andy Hung        size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
216981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
217081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
217181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        maxNormalFrameCount = maxNormalFrameCount & ~15;
217281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (maxNormalFrameCount < minNormalFrameCount) {
217381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            maxNormalFrameCount = minNormalFrameCount;
217481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
217581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        multiplier = (double) minNormalFrameCount / (double) mFrameCount;
217681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (multiplier <= 1.0) {
217781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            multiplier = 1.0;
217881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        } else if (multiplier <= 2.0) {
217981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if (2 * mFrameCount <= maxNormalFrameCount) {
218081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                multiplier = 2.0;
218181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            } else {
218281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
218381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
218481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        } else {
218581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
218609a5007b17acb49d25cfa386a2e2534d942e8854Andy Hung            // SRC (it would be unusual for the normal sink buffer size to not be a multiple of fast
218781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // track, but we sometimes have to do this to satisfy the maximum frame count
218881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // constraint)
218981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // FIXME this rounding up should not be done if no HAL SRC
219081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            uint32_t truncMult = (uint32_t) multiplier;
219181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if ((truncMult & 1)) {
219281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
219381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    ++truncMult;
219481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
219581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
219681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            multiplier = (double) truncMult;
219781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
219881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
219981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mNormalFrameCount = multiplier * mFrameCount;
220081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // round up to nearest 16 frames to satisfy AudioMixer
2201ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent    if (mType == MIXER || mType == DUPLICATING) {
2202ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent        mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2203ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent    }
220409a5007b17acb49d25cfa386a2e2534d942e8854Andy Hung    ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
220581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mNormalFrameCount);
220681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
220708fb1743f80437c38b4094070d851ea7f6d485e5Andy Hung    // Check if we want to throttle the processing to no more than 2x normal rate
220808fb1743f80437c38b4094070d851ea7f6d485e5Andy Hung    mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
220940eb1a1f8871909c272e72afaf7d5af84fea2412Andy Hung    mThreadThrottleTimeMs = 0;
221040eb1a1f8871909c272e72afaf7d5af84fea2412Andy Hung    mThreadThrottleEndMs = 0;
221108fb1743f80437c38b4094070d851ea7f6d485e5Andy Hung    mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
221208fb1743f80437c38b4094070d851ea7f6d485e5Andy Hung
2213010a1a1a552cdaad362cea8a0333b8906402dbcbAndy Hung    // mSinkBuffer is the sink buffer.  Size is always multiple-of-16 frames.
2214010a1a1a552cdaad362cea8a0333b8906402dbcbAndy Hung    // Originally this was int16_t[] array, need to remove legacy implications.
2215010a1a1a552cdaad362cea8a0333b8906402dbcbAndy Hung    free(mSinkBuffer);
2216010a1a1a552cdaad362cea8a0333b8906402dbcbAndy Hung    mSinkBuffer = NULL;
22175b10a2037a835e790994b9ebec3c2e55052f1f3bAndy Hung    // For sink buffer size, we use the frame size from the downstream sink to avoid problems
22185b10a2037a835e790994b9ebec3c2e55052f1f3bAndy Hung    // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
22195b10a2037a835e790994b9ebec3c2e55052f1f3bAndy Hung    const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
2220010a1a1a552cdaad362cea8a0333b8906402dbcbAndy Hung    (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
222181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
222269aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung    // We resize the mMixerBuffer according to the requirements of the sink buffer which
222369aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung    // drives the output.
222469aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung    free(mMixerBuffer);
222569aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung    mMixerBuffer = NULL;
222669aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung    if (mMixerBufferEnabled) {
222769aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung        mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
222869aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung        mMixerBufferSize = mNormalFrameCount * mChannelCount
222969aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung                * audio_bytes_per_sample(mMixerBufferFormat);
223069aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung        (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
223169aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung    }
223298ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung    free(mEffectBuffer);
223398ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung    mEffectBuffer = NULL;
223498ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung    if (mEffectBufferEnabled) {
223598ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung        mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
223698ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung        mEffectBufferSize = mNormalFrameCount * mChannelCount
223798ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung                * audio_bytes_per_sample(mEffectBufferFormat);
223898ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung        (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
223998ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung    }
224069aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung
224181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // force reconfiguration of effect chains and engines to take new buffer size and audio
224281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // parameters into account
2243deca2ae0a7cf8bc54ff3f30b7dc39bbc78b94c0dGlenn Kasten    // Note that mLock is not held when readOutputParameters_l() is called from the constructor
224481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
224581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // matter.
224681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
224781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Vector< sp<EffectChain> > effectChains = mEffectChains;
224881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    for (size_t i = 0; i < effectChains.size(); i ++) {
224981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
225081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
225181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
225281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
225381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
2254377b2ec9a2885f9b6405b07ba900a9e3f4349c38Kévin PETITstatus_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
225581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
225681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (halFrames == NULL || dspFrames == NULL) {
225781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        return BAD_VALUE;
225881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
225981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
226081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (initCheck() != NO_ERROR) {
226181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        return INVALID_OPERATION;
226281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
226381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    size_t framesWritten = mBytesWritten / mFrameSize;
226481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    *halFrames = framesWritten;
226581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
226681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (isSuspended()) {
226781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // return an estimation of rendered frames when the output is suspended
226881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
226981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
227081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        return NO_ERROR;
227181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    } else {
2272377b2ec9a2885f9b6405b07ba900a9e3f4349c38Kévin PETIT        status_t status;
2273377b2ec9a2885f9b6405b07ba900a9e3f4349c38Kévin PETIT        uint32_t frames;
2274062e67a26e0553dd142be622821f493df541f0c6Phil Burk        status = mOutput->getRenderPosition(&frames);
2275377b2ec9a2885f9b6405b07ba900a9e3f4349c38Kévin PETIT        *dspFrames = (size_t)frames;
2276377b2ec9a2885f9b6405b07ba900a9e3f4349c38Kévin PETIT        return status;
227781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
227881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
227981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
228081784c37c61b09289654b979567a42bf73cd2b12Eric Laurentuint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
228181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
228281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
228381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    uint32_t result = 0;
228481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (getEffectChain_l(sessionId) != 0) {
228581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        result = EFFECT_SESSION;
228681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
228781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
228881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    for (size_t i = 0; i < mTracks.size(); ++i) {
228981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sp<Track> track = mTracks[i];
22905736c35b841de56ce394b4879389f669b61425e6Glenn Kasten        if (sessionId == track->sessionId() && !track->isInvalid()) {
229181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            result |= TRACK_SESSION;
229281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            break;
229381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
229481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
229581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
229681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return result;
229781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
229881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
229981784c37c61b09289654b979567a42bf73cd2b12Eric Laurentuint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
230081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
230181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
230281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
230381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
230481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
230581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
230681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    for (size_t i = 0; i < mTracks.size(); i++) {
230781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sp<Track> track = mTracks[i];
23085736c35b841de56ce394b4879389f669b61425e6Glenn Kasten        if (sessionId == track->sessionId() && !track->isInvalid()) {
230981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            return AudioSystem::getStrategyForStream(track->streamType());
231081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
231181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
231281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
231381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
231481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
231581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
2316062e67a26e0553dd142be622821f493df541f0c6Phil BurkAudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
231781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
231881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
231981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return mOutput;
232081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
232181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
2322062e67a26e0553dd142be622821f493df541f0c6Phil BurkAudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
232381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
232481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
232581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    AudioStreamOut *output = mOutput;
232681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mOutput = NULL;
232781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // FIXME FastMixer might also have a raw ptr to mOutputSink;
232881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    //       must push a NULL and wait for ack
232981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mOutputSink.clear();
233081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mPipeSink.clear();
233181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mNormalSink.clear();
233281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return output;
233381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
233481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
233581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// this method must always be called either with ThreadBase mLock held or inside the thread loop
233681784c37c61b09289654b979567a42bf73cd2b12Eric Laurentaudio_stream_t* AudioFlinger::PlaybackThread::stream() const
233781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
233881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (mOutput == NULL) {
233981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        return NULL;
234081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
234181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return &mOutput->stream->common;
234281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
234381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
234481784c37c61b09289654b979567a42bf73cd2b12Eric Laurentuint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
234581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
234681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
234781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
234881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
234981784c37c61b09289654b979567a42bf73cd2b12Eric Laurentstatus_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
235081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
235181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (!isValidSyncEvent(event)) {
235281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        return BAD_VALUE;
235381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
235481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
235581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
235681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
235781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    for (size_t i = 0; i < mTracks.size(); ++i) {
235881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sp<Track> track = mTracks[i];
235981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (event->triggerSession() == track->sessionId()) {
236081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            (void) track->setSyncEvent(event);
236181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            return NO_ERROR;
236281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
236381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
236481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
236581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return NAME_NOT_FOUND;
236681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
236781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
236881784c37c61b09289654b979567a42bf73cd2b12Eric Laurentbool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
236981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
237081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
237181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
237281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
237381784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::PlaybackThread::threadLoop_removeTracks(
237481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        const Vector< sp<Track> >& tracksToRemove)
237581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
237681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    size_t count = tracksToRemove.size();
237734fca34606b448e6b71c2942f63cb13a0aebd620Glenn Kasten    if (count > 0) {
237881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        for (size_t i = 0 ; i < count ; i++) {
237981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            const sp<Track>& track = tracksToRemove.itemAt(i);
238083b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent            if (track->isExternalTrack()) {
2381e83b55dc29ca16092ba02f36f55fa6e0e37fd78cEric Laurent                AudioSystem::stopOutput(mId, track->streamType(),
2382e83b55dc29ca16092ba02f36f55fa6e0e37fd78cEric Laurent                                        (audio_session_t)track->sessionId());
2383bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent#ifdef ADD_BATTERY_DATA
2384bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                // to track the speaker usage
2385bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2386bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent#endif
2387bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                if (track->isTerminated()) {
2388e83b55dc29ca16092ba02f36f55fa6e0e37fd78cEric Laurent                    AudioSystem::releaseOutput(mId, track->streamType(),
2389e83b55dc29ca16092ba02f36f55fa6e0e37fd78cEric Laurent                                               (audio_session_t)track->sessionId());
2390bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                }
239181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
239281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
239381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
239481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
239581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
239681784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::PlaybackThread::checkSilentMode_l()
239781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
239881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (!mMasterMute) {
239981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        char value[PROPERTY_VALUE_MAX];
240081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (property_get("ro.audio.silent", value, "0") > 0) {
240181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            char *endptr;
240281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            unsigned long ul = strtoul(value, &endptr, 0);
240381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if (*endptr == '\0' && ul != 0) {
240481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                ALOGD("Silence is golden");
240581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // The setprop command will not allow a property to be changed after
240681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // the first time it is set, so we don't have to worry about un-muting.
240781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                setMasterMute_l(true);
240881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
240981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
241081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
241181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
241281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
241381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// shared by MIXER and DIRECT, overridden by DUPLICATING
2414bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurentssize_t AudioFlinger::PlaybackThread::threadLoop_write()
241581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
241681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // FIXME rewrite to reduce number of system calls
241781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mLastWriteTime = systemTime();
241881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mInWrite = true;
2419bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    ssize_t bytesWritten;
2420010a1a1a552cdaad362cea8a0333b8906402dbcbAndy Hung    const size_t offset = mCurrentWriteLength - mBytesRemaining;
242181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
242281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // If an NBAIO sink is present, use it to write the normal mixer's submix
242381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (mNormalSink != 0) {
24244c053ea158b29fa2cdd4c6f39d3c8da4ee5a7a02Glenn Kasten
2425010a1a1a552cdaad362cea8a0333b8906402dbcbAndy Hung        const size_t count = mBytesRemaining / mFrameSize;
2426010a1a1a552cdaad362cea8a0333b8906402dbcbAndy Hung
24272d590964aa58e137d17a43e095e6443dd0fe2e98Simon Wilson        ATRACE_BEGIN("write");
242881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // update the setpoint when AudioFlinger::mScreenState changes
242981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        uint32_t screenState = AudioFlinger::mScreenState;
243081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (screenState != mScreenState) {
243181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mScreenState = screenState;
243281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
243381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if (pipe != NULL) {
243481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                pipe->setAvgFrames((mScreenState & 1) ?
243581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                        (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
243681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
243781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
2438010a1a1a552cdaad362cea8a0333b8906402dbcbAndy Hung        ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
24392d590964aa58e137d17a43e095e6443dd0fe2e98Simon Wilson        ATRACE_END();
244081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (framesWritten > 0) {
2441010a1a1a552cdaad362cea8a0333b8906402dbcbAndy Hung            bytesWritten = framesWritten * mFrameSize;
244281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        } else {
244381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            bytesWritten = framesWritten;
244481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
2445efaa7ab620b2ee936efa4fb74dc4c670ed757a46Glenn Kasten        mLatchDValid = false;
2446767094dd98b01baf21de2ad09c27b3c98776cf73Glenn Kasten        status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
2447bd096fd9d8e5fc0e62f98807f4818a06f70d0812Glenn Kasten        if (status == NO_ERROR) {
2448bd096fd9d8e5fc0e62f98807f4818a06f70d0812Glenn Kasten            size_t totalFramesWritten = mNormalSink->framesWritten();
2449bd096fd9d8e5fc0e62f98807f4818a06f70d0812Glenn Kasten            if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
2450bd096fd9d8e5fc0e62f98807f4818a06f70d0812Glenn Kasten                mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
24514c053ea158b29fa2cdd4c6f39d3c8da4ee5a7a02Glenn Kasten                // mLatchD.mFramesReleased is set immediately before D is clocked into Q
2452bd096fd9d8e5fc0e62f98807f4818a06f70d0812Glenn Kasten                mLatchDValid = true;
2453bd096fd9d8e5fc0e62f98807f4818a06f70d0812Glenn Kasten            }
2454bd096fd9d8e5fc0e62f98807f4818a06f70d0812Glenn Kasten        }
245581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // otherwise use the HAL / AudioStreamOut directly
245681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    } else {
2457bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        // Direct output and offload threads
2458010a1a1a552cdaad362cea8a0333b8906402dbcbAndy Hung
2459bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        if (mUseAsyncWrite) {
24603b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent            ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
24613b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent            mWriteAckSequence += 2;
24623b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent            mWriteAckSequence |= 1;
2463bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            ALOG_ASSERT(mCallbackThread != 0);
24643b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent            mCallbackThread->setWriteBlocked(mWriteAckSequence);
2465bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        }
2466767094dd98b01baf21de2ad09c27b3c98776cf73Glenn Kasten        // FIXME We should have an implementation of timestamps for direct output threads.
2467767094dd98b01baf21de2ad09c27b3c98776cf73Glenn Kasten        // They are used e.g for multichannel PCM playback over HDMI.
2468062e67a26e0553dd142be622821f493df541f0c6Phil Burk        bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
2469bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        if (mUseAsyncWrite &&
2470bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2471bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            // do not wait for async callback in case of error of full write
24723b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent            mWriteAckSequence &= ~1;
2473bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            ALOG_ASSERT(mCallbackThread != 0);
24743b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent            mCallbackThread->setWriteBlocked(mWriteAckSequence);
2475bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        }
247681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
247781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
247881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mNumWrites++;
247981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mInWrite = false;
2480fd4779740ec3e9e865d5514464df26d015354388Eric Laurent    mStandby = false;
2481bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    return bytesWritten;
2482bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent}
2483bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
2484bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurentvoid AudioFlinger::PlaybackThread::threadLoop_drain()
2485bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent{
2486bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    if (mOutput->stream->drain) {
2487bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2488bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        if (mUseAsyncWrite) {
24893b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent            ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
24903b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent            mDrainSequence |= 1;
2491bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            ALOG_ASSERT(mCallbackThread != 0);
24923b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent            mCallbackThread->setDraining(mDrainSequence);
2493bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        }
2494bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        mOutput->stream->drain(mOutput->stream,
2495bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2496bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                                                : AUDIO_DRAIN_ALL);
2497bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    }
2498bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent}
2499bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
2500bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurentvoid AudioFlinger::PlaybackThread::threadLoop_exit()
2501bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent{
2502275e8e9de2e11b4b344f5a201f1f0e51fda02d9cEric Laurent    {
2503275e8e9de2e11b4b344f5a201f1f0e51fda02d9cEric Laurent        Mutex::Autolock _l(mLock);
2504275e8e9de2e11b4b344f5a201f1f0e51fda02d9cEric Laurent        for (size_t i = 0; i < mTracks.size(); i++) {
2505275e8e9de2e11b4b344f5a201f1f0e51fda02d9cEric Laurent            sp<Track> track = mTracks[i];
2506275e8e9de2e11b4b344f5a201f1f0e51fda02d9cEric Laurent            track->invalidate();
2507275e8e9de2e11b4b344f5a201f1f0e51fda02d9cEric Laurent        }
2508275e8e9de2e11b4b344f5a201f1f0e51fda02d9cEric Laurent    }
250981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
251081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
251181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent/*
251281784c37c61b09289654b979567a42bf73cd2b12Eric LaurentThe derived values that are cached:
251325c2dac12114699e90deb1c579cadebce7b91a97Andy Hung - mSinkBufferSize from frame count * frame size
2514ad9cb8b88e4f8face23f01d8dc89fa769dacb50fEric Laurent - mActiveSleepTimeUs from activeSleepTimeUs()
2515ad9cb8b88e4f8face23f01d8dc89fa769dacb50fEric Laurent - mIdleSleepTimeUs from idleSleepTimeUs()
2516ad9cb8b88e4f8face23f01d8dc89fa769dacb50fEric Laurent - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only)
251781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent - maxPeriod from frame count and sample rate (MIXER only)
251881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
251981784c37c61b09289654b979567a42bf73cd2b12Eric LaurentThe parameters that affect these derived values are:
252081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent - frame count
252181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent - frame size
252281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent - sample rate
252381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent - device type: A2DP or not
252481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent - device latency
252581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent - format: PCM or not
252681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent - active sleep time
252781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent - idle sleep time
252881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent*/
252981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
253081784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::PlaybackThread::cacheParameters_l()
253181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
253225c2dac12114699e90deb1c579cadebce7b91a97Andy Hung    mSinkBufferSize = mNormalFrameCount * mFrameSize;
2533ad9cb8b88e4f8face23f01d8dc89fa769dacb50fEric Laurent    mActiveSleepTimeUs = activeSleepTimeUs();
2534ad9cb8b88e4f8face23f01d8dc89fa769dacb50fEric Laurent    mIdleSleepTimeUs = idleSleepTimeUs();
253581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
253681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
253781784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
253881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
25397c027248e1a4ccd5b22bc4deafb03e2d87ac8f38Glenn Kasten    ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
254081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            this,  streamType, mTracks.size());
254181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
254281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
254381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    size_t size = mTracks.size();
254481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    for (size_t i = 0; i < size; i++) {
254581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sp<Track> t = mTracks[i];
254681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (t->streamType() == streamType) {
25475736c35b841de56ce394b4879389f669b61425e6Glenn Kasten            t->invalidate();
254881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
254981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
255081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
255181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
255281784c37c61b09289654b979567a42bf73cd2b12Eric Laurentstatus_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
255381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
255481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    int session = chain->sessionId();
2555010a1a1a552cdaad362cea8a0333b8906402dbcbAndy Hung    int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2556010a1a1a552cdaad362cea8a0333b8906402dbcbAndy Hung            ? mEffectBuffer : mSinkBuffer);
255781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    bool ownsBuffer = false;
255881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
255981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
256081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (session > 0) {
256181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // Only one effect chain can be present in direct output thread and it uses
25622098f2744cedf2dc3fa36f608aa965a34602e7c0Andy Hung        // the sink buffer as input
256381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (mType != DIRECT) {
256481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            size_t numSamples = mNormalFrameCount * mChannelCount;
256581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            buffer = new int16_t[numSamples];
256681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            memset(buffer, 0, numSamples * sizeof(int16_t));
256781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
256881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            ownsBuffer = true;
256981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
257081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
257181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // Attach all tracks with same session ID to this chain.
257281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        for (size_t i = 0; i < mTracks.size(); ++i) {
257381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            sp<Track> track = mTracks[i];
257481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if (session == track->sessionId()) {
257581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
257681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                        buffer);
257781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                track->setMainBuffer(buffer);
257881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                chain->incTrackCnt();
257981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
258081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
258181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
258281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // indicate all active tracks in the chain
258381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
258481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            sp<Track> track = mActiveTracks[i].promote();
258581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if (track == 0) {
258681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                continue;
258781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
258881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if (session == track->sessionId()) {
258981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
259081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                chain->incActiveTrackCnt();
259181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
259281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
259381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
2594aaa44478a373232d8416657035a9020f9c7aa7c3Eric Laurent    chain->setThread(this);
259581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    chain->setInBuffer(buffer, ownsBuffer);
2596010a1a1a552cdaad362cea8a0333b8906402dbcbAndy Hung    chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2597010a1a1a552cdaad362cea8a0333b8906402dbcbAndy Hung            ? mEffectBuffer : mSinkBuffer));
259881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
259981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // chains list in order to be processed last as it contains output stage effects
260081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
260181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // session AUDIO_SESSION_OUTPUT_STAGE to be processed
260281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // after track specific effects and before output stage
260381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
260481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
260581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // Effect chain for other sessions are inserted at beginning of effect
260681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // chains list to be processed before output mix effects. Relative order between other
260781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // sessions is not important
260881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    size_t size = mEffectChains.size();
260981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    size_t i = 0;
261081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    for (i = 0; i < size; i++) {
261181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (mEffectChains[i]->sessionId() < session) {
261281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            break;
261381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
261481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
261581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mEffectChains.insertAt(chain, i);
261681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    checkSuspendOnAddEffectChain_l(chain);
261781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
261881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return NO_ERROR;
261981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
262081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
262181784c37c61b09289654b979567a42bf73cd2b12Eric Laurentsize_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
262281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
262381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    int session = chain->sessionId();
262481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
262581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
262681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
262781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    for (size_t i = 0; i < mEffectChains.size(); i++) {
262881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (chain == mEffectChains[i]) {
262981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mEffectChains.removeAt(i);
263081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // detach all active tracks from the chain
263181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
263281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                sp<Track> track = mActiveTracks[i].promote();
263381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                if (track == 0) {
263481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    continue;
263581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
263681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                if (session == track->sessionId()) {
263781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
263881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                            chain.get(), session);
263981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    chain->decActiveTrackCnt();
264081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
264181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
264281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
264381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // detach all tracks with same session ID from this chain
264481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            for (size_t i = 0; i < mTracks.size(); ++i) {
264581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                sp<Track> track = mTracks[i];
264681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                if (session == track->sessionId()) {
2647010a1a1a552cdaad362cea8a0333b8906402dbcbAndy Hung                    track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
264881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    chain->decTrackCnt();
264981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
265081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
265181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            break;
265281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
265381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
265481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return mEffectChains.size();
265581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
265681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
265781784c37c61b09289654b979567a42bf73cd2b12Eric Laurentstatus_t AudioFlinger::PlaybackThread::attachAuxEffect(
265881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
265981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
266081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
266181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return attachAuxEffect_l(track, EffectId);
266281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
266381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
266481784c37c61b09289654b979567a42bf73cd2b12Eric Laurentstatus_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
266581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
266681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
266781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    status_t status = NO_ERROR;
266881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
266981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (EffectId == 0) {
267081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        track->setAuxBuffer(0, NULL);
267181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    } else {
267281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
267381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
267481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (effect != 0) {
267581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
267681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
267781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            } else {
267881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                status = INVALID_OPERATION;
267981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
268081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        } else {
268181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            status = BAD_VALUE;
268281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
268381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
268481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return status;
268581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
268681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
268781784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
268881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
268981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    for (size_t i = 0; i < mTracks.size(); ++i) {
269081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sp<Track> track = mTracks[i];
269181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (track->auxEffectId() == effectId) {
269281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            attachAuxEffect_l(track, 0);
269381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
269481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
269581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
269681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
269781784c37c61b09289654b979567a42bf73cd2b12Eric Laurentbool AudioFlinger::PlaybackThread::threadLoop()
269881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
269981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Vector< sp<Track> > tracksToRemove;
270081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
2701ad9cb8b88e4f8face23f01d8dc89fa769dacb50fEric Laurent    mStandbyTimeNs = systemTime();
270281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
270381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // MIXER
270481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    nsecs_t lastWarning = 0;
270581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
270681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // DUPLICATING
270781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // FIXME could this be made local to while loop?
270881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    writeFrames = 0;
270981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
2710462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen    int lastGeneration = 0;
2711462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen
271281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    cacheParameters_l();
2713ad9cb8b88e4f8face23f01d8dc89fa769dacb50fEric Laurent    mSleepTimeUs = mIdleSleepTimeUs;
271481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
271581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (mType == MIXER) {
271681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sleepTimeShift = 0;
271781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
271881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
271981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    CpuStats cpuStats;
272081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
272181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
272281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    acquireWakeLock();
272381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
27249e58b552f51b00b3b674102876bd6c77ef3da806Glenn Kasten    // mNBLogWriter->log can only be called while thread mutex mLock is held.
27259e58b552f51b00b3b674102876bd6c77ef3da806Glenn Kasten    // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
27269e58b552f51b00b3b674102876bd6c77ef3da806Glenn Kasten    // and then that string will be logged at the next convenient opportunity.
27279e58b552f51b00b3b674102876bd6c77ef3da806Glenn Kasten    const char *logString = NULL;
27289e58b552f51b00b3b674102876bd6c77ef3da806Glenn Kasten
2729664539d25180ab8f77e0521533ea2821cf28985fEric Laurent    checkSilentMode_l();
2730664539d25180ab8f77e0521533ea2821cf28985fEric Laurent
273181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    while (!exitPending())
273281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    {
273381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        cpuStats.sample(myName);
273481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
273581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        Vector< sp<EffectChain> > effectChains;
273681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
273781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        { // scope for mLock
273881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
273981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            Mutex::Autolock _l(mLock);
274081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
2741021cf9634ab09c0753a40b7c9ef4ba603be5c3daEric Laurent            processConfigEvents_l();
27421035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent
27439e58b552f51b00b3b674102876bd6c77ef3da806Glenn Kasten            if (logString != NULL) {
27449e58b552f51b00b3b674102876bd6c77ef3da806Glenn Kasten                mNBLogWriter->logTimestamp();
27459e58b552f51b00b3b674102876bd6c77ef3da806Glenn Kasten                mNBLogWriter->log(logString);
27469e58b552f51b00b3b674102876bd6c77ef3da806Glenn Kasten                logString = NULL;
27479e58b552f51b00b3b674102876bd6c77ef3da806Glenn Kasten            }
27489e58b552f51b00b3b674102876bd6c77ef3da806Glenn Kasten
27494c053ea158b29fa2cdd4c6f39d3c8da4ee5a7a02Glenn Kasten            // Gather the framesReleased counters for all active tracks,
27504c053ea158b29fa2cdd4c6f39d3c8da4ee5a7a02Glenn Kasten            // and latch them atomically with the timestamp.
27514c053ea158b29fa2cdd4c6f39d3c8da4ee5a7a02Glenn Kasten            // FIXME We're using raw pointers as indices. A unique track ID would be a better index.
27524c053ea158b29fa2cdd4c6f39d3c8da4ee5a7a02Glenn Kasten            mLatchD.mFramesReleased.clear();
27534c053ea158b29fa2cdd4c6f39d3c8da4ee5a7a02Glenn Kasten            size_t size = mActiveTracks.size();
27544c053ea158b29fa2cdd4c6f39d3c8da4ee5a7a02Glenn Kasten            for (size_t i = 0; i < size; i++) {
27554c053ea158b29fa2cdd4c6f39d3c8da4ee5a7a02Glenn Kasten                sp<Track> t = mActiveTracks[i].promote();
27564c053ea158b29fa2cdd4c6f39d3c8da4ee5a7a02Glenn Kasten                if (t != 0) {
27574c053ea158b29fa2cdd4c6f39d3c8da4ee5a7a02Glenn Kasten                    mLatchD.mFramesReleased.add(t.get(),
27584c053ea158b29fa2cdd4c6f39d3c8da4ee5a7a02Glenn Kasten                            t->mAudioTrackServerProxy->framesReleased());
27594c053ea158b29fa2cdd4c6f39d3c8da4ee5a7a02Glenn Kasten                }
27604c053ea158b29fa2cdd4c6f39d3c8da4ee5a7a02Glenn Kasten            }
2761bd096fd9d8e5fc0e62f98807f4818a06f70d0812Glenn Kasten            if (mLatchDValid) {
2762bd096fd9d8e5fc0e62f98807f4818a06f70d0812Glenn Kasten                mLatchQ = mLatchD;
2763bd096fd9d8e5fc0e62f98807f4818a06f70d0812Glenn Kasten                mLatchDValid = false;
2764bd096fd9d8e5fc0e62f98807f4818a06f70d0812Glenn Kasten                mLatchQValid = true;
2765bd096fd9d8e5fc0e62f98807f4818a06f70d0812Glenn Kasten            }
2766bd096fd9d8e5fc0e62f98807f4818a06f70d0812Glenn Kasten
276781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            saveOutputTracks();
2768bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            if (mSignalPending) {
2769bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                // A signal was raised while we were unlocked
2770bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                mSignalPending = false;
2771bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            } else if (waitingAsyncCallback_l()) {
2772bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                if (exitPending()) {
2773bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                    break;
2774bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                }
2775078538cfc6c4682889ed52de460d29c0d15bb9ebMarco Nelissen                bool released = false;
2776078538cfc6c4682889ed52de460d29c0d15bb9ebMarco Nelissen                // The following works around a bug in the offload driver. Ideally we would release
2777078538cfc6c4682889ed52de460d29c0d15bb9ebMarco Nelissen                // the wake lock every time, but that causes the last offload buffer(s) to be
2778078538cfc6c4682889ed52de460d29c0d15bb9ebMarco Nelissen                // dropped while the device is on battery, so we need to hold a wake lock during
2779078538cfc6c4682889ed52de460d29c0d15bb9ebMarco Nelissen                // the drain phase.
2780078538cfc6c4682889ed52de460d29c0d15bb9ebMarco Nelissen                if (mBytesRemaining && !(mDrainSequence & 1)) {
2781078538cfc6c4682889ed52de460d29c0d15bb9ebMarco Nelissen                    releaseWakeLock_l();
2782078538cfc6c4682889ed52de460d29c0d15bb9ebMarco Nelissen                    released = true;
2783078538cfc6c4682889ed52de460d29c0d15bb9ebMarco Nelissen                }
2784462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen                mWakeLockUids.clear();
2785462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen                mActiveTracksGeneration++;
2786bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                ALOGV("wait async completion");
2787bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                mWaitWorkCV.wait(mLock);
2788bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                ALOGV("async completion/wake");
2789078538cfc6c4682889ed52de460d29c0d15bb9ebMarco Nelissen                if (released) {
2790078538cfc6c4682889ed52de460d29c0d15bb9ebMarco Nelissen                    acquireWakeLock_l();
2791078538cfc6c4682889ed52de460d29c0d15bb9ebMarco Nelissen                }
2792ad9cb8b88e4f8face23f01d8dc89fa769dacb50fEric Laurent                mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2793ad9cb8b88e4f8face23f01d8dc89fa769dacb50fEric Laurent                mSleepTimeUs = 0;
2794ede6c3b8b1147bc425f7b923882f559a513fe23bEric Laurent
2795ede6c3b8b1147bc425f7b923882f559a513fe23bEric Laurent                continue;
2796ede6c3b8b1147bc425f7b923882f559a513fe23bEric Laurent            }
2797ad9cb8b88e4f8face23f01d8dc89fa769dacb50fEric Laurent            if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
2798bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                                   isSuspended()) {
2799bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                // put audio hardware into standby after short delay
2800bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                if (shouldStandby_l()) {
280181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
280281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    threadLoop_standby();
280381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
280481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    mStandby = true;
280581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
280681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
280781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
280881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    // we're about to wait, flush the binder command buffer
280981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    IPCThreadState::self()->flushCommands();
281081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
281181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    clearOutputTracks();
281281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
281381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    if (exitPending()) {
281481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                        break;
281581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    }
281681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
281781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    releaseWakeLock_l();
2818462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen                    mWakeLockUids.clear();
2819462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen                    mActiveTracksGeneration++;
282081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    // wait until we have something to do...
282181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    ALOGV("%s going to sleep", myName.string());
282281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    mWaitWorkCV.wait(mLock);
282381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    ALOGV("%s waking up", myName.string());
282481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    acquireWakeLock_l();
282581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
282681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    mMixerStatus = MIXER_IDLE;
282781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    mMixerStatusIgnoringFastTracks = MIXER_IDLE;
282881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    mBytesWritten = 0;
2829bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                    mBytesRemaining = 0;
283081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    checkSilentMode_l();
283181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
2832ad9cb8b88e4f8face23f01d8dc89fa769dacb50fEric Laurent                    mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2833ad9cb8b88e4f8face23f01d8dc89fa769dacb50fEric Laurent                    mSleepTimeUs = mIdleSleepTimeUs;
283481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    if (mType == MIXER) {
283581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                        sleepTimeShift = 0;
283681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    }
283781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
283881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    continue;
283981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
284081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
284181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // mMixerStatusIgnoringFastTracks is also updated internally
284281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mMixerStatus = prepareTracks_l(&tracksToRemove);
284381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
2844462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen            // compare with previously applied list
2845462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen            if (lastGeneration != mActiveTracksGeneration) {
2846462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen                // update wakelock
2847462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen                updateWakeLockUids_l(mWakeLockUids);
2848462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen                lastGeneration = mActiveTracksGeneration;
2849462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen            }
2850462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen
285181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // prevent any changes in effect chain list and in each effect chain
285281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // during mixing and effect process as the audio buffers could be deleted
285381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // or modified if an effect is created or deleted
285481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            lockEffectChains_l(effectChains);
2855462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen        } // mLock scope ends
285681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
2857bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        if (mBytesRemaining == 0) {
2858bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            mCurrentWriteLength = 0;
2859bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            if (mMixerStatus == MIXER_TRACKS_READY) {
2860bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                // threadLoop_mix() sets mCurrentWriteLength
2861bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                threadLoop_mix();
2862bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2863bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                        && (mMixerStatus != MIXER_DRAIN_ALL)) {
2864ad9cb8b88e4f8face23f01d8dc89fa769dacb50fEric Laurent                // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
2865bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                // must be written to HAL
2866bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                threadLoop_sleepTime();
2867ad9cb8b88e4f8face23f01d8dc89fa769dacb50fEric Laurent                if (mSleepTimeUs == 0) {
286825c2dac12114699e90deb1c579cadebce7b91a97Andy Hung                    mCurrentWriteLength = mSinkBufferSize;
2869bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                }
2870bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            }
287198ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung            // Either threadLoop_mix() or threadLoop_sleepTime() should have set
2872ad9cb8b88e4f8face23f01d8dc89fa769dacb50fEric Laurent            // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
287398ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung            // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
287498ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung            // or mSinkBuffer (if there are no effects).
287598ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung            //
287698ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung            // This is done pre-effects computation; if effects change to
287798ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung            // support higher precision, this needs to move.
287898ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung            //
287998ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung            // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
2880ad9cb8b88e4f8face23f01d8dc89fa769dacb50fEric Laurent            // TODO use mSleepTimeUs == 0 as an additional condition.
288198ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung            if (mMixerBufferValid) {
288298ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung                void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
288398ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung                audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
288498ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung
288598ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung                memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
288698ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung                        mNormalFrameCount * mChannelCount);
288798ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung            }
288898ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung
2889bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            mBytesRemaining = mCurrentWriteLength;
2890bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            if (isSuspended()) {
2891ad9cb8b88e4f8face23f01d8dc89fa769dacb50fEric Laurent                mSleepTimeUs = suspendSleepTimeUs();
2892bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                // simulate write to HAL when suspended
289325c2dac12114699e90deb1c579cadebce7b91a97Andy Hung                mBytesWritten += mSinkBufferSize;
2894bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                mBytesRemaining = 0;
2895bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            }
289681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
2897bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            // only process effects if we're going to write
2898ad9cb8b88e4f8face23f01d8dc89fa769dacb50fEric Laurent            if (mSleepTimeUs == 0 && mType != OFFLOAD) {
2899bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                for (size_t i = 0; i < effectChains.size(); i ++) {
2900bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                    effectChains[i]->process_l();
2901bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                }
290281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
290381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
290459fe010bcc072597852454a2ec53d7b0a2002a3bEric Laurent        // Process effect chains for offloaded thread even if no audio
290559fe010bcc072597852454a2ec53d7b0a2002a3bEric Laurent        // was read from audio track: process only updates effect state
290659fe010bcc072597852454a2ec53d7b0a2002a3bEric Laurent        // and thus does have to be synchronized with audio writes but may have
290759fe010bcc072597852454a2ec53d7b0a2002a3bEric Laurent        // to be called while waiting for async write callback
290859fe010bcc072597852454a2ec53d7b0a2002a3bEric Laurent        if (mType == OFFLOAD) {
290959fe010bcc072597852454a2ec53d7b0a2002a3bEric Laurent            for (size_t i = 0; i < effectChains.size(); i ++) {
291059fe010bcc072597852454a2ec53d7b0a2002a3bEric Laurent                effectChains[i]->process_l();
291159fe010bcc072597852454a2ec53d7b0a2002a3bEric Laurent            }
291259fe010bcc072597852454a2ec53d7b0a2002a3bEric Laurent        }
291381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
291498ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung        // Only if the Effects buffer is enabled and there is data in the
291598ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung        // Effects buffer (buffer valid), we need to
291698ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung        // copy into the sink buffer.
2917ad9cb8b88e4f8face23f01d8dc89fa769dacb50fEric Laurent        // TODO use mSleepTimeUs == 0 as an additional condition.
291898ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung        if (mEffectBufferValid) {
291998ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung            //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
292098ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung            memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
292198ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung                    mNormalFrameCount * mChannelCount);
292298ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung        }
292398ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung
292481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // enable changes in effect chain
292581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        unlockEffectChains(effectChains);
292681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
2927bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        if (!waitingAsyncCallback()) {
2928ad9cb8b88e4f8face23f01d8dc89fa769dacb50fEric Laurent            // mSleepTimeUs == 0 means we must write to audio hardware
2929ad9cb8b88e4f8face23f01d8dc89fa769dacb50fEric Laurent            if (mSleepTimeUs == 0) {
293008fb1743f80437c38b4094070d851ea7f6d485e5Andy Hung                ssize_t ret = 0;
2931bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                if (mBytesRemaining) {
293208fb1743f80437c38b4094070d851ea7f6d485e5Andy Hung                    ret = threadLoop_write();
2933bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                    if (ret < 0) {
2934bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                        mBytesRemaining = 0;
2935bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                    } else {
2936bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                        mBytesWritten += ret;
2937bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                        mBytesRemaining -= ret;
2938bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                    }
2939bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2940bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                        (mMixerStatus == MIXER_DRAIN_ALL)) {
2941bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                    threadLoop_drain();
2942bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                }
294308fb1743f80437c38b4094070d851ea7f6d485e5Andy Hung                if (mType == MIXER && !mStandby) {
29444944acb7355b3aa25748fd25945a363a69d65444Glenn Kasten                    // write blocked detection
29454944acb7355b3aa25748fd25945a363a69d65444Glenn Kasten                    nsecs_t now = systemTime();
29464944acb7355b3aa25748fd25945a363a69d65444Glenn Kasten                    nsecs_t delta = now - mLastWriteTime;
294708fb1743f80437c38b4094070d851ea7f6d485e5Andy Hung                    if (delta > maxPeriod) {
29484944acb7355b3aa25748fd25945a363a69d65444Glenn Kasten                        mNumDelayedWrites++;
29494944acb7355b3aa25748fd25945a363a69d65444Glenn Kasten                        if ((now - lastWarning) > kWarningThrottleNs) {
29504944acb7355b3aa25748fd25945a363a69d65444Glenn Kasten                            ATRACE_NAME("underrun");
29514944acb7355b3aa25748fd25945a363a69d65444Glenn Kasten                            ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
29524944acb7355b3aa25748fd25945a363a69d65444Glenn Kasten                                    ns2ms(delta), mNumDelayedWrites, this);
29534944acb7355b3aa25748fd25945a363a69d65444Glenn Kasten                            lastWarning = now;
29544944acb7355b3aa25748fd25945a363a69d65444Glenn Kasten                        }
2955bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                    }
295608fb1743f80437c38b4094070d851ea7f6d485e5Andy Hung
295708fb1743f80437c38b4094070d851ea7f6d485e5Andy Hung                    if (mThreadThrottle
295808fb1743f80437c38b4094070d851ea7f6d485e5Andy Hung                            && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
295908fb1743f80437c38b4094070d851ea7f6d485e5Andy Hung                            && ret > 0) {                         // we wrote something
296008fb1743f80437c38b4094070d851ea7f6d485e5Andy Hung                        // Limit MixerThread data processing to no more than twice the
296108fb1743f80437c38b4094070d851ea7f6d485e5Andy Hung                        // expected processing rate.
296208fb1743f80437c38b4094070d851ea7f6d485e5Andy Hung                        //
296308fb1743f80437c38b4094070d851ea7f6d485e5Andy Hung                        // This helps prevent underruns with NuPlayer and other applications
296408fb1743f80437c38b4094070d851ea7f6d485e5Andy Hung                        // which may set up buffers that are close to the minimum size, or use
296508fb1743f80437c38b4094070d851ea7f6d485e5Andy Hung                        // deep buffers, and rely on a double-buffering sleep strategy to fill.
296608fb1743f80437c38b4094070d851ea7f6d485e5Andy Hung                        //
296708fb1743f80437c38b4094070d851ea7f6d485e5Andy Hung                        // The throttle smooths out sudden large data drains from the device,
296808fb1743f80437c38b4094070d851ea7f6d485e5Andy Hung                        // e.g. when it comes out of standby, which often causes problems with
296908fb1743f80437c38b4094070d851ea7f6d485e5Andy Hung                        // (1) mixer threads without a fast mixer (which has its own warm-up)
297008fb1743f80437c38b4094070d851ea7f6d485e5Andy Hung                        // (2) minimum buffer sized tracks (even if the track is full,
297108fb1743f80437c38b4094070d851ea7f6d485e5Andy Hung                        //     the app won't fill fast enough to handle the sudden draw).
297208fb1743f80437c38b4094070d851ea7f6d485e5Andy Hung
297308fb1743f80437c38b4094070d851ea7f6d485e5Andy Hung                        const int32_t deltaMs = delta / 1000000;
297408fb1743f80437c38b4094070d851ea7f6d485e5Andy Hung                        const int32_t throttleMs = mHalfBufferMs - deltaMs;
297508fb1743f80437c38b4094070d851ea7f6d485e5Andy Hung                        if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
297608fb1743f80437c38b4094070d851ea7f6d485e5Andy Hung                            usleep(throttleMs * 1000);
297740eb1a1f8871909c272e72afaf7d5af84fea2412Andy Hung                            // notify of throttle start on verbose log
297840eb1a1f8871909c272e72afaf7d5af84fea2412Andy Hung                            ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
297940eb1a1f8871909c272e72afaf7d5af84fea2412Andy Hung                                    "mixer(%p) throttle begin:"
298040eb1a1f8871909c272e72afaf7d5af84fea2412Andy Hung                                    " ret(%zd) deltaMs(%d) requires sleep %d ms",
298108fb1743f80437c38b4094070d851ea7f6d485e5Andy Hung                                    this, ret, deltaMs, throttleMs);
298240eb1a1f8871909c272e72afaf7d5af84fea2412Andy Hung                            mThreadThrottleTimeMs += throttleMs;
298340eb1a1f8871909c272e72afaf7d5af84fea2412Andy Hung                        } else {
298440eb1a1f8871909c272e72afaf7d5af84fea2412Andy Hung                            uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
298540eb1a1f8871909c272e72afaf7d5af84fea2412Andy Hung                            if (diff > 0) {
298640eb1a1f8871909c272e72afaf7d5af84fea2412Andy Hung                                // notify of throttle end on debug log
298740eb1a1f8871909c272e72afaf7d5af84fea2412Andy Hung                                ALOGD("mixer(%p) throttle end: throttle time(%u)", this, diff);
298840eb1a1f8871909c272e72afaf7d5af84fea2412Andy Hung                                mThreadThrottleEndMs = mThreadThrottleTimeMs;
298940eb1a1f8871909c272e72afaf7d5af84fea2412Andy Hung                            }
299008fb1743f80437c38b4094070d851ea7f6d485e5Andy Hung                        }
299108fb1743f80437c38b4094070d851ea7f6d485e5Andy Hung                    }
299281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
299381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
2994bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            } else {
2995e77540228e1f60b1129a1615d2e43e0bf8015d3cGlenn Kasten                ATRACE_BEGIN("sleep");
2996ad9cb8b88e4f8face23f01d8dc89fa769dacb50fEric Laurent                usleep(mSleepTimeUs);
2997e77540228e1f60b1129a1615d2e43e0bf8015d3cGlenn Kasten                ATRACE_END();
2998bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            }
299981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
300081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
300181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // Finally let go of removed track(s), without the lock held
300281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // since we can't guarantee the destructors won't acquire that
300381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // same lock.  This will also mutate and push a new fast mixer state.
300481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        threadLoop_removeTracks(tracksToRemove);
300581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        tracksToRemove.clear();
300681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
300781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // FIXME I don't understand the need for this here;
300881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        //       it was in the original code but maybe the
300981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        //       assignment in saveOutputTracks() makes this unnecessary?
301081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        clearOutputTracks();
301181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
301281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // Effect chains will be actually deleted here if they were removed from
301381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // mEffectChains list during mixing or effects processing
301481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        effectChains.clear();
301581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
301681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // FIXME Note that the above .clear() is no longer necessary since effectChains
301781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // is now local to this block, but will keep it for now (at least until merge done).
301881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
301981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
3020bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    threadLoop_exit();
3021bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
3022cf817a2330936947df94c11859f48771f5596a59Eric Laurent    if (!mStandby) {
3023cf817a2330936947df94c11859f48771f5596a59Eric Laurent        threadLoop_standby();
3024cf817a2330936947df94c11859f48771f5596a59Eric Laurent        mStandby = true;
302581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
302681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
302781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    releaseWakeLock();
3028462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen    mWakeLockUids.clear();
3029462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen    mActiveTracksGeneration++;
303081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
303181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    ALOGV("Thread %p type %d exiting", this, mType);
303281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return false;
303381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
303481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
3035bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent// removeTracks_l() must be called with ThreadBase::mLock held
3036bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurentvoid AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3037bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent{
3038bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    size_t count = tracksToRemove.size();
303934fca34606b448e6b71c2942f63cb13a0aebd620Glenn Kasten    if (count > 0) {
3040bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        for (size_t i=0 ; i<count ; i++) {
3041bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            const sp<Track>& track = tracksToRemove.itemAt(i);
3042bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            mActiveTracks.remove(track);
3043462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen            mWakeLockUids.remove(track->uid());
3044462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen            mActiveTracksGeneration++;
3045bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3046bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3047bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            if (chain != 0) {
3048bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3049bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                        track->sessionId());
3050bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                chain->decActiveTrackCnt();
3051bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            }
3052bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            if (track->isTerminated()) {
3053bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                removeTrack_l(track);
3054bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            }
3055bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        }
3056bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    }
3057bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
3058bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent}
305981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
3060accc147666bfd37fc8b4ef745f18a8c751555ec2Eric Laurentstatus_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3061accc147666bfd37fc8b4ef745f18a8c751555ec2Eric Laurent{
3062accc147666bfd37fc8b4ef745f18a8c751555ec2Eric Laurent    if (mNormalSink != 0) {
3063accc147666bfd37fc8b4ef745f18a8c751555ec2Eric Laurent        return mNormalSink->getTimestamp(timestamp);
3064accc147666bfd37fc8b4ef745f18a8c751555ec2Eric Laurent    }
30659a1c8892f6835325db6931529dc74bf98cf0aee8Andy Hung    if ((mType == OFFLOAD || mType == DIRECT)
30669a1c8892f6835325db6931529dc74bf98cf0aee8Andy Hung            && mOutput != NULL && mOutput->stream->get_presentation_position) {
3067accc147666bfd37fc8b4ef745f18a8c751555ec2Eric Laurent        uint64_t position64;
3068062e67a26e0553dd142be622821f493df541f0c6Phil Burk        int ret = mOutput->getPresentationPosition(&position64, &timestamp.mTime);
3069accc147666bfd37fc8b4ef745f18a8c751555ec2Eric Laurent        if (ret == 0) {
3070accc147666bfd37fc8b4ef745f18a8c751555ec2Eric Laurent            timestamp.mPosition = (uint32_t)position64;
3071accc147666bfd37fc8b4ef745f18a8c751555ec2Eric Laurent            return NO_ERROR;
3072accc147666bfd37fc8b4ef745f18a8c751555ec2Eric Laurent        }
3073accc147666bfd37fc8b4ef745f18a8c751555ec2Eric Laurent    }
3074accc147666bfd37fc8b4ef745f18a8c751555ec2Eric Laurent    return INVALID_OPERATION;
3075accc147666bfd37fc8b4ef745f18a8c751555ec2Eric Laurent}
30761c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent
3077054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurentstatus_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3078054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent                                                          audio_patch_handle_t *handle)
3079054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent{
3080054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent    // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3081054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent    FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3082054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent    if (mFastMixer != 0) {
3083054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        FastMixerStateQueue *sq = mFastMixer->sq();
3084054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        FastMixerState *state = sq->begin();
3085054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        if (!(state->mCommand & FastMixerState::IDLE)) {
3086054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent            previousCommand = state->mCommand;
3087054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent            state->mCommand = FastMixerState::HOT_IDLE;
3088054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent            sq->end();
3089054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent            sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3090054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        } else {
3091054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent            sq->end(false /*didModify*/);
3092054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        }
3093054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent    }
3094054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent    status_t status = PlaybackThread::createAudioPatch_l(patch, handle);
3095054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent
3096054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent    if (!(previousCommand & FastMixerState::IDLE)) {
3097054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        ALOG_ASSERT(mFastMixer != 0);
3098054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        FastMixerStateQueue *sq = mFastMixer->sq();
3099054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        FastMixerState *state = sq->begin();
3100054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3101054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        state->mCommand = previousCommand;
3102054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        sq->end();
3103054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3104054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent    }
3105054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent
3106054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent    return status;
3107054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent}
3108054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent
31091c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurentstatus_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
31101c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent                                                          audio_patch_handle_t *handle)
31111c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent{
31121c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent    status_t status = NO_ERROR;
3113054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent
3114054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent    // store new device and send to effects
3115054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent    audio_devices_t type = AUDIO_DEVICE_NONE;
3116054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent    for (unsigned int i = 0; i < patch->num_sinks; i++) {
3117054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        type |= patch->sinks[i].ext.device.type;
3118054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent    }
3119054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent
3120054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent#ifdef ADD_BATTERY_DATA
3121054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent    // when changing the audio output device, call addBatteryData to notify
3122054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent    // the change
3123054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent    if (mOutDevice != type) {
3124054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        uint32_t params = 0;
3125054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        // check whether speaker is on
3126054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3127054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent            params |= IMediaPlayerService::kBatteryDataSpeakerOn;
31281c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent        }
3129054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent
3130054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        audio_devices_t deviceWithoutSpeaker
3131054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent            = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3132054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        // check if any other device (except speaker) is on
3133054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        if (type & deviceWithoutSpeaker) {
3134054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent            params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3135054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        }
3136054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent
3137054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        if (params != 0) {
3138054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent            addBatteryData(params);
31391c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent        }
3140054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent    }
3141054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent#endif
31421c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent
3143054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent    for (size_t i = 0; i < mEffectChains.size(); i++) {
3144054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        mEffectChains[i]->setDevice_l(type);
3145054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent    }
31467c1ec5f038e63a5eb8b04434577c25bc23f5f410Eric Laurent
31477c1ec5f038e63a5eb8b04434577c25bc23f5f410Eric Laurent    // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
31487c1ec5f038e63a5eb8b04434577c25bc23f5f410Eric Laurent    // the thread is created so that the first patch creation triggers an ioConfigChanged callback
31497c1ec5f038e63a5eb8b04434577c25bc23f5f410Eric Laurent    bool configChanged = mPrevOutDevice != type;
3150054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent    mOutDevice = type;
3151296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent    mPatch = *patch;
3152054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent
3153054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent    if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
31541c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent        audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
31551c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent        status = hwDevice->create_audio_patch(hwDevice,
31561c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent                                               patch->num_sources,
31571c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent                                               patch->sources,
31581c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent                                               patch->num_sinks,
31591c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent                                               patch->sinks,
31601c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent                                               handle);
31611c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent    } else {
3162054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        char *address;
3163054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3164054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent            //FIXME: we only support address on first sink with HAL version < 3.0
3165054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent            address = audio_device_address_to_parameter(
3166054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent                                                        patch->sinks[0].ext.device.type,
3167054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent                                                        patch->sinks[0].ext.device.address);
3168054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        } else {
3169054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent            address = (char *)calloc(1, 1);
3170054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        }
3171054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        AudioParameter param = AudioParameter(String8(address));
3172054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        free(address);
3173054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), (int)type);
3174054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3175054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent                param.toString().string());
3176054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        *handle = AUDIO_PATCH_HANDLE_NONE;
3177054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent    }
3178e8726fea8a53bf3474aa3c6deaf2f6c1f565e694Eric Laurent    if (configChanged) {
31797c1ec5f038e63a5eb8b04434577c25bc23f5f410Eric Laurent        mPrevOutDevice = type;
3180e8726fea8a53bf3474aa3c6deaf2f6c1f565e694Eric Laurent        sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3181e8726fea8a53bf3474aa3c6deaf2f6c1f565e694Eric Laurent    }
3182054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent    return status;
3183054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent}
3184054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent
3185054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurentstatus_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3186054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent{
3187054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent    // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3188054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent    FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3189054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent    if (mFastMixer != 0) {
3190054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        FastMixerStateQueue *sq = mFastMixer->sq();
3191054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        FastMixerState *state = sq->begin();
3192054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        if (!(state->mCommand & FastMixerState::IDLE)) {
3193054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent            previousCommand = state->mCommand;
3194054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent            state->mCommand = FastMixerState::HOT_IDLE;
3195054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent            sq->end();
3196054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent            sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3197054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        } else {
3198054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent            sq->end(false /*didModify*/);
3199054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        }
32001c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent    }
3201054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent
3202054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent    status_t status = PlaybackThread::releaseAudioPatch_l(handle);
3203054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent
3204054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent    if (!(previousCommand & FastMixerState::IDLE)) {
3205054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        ALOG_ASSERT(mFastMixer != 0);
3206054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        FastMixerStateQueue *sq = mFastMixer->sq();
3207054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        FastMixerState *state = sq->begin();
3208054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3209054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        state->mCommand = previousCommand;
3210054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        sq->end();
3211054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3212054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent    }
3213054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent
32141c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent    return status;
32151c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent}
32161c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent
32171c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurentstatus_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
32181c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent{
32191c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent    status_t status = NO_ERROR;
3220054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent
3221054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent    mOutDevice = AUDIO_DEVICE_NONE;
3222054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent
32231c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent    if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
32241c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent        audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
32251c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent        status = hwDevice->release_audio_patch(hwDevice, handle);
32261c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent    } else {
3227054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        AudioParameter param;
3228054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
3229054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3230054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent                param.toString().string());
32311c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent    }
32321c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent    return status;
32331c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent}
32341c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent
323583b8808faad1e91690c64d7007348be8d9ebde73Eric Laurentvoid AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
323683b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent{
323783b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent    Mutex::Autolock _l(mLock);
323883b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent    mTracks.add(track);
323983b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent}
324083b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent
324183b8808faad1e91690c64d7007348be8d9ebde73Eric Laurentvoid AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
324283b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent{
324383b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent    Mutex::Autolock _l(mLock);
324483b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent    destroyTrack_l(track);
324583b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent}
324683b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent
324783b8808faad1e91690c64d7007348be8d9ebde73Eric Laurentvoid AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
324883b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent{
324983b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent    ThreadBase::getAudioPortConfig(config);
325083b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent    config->role = AUDIO_PORT_ROLE_SOURCE;
325183b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent    config->ext.mix.hw_module = mOutput->audioHwDev->handle();
325283b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent    config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
325383b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent}
325483b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent
325581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// ----------------------------------------------------------------------------
325681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
325781784c37c61b09289654b979567a42bf73cd2b12Eric LaurentAudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
325872e3f39146fce4686bd96f11057c051bea376dfbEric Laurent        audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
325972e3f39146fce4686bd96f11057c051bea376dfbEric Laurent    :   PlaybackThread(audioFlinger, output, id, device, type, systemReady),
326081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // mAudioMixer below
326181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // mFastMixer below
326281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mFastMixerFutex(0)
326381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // mOutputSink below
326481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // mPipeSink below
326581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // mNormalSink below
326681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
326781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
3268f6ed423af92a56ef54bba23eba883b1f21448b54Glenn Kasten    ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
326981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            "mFrameCount=%d, mNormalFrameCount=%d",
327081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
327181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mNormalFrameCount);
327281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
327381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
3274fbfc3959f4aac839445edc7075532067fef497c2Andy Hung    if (type == DUPLICATING) {
3275fbfc3959f4aac839445edc7075532067fef497c2Andy Hung        // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3276fbfc3959f4aac839445edc7075532067fef497c2Andy Hung        // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3277fbfc3959f4aac839445edc7075532067fef497c2Andy Hung        // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3278fbfc3959f4aac839445edc7075532067fef497c2Andy Hung        return;
3279fbfc3959f4aac839445edc7075532067fef497c2Andy Hung    }
328081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // create an NBAIO sink for the HAL output stream, and negotiate
328181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mOutputSink = new AudioStreamOutSink(output->stream);
328281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    size_t numCounterOffers = 0;
3283f69f9869514730aebe5724c461768507084dfff7Glenn Kasten    const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
328481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
328581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    ALOG_ASSERT(index == 0);
328681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
328781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // initialize fast mixer depending on configuration
328881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    bool initFastMixer;
328981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    switch (kUseFastMixer) {
329081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    case FastMixer_Never:
329181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        initFastMixer = false;
329281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        break;
329381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    case FastMixer_Always:
329481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        initFastMixer = true;
329581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        break;
329681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    case FastMixer_Static:
329781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    case FastMixer_Dynamic:
329881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        initFastMixer = mFrameCount < mNormalFrameCount;
329981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        break;
330081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
330181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (initFastMixer) {
33021258c1ab592a899fabb1e31eb5db2ef413b6f38aAndy Hung        audio_format_t fastMixerFormat;
33031258c1ab592a899fabb1e31eb5db2ef413b6f38aAndy Hung        if (mMixerBufferEnabled && mEffectBufferEnabled) {
33041258c1ab592a899fabb1e31eb5db2ef413b6f38aAndy Hung            fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
33051258c1ab592a899fabb1e31eb5db2ef413b6f38aAndy Hung        } else {
33061258c1ab592a899fabb1e31eb5db2ef413b6f38aAndy Hung            fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
33071258c1ab592a899fabb1e31eb5db2ef413b6f38aAndy Hung        }
33081258c1ab592a899fabb1e31eb5db2ef413b6f38aAndy Hung        if (mFormat != fastMixerFormat) {
33091258c1ab592a899fabb1e31eb5db2ef413b6f38aAndy Hung            // change our Sink format to accept our intermediate precision
33101258c1ab592a899fabb1e31eb5db2ef413b6f38aAndy Hung            mFormat = fastMixerFormat;
33111258c1ab592a899fabb1e31eb5db2ef413b6f38aAndy Hung            free(mSinkBuffer);
33121258c1ab592a899fabb1e31eb5db2ef413b6f38aAndy Hung            mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
33131258c1ab592a899fabb1e31eb5db2ef413b6f38aAndy Hung            const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
33141258c1ab592a899fabb1e31eb5db2ef413b6f38aAndy Hung            (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
33151258c1ab592a899fabb1e31eb5db2ef413b6f38aAndy Hung        }
331681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
331781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // create a MonoPipe to connect our submix to FastMixer
331881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        NBAIO_Format format = mOutputSink->format();
3319ba0b34c18da93681c0813ecdab19b0e215b6d261Glenn Kasten        NBAIO_Format origformat = format;
33201258c1ab592a899fabb1e31eb5db2ef413b6f38aAndy Hung        // adjust format to match that of the Fast Mixer
332197b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten        ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
33221258c1ab592a899fabb1e31eb5db2ef413b6f38aAndy Hung        format.mFormat = fastMixerFormat;
33231258c1ab592a899fabb1e31eb5db2ef413b6f38aAndy Hung        format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
33241258c1ab592a899fabb1e31eb5db2ef413b6f38aAndy Hung
332581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // This pipe depth compensates for scheduling latency of the normal mixer thread.
332681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // When it wakes up after a maximum latency, it runs a few cycles quickly before
332781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // finally blocking.  Note the pipe implementation rounds up the request to a power of 2.
332881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
332981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        const NBAIO_Format offers[1] = {format};
333081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        size_t numCounterOffers = 0;
333181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
333281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        ALOG_ASSERT(index == 0);
333381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        monoPipe->setAvgFrames((mScreenState & 1) ?
333481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
333581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mPipeSink = monoPipe;
333681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
333746909e7eb074ce1b95b8a411eb71154f53f84f77Glenn Kasten#ifdef TEE_SINK
3338da6ef1320d0161b1640dc84d7a9c5a25860c3619Glenn Kasten        if (mTeeSinkOutputEnabled) {
3339da6ef1320d0161b1640dc84d7a9c5a25860c3619Glenn Kasten            // create a Pipe to archive a copy of FastMixer's output for dumpsys
3340ba0b34c18da93681c0813ecdab19b0e215b6d261Glenn Kasten            Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3341ba0b34c18da93681c0813ecdab19b0e215b6d261Glenn Kasten            const NBAIO_Format offers2[1] = {origformat};
3342da6ef1320d0161b1640dc84d7a9c5a25860c3619Glenn Kasten            numCounterOffers = 0;
3343ba0b34c18da93681c0813ecdab19b0e215b6d261Glenn Kasten            index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
3344da6ef1320d0161b1640dc84d7a9c5a25860c3619Glenn Kasten            ALOG_ASSERT(index == 0);
3345da6ef1320d0161b1640dc84d7a9c5a25860c3619Glenn Kasten            mTeeSink = teeSink;
3346da6ef1320d0161b1640dc84d7a9c5a25860c3619Glenn Kasten            PipeReader *teeSource = new PipeReader(*teeSink);
3347da6ef1320d0161b1640dc84d7a9c5a25860c3619Glenn Kasten            numCounterOffers = 0;
3348ba0b34c18da93681c0813ecdab19b0e215b6d261Glenn Kasten            index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
3349da6ef1320d0161b1640dc84d7a9c5a25860c3619Glenn Kasten            ALOG_ASSERT(index == 0);
3350da6ef1320d0161b1640dc84d7a9c5a25860c3619Glenn Kasten            mTeeSource = teeSource;
3351da6ef1320d0161b1640dc84d7a9c5a25860c3619Glenn Kasten        }
335246909e7eb074ce1b95b8a411eb71154f53f84f77Glenn Kasten#endif
335381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
335481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // create fast mixer and configure it initially with just one fast track for our submix
335581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mFastMixer = new FastMixer();
335681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        FastMixerStateQueue *sq = mFastMixer->sq();
335781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#ifdef STATE_QUEUE_DUMP
335881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sq->setObserverDump(&mStateQueueObserverDump);
335981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sq->setMutatorDump(&mStateQueueMutatorDump);
336081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#endif
336181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        FastMixerState *state = sq->begin();
336281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        FastTrack *fastTrack = &state->mFastTracks[0];
336381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // wrap the source side of the MonoPipe to make it an AudioBufferProvider
336481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
336581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        fastTrack->mVolumeProvider = NULL;
3366e8a1ced4da17dc6c07803dc2af8060f62a8389c1Andy Hung        fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3367e8a1ced4da17dc6c07803dc2af8060f62a8389c1Andy Hung        fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
336881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        fastTrack->mGeneration++;
336981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        state->mFastTracksGen++;
337081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        state->mTrackMask = 1;
337181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // fast mixer will use the HAL output sink
337281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        state->mOutputSink = mOutputSink.get();
337381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        state->mOutputSinkGen++;
337481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        state->mFrameCount = mFrameCount;
337581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        state->mCommand = FastMixerState::COLD_IDLE;
337681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // already done in constructor initialization list
337781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        //mFastMixerFutex = 0;
337881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        state->mColdFutexAddr = &mFastMixerFutex;
337981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        state->mColdGen++;
338081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        state->mDumpState = &mFastMixerDumpState;
338146909e7eb074ce1b95b8a411eb71154f53f84f77Glenn Kasten#ifdef TEE_SINK
338281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        state->mTeeSink = mTeeSink.get();
338346909e7eb074ce1b95b8a411eb71154f53f84f77Glenn Kasten#endif
33849e58b552f51b00b3b674102876bd6c77ef3da806Glenn Kasten        mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
33859e58b552f51b00b3b674102876bd6c77ef3da806Glenn Kasten        state->mNBLogWriter = mFastMixerNBLogWriter.get();
338681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sq->end();
338781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
338881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
338981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // start the fast mixer
339081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
339181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        pid_t tid = mFastMixer->getTid();
339272e3f39146fce4686bd96f11057c051bea376dfbEric Laurent        sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
339381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
339481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#ifdef AUDIO_WATCHDOG
339581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // create and start the watchdog
339681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mAudioWatchdog = new AudioWatchdog();
339781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mAudioWatchdog->setDump(&mAudioWatchdogDump);
339881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
339981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        tid = mAudioWatchdog->getTid();
340072e3f39146fce4686bd96f11057c051bea376dfbEric Laurent        sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
340181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#endif
340281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
340381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
340481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
340581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    switch (kUseFastMixer) {
340681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    case FastMixer_Never:
340781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    case FastMixer_Dynamic:
340881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mNormalSink = mOutputSink;
340981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        break;
341081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    case FastMixer_Always:
341181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mNormalSink = mPipeSink;
341281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        break;
341381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    case FastMixer_Static:
341481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
341581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        break;
341681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
341781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
341881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
341981784c37c61b09289654b979567a42bf73cd2b12Eric LaurentAudioFlinger::MixerThread::~MixerThread()
342081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
34214d23ca370dd0ce584f49a80ef9dfcdbb75ba2c8eGlenn Kasten    if (mFastMixer != 0) {
342281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        FastMixerStateQueue *sq = mFastMixer->sq();
342381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        FastMixerState *state = sq->begin();
342481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (state->mCommand == FastMixerState::COLD_IDLE) {
342581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            int32_t old = android_atomic_inc(&mFastMixerFutex);
342681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if (old == -1) {
3427ee499291404a192b059f2e04c5afc65aa6cdd74cElliott Hughes                (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
342881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
342981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
343081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        state->mCommand = FastMixerState::EXIT;
343181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sq->end();
343281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
343381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mFastMixer->join();
343481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // Though the fast mixer thread has exited, it's state queue is still valid.
343581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // We'll use that extract the final state which contains one remaining fast track
343681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // corresponding to our sub-mix.
343781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        state = sq->begin();
343881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        ALOG_ASSERT(state->mTrackMask == 1);
343981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        FastTrack *fastTrack = &state->mFastTracks[0];
344081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
344181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        delete fastTrack->mBufferProvider;
344281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sq->end(false /*didModify*/);
34434d23ca370dd0ce584f49a80ef9dfcdbb75ba2c8eGlenn Kasten        mFastMixer.clear();
344481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#ifdef AUDIO_WATCHDOG
344581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (mAudioWatchdog != 0) {
344681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mAudioWatchdog->requestExit();
344781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mAudioWatchdog->requestExitAndWait();
344881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mAudioWatchdog.clear();
344981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
345081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#endif
345181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
34529e58b552f51b00b3b674102876bd6c77ef3da806Glenn Kasten    mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
345381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    delete mAudioMixer;
345481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
345581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
345681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
345781784c37c61b09289654b979567a42bf73cd2b12Eric Laurentuint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
345881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
34594d23ca370dd0ce584f49a80ef9dfcdbb75ba2c8eGlenn Kasten    if (mFastMixer != 0) {
346081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
346181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
346281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
346381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return latency;
346481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
346581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
346681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
346781784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
346881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
346981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    PlaybackThread::threadLoop_removeTracks(tracksToRemove);
347081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
347181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
3472bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurentssize_t AudioFlinger::MixerThread::threadLoop_write()
347381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
347481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // FIXME we should only do one push per cycle; confirm this is true
347581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // Start the fast mixer if it's not already running
34764d23ca370dd0ce584f49a80ef9dfcdbb75ba2c8eGlenn Kasten    if (mFastMixer != 0) {
347781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        FastMixerStateQueue *sq = mFastMixer->sq();
347881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        FastMixerState *state = sq->begin();
347981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (state->mCommand != FastMixerState::MIX_WRITE &&
348081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
348181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if (state->mCommand == FastMixerState::COLD_IDLE) {
348281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                int32_t old = android_atomic_inc(&mFastMixerFutex);
348381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                if (old == -1) {
3484ee499291404a192b059f2e04c5afc65aa6cdd74cElliott Hughes                    (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
348581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
348681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#ifdef AUDIO_WATCHDOG
348781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                if (mAudioWatchdog != 0) {
348881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    mAudioWatchdog->resume();
348981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
349081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#endif
349181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
349281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            state->mCommand = FastMixerState::MIX_WRITE;
3493d797a9d5daad3051f9ac1d348abc2f434ea3ddcfGlenn Kasten#ifdef FAST_THREAD_STATISTICS
34944182c4e2a07e2441fcd5c22eaff0ddfe7f826f61Glenn Kasten            mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
3495fbdb2aceab7317aa44bc8f301a93eb49e17b2bceGlenn Kasten                FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
3496d797a9d5daad3051f9ac1d348abc2f434ea3ddcfGlenn Kasten#endif
349781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            sq->end();
349881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
349981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if (kUseFastMixer == FastMixer_Dynamic) {
350081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                mNormalSink = mPipeSink;
350181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
350281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        } else {
350381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            sq->end(false /*didModify*/);
350481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
350581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
3506bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    return PlaybackThread::threadLoop_write();
350781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
350881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
350981784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::MixerThread::threadLoop_standby()
351081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
351181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // Idle the fast mixer if it's currently running
35124d23ca370dd0ce584f49a80ef9dfcdbb75ba2c8eGlenn Kasten    if (mFastMixer != 0) {
351381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        FastMixerStateQueue *sq = mFastMixer->sq();
351481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        FastMixerState *state = sq->begin();
351581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (!(state->mCommand & FastMixerState::IDLE)) {
351681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            state->mCommand = FastMixerState::COLD_IDLE;
351781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            state->mColdFutexAddr = &mFastMixerFutex;
351881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            state->mColdGen++;
351981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mFastMixerFutex = 0;
352081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            sq->end();
352181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
352281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
352381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if (kUseFastMixer == FastMixer_Dynamic) {
352481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                mNormalSink = mOutputSink;
352581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
352681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#ifdef AUDIO_WATCHDOG
352781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if (mAudioWatchdog != 0) {
352881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                mAudioWatchdog->pause();
352981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
353081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#endif
353181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        } else {
353281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            sq->end(false /*didModify*/);
353381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
353481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
353581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    PlaybackThread::threadLoop_standby();
353681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
353781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
3538bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurentbool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3539bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent{
3540bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    return false;
3541bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent}
3542bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
3543bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurentbool AudioFlinger::PlaybackThread::shouldStandby_l()
3544bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent{
3545bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    return !mStandby;
3546bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent}
3547bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
3548bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurentbool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3549bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent{
3550bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    Mutex::Autolock _l(mLock);
3551bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    return waitingAsyncCallback_l();
3552bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent}
3553bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
355481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// shared by MIXER and DIRECT, overridden by DUPLICATING
355581784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::PlaybackThread::threadLoop_standby()
355681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
355781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
3558062e67a26e0553dd142be622821f493df541f0c6Phil Burk    mOutput->standby();
3559bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    if (mUseAsyncWrite != 0) {
35603b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent        // discard any pending drain or write ack by incrementing sequence
35613b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent        mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
35623b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent        mDrainSequence = (mDrainSequence + 2) & ~1;
3563bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        ALOG_ASSERT(mCallbackThread != 0);
35643b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent        mCallbackThread->setWriteBlocked(mWriteAckSequence);
35653b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent        mCallbackThread->setDraining(mDrainSequence);
3566bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    }
3567d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    mHwPaused = false;
356881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
356981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
35704c6a433d74d5ae8b9bc0557207e3ced43bf34a25Haynes Mathew Georgevoid AudioFlinger::PlaybackThread::onAddNewTrack_l()
35714c6a433d74d5ae8b9bc0557207e3ced43bf34a25Haynes Mathew George{
35724c6a433d74d5ae8b9bc0557207e3ced43bf34a25Haynes Mathew George    ALOGV("signal playback thread");
35734c6a433d74d5ae8b9bc0557207e3ced43bf34a25Haynes Mathew George    broadcast_l();
35744c6a433d74d5ae8b9bc0557207e3ced43bf34a25Haynes Mathew George}
35754c6a433d74d5ae8b9bc0557207e3ced43bf34a25Haynes Mathew George
357681784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::MixerThread::threadLoop_mix()
357781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
357881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // obtain the presentation timestamp of the next output buffer
357981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    int64_t pts;
358081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    status_t status = INVALID_OPERATION;
358181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
358281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (mNormalSink != 0) {
358381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        status = mNormalSink->getNextWriteTimestamp(&pts);
358481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    } else {
358581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        status = mOutputSink->getNextWriteTimestamp(&pts);
358681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
358781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
358881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (status != NO_ERROR) {
358981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        pts = AudioBufferProvider::kInvalidPTS;
359081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
359181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
359281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // mix buffers...
359381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mAudioMixer->process(pts);
359425c2dac12114699e90deb1c579cadebce7b91a97Andy Hung    mCurrentWriteLength = mSinkBufferSize;
359581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // increase sleep time progressively when application underrun condition clears.
359681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // Only increase sleep time if the mixer is ready for two consecutive times to avoid
359781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // that a steady state of alternating ready/not ready conditions keeps the sleep time
359881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // such that we would underrun the audio HAL.
3599ad9cb8b88e4f8face23f01d8dc89fa769dacb50fEric Laurent    if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
360081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sleepTimeShift--;
360181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
3602ad9cb8b88e4f8face23f01d8dc89fa769dacb50fEric Laurent    mSleepTimeUs = 0;
3603ad9cb8b88e4f8face23f01d8dc89fa769dacb50fEric Laurent    mStandbyTimeNs = systemTime() + mStandbyDelayNs;
360481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    //TODO: delay standby when effects have a tail
36054c053ea158b29fa2cdd4c6f39d3c8da4ee5a7a02Glenn Kasten
360681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
360781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
360881784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::MixerThread::threadLoop_sleepTime()
360981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
361081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // If no tracks are ready, sleep once for the duration of an output
361181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // buffer size, then write 0s to the output
3612ad9cb8b88e4f8face23f01d8dc89fa769dacb50fEric Laurent    if (mSleepTimeUs == 0) {
361381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3614ad9cb8b88e4f8face23f01d8dc89fa769dacb50fEric Laurent            mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3615ad9cb8b88e4f8face23f01d8dc89fa769dacb50fEric Laurent            if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3616ad9cb8b88e4f8face23f01d8dc89fa769dacb50fEric Laurent                mSleepTimeUs = kMinThreadSleepTimeUs;
361781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
361881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // reduce sleep time in case of consecutive application underruns to avoid
361981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
362081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // duration we would end up writing less data than needed by the audio HAL if
362181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // the condition persists.
362281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if (sleepTimeShift < kMaxThreadSleepTimeShift) {
362381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                sleepTimeShift++;
362481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
362581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        } else {
3626ad9cb8b88e4f8face23f01d8dc89fa769dacb50fEric Laurent            mSleepTimeUs = mIdleSleepTimeUs;
362781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
362881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
362998ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung        // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
363098ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung        // before effects processing or output.
363198ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung        if (mMixerBufferValid) {
363298ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung            memset(mMixerBuffer, 0, mMixerBufferSize);
363398ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung        } else {
363498ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung            memset(mSinkBuffer, 0, mSinkBufferSize);
363598ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung        }
3636ad9cb8b88e4f8face23f01d8dc89fa769dacb50fEric Laurent        mSleepTimeUs = 0;
363781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
363881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                "anticipated start");
363981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
364081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // TODO add standby time extension fct of effect tail
364181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
364281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
364381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// prepareTracks_l() must be called with ThreadBase::mLock held
364481784c37c61b09289654b979567a42bf73cd2b12Eric LaurentAudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
364581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        Vector< sp<Track> > *tracksToRemove)
364681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
364781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
364881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mixer_state mixerStatus = MIXER_IDLE;
364981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // find out which tracks need to be processed
365081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    size_t count = mActiveTracks.size();
365181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    size_t mixedTracks = 0;
365281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    size_t tracksWithEffect = 0;
365381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // counts only _active_ fast tracks
365481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    size_t fastTracks = 0;
365581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
365681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
365781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    float masterVolume = mMasterVolume;
365881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    bool masterMute = mMasterMute;
365981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
366081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (masterMute) {
366181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        masterVolume = 0;
366281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
366381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // Delegate master volume control to effect in output mix effect chain if needed
366481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
366581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (chain != 0) {
366681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        uint32_t v = (uint32_t)(masterVolume * (1 << 24));
366781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        chain->setVolume_l(&v, &v);
366881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        masterVolume = (float)((v + (1 << 23)) >> 24);
366981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        chain.clear();
367081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
367181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
367281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // prepare a new state to push
367381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    FastMixerStateQueue *sq = NULL;
367481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    FastMixerState *state = NULL;
367581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    bool didModify = false;
367681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
36774d23ca370dd0ce584f49a80ef9dfcdbb75ba2c8eGlenn Kasten    if (mFastMixer != 0) {
367881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sq = mFastMixer->sq();
367981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        state = sq->begin();
368081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
368181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
368269aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung    mMixerBufferValid = false;  // mMixerBuffer has no valid data until appropriate tracks found.
368398ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung    mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
368469aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung
368581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    for (size_t i=0 ; i<count ; i++) {
36869fdcb0a9497ca290bcf364b10868587b6bde3a34Glenn Kasten        const sp<Track> t = mActiveTracks[i].promote();
368781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (t == 0) {
368881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            continue;
368981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
369081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
369181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // this const just means the local variable doesn't change
369281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        Track* const track = t.get();
369381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
369481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // process fast tracks
369581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (track->isFastTrack()) {
369681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
369781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // It's theoretically possible (though unlikely) for a fast track to be created
369881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // and then removed within the same normal mix cycle.  This is not a problem, as
369981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // the track never becomes active so it's fast mixer slot is never touched.
370081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // The converse, of removing an (active) track and then creating a new track
370181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // at the identical fast mixer slot within the same normal mix cycle,
370281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // is impossible because the slot isn't marked available until the end of each cycle.
370381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            int j = track->mFastIndex;
370481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
370581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
370681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            FastTrack *fastTrack = &state->mFastTracks[j];
370781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
370881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // Determine whether the track is currently in underrun condition,
370981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // and whether it had a recent underrun.
371081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
371181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            FastTrackUnderruns underruns = ftDump->mUnderruns;
371281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            uint32_t recentFull = (underruns.mBitFields.mFull -
371381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
371481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            uint32_t recentPartial = (underruns.mBitFields.mPartial -
371581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
371681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
371781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
371881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            uint32_t recentUnderruns = recentPartial + recentEmpty;
371981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            track->mObservedUnderruns = underruns;
372081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // don't count underruns that occur while stopping or pausing
372181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // or stopped which can occur when flush() is called while active
372282aaf94a5b18939e4d790bbc752031f3070704a3Glenn Kasten            if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
372382aaf94a5b18939e4d790bbc752031f3070704a3Glenn Kasten                    recentUnderruns > 0) {
372482aaf94a5b18939e4d790bbc752031f3070704a3Glenn Kasten                // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
372582aaf94a5b18939e4d790bbc752031f3070704a3Glenn Kasten                track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
372681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
372781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
372881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // This is similar to the state machine for normal tracks,
372981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // with a few modifications for fast tracks.
373081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            bool isActive = true;
373181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            switch (track->mState) {
373281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            case TrackBase::STOPPING_1:
373381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // track stays active in STOPPING_1 state until first underrun
3734bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                if (recentUnderruns > 0 || track->isTerminated()) {
373581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    track->mState = TrackBase::STOPPING_2;
373681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
373781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                break;
373881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            case TrackBase::PAUSING:
373981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // ramp down is not yet implemented
374081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                track->setPaused();
374181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                break;
374281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            case TrackBase::RESUMING:
374381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // ramp up is not yet implemented
374481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                track->mState = TrackBase::ACTIVE;
374581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                break;
374681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            case TrackBase::ACTIVE:
374781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                if (recentFull > 0 || recentPartial > 0) {
374881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    // track has provided at least some frames recently: reset retry count
374981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    track->mRetryCount = kMaxTrackRetries;
375081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
375181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                if (recentUnderruns == 0) {
375281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    // no recent underruns: stay active
375381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    break;
375481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
375581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // there has recently been an underrun of some kind
375681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                if (track->sharedBuffer() == 0) {
375781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    // were any of the recent underruns "empty" (no frames available)?
375881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    if (recentEmpty == 0) {
375981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                        // no, then ignore the partial underruns as they are allowed indefinitely
376081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                        break;
376181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    }
376281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    // there has recently been an "empty" underrun: decrement the retry counter
376381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    if (--(track->mRetryCount) > 0) {
376481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                        break;
376581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    }
376681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    // indicate to client process that the track was disabled because of underrun;
376781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    // it will then automatically call start() when data is available
376896f60d8f04432a1ed503b3e24d5736d28c63c9a2Glenn Kasten                    android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
376981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    // remove from active list, but state remains ACTIVE [confusing but true]
377081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    isActive = false;
377181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    break;
377281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
377381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // fall through
377481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            case TrackBase::STOPPING_2:
377581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            case TrackBase::PAUSED:
377681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            case TrackBase::STOPPED:
377781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            case TrackBase::FLUSHED:   // flush() while active
377881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // Check for presentation complete if track is inactive
377981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // We have consumed all the buffers of this track.
378081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // This would be incomplete if we auto-paused on underrun
378181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                {
378281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    size_t audioHALFrames =
378381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                            (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
378481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    size_t framesWritten = mBytesWritten / mFrameSize;
378581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
378681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                        // track stays in active list until presentation is complete
378781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                        break;
378881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    }
378981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
379081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                if (track->isStopping_2()) {
379181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    track->mState = TrackBase::STOPPED;
379281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
379381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                if (track->isStopped()) {
379481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    // Can't reset directly, as fast mixer is still polling this track
379581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    //   track->reset();
379681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    // So instead mark this track as needing to be reset after push with ack
379781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    resetMask |= 1 << i;
379881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
379981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                isActive = false;
380081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                break;
380181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            case TrackBase::IDLE:
380281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            default:
3803adad3d7d935da176ff24941b4ae9edf7340e9b96Glenn Kasten                LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
380481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
380581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
380681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if (isActive) {
380781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // was it previously inactive?
380881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                if (!(state->mTrackMask & (1 << j))) {
380981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    ExtendedAudioBufferProvider *eabp = track;
381081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    VolumeProvider *vp = track;
381181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    fastTrack->mBufferProvider = eabp;
381281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    fastTrack->mVolumeProvider = vp;
381381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    fastTrack->mChannelMask = track->mChannelMask;
3814e8a1ced4da17dc6c07803dc2af8060f62a8389c1Andy Hung                    fastTrack->mFormat = track->mFormat;
381581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    fastTrack->mGeneration++;
381681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    state->mTrackMask |= 1 << j;
381781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    didModify = true;
381881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    // no acknowledgement required for newly active tracks
381981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
382081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // cache the combined master volume and stream type volume for fast mixer; this
382181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // lacks any synchronization or barrier so VolumeProvider may read a stale value
3822e4756fe3a387615acb63c6a05788c8db9b5786cbGlenn Kasten                track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
382381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                ++fastTracks;
382481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            } else {
382581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // was it previously active?
382681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                if (state->mTrackMask & (1 << j)) {
382781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    fastTrack->mBufferProvider = NULL;
382881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    fastTrack->mGeneration++;
382981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    state->mTrackMask &= ~(1 << j);
383081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    didModify = true;
383181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    // If any fast tracks were removed, we must wait for acknowledgement
383281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    // because we're about to decrement the last sp<> on those tracks.
383381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
383481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                } else {
3835adad3d7d935da176ff24941b4ae9edf7340e9b96Glenn Kasten                    LOG_ALWAYS_FATAL("fast track %d should have been active", j);
383681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
383781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                tracksToRemove->add(track);
383881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // Avoids a misleading display in dumpsys
383981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
384081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
384181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            continue;
384281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
384381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
384481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        {   // local variable scope to avoid goto warning
384581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
384681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        audio_track_cblk_t* cblk = track->cblk();
384781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
384881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // The first time a track is added we wait
384981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // for all its buffers to be filled before processing it
385081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        int name = track->name();
385181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // make sure that we have enough frames to mix one full buffer.
385281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // enforce this condition only once to enable draining the buffer in case the client
385381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // app does not call stop() and relies on underrun to stop:
385481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
385581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // during last round
38569f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        size_t desiredFrames;
38578edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung        const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
38585a8a95de6dad1a3bcf3da5a37b35766e89086e13Ricardo Garcia        AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
38598edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung
38608edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung        desiredFrames = sourceFramesNeededWithTimestretch(
38615a8a95de6dad1a3bcf3da5a37b35766e89086e13Ricardo Garcia                sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
38628edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung        // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
38638edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung        // add frames already consumed but not yet released by the resampler
38648edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung        // because mAudioTrackServerProxy->framesReady() will include these frames
38658edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung        desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
38668edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung
386781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        uint32_t minFrames = 1;
386881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
386981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
38709f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            minFrames = desiredFrames;
38719f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
387213e4c960ea3db03a43e084fbd85d52aa77f7b871Eric Laurent
387313e4c960ea3db03a43e084fbd85d52aa77f7b871Eric Laurent        size_t framesReady = track->framesReady();
3874e77540228e1f60b1129a1615d2e43e0bf8015d3cGlenn Kasten        if (ATRACE_ENABLED()) {
3875e77540228e1f60b1129a1615d2e43e0bf8015d3cGlenn Kasten            // I wish we had formatted trace names
3876e77540228e1f60b1129a1615d2e43e0bf8015d3cGlenn Kasten            char traceName[16];
3877e77540228e1f60b1129a1615d2e43e0bf8015d3cGlenn Kasten            strcpy(traceName, "nRdy");
3878e77540228e1f60b1129a1615d2e43e0bf8015d3cGlenn Kasten            int name = track->name();
3879e77540228e1f60b1129a1615d2e43e0bf8015d3cGlenn Kasten            if (AudioMixer::TRACK0 <= name &&
3880e77540228e1f60b1129a1615d2e43e0bf8015d3cGlenn Kasten                    name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
3881e77540228e1f60b1129a1615d2e43e0bf8015d3cGlenn Kasten                name -= AudioMixer::TRACK0;
3882e77540228e1f60b1129a1615d2e43e0bf8015d3cGlenn Kasten                traceName[4] = (name / 10) + '0';
3883e77540228e1f60b1129a1615d2e43e0bf8015d3cGlenn Kasten                traceName[5] = (name % 10) + '0';
3884e77540228e1f60b1129a1615d2e43e0bf8015d3cGlenn Kasten            } else {
3885e77540228e1f60b1129a1615d2e43e0bf8015d3cGlenn Kasten                traceName[4] = '?';
3886e77540228e1f60b1129a1615d2e43e0bf8015d3cGlenn Kasten                traceName[5] = '?';
3887e77540228e1f60b1129a1615d2e43e0bf8015d3cGlenn Kasten            }
3888e77540228e1f60b1129a1615d2e43e0bf8015d3cGlenn Kasten            traceName[6] = '\0';
3889e77540228e1f60b1129a1615d2e43e0bf8015d3cGlenn Kasten            ATRACE_INT(traceName, framesReady);
3890e77540228e1f60b1129a1615d2e43e0bf8015d3cGlenn Kasten        }
38919f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        if ((framesReady >= minFrames) && track->isReady() &&
389281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                !track->isPaused() && !track->isTerminated())
389381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        {
3894f20e1d8df84c5fbeeace0052d100982ae39bb7a4Glenn Kasten            ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
389581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
389681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mixedTracks++;
389781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
389869aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung            // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
389969aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung            // there is an effect chain connected to the track
390081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            chain.clear();
390169aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung            if (track->mainBuffer() != mSinkBuffer &&
390269aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung                    track->mainBuffer() != mMixerBuffer) {
390398ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung                if (mEffectBufferEnabled) {
390498ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung                    mEffectBufferValid = true; // Later can set directly.
390598ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung                }
390681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                chain = getEffectChain_l(track->sessionId());
390781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // Delegate volume control to effect in track effect chain if needed
390881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                if (chain != 0) {
390981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    tracksWithEffect++;
391081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                } else {
391181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
391281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                            "session %d",
391381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                            name, track->sessionId());
391481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
391581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
391681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
391781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
391881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            int param = AudioMixer::VOLUME;
391981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if (track->mFillingUpStatus == Track::FS_FILLED) {
392081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // no ramp for the first volume setting
392181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                track->mFillingUpStatus = Track::FS_ACTIVE;
392281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                if (track->mState == TrackBase::RESUMING) {
392381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    track->mState = TrackBase::ACTIVE;
392481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    param = AudioMixer::RAMP_VOLUME;
392581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
392681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
3927f20e1d8df84c5fbeeace0052d100982ae39bb7a4Glenn Kasten            // FIXME should not make a decision based on mServer
3928f20e1d8df84c5fbeeace0052d100982ae39bb7a4Glenn Kasten            } else if (cblk->mServer != 0) {
392981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // If the track is stopped before the first frame was mixed,
393081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // do not apply ramp
393181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                param = AudioMixer::RAMP_VOLUME;
393281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
393381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
393481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // compute volume for this track
39356be494077f8d7970f3a88129c5d139c5a0c88f6dAndy Hung            uint32_t vl, vr;       // in U8.24 integer format
39366be494077f8d7970f3a88129c5d139c5a0c88f6dAndy Hung            float vlf, vrf, vaf;   // in [0.0, 1.0] float format
3937e4756fe3a387615acb63c6a05788c8db9b5786cbGlenn Kasten            if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
39386be494077f8d7970f3a88129c5d139c5a0c88f6dAndy Hung                vl = vr = 0;
39396be494077f8d7970f3a88129c5d139c5a0c88f6dAndy Hung                vlf = vrf = vaf = 0.;
394081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                if (track->isPausing()) {
394181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    track->setPaused();
394281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
394381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            } else {
394481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
394581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // read original volumes with volume control
394681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                float typeVolume = mStreamTypes[track->streamType()].volume;
394781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                float v = masterVolume * typeVolume;
39489f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
3949c56f3426099a3cf2d07ccff8886050c7fbce140fGlenn Kasten                gain_minifloat_packed_t vlr = proxy->getVolumeLR();
39506be494077f8d7970f3a88129c5d139c5a0c88f6dAndy Hung                vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
39516be494077f8d7970f3a88129c5d139c5a0c88f6dAndy Hung                vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
395281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // track volumes come from shared memory, so can't be trusted and must be clamped
3953c56f3426099a3cf2d07ccff8886050c7fbce140fGlenn Kasten                if (vlf > GAIN_FLOAT_UNITY) {
3954c56f3426099a3cf2d07ccff8886050c7fbce140fGlenn Kasten                    ALOGV("Track left volume out of range: %.3g", vlf);
3955c56f3426099a3cf2d07ccff8886050c7fbce140fGlenn Kasten                    vlf = GAIN_FLOAT_UNITY;
395681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
3957c56f3426099a3cf2d07ccff8886050c7fbce140fGlenn Kasten                if (vrf > GAIN_FLOAT_UNITY) {
3958c56f3426099a3cf2d07ccff8886050c7fbce140fGlenn Kasten                    ALOGV("Track right volume out of range: %.3g", vrf);
3959c56f3426099a3cf2d07ccff8886050c7fbce140fGlenn Kasten                    vrf = GAIN_FLOAT_UNITY;
396081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
396181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // now apply the master volume and stream type volume
39626be494077f8d7970f3a88129c5d139c5a0c88f6dAndy Hung                vlf *= v;
39636be494077f8d7970f3a88129c5d139c5a0c88f6dAndy Hung                vrf *= v;
396481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // assuming master volume and stream type volume each go up to 1.0,
39656be494077f8d7970f3a88129c5d139c5a0c88f6dAndy Hung                // then derive vl and vr as U8.24 versions for the effect chain
39666be494077f8d7970f3a88129c5d139c5a0c88f6dAndy Hung                const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
39676be494077f8d7970f3a88129c5d139c5a0c88f6dAndy Hung                vl = (uint32_t) (scaleto8_24 * vlf);
39686be494077f8d7970f3a88129c5d139c5a0c88f6dAndy Hung                vr = (uint32_t) (scaleto8_24 * vrf);
39696be494077f8d7970f3a88129c5d139c5a0c88f6dAndy Hung                // vl and vr are now in U8.24 format
3970e3aa659e9cee7df5c12a80d285cc29ab3b2cbb39Glenn Kasten                uint16_t sendLevel = proxy->getSendLevel_U4_12();
397181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // send level comes from shared memory and so may be corrupt
397281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                if (sendLevel > MAX_GAIN_INT) {
397381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    ALOGV("Track send level out of range: %04X", sendLevel);
397481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    sendLevel = MAX_GAIN_INT;
397581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
39766be494077f8d7970f3a88129c5d139c5a0c88f6dAndy Hung                // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
39776be494077f8d7970f3a88129c5d139c5a0c88f6dAndy Hung                vaf = v * sendLevel * (1. / MAX_GAIN_INT);
397881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
3979bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
398081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // Delegate volume control to effect in track effect chain if needed
398181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
398281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // Do not ramp volume if volume is controlled by effect
398381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                param = AudioMixer::VOLUME;
3984b6be7f22a82ee3bad8bcc709d21e72fc4727da09Bryant Liu                // Update remaining floating point volume levels
3985b6be7f22a82ee3bad8bcc709d21e72fc4727da09Bryant Liu                vlf = (float)vl / (1 << 24);
3986b6be7f22a82ee3bad8bcc709d21e72fc4727da09Bryant Liu                vrf = (float)vr / (1 << 24);
398781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                track->mHasVolumeController = true;
398881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            } else {
398981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // force no volume ramp when volume controller was just disabled or removed
399081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // from effect chain to avoid volume spike
399181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                if (track->mHasVolumeController) {
399281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    param = AudioMixer::VOLUME;
399381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
399481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                track->mHasVolumeController = false;
399581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
399681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
399781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // XXX: these things DON'T need to be done each time
399881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mAudioMixer->setBufferProvider(name, track);
399981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mAudioMixer->enable(name);
400081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
40016be494077f8d7970f3a88129c5d139c5a0c88f6dAndy Hung            mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
40026be494077f8d7970f3a88129c5d139c5a0c88f6dAndy Hung            mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
40036be494077f8d7970f3a88129c5d139c5a0c88f6dAndy Hung            mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
400481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mAudioMixer->setParameter(
400581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                name,
400681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                AudioMixer::TRACK,
400781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                AudioMixer::FORMAT, (void *)track->format());
400881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mAudioMixer->setParameter(
400981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                name,
401081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                AudioMixer::TRACK,
4011377b2ec9a2885f9b6405b07ba900a9e3f4349c38Kévin PETIT                AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
40129a59276fb465e492138e0576523b54079671e8f4Andy Hung            mAudioMixer->setParameter(
40139a59276fb465e492138e0576523b54079671e8f4Andy Hung                name,
40149a59276fb465e492138e0576523b54079671e8f4Andy Hung                AudioMixer::TRACK,
40159a59276fb465e492138e0576523b54079671e8f4Andy Hung                AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
4016e3aa659e9cee7df5c12a80d285cc29ab3b2cbb39Glenn Kasten            // limit track sample rate to 2 x output sample rate, which changes at re-configuration
4017cd04484f4837b8ca0041d118286ab6a98e84fc75Andy Hung            uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
40189f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
4019e3aa659e9cee7df5c12a80d285cc29ab3b2cbb39Glenn Kasten            if (reqSampleRate == 0) {
4020e3aa659e9cee7df5c12a80d285cc29ab3b2cbb39Glenn Kasten                reqSampleRate = mSampleRate;
4021e3aa659e9cee7df5c12a80d285cc29ab3b2cbb39Glenn Kasten            } else if (reqSampleRate > maxSampleRate) {
4022e3aa659e9cee7df5c12a80d285cc29ab3b2cbb39Glenn Kasten                reqSampleRate = maxSampleRate;
4023e3aa659e9cee7df5c12a80d285cc29ab3b2cbb39Glenn Kasten            }
402481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mAudioMixer->setParameter(
402581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                name,
402681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                AudioMixer::RESAMPLE,
402781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                AudioMixer::SAMPLE_RATE,
4028377b2ec9a2885f9b6405b07ba900a9e3f4349c38Kévin PETIT                (void *)(uintptr_t)reqSampleRate);
40298edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung
40305a8a95de6dad1a3bcf3da5a37b35766e89086e13Ricardo Garcia            AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
40318edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung            mAudioMixer->setParameter(
40328edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung                name,
40338edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung                AudioMixer::TIMESTRETCH,
40348edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung                AudioMixer::PLAYBACK_RATE,
40355a8a95de6dad1a3bcf3da5a37b35766e89086e13Ricardo Garcia                &playbackRate);
40368edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung
403769aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung            /*
403869aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung             * Select the appropriate output buffer for the track.
403969aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung             *
404098ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung             * Tracks with effects go into their own effects chain buffer
404198ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung             * and from there into either mEffectBuffer or mSinkBuffer.
404269aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung             *
404369aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung             * Other tracks can use mMixerBuffer for higher precision
404469aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung             * channel accumulation.  If this buffer is enabled
404569aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung             * (mMixerBufferEnabled true), then selected tracks will accumulate
404669aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung             * into it.
404769aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung             *
404869aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung             */
404969aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung            if (mMixerBufferEnabled
405069aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung                    && (track->mainBuffer() == mSinkBuffer
405169aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung                            || track->mainBuffer() == mMixerBuffer)) {
405269aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung                mAudioMixer->setParameter(
405369aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung                        name,
405469aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung                        AudioMixer::TRACK,
4055788207057ed4b8df4719ed8089f376ef52de9ca1Andy Hung                        AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
405669aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung                mAudioMixer->setParameter(
405769aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung                        name,
405869aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung                        AudioMixer::TRACK,
405969aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung                        AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
406069aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung                // TODO: override track->mainBuffer()?
406169aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung                mMixerBufferValid = true;
406269aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung            } else {
406369aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung                mAudioMixer->setParameter(
406469aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung                        name,
406569aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung                        AudioMixer::TRACK,
4066788207057ed4b8df4719ed8089f376ef52de9ca1Andy Hung                        AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
406769aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung                mAudioMixer->setParameter(
406869aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung                        name,
406969aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung                        AudioMixer::TRACK,
407069aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung                        AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
407169aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung            }
407281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mAudioMixer->setParameter(
407381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                name,
407481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                AudioMixer::TRACK,
407581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
407681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
407781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // reset retry count
407881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            track->mRetryCount = kMaxTrackRetries;
407981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
408081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // If one track is ready, set the mixer ready if:
408181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            //  - the mixer was not ready during previous round OR
408281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            //  - no other track is not ready
408381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
408481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    mixerStatus != MIXER_TRACKS_ENABLED) {
408581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                mixerStatus = MIXER_TRACKS_READY;
408681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
408781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        } else {
40889f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
408908fb1743f80437c38b4094070d851ea7f6d485e5Andy Hung                ALOGV("track(%p) underrun,  framesReady(%zu) < framesDesired(%zd)",
409008fb1743f80437c38b4094070d851ea7f6d485e5Andy Hung                        track, framesReady, desiredFrames);
409182aaf94a5b18939e4d790bbc752031f3070704a3Glenn Kasten                track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
40929f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            }
409381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // clear effect chain input buffer if an active track underruns to avoid sending
409481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // previous audio buffer again to effects
409581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            chain = getEffectChain_l(track->sessionId());
409681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if (chain != 0) {
409781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                chain->clearInputBuffer();
409881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
409981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
4100f20e1d8df84c5fbeeace0052d100982ae39bb7a4Glenn Kasten            ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
410181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if ((track->sharedBuffer() != 0) || track->isTerminated() ||
410281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    track->isStopped() || track->isPaused()) {
410381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // We have consumed all the buffers of this track.
410481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // Remove it from the list of active tracks.
410581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // TODO: use actual buffer filling status instead of latency when available from
410681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // audio HAL
410781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
410881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                size_t framesWritten = mBytesWritten / mFrameSize;
410981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
411081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    if (track->isStopped()) {
411181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                        track->reset();
411281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    }
411381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    tracksToRemove->add(track);
411481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
411581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            } else {
411681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // No buffers for this track. Give it a few chances to
411781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // fill a buffer, then remove it from active list.
411881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                if (--(track->mRetryCount) <= 0) {
4119c9b2e20f7c9a71e07ef398152709c76079decbcdGlenn Kasten                    ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
412081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    tracksToRemove->add(track);
412181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    // indicate to client process that the track was disabled because of underrun;
412281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    // it will then automatically call start() when data is available
412396f60d8f04432a1ed503b3e24d5736d28c63c9a2Glenn Kasten                    android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
412481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // If one track is not ready, mark the mixer also not ready if:
412581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                //  - the mixer was ready during previous round OR
412681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                //  - no other track is ready
412781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
412881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                                mixerStatus != MIXER_TRACKS_READY) {
412981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    mixerStatus = MIXER_TRACKS_ENABLED;
413081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
413181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
413281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mAudioMixer->disable(name);
413381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
413481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
413581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }   // local variable scope to avoid goto warning
413681784c37c61b09289654b979567a42bf73cd2b12Eric Laurenttrack_is_ready: ;
413781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
413881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
413981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
414081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // Push the new FastMixer state if necessary
414181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    bool pauseAudioWatchdog = false;
414281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (didModify) {
414381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        state->mFastTracksGen++;
414481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
414581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (kUseFastMixer == FastMixer_Dynamic &&
414681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
414781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            state->mCommand = FastMixerState::COLD_IDLE;
414881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            state->mColdFutexAddr = &mFastMixerFutex;
414981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            state->mColdGen++;
415081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mFastMixerFutex = 0;
415181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if (kUseFastMixer == FastMixer_Dynamic) {
415281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                mNormalSink = mOutputSink;
415381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
415481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // If we go into cold idle, need to wait for acknowledgement
415581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // so that fast mixer stops doing I/O.
415681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
415781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            pauseAudioWatchdog = true;
415881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
415981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
416081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (sq != NULL) {
416181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sq->end(didModify);
416281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sq->push(block);
416381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
416481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#ifdef AUDIO_WATCHDOG
416581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (pauseAudioWatchdog && mAudioWatchdog != 0) {
416681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mAudioWatchdog->pause();
416781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
416881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#endif
416981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
417081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // Now perform the deferred reset on fast tracks that have stopped
417181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    while (resetMask != 0) {
417281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        size_t i = __builtin_ctz(resetMask);
417381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        ALOG_ASSERT(i < count);
417481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        resetMask &= ~(1 << i);
417581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sp<Track> t = mActiveTracks[i].promote();
417681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (t == 0) {
417781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            continue;
417881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
417981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        Track* track = t.get();
418081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        ALOG_ASSERT(track->isFastTrack() && track->isStopped());
418181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        track->reset();
418281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
418381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
418481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // remove all the tracks that need to be...
4185bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    removeTracks_l(*tracksToRemove);
418681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
418797d547da43c9c41711d1ed1e3f4fa87c2ee3cb9aEric Laurent    if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
418897d547da43c9c41711d1ed1e3f4fa87c2ee3cb9aEric Laurent        mEffectBufferValid = true;
4189ac302143551a8b964f026385a524dda9ff8ea5baMarco Nelissen    }
4190ac302143551a8b964f026385a524dda9ff8ea5baMarco Nelissen
4191ac302143551a8b964f026385a524dda9ff8ea5baMarco Nelissen    if (mEffectBufferValid) {
419257088b5c8e76855b99b3e6b3e410de5b6382670eMarco Nelissen        // as long as there are effects we should clear the effects buffer, to avoid
419357088b5c8e76855b99b3e6b3e410de5b6382670eMarco Nelissen        // passing a non-clean buffer to the effect chain
419457088b5c8e76855b99b3e6b3e410de5b6382670eMarco Nelissen        memset(mEffectBuffer, 0, mEffectBufferSize);
419597d547da43c9c41711d1ed1e3f4fa87c2ee3cb9aEric Laurent    }
419669aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung    // sink or mix buffer must be cleared if all tracks are connected to an
419769aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung    // effect chain as in this case the mixer will not write to the sink or mix buffer
419869aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung    // and track effects will accumulate into it
4199bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4200bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            (mixedTracks == 0 && fastTracks > 0))) {
420181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // FIXME as a performance optimization, should remember previous zero status
420269aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung        if (mMixerBufferValid) {
420369aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung            memset(mMixerBuffer, 0, mMixerBufferSize);
420469aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung            // TODO: In testing, mSinkBuffer below need not be cleared because
420569aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung            // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
420669aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung            // after mixing.
420769aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung            //
420869aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung            // To enforce this guarantee:
420969aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung            // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
421069aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung            // (mixedTracks == 0 && fastTracks > 0))
421169aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung            // must imply MIXER_TRACKS_READY.
421269aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung            // Later, we may clear buffers regardless, and skip much of this logic.
421369aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung        }
421498ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung        // FIXME as a performance optimization, should remember previous zero status
42155567aaf4818007cd8e77329683a91c0f5d7a8837Andy Hung        memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
421681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
421781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
421881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // if any fast tracks, then status is ready
421981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mMixerStatusIgnoringFastTracks = mixerStatus;
422081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (fastTracks > 0) {
422181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mixerStatus = MIXER_TRACKS_READY;
422281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
422381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return mixerStatus;
422481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
422581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
422681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// getTrackName_l() must be called with ThreadBase::mLock held
4227e8a1ced4da17dc6c07803dc2af8060f62a8389c1Andy Hungint AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
4228e8a1ced4da17dc6c07803dc2af8060f62a8389c1Andy Hung        audio_format_t format, int sessionId)
422981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
4230e8a1ced4da17dc6c07803dc2af8060f62a8389c1Andy Hung    return mAudioMixer->getTrackName(channelMask, format, sessionId);
423181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
423281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
423381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// deleteTrackName_l() must be called with ThreadBase::mLock held
423481784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::MixerThread::deleteTrackName_l(int name)
423581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
423681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    ALOGV("remove track (%d) and delete from mixer", name);
423781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mAudioMixer->deleteTrackName(name);
423881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
423981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
42401035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent// checkForNewParameter_l() must be called with ThreadBase::mLock held
42411035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurentbool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
42421035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                                                       status_t& status)
424381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
424481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    bool reconfig = false;
424581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
42461035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    status = NO_ERROR;
424781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
42481035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    // if !&IDLE, holds the FastMixer state to restore after new parameters processed
42491035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
42504d23ca370dd0ce584f49a80ef9dfcdbb75ba2c8eGlenn Kasten    if (mFastMixer != 0) {
42511035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        FastMixerStateQueue *sq = mFastMixer->sq();
42521035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        FastMixerState *state = sq->begin();
42531035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        if (!(state->mCommand & FastMixerState::IDLE)) {
42541035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            previousCommand = state->mCommand;
42551035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            state->mCommand = FastMixerState::HOT_IDLE;
42561035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            sq->end();
42571035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
42581035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        } else {
42591035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            sq->end(false /*didModify*/);
426081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
42611035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    }
426281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
42631035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    AudioParameter param = AudioParameter(keyValuePair);
42641035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    int value;
42651035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
42661035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        reconfig = true;
42671035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    }
42681035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
42699a59276fb465e492138e0576523b54079671e8f4Andy Hung        if (!isValidPcmSinkFormat((audio_format_t) value)) {
42701035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            status = BAD_VALUE;
42711035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        } else {
42721035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            // no need to save value, since it's constant
427381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            reconfig = true;
427481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
42751035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    }
42761035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
42779a59276fb465e492138e0576523b54079671e8f4Andy Hung        if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
42781035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            status = BAD_VALUE;
42791035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        } else {
42801035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            // no need to save value, since it's constant
42811035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            reconfig = true;
428281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
42831035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    }
42841035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
42851035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        // do not accept frame count changes if tracks are open as the track buffer
42861035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        // size depends on frame count and correct behavior would not be guaranteed
42871035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        // if frame count is changed after track creation
42881035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        if (!mTracks.isEmpty()) {
42891035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            status = INVALID_OPERATION;
42901035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        } else {
42911035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            reconfig = true;
429281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
42931035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    }
42941035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
429581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#ifdef ADD_BATTERY_DATA
42961035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        // when changing the audio output device, call addBatteryData to notify
42971035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        // the change
42981035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        if (mOutDevice != value) {
42991035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            uint32_t params = 0;
43001035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            // check whether speaker is on
43011035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            if (value & AUDIO_DEVICE_OUT_SPEAKER) {
43021035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                params |= IMediaPlayerService::kBatteryDataSpeakerOn;
43031035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            }
430481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
43051035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            audio_devices_t deviceWithoutSpeaker
43061035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
43071035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            // check if any other device (except speaker) is on
4308054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent            if (value & deviceWithoutSpeaker) {
43091035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
43101035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            }
431181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
43121035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            if (params != 0) {
43131035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                addBatteryData(params);
431481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
43151035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        }
431681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#endif
431781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
43181035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        // forward device change to effects that have requested to be
43191035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        // aware of attached audio device.
43201035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        if (value != AUDIO_DEVICE_NONE) {
43211035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            mOutDevice = value;
43221035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            for (size_t i = 0; i < mEffectChains.size(); i++) {
43231035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                mEffectChains[i]->setDevice_l(mOutDevice);
432481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
432581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
43261035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    }
432781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
43281035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    if (status == NO_ERROR) {
43291035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
43301035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                                                keyValuePair.string());
43311035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        if (!mStandby && status == INVALID_OPERATION) {
4332062e67a26e0553dd142be622821f493df541f0c6Phil Burk            mOutput->standby();
43331035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            mStandby = true;
43341035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            mBytesWritten = 0;
433581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
43361035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                                                   keyValuePair.string());
43371035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        }
43381035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        if (status == NO_ERROR && reconfig) {
43391035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            readOutputParameters_l();
43401035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            delete mAudioMixer;
43411035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
43421035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            for (size_t i = 0; i < mTracks.size() ; i++) {
4343e8a1ced4da17dc6c07803dc2af8060f62a8389c1Andy Hung                int name = getTrackName_l(mTracks[i]->mChannelMask,
4344e8a1ced4da17dc6c07803dc2af8060f62a8389c1Andy Hung                        mTracks[i]->mFormat, mTracks[i]->mSessionId);
43451035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                if (name < 0) {
43461035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                    break;
434781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
43481035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                mTracks[i]->mName = name;
434981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
435073e26b661af50be2c0a4ff6c9ac85f7347a8b235Eric Laurent            sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
435181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
435281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
435381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
435481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (!(previousCommand & FastMixerState::IDLE)) {
43554d23ca370dd0ce584f49a80ef9dfcdbb75ba2c8eGlenn Kasten        ALOG_ASSERT(mFastMixer != 0);
435681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        FastMixerStateQueue *sq = mFastMixer->sq();
435781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        FastMixerState *state = sq->begin();
435881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
435981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        state->mCommand = previousCommand;
436081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sq->end();
436181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
436281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
436381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
436481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return reconfig;
436581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
436681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
436781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
436881784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
436981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
437081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    const size_t SIZE = 256;
437181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    char buffer[SIZE];
437281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    String8 result;
437381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
437481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    PlaybackThread::dumpInternals(fd, args);
437540eb1a1f8871909c272e72afaf7d5af84fea2412Andy Hung    dprintf(fd, "  Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
437687cebadd48710e42474756fc3513df678de045ceElliott Hughes    dprintf(fd, "  AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
437781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
437881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
43794182c4e2a07e2441fcd5c22eaff0ddfe7f826f61Glenn Kasten    const FastMixerDumpState copy(mFastMixerDumpState);
438081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    copy.dump(fd);
438181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
438281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#ifdef STATE_QUEUE_DUMP
438381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // Similar for state queue
438481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    StateQueueObserverDump observerCopy = mStateQueueObserverDump;
438581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    observerCopy.dump(fd);
438681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
438781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mutatorCopy.dump(fd);
438881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#endif
438981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
439046909e7eb074ce1b95b8a411eb71154f53f84f77Glenn Kasten#ifdef TEE_SINK
439181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // Write the tee output to a .wav file
439281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    dumpTee(fd, mTeeSource, mId);
439346909e7eb074ce1b95b8a411eb71154f53f84f77Glenn Kasten#endif
439481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
439581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#ifdef AUDIO_WATCHDOG
439681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (mAudioWatchdog != 0) {
439781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
439881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        AudioWatchdogDump wdCopy = mAudioWatchdogDump;
439981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        wdCopy.dump(fd);
440081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
440181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#endif
440281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
440381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
440481784c37c61b09289654b979567a42bf73cd2b12Eric Laurentuint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
440581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
440681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
440781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
440881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
440981784c37c61b09289654b979567a42bf73cd2b12Eric Laurentuint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
441081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
441181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
441281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
441381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
441481784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::MixerThread::cacheParameters_l()
441581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
441681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    PlaybackThread::cacheParameters_l();
441781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
441881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // FIXME: Relaxed timing because of a certain device that can't meet latency
441981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // Should be reduced to 2x after the vendor fixes the driver issue
442081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // increase threshold again due to low power audio mode. The way this warning
442181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // threshold is calculated and its usefulness should be reconsidered anyway.
442281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
442381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
442481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
442581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// ----------------------------------------------------------------------------
442681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
442781784c37c61b09289654b979567a42bf73cd2b12Eric LaurentAudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
442872e3f39146fce4686bd96f11057c051bea376dfbEric Laurent        AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
442972e3f39146fce4686bd96f11057c051bea376dfbEric Laurent    :   PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
443081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // mLeftVolFloat, mRightVolFloat
443181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
443281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
443381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
4434bfb1b832079bbb9426f72f3863199a54aefd02daEric LaurentAudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4435bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
443672e3f39146fce4686bd96f11057c051bea376dfbEric Laurent        ThreadBase::type_t type, bool systemReady)
443772e3f39146fce4686bd96f11057c051bea376dfbEric Laurent    :   PlaybackThread(audioFlinger, output, id, device, type, systemReady)
4438bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        // mLeftVolFloat, mRightVolFloat
4439bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent{
4440bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent}
4441bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
444281784c37c61b09289654b979567a42bf73cd2b12Eric LaurentAudioFlinger::DirectOutputThread::~DirectOutputThread()
444381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
444481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
444581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
4446bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurentvoid AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4447bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent{
4448bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    audio_track_cblk_t* cblk = track->cblk();
4449bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    float left, right;
4450bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
4451bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4452bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        left = right = 0;
4453bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    } else {
4454bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        float typeVolume = mStreamTypes[track->streamType()].volume;
4455bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        float v = mMasterVolume * typeVolume;
4456bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
4457c56f3426099a3cf2d07ccff8886050c7fbce140fGlenn Kasten        gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4458c56f3426099a3cf2d07ccff8886050c7fbce140fGlenn Kasten        left = float_from_gain(gain_minifloat_unpack_left(vlr));
4459c56f3426099a3cf2d07ccff8886050c7fbce140fGlenn Kasten        if (left > GAIN_FLOAT_UNITY) {
4460c56f3426099a3cf2d07ccff8886050c7fbce140fGlenn Kasten            left = GAIN_FLOAT_UNITY;
4461c56f3426099a3cf2d07ccff8886050c7fbce140fGlenn Kasten        }
4462c56f3426099a3cf2d07ccff8886050c7fbce140fGlenn Kasten        left *= v;
4463c56f3426099a3cf2d07ccff8886050c7fbce140fGlenn Kasten        right = float_from_gain(gain_minifloat_unpack_right(vlr));
4464c56f3426099a3cf2d07ccff8886050c7fbce140fGlenn Kasten        if (right > GAIN_FLOAT_UNITY) {
4465c56f3426099a3cf2d07ccff8886050c7fbce140fGlenn Kasten            right = GAIN_FLOAT_UNITY;
4466c56f3426099a3cf2d07ccff8886050c7fbce140fGlenn Kasten        }
4467c56f3426099a3cf2d07ccff8886050c7fbce140fGlenn Kasten        right *= v;
4468bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    }
4469bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
4470bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    if (lastTrack) {
4471bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        if (left != mLeftVolFloat || right != mRightVolFloat) {
4472bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            mLeftVolFloat = left;
4473bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            mRightVolFloat = right;
4474bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
4475bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            // Convert volumes from float to 8.24
4476bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            uint32_t vl = (uint32_t)(left * (1 << 24));
4477bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            uint32_t vr = (uint32_t)(right * (1 << 24));
4478bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
4479bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            // Delegate volume control to effect in track effect chain if needed
4480bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            // only one effect chain can be present on DirectOutputThread, so if
4481bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            // there is one, the track is connected to it
4482bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            if (!mEffectChains.isEmpty()) {
4483bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                mEffectChains[0]->setVolume_l(&vl, &vr);
4484bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                left = (float)vl / (1 << 24);
4485bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                right = (float)vr / (1 << 24);
4486bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            }
4487bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            if (mOutput->stream->set_volume) {
4488bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                mOutput->stream->set_volume(mOutput->stream, left, right);
4489bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            }
4490bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        }
4491bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    }
4492bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent}
4493bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
449443b4dcc660e6da96285e4672ae371070ab845401Phil Burkvoid AudioFlinger::DirectOutputThread::onAddNewTrack_l()
449543b4dcc660e6da96285e4672ae371070ab845401Phil Burk{
449643b4dcc660e6da96285e4672ae371070ab845401Phil Burk    sp<Track> previousTrack = mPreviousTrack.promote();
449743b4dcc660e6da96285e4672ae371070ab845401Phil Burk    sp<Track> latestTrack = mLatestActiveTrack.promote();
449843b4dcc660e6da96285e4672ae371070ab845401Phil Burk
44990f0631eb55b1f0a7f4b62212b78a3faa0b49919bEric Laurent    if (previousTrack != 0 && latestTrack != 0) {
45000f0631eb55b1f0a7f4b62212b78a3faa0b49919bEric Laurent        if (mType == DIRECT) {
45010f0631eb55b1f0a7f4b62212b78a3faa0b49919bEric Laurent            if (previousTrack.get() != latestTrack.get()) {
45020f0631eb55b1f0a7f4b62212b78a3faa0b49919bEric Laurent                mFlushPending = true;
45030f0631eb55b1f0a7f4b62212b78a3faa0b49919bEric Laurent            }
45040f0631eb55b1f0a7f4b62212b78a3faa0b49919bEric Laurent        } else /* mType == OFFLOAD */ {
45050f0631eb55b1f0a7f4b62212b78a3faa0b49919bEric Laurent            if (previousTrack->sessionId() != latestTrack->sessionId()) {
45060f0631eb55b1f0a7f4b62212b78a3faa0b49919bEric Laurent                mFlushPending = true;
45070f0631eb55b1f0a7f4b62212b78a3faa0b49919bEric Laurent            }
45080f0631eb55b1f0a7f4b62212b78a3faa0b49919bEric Laurent        }
450943b4dcc660e6da96285e4672ae371070ab845401Phil Burk    }
451043b4dcc660e6da96285e4672ae371070ab845401Phil Burk    PlaybackThread::onAddNewTrack_l();
451143b4dcc660e6da96285e4672ae371070ab845401Phil Burk}
4512bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
451381784c37c61b09289654b979567a42bf73cd2b12Eric LaurentAudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
451481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Vector< sp<Track> > *tracksToRemove
451581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent)
451681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
4517d595b7c858c481a07745674ce2d8a6690e980e74Eric Laurent    size_t count = mActiveTracks.size();
451881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mixer_state mixerStatus = MIXER_IDLE;
4519d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    bool doHwPause = false;
4520d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    bool doHwResume = false;
452181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
452281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // find out which tracks need to be processed
4523d595b7c858c481a07745674ce2d8a6690e980e74Eric Laurent    for (size_t i = 0; i < count; i++) {
4524d595b7c858c481a07745674ce2d8a6690e980e74Eric Laurent        sp<Track> t = mActiveTracks[i].promote();
452581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // The track died recently
452681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (t == 0) {
4527d595b7c858c481a07745674ce2d8a6690e980e74Eric Laurent            continue;
452881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
452981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
453043b4dcc660e6da96285e4672ae371070ab845401Phil Burk        if (t->isInvalid()) {
453143b4dcc660e6da96285e4672ae371070ab845401Phil Burk            ALOGW("An invalidated track shouldn't be in active list");
453243b4dcc660e6da96285e4672ae371070ab845401Phil Burk            tracksToRemove->add(t);
453343b4dcc660e6da96285e4672ae371070ab845401Phil Burk            continue;
453443b4dcc660e6da96285e4672ae371070ab845401Phil Burk        }
453543b4dcc660e6da96285e4672ae371070ab845401Phil Burk
453681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        Track* const track = t.get();
453781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        audio_track_cblk_t* cblk = track->cblk();
4538fd4779740ec3e9e865d5514464df26d015354388Eric Laurent        // Only consider last track started for volume and mixer state control.
4539fd4779740ec3e9e865d5514464df26d015354388Eric Laurent        // In theory an older track could underrun and restart after the new one starts
4540fd4779740ec3e9e865d5514464df26d015354388Eric Laurent        // but as we only care about the transition phase between two tracks on a
4541fd4779740ec3e9e865d5514464df26d015354388Eric Laurent        // direct output, it is not a problem to ignore the underrun case.
4542fd4779740ec3e9e865d5514464df26d015354388Eric Laurent        sp<Track> l = mLatestActiveTrack.promote();
4543fd4779740ec3e9e865d5514464df26d015354388Eric Laurent        bool last = l.get() == track;
454481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
45456fc2a7c81f62b1e21487ae37e11aae6241bc3eadPhil Burk        if (track->isPausing()) {
4546d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent            track->setPaused();
45476fc2a7c81f62b1e21487ae37e11aae6241bc3eadPhil Burk            if (mHwSupportsPause && last && !mHwPaused) {
4548d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent                doHwPause = true;
4549d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent                mHwPaused = true;
4550d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent            }
4551d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent            tracksToRemove->add(track);
4552d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent        } else if (track->isFlushPending()) {
4553d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent            track->flushAck();
4554d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent            if (last) {
455543b4dcc660e6da96285e4672ae371070ab845401Phil Burk                mFlushPending = true;
4556d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent            }
45576fc2a7c81f62b1e21487ae37e11aae6241bc3eadPhil Burk        } else if (track->isResumePending()) {
4558d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent            track->resumeAck();
45596fc2a7c81f62b1e21487ae37e11aae6241bc3eadPhil Burk            if (last && mHwPaused) {
45606fc2a7c81f62b1e21487ae37e11aae6241bc3eadPhil Burk                doHwResume = true;
45616fc2a7c81f62b1e21487ae37e11aae6241bc3eadPhil Burk                mHwPaused = false;
4562d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent            }
4563d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent        }
4564d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent
456581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // The first time a track is added we wait
456699adee3c3d9cde6819741a38163954808fea270aPhil Burk        // for all its buffers to be filled before processing it.
456799adee3c3d9cde6819741a38163954808fea270aPhil Burk        // Allow draining the buffer in case the client
456899adee3c3d9cde6819741a38163954808fea270aPhil Burk        // app does not call stop() and relies on underrun to stop:
456999adee3c3d9cde6819741a38163954808fea270aPhil Burk        // hence the test on (track->mRetryCount > 1).
457099adee3c3d9cde6819741a38163954808fea270aPhil Burk        // If retryCount<=1 then track is about to underrun and be removed.
4571ca5e6143740299c877d69e97f7968cd04476d32cPhil Burk        // Do not use a high threshold for compressed audio.
457281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        uint32_t minFrames;
457399adee3c3d9cde6819741a38163954808fea270aPhil Burk        if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
4574ca5e6143740299c877d69e97f7968cd04476d32cPhil Burk            && (track->mRetryCount > 1) && audio_is_linear_pcm(mFormat)) {
457581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            minFrames = mNormalFrameCount;
457681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        } else {
457781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            minFrames = 1;
457881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
4579bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
4580ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent        if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4581ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent                !track->isStopping_2() && !track->isStopped())
458281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        {
4583f20e1d8df84c5fbeeace0052d100982ae39bb7a4Glenn Kasten            ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
458481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
458581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if (track->mFillingUpStatus == Track::FS_FILLED) {
458681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                track->mFillingUpStatus = Track::FS_ACTIVE;
45871abbdb4429479975718421c4fef3f79ce7c820e3Eric Laurent                // make sure processVolume_l() will apply new volume even if 0
45881abbdb4429479975718421c4fef3f79ce7c820e3Eric Laurent                mLeftVolFloat = mRightVolFloat = -1.0;
4589d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent                if (!mHwSupportsPause) {
4590d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent                    track->resumeAck();
459181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
459281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
459381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
459481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // compute volume for this track
4595bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            processVolume_l(track, last);
4596bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            if (last) {
459743b4dcc660e6da96285e4672ae371070ab845401Phil Burk                sp<Track> previousTrack = mPreviousTrack.promote();
459843b4dcc660e6da96285e4672ae371070ab845401Phil Burk                if (previousTrack != 0) {
459943b4dcc660e6da96285e4672ae371070ab845401Phil Burk                    if (track != previousTrack.get()) {
460043b4dcc660e6da96285e4672ae371070ab845401Phil Burk                        // Flush any data still being written from last track
460143b4dcc660e6da96285e4672ae371070ab845401Phil Burk                        mBytesRemaining = 0;
46020f0631eb55b1f0a7f4b62212b78a3faa0b49919bEric Laurent                        // Invalidate previous track to force a seek when resuming.
46030f0631eb55b1f0a7f4b62212b78a3faa0b49919bEric Laurent                        previousTrack->invalidate();
460443b4dcc660e6da96285e4672ae371070ab845401Phil Burk                    }
460543b4dcc660e6da96285e4672ae371070ab845401Phil Burk                }
460643b4dcc660e6da96285e4672ae371070ab845401Phil Burk                mPreviousTrack = track;
460743b4dcc660e6da96285e4672ae371070ab845401Phil Burk
4608d595b7c858c481a07745674ce2d8a6690e980e74Eric Laurent                // reset retry count
4609d595b7c858c481a07745674ce2d8a6690e980e74Eric Laurent                track->mRetryCount = kMaxTrackRetriesDirect;
4610d595b7c858c481a07745674ce2d8a6690e980e74Eric Laurent                mActiveTrack = t;
4611d595b7c858c481a07745674ce2d8a6690e980e74Eric Laurent                mixerStatus = MIXER_TRACKS_READY;
46125cff403679fc44c8293de81aed31c459c6129243Eric Laurent                if (mHwPaused) {
46130f7b5f2b231caf87da9b20b74d086e5a9d6f4a9dEric Laurent                    doHwResume = true;
46140f7b5f2b231caf87da9b20b74d086e5a9d6f4a9dEric Laurent                    mHwPaused = false;
46150f7b5f2b231caf87da9b20b74d086e5a9d6f4a9dEric Laurent                }
4616d595b7c858c481a07745674ce2d8a6690e980e74Eric Laurent            }
461781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        } else {
4618d595b7c858c481a07745674ce2d8a6690e980e74Eric Laurent            // clear effect chain input buffer if the last active track started underruns
4619d595b7c858c481a07745674ce2d8a6690e980e74Eric Laurent            // to avoid sending previous audio buffer again to effects
4620fd4779740ec3e9e865d5514464df26d015354388Eric Laurent            if (!mEffectChains.isEmpty() && last) {
462181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                mEffectChains[0]->clearInputBuffer();
462281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
4623ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent            if (track->isStopping_1()) {
4624ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent                track->mState = TrackBase::STOPPING_2;
4625b369cafd67beb63dd0278dba543f519956208a7fEric Laurent                if (last && mHwPaused) {
4626b369cafd67beb63dd0278dba543f519956208a7fEric Laurent                     doHwResume = true;
4627b369cafd67beb63dd0278dba543f519956208a7fEric Laurent                     mHwPaused = false;
4628b369cafd67beb63dd0278dba543f519956208a7fEric Laurent                 }
4629ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent            }
4630ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent            if ((track->sharedBuffer() != 0) || track->isStopped() ||
4631ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent                    track->isStopping_2() || track->isPaused()) {
463281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // We have consumed all the buffers of this track.
463381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // Remove it from the list of active tracks.
4634ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent                size_t audioHALFrames;
4635ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent                if (audio_is_linear_pcm(mFormat)) {
4636ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent                    audioHALFrames = (latency_l() * mSampleRate) / 1000;
4637ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent                } else {
4638ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent                    audioHALFrames = 0;
4639ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent                }
4640ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent
464181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                size_t framesWritten = mBytesWritten / mFrameSize;
4642fd4779740ec3e9e865d5514464df26d015354388Eric Laurent                if (mStandby || !last ||
4643fd4779740ec3e9e865d5514464df26d015354388Eric Laurent                        track->presentationComplete(framesWritten, audioHALFrames)) {
4644ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent                    if (track->isStopping_2()) {
4645ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent                        track->mState = TrackBase::STOPPED;
4646ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent                    }
464781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    if (track->isStopped()) {
464881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                        track->reset();
464981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    }
4650d595b7c858c481a07745674ce2d8a6690e980e74Eric Laurent                    tracksToRemove->add(track);
465181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
465281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            } else {
465381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // No buffers for this track. Give it a few chances to
465481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // fill a buffer, then remove it from active list.
4655d595b7c858c481a07745674ce2d8a6690e980e74Eric Laurent                // Only consider last track started for mixer state control
465681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                if (--(track->mRetryCount) <= 0) {
465781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
4658d595b7c858c481a07745674ce2d8a6690e980e74Eric Laurent                    tracksToRemove->add(track);
4659a23f17ac334ff20a11ee63dd177cb1080e44c483Eric Laurent                    // indicate to client process that the track was disabled because of underrun;
4660a23f17ac334ff20a11ee63dd177cb1080e44c483Eric Laurent                    // it will then automatically call start() when data is available
4661a23f17ac334ff20a11ee63dd177cb1080e44c483Eric Laurent                    android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
4662bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                } else if (last) {
4663ca5e6143740299c877d69e97f7968cd04476d32cPhil Burk                    ALOGW("pause because of UNDERRUN, framesReady = %zu,"
4664ca5e6143740299c877d69e97f7968cd04476d32cPhil Burk                            "minFrames = %u, mFormat = %#x",
4665ca5e6143740299c877d69e97f7968cd04476d32cPhil Burk                            track->framesReady(), minFrames, mFormat);
466681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    mixerStatus = MIXER_TRACKS_ENABLED;
46675cff403679fc44c8293de81aed31c459c6129243Eric Laurent                    if (mHwSupportsPause && !mHwPaused && !mStandby) {
46680f7b5f2b231caf87da9b20b74d086e5a9d6f4a9dEric Laurent                        doHwPause = true;
46690f7b5f2b231caf87da9b20b74d086e5a9d6f4a9dEric Laurent                        mHwPaused = true;
46700f7b5f2b231caf87da9b20b74d086e5a9d6f4a9dEric Laurent                    }
467181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
467281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
467381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
467481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
467581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
4676d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    // if an active track did not command a flush, check for pending flush on stopped tracks
467743b4dcc660e6da96285e4672ae371070ab845401Phil Burk    if (!mFlushPending) {
4678d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent        for (size_t i = 0; i < mTracks.size(); i++) {
4679d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent            if (mTracks[i]->isFlushPending()) {
4680d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent                mTracks[i]->flushAck();
468143b4dcc660e6da96285e4672ae371070ab845401Phil Burk                mFlushPending = true;
4682d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent            }
4683d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent        }
4684d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    }
4685d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent
4686d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    // make sure the pause/flush/resume sequence is executed in the right order.
4687d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4688d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    // before flush and then resume HW. This can happen in case of pause/flush/resume
4689d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    // if resume is received before pause is executed.
4690d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    if (mHwSupportsPause && !mStandby &&
469143b4dcc660e6da96285e4672ae371070ab845401Phil Burk            (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
4692d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent        mOutput->stream->pause(mOutput->stream);
4693d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    }
469443b4dcc660e6da96285e4672ae371070ab845401Phil Burk    if (mFlushPending) {
4695d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent        flushHw_l();
4696d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    }
4697d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    if (mHwSupportsPause && !mStandby && doHwResume) {
4698d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent        mOutput->stream->resume(mOutput->stream);
4699d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    }
470081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // remove all the tracks that need to be...
4701bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    removeTracks_l(*tracksToRemove);
470281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
470381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return mixerStatus;
470481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
470581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
470681784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::DirectOutputThread::threadLoop_mix()
470781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
470881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    size_t frameCount = mFrameCount;
47092098f2744cedf2dc3fa36f608aa965a34602e7c0Andy Hung    int8_t *curBuf = (int8_t *)mSinkBuffer;
471081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // output audio to hardware
471181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    while (frameCount) {
471234542acfa25c6413c87a94b6f7cc315a0c496277Glenn Kasten        AudioBufferProvider::Buffer buffer;
471381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        buffer.frameCount = frameCount;
4714062e67a26e0553dd142be622821f493df541f0c6Phil Burk        status_t status = mActiveTrack->getNextBuffer(&buffer);
4715062e67a26e0553dd142be622821f493df541f0c6Phil Burk        if (status != NO_ERROR || buffer.raw == NULL) {
471681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            memset(curBuf, 0, frameCount * mFrameSize);
471781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            break;
471881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
471981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
472081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        frameCount -= buffer.frameCount;
472181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        curBuf += buffer.frameCount * mFrameSize;
472281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mActiveTrack->releaseBuffer(&buffer);
472381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
47242098f2744cedf2dc3fa36f608aa965a34602e7c0Andy Hung    mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
4725ad9cb8b88e4f8face23f01d8dc89fa769dacb50fEric Laurent    mSleepTimeUs = 0;
4726ad9cb8b88e4f8face23f01d8dc89fa769dacb50fEric Laurent    mStandbyTimeNs = systemTime() + mStandbyDelayNs;
472781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mActiveTrack.clear();
472881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
472981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
473081784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
473181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
4732d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    // do not write to HAL when paused
47330f7b5f2b231caf87da9b20b74d086e5a9d6f4a9dEric Laurent    if (mHwPaused || (usesHwAvSync() && mStandby)) {
4734ad9cb8b88e4f8face23f01d8dc89fa769dacb50fEric Laurent        mSleepTimeUs = mIdleSleepTimeUs;
4735d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent        return;
4736d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    }
4737ad9cb8b88e4f8face23f01d8dc89fa769dacb50fEric Laurent    if (mSleepTimeUs == 0) {
473881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4739ad9cb8b88e4f8face23f01d8dc89fa769dacb50fEric Laurent            mSleepTimeUs = mActiveSleepTimeUs;
474081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        } else {
4741ad9cb8b88e4f8face23f01d8dc89fa769dacb50fEric Laurent            mSleepTimeUs = mIdleSleepTimeUs;
474281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
474381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
47442098f2744cedf2dc3fa36f608aa965a34602e7c0Andy Hung        memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
4745ad9cb8b88e4f8face23f01d8dc89fa769dacb50fEric Laurent        mSleepTimeUs = 0;
474681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
474781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
474881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
4749d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurentvoid AudioFlinger::DirectOutputThread::threadLoop_exit()
4750d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent{
4751d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    {
4752d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent        Mutex::Autolock _l(mLock);
4753d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent        for (size_t i = 0; i < mTracks.size(); i++) {
4754d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent            if (mTracks[i]->isFlushPending()) {
4755d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent                mTracks[i]->flushAck();
475643b4dcc660e6da96285e4672ae371070ab845401Phil Burk                mFlushPending = true;
4757d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent            }
4758d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent        }
475943b4dcc660e6da96285e4672ae371070ab845401Phil Burk        if (mFlushPending) {
4760d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent            flushHw_l();
4761d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent        }
4762d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    }
4763d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    PlaybackThread::threadLoop_exit();
4764d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent}
4765d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent
4766d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent// must be called with thread mutex locked
4767d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurentbool AudioFlinger::DirectOutputThread::shouldStandby_l()
4768d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent{
4769d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    bool trackPaused = false;
4770b369cafd67beb63dd0278dba543f519956208a7fEric Laurent    bool trackStopped = false;
4771d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent
4772d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4773d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    // after a timeout and we will enter standby then.
4774d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    if (mTracks.size() > 0) {
4775d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent        trackPaused = mTracks[mTracks.size() - 1]->isPaused();
4776b369cafd67beb63dd0278dba543f519956208a7fEric Laurent        trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
4777b369cafd67beb63dd0278dba543f519956208a7fEric Laurent                           mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
4778d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    }
4779d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent
47805cff403679fc44c8293de81aed31c459c6129243Eric Laurent    return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
4781d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent}
4782d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent
478381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// getTrackName_l() must be called with ThreadBase::mLock held
47840f11b51a57bc9062c4fe8af73747319cedabc5d6Glenn Kastenint AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
4785e8a1ced4da17dc6c07803dc2af8060f62a8389c1Andy Hung        audio_format_t format __unused, int sessionId __unused)
478681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
478781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return 0;
478881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
478981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
479081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// deleteTrackName_l() must be called with ThreadBase::mLock held
47910f11b51a57bc9062c4fe8af73747319cedabc5d6Glenn Kastenvoid AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
479281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
479381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
479481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
47951035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent// checkForNewParameter_l() must be called with ThreadBase::mLock held
47961035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurentbool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
47971035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                                                              status_t& status)
479881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
479981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    bool reconfig = false;
480081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
48011035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    status = NO_ERROR;
48021035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent
48031035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    AudioParameter param = AudioParameter(keyValuePair);
48041035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    int value;
48051035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
48061035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        // forward device change to effects that have requested to be
48071035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        // aware of attached audio device.
48081035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        if (value != AUDIO_DEVICE_NONE) {
48091035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            mOutDevice = value;
48101035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            for (size_t i = 0; i < mEffectChains.size(); i++) {
48111035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                mEffectChains[i]->setDevice_l(mOutDevice);
4812c125f38cd0ae35409a01b98a99e483550daa1313Glenn Kasten            }
4813c125f38cd0ae35409a01b98a99e483550daa1313Glenn Kasten        }
48141035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    }
48151035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
48161035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        // do not accept frame count changes if tracks are open as the track buffer
48171035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        // size depends on frame count and correct behavior would not be garantied
48181035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        // if frame count is changed after track creation
48191035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        if (!mTracks.isEmpty()) {
48201035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            status = INVALID_OPERATION;
48211035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        } else {
48221035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            reconfig = true;
482381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
48241035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    }
48251035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    if (status == NO_ERROR) {
48261035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
48271035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                                                keyValuePair.string());
48281035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        if (!mStandby && status == INVALID_OPERATION) {
4829062e67a26e0553dd142be622821f493df541f0c6Phil Burk            mOutput->standby();
48301035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            mStandby = true;
48311035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            mBytesWritten = 0;
483281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
48331035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                                                   keyValuePair.string());
48341035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        }
48351035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        if (status == NO_ERROR && reconfig) {
48361035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            readOutputParameters_l();
483773e26b661af50be2c0a4ff6c9ac85f7347a8b235Eric Laurent            sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
483881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
483981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
48401035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent
484181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return reconfig;
484281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
484381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
484481784c37c61b09289654b979567a42bf73cd2b12Eric Laurentuint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
484581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
484681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    uint32_t time;
484781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (audio_is_linear_pcm(mFormat)) {
484881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        time = PlaybackThread::activeSleepTimeUs();
484981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    } else {
485081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        time = 10000;
485181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
485281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return time;
485381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
485481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
485581784c37c61b09289654b979567a42bf73cd2b12Eric Laurentuint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
485681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
485781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    uint32_t time;
485881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (audio_is_linear_pcm(mFormat)) {
485981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
486081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    } else {
486181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        time = 10000;
486281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
486381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return time;
486481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
486581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
486681784c37c61b09289654b979567a42bf73cd2b12Eric Laurentuint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
486781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
486881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    uint32_t time;
486981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (audio_is_linear_pcm(mFormat)) {
487081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
487181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    } else {
487281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        time = 10000;
487381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
487481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return time;
487581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
487681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
487781784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::DirectOutputThread::cacheParameters_l()
487881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
487981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    PlaybackThread::cacheParameters_l();
488081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
488181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // use shorter standby delay as on normal output to release
488281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // hardware resources as soon as possible
4883b369cafd67beb63dd0278dba543f519956208a7fEric Laurent    // no delay on outputs with HW A/V sync
4884b369cafd67beb63dd0278dba543f519956208a7fEric Laurent    if (usesHwAvSync()) {
4885ad9cb8b88e4f8face23f01d8dc89fa769dacb50fEric Laurent        mStandbyDelayNs = 0;
48865cff403679fc44c8293de81aed31c459c6129243Eric Laurent    } else if ((mType == OFFLOAD) && !audio_is_linear_pcm(mFormat)) {
4887ad9cb8b88e4f8face23f01d8dc89fa769dacb50fEric Laurent        mStandbyDelayNs = kOffloadStandbyDelayNs;
48885cff403679fc44c8293de81aed31c459c6129243Eric Laurent    } else {
4889ad9cb8b88e4f8face23f01d8dc89fa769dacb50fEric Laurent        mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
4890972a173d7d1de1a3b5a617aae3e2abb6e05ae02dEric Laurent    }
489181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
489281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
4893e659ef420dae0caae84ab78f9df8952acb9ad3a0Eric Laurentvoid AudioFlinger::DirectOutputThread::flushHw_l()
4894e659ef420dae0caae84ab78f9df8952acb9ad3a0Eric Laurent{
4895062e67a26e0553dd142be622821f493df541f0c6Phil Burk    mOutput->flush();
4896d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    mHwPaused = false;
489743b4dcc660e6da96285e4672ae371070ab845401Phil Burk    mFlushPending = false;
4898e659ef420dae0caae84ab78f9df8952acb9ad3a0Eric Laurent}
4899e659ef420dae0caae84ab78f9df8952acb9ad3a0Eric Laurent
490081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// ----------------------------------------------------------------------------
490181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
4902bfb1b832079bbb9426f72f3863199a54aefd02daEric LaurentAudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
49034de95592980dba88a35b3dc8f3fd045588387a4fEric Laurent        const wp<AudioFlinger::PlaybackThread>& playbackThread)
4904bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    :   Thread(false /*canCallJava*/),
49054de95592980dba88a35b3dc8f3fd045588387a4fEric Laurent        mPlaybackThread(playbackThread),
49063b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent        mWriteAckSequence(0),
49073b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent        mDrainSequence(0)
4908bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent{
4909bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent}
4910bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
4911bfb1b832079bbb9426f72f3863199a54aefd02daEric LaurentAudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4912bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent{
4913bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent}
4914bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
4915bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurentvoid AudioFlinger::AsyncCallbackThread::onFirstRef()
4916bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent{
4917bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4918bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent}
4919bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
4920bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurentbool AudioFlinger::AsyncCallbackThread::threadLoop()
4921bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent{
4922bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    while (!exitPending()) {
49233b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent        uint32_t writeAckSequence;
49243b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent        uint32_t drainSequence;
4925bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
4926bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        {
4927bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            Mutex::Autolock _l(mLock);
492824a325d6f8c4bbf9330e6ce0c769d46e04266ffcHaynes Mathew George            while (!((mWriteAckSequence & 1) ||
492924a325d6f8c4bbf9330e6ce0c769d46e04266ffcHaynes Mathew George                     (mDrainSequence & 1) ||
493024a325d6f8c4bbf9330e6ce0c769d46e04266ffcHaynes Mathew George                     exitPending())) {
493124a325d6f8c4bbf9330e6ce0c769d46e04266ffcHaynes Mathew George                mWaitWorkCV.wait(mLock);
493224a325d6f8c4bbf9330e6ce0c769d46e04266ffcHaynes Mathew George            }
493324a325d6f8c4bbf9330e6ce0c769d46e04266ffcHaynes Mathew George
4934bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            if (exitPending()) {
4935bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                break;
4936bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            }
49373b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent            ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
49383b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent                  mWriteAckSequence, mDrainSequence);
49393b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent            writeAckSequence = mWriteAckSequence;
49403b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent            mWriteAckSequence &= ~1;
49413b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent            drainSequence = mDrainSequence;
49423b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent            mDrainSequence &= ~1;
4943bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        }
4944bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        {
49454de95592980dba88a35b3dc8f3fd045588387a4fEric Laurent            sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
49464de95592980dba88a35b3dc8f3fd045588387a4fEric Laurent            if (playbackThread != 0) {
49473b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent                if (writeAckSequence & 1) {
49484de95592980dba88a35b3dc8f3fd045588387a4fEric Laurent                    playbackThread->resetWriteBlocked(writeAckSequence >> 1);
4949bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                }
49503b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent                if (drainSequence & 1) {
49514de95592980dba88a35b3dc8f3fd045588387a4fEric Laurent                    playbackThread->resetDraining(drainSequence >> 1);
4952bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                }
4953bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            }
4954bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        }
4955bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    }
4956bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    return false;
4957bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent}
4958bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
4959bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurentvoid AudioFlinger::AsyncCallbackThread::exit()
4960bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent{
4961bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    ALOGV("AsyncCallbackThread::exit");
4962bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    Mutex::Autolock _l(mLock);
4963bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    requestExit();
4964bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    mWaitWorkCV.broadcast();
4965bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent}
4966bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
49673b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurentvoid AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
4968bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent{
4969bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    Mutex::Autolock _l(mLock);
49703b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent    // bit 0 is cleared
49713b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent    mWriteAckSequence = sequence << 1;
49723b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent}
49733b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent
49743b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurentvoid AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
49753b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent{
49763b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent    Mutex::Autolock _l(mLock);
49773b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent    // ignore unexpected callbacks
49783b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent    if (mWriteAckSequence & 2) {
49793b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent        mWriteAckSequence |= 1;
4980bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        mWaitWorkCV.signal();
4981bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    }
4982bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent}
4983bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
49843b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurentvoid AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
49853b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent{
49863b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent    Mutex::Autolock _l(mLock);
49873b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent    // bit 0 is cleared
49883b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent    mDrainSequence = sequence << 1;
49893b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent}
49903b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent
49913b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurentvoid AudioFlinger::AsyncCallbackThread::resetDraining()
4992bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent{
4993bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    Mutex::Autolock _l(mLock);
49943b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent    // ignore unexpected callbacks
49953b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent    if (mDrainSequence & 2) {
49963b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent        mDrainSequence |= 1;
4997bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        mWaitWorkCV.signal();
4998bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    }
4999bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent}
5000bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
5001bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
5002bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent// ----------------------------------------------------------------------------
5003bfb1b832079bbb9426f72f3863199a54aefd02daEric LaurentAudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
500472e3f39146fce4686bd96f11057c051bea376dfbEric Laurent        AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
500572e3f39146fce4686bd96f11057c051bea376dfbEric Laurent    :   DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
5006d7e59228caad3867794d847f6bf163c6495e9506Eric Laurent        mPausedBytesRemaining(0)
5007bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent{
5008fd4779740ec3e9e865d5514464df26d015354388Eric Laurent    //FIXME: mStandby should be set to true by ThreadBase constructor
5009fd4779740ec3e9e865d5514464df26d015354388Eric Laurent    mStandby = true;
5010bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent}
5011bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
5012bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurentvoid AudioFlinger::OffloadThread::threadLoop_exit()
5013bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent{
5014bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    if (mFlushPending || mHwPaused) {
5015bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        // If a flush is pending or track was paused, just discard buffered data
5016bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        flushHw_l();
5017bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    } else {
5018bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        mMixerStatus = MIXER_DRAIN_ALL;
5019bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        threadLoop_drain();
5020bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    }
502156604aa3a56dc8e15532597a0a74b3c7b165e006Uday Gupta    if (mUseAsyncWrite) {
502256604aa3a56dc8e15532597a0a74b3c7b165e006Uday Gupta        ALOG_ASSERT(mCallbackThread != 0);
502356604aa3a56dc8e15532597a0a74b3c7b165e006Uday Gupta        mCallbackThread->exit();
502456604aa3a56dc8e15532597a0a74b3c7b165e006Uday Gupta    }
5025bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    PlaybackThread::threadLoop_exit();
5026bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent}
5027bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
5028bfb1b832079bbb9426f72f3863199a54aefd02daEric LaurentAudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5029bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    Vector< sp<Track> > *tracksToRemove
5030bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent)
5031bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent{
5032bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    size_t count = mActiveTracks.size();
5033bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
5034bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    mixer_state mixerStatus = MIXER_IDLE;
5035972a173d7d1de1a3b5a617aae3e2abb6e05ae02dEric Laurent    bool doHwPause = false;
5036972a173d7d1de1a3b5a617aae3e2abb6e05ae02dEric Laurent    bool doHwResume = false;
5037972a173d7d1de1a3b5a617aae3e2abb6e05ae02dEric Laurent
5038ede6c3b8b1147bc425f7b923882f559a513fe23bEric Laurent    ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
5039ede6c3b8b1147bc425f7b923882f559a513fe23bEric Laurent
5040bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    // find out which tracks need to be processed
5041bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    for (size_t i = 0; i < count; i++) {
5042bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        sp<Track> t = mActiveTracks[i].promote();
5043bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        // The track died recently
5044bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        if (t == 0) {
5045bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            continue;
5046bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        }
5047bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        Track* const track = t.get();
5048bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        audio_track_cblk_t* cblk = track->cblk();
5049fd4779740ec3e9e865d5514464df26d015354388Eric Laurent        // Only consider last track started for volume and mixer state control.
5050fd4779740ec3e9e865d5514464df26d015354388Eric Laurent        // In theory an older track could underrun and restart after the new one starts
5051fd4779740ec3e9e865d5514464df26d015354388Eric Laurent        // but as we only care about the transition phase between two tracks on a
5052fd4779740ec3e9e865d5514464df26d015354388Eric Laurent        // direct output, it is not a problem to ignore the underrun case.
5053fd4779740ec3e9e865d5514464df26d015354388Eric Laurent        sp<Track> l = mLatestActiveTrack.promote();
5054fd4779740ec3e9e865d5514464df26d015354388Eric Laurent        bool last = l.get() == track;
5055fd4779740ec3e9e865d5514464df26d015354388Eric Laurent
50567844f679be8d94c5cdf017f53754cb68ee2f00daHaynes Mathew George        if (track->isInvalid()) {
50577844f679be8d94c5cdf017f53754cb68ee2f00daHaynes Mathew George            ALOGW("An invalidated track shouldn't be in active list");
50587844f679be8d94c5cdf017f53754cb68ee2f00daHaynes Mathew George            tracksToRemove->add(track);
50597844f679be8d94c5cdf017f53754cb68ee2f00daHaynes Mathew George            continue;
50607844f679be8d94c5cdf017f53754cb68ee2f00daHaynes Mathew George        }
50617844f679be8d94c5cdf017f53754cb68ee2f00daHaynes Mathew George
50627844f679be8d94c5cdf017f53754cb68ee2f00daHaynes Mathew George        if (track->mState == TrackBase::IDLE) {
50637844f679be8d94c5cdf017f53754cb68ee2f00daHaynes Mathew George            ALOGW("An idle track shouldn't be in active list");
50647844f679be8d94c5cdf017f53754cb68ee2f00daHaynes Mathew George            continue;
50657844f679be8d94c5cdf017f53754cb68ee2f00daHaynes Mathew George        }
50667844f679be8d94c5cdf017f53754cb68ee2f00daHaynes Mathew George
5067bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        if (track->isPausing()) {
5068bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            track->setPaused();
5069bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            if (last) {
50705cff403679fc44c8293de81aed31c459c6129243Eric Laurent                if (mHwSupportsPause && !mHwPaused) {
5071972a173d7d1de1a3b5a617aae3e2abb6e05ae02dEric Laurent                    doHwPause = true;
5072bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                    mHwPaused = true;
5073bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                }
5074bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                // If we were part way through writing the mixbuffer to
5075bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                // the HAL we must save this until we resume
5076bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                // BUG - this will be wrong if a different track is made active,
5077bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                // in that case we want to discard the pending data in the
5078bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                // mixbuffer and tell the client to present it again when the
5079bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                // track is resumed
5080bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                mPausedWriteLength = mCurrentWriteLength;
5081bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                mPausedBytesRemaining = mBytesRemaining;
5082bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                mBytesRemaining = 0;    // stop writing
5083bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            }
5084bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            tracksToRemove->add(track);
50857844f679be8d94c5cdf017f53754cb68ee2f00daHaynes Mathew George        } else if (track->isFlushPending()) {
50867844f679be8d94c5cdf017f53754cb68ee2f00daHaynes Mathew George            track->flushAck();
50877844f679be8d94c5cdf017f53754cb68ee2f00daHaynes Mathew George            if (last) {
50887844f679be8d94c5cdf017f53754cb68ee2f00daHaynes Mathew George                mFlushPending = true;
50897844f679be8d94c5cdf017f53754cb68ee2f00daHaynes Mathew George            }
50902d3ca68363f723fbe269d3ce52dab4985dfc7154Haynes Mathew George        } else if (track->isResumePending()){
50912d3ca68363f723fbe269d3ce52dab4985dfc7154Haynes Mathew George            track->resumeAck();
50922d3ca68363f723fbe269d3ce52dab4985dfc7154Haynes Mathew George            if (last) {
50932d3ca68363f723fbe269d3ce52dab4985dfc7154Haynes Mathew George                if (mPausedBytesRemaining) {
50942d3ca68363f723fbe269d3ce52dab4985dfc7154Haynes Mathew George                    // Need to continue write that was interrupted
50952d3ca68363f723fbe269d3ce52dab4985dfc7154Haynes Mathew George                    mCurrentWriteLength = mPausedWriteLength;
50962d3ca68363f723fbe269d3ce52dab4985dfc7154Haynes Mathew George                    mBytesRemaining = mPausedBytesRemaining;
50972d3ca68363f723fbe269d3ce52dab4985dfc7154Haynes Mathew George                    mPausedBytesRemaining = 0;
50982d3ca68363f723fbe269d3ce52dab4985dfc7154Haynes Mathew George                }
50992d3ca68363f723fbe269d3ce52dab4985dfc7154Haynes Mathew George                if (mHwPaused) {
51002d3ca68363f723fbe269d3ce52dab4985dfc7154Haynes Mathew George                    doHwResume = true;
51012d3ca68363f723fbe269d3ce52dab4985dfc7154Haynes Mathew George                    mHwPaused = false;
51022d3ca68363f723fbe269d3ce52dab4985dfc7154Haynes Mathew George                    // threadLoop_mix() will handle the case that we need to
51032d3ca68363f723fbe269d3ce52dab4985dfc7154Haynes Mathew George                    // resume an interrupted write
51042d3ca68363f723fbe269d3ce52dab4985dfc7154Haynes Mathew George                }
51052d3ca68363f723fbe269d3ce52dab4985dfc7154Haynes Mathew George                // enable write to audio HAL
5106ad9cb8b88e4f8face23f01d8dc89fa769dacb50fEric Laurent                mSleepTimeUs = 0;
51072d3ca68363f723fbe269d3ce52dab4985dfc7154Haynes Mathew George
51082d3ca68363f723fbe269d3ce52dab4985dfc7154Haynes Mathew George                // Do not handle new data in this iteration even if track->framesReady()
51092d3ca68363f723fbe269d3ce52dab4985dfc7154Haynes Mathew George                mixerStatus = MIXER_TRACKS_ENABLED;
51102d3ca68363f723fbe269d3ce52dab4985dfc7154Haynes Mathew George            }
51112d3ca68363f723fbe269d3ce52dab4985dfc7154Haynes Mathew George        }  else if (track->framesReady() && track->isReady() &&
51123b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent                !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
5113f20e1d8df84c5fbeeace0052d100982ae39bb7a4Glenn Kasten            ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
5114bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            if (track->mFillingUpStatus == Track::FS_FILLED) {
5115bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                track->mFillingUpStatus = Track::FS_ACTIVE;
51161abbdb4429479975718421c4fef3f79ce7c820e3Eric Laurent                // make sure processVolume_l() will apply new volume even if 0
51171abbdb4429479975718421c4fef3f79ce7c820e3Eric Laurent                mLeftVolFloat = mRightVolFloat = -1.0;
5118bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            }
5119bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
5120bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            if (last) {
5121d7e59228caad3867794d847f6bf163c6495e9506Eric Laurent                sp<Track> previousTrack = mPreviousTrack.promote();
5122d7e59228caad3867794d847f6bf163c6495e9506Eric Laurent                if (previousTrack != 0) {
5123d7e59228caad3867794d847f6bf163c6495e9506Eric Laurent                    if (track != previousTrack.get()) {
51249da3d9573a18ffe08365557c706cf52f09118d1cEric Laurent                        // Flush any data still being written from last track
51259da3d9573a18ffe08365557c706cf52f09118d1cEric Laurent                        mBytesRemaining = 0;
51269da3d9573a18ffe08365557c706cf52f09118d1cEric Laurent                        if (mPausedBytesRemaining) {
51279da3d9573a18ffe08365557c706cf52f09118d1cEric Laurent                            // Last track was paused so we also need to flush saved
51289da3d9573a18ffe08365557c706cf52f09118d1cEric Laurent                            // mixbuffer state and invalidate track so that it will
51299da3d9573a18ffe08365557c706cf52f09118d1cEric Laurent                            // re-submit that unwritten data when it is next resumed
51309da3d9573a18ffe08365557c706cf52f09118d1cEric Laurent                            mPausedBytesRemaining = 0;
51319da3d9573a18ffe08365557c706cf52f09118d1cEric Laurent                            // Invalidate is a bit drastic - would be more efficient
51329da3d9573a18ffe08365557c706cf52f09118d1cEric Laurent                            // to have a flag to tell client that some of the
51339da3d9573a18ffe08365557c706cf52f09118d1cEric Laurent                            // previously written data was lost
5134d7e59228caad3867794d847f6bf163c6495e9506Eric Laurent                            previousTrack->invalidate();
51359da3d9573a18ffe08365557c706cf52f09118d1cEric Laurent                        }
51369da3d9573a18ffe08365557c706cf52f09118d1cEric Laurent                        // flush data already sent to the DSP if changing audio session as audio
51379da3d9573a18ffe08365557c706cf52f09118d1cEric Laurent                        // comes from a different source. Also invalidate previous track to force a
51389da3d9573a18ffe08365557c706cf52f09118d1cEric Laurent                        // seek when resuming.
5139d7e59228caad3867794d847f6bf163c6495e9506Eric Laurent                        if (previousTrack->sessionId() != track->sessionId()) {
5140d7e59228caad3867794d847f6bf163c6495e9506Eric Laurent                            previousTrack->invalidate();
51419da3d9573a18ffe08365557c706cf52f09118d1cEric Laurent                        }
51429da3d9573a18ffe08365557c706cf52f09118d1cEric Laurent                    }
51439da3d9573a18ffe08365557c706cf52f09118d1cEric Laurent                }
51449da3d9573a18ffe08365557c706cf52f09118d1cEric Laurent                mPreviousTrack = track;
5145bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                // reset retry count
5146bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                track->mRetryCount = kMaxTrackRetriesOffload;
5147bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                mActiveTrack = t;
5148bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                mixerStatus = MIXER_TRACKS_READY;
5149bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            }
5150bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        } else {
5151f20e1d8df84c5fbeeace0052d100982ae39bb7a4Glenn Kasten            ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
5152bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            if (track->isStopping_1()) {
5153bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                // Hardware buffer can hold a large amount of audio so we must
5154bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                // wait for all current track's data to drain before we say
5155bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                // that the track is stopped.
5156bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                if (mBytesRemaining == 0) {
5157bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                    // Only start draining when all data in mixbuffer
5158bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                    // has been written
5159bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                    ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5160bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                    track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
51616a51d7ed7062536ccc892c8850a34ed55cbc8d5cEric Laurent                    // do not drain if no data was ever sent to HAL (mStandby == true)
51626a51d7ed7062536ccc892c8850a34ed55cbc8d5cEric Laurent                    if (last && !mStandby) {
51631b9f9b134e732a48198e51f16424f330cbf03143Eric Laurent                        // do not modify drain sequence if we are already draining. This happens
51641b9f9b134e732a48198e51f16424f330cbf03143Eric Laurent                        // when resuming from pause after drain.
51651b9f9b134e732a48198e51f16424f330cbf03143Eric Laurent                        if ((mDrainSequence & 1) == 0) {
5166ad9cb8b88e4f8face23f01d8dc89fa769dacb50fEric Laurent                            mSleepTimeUs = 0;
5167ad9cb8b88e4f8face23f01d8dc89fa769dacb50fEric Laurent                            mStandbyTimeNs = systemTime() + mStandbyDelayNs;
51681b9f9b134e732a48198e51f16424f330cbf03143Eric Laurent                            mixerStatus = MIXER_DRAIN_TRACK;
51691b9f9b134e732a48198e51f16424f330cbf03143Eric Laurent                            mDrainSequence += 2;
51701b9f9b134e732a48198e51f16424f330cbf03143Eric Laurent                        }
5171bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                        if (mHwPaused) {
5172bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                            // It is possible to move from PAUSED to STOPPING_1 without
5173bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                            // a resume so we must ensure hardware is running
51741b9f9b134e732a48198e51f16424f330cbf03143Eric Laurent                            doHwResume = true;
5175bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                            mHwPaused = false;
5176bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                        }
5177bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                    }
5178bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                }
5179bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            } else if (track->isStopping_2()) {
51806a51d7ed7062536ccc892c8850a34ed55cbc8d5cEric Laurent                // Drain has completed or we are in standby, signal presentation complete
51816a51d7ed7062536ccc892c8850a34ed55cbc8d5cEric Laurent                if (!(mDrainSequence & 1) || !last || mStandby) {
5182bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                    track->mState = TrackBase::STOPPED;
5183bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                    size_t audioHALFrames =
5184bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                            (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
5185bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                    size_t framesWritten =
5186062e67a26e0553dd142be622821f493df541f0c6Phil Burk                            mBytesWritten / mOutput->getFrameSize();
5187bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                    track->presentationComplete(framesWritten, audioHALFrames);
5188bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                    track->reset();
5189bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                    tracksToRemove->add(track);
5190bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                }
5191bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            } else {
5192bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                // No buffers for this track. Give it a few chances to
5193bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                // fill a buffer, then remove it from active list.
5194bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                if (--(track->mRetryCount) <= 0) {
5195bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                    ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5196bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                          track->name());
5197bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                    tracksToRemove->add(track);
5198a23f17ac334ff20a11ee63dd177cb1080e44c483Eric Laurent                    // indicate to client process that the track was disabled because of underrun;
5199a23f17ac334ff20a11ee63dd177cb1080e44c483Eric Laurent                    // it will then automatically call start() when data is available
5200a23f17ac334ff20a11ee63dd177cb1080e44c483Eric Laurent                    android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
5201bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                } else if (last){
5202bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                    mixerStatus = MIXER_TRACKS_ENABLED;
5203bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                }
5204bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            }
5205bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        }
5206bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        // compute volume for this track
5207bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        processVolume_l(track, last);
5208bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    }
52096bf9ae20b3bd2dbb8f2e89ee167a6785222301cfEric Laurent
5210ea0fadeb5d81ef3cb7f9db458c9033d628bdb86aEric Laurent    // make sure the pause/flush/resume sequence is executed in the right order.
5211ea0fadeb5d81ef3cb7f9db458c9033d628bdb86aEric Laurent    // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5212ea0fadeb5d81ef3cb7f9db458c9033d628bdb86aEric Laurent    // before flush and then resume HW. This can happen in case of pause/flush/resume
5213ea0fadeb5d81ef3cb7f9db458c9033d628bdb86aEric Laurent    // if resume is received before pause is executed.
5214fd4779740ec3e9e865d5514464df26d015354388Eric Laurent    if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
5215972a173d7d1de1a3b5a617aae3e2abb6e05ae02dEric Laurent        mOutput->stream->pause(mOutput->stream);
5216972a173d7d1de1a3b5a617aae3e2abb6e05ae02dEric Laurent    }
52176bf9ae20b3bd2dbb8f2e89ee167a6785222301cfEric Laurent    if (mFlushPending) {
52186bf9ae20b3bd2dbb8f2e89ee167a6785222301cfEric Laurent        flushHw_l();
52196bf9ae20b3bd2dbb8f2e89ee167a6785222301cfEric Laurent    }
5220fd4779740ec3e9e865d5514464df26d015354388Eric Laurent    if (!mStandby && doHwResume) {
5221972a173d7d1de1a3b5a617aae3e2abb6e05ae02dEric Laurent        mOutput->stream->resume(mOutput->stream);
5222972a173d7d1de1a3b5a617aae3e2abb6e05ae02dEric Laurent    }
52236bf9ae20b3bd2dbb8f2e89ee167a6785222301cfEric Laurent
5224bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    // remove all the tracks that need to be...
5225bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    removeTracks_l(*tracksToRemove);
5226bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
5227bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    return mixerStatus;
5228bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent}
5229bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
5230bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent// must be called with thread mutex locked
5231bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurentbool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5232bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent{
52333b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent    ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
52343b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent          mWriteAckSequence, mDrainSequence);
52353b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent    if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
5236bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        return true;
5237bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    }
5238bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    return false;
5239bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent}
5240bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
5241bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurentbool AudioFlinger::OffloadThread::waitingAsyncCallback()
5242bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent{
5243bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    Mutex::Autolock _l(mLock);
5244bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    return waitingAsyncCallback_l();
5245bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent}
5246bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
5247bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurentvoid AudioFlinger::OffloadThread::flushHw_l()
5248bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent{
5249e659ef420dae0caae84ab78f9df8952acb9ad3a0Eric Laurent    DirectOutputThread::flushHw_l();
5250bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    // Flush anything still waiting in the mixbuffer
5251bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    mCurrentWriteLength = 0;
5252bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    mBytesRemaining = 0;
5253bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    mPausedWriteLength = 0;
5254bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    mPausedBytesRemaining = 0;
52550f02f265123b7ef2fd6ac09ff70cde26eb5559adHaynes Mathew George
5256bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    if (mUseAsyncWrite) {
52573b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent        // discard any pending drain or write ack by incrementing sequence
52583b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent        mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
52593b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent        mDrainSequence = (mDrainSequence + 2) & ~1;
5260bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        ALOG_ASSERT(mCallbackThread != 0);
52613b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent        mCallbackThread->setWriteBlocked(mWriteAckSequence);
52623b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent        mCallbackThread->setDraining(mDrainSequence);
5263bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    }
5264bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent}
5265bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
5266bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent// ----------------------------------------------------------------------------
5267bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
526881784c37c61b09289654b979567a42bf73cd2b12Eric LaurentAudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
526972e3f39146fce4686bd96f11057c051bea376dfbEric Laurent        AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
527081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    :   MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
527172e3f39146fce4686bd96f11057c051bea376dfbEric Laurent                    systemReady, DUPLICATING),
527281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mWaitTimeMs(UINT_MAX)
527381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
527481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    addOutputTrack(mainThread);
527581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
527681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
527781784c37c61b09289654b979567a42bf73cd2b12Eric LaurentAudioFlinger::DuplicatingThread::~DuplicatingThread()
527881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
527981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    for (size_t i = 0; i < mOutputTracks.size(); i++) {
528081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mOutputTracks[i]->destroy();
528181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
528281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
528381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
528481784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::DuplicatingThread::threadLoop_mix()
528581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
528681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // mix buffers...
528781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (outputsReady(outputTracks)) {
528881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
528981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    } else {
529002b5708776ba2a9b4ff8c09008483aef7dbe38c7Eric Laurent        if (mMixerBufferValid) {
529102b5708776ba2a9b4ff8c09008483aef7dbe38c7Eric Laurent            memset(mMixerBuffer, 0, mMixerBufferSize);
529202b5708776ba2a9b4ff8c09008483aef7dbe38c7Eric Laurent        } else {
529302b5708776ba2a9b4ff8c09008483aef7dbe38c7Eric Laurent            memset(mSinkBuffer, 0, mSinkBufferSize);
529402b5708776ba2a9b4ff8c09008483aef7dbe38c7Eric Laurent        }
529581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
5296ad9cb8b88e4f8face23f01d8dc89fa769dacb50fEric Laurent    mSleepTimeUs = 0;
529781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    writeFrames = mNormalFrameCount;
529825c2dac12114699e90deb1c579cadebce7b91a97Andy Hung    mCurrentWriteLength = mSinkBufferSize;
5299ad9cb8b88e4f8face23f01d8dc89fa769dacb50fEric Laurent    mStandbyTimeNs = systemTime() + mStandbyDelayNs;
530081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
530181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
530281784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
530381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
5304ad9cb8b88e4f8face23f01d8dc89fa769dacb50fEric Laurent    if (mSleepTimeUs == 0) {
530581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5306ad9cb8b88e4f8face23f01d8dc89fa769dacb50fEric Laurent            mSleepTimeUs = mActiveSleepTimeUs;
530781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        } else {
5308ad9cb8b88e4f8face23f01d8dc89fa769dacb50fEric Laurent            mSleepTimeUs = mIdleSleepTimeUs;
530981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
531081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    } else if (mBytesWritten != 0) {
531181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (mMixerStatus == MIXER_TRACKS_ENABLED) {
531281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            writeFrames = mNormalFrameCount;
531325c2dac12114699e90deb1c579cadebce7b91a97Andy Hung            memset(mSinkBuffer, 0, mSinkBufferSize);
531481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        } else {
531581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // flush remaining overflow buffers in output tracks
531681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            writeFrames = 0;
531781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
5318ad9cb8b88e4f8face23f01d8dc89fa769dacb50fEric Laurent        mSleepTimeUs = 0;
531981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
532081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
532181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
5322bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurentssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
532381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
532481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    for (size_t i = 0; i < outputTracks.size(); i++) {
5325c25b84abdd7ff229d0af663fbf3a37bd9512939dAndy Hung        outputTracks[i]->write(mSinkBuffer, writeFrames);
532681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
53272c3740f01acca69c3e0bcc5e01bb0edc51b6777fEric Laurent    mStandby = false;
532825c2dac12114699e90deb1c579cadebce7b91a97Andy Hung    return (ssize_t)mSinkBufferSize;
532981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
533081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
533181784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::DuplicatingThread::threadLoop_standby()
533281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
533381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // DuplicatingThread implements standby by stopping all tracks
533481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    for (size_t i = 0; i < outputTracks.size(); i++) {
533581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        outputTracks[i]->stop();
533681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
533781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
533881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
533981784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::DuplicatingThread::saveOutputTracks()
534081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
534181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    outputTracks = mOutputTracks;
534281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
534381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
534481784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::DuplicatingThread::clearOutputTracks()
534581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
534681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    outputTracks.clear();
534781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
534881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
534981784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
535081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
535181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
5352c25b84abdd7ff229d0af663fbf3a37bd9512939dAndy Hung    // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5353c25b84abdd7ff229d0af663fbf3a37bd9512939dAndy Hung    // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5354c25b84abdd7ff229d0af663fbf3a37bd9512939dAndy Hung    // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5355c25b84abdd7ff229d0af663fbf3a37bd9512939dAndy Hung    const size_t frameCount =
5356c25b84abdd7ff229d0af663fbf3a37bd9512939dAndy Hung            3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5357c25b84abdd7ff229d0af663fbf3a37bd9512939dAndy Hung    // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5358c25b84abdd7ff229d0af663fbf3a37bd9512939dAndy Hung    // from different OutputTracks and their associated MixerThreads (e.g. one may
5359c25b84abdd7ff229d0af663fbf3a37bd9512939dAndy Hung    // nearly empty and the other may be dropping data).
5360c25b84abdd7ff229d0af663fbf3a37bd9512939dAndy Hung
5361c25b84abdd7ff229d0af663fbf3a37bd9512939dAndy Hung    sp<OutputTrack> outputTrack = new OutputTrack(thread,
536281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                                            this,
536381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                                            mSampleRate,
5364c25b84abdd7ff229d0af663fbf3a37bd9512939dAndy Hung                                            mFormat,
536581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                                            mChannelMask,
5366462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen                                            frameCount,
5367462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen                                            IPCThreadState::self()->getCallingUid());
536881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (outputTrack->cblk() != NULL) {
5369223fd5c9738e9665e495904d37d4632414b68c1eEric Laurent        thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
537081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mOutputTracks.add(outputTrack);
5371c25b84abdd7ff229d0af663fbf3a37bd9512939dAndy Hung        ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
537281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        updateWaitTime_l();
537381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
537481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
537581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
537681784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
537781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
537881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
537981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    for (size_t i = 0; i < mOutputTracks.size(); i++) {
538081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (mOutputTracks[i]->thread() == thread) {
538181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mOutputTracks[i]->destroy();
538281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mOutputTracks.removeAt(i);
538381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            updateWaitTime_l();
5384f6870aefc5e31d4220f3778c4e79ff34a61f48adEric Laurent            if (thread->getOutput() == mOutput) {
5385f6870aefc5e31d4220f3778c4e79ff34a61f48adEric Laurent                mOutput = NULL;
5386f6870aefc5e31d4220f3778c4e79ff34a61f48adEric Laurent            }
538781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            return;
538881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
538981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
5390f6870aefc5e31d4220f3778c4e79ff34a61f48adEric Laurent    ALOGV("removeOutputTrack(): unknown thread: %p", thread);
539181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
539281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
539381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// caller must hold mLock
539481784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::DuplicatingThread::updateWaitTime_l()
539581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
539681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mWaitTimeMs = UINT_MAX;
539781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    for (size_t i = 0; i < mOutputTracks.size(); i++) {
539881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
539981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (strong != 0) {
540081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
540181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if (waitTimeMs < mWaitTimeMs) {
540281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                mWaitTimeMs = waitTimeMs;
540381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
540481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
540581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
540681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
540781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
540881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
540981784c37c61b09289654b979567a42bf73cd2b12Eric Laurentbool AudioFlinger::DuplicatingThread::outputsReady(
541081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        const SortedVector< sp<OutputTrack> > &outputTracks)
541181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
541281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    for (size_t i = 0; i < outputTracks.size(); i++) {
541381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sp<ThreadBase> thread = outputTracks[i]->thread().promote();
541481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (thread == 0) {
541581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
541681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    outputTracks[i].get());
541781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            return false;
541881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
541981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
542081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // see note at standby() declaration
542181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (playbackThread->standby() && !playbackThread->isSuspended()) {
542281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
542381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    thread.get());
542481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            return false;
542581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
542681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
542781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return true;
542881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
542981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
543081784c37c61b09289654b979567a42bf73cd2b12Eric Laurentuint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
543181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
543281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return (mWaitTimeMs * 1000) / 2;
543381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
543481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
543581784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::DuplicatingThread::cacheParameters_l()
543681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
543781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
543881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    updateWaitTime_l();
543981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
544081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    MixerThread::cacheParameters_l();
544181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
544281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
544381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// ----------------------------------------------------------------------------
544481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent//      Record
544581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// ----------------------------------------------------------------------------
544681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
544781784c37c61b09289654b979567a42bf73cd2b12Eric LaurentAudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
544881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                                         AudioStreamIn *input,
544981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                                         audio_io_handle_t id,
5450d3922f72601d82c6fc067a98916fda0bd1291c5fEric Laurent                                         audio_devices_t outDevice,
545172e3f39146fce4686bd96f11057c051bea376dfbEric Laurent                                         audio_devices_t inDevice,
545272e3f39146fce4686bd96f11057c051bea376dfbEric Laurent                                         bool systemReady
545346909e7eb074ce1b95b8a411eb71154f53f84f77Glenn Kasten#ifdef TEE_SINK
545446909e7eb074ce1b95b8a411eb71154f53f84f77Glenn Kasten                                         , const sp<NBAIO_Sink>& teeSink
545546909e7eb074ce1b95b8a411eb71154f53f84f77Glenn Kasten#endif
545646909e7eb074ce1b95b8a411eb71154f53f84f77Glenn Kasten                                         ) :
545772e3f39146fce4686bd96f11057c051bea376dfbEric Laurent    ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
54586dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten    mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
5459deca2ae0a7cf8bc54ff3f30b7dc39bbc78b94c0dGlenn Kasten    // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
54604cc0a6a835c806d200ef83ef31fe5bef327c355cGlenn Kasten    mRsmpInRear(0)
546146909e7eb074ce1b95b8a411eb71154f53f84f77Glenn Kasten#ifdef TEE_SINK
546246909e7eb074ce1b95b8a411eb71154f53f84f77Glenn Kasten    , mTeeSink(teeSink)
546346909e7eb074ce1b95b8a411eb71154f53f84f77Glenn Kasten#endif
5464b880f5e5fc07397ddd09a94ba18bdf4fa62aae00Glenn Kasten    , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5465b880f5e5fc07397ddd09a94ba18bdf4fa62aae00Glenn Kasten            "RecordThreadRO", MemoryHeapBase::READ_ONLY))
54666dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    // mFastCapture below
54676dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    , mFastCaptureFutex(0)
54686dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    // mInputSource
54696dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    // mPipeSink
54706dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    // mPipeSource
54716dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    , mPipeFramesP2(0)
54726dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    // mPipeMemory
54736dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    // mFastCaptureNBLogWriter
54746e6704c06d61bc356e30c164081e5bcffb37920cGlenn Kasten    , mFastTrackAvail(false)
547581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
5476d7dca050c630bddbd73a6623271b34b4290460eeGlenn Kasten    snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5477d7dca050c630bddbd73a6623271b34b4290460eeGlenn Kasten    mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
547881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
5479deca2ae0a7cf8bc54ff3f30b7dc39bbc78b94c0dGlenn Kasten    readInputParameters_l();
54806dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten
54816dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    // create an NBAIO source for the HAL input stream, and negotiate
54826dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    mInputSource = new AudioStreamInSource(input->stream);
54836dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    size_t numCounterOffers = 0;
54846dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
54856dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
54866dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    ALOG_ASSERT(index == 0);
54876dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten
54886dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    // initialize fast capture depending on configuration
54896dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    bool initFastCapture;
54906dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    switch (kUseFastCapture) {
54916dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    case FastCapture_Never:
54926dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        initFastCapture = false;
54936dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        break;
54946dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    case FastCapture_Always:
54956dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        initFastCapture = true;
54966dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        break;
54976dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    case FastCapture_Static:
5498eb9487e10294a4e73977f460f30eeaff503acd21Glenn Kasten        initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
54996dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        break;
55006dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    // case FastCapture_Dynamic:
55016dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    }
55026dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten
55036dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    if (initFastCapture) {
5504d198b85a163330b03e7507c9e8bfeb5f4d958a6cGlenn Kasten        // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
55056dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        NBAIO_Format format = mInputSource->format();
550649d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten        size_t pipeFramesP2 = roundup(mSampleRate / 25);    // double-buffering of 20 ms each
55076dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
55086dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        void *pipeBuffer;
55096dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        const sp<MemoryDealer> roHeap(readOnlyHeap());
55106dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        sp<IMemory> pipeMemory;
55116dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        if ((roHeap == 0) ||
55126dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
55136dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                (pipeBuffer = pipeMemory->pointer()) == NULL) {
55146dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
55156dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            goto failed;
55166dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        }
55176dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        // pipe will be shared directly with fast clients, so clear to avoid leaking old information
55186dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        memset(pipeBuffer, 0, pipeSize);
55196dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
55206dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        const NBAIO_Format offers[1] = {format};
55216dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        size_t numCounterOffers = 0;
55226dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
55236dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        ALOG_ASSERT(index == 0);
55246dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        mPipeSink = pipe;
55256dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        PipeReader *pipeReader = new PipeReader(*pipe);
55266dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        numCounterOffers = 0;
55276dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
55286dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        ALOG_ASSERT(index == 0);
55296dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        mPipeSource = pipeReader;
55306dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        mPipeFramesP2 = pipeFramesP2;
55316dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        mPipeMemory = pipeMemory;
55326dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten
55336dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        // create fast capture
55346dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        mFastCapture = new FastCapture();
55356dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        FastCaptureStateQueue *sq = mFastCapture->sq();
55366dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten#ifdef STATE_QUEUE_DUMP
55376dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        // FIXME
55386dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten#endif
55396dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        FastCaptureState *state = sq->begin();
55406dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        state->mCblk = NULL;
55416dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        state->mInputSource = mInputSource.get();
55426dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        state->mInputSourceGen++;
55436dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        state->mPipeSink = pipe;
55446dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        state->mPipeSinkGen++;
55456dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        state->mFrameCount = mFrameCount;
55466dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        state->mCommand = FastCaptureState::COLD_IDLE;
55476dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        // already done in constructor initialization list
55486dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        //mFastCaptureFutex = 0;
55496dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        state->mColdFutexAddr = &mFastCaptureFutex;
55506dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        state->mColdGen++;
55516dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        state->mDumpState = &mFastCaptureDumpState;
55526dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten#ifdef TEE_SINK
55536dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        // FIXME
55546dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten#endif
55556dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
55566dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        state->mNBLogWriter = mFastCaptureNBLogWriter.get();
55576dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        sq->end();
55586dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
55596dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten
55606dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        // start the fast capture
55616dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
55626dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        pid_t tid = mFastCapture->getTid();
556372e3f39146fce4686bd96f11057c051bea376dfbEric Laurent        sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
55646dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten#ifdef AUDIO_WATCHDOG
55656dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        // FIXME
55666dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten#endif
55676dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten
55686e6704c06d61bc356e30c164081e5bcffb37920cGlenn Kasten        mFastTrackAvail = true;
55696dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    }
55706dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kastenfailed: ;
55716dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten
55726dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    // FIXME mNormalSource
557381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
557481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
557581784c37c61b09289654b979567a42bf73cd2b12Eric LaurentAudioFlinger::RecordThread::~RecordThread()
557681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
55776dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    if (mFastCapture != 0) {
55786dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        FastCaptureStateQueue *sq = mFastCapture->sq();
55796dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        FastCaptureState *state = sq->begin();
55806dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        if (state->mCommand == FastCaptureState::COLD_IDLE) {
55816dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            int32_t old = android_atomic_inc(&mFastCaptureFutex);
55826dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            if (old == -1) {
55836dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
55846dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            }
55856dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        }
55866dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        state->mCommand = FastCaptureState::EXIT;
55876dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        sq->end();
55886dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
55896dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        mFastCapture->join();
55906dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        mFastCapture.clear();
55916dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    }
55926dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
5593481fb67a595f23c5b7f5be84b06db9b84a41a42fGlenn Kasten    mAudioFlinger->unregisterWriter(mNBLogWriter);
55945744661e85981f8a9456bf470e2761235fc026daAndy Hung    free(mRsmpInBuffer);
559581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
559681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
559781784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::RecordThread::onFirstRef()
559881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
5599d7dca050c630bddbd73a6623271b34b4290460eeGlenn Kasten    run(mThreadName, PRIORITY_URGENT_AUDIO);
560081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
560181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
560281784c37c61b09289654b979567a42bf73cd2b12Eric Laurentbool AudioFlinger::RecordThread::threadLoop()
560381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
560481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    nsecs_t lastWarning = 0;
560581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
560681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    inputStandBy();
560781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
5608f10ffec18f930d92e1abe9200d60e746831841a7Glenn Kastenreacquire_wakelock:
5609f10ffec18f930d92e1abe9200d60e746831841a7Glenn Kasten    sp<RecordTrack> activeTrack;
56102b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten    int activeTracksGen;
5611f10ffec18f930d92e1abe9200d60e746831841a7Glenn Kasten    {
5612f10ffec18f930d92e1abe9200d60e746831841a7Glenn Kasten        Mutex::Autolock _l(mLock);
56132b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten        size_t size = mActiveTracks.size();
56142b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten        activeTracksGen = mActiveTracksGen;
56152b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten        if (size > 0) {
56162b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten            // FIXME an arbitrary choice
56172b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten            activeTrack = mActiveTracks[0];
56182b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten            acquireWakeLock_l(activeTrack->uid());
56192b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten            if (size > 1) {
56202b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten                SortedVector<int> tmp;
56212b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten                for (size_t i = 0; i < size; i++) {
56222b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten                    tmp.add(mActiveTracks[i]->uid());
56232b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten                }
56242b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten                updateWakeLockUids_l(tmp);
56252b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten            }
56262b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten        } else {
56272b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten            acquireWakeLock_l(-1);
56282b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten        }
5629f10ffec18f930d92e1abe9200d60e746831841a7Glenn Kasten    }
5630f10ffec18f930d92e1abe9200d60e746831841a7Glenn Kasten
56316dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten    // used to request a deferred sleep, to be executed later while mutex is unlocked
56326dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten    uint32_t sleepUs = 0;
56336dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten
56346dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten    // loop while there is work to do
56354ef0b463a56c19bad9197aa9f90d792090461429Glenn Kasten    for (;;) {
5636c527a7c2b1bfd26e8f3086e1b653d56e521379d9Glenn Kasten        Vector< sp<EffectChain> > effectChains;
56372cfbf88b89854f30b295e8ae26a031edb8d712f8Glenn Kasten
56385edadd46c76c5ff1c3edabf2ea943c2278e82e1cGlenn Kasten        // sleep with mutex unlocked
56396dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        if (sleepUs > 0) {
5640e77540228e1f60b1129a1615d2e43e0bf8015d3cGlenn Kasten            ATRACE_BEGIN("sleep");
56416dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten            usleep(sleepUs);
5642e77540228e1f60b1129a1615d2e43e0bf8015d3cGlenn Kasten            ATRACE_END();
56436dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten            sleepUs = 0;
56445edadd46c76c5ff1c3edabf2ea943c2278e82e1cGlenn Kasten        }
56455edadd46c76c5ff1c3edabf2ea943c2278e82e1cGlenn Kasten
56466dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        // activeTracks accumulates a copy of a subset of mActiveTracks
56476dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        Vector< sp<RecordTrack> > activeTracks;
56486dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten
5649735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten        // reference to the (first and only) active fast track
56506dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        sp<RecordTrack> fastTrack;
56511035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent
5652735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten        // reference to a fast track which is about to be removed
5653735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten        sp<RecordTrack> fastTrackToRemove;
5654735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten
565581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        { // scope for mLock
565681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            Mutex::Autolock _l(mLock);
5657000a4193dd82549192277fd4b9bb571d8a4c262fEric Laurent
5658021cf9634ab09c0753a40b7c9ef4ba603be5c3daEric Laurent            processConfigEvents_l();
5659f10ffec18f930d92e1abe9200d60e746831841a7Glenn Kasten
5660000a4193dd82549192277fd4b9bb571d8a4c262fEric Laurent            // check exitPending here because checkForNewParameters_l() and
5661000a4193dd82549192277fd4b9bb571d8a4c262fEric Laurent            // checkForNewParameters_l() can temporarily release mLock
5662000a4193dd82549192277fd4b9bb571d8a4c262fEric Laurent            if (exitPending()) {
5663000a4193dd82549192277fd4b9bb571d8a4c262fEric Laurent                break;
5664000a4193dd82549192277fd4b9bb571d8a4c262fEric Laurent            }
5665000a4193dd82549192277fd4b9bb571d8a4c262fEric Laurent
56662b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten            // if no active track(s), then standby and release wakelock
56672b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten            size_t size = mActiveTracks.size();
56682b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten            if (size == 0) {
566993e471f620454f7de73d190521568b1e25879767Glenn Kasten                standbyIfNotAlreadyInStandby();
56704ef0b463a56c19bad9197aa9f90d792090461429Glenn Kasten                // exitPending() can't become true here
567181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                releaseWakeLock_l();
567281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                ALOGV("RecordThread: loop stopping");
567381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // go to sleep
567481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                mWaitWorkCV.wait(mLock);
567581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                ALOGV("RecordThread: loop starting");
5676f10ffec18f930d92e1abe9200d60e746831841a7Glenn Kasten                goto reacquire_wakelock;
5677f10ffec18f930d92e1abe9200d60e746831841a7Glenn Kasten            }
5678f10ffec18f930d92e1abe9200d60e746831841a7Glenn Kasten
56792b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten            if (mActiveTracksGen != activeTracksGen) {
56802b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten                activeTracksGen = mActiveTracksGen;
5681f10ffec18f930d92e1abe9200d60e746831841a7Glenn Kasten                SortedVector<int> tmp;
56822b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten                for (size_t i = 0; i < size; i++) {
56832b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten                    tmp.add(mActiveTracks[i]->uid());
56842b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten                }
5685f10ffec18f930d92e1abe9200d60e746831841a7Glenn Kasten                updateWakeLockUids_l(tmp);
568681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
56879e98235a9e9bb870e1c76911e3b4d00386a52c39Glenn Kasten
56886dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten            bool doBroadcast = false;
56896dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten            for (size_t i = 0; i < size; ) {
56909e98235a9e9bb870e1c76911e3b4d00386a52c39Glenn Kasten
56916dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                activeTrack = mActiveTracks[i];
56926dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                if (activeTrack->isTerminated()) {
5693735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten                    if (activeTrack->isFastTrack()) {
5694735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten                        ALOG_ASSERT(fastTrackToRemove == 0);
5695735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten                        fastTrackToRemove = activeTrack;
5696735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten                    }
56976dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    removeTrack_l(activeTrack);
56982b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten                    mActiveTracks.remove(activeTrack);
56992b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten                    mActiveTracksGen++;
57006dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    size--;
57019e98235a9e9bb870e1c76911e3b4d00386a52c39Glenn Kasten                    continue;
57029e98235a9e9bb870e1c76911e3b4d00386a52c39Glenn Kasten                }
57036dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten
57046dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                TrackBase::track_state activeTrackState = activeTrack->mState;
57056dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                switch (activeTrackState) {
57066dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten
57076dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                case TrackBase::PAUSING:
57086dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    mActiveTracks.remove(activeTrack);
57096dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    mActiveTracksGen++;
57106dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    doBroadcast = true;
57116dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    size--;
57126dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    continue;
57136dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten
57146dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                case TrackBase::STARTING_1:
57156dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    sleepUs = 10000;
57166dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    i++;
57176dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    continue;
57186dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten
57196dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                case TrackBase::STARTING_2:
57206dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    doBroadcast = true;
57216dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    mStandby = false;
57229e98235a9e9bb870e1c76911e3b4d00386a52c39Glenn Kasten                    activeTrack->mState = TrackBase::ACTIVE;
57236dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    break;
57246dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten
57256dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                case TrackBase::ACTIVE:
57266dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    break;
57276dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten
57286dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                case TrackBase::IDLE:
57296dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    i++;
57306dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    continue;
57316dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten
57326dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                default:
5733adad3d7d935da176ff24941b4ae9edf7340e9b96Glenn Kasten                    LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
57349e98235a9e9bb870e1c76911e3b4d00386a52c39Glenn Kasten                }
57352d94426cd3302cb1215c92c5f1c4b90c24ceb72bGlenn Kasten
57366dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                activeTracks.add(activeTrack);
57376dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                i++;
57382d94426cd3302cb1215c92c5f1c4b90c24ceb72bGlenn Kasten
57396dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                if (activeTrack->isFastTrack()) {
57406dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                    ALOG_ASSERT(!mFastTrackAvail);
57416dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                    ALOG_ASSERT(fastTrack == 0);
57426dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                    fastTrack = activeTrack;
57436dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                }
57446dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten            }
57456dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten            if (doBroadcast) {
57466dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                mStartStopCond.broadcast();
57476dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten            }
5748d9fc34fb0fcfcc739f868b116edf50c62af19d5eGlenn Kasten
57496dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten            // sleep if there are no active tracks to process
57506dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten            if (activeTracks.size() == 0) {
57516dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                if (sleepUs == 0) {
57526dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    sleepUs = kRecordThreadSleepUs;
57536dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                }
57546dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                continue;
575581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
57566dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten            sleepUs = 0;
57579e98235a9e9bb870e1c76911e3b4d00386a52c39Glenn Kasten
575881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            lockEffectChains_l(effectChains);
575981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
576081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
57616dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
57627165268ffa6c7b6b405b6afad82e2a346500e8eeGlenn Kasten
57636dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        size_t size = effectChains.size();
57646dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        for (size_t i = 0; i < size; i++) {
57651ba19cd7fcdf18ab6efab2a1b831affab9a46157Glenn Kasten            // thread mutex is not locked, but effect chain is locked
57661ba19cd7fcdf18ab6efab2a1b831affab9a46157Glenn Kasten            effectChains[i]->process_l();
57671ba19cd7fcdf18ab6efab2a1b831affab9a46157Glenn Kasten        }
576881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
5769735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten        // Push a new fast capture state if fast capture is not already running, or cblk change
57706dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        if (mFastCapture != 0) {
57716dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            FastCaptureStateQueue *sq = mFastCapture->sq();
57726dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            FastCaptureState *state = sq->begin();
5773735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten            bool didModify = false;
5774735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten            FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
57756dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
57766dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                    (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
57776dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                if (state->mCommand == FastCaptureState::COLD_IDLE) {
57786dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                    int32_t old = android_atomic_inc(&mFastCaptureFutex);
57796dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                    if (old == -1) {
57806dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                        (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
57816dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                    }
57826dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                }
57836dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                state->mCommand = FastCaptureState::READ_WRITE;
57846dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten#if 0   // FIXME
57856dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
5786fbdb2aceab7317aa44bc8f301a93eb49e17b2bceGlenn Kasten                        FastThreadDumpState::kSamplingNforLowRamDevice :
5787fbdb2aceab7317aa44bc8f301a93eb49e17b2bceGlenn Kasten                        FastThreadDumpState::kSamplingN);
57886dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten#endif
5789735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten                didModify = true;
5790735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten            }
5791735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten            audio_track_cblk_t *cblkOld = state->mCblk;
5792735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten            audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
5793735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten            if (cblkNew != cblkOld) {
5794735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten                state->mCblk = cblkNew;
5795735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten                // block until acked if removing a fast track
5796735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten                if (cblkOld != NULL) {
5797735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten                    block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
5798735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten                }
5799735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten                didModify = true;
5800735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten            }
5801735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten            sq->end(didModify);
5802735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten            if (didModify) {
5803735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten                sq->push(block);
58046dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten#if 0
58056dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                if (kUseFastCapture == FastCapture_Dynamic) {
58066dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                    mNormalSource = mPipeSource;
58076dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                }
58086dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten#endif
58096dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            }
58106dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        }
58116dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten
5812735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten        // now run the fast track destructor with thread mutex unlocked
5813735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten        fastTrackToRemove.clear();
5814735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten
58156dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
58166dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        // Only the client(s) that are too slow will overrun. But if even the fastest client is too
58176dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        // slow, then this RecordThread will overrun by not calling HAL read often enough.
58186dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        // If destination is non-contiguous, first read past the nominal end of buffer, then
58196dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        // copy to the right place.  Permitted because mRsmpInBuffer was over-allocated.
58206dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten
58216dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
58226dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        ssize_t framesRead;
58236dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten
58246dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        // If an NBAIO source is present, use it to read the normal capture's data
58256dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        if (mPipeSource != 0) {
58266dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            size_t framesToRead = mBufferSize / mFrameSize;
58275744661e85981f8a9456bf470e2761235fc026daAndy Hung            framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
58286dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                    framesToRead, AudioBufferProvider::kInvalidPTS);
58296dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            if (framesRead == 0) {
58306dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                // since pipe is non-blocking, simulate blocking input
58316dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                sleepUs = (framesToRead * 1000000LL) / mSampleRate;
58326dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            }
58336dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        // otherwise use the HAL / AudioStreamIn directly
58346dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        } else {
58356dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            ssize_t bytesRead = mInput->stream->read(mInput->stream,
58365744661e85981f8a9456bf470e2761235fc026daAndy Hung                    (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize);
58376dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            if (bytesRead < 0) {
58386dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                framesRead = bytesRead;
58396dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            } else {
58406dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                framesRead = bytesRead / mFrameSize;
58416dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            }
58426dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        }
58436dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten
58446dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
58456dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            ALOGE("read failed: framesRead=%d", framesRead);
58466dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten            // Force input into standby so that it tries to recover at next read attempt
58476dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten            inputStandBy();
58486dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten            sleepUs = kRecordThreadSleepUs;
58496dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        }
58506dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        if (framesRead <= 0) {
58513d61bc1ffc8afc8d7be3b0d4205c9b5ba6daf2e8Glenn Kasten            goto unlock;
58526dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        }
58536dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        ALOG_ASSERT(framesRead > 0);
58546dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten
58556dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        if (mTeeSink != 0) {
58565744661e85981f8a9456bf470e2761235fc026daAndy Hung            (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
58576dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        }
58586dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        // If destination is non-contiguous, we now correct for reading past end of buffer.
58593d61bc1ffc8afc8d7be3b0d4205c9b5ba6daf2e8Glenn Kasten        {
58603d61bc1ffc8afc8d7be3b0d4205c9b5ba6daf2e8Glenn Kasten            size_t part1 = mRsmpInFramesP2 - rear;
58613d61bc1ffc8afc8d7be3b0d4205c9b5ba6daf2e8Glenn Kasten            if ((size_t) framesRead > part1) {
58625744661e85981f8a9456bf470e2761235fc026daAndy Hung                memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
58633d61bc1ffc8afc8d7be3b0d4205c9b5ba6daf2e8Glenn Kasten                        (framesRead - part1) * mFrameSize);
58643d61bc1ffc8afc8d7be3b0d4205c9b5ba6daf2e8Glenn Kasten            }
58656dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        }
58666dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        rear = mRsmpInRear += framesRead;
58676dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten
58686dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        size = activeTracks.size();
58696dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        // loop over each active track
58706dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        for (size_t i = 0; i < size; i++) {
58716dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten            activeTrack = activeTracks[i];
58726dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten
58736dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            // skip fast tracks, as those are handled directly by FastCapture
58746dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            if (activeTrack->isFastTrack()) {
58756dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                continue;
58766dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            }
58776dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten
587873c02e4277b399c2ec1555d32b6ad5df23bb83dcAndy Hung            // TODO: This code probably should be moved to RecordTrack.
587997a893eb34f8687485c88eaf15917974a203f20bAndy Hung            // TODO: Update the activeTrack buffer converter in case of reconfigure.
588097a893eb34f8687485c88eaf15917974a203f20bAndy Hung
58816dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten            enum {
58826dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                OVERRUN_UNKNOWN,
58836dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                OVERRUN_TRUE,
58846dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                OVERRUN_FALSE
58856dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten            } overrun = OVERRUN_UNKNOWN;
58866dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten
58876dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten            // loop over getNextBuffer to handle circular sink
58886dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten            for (;;) {
58896dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten
58906dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                activeTrack->mSink.frameCount = ~0;
58916dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
58926dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                size_t framesOut = activeTrack->mSink.frameCount;
58936dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
58946dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten
589573c02e4277b399c2ec1555d32b6ad5df23bb83dcAndy Hung                // check available frames and handle overrun conditions
589673c02e4277b399c2ec1555d32b6ad5df23bb83dcAndy Hung                // if the record track isn't draining fast enough.
589773c02e4277b399c2ec1555d32b6ad5df23bb83dcAndy Hung                bool hasOverrun;
58986dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                size_t framesIn;
589973c02e4277b399c2ec1555d32b6ad5df23bb83dcAndy Hung                activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
590073c02e4277b399c2ec1555d32b6ad5df23bb83dcAndy Hung                if (hasOverrun) {
59016dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    overrun = OVERRUN_TRUE;
59026dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                }
59034cc0a6a835c806d200ef83ef31fe5bef327c355cGlenn Kasten                if (framesOut == 0 || framesIn == 0) {
59044cc0a6a835c806d200ef83ef31fe5bef327c355cGlenn Kasten                    break;
59054cc0a6a835c806d200ef83ef31fe5bef327c355cGlenn Kasten                }
59064cc0a6a835c806d200ef83ef31fe5bef327c355cGlenn Kasten
59076770c6faa3467c92eabc5ec9b23d60eb556a0d03Andy Hung                // Don't allow framesOut to be larger than what is possible with resampling
59086770c6faa3467c92eabc5ec9b23d60eb556a0d03Andy Hung                // from framesIn.
59096770c6faa3467c92eabc5ec9b23d60eb556a0d03Andy Hung                // This isn't strictly necessary but helps limit buffer resizing in
59106770c6faa3467c92eabc5ec9b23d60eb556a0d03Andy Hung                // RecordBufferConverter.  TODO: remove when no longer needed.
59116770c6faa3467c92eabc5ec9b23d60eb556a0d03Andy Hung                framesOut = min(framesOut,
59126770c6faa3467c92eabc5ec9b23d60eb556a0d03Andy Hung                        destinationFramesPossible(
59136770c6faa3467c92eabc5ec9b23d60eb556a0d03Andy Hung                                framesIn, mSampleRate, activeTrack->mSampleRate));
591497a893eb34f8687485c88eaf15917974a203f20bAndy Hung                // process frames from the RecordThread buffer provider to the RecordTrack buffer
591597a893eb34f8687485c88eaf15917974a203f20bAndy Hung                framesOut = activeTrack->mRecordBufferConverter->convert(
591697a893eb34f8687485c88eaf15917974a203f20bAndy Hung                        activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
59178594843c15b4722ced39436fe9e64f3e57e7ace4Glenn Kasten
59186dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
59196dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    overrun = OVERRUN_FALSE;
59201ba19cd7fcdf18ab6efab2a1b831affab9a46157Glenn Kasten                }
592181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
59226dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                if (activeTrack->mFramesToDrop == 0) {
59236dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    if (framesOut > 0) {
59246dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                        activeTrack->mSink.frameCount = framesOut;
59256dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                        activeTrack->releaseBuffer(&activeTrack->mSink);
592681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    }
592781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                } else {
59286dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    // FIXME could do a partial drop of framesOut
59296dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    if (activeTrack->mFramesToDrop > 0) {
59306dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                        activeTrack->mFramesToDrop -= framesOut;
59316dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                        if (activeTrack->mFramesToDrop <= 0) {
593225f4aa83efaa9179e65a20583a6d441de2c3ff3fGlenn Kasten                            activeTrack->clearSyncStartEvent();
59336dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                        }
59346dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    } else {
59356dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                        activeTrack->mFramesToDrop += framesOut;
59366dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                        if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
59376dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                                activeTrack->mSyncStartEvent->isCancelled()) {
59386dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                            ALOGW("Synced record %s, session %d, trigger session %d",
59396dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                                  (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
59406dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                                  activeTrack->sessionId(),
59416dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                                  (activeTrack->mSyncStartEvent != 0) ?
59426dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                                          activeTrack->mSyncStartEvent->triggerSession() : 0);
594325f4aa83efaa9179e65a20583a6d441de2c3ff3fGlenn Kasten                            activeTrack->clearSyncStartEvent();
59446dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                        }
594581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    }
594681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
59476dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten
59486dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                if (framesOut == 0) {
59496dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    break;
59506dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                }
595181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
59526dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten
59536dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten            switch (overrun) {
59546dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten            case OVERRUN_TRUE:
59556dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                // client isn't retrieving buffers fast enough
59566dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                if (!activeTrack->setOverflow()) {
59576dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    nsecs_t now = systemTime();
59586dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    // FIXME should lastWarning per track?
59596dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    if ((now - lastWarning) > kWarningThrottleNs) {
59606dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                        ALOGW("RecordThread: buffer overflow");
59616dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                        lastWarning = now;
59626dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    }
596381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
59646dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                break;
59656dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten            case OVERRUN_FALSE:
59666dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                activeTrack->clearOverflow();
59676dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                break;
59686dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten            case OVERRUN_UNKNOWN:
59696dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                break;
597081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
59716dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten
597281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
59731ba19cd7fcdf18ab6efab2a1b831affab9a46157Glenn Kasten
59743d61bc1ffc8afc8d7be3b0d4205c9b5ba6daf2e8Glenn Kastenunlock:
597581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // enable changes in effect chain
597681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        unlockEffectChains(effectChains);
5977c527a7c2b1bfd26e8f3086e1b653d56e521379d9Glenn Kasten        // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
597881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
597981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
598093e471f620454f7de73d190521568b1e25879767Glenn Kasten    standbyIfNotAlreadyInStandby();
598181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
598281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    {
598381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        Mutex::Autolock _l(mLock);
59849a54bc27876acd5d8be5b1fc3dc46701fe76fbb3Eric Laurent        for (size_t i = 0; i < mTracks.size(); i++) {
59859a54bc27876acd5d8be5b1fc3dc46701fe76fbb3Eric Laurent            sp<RecordTrack> track = mTracks[i];
59869a54bc27876acd5d8be5b1fc3dc46701fe76fbb3Eric Laurent            track->invalidate();
59879a54bc27876acd5d8be5b1fc3dc46701fe76fbb3Eric Laurent        }
59882b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten        mActiveTracks.clear();
59892b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten        mActiveTracksGen++;
599081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mStartStopCond.broadcast();
599181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
599281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
599381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    releaseWakeLock();
599481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
599581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    ALOGV("RecordThread %p exiting", this);
599681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return false;
599781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
599881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
599993e471f620454f7de73d190521568b1e25879767Glenn Kastenvoid AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
600081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
600181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (!mStandby) {
600281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        inputStandBy();
600381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mStandby = true;
600481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
600581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
600681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
600781784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::RecordThread::inputStandBy()
600881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
60096dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    // Idle the fast capture if it's currently running
60106dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    if (mFastCapture != 0) {
60116dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        FastCaptureStateQueue *sq = mFastCapture->sq();
60126dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        FastCaptureState *state = sq->begin();
60136dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        if (!(state->mCommand & FastCaptureState::IDLE)) {
60146dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            state->mCommand = FastCaptureState::COLD_IDLE;
60156dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            state->mColdFutexAddr = &mFastCaptureFutex;
60166dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            state->mColdGen++;
60176dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            mFastCaptureFutex = 0;
60186dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            sq->end();
60196dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
60206dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
60216dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten#if 0
60226dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            if (kUseFastCapture == FastCapture_Dynamic) {
60236dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                // FIXME
60246dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            }
60256dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten#endif
60266dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten#ifdef AUDIO_WATCHDOG
60276dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            // FIXME
60286dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten#endif
60296dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        } else {
60306dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            sq->end(false /*didModify*/);
60316dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        }
60326dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    }
603381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mInput->stream->common.standby(&mInput->stream->common);
603481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
603581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
603605997e21af6c4517f375def6563af4b9ebe95f39Glenn Kasten// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
6037e198c360d5e75a9b2097844c495c10902e7e8500Glenn Kastensp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
603881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        const sp<AudioFlinger::Client>& client,
603981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        uint32_t sampleRate,
604081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        audio_format_t format,
604181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        audio_channel_mask_t channelMask,
604274935e44734c1ec235c2b6677db3e0dbefa5ddb8Glenn Kasten        size_t *pFrameCount,
604381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        int sessionId,
60447df8c0b799d8f52d6386e03313286dbd7d5cdc7cGlenn Kasten        size_t *notificationFrames,
6045462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen        int uid,
6046ddb0ccf3fb6fe8da8c71a6deb30561b821f3c0a2Glenn Kasten        IAudioFlinger::track_flags_t *flags,
604781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        pid_t tid,
604881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        status_t *status)
604981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
605074935e44734c1ec235c2b6677db3e0dbefa5ddb8Glenn Kasten    size_t frameCount = *pFrameCount;
605181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    sp<RecordTrack> track;
605281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    status_t lStatus;
605381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
605490e58b1fefc8caf70b34301a92bc86179580b6fcGlenn Kasten    // client expresses a preference for FAST, but we get the final say
605590e58b1fefc8caf70b34301a92bc86179580b6fcGlenn Kasten    if (*flags & IAudioFlinger::TRACK_FAST) {
605690e58b1fefc8caf70b34301a92bc86179580b6fcGlenn Kasten      if (
6057b7fbf7ecc6b034243ec64f79f3113675b5e3c941Glenn Kasten            // we formerly checked for a callback handler (non-0 tid),
6058b7fbf7ecc6b034243ec64f79f3113675b5e3c941Glenn Kasten            // but that is no longer required for TRANSFER_OBTAIN mode
6059b7fbf7ecc6b034243ec64f79f3113675b5e3c941Glenn Kasten            //
60607410591dad836434c72ddee66680802708b70c10Glenn Kasten            // frame count is not specified, or is exactly the pipe depth
60617410591dad836434c72ddee66680802708b70c10Glenn Kasten            ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
60623a6c90aa0617666d9abc94c02b752d9eb3d64772Glenn Kasten            // PCM data
60633a6c90aa0617666d9abc94c02b752d9eb3d64772Glenn Kasten            audio_is_linear_pcm(format) &&
60646dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            // native format
60656dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            (format == mFormat) &&
60666dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            // native channel mask
60676dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            (channelMask == mChannelMask) &&
60686dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            // native hardware sample rate
606990e58b1fefc8caf70b34301a92bc86179580b6fcGlenn Kasten            (sampleRate == mSampleRate) &&
60703a6c90aa0617666d9abc94c02b752d9eb3d64772Glenn Kasten            // record thread has an associated fast capture
60716dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            hasFastCapture() &&
60726dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            // there are sufficient fast track slots available
60736dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            mFastTrackAvail
607490e58b1fefc8caf70b34301a92bc86179580b6fcGlenn Kasten        ) {
60757410591dad836434c72ddee66680802708b70c10Glenn Kasten        ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u",
607690e58b1fefc8caf70b34301a92bc86179580b6fcGlenn Kasten                frameCount, mFrameCount);
607790e58b1fefc8caf70b34301a92bc86179580b6fcGlenn Kasten      } else {
60787410591dad836434c72ddee66680802708b70c10Glenn Kasten        ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u "
60797410591dad836434c72ddee66680802708b70c10Glenn Kasten                "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
60806dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
60817410591dad836434c72ddee66680802708b70c10Glenn Kasten                frameCount, mFrameCount, mPipeFramesP2,
60827410591dad836434c72ddee66680802708b70c10Glenn Kasten                format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
60837410591dad836434c72ddee66680802708b70c10Glenn Kasten                hasFastCapture(), tid, mFastTrackAvail);
608490e58b1fefc8caf70b34301a92bc86179580b6fcGlenn Kasten        *flags &= ~IAudioFlinger::TRACK_FAST;
60857410591dad836434c72ddee66680802708b70c10Glenn Kasten      }
60867410591dad836434c72ddee66680802708b70c10Glenn Kasten    }
60877410591dad836434c72ddee66680802708b70c10Glenn Kasten
60887410591dad836434c72ddee66680802708b70c10Glenn Kasten    // compute track buffer size in frames, and suggest the notification frame count
60897410591dad836434c72ddee66680802708b70c10Glenn Kasten    if (*flags & IAudioFlinger::TRACK_FAST) {
60907410591dad836434c72ddee66680802708b70c10Glenn Kasten        // fast track: frame count is exactly the pipe depth
60917410591dad836434c72ddee66680802708b70c10Glenn Kasten        frameCount = mPipeFramesP2;
60927410591dad836434c72ddee66680802708b70c10Glenn Kasten        // ignore requested notificationFrames, and always notify exactly once every HAL buffer
60937410591dad836434c72ddee66680802708b70c10Glenn Kasten        *notificationFrames = mFrameCount;
60947410591dad836434c72ddee66680802708b70c10Glenn Kasten    } else {
609549d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten        // not fast track: max notification period is resampled equivalent of one HAL buffer time
609649d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten        //                 or 20 ms if there is a fast capture
609749d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten        // TODO This could be a roundupRatio inline, and const
609849d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten        size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
609949d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten                * sampleRate + mSampleRate - 1) / mSampleRate;
610049d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten        // minimum number of notification periods is at least kMinNotifications,
610149d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten        // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
610249d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten        static const size_t kMinNotifications = 3;
610349d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten        static const uint32_t kMinMs = 30;
610449d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten        // TODO This could be a roundupRatio inline
610549d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten        const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
610649d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten        // TODO This could be a roundupRatio inline
610749d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten        const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
610849d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten                maxNotificationFrames;
610949d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten        const size_t minFrameCount = maxNotificationFrames *
611049d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten                max(kMinNotifications, minNotificationsByMs);
611149d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten        frameCount = max(frameCount, minFrameCount);
611249d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten        if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
611349d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten            *notificationFrames = maxNotificationFrames;
61147410591dad836434c72ddee66680802708b70c10Glenn Kasten        }
611590e58b1fefc8caf70b34301a92bc86179580b6fcGlenn Kasten    }
611674935e44734c1ec235c2b6677db3e0dbefa5ddb8Glenn Kasten    *pFrameCount = frameCount;
611790e58b1fefc8caf70b34301a92bc86179580b6fcGlenn Kasten
611815e5798908ccac14e10c84834eaf08c42931bd06Glenn Kasten    lStatus = initCheck();
611915e5798908ccac14e10c84834eaf08c42931bd06Glenn Kasten    if (lStatus != NO_ERROR) {
612015e5798908ccac14e10c84834eaf08c42931bd06Glenn Kasten        ALOGE("createRecordTrack_l() audio driver not initialized");
612115e5798908ccac14e10c84834eaf08c42931bd06Glenn Kasten        goto Exit;
612215e5798908ccac14e10c84834eaf08c42931bd06Glenn Kasten    }
612381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
612481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    { // scope for mLock
612581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        Mutex::Autolock _l(mLock);
612681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
612781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        track = new RecordTrack(this, client, sampleRate,
612883b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent                      format, channelMask, frameCount, NULL, sessionId, uid,
612983b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent                      *flags, TrackBase::TYPE_DEFAULT);
613081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
6131030033342a6ea17003e6af38a56c7edc6d2ead01Glenn Kasten        lStatus = track->initCheck();
6132030033342a6ea17003e6af38a56c7edc6d2ead01Glenn Kasten        if (lStatus != NO_ERROR) {
613335295078ab59c8c5d143a54d5a55557c3ca62c51Glenn Kasten            ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
613403e9e83c47ab4a518da0a1f36b8f702f59221c95Haynes Mathew George            // track must be cleared from the caller as the caller has the AF lock
613581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            goto Exit;
613681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
613781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mTracks.add(track);
613881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
613981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
614081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
614181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                        mAudioFlinger->btNrecIsOff();
614281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
614381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
614490e58b1fefc8caf70b34301a92bc86179580b6fcGlenn Kasten
614590e58b1fefc8caf70b34301a92bc86179580b6fcGlenn Kasten        if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
614690e58b1fefc8caf70b34301a92bc86179580b6fcGlenn Kasten            pid_t callingPid = IPCThreadState::self()->getCallingPid();
614790e58b1fefc8caf70b34301a92bc86179580b6fcGlenn Kasten            // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
614890e58b1fefc8caf70b34301a92bc86179580b6fcGlenn Kasten            // so ask activity manager to do this on our behalf
614990e58b1fefc8caf70b34301a92bc86179580b6fcGlenn Kasten            sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
615090e58b1fefc8caf70b34301a92bc86179580b6fcGlenn Kasten        }
615181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
615205997e21af6c4517f375def6563af4b9ebe95f39Glenn Kasten
615381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    lStatus = NO_ERROR;
615481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
615581784c37c61b09289654b979567a42bf73cd2b12Eric LaurentExit:
61569156ef3e11b68cc4b6d3cea77f1f63673855a6d1Glenn Kasten    *status = lStatus;
615781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return track;
615881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
615981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
616081784c37c61b09289654b979567a42bf73cd2b12Eric Laurentstatus_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
616181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                                           AudioSystem::sync_event_t event,
616281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                                           int triggerSession)
616381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
616481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
616581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    sp<ThreadBase> strongMe = this;
616681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    status_t status = NO_ERROR;
616781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
616881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (event == AudioSystem::SYNC_EVENT_NONE) {
616925f4aa83efaa9179e65a20583a6d441de2c3ff3fGlenn Kasten        recordTrack->clearSyncStartEvent();
617081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    } else if (event != AudioSystem::SYNC_EVENT_SAME) {
61716dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
617281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                                       triggerSession,
617381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                                       recordTrack->sessionId(),
617481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                                       syncStartEventCallback,
61756dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                                       recordTrack);
617681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // Sync event can be cancelled by the trigger session if the track is not in a
617781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // compatible state in which case we start record immediately
61786dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        if (recordTrack->mSyncStartEvent->isCancelled()) {
617925f4aa83efaa9179e65a20583a6d441de2c3ff3fGlenn Kasten            recordTrack->clearSyncStartEvent();
618081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        } else {
618181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
61826dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten            recordTrack->mFramesToDrop = -
61834cc0a6a835c806d200ef83ef31fe5bef327c355cGlenn Kasten                    ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
618481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
618581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
618681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
618781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    {
618847c2070b2ce8aedb7300c0aad91caccf3c383841Glenn Kasten        // This section is a rendezvous between binder thread executing start() and RecordThread
618981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        AutoMutex lock(mLock);
61906dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        if (mActiveTracks.indexOf(recordTrack) >= 0) {
61916dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten            if (recordTrack->mState == TrackBase::PAUSING) {
61926dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                ALOGV("active record track PAUSING -> ACTIVE");
6193f10ffec18f930d92e1abe9200d60e746831841a7Glenn Kasten                recordTrack->mState = TrackBase::ACTIVE;
61946dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten            } else {
61956dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                ALOGV("active record track state %d", recordTrack->mState);
619681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
619781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            return status;
619881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
619981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
62004cc0a6a835c806d200ef83ef31fe5bef327c355cGlenn Kasten        // TODO consider other ways of handling this, such as changing the state to :STARTING and
62014cc0a6a835c806d200ef83ef31fe5bef327c355cGlenn Kasten        //      adding the track to mActiveTracks after returning from AudioSystem::startInput(),
62024cc0a6a835c806d200ef83ef31fe5bef327c355cGlenn Kasten        //      or using a separate command thread
62036dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        recordTrack->mState = TrackBase::STARTING_1;
62042b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten        mActiveTracks.add(recordTrack);
62052b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten        mActiveTracksGen++;
620683b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent        status_t status = NO_ERROR;
620783b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent        if (recordTrack->isExternalTrack()) {
620883b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent            mLock.unlock();
62094dc680607181e6a76f4e91a39366c4f5dfb7b03eEric Laurent            status = AudioSystem::startInput(mId, (audio_session_t)recordTrack->sessionId());
621083b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent            mLock.lock();
621183b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent            // FIXME should verify that recordTrack is still in mActiveTracks
621283b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent            if (status != NO_ERROR) {
621383b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent                mActiveTracks.remove(recordTrack);
621483b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent                mActiveTracksGen++;
621583b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent                recordTrack->clearSyncStartEvent();
621683b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent                ALOGV("RecordThread::start error %d", status);
621783b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent                return status;
621883b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent            }
621981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
62206dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        // Catch up with current buffer indices if thread is already running.
62216dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        // This is what makes a new client discard all buffered data.  If the track's mRsmpInFront
62226dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        // was initialized to some value closer to the thread's mRsmpInFront, then the track could
62236dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        // see previously buffered data before it called start(), but with greater risk of overrun.
62246dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten
622573c02e4277b399c2ec1555d32b6ad5df23bb83dcAndy Hung        recordTrack->mResamplerBufferProvider->reset();
622697a893eb34f8687485c88eaf15917974a203f20bAndy Hung        // clear any converter state as new data will be discontinuous
622797a893eb34f8687485c88eaf15917974a203f20bAndy Hung        recordTrack->mRecordBufferConverter->reset();
62286dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        recordTrack->mState = TrackBase::STARTING_2;
622981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // signal thread to start
623081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mWaitWorkCV.broadcast();
62312b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten        if (mActiveTracks.indexOf(recordTrack) < 0) {
623281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            ALOGV("Record failed to start");
623381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            status = BAD_VALUE;
623481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            goto startError;
623581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
623681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        return status;
623781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
62387c027248e1a4ccd5b22bc4deafb03e2d87ac8f38Glenn Kasten
623981784c37c61b09289654b979567a42bf73cd2b12Eric LaurentstartError:
624083b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent    if (recordTrack->isExternalTrack()) {
62414dc680607181e6a76f4e91a39366c4f5dfb7b03eEric Laurent        AudioSystem::stopInput(mId, (audio_session_t)recordTrack->sessionId());
624283b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent    }
624325f4aa83efaa9179e65a20583a6d441de2c3ff3fGlenn Kasten    recordTrack->clearSyncStartEvent();
62446dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten    // FIXME I wonder why we do not reset the state here?
624581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return status;
624681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
624781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
624881784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
624981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
625081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    sp<SyncEvent> strongEvent = event.promote();
625181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
625281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (strongEvent != 0) {
62538ea16e4b0a7d398d26887c18675b3899de5d779dEric Laurent        sp<RefBase> ptr = strongEvent->cookie().promote();
62548ea16e4b0a7d398d26887c18675b3899de5d779dEric Laurent        if (ptr != 0) {
62558ea16e4b0a7d398d26887c18675b3899de5d779dEric Laurent            RecordTrack *recordTrack = (RecordTrack *)ptr.get();
62568ea16e4b0a7d398d26887c18675b3899de5d779dEric Laurent            recordTrack->handleSyncStartEvent(strongEvent);
62578ea16e4b0a7d398d26887c18675b3899de5d779dEric Laurent        }
625881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
625981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
626081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
6261a8356f663014e7d4c27869629af83d8bb3441e19Glenn Kastenbool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
626281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    ALOGV("RecordThread::stop");
6263a8356f663014e7d4c27869629af83d8bb3441e19Glenn Kasten    AutoMutex _l(mLock);
62642b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten    if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
626581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        return false;
626681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
626747c2070b2ce8aedb7300c0aad91caccf3c383841Glenn Kasten    // note that threadLoop may still be processing the track at this point [without lock]
626881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    recordTrack->mState = TrackBase::PAUSING;
626981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // do not wait for mStartStopCond if exiting
627081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (exitPending()) {
627181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        return true;
627281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
627347c2070b2ce8aedb7300c0aad91caccf3c383841Glenn Kasten    // FIXME incorrect usage of wait: no explicit predicate or loop
627481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mStartStopCond.wait(mLock);
62752b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten    // if we have been restarted, recordTrack is in mActiveTracks here
62762b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten    if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
627781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        ALOGV("Record stopped OK");
627881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        return true;
627981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
628081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return false;
628181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
628281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
62830f11b51a57bc9062c4fe8af73747319cedabc5d6Glenn Kastenbool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
628481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
628581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return false;
628681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
628781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
62880f11b51a57bc9062c4fe8af73747319cedabc5d6Glenn Kastenstatus_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
628981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
629081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#if 0   // This branch is currently dead code, but is preserved in case it will be needed in future
629181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (!isValidSyncEvent(event)) {
629281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        return BAD_VALUE;
629381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
629481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
629581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    int eventSession = event->triggerSession();
629681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    status_t ret = NAME_NOT_FOUND;
629781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
629881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
629981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
630081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    for (size_t i = 0; i < mTracks.size(); i++) {
630181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sp<RecordTrack> track = mTracks[i];
630281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (eventSession == track->sessionId()) {
630381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            (void) track->setSyncEvent(event);
630481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            ret = NO_ERROR;
630581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
630681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
630781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return ret;
630881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#else
630981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return BAD_VALUE;
631081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#endif
631181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
631281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
631381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// destroyTrack_l() must be called with ThreadBase::mLock held
631481784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
631581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
6316bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    track->terminate();
6317bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    track->mState = TrackBase::STOPPED;
631881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // active tracks are removed by threadLoop()
63192b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten    if (mActiveTracks.indexOf(track) < 0) {
632081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        removeTrack_l(track);
632181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
632281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
632381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
632481784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
632581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
632681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mTracks.remove(track);
632781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // need anything related to effects here?
63286dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    if (track->isFastTrack()) {
63296dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        ALOG_ASSERT(!mFastTrackAvail);
63306dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        mFastTrackAvail = true;
63316dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    }
633281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
633381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
633481784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
633581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
633681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    dumpInternals(fd, args);
633781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    dumpTracks(fd, args);
633881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    dumpEffectChains(fd, args);
633981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
634081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
634181784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
634281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
634387cebadd48710e42474756fc3513df678de045ceElliott Hughes    dprintf(fd, "\nInput thread %p:\n", this);
634481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
634544182c206f7c5584ef2cf504da6be98fab665dbfGlenn Kasten    dumpBase(fd, args);
634644182c206f7c5584ef2cf504da6be98fab665dbfGlenn Kasten
634744182c206f7c5584ef2cf504da6be98fab665dbfGlenn Kasten    if (mActiveTracks.size() == 0) {
634887cebadd48710e42474756fc3513df678de045ceElliott Hughes        dprintf(fd, "  No active record clients\n");
634981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
63506e6704c06d61bc356e30c164081e5bcffb37920cGlenn Kasten    dprintf(fd, "  Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
63516dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    dprintf(fd, "  Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
635217c9c998afed5ed9df7495eeed5822f3ed53ebecGlenn Kasten
635317c9c998afed5ed9df7495eeed5822f3ed53ebecGlenn Kasten    //  Make a non-atomic copy of fast capture dump state so it won't change underneath us
635417c9c998afed5ed9df7495eeed5822f3ed53ebecGlenn Kasten    const FastCaptureDumpState copy(mFastCaptureDumpState);
635517c9c998afed5ed9df7495eeed5822f3ed53ebecGlenn Kasten    copy.dump(fd);
635681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
635781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
63580f11b51a57bc9062c4fe8af73747319cedabc5d6Glenn Kastenvoid AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
635981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
636081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    const size_t SIZE = 256;
636181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    char buffer[SIZE];
636281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    String8 result;
636381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
6364b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen    size_t numtracks = mTracks.size();
6365b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen    size_t numactive = mActiveTracks.size();
6366b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen    size_t numactiveseen = 0;
636787cebadd48710e42474756fc3513df678de045ceElliott Hughes    dprintf(fd, "  %d Tracks", numtracks);
6368b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen    if (numtracks) {
636987cebadd48710e42474756fc3513df678de045ceElliott Hughes        dprintf(fd, " of which %d are active\n", numactive);
6370b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        RecordTrack::appendDumpHeader(result);
6371b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        for (size_t i = 0; i < numtracks ; ++i) {
6372b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen            sp<RecordTrack> track = mTracks[i];
6373b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen            if (track != 0) {
6374b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen                bool active = mActiveTracks.indexOf(track) >= 0;
6375b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen                if (active) {
6376b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen                    numactiveseen++;
6377b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen                }
6378b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen                track->dump(buffer, SIZE, active);
6379b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen                result.append(buffer);
6380b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen            }
638181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
6382b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen    } else {
638387cebadd48710e42474756fc3513df678de045ceElliott Hughes        dprintf(fd, "\n");
638481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
638581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
6386b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen    if (numactiveseen != numactive) {
6387b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        snprintf(buffer, SIZE, "  The following tracks are in the active list but"
6388b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen                " not in the track list\n");
638981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        result.append(buffer);
639081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        RecordTrack::appendDumpHeader(result);
6391b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        for (size_t i = 0; i < numactive; ++i) {
63922b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten            sp<RecordTrack> track = mActiveTracks[i];
6393b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen            if (mTracks.indexOf(track) < 0) {
6394b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen                track->dump(buffer, SIZE, true);
6395b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen                result.append(buffer);
6396b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen            }
63972b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten        }
639881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
639981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
640081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    write(fd, result.string(), result.size());
640181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
640281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
640373c02e4277b399c2ec1555d32b6ad5df23bb83dcAndy Hung
640473c02e4277b399c2ec1555d32b6ad5df23bb83dcAndy Hungvoid AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
640573c02e4277b399c2ec1555d32b6ad5df23bb83dcAndy Hung{
640673c02e4277b399c2ec1555d32b6ad5df23bb83dcAndy Hung    sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
640773c02e4277b399c2ec1555d32b6ad5df23bb83dcAndy Hung    RecordThread *recordThread = (RecordThread *) threadBase.get();
640873c02e4277b399c2ec1555d32b6ad5df23bb83dcAndy Hung    mRsmpInFront = recordThread->mRsmpInRear;
640973c02e4277b399c2ec1555d32b6ad5df23bb83dcAndy Hung    mRsmpInUnrel = 0;
641073c02e4277b399c2ec1555d32b6ad5df23bb83dcAndy Hung}
641173c02e4277b399c2ec1555d32b6ad5df23bb83dcAndy Hung
641273c02e4277b399c2ec1555d32b6ad5df23bb83dcAndy Hungvoid AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
641373c02e4277b399c2ec1555d32b6ad5df23bb83dcAndy Hung        size_t *framesAvailable, bool *hasOverrun)
641473c02e4277b399c2ec1555d32b6ad5df23bb83dcAndy Hung{
641573c02e4277b399c2ec1555d32b6ad5df23bb83dcAndy Hung    sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
641673c02e4277b399c2ec1555d32b6ad5df23bb83dcAndy Hung    RecordThread *recordThread = (RecordThread *) threadBase.get();
641773c02e4277b399c2ec1555d32b6ad5df23bb83dcAndy Hung    const int32_t rear = recordThread->mRsmpInRear;
641873c02e4277b399c2ec1555d32b6ad5df23bb83dcAndy Hung    const int32_t front = mRsmpInFront;
641973c02e4277b399c2ec1555d32b6ad5df23bb83dcAndy Hung    const ssize_t filled = rear - front;
642073c02e4277b399c2ec1555d32b6ad5df23bb83dcAndy Hung
642173c02e4277b399c2ec1555d32b6ad5df23bb83dcAndy Hung    size_t framesIn;
642273c02e4277b399c2ec1555d32b6ad5df23bb83dcAndy Hung    bool overrun = false;
642373c02e4277b399c2ec1555d32b6ad5df23bb83dcAndy Hung    if (filled < 0) {
642473c02e4277b399c2ec1555d32b6ad5df23bb83dcAndy Hung        // should not happen, but treat like a massive overrun and re-sync
642573c02e4277b399c2ec1555d32b6ad5df23bb83dcAndy Hung        framesIn = 0;
642673c02e4277b399c2ec1555d32b6ad5df23bb83dcAndy Hung        mRsmpInFront = rear;
642773c02e4277b399c2ec1555d32b6ad5df23bb83dcAndy Hung        overrun = true;
642873c02e4277b399c2ec1555d32b6ad5df23bb83dcAndy Hung    } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
642973c02e4277b399c2ec1555d32b6ad5df23bb83dcAndy Hung        framesIn = (size_t) filled;
643073c02e4277b399c2ec1555d32b6ad5df23bb83dcAndy Hung    } else {
643173c02e4277b399c2ec1555d32b6ad5df23bb83dcAndy Hung        // client is not keeping up with server, but give it latest data
643273c02e4277b399c2ec1555d32b6ad5df23bb83dcAndy Hung        framesIn = recordThread->mRsmpInFrames;
643373c02e4277b399c2ec1555d32b6ad5df23bb83dcAndy Hung        mRsmpInFront = /* front = */ rear - framesIn;
643473c02e4277b399c2ec1555d32b6ad5df23bb83dcAndy Hung        overrun = true;
643573c02e4277b399c2ec1555d32b6ad5df23bb83dcAndy Hung    }
643673c02e4277b399c2ec1555d32b6ad5df23bb83dcAndy Hung    if (framesAvailable != NULL) {
643773c02e4277b399c2ec1555d32b6ad5df23bb83dcAndy Hung        *framesAvailable = framesIn;
643873c02e4277b399c2ec1555d32b6ad5df23bb83dcAndy Hung    }
643973c02e4277b399c2ec1555d32b6ad5df23bb83dcAndy Hung    if (hasOverrun != NULL) {
644073c02e4277b399c2ec1555d32b6ad5df23bb83dcAndy Hung        *hasOverrun = overrun;
644173c02e4277b399c2ec1555d32b6ad5df23bb83dcAndy Hung    }
644273c02e4277b399c2ec1555d32b6ad5df23bb83dcAndy Hung}
644373c02e4277b399c2ec1555d32b6ad5df23bb83dcAndy Hung
644481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// AudioBufferProvider interface
64456dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kastenstatus_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
64466dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
644781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
644873c02e4277b399c2ec1555d32b6ad5df23bb83dcAndy Hung    sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
64496dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten    if (threadBase == 0) {
64506dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        buffer->frameCount = 0;
6451607fa3e928de696eba49f198af72d68e4591ca1bGlenn Kasten        buffer->raw = NULL;
64526dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        return NOT_ENOUGH_DATA;
64536dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten    }
64546dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten    RecordThread *recordThread = (RecordThread *) threadBase.get();
64556dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten    int32_t rear = recordThread->mRsmpInRear;
645673c02e4277b399c2ec1555d32b6ad5df23bb83dcAndy Hung    int32_t front = mRsmpInFront;
64578594843c15b4722ced39436fe9e64f3e57e7ace4Glenn Kasten    ssize_t filled = rear - front;
64586dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten    // FIXME should not be P2 (don't want to increase latency)
64596dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten    // FIXME if client not keeping up, discard
6460607fa3e928de696eba49f198af72d68e4591ca1bGlenn Kasten    LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
64618594843c15b4722ced39436fe9e64f3e57e7ace4Glenn Kasten    // 'filled' may be non-contiguous, so return only the first contiguous chunk
64626dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten    front &= recordThread->mRsmpInFramesP2 - 1;
64636dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten    size_t part1 = recordThread->mRsmpInFramesP2 - front;
64648594843c15b4722ced39436fe9e64f3e57e7ace4Glenn Kasten    if (part1 > (size_t) filled) {
64658594843c15b4722ced39436fe9e64f3e57e7ace4Glenn Kasten        part1 = filled;
64668594843c15b4722ced39436fe9e64f3e57e7ace4Glenn Kasten    }
64678594843c15b4722ced39436fe9e64f3e57e7ace4Glenn Kasten    size_t ask = buffer->frameCount;
64688594843c15b4722ced39436fe9e64f3e57e7ace4Glenn Kasten    ALOG_ASSERT(ask > 0);
64698594843c15b4722ced39436fe9e64f3e57e7ace4Glenn Kasten    if (part1 > ask) {
64708594843c15b4722ced39436fe9e64f3e57e7ace4Glenn Kasten        part1 = ask;
64718594843c15b4722ced39436fe9e64f3e57e7ace4Glenn Kasten    }
64728594843c15b4722ced39436fe9e64f3e57e7ace4Glenn Kasten    if (part1 == 0) {
647373c02e4277b399c2ec1555d32b6ad5df23bb83dcAndy Hung        // out of data is fine since the resampler will return a short-count.
64748594843c15b4722ced39436fe9e64f3e57e7ace4Glenn Kasten        buffer->raw = NULL;
64758594843c15b4722ced39436fe9e64f3e57e7ace4Glenn Kasten        buffer->frameCount = 0;
647673c02e4277b399c2ec1555d32b6ad5df23bb83dcAndy Hung        mRsmpInUnrel = 0;
64778594843c15b4722ced39436fe9e64f3e57e7ace4Glenn Kasten        return NOT_ENOUGH_DATA;
64788594843c15b4722ced39436fe9e64f3e57e7ace4Glenn Kasten    }
64798594843c15b4722ced39436fe9e64f3e57e7ace4Glenn Kasten
64805744661e85981f8a9456bf470e2761235fc026daAndy Hung    buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
64818594843c15b4722ced39436fe9e64f3e57e7ace4Glenn Kasten    buffer->frameCount = part1;
648273c02e4277b399c2ec1555d32b6ad5df23bb83dcAndy Hung    mRsmpInUnrel = part1;
648381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return NO_ERROR;
648481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
648581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
648681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// AudioBufferProvider interface
64876dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kastenvoid AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
64886dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        AudioBufferProvider::Buffer* buffer)
648981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
64908594843c15b4722ced39436fe9e64f3e57e7ace4Glenn Kasten    size_t stepCount = buffer->frameCount;
64918594843c15b4722ced39436fe9e64f3e57e7ace4Glenn Kasten    if (stepCount == 0) {
64928594843c15b4722ced39436fe9e64f3e57e7ace4Glenn Kasten        return;
64938594843c15b4722ced39436fe9e64f3e57e7ace4Glenn Kasten    }
649473c02e4277b399c2ec1555d32b6ad5df23bb83dcAndy Hung    ALOG_ASSERT(stepCount <= mRsmpInUnrel);
649573c02e4277b399c2ec1555d32b6ad5df23bb83dcAndy Hung    mRsmpInUnrel -= stepCount;
649673c02e4277b399c2ec1555d32b6ad5df23bb83dcAndy Hung    mRsmpInFront += stepCount;
64978594843c15b4722ced39436fe9e64f3e57e7ace4Glenn Kasten    buffer->raw = NULL;
649881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    buffer->frameCount = 0;
649981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
650081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
650197a893eb34f8687485c88eaf15917974a203f20bAndy HungAudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
650297a893eb34f8687485c88eaf15917974a203f20bAndy Hung        audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
650397a893eb34f8687485c88eaf15917974a203f20bAndy Hung        uint32_t srcSampleRate,
650497a893eb34f8687485c88eaf15917974a203f20bAndy Hung        audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
650597a893eb34f8687485c88eaf15917974a203f20bAndy Hung        uint32_t dstSampleRate) :
650697a893eb34f8687485c88eaf15917974a203f20bAndy Hung            mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
650797a893eb34f8687485c88eaf15917974a203f20bAndy Hung            // mSrcFormat
650897a893eb34f8687485c88eaf15917974a203f20bAndy Hung            // mSrcSampleRate
650997a893eb34f8687485c88eaf15917974a203f20bAndy Hung            // mDstChannelMask
651097a893eb34f8687485c88eaf15917974a203f20bAndy Hung            // mDstFormat
651197a893eb34f8687485c88eaf15917974a203f20bAndy Hung            // mDstSampleRate
651297a893eb34f8687485c88eaf15917974a203f20bAndy Hung            // mSrcChannelCount
651397a893eb34f8687485c88eaf15917974a203f20bAndy Hung            // mDstChannelCount
651497a893eb34f8687485c88eaf15917974a203f20bAndy Hung            // mDstFrameSize
651597a893eb34f8687485c88eaf15917974a203f20bAndy Hung            mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
6516d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung            mResampler(NULL),
6517d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung            mIsLegacyDownmix(false),
6518d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung            mIsLegacyUpmix(false),
6519d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung            mRequiresFloat(false),
6520d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung            mInputConverterProvider(NULL)
652197a893eb34f8687485c88eaf15917974a203f20bAndy Hung{
652297a893eb34f8687485c88eaf15917974a203f20bAndy Hung    (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
652397a893eb34f8687485c88eaf15917974a203f20bAndy Hung            dstChannelMask, dstFormat, dstSampleRate);
652497a893eb34f8687485c88eaf15917974a203f20bAndy Hung}
652597a893eb34f8687485c88eaf15917974a203f20bAndy Hung
652697a893eb34f8687485c88eaf15917974a203f20bAndy HungAudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
652797a893eb34f8687485c88eaf15917974a203f20bAndy Hung    free(mBuf);
652897a893eb34f8687485c88eaf15917974a203f20bAndy Hung    delete mResampler;
6529d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung    delete mInputConverterProvider;
653097a893eb34f8687485c88eaf15917974a203f20bAndy Hung}
653197a893eb34f8687485c88eaf15917974a203f20bAndy Hung
653297a893eb34f8687485c88eaf15917974a203f20bAndy Hungsize_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
653397a893eb34f8687485c88eaf15917974a203f20bAndy Hung        AudioBufferProvider *provider, size_t frames)
653497a893eb34f8687485c88eaf15917974a203f20bAndy Hung{
6535d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung    if (mInputConverterProvider != NULL) {
6536d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung        mInputConverterProvider->setBufferProvider(provider);
6537d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung        provider = mInputConverterProvider;
6538d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung    }
6539d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung
6540d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung    if (mResampler == NULL) {
654197a893eb34f8687485c88eaf15917974a203f20bAndy Hung        ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
654297a893eb34f8687485c88eaf15917974a203f20bAndy Hung                mSrcSampleRate, mSrcFormat, mDstFormat);
654397a893eb34f8687485c88eaf15917974a203f20bAndy Hung
654497a893eb34f8687485c88eaf15917974a203f20bAndy Hung        AudioBufferProvider::Buffer buffer;
654597a893eb34f8687485c88eaf15917974a203f20bAndy Hung        for (size_t i = frames; i > 0; ) {
654697a893eb34f8687485c88eaf15917974a203f20bAndy Hung            buffer.frameCount = i;
654797a893eb34f8687485c88eaf15917974a203f20bAndy Hung            status_t status = provider->getNextBuffer(&buffer, 0);
654897a893eb34f8687485c88eaf15917974a203f20bAndy Hung            if (status != OK || buffer.frameCount == 0) {
654997a893eb34f8687485c88eaf15917974a203f20bAndy Hung                frames -= i; // cannot fill request.
655097a893eb34f8687485c88eaf15917974a203f20bAndy Hung                break;
655197a893eb34f8687485c88eaf15917974a203f20bAndy Hung            }
6552d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung            // format convert to destination buffer
6553d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung            convertNoResampler(dst, buffer.raw, buffer.frameCount);
655497a893eb34f8687485c88eaf15917974a203f20bAndy Hung
655597a893eb34f8687485c88eaf15917974a203f20bAndy Hung            dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
655697a893eb34f8687485c88eaf15917974a203f20bAndy Hung            i -= buffer.frameCount;
655797a893eb34f8687485c88eaf15917974a203f20bAndy Hung            provider->releaseBuffer(&buffer);
655897a893eb34f8687485c88eaf15917974a203f20bAndy Hung        }
655997a893eb34f8687485c88eaf15917974a203f20bAndy Hung    } else {
656097a893eb34f8687485c88eaf15917974a203f20bAndy Hung         ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
656197a893eb34f8687485c88eaf15917974a203f20bAndy Hung                 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
656297a893eb34f8687485c88eaf15917974a203f20bAndy Hung
6563d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung         // reallocate buffer if needed
6564d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung         if (mBufFrameSize != 0 && mBufFrames < frames) {
6565d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung             free(mBuf);
6566d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung             mBufFrames = frames;
6567d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung             (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6568d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung         }
656997a893eb34f8687485c88eaf15917974a203f20bAndy Hung        // resampler accumulates, but we only have one source track
6570d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung        memset(mBuf, 0, frames * mBufFrameSize);
6571d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung        frames = mResampler->resample((int32_t*)mBuf, frames, provider);
6572d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung        // format convert to destination buffer
6573d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung        convertResampler(dst, mBuf, frames);
657497a893eb34f8687485c88eaf15917974a203f20bAndy Hung    }
657597a893eb34f8687485c88eaf15917974a203f20bAndy Hung    return frames;
657697a893eb34f8687485c88eaf15917974a203f20bAndy Hung}
657797a893eb34f8687485c88eaf15917974a203f20bAndy Hung
657897a893eb34f8687485c88eaf15917974a203f20bAndy Hungstatus_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
657997a893eb34f8687485c88eaf15917974a203f20bAndy Hung        audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
658097a893eb34f8687485c88eaf15917974a203f20bAndy Hung        uint32_t srcSampleRate,
658197a893eb34f8687485c88eaf15917974a203f20bAndy Hung        audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
658297a893eb34f8687485c88eaf15917974a203f20bAndy Hung        uint32_t dstSampleRate)
658397a893eb34f8687485c88eaf15917974a203f20bAndy Hung{
658497a893eb34f8687485c88eaf15917974a203f20bAndy Hung    // quick evaluation if there is any change.
658597a893eb34f8687485c88eaf15917974a203f20bAndy Hung    if (mSrcFormat == srcFormat
658697a893eb34f8687485c88eaf15917974a203f20bAndy Hung            && mSrcChannelMask == srcChannelMask
658797a893eb34f8687485c88eaf15917974a203f20bAndy Hung            && mSrcSampleRate == srcSampleRate
658897a893eb34f8687485c88eaf15917974a203f20bAndy Hung            && mDstFormat == dstFormat
658997a893eb34f8687485c88eaf15917974a203f20bAndy Hung            && mDstChannelMask == dstChannelMask
659097a893eb34f8687485c88eaf15917974a203f20bAndy Hung            && mDstSampleRate == dstSampleRate) {
659197a893eb34f8687485c88eaf15917974a203f20bAndy Hung        return NO_ERROR;
659297a893eb34f8687485c88eaf15917974a203f20bAndy Hung    }
659397a893eb34f8687485c88eaf15917974a203f20bAndy Hung
6594db4c031f518ae5806af73756273ff32cd8d0e4f8Andy Hung    ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x"
6595db4c031f518ae5806af73756273ff32cd8d0e4f8Andy Hung            "  srcFormat:%#x dstFormat:%#x  srcRate:%u dstRate:%u",
6596db4c031f518ae5806af73756273ff32cd8d0e4f8Andy Hung            srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate);
659797a893eb34f8687485c88eaf15917974a203f20bAndy Hung    const bool valid =
659897a893eb34f8687485c88eaf15917974a203f20bAndy Hung            audio_is_input_channel(srcChannelMask)
659997a893eb34f8687485c88eaf15917974a203f20bAndy Hung            && audio_is_input_channel(dstChannelMask)
660097a893eb34f8687485c88eaf15917974a203f20bAndy Hung            && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
660197a893eb34f8687485c88eaf15917974a203f20bAndy Hung            && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
660297a893eb34f8687485c88eaf15917974a203f20bAndy Hung            && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
660397a893eb34f8687485c88eaf15917974a203f20bAndy Hung            ; // no upsampling checks for now
660497a893eb34f8687485c88eaf15917974a203f20bAndy Hung    if (!valid) {
660597a893eb34f8687485c88eaf15917974a203f20bAndy Hung        return BAD_VALUE;
660697a893eb34f8687485c88eaf15917974a203f20bAndy Hung    }
660797a893eb34f8687485c88eaf15917974a203f20bAndy Hung
660897a893eb34f8687485c88eaf15917974a203f20bAndy Hung    mSrcFormat = srcFormat;
660997a893eb34f8687485c88eaf15917974a203f20bAndy Hung    mSrcChannelMask = srcChannelMask;
661097a893eb34f8687485c88eaf15917974a203f20bAndy Hung    mSrcSampleRate = srcSampleRate;
661197a893eb34f8687485c88eaf15917974a203f20bAndy Hung    mDstFormat = dstFormat;
661297a893eb34f8687485c88eaf15917974a203f20bAndy Hung    mDstChannelMask = dstChannelMask;
661397a893eb34f8687485c88eaf15917974a203f20bAndy Hung    mDstSampleRate = dstSampleRate;
661497a893eb34f8687485c88eaf15917974a203f20bAndy Hung
661597a893eb34f8687485c88eaf15917974a203f20bAndy Hung    // compute derived parameters
661697a893eb34f8687485c88eaf15917974a203f20bAndy Hung    mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
661797a893eb34f8687485c88eaf15917974a203f20bAndy Hung    mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
661897a893eb34f8687485c88eaf15917974a203f20bAndy Hung    mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
661997a893eb34f8687485c88eaf15917974a203f20bAndy Hung
6620d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung    // do we need to resample?
6621d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung    delete mResampler;
6622d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung    mResampler = NULL;
6623d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung    if (mSrcSampleRate != mDstSampleRate) {
6624d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung        mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
6625d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung                mSrcChannelCount, mDstSampleRate);
6626d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung        mResampler->setSampleRate(mSrcSampleRate);
6627d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung        mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
6628d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung    }
6629d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung
6630d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung    // are we running legacy channel conversion modes?
6631d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung    mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
6632d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung                            || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
6633d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung                   && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
6634d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung    mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
6635d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung                   && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
6636d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung                            || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
6637d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung
6638d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung    // do we need to process in float?
6639d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung    mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
6640d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung
6641d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung    // do we need a staging buffer to convert for destination (we can still optimize this)?
6642d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung    // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
6643d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung    if (mResampler != NULL) {
6644d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung        mBufFrameSize = max(mSrcChannelCount, FCC_2)
6645d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung                * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
6646a97630bda8815958587ca31adb2d37090022af25Andy Hung    } else if (mIsLegacyUpmix || mIsLegacyDownmix) { // legacy modes always float
6647d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung        mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
6648d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung    } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
664997a893eb34f8687485c88eaf15917974a203f20bAndy Hung        mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
665097a893eb34f8687485c88eaf15917974a203f20bAndy Hung    } else {
665197a893eb34f8687485c88eaf15917974a203f20bAndy Hung        mBufFrameSize = 0;
665297a893eb34f8687485c88eaf15917974a203f20bAndy Hung    }
665397a893eb34f8687485c88eaf15917974a203f20bAndy Hung    mBufFrames = 0; // force the buffer to be resized.
665497a893eb34f8687485c88eaf15917974a203f20bAndy Hung
6655d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung    // do we need an input converter buffer provider to give us float?
6656d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung    delete mInputConverterProvider;
6657d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung    mInputConverterProvider = NULL;
6658d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung    if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
6659d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung        mInputConverterProvider = new ReformatBufferProvider(
6660d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung                audio_channel_count_from_in_mask(mSrcChannelMask),
6661d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung                mSrcFormat,
6662d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung                AUDIO_FORMAT_PCM_FLOAT,
6663d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung                256 /* provider buffer frame count */);
6664d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung    }
6665d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung
6666d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung    // do we need a remixer to do channel mask conversion
6667d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung    if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
6668d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung        (void) memcpy_by_index_array_initialization_from_channel_mask(
6669d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung                mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
667097a893eb34f8687485c88eaf15917974a203f20bAndy Hung    }
667197a893eb34f8687485c88eaf15917974a203f20bAndy Hung    return NO_ERROR;
667297a893eb34f8687485c88eaf15917974a203f20bAndy Hung}
667397a893eb34f8687485c88eaf15917974a203f20bAndy Hung
6674d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hungvoid AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
6675d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung        void *dst, const void *src, size_t frames)
667697a893eb34f8687485c88eaf15917974a203f20bAndy Hung{
6677d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung    // src is native type unless there is legacy upmix or downmix, whereupon it is float.
667897a893eb34f8687485c88eaf15917974a203f20bAndy Hung    if (mBufFrameSize != 0 && mBufFrames < frames) {
667997a893eb34f8687485c88eaf15917974a203f20bAndy Hung        free(mBuf);
668097a893eb34f8687485c88eaf15917974a203f20bAndy Hung        mBufFrames = frames;
668197a893eb34f8687485c88eaf15917974a203f20bAndy Hung        (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
668297a893eb34f8687485c88eaf15917974a203f20bAndy Hung    }
6683d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung    // do we need to do legacy upmix and downmix?
6684d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung    if (mIsLegacyUpmix || mIsLegacyDownmix) {
668597a893eb34f8687485c88eaf15917974a203f20bAndy Hung        void *dstBuf = mBuf != NULL ? mBuf : dst;
6686d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung        if (mIsLegacyUpmix) {
6687d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung            upmix_to_stereo_float_from_mono_float((float *)dstBuf,
6688d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung                    (const float *)src, frames);
6689d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung        } else /*mIsLegacyDownmix */ {
6690d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung            downmix_to_mono_float_from_stereo_float((float *)dstBuf,
6691d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung                    (const float *)src, frames);
669297a893eb34f8687485c88eaf15917974a203f20bAndy Hung        }
6693d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung        if (mBuf != NULL) {
6694d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung            memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
6695d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung                    frames * mDstChannelCount);
6696d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung        }
6697d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung        return;
6698d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung    }
6699d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung    // do we need to do channel mask conversion?
6700d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung    if (mSrcChannelMask != mDstChannelMask) {
670197a893eb34f8687485c88eaf15917974a203f20bAndy Hung        void *dstBuf = mBuf != NULL ? mBuf : dst;
6702d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung        memcpy_by_index_array(dstBuf, mDstChannelCount,
6703d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung                src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
6704d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung        if (dstBuf == dst) {
6705d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung            return; // format is the same
6706d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung        }
6707d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung    }
6708d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung    // convert to destination buffer
6709d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung    const void *convertBuf = mBuf != NULL ? mBuf : src;
6710d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung    memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
6711d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung            frames * mDstChannelCount);
6712d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung}
6713d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung
6714d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hungvoid AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
6715d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung        void *dst, /*not-a-const*/ void *src, size_t frames)
6716d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung{
6717d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung    // src buffer format is ALWAYS float when entering this routine
6718d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung    if (mIsLegacyUpmix) {
6719d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung        ; // mono to stereo already handled by resampler
6720d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung    } else if (mIsLegacyDownmix
6721d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung            || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
6722d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung        // the resampler outputs stereo for mono input channel (a feature?)
6723d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung        // must convert to mono
6724d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung        downmix_to_mono_float_from_stereo_float((float *)src,
6725d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung                (const float *)src, frames);
6726d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung    } else if (mSrcChannelMask != mDstChannelMask) {
6727d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung        // convert to mono channel again for channel mask conversion (could be skipped
6728d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung        // with further optimization).
672997a893eb34f8687485c88eaf15917974a203f20bAndy Hung        if (mSrcChannelCount == 1) {
6730d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung            downmix_to_mono_float_from_stereo_float((float *)src,
6731d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung                (const float *)src, frames);
673297a893eb34f8687485c88eaf15917974a203f20bAndy Hung        }
6733d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung        // convert to destination format (in place, OK as float is larger than other types)
6734d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung        if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
6735d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung            memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6736d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung                    frames * mSrcChannelCount);
6737d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung        }
6738d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung        // channel convert and save to dst
6739d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung        memcpy_by_index_array(dst, mDstChannelCount,
6740d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung                src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
6741d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung        return;
674297a893eb34f8687485c88eaf15917974a203f20bAndy Hung    }
6743d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung    // convert to destination format and save to dst
6744d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung    memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6745d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung            frames * mDstChannelCount);
674697a893eb34f8687485c88eaf15917974a203f20bAndy Hung}
674797a893eb34f8687485c88eaf15917974a203f20bAndy Hung
67481035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurentbool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
67491035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                                                        status_t& status)
675081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
675181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    bool reconfig = false;
675281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
67531035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    status = NO_ERROR;
67541035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent
67551035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    audio_format_t reqFormat = mFormat;
67561035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    uint32_t samplingRate = mSampleRate;
6757e1635ec096d1110c33a5aa46847af59c261fb7faGlenn Kasten    // TODO this may change if we want to support capture from HDMI PCM multi channel (e.g on TVs).
67581035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
67591035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent
67601035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    AudioParameter param = AudioParameter(keyValuePair);
67611035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    int value;
67621035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    // TODO Investigate when this code runs. Check with audio policy when a sample rate and
67631035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    //      channel count change can be requested. Do we mandate the first client defines the
67641035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    //      HAL sampling rate and channel count or do we allow changes on the fly?
67651035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
67661035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        samplingRate = value;
67671035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        reconfig = true;
67681035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    }
67691035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
677097a893eb34f8687485c88eaf15917974a203f20bAndy Hung        if (!audio_is_linear_pcm((audio_format_t) value)) {
67711035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            status = BAD_VALUE;
67721035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        } else {
67731035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            reqFormat = (audio_format_t) value;
677481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            reconfig = true;
677581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
67761035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    }
67771035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
67781035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        audio_channel_mask_t mask = (audio_channel_mask_t) value;
6779d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung        if (!audio_is_input_channel(mask) ||
6780d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung                audio_channel_count_from_in_mask(mask) > FCC_8) {
67811035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            status = BAD_VALUE;
67821035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        } else {
67831035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            channelMask = mask;
67841035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            reconfig = true;
678581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
67861035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    }
67871035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
67881035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        // do not accept frame count changes if tracks are open as the track buffer
67891035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        // size depends on frame count and correct behavior would not be guaranteed
67901035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        // if frame count is changed after track creation
67911035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        if (mActiveTracks.size() > 0) {
67921035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            status = INVALID_OPERATION;
67931035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        } else {
67941035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            reconfig = true;
679581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
67961035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    }
67971035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
67981035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        // forward device change to effects that have requested to be
67991035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        // aware of attached audio device.
68001035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        for (size_t i = 0; i < mEffectChains.size(); i++) {
68011035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            mEffectChains[i]->setDevice_l(value);
680281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
680381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
68041035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        // store input device and output device but do not forward output device to audio HAL.
68051035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        // Note that status is ignored by the caller for output device
68061035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        // (see AudioFlinger::setParameters()
68071035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        if (audio_is_output_devices(value)) {
68081035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            mOutDevice = value;
68091035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            status = BAD_VALUE;
68101035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        } else {
68111035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            mInDevice = value;
6812e8726fea8a53bf3474aa3c6deaf2f6c1f565e694Eric Laurent            if (value != AUDIO_DEVICE_NONE) {
6813e8726fea8a53bf3474aa3c6deaf2f6c1f565e694Eric Laurent                mPrevInDevice = value;
6814e8726fea8a53bf3474aa3c6deaf2f6c1f565e694Eric Laurent            }
68151035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            // disable AEC and NS if the device is a BT SCO headset supporting those
68161035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            // pre processings
68171035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            if (mTracks.size() > 0) {
68181035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
68191035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                                    mAudioFlinger->btNrecIsOff();
68201035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                for (size_t i = 0; i < mTracks.size(); i++) {
68211035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                    sp<RecordTrack> track = mTracks[i];
68221035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                    setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
68231035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                    setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
682481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
682581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
682681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
68271035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    }
68281035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
68291035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            mAudioSource != (audio_source_t)value) {
68301035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        // forward device change to effects that have requested to be
68311035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        // aware of attached audio device.
68321035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        for (size_t i = 0; i < mEffectChains.size(); i++) {
68331035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            mEffectChains[i]->setAudioSource_l((audio_source_t)value);
683481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
68351035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        mAudioSource = (audio_source_t)value;
68361035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    }
6837e198c360d5e75a9b2097844c495c10902e7e8500Glenn Kasten
68381035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    if (status == NO_ERROR) {
68391035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        status = mInput->stream->common.set_parameters(&mInput->stream->common,
68401035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                keyValuePair.string());
68411035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        if (status == INVALID_OPERATION) {
68421035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            inputStandBy();
684381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            status = mInput->stream->common.set_parameters(&mInput->stream->common,
684481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    keyValuePair.string());
68451035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        }
68461035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        if (reconfig) {
68471035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            if (status == BAD_VALUE &&
684897a893eb34f8687485c88eaf15917974a203f20bAndy Hung                audio_is_linear_pcm(mInput->stream->common.get_format(&mInput->stream->common)) &&
684997a893eb34f8687485c88eaf15917974a203f20bAndy Hung                audio_is_linear_pcm(reqFormat) &&
68501035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                (mInput->stream->common.get_sample_rate(&mInput->stream->common)
685197a893eb34f8687485c88eaf15917974a203f20bAndy Hung                        <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate)) &&
6852e541269be94f3a1072932d51537905b120ef4733Andy Hung                audio_channel_count_from_in_mask(
6853d1abb8f94d7ed749ee959655db1e07d26dad074dAndy Hung                        mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_8) {
68541035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                status = NO_ERROR;
685581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
68561035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            if (status == NO_ERROR) {
68571035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                readInputParameters_l();
685873e26b661af50be2c0a4ff6c9ac85f7347a8b235Eric Laurent                sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
685981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
686081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
686181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
68621035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent
686381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return reconfig;
686481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
686581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
686681784c37c61b09289654b979567a42bf73cd2b12Eric LaurentString8 AudioFlinger::RecordThread::getParameters(const String8& keys)
686781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
686881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
686981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (initCheck() != NO_ERROR) {
6870d8ea699dc8e7dac58bb32e9cdb31b0758da25817Glenn Kasten        return String8();
687181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
687281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
6873d8ea699dc8e7dac58bb32e9cdb31b0758da25817Glenn Kasten    char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
6874d8ea699dc8e7dac58bb32e9cdb31b0758da25817Glenn Kasten    const String8 out_s8(s);
687581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    free(s);
687681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return out_s8;
687781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
687881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
68797c1ec5f038e63a5eb8b04434577c25bc23f5f410Eric Laurentvoid AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
688073e26b661af50be2c0a4ff6c9ac85f7347a8b235Eric Laurent    sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
688173e26b661af50be2c0a4ff6c9ac85f7347a8b235Eric Laurent
688273e26b661af50be2c0a4ff6c9ac85f7347a8b235Eric Laurent    desc->mIoHandle = mId;
688381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
688481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    switch (event) {
688573e26b661af50be2c0a4ff6c9ac85f7347a8b235Eric Laurent    case AUDIO_INPUT_OPENED:
688673e26b661af50be2c0a4ff6c9ac85f7347a8b235Eric Laurent    case AUDIO_INPUT_CONFIG_CHANGED:
6887296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent        desc->mPatch = mPatch;
688873e26b661af50be2c0a4ff6c9ac85f7347a8b235Eric Laurent        desc->mChannelMask = mChannelMask;
688973e26b661af50be2c0a4ff6c9ac85f7347a8b235Eric Laurent        desc->mSamplingRate = mSampleRate;
689073e26b661af50be2c0a4ff6c9ac85f7347a8b235Eric Laurent        desc->mFormat = mFormat;
689173e26b661af50be2c0a4ff6c9ac85f7347a8b235Eric Laurent        desc->mFrameCount = mFrameCount;
689273e26b661af50be2c0a4ff6c9ac85f7347a8b235Eric Laurent        desc->mLatency = 0;
689381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        break;
689481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
689573e26b661af50be2c0a4ff6c9ac85f7347a8b235Eric Laurent    case AUDIO_INPUT_CLOSED:
689681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    default:
689781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        break;
689881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
68997c1ec5f038e63a5eb8b04434577c25bc23f5f410Eric Laurent    mAudioFlinger->ioConfigChanged(event, desc, pid);
690081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
690181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
6902deca2ae0a7cf8bc54ff3f30b7dc39bbc78b94c0dGlenn Kastenvoid AudioFlinger::RecordThread::readInputParameters_l()
690381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
690481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
690581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
6906e541269be94f3a1072932d51537905b120ef4733Andy Hung    mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
6907d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung    if (mChannelCount > FCC_8) {
6908d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung        ALOGE("HAL channel count %d > %d", mChannelCount, FCC_8);
6909d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung    }
6910463be250de73907965faa6a216c00312bf81e049Andy Hung    mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
6911463be250de73907965faa6a216c00312bf81e049Andy Hung    mFormat = mHALFormat;
6912d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung    if (!audio_is_linear_pcm(mFormat)) {
6913d330ee46022f34da76d14d0c4d2910526ecc2321Andy Hung        ALOGE("HAL format %#x is not linear pcm", mFormat);
6914291bb6d8947c5b0c062f0895d623c529259bfa39Glenn Kasten    }
6915665470b36f202bcc8ee2f7417f68fd2608dd07c1Eric Laurent    mFrameSize = audio_stream_in_frame_size(mInput->stream);
6916548efc94813c1dec6e8cf6c085ae41ccb04827f1Glenn Kasten    mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
6917548efc94813c1dec6e8cf6c085ae41ccb04827f1Glenn Kasten    mFrameCount = mBufferSize / mFrameSize;
69186dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten    // This is the formula for calculating the temporary buffer size.
6919e842614837e5401adf77e90485300c288b9a7876Glenn Kasten    // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
69208594843c15b4722ced39436fe9e64f3e57e7ace4Glenn Kasten    // 1 full output buffer, regardless of the alignment of the available input.
6921e842614837e5401adf77e90485300c288b9a7876Glenn Kasten    // The value is somewhat arbitrary, and could probably be even larger.
69226dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten    // A larger value should allow more old data to be read after a track calls start(),
69236dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten    // without increasing latency.
692497a893eb34f8687485c88eaf15917974a203f20bAndy Hung    //
692597a893eb34f8687485c88eaf15917974a203f20bAndy Hung    // Note this is independent of the maximum downsampling ratio permitted for capture.
6926e842614837e5401adf77e90485300c288b9a7876Glenn Kasten    mRsmpInFrames = mFrameCount * 7;
69278594843c15b4722ced39436fe9e64f3e57e7ace4Glenn Kasten    mRsmpInFramesP2 = roundup(mRsmpInFrames);
69285744661e85981f8a9456bf470e2761235fc026daAndy Hung    free(mRsmpInBuffer);
692949d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten
693049d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten    // TODO optimize audio capture buffer sizes ...
693149d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten    // Here we calculate the size of the sliding buffer used as a source
693249d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten    // for resampling.  mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
693349d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten    // For current HAL frame counts, this is usually 2048 = 40 ms.  It would
693449d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten    // be better to have it derived from the pipe depth in the long term.
693549d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten    // The current value is higher than necessary.  However it should not add to latency.
693649d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten
69378594843c15b4722ced39436fe9e64f3e57e7ace4Glenn Kasten    // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
69385744661e85981f8a9456bf470e2761235fc026daAndy Hung    (void)posix_memalign(&mRsmpInBuffer, 32, (mRsmpInFramesP2 + mFrameCount - 1) * mFrameSize);
69396dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten
69404cc0a6a835c806d200ef83ef31fe5bef327c355cGlenn Kasten    // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
69414cc0a6a835c806d200ef83ef31fe5bef327c355cGlenn Kasten    // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
694281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
694381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
69445f972c031d4061f4f037c9fda1ea4bd9b6a756cdGlenn Kastenuint32_t AudioFlinger::RecordThread::getInputFramesLost()
694581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
694681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
694781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (initCheck() != NO_ERROR) {
694881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        return 0;
694981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
695081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
695181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return mInput->stream->get_input_frames_lost(mInput->stream);
695281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
695381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
695481784c37c61b09289654b979567a42bf73cd2b12Eric Laurentuint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
695581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
695681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
695781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    uint32_t result = 0;
695881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (getEffectChain_l(sessionId) != 0) {
695981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        result = EFFECT_SESSION;
696081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
696181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
696281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    for (size_t i = 0; i < mTracks.size(); ++i) {
696381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (sessionId == mTracks[i]->sessionId()) {
696481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            result |= TRACK_SESSION;
696581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            break;
696681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
696781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
696881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
696981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return result;
697081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
697181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
697281784c37c61b09289654b979567a42bf73cd2b12Eric LaurentKeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
697381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
697481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    KeyedVector<int, bool> ids;
697581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
697681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    for (size_t j = 0; j < mTracks.size(); ++j) {
697781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sp<RecordThread::RecordTrack> track = mTracks[j];
697881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        int sessionId = track->sessionId();
697981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (ids.indexOfKey(sessionId) < 0) {
698081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            ids.add(sessionId, true);
698181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
698281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
698381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return ids;
698481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
698581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
698681784c37c61b09289654b979567a42bf73cd2b12Eric LaurentAudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
698781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
698881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
698981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    AudioStreamIn *input = mInput;
699081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mInput = NULL;
699181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return input;
699281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
699381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
699481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// this method must always be called either with ThreadBase mLock held or inside the thread loop
699581784c37c61b09289654b979567a42bf73cd2b12Eric Laurentaudio_stream_t* AudioFlinger::RecordThread::stream() const
699681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
699781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (mInput == NULL) {
699881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        return NULL;
699981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
700081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return &mInput->stream->common;
700181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
700281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
700381784c37c61b09289654b979567a42bf73cd2b12Eric Laurentstatus_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
700481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
700581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // only one chain per input thread
700681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (mEffectChains.size() != 0) {
7007aaa44478a373232d8416657035a9020f9c7aa7c3Eric Laurent        ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
700881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        return INVALID_OPERATION;
700981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
701081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
7011aaa44478a373232d8416657035a9020f9c7aa7c3Eric Laurent    chain->setThread(this);
701281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    chain->setInBuffer(NULL);
701381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    chain->setOutBuffer(NULL);
701481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
701581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    checkSuspendOnAddEffectChain_l(chain);
701681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
70171b92868010b5c1409692a86f6b27e4a265b64c1aEric Laurent    // make sure enabled pre processing effects state is communicated to the HAL as we
70181b92868010b5c1409692a86f6b27e4a265b64c1aEric Laurent    // just moved them to a new input stream.
70191b92868010b5c1409692a86f6b27e4a265b64c1aEric Laurent    chain->syncHalEffectsState();
70201b92868010b5c1409692a86f6b27e4a265b64c1aEric Laurent
702181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mEffectChains.add(chain);
702281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
702381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return NO_ERROR;
702481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
702581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
702681784c37c61b09289654b979567a42bf73cd2b12Eric Laurentsize_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
702781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
702881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
702981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    ALOGW_IF(mEffectChains.size() != 1,
703081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            "removeEffectChain_l() %p invalid chain size %d on thread %p",
703181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            chain.get(), mEffectChains.size(), this);
703281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (mEffectChains.size() == 1) {
703381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mEffectChains.removeAt(0);
703481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
703581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return 0;
703681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
703781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
70381c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurentstatus_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
70391c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent                                                          audio_patch_handle_t *handle)
70401c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent{
70411c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent    status_t status = NO_ERROR;
7042054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent
7043054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent    // store new device and send to effects
7044054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent    mInDevice = patch->sources[0].ext.device.type;
7045296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent    mPatch = *patch;
7046054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent    for (size_t i = 0; i < mEffectChains.size(); i++) {
7047054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        mEffectChains[i]->setDevice_l(mInDevice);
7048054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent    }
7049054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent
7050054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent    // disable AEC and NS if the device is a BT SCO headset supporting those
7051054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent    // pre processings
7052054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent    if (mTracks.size() > 0) {
7053054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7054054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent                            mAudioFlinger->btNrecIsOff();
7055054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        for (size_t i = 0; i < mTracks.size(); i++) {
7056054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent            sp<RecordTrack> track = mTracks[i];
7057054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent            setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7058054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent            setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
70591c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent        }
7060054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent    }
70611c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent
7062054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent    // store new source and send to effects
7063054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent    if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7064054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        mAudioSource = patch->sinks[0].ext.mix.usecase.source;
7065054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        for (size_t i = 0; i < mEffectChains.size(); i++) {
7066054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent            mEffectChains[i]->setAudioSource_l(mAudioSource);
70671c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent        }
7068054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent    }
70691c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent
7070054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent    if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
70711c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent        audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
70721c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent        status = hwDevice->create_audio_patch(hwDevice,
70731c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent                                               patch->num_sources,
70741c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent                                               patch->sources,
70751c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent                                               patch->num_sinks,
70761c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent                                               patch->sinks,
70771c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent                                               handle);
70781c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent    } else {
7079054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        char *address;
7080054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7081054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent            address = audio_device_address_to_parameter(
7082054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent                                                patch->sources[0].ext.device.type,
7083054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent                                                patch->sources[0].ext.device.address);
7084054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        } else {
7085054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent            address = (char *)calloc(1, 1);
7086054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        }
7087054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        AudioParameter param = AudioParameter(String8(address));
7088054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        free(address);
7089054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING),
7090054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent                     (int)patch->sources[0].ext.device.type);
7091054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        param.addInt(String8(AUDIO_PARAMETER_STREAM_INPUT_SOURCE),
7092054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent                                         (int)patch->sinks[0].ext.mix.usecase.source);
7093054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        status = mInput->stream->common.set_parameters(&mInput->stream->common,
7094054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent                param.toString().string());
7095054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        *handle = AUDIO_PATCH_HANDLE_NONE;
70961c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent    }
7097054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent
7098e8726fea8a53bf3474aa3c6deaf2f6c1f565e694Eric Laurent    if (mInDevice != mPrevInDevice) {
7099e8726fea8a53bf3474aa3c6deaf2f6c1f565e694Eric Laurent        sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7100e8726fea8a53bf3474aa3c6deaf2f6c1f565e694Eric Laurent        mPrevInDevice = mInDevice;
7101e8726fea8a53bf3474aa3c6deaf2f6c1f565e694Eric Laurent    }
7102296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent
71031c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent    return status;
71041c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent}
71051c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent
71061c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurentstatus_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
71071c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent{
71081c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent    status_t status = NO_ERROR;
7109054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent
7110054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent    mInDevice = AUDIO_DEVICE_NONE;
7111054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent
71121c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent    if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
71131c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent        audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
71141c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent        status = hwDevice->release_audio_patch(hwDevice, handle);
71151c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent    } else {
7116054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        AudioParameter param;
7117054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
7118054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent        status = mInput->stream->common.set_parameters(&mInput->stream->common,
7119054d9d3dea1390294650ac704acb4aa0a0731217Eric Laurent                param.toString().string());
71201c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent    }
71211c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent    return status;
71221c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent}
71231c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent
712483b8808faad1e91690c64d7007348be8d9ebde73Eric Laurentvoid AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
712583b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent{
712683b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent    Mutex::Autolock _l(mLock);
712783b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent    mTracks.add(record);
712883b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent}
712983b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent
713083b8808faad1e91690c64d7007348be8d9ebde73Eric Laurentvoid AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
713183b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent{
713283b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent    Mutex::Autolock _l(mLock);
713383b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent    destroyTrack_l(record);
713483b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent}
713583b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent
713683b8808faad1e91690c64d7007348be8d9ebde73Eric Laurentvoid AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
713783b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent{
713883b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent    ThreadBase::getAudioPortConfig(config);
713983b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent    config->role = AUDIO_PORT_ROLE_SINK;
714083b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent    config->ext.mix.hw_module = mInput->audioHwDev->handle();
714183b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent    config->ext.mix.usecase.source = mAudioSource;
714283b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent}
71431c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent
714463238efb0d674758902918e3cdaac322126484b7Glenn Kasten} // namespace android
7145