Threads.cpp revision 97a893eb34f8687485c88eaf15917974a203f20b
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"
5981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#include "FastMixer.h"
606dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten#include "FastCapture.h"
6181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#include "ServiceUtilities.h"
6281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#include "SchedulingPolicyService.h"
6381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
6481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#ifdef ADD_BATTERY_DATA
6581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#include <media/IMediaPlayerService.h>
6681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#include <media/IMediaDeathNotifier.h>
6781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#endif
6881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
6981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#ifdef DEBUG_CPU_USAGE
7081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#include <cpustats/CentralTendencyStatistics.h>
7181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#include <cpustats/ThreadCpuUsage.h>
7281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#endif
7381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
7481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// ----------------------------------------------------------------------------
7581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
7681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// Note: the following macro is used for extremely verbose logging message.  In
7781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
7881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// 0; but one side effect of this is to turn all LOGV's as well.  Some messages
7981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// are so verbose that we want to suppress them even when we have ALOG_ASSERT
8081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// turned on.  Do not uncomment the #def below unless you really know what you
8181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// are doing and want to see all of the extremely verbose messages.
8281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent//#define VERY_VERY_VERBOSE_LOGGING
8381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#ifdef VERY_VERY_VERBOSE_LOGGING
8481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#define ALOGVV ALOGV
8581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#else
8681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#define ALOGVV(a...) do { } while(0)
8781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#endif
8881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
8949d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten#define max(a, b) ((a) > (b) ? (a) : (b))
9049d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten
9181784c37c61b09289654b979567a42bf73cd2b12Eric Laurentnamespace android {
9281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
9381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// retry counts for buffer fill timeout
9481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// 50 * ~20msecs = 1 second
9581784c37c61b09289654b979567a42bf73cd2b12Eric Laurentstatic const int8_t kMaxTrackRetries = 50;
9681784c37c61b09289654b979567a42bf73cd2b12Eric Laurentstatic const int8_t kMaxTrackStartupRetries = 50;
9781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// allow less retry attempts on direct output thread.
9881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// direct outputs can be a scarce resource in audio hardware and should
9981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// be released as quickly as possible.
10081784c37c61b09289654b979567a42bf73cd2b12Eric Laurentstatic const int8_t kMaxTrackRetriesDirect = 2;
10181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
10281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// don't warn about blocked writes or record buffer overflows more often than this
10381784c37c61b09289654b979567a42bf73cd2b12Eric Laurentstatic const nsecs_t kWarningThrottleNs = seconds(5);
10481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
10581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// RecordThread loop sleep time upon application overrun or audio HAL read error
10681784c37c61b09289654b979567a42bf73cd2b12Eric Laurentstatic const int kRecordThreadSleepUs = 5000;
10781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
1081035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent// maximum time to wait in sendConfigEvent_l() for a status to be received
1091035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurentstatic const nsecs_t kConfigEventTimeoutNs = seconds(2);
11081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
11181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// minimum sleep time for the mixer thread loop when tracks are active but in underrun
11281784c37c61b09289654b979567a42bf73cd2b12Eric Laurentstatic const uint32_t kMinThreadSleepTimeUs = 5000;
11381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// maximum divider applied to the active sleep time in the mixer thread loop
11481784c37c61b09289654b979567a42bf73cd2b12Eric Laurentstatic const uint32_t kMaxThreadSleepTimeShift = 2;
11581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
11609a5007b17acb49d25cfa386a2e2534d942e8854Andy Hung// minimum normal sink buffer size, expressed in milliseconds rather than frames
11709a5007b17acb49d25cfa386a2e2534d942e8854Andy Hungstatic const uint32_t kMinNormalSinkBufferSizeMs = 20;
11809a5007b17acb49d25cfa386a2e2534d942e8854Andy Hung// maximum normal sink buffer size
11909a5007b17acb49d25cfa386a2e2534d942e8854Andy Hungstatic const uint32_t kMaxNormalSinkBufferSizeMs = 24;
12081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
121972a173d7d1de1a3b5a617aae3e2abb6e05ae02dEric Laurent// Offloaded output thread standby delay: allows track transition without going to standby
122972a173d7d1de1a3b5a617aae3e2abb6e05ae02dEric Laurentstatic const nsecs_t kOffloadStandbyDelayNs = seconds(1);
123972a173d7d1de1a3b5a617aae3e2abb6e05ae02dEric Laurent
12481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// Whether to use fast mixer
12581784c37c61b09289654b979567a42bf73cd2b12Eric Laurentstatic const enum {
12681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    FastMixer_Never,    // never initialize or use: for debugging only
12781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    FastMixer_Always,   // always initialize and use, even if not needed: for debugging only
12881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                        // normal mixer multiplier is 1
12981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    FastMixer_Static,   // initialize if needed, then use all the time if initialized,
13081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                        // multiplier is calculated based on min & max normal mixer buffer size
13181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    FastMixer_Dynamic,  // initialize if needed, then use dynamically depending on track load,
13281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                        // multiplier is calculated based on min & max normal mixer buffer size
13381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // FIXME for FastMixer_Dynamic:
13481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    //  Supporting this option will require fixing HALs that can't handle large writes.
13581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    //  For example, one HAL implementation returns an error from a large write,
13681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    //  and another HAL implementation corrupts memory, possibly in the sample rate converter.
13781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    //  We could either fix the HAL implementations, or provide a wrapper that breaks
13881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    //  up large writes into smaller ones, and the wrapper would need to deal with scheduler.
13981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent} kUseFastMixer = FastMixer_Static;
14081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
1416dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten// Whether to use fast capture
1426dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kastenstatic const enum {
1436dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    FastCapture_Never,  // never initialize or use: for debugging only
1446dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    FastCapture_Always, // always initialize and use, even if not needed: for debugging only
1456dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    FastCapture_Static, // initialize if needed, then use all the time if initialized
1466dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten} kUseFastCapture = FastCapture_Static;
1476dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten
14881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// Priorities for requestPriority
14981784c37c61b09289654b979567a42bf73cd2b12Eric Laurentstatic const int kPriorityAudioApp = 2;
15081784c37c61b09289654b979567a42bf73cd2b12Eric Laurentstatic const int kPriorityFastMixer = 3;
1516dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kastenstatic const int kPriorityFastCapture = 3;
15281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
15381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
15481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// for the track.  The client then sub-divides this into smaller buffers for its use.
155b5fed68bcdd6f44424c9e4d12bfe9a3ff51bd62eGlenn Kasten// Currently the client uses N-buffering by default, but doesn't tell us about the value of N.
156b5fed68bcdd6f44424c9e4d12bfe9a3ff51bd62eGlenn Kasten// So for now we just assume that client is double-buffered for fast tracks.
157b5fed68bcdd6f44424c9e4d12bfe9a3ff51bd62eGlenn Kasten// FIXME It would be better for client to tell AudioFlinger the value of N,
158b5fed68bcdd6f44424c9e4d12bfe9a3ff51bd62eGlenn Kasten// so AudioFlinger could allocate the right amount of memory.
15981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// See the client's minBufCount and mNotificationFramesAct calculations for details.
1600349009fd19f89f8414c428f6b71b369f7546085Glenn Kasten
1610349009fd19f89f8414c428f6b71b369f7546085Glenn Kasten// This is the default value, if not specified by property.
162b5fed68bcdd6f44424c9e4d12bfe9a3ff51bd62eGlenn Kastenstatic const int kFastTrackMultiplier = 2;
16381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
1640349009fd19f89f8414c428f6b71b369f7546085Glenn Kasten// The minimum and maximum allowed values
1650349009fd19f89f8414c428f6b71b369f7546085Glenn Kastenstatic const int kFastTrackMultiplierMin = 1;
1660349009fd19f89f8414c428f6b71b369f7546085Glenn Kastenstatic const int kFastTrackMultiplierMax = 2;
1670349009fd19f89f8414c428f6b71b369f7546085Glenn Kasten
1680349009fd19f89f8414c428f6b71b369f7546085Glenn Kasten// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
1690349009fd19f89f8414c428f6b71b369f7546085Glenn Kastenstatic int sFastTrackMultiplier = kFastTrackMultiplier;
1700349009fd19f89f8414c428f6b71b369f7546085Glenn Kasten
171b880f5e5fc07397ddd09a94ba18bdf4fa62aae00Glenn Kasten// See Thread::readOnlyHeap().
172b880f5e5fc07397ddd09a94ba18bdf4fa62aae00Glenn Kasten// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
173b880f5e5fc07397ddd09a94ba18bdf4fa62aae00Glenn Kasten// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
174b880f5e5fc07397ddd09a94ba18bdf4fa62aae00Glenn Kasten// and that all "fast" AudioRecord clients read from.  In either case, the size can be small.
1759f81de3452dfb2385bd57dc05456a045174a1ab1Glenn Kastenstatic const size_t kRecordThreadReadOnlyHeapSize = 0x2000;
176b880f5e5fc07397ddd09a94ba18bdf4fa62aae00Glenn Kasten
17781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// ----------------------------------------------------------------------------
17881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
1790349009fd19f89f8414c428f6b71b369f7546085Glenn Kastenstatic pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
1800349009fd19f89f8414c428f6b71b369f7546085Glenn Kasten
1810349009fd19f89f8414c428f6b71b369f7546085Glenn Kastenstatic void sFastTrackMultiplierInit()
1820349009fd19f89f8414c428f6b71b369f7546085Glenn Kasten{
1830349009fd19f89f8414c428f6b71b369f7546085Glenn Kasten    char value[PROPERTY_VALUE_MAX];
1840349009fd19f89f8414c428f6b71b369f7546085Glenn Kasten    if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
1850349009fd19f89f8414c428f6b71b369f7546085Glenn Kasten        char *endptr;
1860349009fd19f89f8414c428f6b71b369f7546085Glenn Kasten        unsigned long ul = strtoul(value, &endptr, 0);
1870349009fd19f89f8414c428f6b71b369f7546085Glenn Kasten        if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
1880349009fd19f89f8414c428f6b71b369f7546085Glenn Kasten            sFastTrackMultiplier = (int) ul;
1890349009fd19f89f8414c428f6b71b369f7546085Glenn Kasten        }
1900349009fd19f89f8414c428f6b71b369f7546085Glenn Kasten    }
1910349009fd19f89f8414c428f6b71b369f7546085Glenn Kasten}
1920349009fd19f89f8414c428f6b71b369f7546085Glenn Kasten
1930349009fd19f89f8414c428f6b71b369f7546085Glenn Kasten// ----------------------------------------------------------------------------
1940349009fd19f89f8414c428f6b71b369f7546085Glenn Kasten
19581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#ifdef ADD_BATTERY_DATA
19681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// To collect the amplifier usage
19781784c37c61b09289654b979567a42bf73cd2b12Eric Laurentstatic void addBatteryData(uint32_t params) {
19881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
19981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (service == NULL) {
20081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // it already logged
20181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        return;
20281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
20381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
20481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    service->addBatteryData(params);
20581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
20681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#endif
20781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
20881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
20981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// ----------------------------------------------------------------------------
21081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent//      CPU Stats
21181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// ----------------------------------------------------------------------------
21281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
21381784c37c61b09289654b979567a42bf73cd2b12Eric Laurentclass CpuStats {
21481784c37c61b09289654b979567a42bf73cd2b12Eric Laurentpublic:
21581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    CpuStats();
21681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    void sample(const String8 &title);
21781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#ifdef DEBUG_CPU_USAGE
21881784c37c61b09289654b979567a42bf73cd2b12Eric Laurentprivate:
21981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    ThreadCpuUsage mCpuUsage;           // instantaneous thread CPU usage in wall clock ns
22081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
22181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
22281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
22381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
22481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    int mCpuNum;                        // thread's current CPU number
22581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    int mCpukHz;                        // frequency of thread's current CPU in kHz
22681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#endif
22781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent};
22881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
22981784c37c61b09289654b979567a42bf73cd2b12Eric LaurentCpuStats::CpuStats()
23081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#ifdef DEBUG_CPU_USAGE
23181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    : mCpuNum(-1), mCpukHz(-1)
23281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#endif
23381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
23481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
23581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
2360f11b51a57bc9062c4fe8af73747319cedabc5d6Glenn Kastenvoid CpuStats::sample(const String8 &title
2370f11b51a57bc9062c4fe8af73747319cedabc5d6Glenn Kasten#ifndef DEBUG_CPU_USAGE
2380f11b51a57bc9062c4fe8af73747319cedabc5d6Glenn Kasten                __unused
2390f11b51a57bc9062c4fe8af73747319cedabc5d6Glenn Kasten#endif
2400f11b51a57bc9062c4fe8af73747319cedabc5d6Glenn Kasten        ) {
24181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#ifdef DEBUG_CPU_USAGE
24281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // get current thread's delta CPU time in wall clock ns
24381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    double wcNs;
24481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    bool valid = mCpuUsage.sampleAndEnable(wcNs);
24581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
24681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // record sample for wall clock statistics
24781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (valid) {
24881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mWcStats.sample(wcNs);
24981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
25081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
25181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // get the current CPU number
25281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    int cpuNum = sched_getcpu();
25381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
25481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // get the current CPU frequency in kHz
25581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    int cpukHz = mCpuUsage.getCpukHz(cpuNum);
25681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
25781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // check if either CPU number or frequency changed
25881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
25981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mCpuNum = cpuNum;
26081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mCpukHz = cpukHz;
26181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // ignore sample for purposes of cycles
26281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        valid = false;
26381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
26481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
26581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // if no change in CPU number or frequency, then record sample for cycle statistics
26681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (valid && mCpukHz > 0) {
26781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        double cycles = wcNs * cpukHz * 0.000001;
26881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mHzStats.sample(cycles);
26981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
27081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
27181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    unsigned n = mWcStats.n();
27281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // mCpuUsage.elapsed() is expensive, so don't call it every loop
27381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if ((n & 127) == 1) {
27481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        long long elapsed = mCpuUsage.elapsed();
27581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
27681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            double perLoop = elapsed / (double) n;
27781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            double perLoop100 = perLoop * 0.01;
27881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            double perLoop1k = perLoop * 0.001;
27981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            double mean = mWcStats.mean();
28081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            double stddev = mWcStats.stddev();
28181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            double minimum = mWcStats.minimum();
28281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            double maximum = mWcStats.maximum();
28381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            double meanCycles = mHzStats.mean();
28481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            double stddevCycles = mHzStats.stddev();
28581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            double minCycles = mHzStats.minimum();
28681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            double maxCycles = mHzStats.maximum();
28781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mCpuUsage.resetElapsed();
28881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mWcStats.reset();
28981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mHzStats.reset();
29081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            ALOGD("CPU usage for %s over past %.1f secs\n"
29181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                "  (%u mixer loops at %.1f mean ms per loop):\n"
29281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                "  us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
29381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                "  %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
29481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                "  MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
29581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    title.string(),
29681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    elapsed * .000000001, n, perLoop * .000001,
29781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    mean * .001,
29881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    stddev * .001,
29981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    minimum * .001,
30081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    maximum * .001,
30181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    mean / perLoop100,
30281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    stddev / perLoop100,
30381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    minimum / perLoop100,
30481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    maximum / perLoop100,
30581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    meanCycles / perLoop1k,
30681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    stddevCycles / perLoop1k,
30781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    minCycles / perLoop1k,
30881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    maxCycles / perLoop1k);
30981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
31081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
31181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
31281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#endif
31381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent};
31481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
31581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// ----------------------------------------------------------------------------
31681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent//      ThreadBase
31781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// ----------------------------------------------------------------------------
31881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
31997b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten// static
32097b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kastenconst char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
32197b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten{
32297b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    switch (type) {
32397b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    case MIXER:
32497b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten        return "MIXER";
32597b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    case DIRECT:
32697b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten        return "DIRECT";
32797b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    case DUPLICATING:
32897b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten        return "DUPLICATING";
32997b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    case RECORD:
33097b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten        return "RECORD";
33197b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    case OFFLOAD:
33297b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten        return "OFFLOAD";
33397b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    default:
33497b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten        return "unknown";
33597b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    }
33697b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten}
33797b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten
3380f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn KastenString8 devicesToString(audio_devices_t devices)
3390f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten{
3400f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    static const struct mapping {
3410f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        audio_devices_t mDevices;
3420f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        const char *    mString;
3430f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    } mappingsOut[] = {
3440f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        AUDIO_DEVICE_OUT_EARPIECE,          "EARPIECE",
3450f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        AUDIO_DEVICE_OUT_SPEAKER,           "SPEAKER",
3460f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        AUDIO_DEVICE_OUT_WIRED_HEADSET,     "WIRED_HEADSET",
3470f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        AUDIO_DEVICE_OUT_WIRED_HEADPHONE,   "WIRED_HEADPHONE",
3480f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        AUDIO_DEVICE_OUT_TELEPHONY_TX,      "TELEPHONY_TX",
3490f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        AUDIO_DEVICE_NONE,                  "NONE",         // must be last
3500f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    }, mappingsIn[] = {
3510f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        AUDIO_DEVICE_IN_BUILTIN_MIC,        "BUILTIN_MIC",
3520f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        AUDIO_DEVICE_IN_WIRED_HEADSET,      "WIRED_HEADSET",
3530f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        AUDIO_DEVICE_IN_VOICE_CALL,         "VOICE_CALL",
3540f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        AUDIO_DEVICE_IN_REMOTE_SUBMIX,      "REMOTE_SUBMIX",
3550f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        AUDIO_DEVICE_NONE,                  "NONE",         // must be last
3560f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    };
3570f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    String8 result;
3580f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    audio_devices_t allDevices = AUDIO_DEVICE_NONE;
3590f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    const mapping *entry;
3600f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    if (devices & AUDIO_DEVICE_BIT_IN) {
3610f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        devices &= ~AUDIO_DEVICE_BIT_IN;
3620f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        entry = mappingsIn;
3630f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    } else {
3640f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        entry = mappingsOut;
3650f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    }
3660f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    for ( ; entry->mDevices != AUDIO_DEVICE_NONE; entry++) {
3670f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        allDevices = (audio_devices_t) (allDevices | entry->mDevices);
3680f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        if (devices & entry->mDevices) {
3690f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten            if (!result.isEmpty()) {
3700f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten                result.append("|");
3710f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten            }
3720f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten            result.append(entry->mString);
3730f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        }
3740f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    }
3750f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    if (devices & ~allDevices) {
3760f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        if (!result.isEmpty()) {
3770f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten            result.append("|");
3780f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        }
3790f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        result.appendFormat("0x%X", devices & ~allDevices);
3800f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    }
3810f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    if (result.isEmpty()) {
3820f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        result.append(entry->mString);
3830f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    }
3840f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    return result;
3850f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten}
3860f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten
3870f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn KastenString8 inputFlagsToString(audio_input_flags_t flags)
3880f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten{
3890f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    static const struct mapping {
3900f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        audio_input_flags_t     mFlag;
3910f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        const char *            mString;
3920f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    } mappings[] = {
3930f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        AUDIO_INPUT_FLAG_FAST,              "FAST",
3940f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        AUDIO_INPUT_FLAG_HW_HOTWORD,        "HW_HOTWORD",
3950f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        AUDIO_INPUT_FLAG_NONE,              "NONE",         // must be last
3960f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    };
3970f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    String8 result;
3980f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    audio_input_flags_t allFlags = AUDIO_INPUT_FLAG_NONE;
3990f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    const mapping *entry;
4000f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    for (entry = mappings; entry->mFlag != AUDIO_INPUT_FLAG_NONE; entry++) {
4010f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        allFlags = (audio_input_flags_t) (allFlags | entry->mFlag);
4020f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        if (flags & entry->mFlag) {
4030f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten            if (!result.isEmpty()) {
4040f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten                result.append("|");
4050f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten            }
4060f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten            result.append(entry->mString);
4070f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        }
4080f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    }
4090f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    if (flags & ~allFlags) {
4100f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        if (!result.isEmpty()) {
4110f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten            result.append("|");
4120f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        }
4130f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        result.appendFormat("0x%X", flags & ~allFlags);
4140f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    }
4150f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    if (result.isEmpty()) {
4160f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten        result.append(entry->mString);
4170f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    }
4180f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    return result;
4190f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten}
4200f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten
4210f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn KastenString8 outputFlagsToString(audio_output_flags_t flags)
42297b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten{
42397b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    static const struct mapping {
42497b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten        audio_output_flags_t    mFlag;
42597b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten        const char *            mString;
42697b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    } mappings[] = {
42797b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten        AUDIO_OUTPUT_FLAG_DIRECT,           "DIRECT",
42897b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten        AUDIO_OUTPUT_FLAG_PRIMARY,          "PRIMARY",
42997b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten        AUDIO_OUTPUT_FLAG_FAST,             "FAST",
43097b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten        AUDIO_OUTPUT_FLAG_DEEP_BUFFER,      "DEEP_BUFFER",
431dfb0e115d827887e2f56a8877fe41b256d24360eGlenn Kasten        AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD, "COMPRESS_OFFLOAD",
43297b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten        AUDIO_OUTPUT_FLAG_NON_BLOCKING,     "NON_BLOCKING",
43397b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten        AUDIO_OUTPUT_FLAG_HW_AV_SYNC,       "HW_AV_SYNC",
43497b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten        AUDIO_OUTPUT_FLAG_NONE,             "NONE",         // must be last
43597b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    };
43697b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    String8 result;
43797b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    audio_output_flags_t allFlags = AUDIO_OUTPUT_FLAG_NONE;
43897b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    const mapping *entry;
43997b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    for (entry = mappings; entry->mFlag != AUDIO_OUTPUT_FLAG_NONE; entry++) {
44097b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten        allFlags = (audio_output_flags_t) (allFlags | entry->mFlag);
44197b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten        if (flags & entry->mFlag) {
44297b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten            if (!result.isEmpty()) {
44397b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten                result.append("|");
44497b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten            }
44597b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten            result.append(entry->mString);
44697b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten        }
44797b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    }
44897b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    if (flags & ~allFlags) {
44997b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten        if (!result.isEmpty()) {
45097b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten            result.append("|");
45197b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten        }
45297b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten        result.appendFormat("0x%X", flags & ~allFlags);
45397b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    }
45497b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    if (result.isEmpty()) {
45597b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten        result.append(entry->mString);
45697b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    }
45797b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    return result;
45897b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten}
45997b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten
4600f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kastenconst char *sourceToString(audio_source_t source)
4610f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten{
4620f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    switch (source) {
4630f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    case AUDIO_SOURCE_DEFAULT:              return "default";
4640f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    case AUDIO_SOURCE_MIC:                  return "mic";
4650f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    case AUDIO_SOURCE_VOICE_UPLINK:         return "voice uplink";
4660f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    case AUDIO_SOURCE_VOICE_DOWNLINK:       return "voice downlink";
4670f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    case AUDIO_SOURCE_VOICE_CALL:           return "voice call";
4680f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    case AUDIO_SOURCE_CAMCORDER:            return "camcorder";
4690f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    case AUDIO_SOURCE_VOICE_RECOGNITION:    return "voice recognition";
4700f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    case AUDIO_SOURCE_VOICE_COMMUNICATION:  return "voice communication";
4710f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    case AUDIO_SOURCE_REMOTE_SUBMIX:        return "remote submix";
4720f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    case AUDIO_SOURCE_FM_TUNER:             return "FM tuner";
4730f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    case AUDIO_SOURCE_HOTWORD:              return "hotword";
4740f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    default:                                return "unknown";
4750f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten    }
4760f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten}
4770f5b562737d6b5457aa83a4fdce9c6fb32584d9dGlenn Kasten
47881784c37c61b09289654b979567a42bf73cd2b12Eric LaurentAudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
47981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        audio_devices_t outDevice, audio_devices_t inDevice, type_t type)
48081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    :   Thread(false /*canCallJava*/),
48181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mType(type),
4829b58f63e45ef2fdfb839b9b9bb3411d81eb96128Glenn Kasten        mAudioFlinger(audioFlinger),
48370949c47fbae3f836d15f040551d7631be3ed7c2Glenn Kasten        // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
484deca2ae0a7cf8bc54ff3f30b7dc39bbc78b94c0dGlenn Kasten        // are set by PlaybackThread::readOutputParameters_l() or
485deca2ae0a7cf8bc54ff3f30b7dc39bbc78b94c0dGlenn Kasten        // RecordThread::readInputParameters_l()
486fd4779740ec3e9e865d5514464df26d015354388Eric Laurent        //FIXME: mStandby should be true here. Is this some kind of hack?
48781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
48881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
48981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // mName will be set by concrete (non-virtual) subclass
49081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mDeathRecipient(new PMDeathRecipient(this))
49181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
49281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
49381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
49481784c37c61b09289654b979567a42bf73cd2b12Eric LaurentAudioFlinger::ThreadBase::~ThreadBase()
49581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
496c6ae3c8a261794fd4445e4e152d1ada074a3f92fGlenn Kasten    // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
497c6ae3c8a261794fd4445e4e152d1ada074a3f92fGlenn Kasten    mConfigEvents.clear();
498c6ae3c8a261794fd4445e4e152d1ada074a3f92fGlenn Kasten
49981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // do not lock the mutex in destructor
50081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    releaseWakeLock_l();
50181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (mPowerManager != 0) {
50206b46062d2f8bc82ca3061a23d197734ae51918bMarco Nelissen        sp<IBinder> binder = IInterface::asBinder(mPowerManager);
50381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        binder->unlinkToDeath(mDeathRecipient);
50481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
50581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
50681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
507cf04c2cb8e031acc03c1c91cb1ccab15098c89b6Glenn Kastenstatus_t AudioFlinger::ThreadBase::readyToRun()
508cf04c2cb8e031acc03c1c91cb1ccab15098c89b6Glenn Kasten{
509cf04c2cb8e031acc03c1c91cb1ccab15098c89b6Glenn Kasten    status_t status = initCheck();
510cf04c2cb8e031acc03c1c91cb1ccab15098c89b6Glenn Kasten    if (status == NO_ERROR) {
511cf04c2cb8e031acc03c1c91cb1ccab15098c89b6Glenn Kasten        ALOGI("AudioFlinger's thread %p ready to run", this);
512cf04c2cb8e031acc03c1c91cb1ccab15098c89b6Glenn Kasten    } else {
513cf04c2cb8e031acc03c1c91cb1ccab15098c89b6Glenn Kasten        ALOGE("No working audio driver found.");
514cf04c2cb8e031acc03c1c91cb1ccab15098c89b6Glenn Kasten    }
515cf04c2cb8e031acc03c1c91cb1ccab15098c89b6Glenn Kasten    return status;
516cf04c2cb8e031acc03c1c91cb1ccab15098c89b6Glenn Kasten}
517cf04c2cb8e031acc03c1c91cb1ccab15098c89b6Glenn Kasten
51881784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::ThreadBase::exit()
51981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
52081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    ALOGV("ThreadBase::exit");
52181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // do any cleanup required for exit to succeed
52281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    preExit();
52381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    {
52481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // This lock prevents the following race in thread (uniprocessor for illustration):
52581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        //  if (!exitPending()) {
52681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        //      // context switch from here to exit()
52781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        //      // exit() calls requestExit(), what exitPending() observes
52881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        //      // exit() calls signal(), which is dropped since no waiters
52981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        //      // context switch back from exit() to here
53081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        //      mWaitWorkCV.wait(...);
53181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        //      // now thread is hung
53281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        //  }
53381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        AutoMutex lock(mLock);
53481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        requestExit();
53581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mWaitWorkCV.broadcast();
53681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
53781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // When Thread::requestExitAndWait is made virtual and this method is renamed to
53881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
53981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    requestExitAndWait();
54081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
54181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
54281784c37c61b09289654b979567a42bf73cd2b12Eric Laurentstatus_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
54381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
54481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    status_t status;
54581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
54681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
54781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
54881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
5491035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    return sendSetParameterConfigEvent_l(keyValuePairs);
5501035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent}
5511035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent
5521035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent// sendConfigEvent_l() must be called with ThreadBase::mLock held
5531035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
5541035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurentstatus_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
5551035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent{
5561035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    status_t status = NO_ERROR;
5571035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent
5581035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    mConfigEvents.add(event);
5591035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    ALOGV("sendConfigEvent_l() num events %d event %d", mConfigEvents.size(), event->mType);
56081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mWaitWorkCV.signal();
5611035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    mLock.unlock();
5621035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    {
5631035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        Mutex::Autolock _l(event->mLock);
5641035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        while (event->mWaitStatus) {
5651035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
5661035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                event->mStatus = TIMED_OUT;
5671035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                event->mWaitStatus = false;
5681035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            }
5691035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        }
5701035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        status = event->mStatus;
57181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
5721035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    mLock.lock();
57381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return status;
57481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
57581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
57681784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param)
57781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
57881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
57981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    sendIoConfigEvent_l(event, param);
58081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
58181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
58281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
58381784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param)
58481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
5851035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, param);
5861035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    sendConfigEvent_l(configEvent);
58781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
58881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
58981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
59081784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
59181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
5921035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
5931035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    sendConfigEvent_l(configEvent);
59481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
59581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
5961035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
5971035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurentstatus_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
59881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
5991035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    sp<ConfigEvent> configEvent = (ConfigEvent *)new SetParameterConfigEvent(keyValuePair);
6001035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    return sendConfigEvent_l(configEvent);
601f777331418a86cd9fd709af898ef24a69967aeb4Glenn Kasten}
602f777331418a86cd9fd709af898ef24a69967aeb4Glenn Kasten
6031c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurentstatus_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
6041c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent                                                        const struct audio_patch *patch,
6051c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent                                                        audio_patch_handle_t *handle)
6061c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent{
6071c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent    Mutex::Autolock _l(mLock);
6081c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent    sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
6091c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent    status_t status = sendConfigEvent_l(configEvent);
6101c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent    if (status == NO_ERROR) {
6111c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent        CreateAudioPatchConfigEventData *data =
6121c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent                                        (CreateAudioPatchConfigEventData *)configEvent->mData.get();
6131c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent        *handle = data->mHandle;
6141c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent    }
6151c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent    return status;
6161c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent}
6171c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent
6181c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurentstatus_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
6191c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent                                                                const audio_patch_handle_t handle)
6201c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent{
6211c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent    Mutex::Autolock _l(mLock);
6221c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent    sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
6231c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent    return sendConfigEvent_l(configEvent);
6241c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent}
6251c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent
6261c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent
6272cfbf88b89854f30b295e8ae26a031edb8d712f8Glenn Kasten// post condition: mConfigEvents.isEmpty()
628021cf9634ab09c0753a40b7c9ef4ba603be5c3daEric Laurentvoid AudioFlinger::ThreadBase::processConfigEvents_l()
629f777331418a86cd9fd709af898ef24a69967aeb4Glenn Kasten{
6301035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    bool configChanged = false;
6311035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent
63281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    while (!mConfigEvents.isEmpty()) {
6331035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        ALOGV("processConfigEvents_l() remaining events %d", mConfigEvents.size());
6341035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        sp<ConfigEvent> event = mConfigEvents[0];
63581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mConfigEvents.removeAt(0);
6361035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        switch (event->mType) {
6373468e8a4d79cc6a7bb0f03f8382426195bed44dfGlenn Kasten        case CFG_EVENT_PRIO: {
6381035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
6391035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            // FIXME Need to understand why this has to be done asynchronously
6401035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            int err = requestPriority(data->mPid, data->mTid, data->mPrio,
6413468e8a4d79cc6a7bb0f03f8382426195bed44dfGlenn Kasten                    true /*asynchronous*/);
6423468e8a4d79cc6a7bb0f03f8382426195bed44dfGlenn Kasten            if (err != 0) {
6433468e8a4d79cc6a7bb0f03f8382426195bed44dfGlenn Kasten                ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
6441035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                      data->mPrio, data->mPid, data->mTid, err);
6453468e8a4d79cc6a7bb0f03f8382426195bed44dfGlenn Kasten            }
6463468e8a4d79cc6a7bb0f03f8382426195bed44dfGlenn Kasten        } break;
6473468e8a4d79cc6a7bb0f03f8382426195bed44dfGlenn Kasten        case CFG_EVENT_IO: {
6481035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
649021cf9634ab09c0753a40b7c9ef4ba603be5c3daEric Laurent            audioConfigChanged(data->mEvent, data->mParam);
6501035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        } break;
6511035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        case CFG_EVENT_SET_PARAMETER: {
6521035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
6531035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
6541035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                configChanged = true;
655d5418eb594435c958d6c37fa9938161a0112adbdGlenn Kasten            }
6563468e8a4d79cc6a7bb0f03f8382426195bed44dfGlenn Kasten        } break;
6571c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent        case CFG_EVENT_CREATE_AUDIO_PATCH: {
6581c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent            CreateAudioPatchConfigEventData *data =
6591c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent                                            (CreateAudioPatchConfigEventData *)event->mData.get();
6601c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent            event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
6611c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent        } break;
6621c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent        case CFG_EVENT_RELEASE_AUDIO_PATCH: {
6631c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent            ReleaseAudioPatchConfigEventData *data =
6641c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent                                            (ReleaseAudioPatchConfigEventData *)event->mData.get();
6651c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent            event->mStatus = releaseAudioPatch_l(data->mHandle);
6661c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent        } break;
6673468e8a4d79cc6a7bb0f03f8382426195bed44dfGlenn Kasten        default:
6681035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
6693468e8a4d79cc6a7bb0f03f8382426195bed44dfGlenn Kasten            break;
67081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
6711035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        {
6721035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            Mutex::Autolock _l(event->mLock);
6731035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            if (event->mWaitStatus) {
6741035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                event->mWaitStatus = false;
6751035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                event->mCond.signal();
6761035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            }
6771035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        }
6781035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
6791035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    }
6801035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent
6811035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    if (configChanged) {
6821035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        cacheParameters_l();
68381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
68481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
68581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
686b220884bf3129253cc5bc8d030bc475411ea4911Marco NelissenString8 channelMaskToString(audio_channel_mask_t mask, bool output) {
687b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen    String8 s;
688b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen    if (output) {
689b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
690b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
691b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
692b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
693b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
694b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
695b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
696b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
697b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
698b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
699b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
700b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
701b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
702b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
703b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
704b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
705b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
706b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
707b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown,  ");
708b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen    } else {
709b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
710b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
711b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
712b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
713b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
714b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
715b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
716b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
717b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
718b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
719b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
720b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
721b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
722b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
723b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown,  ");
724b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen    }
725b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen    int len = s.length();
726b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen    if (s.length() > 2) {
727b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        char *str = s.lockBuffer(len);
728b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        s.unlockBuffer(len - 2);
729b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen    }
730b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen    return s;
731b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen}
732b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen
7330f11b51a57bc9062c4fe8af73747319cedabc5d6Glenn Kastenvoid AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
73481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
73581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    const size_t SIZE = 256;
73681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    char buffer[SIZE];
73781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    String8 result;
73881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
73981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    bool locked = AudioFlinger::dumpTryLock(mLock);
74081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (!locked) {
74197b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten        dprintf(fd, "thread %p may be deadlocked\n", this);
742b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen    }
743b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen
7440b89bc0d285b8fd4798df1ff0ba9f93851a3bd48Glenn Kasten    dprintf(fd, "  Thread name: %s\n", mThreadName);
74587cebadd48710e42474756fc3513df678de045ceElliott Hughes    dprintf(fd, "  I/O handle: %d\n", mId);
74687cebadd48710e42474756fc3513df678de045ceElliott Hughes    dprintf(fd, "  TID: %d\n", getTid());
74787cebadd48710e42474756fc3513df678de045ceElliott Hughes    dprintf(fd, "  Standby: %s\n", mStandby ? "yes" : "no");
74897b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    dprintf(fd, "  Sample rate: %u Hz\n", mSampleRate);
74987cebadd48710e42474756fc3513df678de045ceElliott Hughes    dprintf(fd, "  HAL frame count: %zu\n", mFrameCount);
75097b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    dprintf(fd, "  HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat));
75187cebadd48710e42474756fc3513df678de045ceElliott Hughes    dprintf(fd, "  HAL buffer size: %u bytes\n", mBufferSize);
75297b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    dprintf(fd, "  Channel count: %u\n", mChannelCount);
75397b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    dprintf(fd, "  Channel mask: 0x%08x (%s)\n", mChannelMask,
754b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen            channelMaskToString(mChannelMask, mType != RECORD).string());
75597b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    dprintf(fd, "  Format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
75697b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    dprintf(fd, "  Frame size: %zu bytes\n", mFrameSize);
75787cebadd48710e42474756fc3513df678de045ceElliott Hughes    dprintf(fd, "  Pending config events:");
758b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen    size_t numConfig = mConfigEvents.size();
759b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen    if (numConfig) {
760b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        for (size_t i = 0; i < numConfig; i++) {
761b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen            mConfigEvents[i]->dump(buffer, SIZE);
76287cebadd48710e42474756fc3513df678de045ceElliott Hughes            dprintf(fd, "\n    %s", buffer);
763b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        }
76487cebadd48710e42474756fc3513df678de045ceElliott Hughes        dprintf(fd, "\n");
765b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen    } else {
76687cebadd48710e42474756fc3513df678de045ceElliott Hughes        dprintf(fd, " none\n");
76781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
7680b89bc0d285b8fd4798df1ff0ba9f93851a3bd48Glenn Kasten    dprintf(fd, "  Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).string());
7690b89bc0d285b8fd4798df1ff0ba9f93851a3bd48Glenn Kasten    dprintf(fd, "  Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).string());
7700b89bc0d285b8fd4798df1ff0ba9f93851a3bd48Glenn Kasten    dprintf(fd, "  Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
77181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
77281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (locked) {
77381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mLock.unlock();
77481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
77581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
77681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
77781784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
77881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
77981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    const size_t SIZE = 256;
78081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    char buffer[SIZE];
78181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    String8 result;
78281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
783b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen    size_t numEffectChains = mEffectChains.size();
7841d6fa7af1288b550faabe4ec2cf98684236723dbNarayan Kamath    snprintf(buffer, SIZE, "  %zu Effect Chains\n", numEffectChains);
78581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    write(fd, buffer, strlen(buffer));
78681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
787b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen    for (size_t i = 0; i < numEffectChains; ++i) {
78881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sp<EffectChain> chain = mEffectChains[i];
78981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (chain != 0) {
79081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            chain->dump(fd, args);
79181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
79281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
79381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
79481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
795e14a5d6d2cc91dd2fc09ffdf7aa670b37da0795dMarco Nelissenvoid AudioFlinger::ThreadBase::acquireWakeLock(int uid)
79681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
79781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
798e14a5d6d2cc91dd2fc09ffdf7aa670b37da0795dMarco Nelissen    acquireWakeLock_l(uid);
79981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
80081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
801014e7fa2e90827d911c37bb0ce4d2e10e14d0bb3Narayan KamathString16 AudioFlinger::ThreadBase::getWakeLockTag()
802014e7fa2e90827d911c37bb0ce4d2e10e14d0bb3Narayan Kamath{
803014e7fa2e90827d911c37bb0ce4d2e10e14d0bb3Narayan Kamath    switch (mType) {
804bcb1486d052e329ae4790d93055d1c51017286c3Glenn Kasten    case MIXER:
805bcb1486d052e329ae4790d93055d1c51017286c3Glenn Kasten        return String16("AudioMix");
806bcb1486d052e329ae4790d93055d1c51017286c3Glenn Kasten    case DIRECT:
807bcb1486d052e329ae4790d93055d1c51017286c3Glenn Kasten        return String16("AudioDirectOut");
808bcb1486d052e329ae4790d93055d1c51017286c3Glenn Kasten    case DUPLICATING:
809bcb1486d052e329ae4790d93055d1c51017286c3Glenn Kasten        return String16("AudioDup");
810bcb1486d052e329ae4790d93055d1c51017286c3Glenn Kasten    case RECORD:
811bcb1486d052e329ae4790d93055d1c51017286c3Glenn Kasten        return String16("AudioIn");
812bcb1486d052e329ae4790d93055d1c51017286c3Glenn Kasten    case OFFLOAD:
813bcb1486d052e329ae4790d93055d1c51017286c3Glenn Kasten        return String16("AudioOffload");
814bcb1486d052e329ae4790d93055d1c51017286c3Glenn Kasten    default:
815bcb1486d052e329ae4790d93055d1c51017286c3Glenn Kasten        ALOG_ASSERT(false);
816bcb1486d052e329ae4790d93055d1c51017286c3Glenn Kasten        return String16("AudioUnknown");
817014e7fa2e90827d911c37bb0ce4d2e10e14d0bb3Narayan Kamath    }
818014e7fa2e90827d911c37bb0ce4d2e10e14d0bb3Narayan Kamath}
819014e7fa2e90827d911c37bb0ce4d2e10e14d0bb3Narayan Kamath
820e14a5d6d2cc91dd2fc09ffdf7aa670b37da0795dMarco Nelissenvoid AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
82181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
822462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen    getPowerManager_l();
82381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (mPowerManager != 0) {
82481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sp<IBinder> binder = new BBinder();
825e14a5d6d2cc91dd2fc09ffdf7aa670b37da0795dMarco Nelissen        status_t status;
826e14a5d6d2cc91dd2fc09ffdf7aa670b37da0795dMarco Nelissen        if (uid >= 0) {
827547789d25dc6bd6561553bcf6b384fb0d4fee834Eric Laurent            status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
828e14a5d6d2cc91dd2fc09ffdf7aa670b37da0795dMarco Nelissen                    binder,
829014e7fa2e90827d911c37bb0ce4d2e10e14d0bb3Narayan Kamath                    getWakeLockTag(),
830e14a5d6d2cc91dd2fc09ffdf7aa670b37da0795dMarco Nelissen                    String16("media"),
8313abc2ded40066f3b1df23aceb553f22d569c5cd3Glenn Kasten                    uid,
8323abc2ded40066f3b1df23aceb553f22d569c5cd3Glenn Kasten                    true /* FIXME force oneway contrary to .aidl */);
833e14a5d6d2cc91dd2fc09ffdf7aa670b37da0795dMarco Nelissen        } else {
834547789d25dc6bd6561553bcf6b384fb0d4fee834Eric Laurent            status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
835e14a5d6d2cc91dd2fc09ffdf7aa670b37da0795dMarco Nelissen                    binder,
836014e7fa2e90827d911c37bb0ce4d2e10e14d0bb3Narayan Kamath                    getWakeLockTag(),
8373abc2ded40066f3b1df23aceb553f22d569c5cd3Glenn Kasten                    String16("media"),
8383abc2ded40066f3b1df23aceb553f22d569c5cd3Glenn Kasten                    true /* FIXME force oneway contrary to .aidl */);
839e14a5d6d2cc91dd2fc09ffdf7aa670b37da0795dMarco Nelissen        }
84081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (status == NO_ERROR) {
84181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mWakeLockToken = binder;
84281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
843d7dca050c630bddbd73a6623271b34b4290460eeGlenn Kasten        ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
84481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
84581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
84681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
84781784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::ThreadBase::releaseWakeLock()
84881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
84981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
85081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    releaseWakeLock_l();
85181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
85281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
85381784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::ThreadBase::releaseWakeLock_l()
85481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
85581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (mWakeLockToken != 0) {
856d7dca050c630bddbd73a6623271b34b4290460eeGlenn Kasten        ALOGV("releaseWakeLock_l() %s", mThreadName);
85781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (mPowerManager != 0) {
8583abc2ded40066f3b1df23aceb553f22d569c5cd3Glenn Kasten            mPowerManager->releaseWakeLock(mWakeLockToken, 0,
8593abc2ded40066f3b1df23aceb553f22d569c5cd3Glenn Kasten                    true /* FIXME force oneway contrary to .aidl */);
86081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
86181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mWakeLockToken.clear();
86281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
86381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
86481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
865462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissenvoid AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
866462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen    Mutex::Autolock _l(mLock);
867462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen    updateWakeLockUids_l(uids);
868462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen}
869462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen
870462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissenvoid AudioFlinger::ThreadBase::getPowerManager_l() {
871462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen
872462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen    if (mPowerManager == 0) {
873462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen        // use checkService() to avoid blocking if power service is not up yet
874462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen        sp<IBinder> binder =
875462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen            defaultServiceManager()->checkService(String16("power"));
876462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen        if (binder == 0) {
877d7dca050c630bddbd73a6623271b34b4290460eeGlenn Kasten            ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
878462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen        } else {
879462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen            mPowerManager = interface_cast<IPowerManager>(binder);
880462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen            binder->linkToDeath(mDeathRecipient);
881462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen        }
882462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen    }
883462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen}
884462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen
885462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissenvoid AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
886462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen
887462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen    getPowerManager_l();
888462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen    if (mWakeLockToken == NULL) {
889462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen        ALOGE("no wake lock to update!");
890462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen        return;
891462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen    }
892462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen    if (mPowerManager != 0) {
893462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen        sp<IBinder> binder = new BBinder();
894462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen        status_t status;
8953abc2ded40066f3b1df23aceb553f22d569c5cd3Glenn Kasten        status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array(),
8963abc2ded40066f3b1df23aceb553f22d569c5cd3Glenn Kasten                    true /* FIXME force oneway contrary to .aidl */);
897d7dca050c630bddbd73a6623271b34b4290460eeGlenn Kasten        ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
898462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen    }
899462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen}
900462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen
90181784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::ThreadBase::clearPowerManager()
90281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
90381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
90481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    releaseWakeLock_l();
90581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mPowerManager.clear();
90681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
90781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
9080f11b51a57bc9062c4fe8af73747319cedabc5d6Glenn Kastenvoid AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
90981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
91081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    sp<ThreadBase> thread = mThread.promote();
91181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (thread != 0) {
91281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        thread->clearPowerManager();
91381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
91481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    ALOGW("power manager service died !!!");
91581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
91681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
91781784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::ThreadBase::setEffectSuspended(
91881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        const effect_uuid_t *type, bool suspend, int sessionId)
91981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
92081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
92181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    setEffectSuspended_l(type, suspend, sessionId);
92281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
92381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
92481784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::ThreadBase::setEffectSuspended_l(
92581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        const effect_uuid_t *type, bool suspend, int sessionId)
92681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
92781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    sp<EffectChain> chain = getEffectChain_l(sessionId);
92881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (chain != 0) {
92981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (type != NULL) {
93081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            chain->setEffectSuspended_l(type, suspend);
93181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        } else {
93281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            chain->setEffectSuspendedAll_l(suspend);
93381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
93481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
93581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
93681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    updateSuspendedSessions_l(type, suspend, sessionId);
93781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
93881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
93981784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
94081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
94181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
94281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (index < 0) {
94381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        return;
94481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
94581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
94681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
94781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mSuspendedSessions.valueAt(index);
94881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
94981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    for (size_t i = 0; i < sessionEffects.size(); i++) {
95081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
95181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        for (int j = 0; j < desc->mRefCount; j++) {
95281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
95381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                chain->setEffectSuspendedAll_l(true);
95481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            } else {
95581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
95681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    desc->mType.timeLow);
95781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                chain->setEffectSuspended_l(&desc->mType, true);
95881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
95981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
96081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
96181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
96281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
96381784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
96481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                                                         bool suspend,
96581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                                                         int sessionId)
96681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
96781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
96881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
96981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
97081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
97181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (suspend) {
97281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (index >= 0) {
97381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            sessionEffects = mSuspendedSessions.valueAt(index);
97481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        } else {
97581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mSuspendedSessions.add(sessionId, sessionEffects);
97681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
97781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    } else {
97881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (index < 0) {
97981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            return;
98081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
98181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sessionEffects = mSuspendedSessions.valueAt(index);
98281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
98381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
98481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
98581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    int key = EffectChain::kKeyForSuspendAll;
98681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (type != NULL) {
98781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        key = type->timeLow;
98881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
98981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    index = sessionEffects.indexOfKey(key);
99081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
99181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    sp<SuspendedSessionDesc> desc;
99281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (suspend) {
99381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (index >= 0) {
99481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            desc = sessionEffects.valueAt(index);
99581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        } else {
99681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            desc = new SuspendedSessionDesc();
99781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if (type != NULL) {
99881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                desc->mType = *type;
99981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
100081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            sessionEffects.add(key, desc);
100181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
100281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
100381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        desc->mRefCount++;
100481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    } else {
100581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (index < 0) {
100681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            return;
100781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
100881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        desc = sessionEffects.valueAt(index);
100981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (--desc->mRefCount == 0) {
101081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
101181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            sessionEffects.removeItemsAt(index);
101281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if (sessionEffects.isEmpty()) {
101381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                ALOGV("updateSuspendedSessions_l() restore removing session %d",
101481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                                 sessionId);
101581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                mSuspendedSessions.removeItem(sessionId);
101681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
101781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
101881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
101981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (!sessionEffects.isEmpty()) {
102081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
102181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
102281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
102381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
102481784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
102581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                                                            bool enabled,
102681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                                                            int sessionId)
102781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
102881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
102981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
103081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
103181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
103281784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
103381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                                                            bool enabled,
103481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                                                            int sessionId)
103581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
103681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (mType != RECORD) {
103781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
103881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // another session. This gives the priority to well behaved effect control panels
103981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // and applications not using global effects.
104081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
104181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // global effects
104281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
104381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
104481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
104581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
104681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
104781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    sp<EffectChain> chain = getEffectChain_l(sessionId);
104881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (chain != 0) {
104981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        chain->checkSuspendOnEffectEnabled(effect, enabled);
105081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
105181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
105281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
105381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
105481784c37c61b09289654b979567a42bf73cd2b12Eric Laurentsp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
105581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        const sp<AudioFlinger::Client>& client,
105681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        const sp<IEffectClient>& effectClient,
105781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        int32_t priority,
105881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        int sessionId,
105981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        effect_descriptor_t *desc,
106081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        int *enabled,
10619156ef3e11b68cc4b6d3cea77f1f63673855a6d1Glenn Kasten        status_t *status)
106281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
106381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    sp<EffectModule> effect;
106481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    sp<EffectHandle> handle;
106581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    status_t lStatus;
106681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    sp<EffectChain> chain;
106781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    bool chainCreated = false;
106881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    bool effectCreated = false;
106981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    bool effectRegistered = false;
107081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
107181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    lStatus = initCheck();
107281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (lStatus != NO_ERROR) {
107381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        ALOGW("createEffect_l() Audio driver not initialized.");
107481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        goto Exit;
107581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
107681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
107798ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung    // Reject any effect on Direct output threads for now, since the format of
107898ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung    // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
107998ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung    if (mType == DIRECT) {
108098ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung        ALOGW("createEffect_l() Cannot add effect %s on Direct output type thread %s",
1081d7dca050c630bddbd73a6623271b34b4290460eeGlenn Kasten                desc->name, mThreadName);
108298ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung        lStatus = BAD_VALUE;
108398ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung        goto Exit;
108498ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung    }
108598ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung
1086389cfdbb9a92a438a0d7710321c2964c7ad55ecaAndy Hung    // Reject any effect on mixer or duplicating multichannel sinks.
10879a59276fb465e492138e0576523b54079671e8f4Andy Hung    // TODO: fix both format and multichannel issues with effects.
1088389cfdbb9a92a438a0d7710321c2964c7ad55ecaAndy Hung    if ((mType == MIXER || mType == DUPLICATING) && mChannelCount != FCC_2) {
1089389cfdbb9a92a438a0d7710321c2964c7ad55ecaAndy Hung        ALOGW("createEffect_l() Cannot add effect %s for multichannel(%d) %s threads",
1090389cfdbb9a92a438a0d7710321c2964c7ad55ecaAndy Hung                desc->name, mChannelCount, mType == MIXER ? "MIXER" : "DUPLICATING");
10919a59276fb465e492138e0576523b54079671e8f4Andy Hung        lStatus = BAD_VALUE;
10929a59276fb465e492138e0576523b54079671e8f4Andy Hung        goto Exit;
10939a59276fb465e492138e0576523b54079671e8f4Andy Hung    }
10949a59276fb465e492138e0576523b54079671e8f4Andy Hung
10955baf2af52cd186633b7173196c1e4a4cd3435f22Eric Laurent    // Allow global effects only on offloaded and mixer threads
10965baf2af52cd186633b7173196c1e4a4cd3435f22Eric Laurent    if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
10975baf2af52cd186633b7173196c1e4a4cd3435f22Eric Laurent        switch (mType) {
10985baf2af52cd186633b7173196c1e4a4cd3435f22Eric Laurent        case MIXER:
10995baf2af52cd186633b7173196c1e4a4cd3435f22Eric Laurent        case OFFLOAD:
11005baf2af52cd186633b7173196c1e4a4cd3435f22Eric Laurent            break;
11015baf2af52cd186633b7173196c1e4a4cd3435f22Eric Laurent        case DIRECT:
11025baf2af52cd186633b7173196c1e4a4cd3435f22Eric Laurent        case DUPLICATING:
11035baf2af52cd186633b7173196c1e4a4cd3435f22Eric Laurent        case RECORD:
11045baf2af52cd186633b7173196c1e4a4cd3435f22Eric Laurent        default:
1105d7dca050c630bddbd73a6623271b34b4290460eeGlenn Kasten            ALOGW("createEffect_l() Cannot add global effect %s on thread %s",
1106d7dca050c630bddbd73a6623271b34b4290460eeGlenn Kasten                    desc->name, mThreadName);
11075baf2af52cd186633b7173196c1e4a4cd3435f22Eric Laurent            lStatus = BAD_VALUE;
11085baf2af52cd186633b7173196c1e4a4cd3435f22Eric Laurent            goto Exit;
11095baf2af52cd186633b7173196c1e4a4cd3435f22Eric Laurent        }
111081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
11115baf2af52cd186633b7173196c1e4a4cd3435f22Eric Laurent
111281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // Only Pre processor effects are allowed on input threads and only on input threads
111381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
111481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
111581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                desc->name, desc->flags, mType);
111681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        lStatus = BAD_VALUE;
111781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        goto Exit;
111881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
111981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
112081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
112181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
112281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    { // scope for mLock
112381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        Mutex::Autolock _l(mLock);
112481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
112581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // check for existing effect chain with the requested audio session
112681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        chain = getEffectChain_l(sessionId);
112781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (chain == 0) {
112881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // create a new chain for this session
112981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            ALOGV("createEffect_l() new effect chain for session %d", sessionId);
113081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            chain = new EffectChain(this, sessionId);
113181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            addEffectChain_l(chain);
113281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            chain->setStrategy(getStrategyForSession_l(sessionId));
113381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            chainCreated = true;
113481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        } else {
113581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            effect = chain->getEffectFromDesc_l(desc);
113681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
113781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
113881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
113981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
114081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (effect == 0) {
114181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            int id = mAudioFlinger->nextUniqueId();
114281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // Check CPU and memory usage
114381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
114481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if (lStatus != NO_ERROR) {
114581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                goto Exit;
114681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
114781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            effectRegistered = true;
114881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // create a new effect module if none present in the chain
114981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            effect = new EffectModule(this, chain, desc, id, sessionId);
115081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            lStatus = effect->status();
115181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if (lStatus != NO_ERROR) {
115281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                goto Exit;
115381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
11545baf2af52cd186633b7173196c1e4a4cd3435f22Eric Laurent            effect->setOffloaded(mType == OFFLOAD, mId);
11555baf2af52cd186633b7173196c1e4a4cd3435f22Eric Laurent
115681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            lStatus = chain->addEffect_l(effect);
115781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if (lStatus != NO_ERROR) {
115881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                goto Exit;
115981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
116081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            effectCreated = true;
116181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
116281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            effect->setDevice(mOutDevice);
116381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            effect->setDevice(mInDevice);
116481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            effect->setMode(mAudioFlinger->getMode());
116581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            effect->setAudioSource(mAudioSource);
116681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
116781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // create effect handle and connect it to effect module
116881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        handle = new EffectHandle(effect, client, effectClient, priority);
1169e75da4004b2c814987aa2adf8a76190f92d99c65Glenn Kasten        lStatus = handle->initCheck();
1170e75da4004b2c814987aa2adf8a76190f92d99c65Glenn Kasten        if (lStatus == OK) {
1171e75da4004b2c814987aa2adf8a76190f92d99c65Glenn Kasten            lStatus = effect->addHandle(handle.get());
1172e75da4004b2c814987aa2adf8a76190f92d99c65Glenn Kasten        }
117381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (enabled != NULL) {
117481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            *enabled = (int)effect->isEnabled();
117581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
117681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
117781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
117881784c37c61b09289654b979567a42bf73cd2b12Eric LaurentExit:
117981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
118081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        Mutex::Autolock _l(mLock);
118181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (effectCreated) {
118281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            chain->removeEffect_l(effect);
118381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
118481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (effectRegistered) {
118581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            AudioSystem::unregisterEffect(effect->id());
118681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
118781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (chainCreated) {
118881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            removeEffectChain_l(chain);
118981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
119081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        handle.clear();
119181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
119281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
11939156ef3e11b68cc4b6d3cea77f1f63673855a6d1Glenn Kasten    *status = lStatus;
119481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return handle;
119581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
119681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
119781784c37c61b09289654b979567a42bf73cd2b12Eric Laurentsp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
119881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
119981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
120081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return getEffect_l(sessionId, effectId);
120181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
120281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
120381784c37c61b09289654b979567a42bf73cd2b12Eric Laurentsp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
120481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
120581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    sp<EffectChain> chain = getEffectChain_l(sessionId);
120681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
120781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
120881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
120981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
121081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// PlaybackThread::mLock held
121181784c37c61b09289654b979567a42bf73cd2b12Eric Laurentstatus_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
121281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
121381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // check for existing effect chain with the requested audio session
121481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    int sessionId = effect->sessionId();
121581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    sp<EffectChain> chain = getEffectChain_l(sessionId);
121681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    bool chainCreated = false;
121781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
12185baf2af52cd186633b7173196c1e4a4cd3435f22Eric Laurent    ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
12195baf2af52cd186633b7173196c1e4a4cd3435f22Eric Laurent             "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
12205baf2af52cd186633b7173196c1e4a4cd3435f22Eric Laurent                    this, effect->desc().name, effect->desc().flags);
12215baf2af52cd186633b7173196c1e4a4cd3435f22Eric Laurent
122281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (chain == 0) {
122381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // create a new chain for this session
122481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        ALOGV("addEffect_l() new effect chain for session %d", sessionId);
122581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        chain = new EffectChain(this, sessionId);
122681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        addEffectChain_l(chain);
122781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        chain->setStrategy(getStrategyForSession_l(sessionId));
122881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        chainCreated = true;
122981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
123081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
123181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
123281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (chain->getEffectFromId_l(effect->id()) != 0) {
123381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        ALOGW("addEffect_l() %p effect %s already present in chain %p",
123481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                this, effect->desc().name, chain.get());
123581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        return BAD_VALUE;
123681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
123781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
12385baf2af52cd186633b7173196c1e4a4cd3435f22Eric Laurent    effect->setOffloaded(mType == OFFLOAD, mId);
12395baf2af52cd186633b7173196c1e4a4cd3435f22Eric Laurent
124081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    status_t status = chain->addEffect_l(effect);
124181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (status != NO_ERROR) {
124281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (chainCreated) {
124381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            removeEffectChain_l(chain);
124481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
124581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        return status;
124681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
124781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
124881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    effect->setDevice(mOutDevice);
124981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    effect->setDevice(mInDevice);
125081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    effect->setMode(mAudioFlinger->getMode());
125181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    effect->setAudioSource(mAudioSource);
125281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return NO_ERROR;
125381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
125481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
125581784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
125681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
125781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    ALOGV("removeEffect_l() %p effect %p", this, effect.get());
125881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    effect_descriptor_t desc = effect->desc();
125981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
126081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        detachAuxEffect_l(effect->id());
126181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
126281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
126381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    sp<EffectChain> chain = effect->chain().promote();
126481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (chain != 0) {
126581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // remove effect chain if removing last effect
126681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (chain->removeEffect_l(effect) == 0) {
126781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            removeEffectChain_l(chain);
126881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
126981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    } else {
127081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
127181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
127281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
127381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
127481784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::ThreadBase::lockEffectChains_l(
127581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        Vector< sp<AudioFlinger::EffectChain> >& effectChains)
127681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
127781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    effectChains = mEffectChains;
127881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    for (size_t i = 0; i < mEffectChains.size(); i++) {
127981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mEffectChains[i]->lock();
128081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
128181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
128281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
128381784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::ThreadBase::unlockEffectChains(
128481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
128581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
128681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    for (size_t i = 0; i < effectChains.size(); i++) {
128781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        effectChains[i]->unlock();
128881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
128981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
129081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
129181784c37c61b09289654b979567a42bf73cd2b12Eric Laurentsp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
129281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
129381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
129481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return getEffectChain_l(sessionId);
129581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
129681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
129781784c37c61b09289654b979567a42bf73cd2b12Eric Laurentsp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
129881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
129981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    size_t size = mEffectChains.size();
130081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    for (size_t i = 0; i < size; i++) {
130181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (mEffectChains[i]->sessionId() == sessionId) {
130281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            return mEffectChains[i];
130381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
130481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
130581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return 0;
130681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
130781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
130881784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
130981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
131081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
131181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    size_t size = mEffectChains.size();
131281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    for (size_t i = 0; i < size; i++) {
131381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mEffectChains[i]->setMode_l(mode);
131481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
131581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
131681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
131783b8808faad1e91690c64d7007348be8d9ebde73Eric Laurentvoid AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
131883b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent{
131983b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent    config->type = AUDIO_PORT_TYPE_MIX;
132083b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent    config->ext.mix.handle = mId;
132183b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent    config->sample_rate = mSampleRate;
132283b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent    config->format = mFormat;
132383b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent    config->channel_mask = mChannelMask;
132483b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent    config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
132583b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent                            AUDIO_PORT_CONFIG_FORMAT;
132683b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent}
132783b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent
132883b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent
132981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// ----------------------------------------------------------------------------
133081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent//      Playback
133181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// ----------------------------------------------------------------------------
133281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
133381784c37c61b09289654b979567a42bf73cd2b12Eric LaurentAudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
133481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                                             AudioStreamOut* output,
133581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                                             audio_io_handle_t id,
133681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                                             audio_devices_t device,
133781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                                             type_t type)
133881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    :   ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
13392098f2744cedf2dc3fa36f608aa965a34602e7c0Andy Hung        mNormalFrameCount(0), mSinkBuffer(NULL),
13406146c08f0c3dd8b9e5788063aa433f304a810602Andy Hung        mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
134169aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung        mMixerBuffer(NULL),
134269aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung        mMixerBufferSize(0),
134369aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung        mMixerBufferFormat(AUDIO_FORMAT_INVALID),
134469aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung        mMixerBufferValid(false),
13456146c08f0c3dd8b9e5788063aa433f304a810602Andy Hung        mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
134698ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung        mEffectBuffer(NULL),
134798ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung        mEffectBufferSize(0),
134898ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung        mEffectBufferFormat(AUDIO_FORMAT_INVALID),
134998ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung        mEffectBufferValid(false),
1350c1fac191069774c7bfcb062edbb821ea56e7dbc0Glenn Kasten        mSuspended(0), mBytesWritten(0),
1351462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen        mActiveTracksGeneration(0),
135281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // mStreamTypes[] initialized in constructor body
135381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mOutput(output),
135481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
135581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mMixerStatus(MIXER_IDLE),
135681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mMixerStatusIgnoringFastTracks(MIXER_IDLE),
135781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
1358bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        mBytesRemaining(0),
1359bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        mCurrentWriteLength(0),
1360bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        mUseAsyncWrite(false),
13613b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent        mWriteAckSequence(0),
13623b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent        mDrainSequence(0),
1363ede6c3b8b1147bc425f7b923882f559a513fe23bEric Laurent        mSignalPending(false),
136481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mScreenState(AudioFlinger::mScreenState),
136581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // index 0 is reserved for normal mixer's submix
1366bd096fd9d8e5fc0e62f98807f4818a06f70d0812Glenn Kasten        mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
1367d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent        mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
1368bd096fd9d8e5fc0e62f98807f4818a06f70d0812Glenn Kasten        // mLatchD, mLatchQ,
1369bd096fd9d8e5fc0e62f98807f4818a06f70d0812Glenn Kasten        mLatchDValid(false), mLatchQValid(false)
137081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
1371d7dca050c630bddbd73a6623271b34b4290460eeGlenn Kasten    snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1372d7dca050c630bddbd73a6623271b34b4290460eeGlenn Kasten    mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
137381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
137481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // Assumes constructor is called by AudioFlinger with it's mLock held, but
137581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // it would be safer to explicitly pass initial masterVolume/masterMute as
137681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // parameter.
137781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    //
137881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // If the HAL we are using has support for master volume or master mute,
137981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // then do not attenuate or mute during mixing (just leave the volume at 1.0
138081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // and the mute set to false).
138181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mMasterVolume = audioFlinger->masterVolume_l();
138281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mMasterMute = audioFlinger->masterMute_l();
138381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (mOutput && mOutput->audioHwDev) {
138481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (mOutput->audioHwDev->canSetMasterVolume()) {
138581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mMasterVolume = 1.0;
138681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
138781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
138881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (mOutput->audioHwDev->canSetMasterMute()) {
138981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mMasterMute = false;
139081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
139181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
139281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
1393deca2ae0a7cf8bc54ff3f30b7dc39bbc78b94c0dGlenn Kasten    readOutputParameters_l();
139481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
1395223fd5c9738e9665e495904d37d4632414b68c1eEric Laurent    // ++ operator does not compile
139666e4635cb09fadcaccf912f37c387396c428378aGlenn Kasten    for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
139781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            stream = (audio_stream_type_t) (stream + 1)) {
139881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
139981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
140081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
140181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
140281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
140381784c37c61b09289654b979567a42bf73cd2b12Eric LaurentAudioFlinger::PlaybackThread::~PlaybackThread()
140481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
14059e58b552f51b00b3b674102876bd6c77ef3da806Glenn Kasten    mAudioFlinger->unregisterWriter(mNBLogWriter);
1406010a1a1a552cdaad362cea8a0333b8906402dbcbAndy Hung    free(mSinkBuffer);
140769aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung    free(mMixerBuffer);
140898ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung    free(mEffectBuffer);
140981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
141081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
141181784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
141281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
141381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    dumpInternals(fd, args);
141481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    dumpTracks(fd, args);
141581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    dumpEffectChains(fd, args);
141681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
141781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
14180f11b51a57bc9062c4fe8af73747319cedabc5d6Glenn Kastenvoid AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
141981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
142081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    const size_t SIZE = 256;
142181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    char buffer[SIZE];
142281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    String8 result;
142381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
1424b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen    result.appendFormat("  Stream volumes in dB: ");
142581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
142681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        const stream_type_t *st = &mStreamTypes[i];
142781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (i > 0) {
142881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            result.appendFormat(", ");
142981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
143081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
143181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (st->mute) {
143281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            result.append("M");
143381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
143481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
143581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    result.append("\n");
143681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    write(fd, result.string(), result.length());
143781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    result.clear();
143881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
1439b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen    // These values are "raw"; they will wrap around.  See prepareTracks_l() for a better way.
1440b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen    FastTrackUnderruns underruns = getFastTrackUnderruns(0);
144187cebadd48710e42474756fc3513df678de045ceElliott Hughes    dprintf(fd, "  Normal mixer raw underrun counters: partial=%u empty=%u\n",
1442b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen            underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
1443b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen
1444b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen    size_t numtracks = mTracks.size();
1445b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen    size_t numactive = mActiveTracks.size();
144687cebadd48710e42474756fc3513df678de045ceElliott Hughes    dprintf(fd, "  %d Tracks", numtracks);
1447b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen    size_t numactiveseen = 0;
1448b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen    if (numtracks) {
144987cebadd48710e42474756fc3513df678de045ceElliott Hughes        dprintf(fd, " of which %d are active\n", numactive);
1450b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        Track::appendDumpHeader(result);
1451b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        for (size_t i = 0; i < numtracks; ++i) {
1452b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen            sp<Track> track = mTracks[i];
1453b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen            if (track != 0) {
1454b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen                bool active = mActiveTracks.indexOf(track) >= 0;
1455b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen                if (active) {
1456b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen                    numactiveseen++;
1457b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen                }
1458b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen                track->dump(buffer, SIZE, active);
1459b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen                result.append(buffer);
1460b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen            }
146181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
1462b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen    } else {
1463b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        result.append("\n");
146481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
1465b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen    if (numactiveseen != numactive) {
1466b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        // some tracks in the active list were not in the tracks list
1467b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        snprintf(buffer, SIZE, "  The following tracks are in the active list but"
1468b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen                " not in the track list\n");
1469b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        result.append(buffer);
1470b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        Track::appendDumpHeader(result);
1471b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        for (size_t i = 0; i < numactive; ++i) {
1472b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen            sp<Track> track = mActiveTracks[i].promote();
1473b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen            if (track != 0 && mTracks.indexOf(track) < 0) {
1474b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen                track->dump(buffer, SIZE, true);
1475b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen                result.append(buffer);
1476b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen            }
147781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
147881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
1479b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen
148081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    write(fd, result.string(), result.size());
148181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
148281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
148381784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
148481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
148597b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
148644182c206f7c5584ef2cf504da6be98fab665dbfGlenn Kasten
148744182c206f7c5584ef2cf504da6be98fab665dbfGlenn Kasten    dumpBase(fd, args);
148844182c206f7c5584ef2cf504da6be98fab665dbfGlenn Kasten
148987cebadd48710e42474756fc3513df678de045ceElliott Hughes    dprintf(fd, "  Normal frame count: %zu\n", mNormalFrameCount);
149087cebadd48710e42474756fc3513df678de045ceElliott Hughes    dprintf(fd, "  Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
149187cebadd48710e42474756fc3513df678de045ceElliott Hughes    dprintf(fd, "  Total writes: %d\n", mNumWrites);
149287cebadd48710e42474756fc3513df678de045ceElliott Hughes    dprintf(fd, "  Delayed writes: %d\n", mNumDelayedWrites);
149387cebadd48710e42474756fc3513df678de045ceElliott Hughes    dprintf(fd, "  Blocked in write: %s\n", mInWrite ? "yes" : "no");
149487cebadd48710e42474756fc3513df678de045ceElliott Hughes    dprintf(fd, "  Suspend count: %d\n", mSuspended);
149587cebadd48710e42474756fc3513df678de045ceElliott Hughes    dprintf(fd, "  Sink buffer : %p\n", mSinkBuffer);
149687cebadd48710e42474756fc3513df678de045ceElliott Hughes    dprintf(fd, "  Mixer buffer: %p\n", mMixerBuffer);
149787cebadd48710e42474756fc3513df678de045ceElliott Hughes    dprintf(fd, "  Effect buffer: %p\n", mEffectBuffer);
149887cebadd48710e42474756fc3513df678de045ceElliott Hughes    dprintf(fd, "  Fast track availMask=%#x\n", mFastTrackAvailMask);
149997b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    AudioStreamOut *output = mOutput;
150097b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
150197b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    String8 flagsAsString = outputFlagsToString(flags);
150297b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten    dprintf(fd, "  AudioStreamOut: %p flags %#x (%s)\n", output, flags, flagsAsString.string());
150381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
150481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
150581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// Thread virtuals
150681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
150781784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::PlaybackThread::onFirstRef()
150881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
1509d7dca050c630bddbd73a6623271b34b4290460eeGlenn Kasten    run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
151081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
151181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
151281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// ThreadBase virtuals
151381784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::PlaybackThread::preExit()
151481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
151581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    ALOGV("  preExit()");
151681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // FIXME this is using hard-coded strings but in the future, this functionality will be
151781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    //       converted to use audio HAL extensions required to support tunneling
151881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
151981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
152081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
152181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
152281784c37c61b09289654b979567a42bf73cd2b12Eric Laurentsp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
152381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        const sp<AudioFlinger::Client>& client,
152481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        audio_stream_type_t streamType,
152581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        uint32_t sampleRate,
152681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        audio_format_t format,
152781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        audio_channel_mask_t channelMask,
152874935e44734c1ec235c2b6677db3e0dbefa5ddb8Glenn Kasten        size_t *pFrameCount,
152981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        const sp<IMemory>& sharedBuffer,
153081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        int sessionId,
153181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        IAudioFlinger::track_flags_t *flags,
153281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        pid_t tid,
1533462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen        int uid,
153481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        status_t *status)
153581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
153674935e44734c1ec235c2b6677db3e0dbefa5ddb8Glenn Kasten    size_t frameCount = *pFrameCount;
153781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    sp<Track> track;
153881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    status_t lStatus;
153981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
154081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
154181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
154281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // client expresses a preference for FAST, but we get the final say
154381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (*flags & IAudioFlinger::TRACK_FAST) {
154481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent      if (
154581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // not timed
154681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            (!isTimed) &&
154781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // either of these use cases:
154881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            (
154981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent              // use case 1: shared buffer with any frame count
155081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent              (
155181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                (sharedBuffer != 0)
155281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent              ) ||
15531dfe2f9c2d03fc8d0ed0cdfe0b9fb894bc0bcc11Glenn Kasten              // use case 2: frame count is default or at least as large as HAL
155481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent              (
15551dfe2f9c2d03fc8d0ed0cdfe0b9fb894bc0bcc11Glenn Kasten                // we formerly checked for a callback handler (non-0 tid),
15561dfe2f9c2d03fc8d0ed0cdfe0b9fb894bc0bcc11Glenn Kasten                // but that is no longer required for TRANSFER_OBTAIN mode
155781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                ((frameCount == 0) ||
1558b5fed68bcdd6f44424c9e4d12bfe9a3ff51bd62eGlenn Kasten                (frameCount >= mFrameCount))
155981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent              )
156081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            ) &&
156181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // PCM data
156281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            audio_is_linear_pcm(format) &&
15639a59276fb465e492138e0576523b54079671e8f4Andy Hung            // identical channel mask to sink, or mono in and stereo sink
15649a59276fb465e492138e0576523b54079671e8f4Andy Hung            (channelMask == mChannelMask ||
15659a59276fb465e492138e0576523b54079671e8f4Andy Hung                    (channelMask == AUDIO_CHANNEL_OUT_MONO &&
15669a59276fb465e492138e0576523b54079671e8f4Andy Hung                            mChannelMask == AUDIO_CHANNEL_OUT_STEREO)) &&
156781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // hardware sample rate
156881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            (sampleRate == mSampleRate) &&
156981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // normal mixer has an associated fast mixer
157081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            hasFastMixer() &&
157181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // there are sufficient fast track slots available
157281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            (mFastTrackAvailMask != 0)
157381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // FIXME test that MixerThread for this fast track has a capable output HAL
157481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // FIXME add a permission test also?
157581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        ) {
157681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
157781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (frameCount == 0) {
15780349009fd19f89f8414c428f6b71b369f7546085Glenn Kasten            // read the fast track multiplier property the first time it is needed
15790349009fd19f89f8414c428f6b71b369f7546085Glenn Kasten            int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
15800349009fd19f89f8414c428f6b71b369f7546085Glenn Kasten            if (ok != 0) {
15810349009fd19f89f8414c428f6b71b369f7546085Glenn Kasten                ALOGE("%s pthread_once failed: %d", __func__, ok);
15820349009fd19f89f8414c428f6b71b369f7546085Glenn Kasten            }
15830349009fd19f89f8414c428f6b71b369f7546085Glenn Kasten            frameCount = mFrameCount * sFastTrackMultiplier;
158481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
158581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
158681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                frameCount, mFrameCount);
158781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent      } else {
158881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
15896146c08f0c3dd8b9e5788063aa433f304a810602Andy Hung                "mFrameCount=%d format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
15906146c08f0c3dd8b9e5788063aa433f304a810602Andy Hung                "sampleRate=%u mSampleRate=%u "
159181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
15926146c08f0c3dd8b9e5788063aa433f304a810602Andy Hung                isTimed, sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
159381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                audio_is_linear_pcm(format),
159481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
159581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        *flags &= ~IAudioFlinger::TRACK_FAST;
15960e48d25606c82def035ad10a5b3923767a765cddAndy Hung      }
15970e48d25606c82def035ad10a5b3923767a765cddAndy Hung    }
15980e48d25606c82def035ad10a5b3923767a765cddAndy Hung    // For normal PCM streaming tracks, update minimum frame count.
15990e48d25606c82def035ad10a5b3923767a765cddAndy Hung    // For compatibility with AudioTrack calculation, buffer depth is forced
16000e48d25606c82def035ad10a5b3923767a765cddAndy Hung    // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
16010e48d25606c82def035ad10a5b3923767a765cddAndy Hung    // This is probably too conservative, but legacy application code may depend on it.
16020e48d25606c82def035ad10a5b3923767a765cddAndy Hung    // If you change this calculation, also review the start threshold which is related.
16030e48d25606c82def035ad10a5b3923767a765cddAndy Hung    if (!(*flags & IAudioFlinger::TRACK_FAST)
16040e48d25606c82def035ad10a5b3923767a765cddAndy Hung            && audio_is_linear_pcm(format) && sharedBuffer == 0) {
160581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
160681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
160781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (minBufCount < 2) {
160881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            minBufCount = 2;
160981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
16100e48d25606c82def035ad10a5b3923767a765cddAndy Hung        size_t minFrameCount =
16110e48d25606c82def035ad10a5b3923767a765cddAndy Hung                minBufCount * sourceFramesNeeded(sampleRate, mNormalFrameCount, mSampleRate);
16120e48d25606c82def035ad10a5b3923767a765cddAndy Hung        if (frameCount < minFrameCount) { // including frameCount == 0
161381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            frameCount = minFrameCount;
161481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
161581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
161674935e44734c1ec235c2b6677db3e0dbefa5ddb8Glenn Kasten    *pFrameCount = frameCount;
161781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
1618c3df838434b37d8400eea2438083cc01a4c1cc71Glenn Kasten    switch (mType) {
1619c3df838434b37d8400eea2438083cc01a4c1cc71Glenn Kasten
1620c3df838434b37d8400eea2438083cc01a4c1cc71Glenn Kasten    case DIRECT:
1621993fa0603707e94ce259e95e56838a85b5ccbdc5Glenn Kasten        if (audio_is_linear_pcm(format)) {
162281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1623cac3daa6332bf6d1f7d26adc4a9915f3d7992dd9Glenn Kasten                ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1624cac3daa6332bf6d1f7d26adc4a9915f3d7992dd9Glenn Kasten                        "for output %p with format %#x",
162581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                        sampleRate, format, channelMask, mOutput, mFormat);
162681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                lStatus = BAD_VALUE;
162781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                goto Exit;
162881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
162981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
1630c3df838434b37d8400eea2438083cc01a4c1cc71Glenn Kasten        break;
1631c3df838434b37d8400eea2438083cc01a4c1cc71Glenn Kasten
1632c3df838434b37d8400eea2438083cc01a4c1cc71Glenn Kasten    case OFFLOAD:
1633bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1634cac3daa6332bf6d1f7d26adc4a9915f3d7992dd9Glenn Kasten            ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1635cac3daa6332bf6d1f7d26adc4a9915f3d7992dd9Glenn Kasten                    "for output %p with format %#x",
1636bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                    sampleRate, format, channelMask, mOutput, mFormat);
1637bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            lStatus = BAD_VALUE;
1638bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            goto Exit;
1639bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        }
1640c3df838434b37d8400eea2438083cc01a4c1cc71Glenn Kasten        break;
1641c3df838434b37d8400eea2438083cc01a4c1cc71Glenn Kasten
1642c3df838434b37d8400eea2438083cc01a4c1cc71Glenn Kasten    default:
1643993fa0603707e94ce259e95e56838a85b5ccbdc5Glenn Kasten        if (!audio_is_linear_pcm(format)) {
1644cac3daa6332bf6d1f7d26adc4a9915f3d7992dd9Glenn Kasten                ALOGE("createTrack_l() Bad parameter: format %#x \""
1645cac3daa6332bf6d1f7d26adc4a9915f3d7992dd9Glenn Kasten                        "for output %p with format %#x",
1646bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                        format, mOutput, mFormat);
1647bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                lStatus = BAD_VALUE;
1648bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                goto Exit;
1649bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        }
1650cd04484f4837b8ca0041d118286ab6a98e84fc75Andy Hung        if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
165181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
165281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            lStatus = BAD_VALUE;
165381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            goto Exit;
165481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
1655c3df838434b37d8400eea2438083cc01a4c1cc71Glenn Kasten        break;
1656c3df838434b37d8400eea2438083cc01a4c1cc71Glenn Kasten
165781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
165881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
165981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    lStatus = initCheck();
166081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (lStatus != NO_ERROR) {
166115e5798908ccac14e10c84834eaf08c42931bd06Glenn Kasten        ALOGE("createTrack_l() audio driver not initialized");
166281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        goto Exit;
166381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
166481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
166581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    { // scope for mLock
166681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        Mutex::Autolock _l(mLock);
166781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
166881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // all tracks in same audio session must share the same routing strategy otherwise
166981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // conflicts will happen when tracks are moved from one output to another by audio policy
167081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // manager
167181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
167281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        for (size_t i = 0; i < mTracks.size(); ++i) {
167381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            sp<Track> t = mTracks[i];
167483b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent            if (t != 0 && t->isExternalTrack()) {
167581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
167681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                if (sessionId == t->sessionId() && strategy != actual) {
167781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
167881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                            strategy, actual);
167981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    lStatus = BAD_VALUE;
168081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    goto Exit;
168181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
168281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
168381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
168481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
168581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (!isTimed) {
168681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            track = new Track(this, client, streamType, sampleRate, format,
168783b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent                              channelMask, frameCount, NULL, sharedBuffer,
168883b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent                              sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
168981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        } else {
169081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            track = TimedTrack::create(this, client, streamType, sampleRate, format,
1691462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen                    channelMask, frameCount, sharedBuffer, sessionId, uid);
169281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
1693030033342a6ea17003e6af38a56c7edc6d2ead01Glenn Kasten
1694030033342a6ea17003e6af38a56c7edc6d2ead01Glenn Kasten        // new Track always returns non-NULL,
1695030033342a6ea17003e6af38a56c7edc6d2ead01Glenn Kasten        // but TimedTrack::create() is a factory that could fail by returning NULL
1696030033342a6ea17003e6af38a56c7edc6d2ead01Glenn Kasten        lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1697030033342a6ea17003e6af38a56c7edc6d2ead01Glenn Kasten        if (lStatus != NO_ERROR) {
16980cde076ddb283c84c3801a2df4cc3df99bd1577fGlenn Kasten            ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
169903e9e83c47ab4a518da0a1f36b8f702f59221c95Haynes Mathew George            // track must be cleared from the caller as the caller has the AF lock
170081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            goto Exit;
170181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
170281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mTracks.add(track);
170381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
170481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sp<EffectChain> chain = getEffectChain_l(sessionId);
170581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (chain != 0) {
170681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
170781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            track->setMainBuffer(chain->inBuffer());
170881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
170981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            chain->incTrackCnt();
171081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
171181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
171281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
171381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            pid_t callingPid = IPCThreadState::self()->getCallingPid();
171481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
171581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // so ask activity manager to do this on our behalf
171681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
171781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
171881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
171981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
172081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    lStatus = NO_ERROR;
172181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
172281784c37c61b09289654b979567a42bf73cd2b12Eric LaurentExit:
17239156ef3e11b68cc4b6d3cea77f1f63673855a6d1Glenn Kasten    *status = lStatus;
172481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return track;
172581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
172681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
172781784c37c61b09289654b979567a42bf73cd2b12Eric Laurentuint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
172881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
172981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return latency;
173081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
173181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
173281784c37c61b09289654b979567a42bf73cd2b12Eric Laurentuint32_t AudioFlinger::PlaybackThread::latency() const
173381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
173481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
173581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return latency_l();
173681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
173781784c37c61b09289654b979567a42bf73cd2b12Eric Laurentuint32_t AudioFlinger::PlaybackThread::latency_l() const
173881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
173981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (initCheck() == NO_ERROR) {
174081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
174181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    } else {
174281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        return 0;
174381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
174481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
174581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
174681784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::PlaybackThread::setMasterVolume(float value)
174781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
174881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
174981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // Don't apply master volume in SW if our HAL can do it for us.
175081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (mOutput && mOutput->audioHwDev &&
175181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mOutput->audioHwDev->canSetMasterVolume()) {
175281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mMasterVolume = 1.0;
175381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    } else {
175481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mMasterVolume = value;
175581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
175681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
175781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
175881784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::PlaybackThread::setMasterMute(bool muted)
175981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
176081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
176181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // Don't apply master mute in SW if our HAL can do it for us.
176281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (mOutput && mOutput->audioHwDev &&
176381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mOutput->audioHwDev->canSetMasterMute()) {
176481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mMasterMute = false;
176581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    } else {
176681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mMasterMute = muted;
176781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
176881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
176981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
177081784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
177181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
177281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
177381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mStreamTypes[stream].volume = value;
1774ede6c3b8b1147bc425f7b923882f559a513fe23bEric Laurent    broadcast_l();
177581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
177681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
177781784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
177881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
177981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
178081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mStreamTypes[stream].mute = muted;
1781ede6c3b8b1147bc425f7b923882f559a513fe23bEric Laurent    broadcast_l();
178281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
178381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
178481784c37c61b09289654b979567a42bf73cd2b12Eric Laurentfloat AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
178581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
178681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
178781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return mStreamTypes[stream].volume;
178881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
178981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
179081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// addTrack_l() must be called with ThreadBase::mLock held
179181784c37c61b09289654b979567a42bf73cd2b12Eric Laurentstatus_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
179281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
179381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    status_t status = ALREADY_EXISTS;
179481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
179581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // set retry count for buffer fill
179681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    track->mRetryCount = kMaxTrackStartupRetries;
179781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (mActiveTracks.indexOf(track) < 0) {
179881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // the track is newly added, make sure it fills up all its
179981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // buffers before playing. This is to ensure the client will
180081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // effectively get the latency it requested.
180183b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent        if (track->isExternalTrack()) {
1802bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            TrackBase::track_state state = track->mState;
1803bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            mLock.unlock();
1804e83b55dc29ca16092ba02f36f55fa6e0e37fd78cEric Laurent            status = AudioSystem::startOutput(mId, track->streamType(),
1805e83b55dc29ca16092ba02f36f55fa6e0e37fd78cEric Laurent                                              (audio_session_t)track->sessionId());
1806bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            mLock.lock();
1807bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            // abort track was stopped/paused while we released the lock
1808bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            if (state != track->mState) {
1809bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                if (status == NO_ERROR) {
1810bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                    mLock.unlock();
1811e83b55dc29ca16092ba02f36f55fa6e0e37fd78cEric Laurent                    AudioSystem::stopOutput(mId, track->streamType(),
1812e83b55dc29ca16092ba02f36f55fa6e0e37fd78cEric Laurent                                            (audio_session_t)track->sessionId());
1813bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                    mLock.lock();
1814bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                }
1815bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                return INVALID_OPERATION;
1816bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            }
1817bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            // abort if start is rejected by audio policy manager
1818bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            if (status != NO_ERROR) {
1819bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                return PERMISSION_DENIED;
1820bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            }
1821bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent#ifdef ADD_BATTERY_DATA
1822bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            // to track the speaker usage
1823bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1824bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent#endif
1825bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        }
1826bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
18279f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
182881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        track->mResetDone = false;
182981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        track->mPresentationCompleteFrames = 0;
183081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mActiveTracks.add(track);
1831462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen        mWakeLockUids.add(track->uid());
1832462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen        mActiveTracksGeneration++;
1833fd4779740ec3e9e865d5514464df26d015354388Eric Laurent        mLatestActiveTrack = track;
1834d0107bcd44fe608b0c00a8843d19fb6356c4cb69Eric Laurent        sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1835d0107bcd44fe608b0c00a8843d19fb6356c4cb69Eric Laurent        if (chain != 0) {
1836d0107bcd44fe608b0c00a8843d19fb6356c4cb69Eric Laurent            ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1837d0107bcd44fe608b0c00a8843d19fb6356c4cb69Eric Laurent                    track->sessionId());
1838d0107bcd44fe608b0c00a8843d19fb6356c4cb69Eric Laurent            chain->incActiveTrackCnt();
183981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
184081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
184181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        status = NO_ERROR;
184281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
184381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
18444c6a433d74d5ae8b9bc0557207e3ced43bf34a25Haynes Mathew George    onAddNewTrack_l();
184581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return status;
184681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
184781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
1848bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurentbool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
184981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
1850bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    track->terminate();
185181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // active tracks are removed by threadLoop()
1852bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1853bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    track->mState = TrackBase::STOPPED;
1854bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    if (!trackActive) {
185581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        removeTrack_l(track);
1856ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent    } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
1857bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        track->mState = TrackBase::STOPPING_1;
185881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
1859bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
1860bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    return trackActive;
186181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
186281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
186381784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
186481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
186581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
186681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mTracks.remove(track);
186781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    deleteTrackName_l(track->name());
186881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // redundant as track is about to be destroyed, for dumpsys only
186981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    track->mName = -1;
187081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (track->isFastTrack()) {
187181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        int index = track->mFastIndex;
187281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
187381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
187481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mFastTrackAvailMask |= 1 << index;
187581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // redundant as track is about to be destroyed, for dumpsys only
187681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        track->mFastIndex = -1;
187781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
187881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    sp<EffectChain> chain = getEffectChain_l(track->sessionId());
187981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (chain != 0) {
188081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        chain->decTrackCnt();
188181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
188281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
188381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
1884ede6c3b8b1147bc425f7b923882f559a513fe23bEric Laurentvoid AudioFlinger::PlaybackThread::broadcast_l()
1885bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent{
1886bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    // Thread could be blocked waiting for async
1887bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    // so signal it to handle state changes immediately
1888bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1889bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    // be lost so we also flag to prevent it blocking on mWaitWorkCV
1890bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    mSignalPending = true;
1891ede6c3b8b1147bc425f7b923882f559a513fe23bEric Laurent    mWaitWorkCV.broadcast();
1892bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent}
1893bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
189481784c37c61b09289654b979567a42bf73cd2b12Eric LaurentString8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
189581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
189681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
189781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (initCheck() != NO_ERROR) {
1898d8ea699dc8e7dac58bb32e9cdb31b0758da25817Glenn Kasten        return String8();
189981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
190081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
1901d8ea699dc8e7dac58bb32e9cdb31b0758da25817Glenn Kasten    char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1902d8ea699dc8e7dac58bb32e9cdb31b0758da25817Glenn Kasten    const String8 out_s8(s);
190381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    free(s);
190481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return out_s8;
190581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
190681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
1907021cf9634ab09c0753a40b7c9ef4ba603be5c3daEric Laurentvoid AudioFlinger::PlaybackThread::audioConfigChanged(int event, int param) {
190881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    AudioSystem::OutputDescriptor desc;
190981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    void *param2 = NULL;
191081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
1911021cf9634ab09c0753a40b7c9ef4ba603be5c3daEric Laurent    ALOGV("PlaybackThread::audioConfigChanged, thread %p, event %d, param %d", this, event,
191281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            param);
191381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
191481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    switch (event) {
191581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    case AudioSystem::OUTPUT_OPENED:
191681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    case AudioSystem::OUTPUT_CONFIG_CHANGED:
1917fad226abd12435dbcd232f7de396f1a097b2bd5fGlenn Kasten        desc.channelMask = mChannelMask;
191881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        desc.samplingRate = mSampleRate;
191981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        desc.format = mFormat;
192081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        desc.frameCount = mNormalFrameCount; // FIXME see
192181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                                             // AudioFlinger::frameCount(audio_io_handle_t)
19221035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        desc.latency = latency_l();
192381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        param2 = &desc;
192481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        break;
192581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
192681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    case AudioSystem::STREAM_CONFIG_CHANGED:
192781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        param2 = &param;
192881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    case AudioSystem::OUTPUT_CLOSED:
192981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    default:
193081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        break;
193181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
1932021cf9634ab09c0753a40b7c9ef4ba603be5c3daEric Laurent    mAudioFlinger->audioConfigChanged(event, mId, param2);
193381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
193481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
1935bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurentvoid AudioFlinger::PlaybackThread::writeCallback()
1936bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent{
1937bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    ALOG_ASSERT(mCallbackThread != 0);
19383b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent    mCallbackThread->resetWriteBlocked();
1939bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent}
1940bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
1941bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurentvoid AudioFlinger::PlaybackThread::drainCallback()
1942bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent{
1943bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    ALOG_ASSERT(mCallbackThread != 0);
19443b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent    mCallbackThread->resetDraining();
1945bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent}
1946bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
19473b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurentvoid AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
1948bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent{
1949bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    Mutex::Autolock _l(mLock);
19503b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent    // reject out of sequence requests
19513b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent    if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
19523b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent        mWriteAckSequence &= ~1;
1953bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        mWaitWorkCV.signal();
1954bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    }
1955bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent}
1956bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
19573b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurentvoid AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
1958bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent{
1959bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    Mutex::Autolock _l(mLock);
19603b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent    // reject out of sequence requests
19613b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent    if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
19623b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent        mDrainSequence &= ~1;
1963bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        mWaitWorkCV.signal();
1964bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    }
1965bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent}
1966bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
1967bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent// static
1968bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurentint AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
19690f11b51a57bc9062c4fe8af73747319cedabc5d6Glenn Kasten                                                void *param __unused,
1970bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                                                void *cookie)
1971bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent{
1972bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
1973bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    ALOGV("asyncCallback() event %d", event);
1974bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    switch (event) {
1975bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    case STREAM_CBK_EVENT_WRITE_READY:
1976bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        me->writeCallback();
1977bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        break;
1978bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    case STREAM_CBK_EVENT_DRAIN_READY:
1979bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        me->drainCallback();
1980bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        break;
1981bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    default:
1982bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        ALOGW("asyncCallback() unknown event %d", event);
1983bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        break;
1984bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    }
1985bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    return 0;
1986bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent}
1987bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
1988deca2ae0a7cf8bc54ff3f30b7dc39bbc78b94c0dGlenn Kastenvoid AudioFlinger::PlaybackThread::readOutputParameters_l()
198981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
1990adad3d7d935da176ff24941b4ae9edf7340e9b96Glenn Kasten    // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
199181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
199281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
19937fc97ba08e2850f3f16db704b78ce78e3dbe1ff0Glenn Kasten    if (!audio_is_output_channel(mChannelMask)) {
1994adad3d7d935da176ff24941b4ae9edf7340e9b96Glenn Kasten        LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
19957fc97ba08e2850f3f16db704b78ce78e3dbe1ff0Glenn Kasten    }
19969a59276fb465e492138e0576523b54079671e8f4Andy Hung    if ((mType == MIXER || mType == DUPLICATING)
19979a59276fb465e492138e0576523b54079671e8f4Andy Hung            && !isValidPcmSinkChannelMask(mChannelMask)) {
19989a59276fb465e492138e0576523b54079671e8f4Andy Hung        LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
19999a59276fb465e492138e0576523b54079671e8f4Andy Hung                mChannelMask);
20007fc97ba08e2850f3f16db704b78ce78e3dbe1ff0Glenn Kasten    }
2001e541269be94f3a1072932d51537905b120ef4733Andy Hung    mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
2002463be250de73907965faa6a216c00312bf81e049Andy Hung    mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
2003463be250de73907965faa6a216c00312bf81e049Andy Hung    mFormat = mHALFormat;
20047fc97ba08e2850f3f16db704b78ce78e3dbe1ff0Glenn Kasten    if (!audio_is_valid_format(mFormat)) {
2005adad3d7d935da176ff24941b4ae9edf7340e9b96Glenn Kasten        LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
20067fc97ba08e2850f3f16db704b78ce78e3dbe1ff0Glenn Kasten    }
20076146c08f0c3dd8b9e5788063aa433f304a810602Andy Hung    if ((mType == MIXER || mType == DUPLICATING)
20086146c08f0c3dd8b9e5788063aa433f304a810602Andy Hung            && !isValidPcmSinkFormat(mFormat)) {
20096146c08f0c3dd8b9e5788063aa433f304a810602Andy Hung        LOG_FATAL("HAL format %#x not supported for mixed output",
20106146c08f0c3dd8b9e5788063aa433f304a810602Andy Hung                mFormat);
20117fc97ba08e2850f3f16db704b78ce78e3dbe1ff0Glenn Kasten    }
2012062e67a26e0553dd142be622821f493df541f0c6Phil Burk    mFrameSize = mOutput->getFrameSize();
201370949c47fbae3f836d15f040551d7631be3ed7c2Glenn Kasten    mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
201470949c47fbae3f836d15f040551d7631be3ed7c2Glenn Kasten    mFrameCount = mBufferSize / mFrameSize;
201581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (mFrameCount & 15) {
201681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
201781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                mFrameCount);
201881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
201981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
2020bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
2021bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            (mOutput->stream->set_callback != NULL)) {
2022bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        if (mOutput->stream->set_callback(mOutput->stream,
2023bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                                      AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
2024bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            mUseAsyncWrite = true;
20254de95592980dba88a35b3dc8f3fd045588387a4fEric Laurent            mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
2026bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        }
2027bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    }
2028bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
2029d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    mHwSupportsPause = false;
2030d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
2031d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent        if (mOutput->stream->pause != NULL) {
2032d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent            if (mOutput->stream->resume != NULL) {
2033d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent                mHwSupportsPause = true;
2034d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent            } else {
2035d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent                ALOGW("direct output implements pause but not resume");
2036d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent            }
2037d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent        } else if (mOutput->stream->resume != NULL) {
2038d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent            ALOGW("direct output implements resume but not pause");
2039d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent        }
2040d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    }
2041d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent
2042fbfc3959f4aac839445edc7075532067fef497c2Andy Hung    if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2043fbfc3959f4aac839445edc7075532067fef497c2Andy Hung        // For best precision, we use float instead of the associated output
2044fbfc3959f4aac839445edc7075532067fef497c2Andy Hung        // device format (typically PCM 16 bit).
2045fbfc3959f4aac839445edc7075532067fef497c2Andy Hung
2046fbfc3959f4aac839445edc7075532067fef497c2Andy Hung        mFormat = AUDIO_FORMAT_PCM_FLOAT;
2047fbfc3959f4aac839445edc7075532067fef497c2Andy Hung        mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2048fbfc3959f4aac839445edc7075532067fef497c2Andy Hung        mBufferSize = mFrameSize * mFrameCount;
2049fbfc3959f4aac839445edc7075532067fef497c2Andy Hung
2050fbfc3959f4aac839445edc7075532067fef497c2Andy Hung        // TODO: We currently use the associated output device channel mask and sample rate.
2051fbfc3959f4aac839445edc7075532067fef497c2Andy Hung        // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2052fbfc3959f4aac839445edc7075532067fef497c2Andy Hung        // (if a valid mask) to avoid premature downmix.
2053fbfc3959f4aac839445edc7075532067fef497c2Andy Hung        // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2054fbfc3959f4aac839445edc7075532067fef497c2Andy Hung        // instead of the output device sample rate to avoid loss of high frequency information.
2055fbfc3959f4aac839445edc7075532067fef497c2Andy Hung        // This may need to be updated as MixerThread/OutputTracks are added and not here.
2056fbfc3959f4aac839445edc7075532067fef497c2Andy Hung    }
2057fbfc3959f4aac839445edc7075532067fef497c2Andy Hung
205809a5007b17acb49d25cfa386a2e2534d942e8854Andy Hung    // Calculate size of normal sink buffer relative to the HAL output buffer size
205981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    double multiplier = 1.0;
206081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
206181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            kUseFastMixer == FastMixer_Dynamic)) {
206209a5007b17acb49d25cfa386a2e2534d942e8854Andy Hung        size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
206309a5007b17acb49d25cfa386a2e2534d942e8854Andy Hung        size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
206481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
206581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
206681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        maxNormalFrameCount = maxNormalFrameCount & ~15;
206781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (maxNormalFrameCount < minNormalFrameCount) {
206881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            maxNormalFrameCount = minNormalFrameCount;
206981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
207081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        multiplier = (double) minNormalFrameCount / (double) mFrameCount;
207181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (multiplier <= 1.0) {
207281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            multiplier = 1.0;
207381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        } else if (multiplier <= 2.0) {
207481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if (2 * mFrameCount <= maxNormalFrameCount) {
207581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                multiplier = 2.0;
207681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            } else {
207781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
207881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
207981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        } else {
208081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
208109a5007b17acb49d25cfa386a2e2534d942e8854Andy Hung            // SRC (it would be unusual for the normal sink buffer size to not be a multiple of fast
208281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // track, but we sometimes have to do this to satisfy the maximum frame count
208381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // constraint)
208481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // FIXME this rounding up should not be done if no HAL SRC
208581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            uint32_t truncMult = (uint32_t) multiplier;
208681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if ((truncMult & 1)) {
208781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
208881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    ++truncMult;
208981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
209081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
209181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            multiplier = (double) truncMult;
209281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
209381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
209481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mNormalFrameCount = multiplier * mFrameCount;
209581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // round up to nearest 16 frames to satisfy AudioMixer
2096ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent    if (mType == MIXER || mType == DUPLICATING) {
2097ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent        mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2098ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent    }
209909a5007b17acb49d25cfa386a2e2534d942e8854Andy Hung    ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
210081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mNormalFrameCount);
210181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
2102010a1a1a552cdaad362cea8a0333b8906402dbcbAndy Hung    // mSinkBuffer is the sink buffer.  Size is always multiple-of-16 frames.
2103010a1a1a552cdaad362cea8a0333b8906402dbcbAndy Hung    // Originally this was int16_t[] array, need to remove legacy implications.
2104010a1a1a552cdaad362cea8a0333b8906402dbcbAndy Hung    free(mSinkBuffer);
2105010a1a1a552cdaad362cea8a0333b8906402dbcbAndy Hung    mSinkBuffer = NULL;
21065b10a2037a835e790994b9ebec3c2e55052f1f3bAndy Hung    // For sink buffer size, we use the frame size from the downstream sink to avoid problems
21075b10a2037a835e790994b9ebec3c2e55052f1f3bAndy Hung    // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
21085b10a2037a835e790994b9ebec3c2e55052f1f3bAndy Hung    const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
2109010a1a1a552cdaad362cea8a0333b8906402dbcbAndy Hung    (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
211081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
211169aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung    // We resize the mMixerBuffer according to the requirements of the sink buffer which
211269aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung    // drives the output.
211369aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung    free(mMixerBuffer);
211469aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung    mMixerBuffer = NULL;
211569aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung    if (mMixerBufferEnabled) {
211669aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung        mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
211769aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung        mMixerBufferSize = mNormalFrameCount * mChannelCount
211869aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung                * audio_bytes_per_sample(mMixerBufferFormat);
211969aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung        (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
212069aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung    }
212198ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung    free(mEffectBuffer);
212298ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung    mEffectBuffer = NULL;
212398ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung    if (mEffectBufferEnabled) {
212498ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung        mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
212598ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung        mEffectBufferSize = mNormalFrameCount * mChannelCount
212698ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung                * audio_bytes_per_sample(mEffectBufferFormat);
212798ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung        (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
212898ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung    }
212969aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung
213081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // force reconfiguration of effect chains and engines to take new buffer size and audio
213181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // parameters into account
2132deca2ae0a7cf8bc54ff3f30b7dc39bbc78b94c0dGlenn Kasten    // Note that mLock is not held when readOutputParameters_l() is called from the constructor
213381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
213481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // matter.
213581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
213681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Vector< sp<EffectChain> > effectChains = mEffectChains;
213781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    for (size_t i = 0; i < effectChains.size(); i ++) {
213881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
213981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
214081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
214181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
214281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
2143377b2ec9a2885f9b6405b07ba900a9e3f4349c38Kévin PETITstatus_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
214481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
214581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (halFrames == NULL || dspFrames == NULL) {
214681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        return BAD_VALUE;
214781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
214881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
214981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (initCheck() != NO_ERROR) {
215081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        return INVALID_OPERATION;
215181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
215281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    size_t framesWritten = mBytesWritten / mFrameSize;
215381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    *halFrames = framesWritten;
215481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
215581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (isSuspended()) {
215681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // return an estimation of rendered frames when the output is suspended
215781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
215881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
215981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        return NO_ERROR;
216081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    } else {
2161377b2ec9a2885f9b6405b07ba900a9e3f4349c38Kévin PETIT        status_t status;
2162377b2ec9a2885f9b6405b07ba900a9e3f4349c38Kévin PETIT        uint32_t frames;
2163062e67a26e0553dd142be622821f493df541f0c6Phil Burk        status = mOutput->getRenderPosition(&frames);
2164377b2ec9a2885f9b6405b07ba900a9e3f4349c38Kévin PETIT        *dspFrames = (size_t)frames;
2165377b2ec9a2885f9b6405b07ba900a9e3f4349c38Kévin PETIT        return status;
216681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
216781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
216881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
216981784c37c61b09289654b979567a42bf73cd2b12Eric Laurentuint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
217081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
217181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
217281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    uint32_t result = 0;
217381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (getEffectChain_l(sessionId) != 0) {
217481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        result = EFFECT_SESSION;
217581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
217681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
217781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    for (size_t i = 0; i < mTracks.size(); ++i) {
217881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sp<Track> track = mTracks[i];
21795736c35b841de56ce394b4879389f669b61425e6Glenn Kasten        if (sessionId == track->sessionId() && !track->isInvalid()) {
218081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            result |= TRACK_SESSION;
218181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            break;
218281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
218381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
218481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
218581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return result;
218681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
218781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
218881784c37c61b09289654b979567a42bf73cd2b12Eric Laurentuint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
218981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
219081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
219181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
219281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
219381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
219481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
219581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    for (size_t i = 0; i < mTracks.size(); i++) {
219681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sp<Track> track = mTracks[i];
21975736c35b841de56ce394b4879389f669b61425e6Glenn Kasten        if (sessionId == track->sessionId() && !track->isInvalid()) {
219881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            return AudioSystem::getStrategyForStream(track->streamType());
219981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
220081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
220181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
220281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
220381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
220481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
2205062e67a26e0553dd142be622821f493df541f0c6Phil BurkAudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
220681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
220781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
220881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return mOutput;
220981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
221081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
2211062e67a26e0553dd142be622821f493df541f0c6Phil BurkAudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
221281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
221381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
221481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    AudioStreamOut *output = mOutput;
221581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mOutput = NULL;
221681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // FIXME FastMixer might also have a raw ptr to mOutputSink;
221781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    //       must push a NULL and wait for ack
221881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mOutputSink.clear();
221981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mPipeSink.clear();
222081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mNormalSink.clear();
222181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return output;
222281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
222381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
222481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// this method must always be called either with ThreadBase mLock held or inside the thread loop
222581784c37c61b09289654b979567a42bf73cd2b12Eric Laurentaudio_stream_t* AudioFlinger::PlaybackThread::stream() const
222681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
222781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (mOutput == NULL) {
222881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        return NULL;
222981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
223081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return &mOutput->stream->common;
223181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
223281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
223381784c37c61b09289654b979567a42bf73cd2b12Eric Laurentuint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
223481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
223581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
223681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
223781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
223881784c37c61b09289654b979567a42bf73cd2b12Eric Laurentstatus_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
223981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
224081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (!isValidSyncEvent(event)) {
224181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        return BAD_VALUE;
224281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
224381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
224481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
224581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
224681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    for (size_t i = 0; i < mTracks.size(); ++i) {
224781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sp<Track> track = mTracks[i];
224881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (event->triggerSession() == track->sessionId()) {
224981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            (void) track->setSyncEvent(event);
225081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            return NO_ERROR;
225181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
225281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
225381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
225481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return NAME_NOT_FOUND;
225581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
225681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
225781784c37c61b09289654b979567a42bf73cd2b12Eric Laurentbool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
225881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
225981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
226081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
226181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
226281784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::PlaybackThread::threadLoop_removeTracks(
226381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        const Vector< sp<Track> >& tracksToRemove)
226481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
226581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    size_t count = tracksToRemove.size();
226634fca34606b448e6b71c2942f63cb13a0aebd620Glenn Kasten    if (count > 0) {
226781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        for (size_t i = 0 ; i < count ; i++) {
226881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            const sp<Track>& track = tracksToRemove.itemAt(i);
226983b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent            if (track->isExternalTrack()) {
2270e83b55dc29ca16092ba02f36f55fa6e0e37fd78cEric Laurent                AudioSystem::stopOutput(mId, track->streamType(),
2271e83b55dc29ca16092ba02f36f55fa6e0e37fd78cEric Laurent                                        (audio_session_t)track->sessionId());
2272bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent#ifdef ADD_BATTERY_DATA
2273bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                // to track the speaker usage
2274bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2275bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent#endif
2276bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                if (track->isTerminated()) {
2277e83b55dc29ca16092ba02f36f55fa6e0e37fd78cEric Laurent                    AudioSystem::releaseOutput(mId, track->streamType(),
2278e83b55dc29ca16092ba02f36f55fa6e0e37fd78cEric Laurent                                               (audio_session_t)track->sessionId());
2279bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                }
228081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
228181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
228281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
228381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
228481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
228581784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::PlaybackThread::checkSilentMode_l()
228681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
228781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (!mMasterMute) {
228881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        char value[PROPERTY_VALUE_MAX];
228981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (property_get("ro.audio.silent", value, "0") > 0) {
229081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            char *endptr;
229181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            unsigned long ul = strtoul(value, &endptr, 0);
229281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if (*endptr == '\0' && ul != 0) {
229381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                ALOGD("Silence is golden");
229481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // The setprop command will not allow a property to be changed after
229581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // the first time it is set, so we don't have to worry about un-muting.
229681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                setMasterMute_l(true);
229781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
229881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
229981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
230081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
230181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
230281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// shared by MIXER and DIRECT, overridden by DUPLICATING
2303bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurentssize_t AudioFlinger::PlaybackThread::threadLoop_write()
230481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
230581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // FIXME rewrite to reduce number of system calls
230681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mLastWriteTime = systemTime();
230781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mInWrite = true;
2308bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    ssize_t bytesWritten;
2309010a1a1a552cdaad362cea8a0333b8906402dbcbAndy Hung    const size_t offset = mCurrentWriteLength - mBytesRemaining;
231081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
231181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // If an NBAIO sink is present, use it to write the normal mixer's submix
231281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (mNormalSink != 0) {
23134c053ea158b29fa2cdd4c6f39d3c8da4ee5a7a02Glenn Kasten
2314010a1a1a552cdaad362cea8a0333b8906402dbcbAndy Hung        const size_t count = mBytesRemaining / mFrameSize;
2315010a1a1a552cdaad362cea8a0333b8906402dbcbAndy Hung
23162d590964aa58e137d17a43e095e6443dd0fe2e98Simon Wilson        ATRACE_BEGIN("write");
231781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // update the setpoint when AudioFlinger::mScreenState changes
231881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        uint32_t screenState = AudioFlinger::mScreenState;
231981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (screenState != mScreenState) {
232081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mScreenState = screenState;
232181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
232281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if (pipe != NULL) {
232381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                pipe->setAvgFrames((mScreenState & 1) ?
232481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                        (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
232581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
232681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
2327010a1a1a552cdaad362cea8a0333b8906402dbcbAndy Hung        ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
23282d590964aa58e137d17a43e095e6443dd0fe2e98Simon Wilson        ATRACE_END();
232981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (framesWritten > 0) {
2330010a1a1a552cdaad362cea8a0333b8906402dbcbAndy Hung            bytesWritten = framesWritten * mFrameSize;
233181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        } else {
233281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            bytesWritten = framesWritten;
233381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
2334efaa7ab620b2ee936efa4fb74dc4c670ed757a46Glenn Kasten        mLatchDValid = false;
2335767094dd98b01baf21de2ad09c27b3c98776cf73Glenn Kasten        status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
2336bd096fd9d8e5fc0e62f98807f4818a06f70d0812Glenn Kasten        if (status == NO_ERROR) {
2337bd096fd9d8e5fc0e62f98807f4818a06f70d0812Glenn Kasten            size_t totalFramesWritten = mNormalSink->framesWritten();
2338bd096fd9d8e5fc0e62f98807f4818a06f70d0812Glenn Kasten            if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
2339bd096fd9d8e5fc0e62f98807f4818a06f70d0812Glenn Kasten                mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
23404c053ea158b29fa2cdd4c6f39d3c8da4ee5a7a02Glenn Kasten                // mLatchD.mFramesReleased is set immediately before D is clocked into Q
2341bd096fd9d8e5fc0e62f98807f4818a06f70d0812Glenn Kasten                mLatchDValid = true;
2342bd096fd9d8e5fc0e62f98807f4818a06f70d0812Glenn Kasten            }
2343bd096fd9d8e5fc0e62f98807f4818a06f70d0812Glenn Kasten        }
234481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // otherwise use the HAL / AudioStreamOut directly
234581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    } else {
2346bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        // Direct output and offload threads
2347010a1a1a552cdaad362cea8a0333b8906402dbcbAndy Hung
2348bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        if (mUseAsyncWrite) {
23493b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent            ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
23503b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent            mWriteAckSequence += 2;
23513b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent            mWriteAckSequence |= 1;
2352bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            ALOG_ASSERT(mCallbackThread != 0);
23533b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent            mCallbackThread->setWriteBlocked(mWriteAckSequence);
2354bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        }
2355767094dd98b01baf21de2ad09c27b3c98776cf73Glenn Kasten        // FIXME We should have an implementation of timestamps for direct output threads.
2356767094dd98b01baf21de2ad09c27b3c98776cf73Glenn Kasten        // They are used e.g for multichannel PCM playback over HDMI.
2357062e67a26e0553dd142be622821f493df541f0c6Phil Burk        bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
2358bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        if (mUseAsyncWrite &&
2359bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2360bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            // do not wait for async callback in case of error of full write
23613b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent            mWriteAckSequence &= ~1;
2362bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            ALOG_ASSERT(mCallbackThread != 0);
23633b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent            mCallbackThread->setWriteBlocked(mWriteAckSequence);
2364bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        }
236581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
236681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
236781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mNumWrites++;
236881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mInWrite = false;
2369fd4779740ec3e9e865d5514464df26d015354388Eric Laurent    mStandby = false;
2370bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    return bytesWritten;
2371bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent}
2372bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
2373bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurentvoid AudioFlinger::PlaybackThread::threadLoop_drain()
2374bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent{
2375bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    if (mOutput->stream->drain) {
2376bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2377bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        if (mUseAsyncWrite) {
23783b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent            ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
23793b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent            mDrainSequence |= 1;
2380bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            ALOG_ASSERT(mCallbackThread != 0);
23813b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent            mCallbackThread->setDraining(mDrainSequence);
2382bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        }
2383bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        mOutput->stream->drain(mOutput->stream,
2384bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2385bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                                                : AUDIO_DRAIN_ALL);
2386bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    }
2387bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent}
2388bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
2389bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurentvoid AudioFlinger::PlaybackThread::threadLoop_exit()
2390bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent{
2391275e8e9de2e11b4b344f5a201f1f0e51fda02d9cEric Laurent    {
2392275e8e9de2e11b4b344f5a201f1f0e51fda02d9cEric Laurent        Mutex::Autolock _l(mLock);
2393275e8e9de2e11b4b344f5a201f1f0e51fda02d9cEric Laurent        for (size_t i = 0; i < mTracks.size(); i++) {
2394275e8e9de2e11b4b344f5a201f1f0e51fda02d9cEric Laurent            sp<Track> track = mTracks[i];
2395275e8e9de2e11b4b344f5a201f1f0e51fda02d9cEric Laurent            track->invalidate();
2396275e8e9de2e11b4b344f5a201f1f0e51fda02d9cEric Laurent        }
2397275e8e9de2e11b4b344f5a201f1f0e51fda02d9cEric Laurent    }
239881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
239981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
240081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent/*
240181784c37c61b09289654b979567a42bf73cd2b12Eric LaurentThe derived values that are cached:
240225c2dac12114699e90deb1c579cadebce7b91a97Andy Hung - mSinkBufferSize from frame count * frame size
240381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent - activeSleepTime from activeSleepTimeUs()
240481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent - idleSleepTime from idleSleepTimeUs()
240581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent - standbyDelay from mActiveSleepTimeUs (DIRECT only)
240681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent - maxPeriod from frame count and sample rate (MIXER only)
240781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
240881784c37c61b09289654b979567a42bf73cd2b12Eric LaurentThe parameters that affect these derived values are:
240981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent - frame count
241081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent - frame size
241181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent - sample rate
241281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent - device type: A2DP or not
241381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent - device latency
241481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent - format: PCM or not
241581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent - active sleep time
241681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent - idle sleep time
241781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent*/
241881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
241981784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::PlaybackThread::cacheParameters_l()
242081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
242125c2dac12114699e90deb1c579cadebce7b91a97Andy Hung    mSinkBufferSize = mNormalFrameCount * mFrameSize;
242281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    activeSleepTime = activeSleepTimeUs();
242381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    idleSleepTime = idleSleepTimeUs();
242481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
242581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
242681784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
242781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
24287c027248e1a4ccd5b22bc4deafb03e2d87ac8f38Glenn Kasten    ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
242981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            this,  streamType, mTracks.size());
243081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
243181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
243281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    size_t size = mTracks.size();
243381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    for (size_t i = 0; i < size; i++) {
243481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sp<Track> t = mTracks[i];
243581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (t->streamType() == streamType) {
24365736c35b841de56ce394b4879389f669b61425e6Glenn Kasten            t->invalidate();
243781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
243881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
243981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
244081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
244181784c37c61b09289654b979567a42bf73cd2b12Eric Laurentstatus_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
244281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
244381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    int session = chain->sessionId();
2444010a1a1a552cdaad362cea8a0333b8906402dbcbAndy Hung    int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2445010a1a1a552cdaad362cea8a0333b8906402dbcbAndy Hung            ? mEffectBuffer : mSinkBuffer);
244681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    bool ownsBuffer = false;
244781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
244881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
244981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (session > 0) {
245081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // Only one effect chain can be present in direct output thread and it uses
24512098f2744cedf2dc3fa36f608aa965a34602e7c0Andy Hung        // the sink buffer as input
245281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (mType != DIRECT) {
245381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            size_t numSamples = mNormalFrameCount * mChannelCount;
245481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            buffer = new int16_t[numSamples];
245581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            memset(buffer, 0, numSamples * sizeof(int16_t));
245681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
245781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            ownsBuffer = true;
245881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
245981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
246081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // Attach all tracks with same session ID to this chain.
246181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        for (size_t i = 0; i < mTracks.size(); ++i) {
246281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            sp<Track> track = mTracks[i];
246381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if (session == track->sessionId()) {
246481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
246581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                        buffer);
246681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                track->setMainBuffer(buffer);
246781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                chain->incTrackCnt();
246881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
246981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
247081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
247181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // indicate all active tracks in the chain
247281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
247381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            sp<Track> track = mActiveTracks[i].promote();
247481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if (track == 0) {
247581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                continue;
247681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
247781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if (session == track->sessionId()) {
247881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
247981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                chain->incActiveTrackCnt();
248081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
248181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
248281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
2483aaa44478a373232d8416657035a9020f9c7aa7c3Eric Laurent    chain->setThread(this);
248481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    chain->setInBuffer(buffer, ownsBuffer);
2485010a1a1a552cdaad362cea8a0333b8906402dbcbAndy Hung    chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2486010a1a1a552cdaad362cea8a0333b8906402dbcbAndy Hung            ? mEffectBuffer : mSinkBuffer));
248781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
248881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // chains list in order to be processed last as it contains output stage effects
248981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
249081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // session AUDIO_SESSION_OUTPUT_STAGE to be processed
249181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // after track specific effects and before output stage
249281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
249381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
249481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // Effect chain for other sessions are inserted at beginning of effect
249581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // chains list to be processed before output mix effects. Relative order between other
249681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // sessions is not important
249781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    size_t size = mEffectChains.size();
249881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    size_t i = 0;
249981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    for (i = 0; i < size; i++) {
250081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (mEffectChains[i]->sessionId() < session) {
250181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            break;
250281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
250381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
250481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mEffectChains.insertAt(chain, i);
250581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    checkSuspendOnAddEffectChain_l(chain);
250681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
250781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return NO_ERROR;
250881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
250981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
251081784c37c61b09289654b979567a42bf73cd2b12Eric Laurentsize_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
251181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
251281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    int session = chain->sessionId();
251381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
251481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
251581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
251681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    for (size_t i = 0; i < mEffectChains.size(); i++) {
251781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (chain == mEffectChains[i]) {
251881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mEffectChains.removeAt(i);
251981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // detach all active tracks from the chain
252081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
252181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                sp<Track> track = mActiveTracks[i].promote();
252281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                if (track == 0) {
252381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    continue;
252481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
252581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                if (session == track->sessionId()) {
252681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
252781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                            chain.get(), session);
252881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    chain->decActiveTrackCnt();
252981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
253081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
253181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
253281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // detach all tracks with same session ID from this chain
253381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            for (size_t i = 0; i < mTracks.size(); ++i) {
253481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                sp<Track> track = mTracks[i];
253581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                if (session == track->sessionId()) {
2536010a1a1a552cdaad362cea8a0333b8906402dbcbAndy Hung                    track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
253781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    chain->decTrackCnt();
253881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
253981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
254081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            break;
254181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
254281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
254381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return mEffectChains.size();
254481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
254581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
254681784c37c61b09289654b979567a42bf73cd2b12Eric Laurentstatus_t AudioFlinger::PlaybackThread::attachAuxEffect(
254781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
254881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
254981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
255081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return attachAuxEffect_l(track, EffectId);
255181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
255281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
255381784c37c61b09289654b979567a42bf73cd2b12Eric Laurentstatus_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
255481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
255581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
255681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    status_t status = NO_ERROR;
255781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
255881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (EffectId == 0) {
255981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        track->setAuxBuffer(0, NULL);
256081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    } else {
256181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
256281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
256381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (effect != 0) {
256481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
256581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
256681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            } else {
256781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                status = INVALID_OPERATION;
256881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
256981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        } else {
257081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            status = BAD_VALUE;
257181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
257281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
257381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return status;
257481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
257581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
257681784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
257781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
257881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    for (size_t i = 0; i < mTracks.size(); ++i) {
257981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sp<Track> track = mTracks[i];
258081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (track->auxEffectId() == effectId) {
258181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            attachAuxEffect_l(track, 0);
258281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
258381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
258481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
258581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
258681784c37c61b09289654b979567a42bf73cd2b12Eric Laurentbool AudioFlinger::PlaybackThread::threadLoop()
258781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
258881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Vector< sp<Track> > tracksToRemove;
258981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
259081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    standbyTime = systemTime();
259181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
259281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // MIXER
259381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    nsecs_t lastWarning = 0;
259481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
259581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // DUPLICATING
259681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // FIXME could this be made local to while loop?
259781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    writeFrames = 0;
259881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
2599462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen    int lastGeneration = 0;
2600462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen
260181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    cacheParameters_l();
260281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    sleepTime = idleSleepTime;
260381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
260481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (mType == MIXER) {
260581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sleepTimeShift = 0;
260681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
260781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
260881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    CpuStats cpuStats;
260981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
261081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
261181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    acquireWakeLock();
261281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
26139e58b552f51b00b3b674102876bd6c77ef3da806Glenn Kasten    // mNBLogWriter->log can only be called while thread mutex mLock is held.
26149e58b552f51b00b3b674102876bd6c77ef3da806Glenn Kasten    // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
26159e58b552f51b00b3b674102876bd6c77ef3da806Glenn Kasten    // and then that string will be logged at the next convenient opportunity.
26169e58b552f51b00b3b674102876bd6c77ef3da806Glenn Kasten    const char *logString = NULL;
26179e58b552f51b00b3b674102876bd6c77ef3da806Glenn Kasten
2618664539d25180ab8f77e0521533ea2821cf28985fEric Laurent    checkSilentMode_l();
2619664539d25180ab8f77e0521533ea2821cf28985fEric Laurent
262081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    while (!exitPending())
262181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    {
262281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        cpuStats.sample(myName);
262381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
262481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        Vector< sp<EffectChain> > effectChains;
262581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
262681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        { // scope for mLock
262781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
262881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            Mutex::Autolock _l(mLock);
262981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
2630021cf9634ab09c0753a40b7c9ef4ba603be5c3daEric Laurent            processConfigEvents_l();
26311035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent
26329e58b552f51b00b3b674102876bd6c77ef3da806Glenn Kasten            if (logString != NULL) {
26339e58b552f51b00b3b674102876bd6c77ef3da806Glenn Kasten                mNBLogWriter->logTimestamp();
26349e58b552f51b00b3b674102876bd6c77ef3da806Glenn Kasten                mNBLogWriter->log(logString);
26359e58b552f51b00b3b674102876bd6c77ef3da806Glenn Kasten                logString = NULL;
26369e58b552f51b00b3b674102876bd6c77ef3da806Glenn Kasten            }
26379e58b552f51b00b3b674102876bd6c77ef3da806Glenn Kasten
26384c053ea158b29fa2cdd4c6f39d3c8da4ee5a7a02Glenn Kasten            // Gather the framesReleased counters for all active tracks,
26394c053ea158b29fa2cdd4c6f39d3c8da4ee5a7a02Glenn Kasten            // and latch them atomically with the timestamp.
26404c053ea158b29fa2cdd4c6f39d3c8da4ee5a7a02Glenn Kasten            // FIXME We're using raw pointers as indices. A unique track ID would be a better index.
26414c053ea158b29fa2cdd4c6f39d3c8da4ee5a7a02Glenn Kasten            mLatchD.mFramesReleased.clear();
26424c053ea158b29fa2cdd4c6f39d3c8da4ee5a7a02Glenn Kasten            size_t size = mActiveTracks.size();
26434c053ea158b29fa2cdd4c6f39d3c8da4ee5a7a02Glenn Kasten            for (size_t i = 0; i < size; i++) {
26444c053ea158b29fa2cdd4c6f39d3c8da4ee5a7a02Glenn Kasten                sp<Track> t = mActiveTracks[i].promote();
26454c053ea158b29fa2cdd4c6f39d3c8da4ee5a7a02Glenn Kasten                if (t != 0) {
26464c053ea158b29fa2cdd4c6f39d3c8da4ee5a7a02Glenn Kasten                    mLatchD.mFramesReleased.add(t.get(),
26474c053ea158b29fa2cdd4c6f39d3c8da4ee5a7a02Glenn Kasten                            t->mAudioTrackServerProxy->framesReleased());
26484c053ea158b29fa2cdd4c6f39d3c8da4ee5a7a02Glenn Kasten                }
26494c053ea158b29fa2cdd4c6f39d3c8da4ee5a7a02Glenn Kasten            }
2650bd096fd9d8e5fc0e62f98807f4818a06f70d0812Glenn Kasten            if (mLatchDValid) {
2651bd096fd9d8e5fc0e62f98807f4818a06f70d0812Glenn Kasten                mLatchQ = mLatchD;
2652bd096fd9d8e5fc0e62f98807f4818a06f70d0812Glenn Kasten                mLatchDValid = false;
2653bd096fd9d8e5fc0e62f98807f4818a06f70d0812Glenn Kasten                mLatchQValid = true;
2654bd096fd9d8e5fc0e62f98807f4818a06f70d0812Glenn Kasten            }
2655bd096fd9d8e5fc0e62f98807f4818a06f70d0812Glenn Kasten
265681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            saveOutputTracks();
2657bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            if (mSignalPending) {
2658bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                // A signal was raised while we were unlocked
2659bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                mSignalPending = false;
2660bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            } else if (waitingAsyncCallback_l()) {
2661bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                if (exitPending()) {
2662bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                    break;
2663bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                }
2664bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                releaseWakeLock_l();
2665462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen                mWakeLockUids.clear();
2666462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen                mActiveTracksGeneration++;
2667bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                ALOGV("wait async completion");
2668bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                mWaitWorkCV.wait(mLock);
2669bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                ALOGV("async completion/wake");
2670bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                acquireWakeLock_l();
2671972a173d7d1de1a3b5a617aae3e2abb6e05ae02dEric Laurent                standbyTime = systemTime() + standbyDelay;
2672972a173d7d1de1a3b5a617aae3e2abb6e05ae02dEric Laurent                sleepTime = 0;
2673ede6c3b8b1147bc425f7b923882f559a513fe23bEric Laurent
2674ede6c3b8b1147bc425f7b923882f559a513fe23bEric Laurent                continue;
2675ede6c3b8b1147bc425f7b923882f559a513fe23bEric Laurent            }
2676ede6c3b8b1147bc425f7b923882f559a513fe23bEric Laurent            if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
2677bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                                   isSuspended()) {
2678bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                // put audio hardware into standby after short delay
2679bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                if (shouldStandby_l()) {
268081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
268181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    threadLoop_standby();
268281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
268381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    mStandby = true;
268481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
268581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
268681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
268781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    // we're about to wait, flush the binder command buffer
268881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    IPCThreadState::self()->flushCommands();
268981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
269081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    clearOutputTracks();
269181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
269281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    if (exitPending()) {
269381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                        break;
269481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    }
269581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
269681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    releaseWakeLock_l();
2697462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen                    mWakeLockUids.clear();
2698462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen                    mActiveTracksGeneration++;
269981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    // wait until we have something to do...
270081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    ALOGV("%s going to sleep", myName.string());
270181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    mWaitWorkCV.wait(mLock);
270281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    ALOGV("%s waking up", myName.string());
270381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    acquireWakeLock_l();
270481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
270581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    mMixerStatus = MIXER_IDLE;
270681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    mMixerStatusIgnoringFastTracks = MIXER_IDLE;
270781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    mBytesWritten = 0;
2708bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                    mBytesRemaining = 0;
270981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    checkSilentMode_l();
271081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
271181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    standbyTime = systemTime() + standbyDelay;
271281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    sleepTime = idleSleepTime;
271381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    if (mType == MIXER) {
271481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                        sleepTimeShift = 0;
271581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    }
271681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
271781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    continue;
271881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
271981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
272081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // mMixerStatusIgnoringFastTracks is also updated internally
272181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mMixerStatus = prepareTracks_l(&tracksToRemove);
272281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
2723462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen            // compare with previously applied list
2724462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen            if (lastGeneration != mActiveTracksGeneration) {
2725462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen                // update wakelock
2726462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen                updateWakeLockUids_l(mWakeLockUids);
2727462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen                lastGeneration = mActiveTracksGeneration;
2728462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen            }
2729462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen
273081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // prevent any changes in effect chain list and in each effect chain
273181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // during mixing and effect process as the audio buffers could be deleted
273281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // or modified if an effect is created or deleted
273381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            lockEffectChains_l(effectChains);
2734462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen        } // mLock scope ends
273581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
2736bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        if (mBytesRemaining == 0) {
2737bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            mCurrentWriteLength = 0;
2738bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            if (mMixerStatus == MIXER_TRACKS_READY) {
2739bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                // threadLoop_mix() sets mCurrentWriteLength
2740bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                threadLoop_mix();
2741bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2742bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                        && (mMixerStatus != MIXER_DRAIN_ALL)) {
2743bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                // threadLoop_sleepTime sets sleepTime to 0 if data
2744bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                // must be written to HAL
2745bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                threadLoop_sleepTime();
2746bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                if (sleepTime == 0) {
274725c2dac12114699e90deb1c579cadebce7b91a97Andy Hung                    mCurrentWriteLength = mSinkBufferSize;
2748bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                }
2749bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            }
275098ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung            // Either threadLoop_mix() or threadLoop_sleepTime() should have set
275198ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung            // mMixerBuffer with data if mMixerBufferValid is true and sleepTime == 0.
275298ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung            // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
275398ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung            // or mSinkBuffer (if there are no effects).
275498ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung            //
275598ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung            // This is done pre-effects computation; if effects change to
275698ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung            // support higher precision, this needs to move.
275798ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung            //
275898ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung            // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
275998ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung            // TODO use sleepTime == 0 as an additional condition.
276098ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung            if (mMixerBufferValid) {
276198ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung                void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
276298ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung                audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
276398ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung
276498ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung                memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
276598ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung                        mNormalFrameCount * mChannelCount);
276698ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung            }
276798ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung
2768bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            mBytesRemaining = mCurrentWriteLength;
2769bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            if (isSuspended()) {
2770bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                sleepTime = suspendSleepTimeUs();
2771bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                // simulate write to HAL when suspended
277225c2dac12114699e90deb1c579cadebce7b91a97Andy Hung                mBytesWritten += mSinkBufferSize;
2773bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                mBytesRemaining = 0;
2774bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            }
277581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
2776bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            // only process effects if we're going to write
277759fe010bcc072597852454a2ec53d7b0a2002a3bEric Laurent            if (sleepTime == 0 && mType != OFFLOAD) {
2778bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                for (size_t i = 0; i < effectChains.size(); i ++) {
2779bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                    effectChains[i]->process_l();
2780bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                }
278181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
278281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
278359fe010bcc072597852454a2ec53d7b0a2002a3bEric Laurent        // Process effect chains for offloaded thread even if no audio
278459fe010bcc072597852454a2ec53d7b0a2002a3bEric Laurent        // was read from audio track: process only updates effect state
278559fe010bcc072597852454a2ec53d7b0a2002a3bEric Laurent        // and thus does have to be synchronized with audio writes but may have
278659fe010bcc072597852454a2ec53d7b0a2002a3bEric Laurent        // to be called while waiting for async write callback
278759fe010bcc072597852454a2ec53d7b0a2002a3bEric Laurent        if (mType == OFFLOAD) {
278859fe010bcc072597852454a2ec53d7b0a2002a3bEric Laurent            for (size_t i = 0; i < effectChains.size(); i ++) {
278959fe010bcc072597852454a2ec53d7b0a2002a3bEric Laurent                effectChains[i]->process_l();
279059fe010bcc072597852454a2ec53d7b0a2002a3bEric Laurent            }
279159fe010bcc072597852454a2ec53d7b0a2002a3bEric Laurent        }
279281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
279398ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung        // Only if the Effects buffer is enabled and there is data in the
279498ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung        // Effects buffer (buffer valid), we need to
279598ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung        // copy into the sink buffer.
279698ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung        // TODO use sleepTime == 0 as an additional condition.
279798ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung        if (mEffectBufferValid) {
279898ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung            //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
279998ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung            memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
280098ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung                    mNormalFrameCount * mChannelCount);
280198ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung        }
280298ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung
280381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // enable changes in effect chain
280481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        unlockEffectChains(effectChains);
280581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
2806bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        if (!waitingAsyncCallback()) {
2807bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            // sleepTime == 0 means we must write to audio hardware
2808bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            if (sleepTime == 0) {
2809bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                if (mBytesRemaining) {
2810bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                    ssize_t ret = threadLoop_write();
2811bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                    if (ret < 0) {
2812bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                        mBytesRemaining = 0;
2813bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                    } else {
2814bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                        mBytesWritten += ret;
2815bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                        mBytesRemaining -= ret;
2816bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                    }
2817bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2818bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                        (mMixerStatus == MIXER_DRAIN_ALL)) {
2819bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                    threadLoop_drain();
2820bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                }
28214944acb7355b3aa25748fd25945a363a69d65444Glenn Kasten                if (mType == MIXER) {
28224944acb7355b3aa25748fd25945a363a69d65444Glenn Kasten                    // write blocked detection
28234944acb7355b3aa25748fd25945a363a69d65444Glenn Kasten                    nsecs_t now = systemTime();
28244944acb7355b3aa25748fd25945a363a69d65444Glenn Kasten                    nsecs_t delta = now - mLastWriteTime;
28254944acb7355b3aa25748fd25945a363a69d65444Glenn Kasten                    if (!mStandby && delta > maxPeriod) {
28264944acb7355b3aa25748fd25945a363a69d65444Glenn Kasten                        mNumDelayedWrites++;
28274944acb7355b3aa25748fd25945a363a69d65444Glenn Kasten                        if ((now - lastWarning) > kWarningThrottleNs) {
28284944acb7355b3aa25748fd25945a363a69d65444Glenn Kasten                            ATRACE_NAME("underrun");
28294944acb7355b3aa25748fd25945a363a69d65444Glenn Kasten                            ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
28304944acb7355b3aa25748fd25945a363a69d65444Glenn Kasten                                    ns2ms(delta), mNumDelayedWrites, this);
28314944acb7355b3aa25748fd25945a363a69d65444Glenn Kasten                            lastWarning = now;
28324944acb7355b3aa25748fd25945a363a69d65444Glenn Kasten                        }
2833bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                    }
283481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
283581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
2836bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            } else {
2837e77540228e1f60b1129a1615d2e43e0bf8015d3cGlenn Kasten                ATRACE_BEGIN("sleep");
2838bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                usleep(sleepTime);
2839e77540228e1f60b1129a1615d2e43e0bf8015d3cGlenn Kasten                ATRACE_END();
2840bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            }
284181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
284281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
284381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // Finally let go of removed track(s), without the lock held
284481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // since we can't guarantee the destructors won't acquire that
284581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // same lock.  This will also mutate and push a new fast mixer state.
284681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        threadLoop_removeTracks(tracksToRemove);
284781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        tracksToRemove.clear();
284881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
284981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // FIXME I don't understand the need for this here;
285081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        //       it was in the original code but maybe the
285181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        //       assignment in saveOutputTracks() makes this unnecessary?
285281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        clearOutputTracks();
285381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
285481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // Effect chains will be actually deleted here if they were removed from
285581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // mEffectChains list during mixing or effects processing
285681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        effectChains.clear();
285781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
285881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // FIXME Note that the above .clear() is no longer necessary since effectChains
285981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // is now local to this block, but will keep it for now (at least until merge done).
286081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
286181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
2862bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    threadLoop_exit();
2863bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
2864cf817a2330936947df94c11859f48771f5596a59Eric Laurent    if (!mStandby) {
2865cf817a2330936947df94c11859f48771f5596a59Eric Laurent        threadLoop_standby();
2866cf817a2330936947df94c11859f48771f5596a59Eric Laurent        mStandby = true;
286781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
286881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
286981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    releaseWakeLock();
2870462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen    mWakeLockUids.clear();
2871462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen    mActiveTracksGeneration++;
287281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
287381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    ALOGV("Thread %p type %d exiting", this, mType);
287481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return false;
287581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
287681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
2877bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent// removeTracks_l() must be called with ThreadBase::mLock held
2878bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurentvoid AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2879bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent{
2880bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    size_t count = tracksToRemove.size();
288134fca34606b448e6b71c2942f63cb13a0aebd620Glenn Kasten    if (count > 0) {
2882bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        for (size_t i=0 ; i<count ; i++) {
2883bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            const sp<Track>& track = tracksToRemove.itemAt(i);
2884bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            mActiveTracks.remove(track);
2885462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen            mWakeLockUids.remove(track->uid());
2886462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen            mActiveTracksGeneration++;
2887bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2888bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2889bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            if (chain != 0) {
2890bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2891bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                        track->sessionId());
2892bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                chain->decActiveTrackCnt();
2893bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            }
2894bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            if (track->isTerminated()) {
2895bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                removeTrack_l(track);
2896bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            }
2897bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        }
2898bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    }
2899bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
2900bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent}
290181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
2902accc147666bfd37fc8b4ef745f18a8c751555ec2Eric Laurentstatus_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2903accc147666bfd37fc8b4ef745f18a8c751555ec2Eric Laurent{
2904accc147666bfd37fc8b4ef745f18a8c751555ec2Eric Laurent    if (mNormalSink != 0) {
2905accc147666bfd37fc8b4ef745f18a8c751555ec2Eric Laurent        return mNormalSink->getTimestamp(timestamp);
2906accc147666bfd37fc8b4ef745f18a8c751555ec2Eric Laurent    }
29079a1c8892f6835325db6931529dc74bf98cf0aee8Andy Hung    if ((mType == OFFLOAD || mType == DIRECT)
29089a1c8892f6835325db6931529dc74bf98cf0aee8Andy Hung            && mOutput != NULL && mOutput->stream->get_presentation_position) {
2909accc147666bfd37fc8b4ef745f18a8c751555ec2Eric Laurent        uint64_t position64;
2910062e67a26e0553dd142be622821f493df541f0c6Phil Burk        int ret = mOutput->getPresentationPosition(&position64, &timestamp.mTime);
2911accc147666bfd37fc8b4ef745f18a8c751555ec2Eric Laurent        if (ret == 0) {
2912accc147666bfd37fc8b4ef745f18a8c751555ec2Eric Laurent            timestamp.mPosition = (uint32_t)position64;
2913accc147666bfd37fc8b4ef745f18a8c751555ec2Eric Laurent            return NO_ERROR;
2914accc147666bfd37fc8b4ef745f18a8c751555ec2Eric Laurent        }
2915accc147666bfd37fc8b4ef745f18a8c751555ec2Eric Laurent    }
2916accc147666bfd37fc8b4ef745f18a8c751555ec2Eric Laurent    return INVALID_OPERATION;
2917accc147666bfd37fc8b4ef745f18a8c751555ec2Eric Laurent}
29181c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent
29191c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurentstatus_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
29201c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent                                                          audio_patch_handle_t *handle)
29211c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent{
29221c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent    status_t status = NO_ERROR;
29231c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent    if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
29241c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent        // store new device and send to effects
29251c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent        audio_devices_t type = AUDIO_DEVICE_NONE;
29261c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent        for (unsigned int i = 0; i < patch->num_sinks; i++) {
29271c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent            type |= patch->sinks[i].ext.device.type;
29281c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent        }
29291c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent        mOutDevice = type;
29301c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent        for (size_t i = 0; i < mEffectChains.size(); i++) {
29311c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent            mEffectChains[i]->setDevice_l(mOutDevice);
29321c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent        }
29331c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent
29341c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent        audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
29351c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent        status = hwDevice->create_audio_patch(hwDevice,
29361c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent                                               patch->num_sources,
29371c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent                                               patch->sources,
29381c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent                                               patch->num_sinks,
29391c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent                                               patch->sinks,
29401c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent                                               handle);
29411c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent    } else {
29421c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent        ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
29431c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent    }
29441c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent    return status;
29451c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent}
29461c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent
29471c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurentstatus_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
29481c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent{
29491c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent    status_t status = NO_ERROR;
29501c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent    if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
29511c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent        audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
29521c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent        status = hwDevice->release_audio_patch(hwDevice, handle);
29531c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent    } else {
29541c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent        ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
29551c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent    }
29561c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent    return status;
29571c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent}
29581c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent
295983b8808faad1e91690c64d7007348be8d9ebde73Eric Laurentvoid AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
296083b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent{
296183b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent    Mutex::Autolock _l(mLock);
296283b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent    mTracks.add(track);
296383b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent}
296483b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent
296583b8808faad1e91690c64d7007348be8d9ebde73Eric Laurentvoid AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
296683b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent{
296783b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent    Mutex::Autolock _l(mLock);
296883b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent    destroyTrack_l(track);
296983b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent}
297083b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent
297183b8808faad1e91690c64d7007348be8d9ebde73Eric Laurentvoid AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
297283b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent{
297383b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent    ThreadBase::getAudioPortConfig(config);
297483b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent    config->role = AUDIO_PORT_ROLE_SOURCE;
297583b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent    config->ext.mix.hw_module = mOutput->audioHwDev->handle();
297683b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent    config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
297783b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent}
297883b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent
297981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// ----------------------------------------------------------------------------
298081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
298181784c37c61b09289654b979567a42bf73cd2b12Eric LaurentAudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
298281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        audio_io_handle_t id, audio_devices_t device, type_t type)
298381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    :   PlaybackThread(audioFlinger, output, id, device, type),
298481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // mAudioMixer below
298581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // mFastMixer below
298681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mFastMixerFutex(0)
298781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // mOutputSink below
298881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // mPipeSink below
298981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // mNormalSink below
299081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
299181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
2992f6ed423af92a56ef54bba23eba883b1f21448b54Glenn Kasten    ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
299381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            "mFrameCount=%d, mNormalFrameCount=%d",
299481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
299581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mNormalFrameCount);
299681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
299781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
2998fbfc3959f4aac839445edc7075532067fef497c2Andy Hung    if (type == DUPLICATING) {
2999fbfc3959f4aac839445edc7075532067fef497c2Andy Hung        // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3000fbfc3959f4aac839445edc7075532067fef497c2Andy Hung        // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3001fbfc3959f4aac839445edc7075532067fef497c2Andy Hung        // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3002fbfc3959f4aac839445edc7075532067fef497c2Andy Hung        return;
3003fbfc3959f4aac839445edc7075532067fef497c2Andy Hung    }
300481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // create an NBAIO sink for the HAL output stream, and negotiate
300581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mOutputSink = new AudioStreamOutSink(output->stream);
300681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    size_t numCounterOffers = 0;
3007f69f9869514730aebe5724c461768507084dfff7Glenn Kasten    const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
300881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
300981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    ALOG_ASSERT(index == 0);
301081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
301181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // initialize fast mixer depending on configuration
301281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    bool initFastMixer;
301381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    switch (kUseFastMixer) {
301481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    case FastMixer_Never:
301581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        initFastMixer = false;
301681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        break;
301781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    case FastMixer_Always:
301881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        initFastMixer = true;
301981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        break;
302081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    case FastMixer_Static:
302181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    case FastMixer_Dynamic:
302281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        initFastMixer = mFrameCount < mNormalFrameCount;
302381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        break;
302481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
302581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (initFastMixer) {
30261258c1ab592a899fabb1e31eb5db2ef413b6f38aAndy Hung        audio_format_t fastMixerFormat;
30271258c1ab592a899fabb1e31eb5db2ef413b6f38aAndy Hung        if (mMixerBufferEnabled && mEffectBufferEnabled) {
30281258c1ab592a899fabb1e31eb5db2ef413b6f38aAndy Hung            fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
30291258c1ab592a899fabb1e31eb5db2ef413b6f38aAndy Hung        } else {
30301258c1ab592a899fabb1e31eb5db2ef413b6f38aAndy Hung            fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
30311258c1ab592a899fabb1e31eb5db2ef413b6f38aAndy Hung        }
30321258c1ab592a899fabb1e31eb5db2ef413b6f38aAndy Hung        if (mFormat != fastMixerFormat) {
30331258c1ab592a899fabb1e31eb5db2ef413b6f38aAndy Hung            // change our Sink format to accept our intermediate precision
30341258c1ab592a899fabb1e31eb5db2ef413b6f38aAndy Hung            mFormat = fastMixerFormat;
30351258c1ab592a899fabb1e31eb5db2ef413b6f38aAndy Hung            free(mSinkBuffer);
30361258c1ab592a899fabb1e31eb5db2ef413b6f38aAndy Hung            mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
30371258c1ab592a899fabb1e31eb5db2ef413b6f38aAndy Hung            const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
30381258c1ab592a899fabb1e31eb5db2ef413b6f38aAndy Hung            (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
30391258c1ab592a899fabb1e31eb5db2ef413b6f38aAndy Hung        }
304081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
304181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // create a MonoPipe to connect our submix to FastMixer
304281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        NBAIO_Format format = mOutputSink->format();
3043ba0b34c18da93681c0813ecdab19b0e215b6d261Glenn Kasten        NBAIO_Format origformat = format;
30441258c1ab592a899fabb1e31eb5db2ef413b6f38aAndy Hung        // adjust format to match that of the Fast Mixer
304597b7b75b6a31330e213bdb96ccc60916218ad903Glenn Kasten        ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
30461258c1ab592a899fabb1e31eb5db2ef413b6f38aAndy Hung        format.mFormat = fastMixerFormat;
30471258c1ab592a899fabb1e31eb5db2ef413b6f38aAndy Hung        format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
30481258c1ab592a899fabb1e31eb5db2ef413b6f38aAndy Hung
304981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // This pipe depth compensates for scheduling latency of the normal mixer thread.
305081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // When it wakes up after a maximum latency, it runs a few cycles quickly before
305181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // finally blocking.  Note the pipe implementation rounds up the request to a power of 2.
305281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
305381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        const NBAIO_Format offers[1] = {format};
305481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        size_t numCounterOffers = 0;
305581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
305681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        ALOG_ASSERT(index == 0);
305781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        monoPipe->setAvgFrames((mScreenState & 1) ?
305881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
305981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mPipeSink = monoPipe;
306081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
306146909e7eb074ce1b95b8a411eb71154f53f84f77Glenn Kasten#ifdef TEE_SINK
3062da6ef1320d0161b1640dc84d7a9c5a25860c3619Glenn Kasten        if (mTeeSinkOutputEnabled) {
3063da6ef1320d0161b1640dc84d7a9c5a25860c3619Glenn Kasten            // create a Pipe to archive a copy of FastMixer's output for dumpsys
3064ba0b34c18da93681c0813ecdab19b0e215b6d261Glenn Kasten            Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3065ba0b34c18da93681c0813ecdab19b0e215b6d261Glenn Kasten            const NBAIO_Format offers2[1] = {origformat};
3066da6ef1320d0161b1640dc84d7a9c5a25860c3619Glenn Kasten            numCounterOffers = 0;
3067ba0b34c18da93681c0813ecdab19b0e215b6d261Glenn Kasten            index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
3068da6ef1320d0161b1640dc84d7a9c5a25860c3619Glenn Kasten            ALOG_ASSERT(index == 0);
3069da6ef1320d0161b1640dc84d7a9c5a25860c3619Glenn Kasten            mTeeSink = teeSink;
3070da6ef1320d0161b1640dc84d7a9c5a25860c3619Glenn Kasten            PipeReader *teeSource = new PipeReader(*teeSink);
3071da6ef1320d0161b1640dc84d7a9c5a25860c3619Glenn Kasten            numCounterOffers = 0;
3072ba0b34c18da93681c0813ecdab19b0e215b6d261Glenn Kasten            index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
3073da6ef1320d0161b1640dc84d7a9c5a25860c3619Glenn Kasten            ALOG_ASSERT(index == 0);
3074da6ef1320d0161b1640dc84d7a9c5a25860c3619Glenn Kasten            mTeeSource = teeSource;
3075da6ef1320d0161b1640dc84d7a9c5a25860c3619Glenn Kasten        }
307646909e7eb074ce1b95b8a411eb71154f53f84f77Glenn Kasten#endif
307781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
307881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // create fast mixer and configure it initially with just one fast track for our submix
307981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mFastMixer = new FastMixer();
308081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        FastMixerStateQueue *sq = mFastMixer->sq();
308181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#ifdef STATE_QUEUE_DUMP
308281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sq->setObserverDump(&mStateQueueObserverDump);
308381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sq->setMutatorDump(&mStateQueueMutatorDump);
308481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#endif
308581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        FastMixerState *state = sq->begin();
308681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        FastTrack *fastTrack = &state->mFastTracks[0];
308781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // wrap the source side of the MonoPipe to make it an AudioBufferProvider
308881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
308981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        fastTrack->mVolumeProvider = NULL;
3090e8a1ced4da17dc6c07803dc2af8060f62a8389c1Andy Hung        fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3091e8a1ced4da17dc6c07803dc2af8060f62a8389c1Andy Hung        fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
309281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        fastTrack->mGeneration++;
309381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        state->mFastTracksGen++;
309481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        state->mTrackMask = 1;
309581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // fast mixer will use the HAL output sink
309681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        state->mOutputSink = mOutputSink.get();
309781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        state->mOutputSinkGen++;
309881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        state->mFrameCount = mFrameCount;
309981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        state->mCommand = FastMixerState::COLD_IDLE;
310081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // already done in constructor initialization list
310181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        //mFastMixerFutex = 0;
310281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        state->mColdFutexAddr = &mFastMixerFutex;
310381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        state->mColdGen++;
310481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        state->mDumpState = &mFastMixerDumpState;
310546909e7eb074ce1b95b8a411eb71154f53f84f77Glenn Kasten#ifdef TEE_SINK
310681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        state->mTeeSink = mTeeSink.get();
310746909e7eb074ce1b95b8a411eb71154f53f84f77Glenn Kasten#endif
31089e58b552f51b00b3b674102876bd6c77ef3da806Glenn Kasten        mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
31099e58b552f51b00b3b674102876bd6c77ef3da806Glenn Kasten        state->mNBLogWriter = mFastMixerNBLogWriter.get();
311081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sq->end();
311181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
311281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
311381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // start the fast mixer
311481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
311581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        pid_t tid = mFastMixer->getTid();
311681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
311781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (err != 0) {
311881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
311981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    kPriorityFastMixer, getpid_cached, tid, err);
312081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
312181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
312281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#ifdef AUDIO_WATCHDOG
312381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // create and start the watchdog
312481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mAudioWatchdog = new AudioWatchdog();
312581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mAudioWatchdog->setDump(&mAudioWatchdogDump);
312681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
312781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        tid = mAudioWatchdog->getTid();
312881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
312981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (err != 0) {
313081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
313181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    kPriorityFastMixer, getpid_cached, tid, err);
313281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
313381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#endif
313481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
313581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
313681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
313781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    switch (kUseFastMixer) {
313881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    case FastMixer_Never:
313981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    case FastMixer_Dynamic:
314081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mNormalSink = mOutputSink;
314181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        break;
314281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    case FastMixer_Always:
314381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mNormalSink = mPipeSink;
314481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        break;
314581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    case FastMixer_Static:
314681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
314781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        break;
314881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
314981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
315081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
315181784c37c61b09289654b979567a42bf73cd2b12Eric LaurentAudioFlinger::MixerThread::~MixerThread()
315281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
31534d23ca370dd0ce584f49a80ef9dfcdbb75ba2c8eGlenn Kasten    if (mFastMixer != 0) {
315481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        FastMixerStateQueue *sq = mFastMixer->sq();
315581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        FastMixerState *state = sq->begin();
315681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (state->mCommand == FastMixerState::COLD_IDLE) {
315781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            int32_t old = android_atomic_inc(&mFastMixerFutex);
315881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if (old == -1) {
3159ee499291404a192b059f2e04c5afc65aa6cdd74cElliott Hughes                (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
316081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
316181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
316281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        state->mCommand = FastMixerState::EXIT;
316381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sq->end();
316481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
316581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mFastMixer->join();
316681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // Though the fast mixer thread has exited, it's state queue is still valid.
316781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // We'll use that extract the final state which contains one remaining fast track
316881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // corresponding to our sub-mix.
316981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        state = sq->begin();
317081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        ALOG_ASSERT(state->mTrackMask == 1);
317181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        FastTrack *fastTrack = &state->mFastTracks[0];
317281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
317381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        delete fastTrack->mBufferProvider;
317481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sq->end(false /*didModify*/);
31754d23ca370dd0ce584f49a80ef9dfcdbb75ba2c8eGlenn Kasten        mFastMixer.clear();
317681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#ifdef AUDIO_WATCHDOG
317781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (mAudioWatchdog != 0) {
317881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mAudioWatchdog->requestExit();
317981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mAudioWatchdog->requestExitAndWait();
318081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mAudioWatchdog.clear();
318181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
318281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#endif
318381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
31849e58b552f51b00b3b674102876bd6c77ef3da806Glenn Kasten    mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
318581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    delete mAudioMixer;
318681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
318781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
318881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
318981784c37c61b09289654b979567a42bf73cd2b12Eric Laurentuint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
319081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
31914d23ca370dd0ce584f49a80ef9dfcdbb75ba2c8eGlenn Kasten    if (mFastMixer != 0) {
319281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
319381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
319481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
319581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return latency;
319681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
319781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
319881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
319981784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
320081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
320181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    PlaybackThread::threadLoop_removeTracks(tracksToRemove);
320281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
320381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
3204bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurentssize_t AudioFlinger::MixerThread::threadLoop_write()
320581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
320681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // FIXME we should only do one push per cycle; confirm this is true
320781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // Start the fast mixer if it's not already running
32084d23ca370dd0ce584f49a80ef9dfcdbb75ba2c8eGlenn Kasten    if (mFastMixer != 0) {
320981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        FastMixerStateQueue *sq = mFastMixer->sq();
321081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        FastMixerState *state = sq->begin();
321181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (state->mCommand != FastMixerState::MIX_WRITE &&
321281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
321381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if (state->mCommand == FastMixerState::COLD_IDLE) {
321481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                int32_t old = android_atomic_inc(&mFastMixerFutex);
321581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                if (old == -1) {
3216ee499291404a192b059f2e04c5afc65aa6cdd74cElliott Hughes                    (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
321781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
321881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#ifdef AUDIO_WATCHDOG
321981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                if (mAudioWatchdog != 0) {
322081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    mAudioWatchdog->resume();
322181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
322281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#endif
322381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
322481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            state->mCommand = FastMixerState::MIX_WRITE;
3225d797a9d5daad3051f9ac1d348abc2f434ea3ddcfGlenn Kasten#ifdef FAST_THREAD_STATISTICS
32264182c4e2a07e2441fcd5c22eaff0ddfe7f826f61Glenn Kasten            mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
3227fbdb2aceab7317aa44bc8f301a93eb49e17b2bceGlenn Kasten                FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
3228d797a9d5daad3051f9ac1d348abc2f434ea3ddcfGlenn Kasten#endif
322981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            sq->end();
323081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
323181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if (kUseFastMixer == FastMixer_Dynamic) {
323281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                mNormalSink = mPipeSink;
323381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
323481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        } else {
323581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            sq->end(false /*didModify*/);
323681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
323781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
3238bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    return PlaybackThread::threadLoop_write();
323981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
324081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
324181784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::MixerThread::threadLoop_standby()
324281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
324381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // Idle the fast mixer if it's currently running
32444d23ca370dd0ce584f49a80ef9dfcdbb75ba2c8eGlenn Kasten    if (mFastMixer != 0) {
324581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        FastMixerStateQueue *sq = mFastMixer->sq();
324681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        FastMixerState *state = sq->begin();
324781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (!(state->mCommand & FastMixerState::IDLE)) {
324881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            state->mCommand = FastMixerState::COLD_IDLE;
324981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            state->mColdFutexAddr = &mFastMixerFutex;
325081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            state->mColdGen++;
325181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mFastMixerFutex = 0;
325281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            sq->end();
325381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
325481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
325581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if (kUseFastMixer == FastMixer_Dynamic) {
325681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                mNormalSink = mOutputSink;
325781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
325881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#ifdef AUDIO_WATCHDOG
325981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if (mAudioWatchdog != 0) {
326081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                mAudioWatchdog->pause();
326181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
326281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#endif
326381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        } else {
326481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            sq->end(false /*didModify*/);
326581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
326681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
326781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    PlaybackThread::threadLoop_standby();
326881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
326981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
3270bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurentbool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3271bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent{
3272bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    return false;
3273bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent}
3274bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
3275bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurentbool AudioFlinger::PlaybackThread::shouldStandby_l()
3276bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent{
3277bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    return !mStandby;
3278bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent}
3279bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
3280bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurentbool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3281bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent{
3282bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    Mutex::Autolock _l(mLock);
3283bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    return waitingAsyncCallback_l();
3284bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent}
3285bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
328681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// shared by MIXER and DIRECT, overridden by DUPLICATING
328781784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::PlaybackThread::threadLoop_standby()
328881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
328981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
3290062e67a26e0553dd142be622821f493df541f0c6Phil Burk    mOutput->standby();
3291bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    if (mUseAsyncWrite != 0) {
32923b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent        // discard any pending drain or write ack by incrementing sequence
32933b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent        mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
32943b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent        mDrainSequence = (mDrainSequence + 2) & ~1;
3295bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        ALOG_ASSERT(mCallbackThread != 0);
32963b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent        mCallbackThread->setWriteBlocked(mWriteAckSequence);
32973b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent        mCallbackThread->setDraining(mDrainSequence);
3298bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    }
3299d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    mHwPaused = false;
330081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
330181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
33024c6a433d74d5ae8b9bc0557207e3ced43bf34a25Haynes Mathew Georgevoid AudioFlinger::PlaybackThread::onAddNewTrack_l()
33034c6a433d74d5ae8b9bc0557207e3ced43bf34a25Haynes Mathew George{
33044c6a433d74d5ae8b9bc0557207e3ced43bf34a25Haynes Mathew George    ALOGV("signal playback thread");
33054c6a433d74d5ae8b9bc0557207e3ced43bf34a25Haynes Mathew George    broadcast_l();
33064c6a433d74d5ae8b9bc0557207e3ced43bf34a25Haynes Mathew George}
33074c6a433d74d5ae8b9bc0557207e3ced43bf34a25Haynes Mathew George
330881784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::MixerThread::threadLoop_mix()
330981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
331081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // obtain the presentation timestamp of the next output buffer
331181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    int64_t pts;
331281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    status_t status = INVALID_OPERATION;
331381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
331481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (mNormalSink != 0) {
331581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        status = mNormalSink->getNextWriteTimestamp(&pts);
331681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    } else {
331781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        status = mOutputSink->getNextWriteTimestamp(&pts);
331881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
331981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
332081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (status != NO_ERROR) {
332181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        pts = AudioBufferProvider::kInvalidPTS;
332281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
332381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
332481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // mix buffers...
332581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mAudioMixer->process(pts);
332625c2dac12114699e90deb1c579cadebce7b91a97Andy Hung    mCurrentWriteLength = mSinkBufferSize;
332781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // increase sleep time progressively when application underrun condition clears.
332881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // Only increase sleep time if the mixer is ready for two consecutive times to avoid
332981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // that a steady state of alternating ready/not ready conditions keeps the sleep time
333081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // such that we would underrun the audio HAL.
333181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if ((sleepTime == 0) && (sleepTimeShift > 0)) {
333281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sleepTimeShift--;
333381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
333481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    sleepTime = 0;
333581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    standbyTime = systemTime() + standbyDelay;
333681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    //TODO: delay standby when effects have a tail
33374c053ea158b29fa2cdd4c6f39d3c8da4ee5a7a02Glenn Kasten
333881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
333981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
334081784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::MixerThread::threadLoop_sleepTime()
334181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
334281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // If no tracks are ready, sleep once for the duration of an output
334381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // buffer size, then write 0s to the output
334481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (sleepTime == 0) {
334581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (mMixerStatus == MIXER_TRACKS_ENABLED) {
334681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            sleepTime = activeSleepTime >> sleepTimeShift;
334781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if (sleepTime < kMinThreadSleepTimeUs) {
334881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                sleepTime = kMinThreadSleepTimeUs;
334981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
335081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // reduce sleep time in case of consecutive application underruns to avoid
335181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
335281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // duration we would end up writing less data than needed by the audio HAL if
335381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // the condition persists.
335481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if (sleepTimeShift < kMaxThreadSleepTimeShift) {
335581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                sleepTimeShift++;
335681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
335781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        } else {
335881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            sleepTime = idleSleepTime;
335981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
336081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
336198ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung        // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
336298ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung        // before effects processing or output.
336398ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung        if (mMixerBufferValid) {
336498ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung            memset(mMixerBuffer, 0, mMixerBufferSize);
336598ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung        } else {
336698ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung            memset(mSinkBuffer, 0, mSinkBufferSize);
336798ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung        }
336881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sleepTime = 0;
336981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
337081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                "anticipated start");
337181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
337281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // TODO add standby time extension fct of effect tail
337381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
337481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
337581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// prepareTracks_l() must be called with ThreadBase::mLock held
337681784c37c61b09289654b979567a42bf73cd2b12Eric LaurentAudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
337781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        Vector< sp<Track> > *tracksToRemove)
337881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
337981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
338081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mixer_state mixerStatus = MIXER_IDLE;
338181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // find out which tracks need to be processed
338281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    size_t count = mActiveTracks.size();
338381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    size_t mixedTracks = 0;
338481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    size_t tracksWithEffect = 0;
338581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // counts only _active_ fast tracks
338681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    size_t fastTracks = 0;
338781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
338881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
338981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    float masterVolume = mMasterVolume;
339081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    bool masterMute = mMasterMute;
339181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
339281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (masterMute) {
339381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        masterVolume = 0;
339481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
339581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // Delegate master volume control to effect in output mix effect chain if needed
339681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
339781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (chain != 0) {
339881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        uint32_t v = (uint32_t)(masterVolume * (1 << 24));
339981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        chain->setVolume_l(&v, &v);
340081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        masterVolume = (float)((v + (1 << 23)) >> 24);
340181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        chain.clear();
340281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
340381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
340481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // prepare a new state to push
340581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    FastMixerStateQueue *sq = NULL;
340681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    FastMixerState *state = NULL;
340781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    bool didModify = false;
340881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
34094d23ca370dd0ce584f49a80ef9dfcdbb75ba2c8eGlenn Kasten    if (mFastMixer != 0) {
341081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sq = mFastMixer->sq();
341181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        state = sq->begin();
341281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
341381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
341469aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung    mMixerBufferValid = false;  // mMixerBuffer has no valid data until appropriate tracks found.
341598ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung    mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
341669aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung
341781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    for (size_t i=0 ; i<count ; i++) {
34189fdcb0a9497ca290bcf364b10868587b6bde3a34Glenn Kasten        const sp<Track> t = mActiveTracks[i].promote();
341981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (t == 0) {
342081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            continue;
342181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
342281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
342381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // this const just means the local variable doesn't change
342481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        Track* const track = t.get();
342581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
342681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // process fast tracks
342781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (track->isFastTrack()) {
342881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
342981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // It's theoretically possible (though unlikely) for a fast track to be created
343081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // and then removed within the same normal mix cycle.  This is not a problem, as
343181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // the track never becomes active so it's fast mixer slot is never touched.
343281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // The converse, of removing an (active) track and then creating a new track
343381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // at the identical fast mixer slot within the same normal mix cycle,
343481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // is impossible because the slot isn't marked available until the end of each cycle.
343581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            int j = track->mFastIndex;
343681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
343781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
343881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            FastTrack *fastTrack = &state->mFastTracks[j];
343981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
344081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // Determine whether the track is currently in underrun condition,
344181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // and whether it had a recent underrun.
344281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
344381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            FastTrackUnderruns underruns = ftDump->mUnderruns;
344481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            uint32_t recentFull = (underruns.mBitFields.mFull -
344581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
344681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            uint32_t recentPartial = (underruns.mBitFields.mPartial -
344781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
344881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
344981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
345081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            uint32_t recentUnderruns = recentPartial + recentEmpty;
345181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            track->mObservedUnderruns = underruns;
345281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // don't count underruns that occur while stopping or pausing
345381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // or stopped which can occur when flush() is called while active
345482aaf94a5b18939e4d790bbc752031f3070704a3Glenn Kasten            if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
345582aaf94a5b18939e4d790bbc752031f3070704a3Glenn Kasten                    recentUnderruns > 0) {
345682aaf94a5b18939e4d790bbc752031f3070704a3Glenn Kasten                // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
345782aaf94a5b18939e4d790bbc752031f3070704a3Glenn Kasten                track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
345881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
345981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
346081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // This is similar to the state machine for normal tracks,
346181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // with a few modifications for fast tracks.
346281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            bool isActive = true;
346381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            switch (track->mState) {
346481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            case TrackBase::STOPPING_1:
346581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // track stays active in STOPPING_1 state until first underrun
3466bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                if (recentUnderruns > 0 || track->isTerminated()) {
346781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    track->mState = TrackBase::STOPPING_2;
346881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
346981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                break;
347081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            case TrackBase::PAUSING:
347181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // ramp down is not yet implemented
347281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                track->setPaused();
347381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                break;
347481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            case TrackBase::RESUMING:
347581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // ramp up is not yet implemented
347681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                track->mState = TrackBase::ACTIVE;
347781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                break;
347881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            case TrackBase::ACTIVE:
347981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                if (recentFull > 0 || recentPartial > 0) {
348081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    // track has provided at least some frames recently: reset retry count
348181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    track->mRetryCount = kMaxTrackRetries;
348281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
348381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                if (recentUnderruns == 0) {
348481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    // no recent underruns: stay active
348581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    break;
348681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
348781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // there has recently been an underrun of some kind
348881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                if (track->sharedBuffer() == 0) {
348981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    // were any of the recent underruns "empty" (no frames available)?
349081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    if (recentEmpty == 0) {
349181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                        // no, then ignore the partial underruns as they are allowed indefinitely
349281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                        break;
349381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    }
349481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    // there has recently been an "empty" underrun: decrement the retry counter
349581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    if (--(track->mRetryCount) > 0) {
349681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                        break;
349781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    }
349881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    // indicate to client process that the track was disabled because of underrun;
349981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    // it will then automatically call start() when data is available
350096f60d8f04432a1ed503b3e24d5736d28c63c9a2Glenn Kasten                    android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
350181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    // remove from active list, but state remains ACTIVE [confusing but true]
350281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    isActive = false;
350381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    break;
350481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
350581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // fall through
350681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            case TrackBase::STOPPING_2:
350781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            case TrackBase::PAUSED:
350881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            case TrackBase::STOPPED:
350981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            case TrackBase::FLUSHED:   // flush() while active
351081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // Check for presentation complete if track is inactive
351181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // We have consumed all the buffers of this track.
351281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // This would be incomplete if we auto-paused on underrun
351381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                {
351481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    size_t audioHALFrames =
351581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                            (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
351681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    size_t framesWritten = mBytesWritten / mFrameSize;
351781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
351881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                        // track stays in active list until presentation is complete
351981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                        break;
352081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    }
352181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
352281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                if (track->isStopping_2()) {
352381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    track->mState = TrackBase::STOPPED;
352481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
352581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                if (track->isStopped()) {
352681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    // Can't reset directly, as fast mixer is still polling this track
352781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    //   track->reset();
352881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    // So instead mark this track as needing to be reset after push with ack
352981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    resetMask |= 1 << i;
353081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
353181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                isActive = false;
353281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                break;
353381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            case TrackBase::IDLE:
353481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            default:
3535adad3d7d935da176ff24941b4ae9edf7340e9b96Glenn Kasten                LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
353681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
353781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
353881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if (isActive) {
353981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // was it previously inactive?
354081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                if (!(state->mTrackMask & (1 << j))) {
354181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    ExtendedAudioBufferProvider *eabp = track;
354281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    VolumeProvider *vp = track;
354381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    fastTrack->mBufferProvider = eabp;
354481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    fastTrack->mVolumeProvider = vp;
354581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    fastTrack->mChannelMask = track->mChannelMask;
3546e8a1ced4da17dc6c07803dc2af8060f62a8389c1Andy Hung                    fastTrack->mFormat = track->mFormat;
354781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    fastTrack->mGeneration++;
354881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    state->mTrackMask |= 1 << j;
354981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    didModify = true;
355081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    // no acknowledgement required for newly active tracks
355181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
355281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // cache the combined master volume and stream type volume for fast mixer; this
355381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // lacks any synchronization or barrier so VolumeProvider may read a stale value
3554e4756fe3a387615acb63c6a05788c8db9b5786cbGlenn Kasten                track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
355581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                ++fastTracks;
355681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            } else {
355781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // was it previously active?
355881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                if (state->mTrackMask & (1 << j)) {
355981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    fastTrack->mBufferProvider = NULL;
356081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    fastTrack->mGeneration++;
356181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    state->mTrackMask &= ~(1 << j);
356281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    didModify = true;
356381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    // If any fast tracks were removed, we must wait for acknowledgement
356481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    // because we're about to decrement the last sp<> on those tracks.
356581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
356681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                } else {
3567adad3d7d935da176ff24941b4ae9edf7340e9b96Glenn Kasten                    LOG_ALWAYS_FATAL("fast track %d should have been active", j);
356881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
356981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                tracksToRemove->add(track);
357081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // Avoids a misleading display in dumpsys
357181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
357281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
357381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            continue;
357481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
357581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
357681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        {   // local variable scope to avoid goto warning
357781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
357881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        audio_track_cblk_t* cblk = track->cblk();
357981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
358081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // The first time a track is added we wait
358181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // for all its buffers to be filled before processing it
358281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        int name = track->name();
358381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // make sure that we have enough frames to mix one full buffer.
358481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // enforce this condition only once to enable draining the buffer in case the client
358581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // app does not call stop() and relies on underrun to stop:
358681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
358781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // during last round
35889f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        size_t desiredFrames;
35899fdcb0a9497ca290bcf364b10868587b6bde3a34Glenn Kasten        uint32_t sr = track->sampleRate();
35909fdcb0a9497ca290bcf364b10868587b6bde3a34Glenn Kasten        if (sr == mSampleRate) {
35919f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            desiredFrames = mNormalFrameCount;
35929f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        } else {
3593c25b84abdd7ff229d0af663fbf3a37bd9512939dAndy Hung            desiredFrames = sourceFramesNeeded(sr, mNormalFrameCount, mSampleRate);
35949f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            // add frames already consumed but not yet released by the resampler
35952fc14730e4697a6f456b4631549c9981f6b0b115Glenn Kasten            // because mAudioTrackServerProxy->framesReady() will include these frames
35969f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
359774935e44734c1ec235c2b6677db3e0dbefa5ddb8Glenn Kasten#if 0
35989f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            // the minimum track buffer size is normally twice the number of frames necessary
35999f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            // to fill one buffer and the resampler should not leave more than one buffer worth
36009f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            // of unreleased frames after each pass, but just in case...
36019f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
360274935e44734c1ec235c2b6677db3e0dbefa5ddb8Glenn Kasten#endif
36039f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
360481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        uint32_t minFrames = 1;
360581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
360681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
36079f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            minFrames = desiredFrames;
36089f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
360913e4c960ea3db03a43e084fbd85d52aa77f7b871Eric Laurent
361013e4c960ea3db03a43e084fbd85d52aa77f7b871Eric Laurent        size_t framesReady = track->framesReady();
3611e77540228e1f60b1129a1615d2e43e0bf8015d3cGlenn Kasten        if (ATRACE_ENABLED()) {
3612e77540228e1f60b1129a1615d2e43e0bf8015d3cGlenn Kasten            // I wish we had formatted trace names
3613e77540228e1f60b1129a1615d2e43e0bf8015d3cGlenn Kasten            char traceName[16];
3614e77540228e1f60b1129a1615d2e43e0bf8015d3cGlenn Kasten            strcpy(traceName, "nRdy");
3615e77540228e1f60b1129a1615d2e43e0bf8015d3cGlenn Kasten            int name = track->name();
3616e77540228e1f60b1129a1615d2e43e0bf8015d3cGlenn Kasten            if (AudioMixer::TRACK0 <= name &&
3617e77540228e1f60b1129a1615d2e43e0bf8015d3cGlenn Kasten                    name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
3618e77540228e1f60b1129a1615d2e43e0bf8015d3cGlenn Kasten                name -= AudioMixer::TRACK0;
3619e77540228e1f60b1129a1615d2e43e0bf8015d3cGlenn Kasten                traceName[4] = (name / 10) + '0';
3620e77540228e1f60b1129a1615d2e43e0bf8015d3cGlenn Kasten                traceName[5] = (name % 10) + '0';
3621e77540228e1f60b1129a1615d2e43e0bf8015d3cGlenn Kasten            } else {
3622e77540228e1f60b1129a1615d2e43e0bf8015d3cGlenn Kasten                traceName[4] = '?';
3623e77540228e1f60b1129a1615d2e43e0bf8015d3cGlenn Kasten                traceName[5] = '?';
3624e77540228e1f60b1129a1615d2e43e0bf8015d3cGlenn Kasten            }
3625e77540228e1f60b1129a1615d2e43e0bf8015d3cGlenn Kasten            traceName[6] = '\0';
3626e77540228e1f60b1129a1615d2e43e0bf8015d3cGlenn Kasten            ATRACE_INT(traceName, framesReady);
3627e77540228e1f60b1129a1615d2e43e0bf8015d3cGlenn Kasten        }
36289f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        if ((framesReady >= minFrames) && track->isReady() &&
362981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                !track->isPaused() && !track->isTerminated())
363081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        {
3631f20e1d8df84c5fbeeace0052d100982ae39bb7a4Glenn Kasten            ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
363281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
363381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mixedTracks++;
363481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
363569aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung            // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
363669aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung            // there is an effect chain connected to the track
363781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            chain.clear();
363869aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung            if (track->mainBuffer() != mSinkBuffer &&
363969aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung                    track->mainBuffer() != mMixerBuffer) {
364098ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung                if (mEffectBufferEnabled) {
364198ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung                    mEffectBufferValid = true; // Later can set directly.
364298ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung                }
364381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                chain = getEffectChain_l(track->sessionId());
364481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // Delegate volume control to effect in track effect chain if needed
364581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                if (chain != 0) {
364681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    tracksWithEffect++;
364781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                } else {
364881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
364981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                            "session %d",
365081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                            name, track->sessionId());
365181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
365281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
365381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
365481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
365581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            int param = AudioMixer::VOLUME;
365681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if (track->mFillingUpStatus == Track::FS_FILLED) {
365781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // no ramp for the first volume setting
365881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                track->mFillingUpStatus = Track::FS_ACTIVE;
365981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                if (track->mState == TrackBase::RESUMING) {
366081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    track->mState = TrackBase::ACTIVE;
366181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    param = AudioMixer::RAMP_VOLUME;
366281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
366381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
3664f20e1d8df84c5fbeeace0052d100982ae39bb7a4Glenn Kasten            // FIXME should not make a decision based on mServer
3665f20e1d8df84c5fbeeace0052d100982ae39bb7a4Glenn Kasten            } else if (cblk->mServer != 0) {
366681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // If the track is stopped before the first frame was mixed,
366781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // do not apply ramp
366881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                param = AudioMixer::RAMP_VOLUME;
366981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
367081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
367181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // compute volume for this track
36726be494077f8d7970f3a88129c5d139c5a0c88f6dAndy Hung            uint32_t vl, vr;       // in U8.24 integer format
36736be494077f8d7970f3a88129c5d139c5a0c88f6dAndy Hung            float vlf, vrf, vaf;   // in [0.0, 1.0] float format
3674e4756fe3a387615acb63c6a05788c8db9b5786cbGlenn Kasten            if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
36756be494077f8d7970f3a88129c5d139c5a0c88f6dAndy Hung                vl = vr = 0;
36766be494077f8d7970f3a88129c5d139c5a0c88f6dAndy Hung                vlf = vrf = vaf = 0.;
367781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                if (track->isPausing()) {
367881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    track->setPaused();
367981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
368081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            } else {
368181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
368281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // read original volumes with volume control
368381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                float typeVolume = mStreamTypes[track->streamType()].volume;
368481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                float v = masterVolume * typeVolume;
36859f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
3686c56f3426099a3cf2d07ccff8886050c7fbce140fGlenn Kasten                gain_minifloat_packed_t vlr = proxy->getVolumeLR();
36876be494077f8d7970f3a88129c5d139c5a0c88f6dAndy Hung                vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
36886be494077f8d7970f3a88129c5d139c5a0c88f6dAndy Hung                vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
368981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // track volumes come from shared memory, so can't be trusted and must be clamped
3690c56f3426099a3cf2d07ccff8886050c7fbce140fGlenn Kasten                if (vlf > GAIN_FLOAT_UNITY) {
3691c56f3426099a3cf2d07ccff8886050c7fbce140fGlenn Kasten                    ALOGV("Track left volume out of range: %.3g", vlf);
3692c56f3426099a3cf2d07ccff8886050c7fbce140fGlenn Kasten                    vlf = GAIN_FLOAT_UNITY;
369381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
3694c56f3426099a3cf2d07ccff8886050c7fbce140fGlenn Kasten                if (vrf > GAIN_FLOAT_UNITY) {
3695c56f3426099a3cf2d07ccff8886050c7fbce140fGlenn Kasten                    ALOGV("Track right volume out of range: %.3g", vrf);
3696c56f3426099a3cf2d07ccff8886050c7fbce140fGlenn Kasten                    vrf = GAIN_FLOAT_UNITY;
369781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
369881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // now apply the master volume and stream type volume
36996be494077f8d7970f3a88129c5d139c5a0c88f6dAndy Hung                vlf *= v;
37006be494077f8d7970f3a88129c5d139c5a0c88f6dAndy Hung                vrf *= v;
370181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // assuming master volume and stream type volume each go up to 1.0,
37026be494077f8d7970f3a88129c5d139c5a0c88f6dAndy Hung                // then derive vl and vr as U8.24 versions for the effect chain
37036be494077f8d7970f3a88129c5d139c5a0c88f6dAndy Hung                const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
37046be494077f8d7970f3a88129c5d139c5a0c88f6dAndy Hung                vl = (uint32_t) (scaleto8_24 * vlf);
37056be494077f8d7970f3a88129c5d139c5a0c88f6dAndy Hung                vr = (uint32_t) (scaleto8_24 * vrf);
37066be494077f8d7970f3a88129c5d139c5a0c88f6dAndy Hung                // vl and vr are now in U8.24 format
3707e3aa659e9cee7df5c12a80d285cc29ab3b2cbb39Glenn Kasten                uint16_t sendLevel = proxy->getSendLevel_U4_12();
370881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // send level comes from shared memory and so may be corrupt
370981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                if (sendLevel > MAX_GAIN_INT) {
371081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    ALOGV("Track send level out of range: %04X", sendLevel);
371181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    sendLevel = MAX_GAIN_INT;
371281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
37136be494077f8d7970f3a88129c5d139c5a0c88f6dAndy Hung                // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
37146be494077f8d7970f3a88129c5d139c5a0c88f6dAndy Hung                vaf = v * sendLevel * (1. / MAX_GAIN_INT);
371581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
3716bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
371781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // Delegate volume control to effect in track effect chain if needed
371881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
371981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // Do not ramp volume if volume is controlled by effect
372081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                param = AudioMixer::VOLUME;
3721b6be7f22a82ee3bad8bcc709d21e72fc4727da09Bryant Liu                // Update remaining floating point volume levels
3722b6be7f22a82ee3bad8bcc709d21e72fc4727da09Bryant Liu                vlf = (float)vl / (1 << 24);
3723b6be7f22a82ee3bad8bcc709d21e72fc4727da09Bryant Liu                vrf = (float)vr / (1 << 24);
372481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                track->mHasVolumeController = true;
372581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            } else {
372681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // force no volume ramp when volume controller was just disabled or removed
372781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // from effect chain to avoid volume spike
372881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                if (track->mHasVolumeController) {
372981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    param = AudioMixer::VOLUME;
373081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
373181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                track->mHasVolumeController = false;
373281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
373381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
373481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // XXX: these things DON'T need to be done each time
373581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mAudioMixer->setBufferProvider(name, track);
373681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mAudioMixer->enable(name);
373781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
37386be494077f8d7970f3a88129c5d139c5a0c88f6dAndy Hung            mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
37396be494077f8d7970f3a88129c5d139c5a0c88f6dAndy Hung            mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
37406be494077f8d7970f3a88129c5d139c5a0c88f6dAndy Hung            mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
374181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mAudioMixer->setParameter(
374281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                name,
374381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                AudioMixer::TRACK,
374481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                AudioMixer::FORMAT, (void *)track->format());
374581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mAudioMixer->setParameter(
374681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                name,
374781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                AudioMixer::TRACK,
3748377b2ec9a2885f9b6405b07ba900a9e3f4349c38Kévin PETIT                AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
37499a59276fb465e492138e0576523b54079671e8f4Andy Hung            mAudioMixer->setParameter(
37509a59276fb465e492138e0576523b54079671e8f4Andy Hung                name,
37519a59276fb465e492138e0576523b54079671e8f4Andy Hung                AudioMixer::TRACK,
37529a59276fb465e492138e0576523b54079671e8f4Andy Hung                AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
3753e3aa659e9cee7df5c12a80d285cc29ab3b2cbb39Glenn Kasten            // limit track sample rate to 2 x output sample rate, which changes at re-configuration
3754cd04484f4837b8ca0041d118286ab6a98e84fc75Andy Hung            uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
37559f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
3756e3aa659e9cee7df5c12a80d285cc29ab3b2cbb39Glenn Kasten            if (reqSampleRate == 0) {
3757e3aa659e9cee7df5c12a80d285cc29ab3b2cbb39Glenn Kasten                reqSampleRate = mSampleRate;
3758e3aa659e9cee7df5c12a80d285cc29ab3b2cbb39Glenn Kasten            } else if (reqSampleRate > maxSampleRate) {
3759e3aa659e9cee7df5c12a80d285cc29ab3b2cbb39Glenn Kasten                reqSampleRate = maxSampleRate;
3760e3aa659e9cee7df5c12a80d285cc29ab3b2cbb39Glenn Kasten            }
376181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mAudioMixer->setParameter(
376281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                name,
376381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                AudioMixer::RESAMPLE,
376481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                AudioMixer::SAMPLE_RATE,
3765377b2ec9a2885f9b6405b07ba900a9e3f4349c38Kévin PETIT                (void *)(uintptr_t)reqSampleRate);
376669aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung            /*
376769aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung             * Select the appropriate output buffer for the track.
376869aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung             *
376998ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung             * Tracks with effects go into their own effects chain buffer
377098ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung             * and from there into either mEffectBuffer or mSinkBuffer.
377169aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung             *
377269aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung             * Other tracks can use mMixerBuffer for higher precision
377369aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung             * channel accumulation.  If this buffer is enabled
377469aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung             * (mMixerBufferEnabled true), then selected tracks will accumulate
377569aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung             * into it.
377669aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung             *
377769aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung             */
377869aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung            if (mMixerBufferEnabled
377969aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung                    && (track->mainBuffer() == mSinkBuffer
378069aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung                            || track->mainBuffer() == mMixerBuffer)) {
378169aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung                mAudioMixer->setParameter(
378269aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung                        name,
378369aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung                        AudioMixer::TRACK,
3784788207057ed4b8df4719ed8089f376ef52de9ca1Andy Hung                        AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
378569aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung                mAudioMixer->setParameter(
378669aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung                        name,
378769aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung                        AudioMixer::TRACK,
378869aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung                        AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
378969aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung                // TODO: override track->mainBuffer()?
379069aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung                mMixerBufferValid = true;
379169aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung            } else {
379269aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung                mAudioMixer->setParameter(
379369aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung                        name,
379469aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung                        AudioMixer::TRACK,
3795788207057ed4b8df4719ed8089f376ef52de9ca1Andy Hung                        AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
379669aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung                mAudioMixer->setParameter(
379769aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung                        name,
379869aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung                        AudioMixer::TRACK,
379969aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung                        AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
380069aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung            }
380181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mAudioMixer->setParameter(
380281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                name,
380381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                AudioMixer::TRACK,
380481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
380581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
380681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // reset retry count
380781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            track->mRetryCount = kMaxTrackRetries;
380881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
380981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // If one track is ready, set the mixer ready if:
381081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            //  - the mixer was not ready during previous round OR
381181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            //  - no other track is not ready
381281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
381381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    mixerStatus != MIXER_TRACKS_ENABLED) {
381481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                mixerStatus = MIXER_TRACKS_READY;
381581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
381681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        } else {
38179f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
381882aaf94a5b18939e4d790bbc752031f3070704a3Glenn Kasten                track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
38199f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            }
382081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // clear effect chain input buffer if an active track underruns to avoid sending
382181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // previous audio buffer again to effects
382281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            chain = getEffectChain_l(track->sessionId());
382381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if (chain != 0) {
382481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                chain->clearInputBuffer();
382581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
382681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
3827f20e1d8df84c5fbeeace0052d100982ae39bb7a4Glenn Kasten            ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
382881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if ((track->sharedBuffer() != 0) || track->isTerminated() ||
382981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    track->isStopped() || track->isPaused()) {
383081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // We have consumed all the buffers of this track.
383181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // Remove it from the list of active tracks.
383281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // TODO: use actual buffer filling status instead of latency when available from
383381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // audio HAL
383481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
383581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                size_t framesWritten = mBytesWritten / mFrameSize;
383681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
383781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    if (track->isStopped()) {
383881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                        track->reset();
383981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    }
384081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    tracksToRemove->add(track);
384181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
384281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            } else {
384381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // No buffers for this track. Give it a few chances to
384481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // fill a buffer, then remove it from active list.
384581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                if (--(track->mRetryCount) <= 0) {
3846c9b2e20f7c9a71e07ef398152709c76079decbcdGlenn Kasten                    ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
384781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    tracksToRemove->add(track);
384881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    // indicate to client process that the track was disabled because of underrun;
384981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    // it will then automatically call start() when data is available
385096f60d8f04432a1ed503b3e24d5736d28c63c9a2Glenn Kasten                    android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
385181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // If one track is not ready, mark the mixer also not ready if:
385281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                //  - the mixer was ready during previous round OR
385381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                //  - no other track is ready
385481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
385581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                                mixerStatus != MIXER_TRACKS_READY) {
385681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    mixerStatus = MIXER_TRACKS_ENABLED;
385781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
385881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
385981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mAudioMixer->disable(name);
386081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
386181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
386281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }   // local variable scope to avoid goto warning
386381784c37c61b09289654b979567a42bf73cd2b12Eric Laurenttrack_is_ready: ;
386481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
386581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
386681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
386781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // Push the new FastMixer state if necessary
386881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    bool pauseAudioWatchdog = false;
386981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (didModify) {
387081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        state->mFastTracksGen++;
387181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
387281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (kUseFastMixer == FastMixer_Dynamic &&
387381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
387481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            state->mCommand = FastMixerState::COLD_IDLE;
387581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            state->mColdFutexAddr = &mFastMixerFutex;
387681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            state->mColdGen++;
387781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mFastMixerFutex = 0;
387881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if (kUseFastMixer == FastMixer_Dynamic) {
387981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                mNormalSink = mOutputSink;
388081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
388181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // If we go into cold idle, need to wait for acknowledgement
388281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // so that fast mixer stops doing I/O.
388381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
388481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            pauseAudioWatchdog = true;
388581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
388681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
388781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (sq != NULL) {
388881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sq->end(didModify);
388981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sq->push(block);
389081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
389181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#ifdef AUDIO_WATCHDOG
389281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (pauseAudioWatchdog && mAudioWatchdog != 0) {
389381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mAudioWatchdog->pause();
389481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
389581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#endif
389681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
389781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // Now perform the deferred reset on fast tracks that have stopped
389881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    while (resetMask != 0) {
389981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        size_t i = __builtin_ctz(resetMask);
390081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        ALOG_ASSERT(i < count);
390181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        resetMask &= ~(1 << i);
390281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sp<Track> t = mActiveTracks[i].promote();
390381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (t == 0) {
390481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            continue;
390581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
390681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        Track* track = t.get();
390781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        ALOG_ASSERT(track->isFastTrack() && track->isStopped());
390881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        track->reset();
390981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
391081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
391181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // remove all the tracks that need to be...
3912bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    removeTracks_l(*tracksToRemove);
391381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
391497d547da43c9c41711d1ed1e3f4fa87c2ee3cb9aEric Laurent    if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
391597d547da43c9c41711d1ed1e3f4fa87c2ee3cb9aEric Laurent        mEffectBufferValid = true;
3916ac302143551a8b964f026385a524dda9ff8ea5baMarco Nelissen    }
3917ac302143551a8b964f026385a524dda9ff8ea5baMarco Nelissen
3918ac302143551a8b964f026385a524dda9ff8ea5baMarco Nelissen    if (mEffectBufferValid) {
391957088b5c8e76855b99b3e6b3e410de5b6382670eMarco Nelissen        // as long as there are effects we should clear the effects buffer, to avoid
392057088b5c8e76855b99b3e6b3e410de5b6382670eMarco Nelissen        // passing a non-clean buffer to the effect chain
392157088b5c8e76855b99b3e6b3e410de5b6382670eMarco Nelissen        memset(mEffectBuffer, 0, mEffectBufferSize);
392297d547da43c9c41711d1ed1e3f4fa87c2ee3cb9aEric Laurent    }
392369aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung    // sink or mix buffer must be cleared if all tracks are connected to an
392469aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung    // effect chain as in this case the mixer will not write to the sink or mix buffer
392569aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung    // and track effects will accumulate into it
3926bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3927bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            (mixedTracks == 0 && fastTracks > 0))) {
392881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // FIXME as a performance optimization, should remember previous zero status
392969aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung        if (mMixerBufferValid) {
393069aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung            memset(mMixerBuffer, 0, mMixerBufferSize);
393169aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung            // TODO: In testing, mSinkBuffer below need not be cleared because
393269aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung            // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
393369aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung            // after mixing.
393469aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung            //
393569aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung            // To enforce this guarantee:
393669aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung            // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
393769aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung            // (mixedTracks == 0 && fastTracks > 0))
393869aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung            // must imply MIXER_TRACKS_READY.
393969aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung            // Later, we may clear buffers regardless, and skip much of this logic.
394069aed5f0f4a3be3996d1e78a0473e1a72c1547daAndy Hung        }
394198ef978df4e928f486d244c4d7f7ad9f13111e98Andy Hung        // FIXME as a performance optimization, should remember previous zero status
39425567aaf4818007cd8e77329683a91c0f5d7a8837Andy Hung        memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
394381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
394481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
394581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // if any fast tracks, then status is ready
394681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mMixerStatusIgnoringFastTracks = mixerStatus;
394781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (fastTracks > 0) {
394881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mixerStatus = MIXER_TRACKS_READY;
394981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
395081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return mixerStatus;
395181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
395281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
395381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// getTrackName_l() must be called with ThreadBase::mLock held
3954e8a1ced4da17dc6c07803dc2af8060f62a8389c1Andy Hungint AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
3955e8a1ced4da17dc6c07803dc2af8060f62a8389c1Andy Hung        audio_format_t format, int sessionId)
395681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
3957e8a1ced4da17dc6c07803dc2af8060f62a8389c1Andy Hung    return mAudioMixer->getTrackName(channelMask, format, sessionId);
395881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
395981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
396081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// deleteTrackName_l() must be called with ThreadBase::mLock held
396181784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::MixerThread::deleteTrackName_l(int name)
396281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
396381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    ALOGV("remove track (%d) and delete from mixer", name);
396481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mAudioMixer->deleteTrackName(name);
396581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
396681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
39671035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent// checkForNewParameter_l() must be called with ThreadBase::mLock held
39681035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurentbool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
39691035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                                                       status_t& status)
397081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
397181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    bool reconfig = false;
397281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
39731035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    status = NO_ERROR;
397481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
39751035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    // if !&IDLE, holds the FastMixer state to restore after new parameters processed
39761035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
39774d23ca370dd0ce584f49a80ef9dfcdbb75ba2c8eGlenn Kasten    if (mFastMixer != 0) {
39781035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        FastMixerStateQueue *sq = mFastMixer->sq();
39791035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        FastMixerState *state = sq->begin();
39801035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        if (!(state->mCommand & FastMixerState::IDLE)) {
39811035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            previousCommand = state->mCommand;
39821035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            state->mCommand = FastMixerState::HOT_IDLE;
39831035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            sq->end();
39841035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
39851035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        } else {
39861035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            sq->end(false /*didModify*/);
398781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
39881035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    }
398981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
39901035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    AudioParameter param = AudioParameter(keyValuePair);
39911035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    int value;
39921035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
39931035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        reconfig = true;
39941035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    }
39951035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
39969a59276fb465e492138e0576523b54079671e8f4Andy Hung        if (!isValidPcmSinkFormat((audio_format_t) value)) {
39971035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            status = BAD_VALUE;
39981035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        } else {
39991035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            // no need to save value, since it's constant
400081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            reconfig = true;
400181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
40021035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    }
40031035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
40049a59276fb465e492138e0576523b54079671e8f4Andy Hung        if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
40051035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            status = BAD_VALUE;
40061035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        } else {
40071035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            // no need to save value, since it's constant
40081035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            reconfig = true;
400981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
40101035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    }
40111035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
40121035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        // do not accept frame count changes if tracks are open as the track buffer
40131035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        // size depends on frame count and correct behavior would not be guaranteed
40141035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        // if frame count is changed after track creation
40151035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        if (!mTracks.isEmpty()) {
40161035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            status = INVALID_OPERATION;
40171035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        } else {
40181035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            reconfig = true;
401981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
40201035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    }
40211035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
402281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#ifdef ADD_BATTERY_DATA
40231035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        // when changing the audio output device, call addBatteryData to notify
40241035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        // the change
40251035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        if (mOutDevice != value) {
40261035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            uint32_t params = 0;
40271035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            // check whether speaker is on
40281035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            if (value & AUDIO_DEVICE_OUT_SPEAKER) {
40291035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                params |= IMediaPlayerService::kBatteryDataSpeakerOn;
40301035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            }
403181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
40321035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            audio_devices_t deviceWithoutSpeaker
40331035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
40341035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            // check if any other device (except speaker) is on
40351035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            if (value & deviceWithoutSpeaker ) {
40361035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
40371035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            }
403881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
40391035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            if (params != 0) {
40401035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                addBatteryData(params);
404181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
40421035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        }
404381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#endif
404481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
40451035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        // forward device change to effects that have requested to be
40461035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        // aware of attached audio device.
40471035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        if (value != AUDIO_DEVICE_NONE) {
40481035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            mOutDevice = value;
40491035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            for (size_t i = 0; i < mEffectChains.size(); i++) {
40501035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                mEffectChains[i]->setDevice_l(mOutDevice);
405181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
405281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
40531035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    }
405481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
40551035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    if (status == NO_ERROR) {
40561035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
40571035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                                                keyValuePair.string());
40581035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        if (!mStandby && status == INVALID_OPERATION) {
4059062e67a26e0553dd142be622821f493df541f0c6Phil Burk            mOutput->standby();
40601035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            mStandby = true;
40611035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            mBytesWritten = 0;
406281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
40631035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                                                   keyValuePair.string());
40641035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        }
40651035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        if (status == NO_ERROR && reconfig) {
40661035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            readOutputParameters_l();
40671035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            delete mAudioMixer;
40681035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
40691035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            for (size_t i = 0; i < mTracks.size() ; i++) {
4070e8a1ced4da17dc6c07803dc2af8060f62a8389c1Andy Hung                int name = getTrackName_l(mTracks[i]->mChannelMask,
4071e8a1ced4da17dc6c07803dc2af8060f62a8389c1Andy Hung                        mTracks[i]->mFormat, mTracks[i]->mSessionId);
40721035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                if (name < 0) {
40731035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                    break;
407481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
40751035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                mTracks[i]->mName = name;
407681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
40771035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
407881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
407981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
408081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
408181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (!(previousCommand & FastMixerState::IDLE)) {
40824d23ca370dd0ce584f49a80ef9dfcdbb75ba2c8eGlenn Kasten        ALOG_ASSERT(mFastMixer != 0);
408381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        FastMixerStateQueue *sq = mFastMixer->sq();
408481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        FastMixerState *state = sq->begin();
408581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
408681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        state->mCommand = previousCommand;
408781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sq->end();
408881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
408981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
409081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
409181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return reconfig;
409281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
409381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
409481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
409581784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
409681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
409781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    const size_t SIZE = 256;
409881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    char buffer[SIZE];
409981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    String8 result;
410081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
410181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    PlaybackThread::dumpInternals(fd, args);
410281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
410387cebadd48710e42474756fc3513df678de045ceElliott Hughes    dprintf(fd, "  AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
410481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
410581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
41064182c4e2a07e2441fcd5c22eaff0ddfe7f826f61Glenn Kasten    const FastMixerDumpState copy(mFastMixerDumpState);
410781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    copy.dump(fd);
410881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
410981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#ifdef STATE_QUEUE_DUMP
411081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // Similar for state queue
411181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    StateQueueObserverDump observerCopy = mStateQueueObserverDump;
411281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    observerCopy.dump(fd);
411381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
411481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mutatorCopy.dump(fd);
411581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#endif
411681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
411746909e7eb074ce1b95b8a411eb71154f53f84f77Glenn Kasten#ifdef TEE_SINK
411881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // Write the tee output to a .wav file
411981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    dumpTee(fd, mTeeSource, mId);
412046909e7eb074ce1b95b8a411eb71154f53f84f77Glenn Kasten#endif
412181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
412281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#ifdef AUDIO_WATCHDOG
412381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (mAudioWatchdog != 0) {
412481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
412581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        AudioWatchdogDump wdCopy = mAudioWatchdogDump;
412681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        wdCopy.dump(fd);
412781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
412881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#endif
412981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
413081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
413181784c37c61b09289654b979567a42bf73cd2b12Eric Laurentuint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
413281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
413381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
413481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
413581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
413681784c37c61b09289654b979567a42bf73cd2b12Eric Laurentuint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
413781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
413881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
413981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
414081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
414181784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::MixerThread::cacheParameters_l()
414281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
414381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    PlaybackThread::cacheParameters_l();
414481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
414581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // FIXME: Relaxed timing because of a certain device that can't meet latency
414681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // Should be reduced to 2x after the vendor fixes the driver issue
414781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // increase threshold again due to low power audio mode. The way this warning
414881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // threshold is calculated and its usefulness should be reconsidered anyway.
414981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
415081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
415181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
415281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// ----------------------------------------------------------------------------
415381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
415481784c37c61b09289654b979567a42bf73cd2b12Eric LaurentAudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
415581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
415681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    :   PlaybackThread(audioFlinger, output, id, device, DIRECT)
415781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // mLeftVolFloat, mRightVolFloat
415881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
415981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
416081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
4161bfb1b832079bbb9426f72f3863199a54aefd02daEric LaurentAudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4162bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
4163bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        ThreadBase::type_t type)
4164bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    :   PlaybackThread(audioFlinger, output, id, device, type)
4165bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        // mLeftVolFloat, mRightVolFloat
4166bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent{
4167bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent}
4168bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
416981784c37c61b09289654b979567a42bf73cd2b12Eric LaurentAudioFlinger::DirectOutputThread::~DirectOutputThread()
417081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
417181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
417281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
4173bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurentvoid AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4174bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent{
4175bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    audio_track_cblk_t* cblk = track->cblk();
4176bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    float left, right;
4177bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
4178bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4179bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        left = right = 0;
4180bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    } else {
4181bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        float typeVolume = mStreamTypes[track->streamType()].volume;
4182bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        float v = mMasterVolume * typeVolume;
4183bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
4184c56f3426099a3cf2d07ccff8886050c7fbce140fGlenn Kasten        gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4185c56f3426099a3cf2d07ccff8886050c7fbce140fGlenn Kasten        left = float_from_gain(gain_minifloat_unpack_left(vlr));
4186c56f3426099a3cf2d07ccff8886050c7fbce140fGlenn Kasten        if (left > GAIN_FLOAT_UNITY) {
4187c56f3426099a3cf2d07ccff8886050c7fbce140fGlenn Kasten            left = GAIN_FLOAT_UNITY;
4188c56f3426099a3cf2d07ccff8886050c7fbce140fGlenn Kasten        }
4189c56f3426099a3cf2d07ccff8886050c7fbce140fGlenn Kasten        left *= v;
4190c56f3426099a3cf2d07ccff8886050c7fbce140fGlenn Kasten        right = float_from_gain(gain_minifloat_unpack_right(vlr));
4191c56f3426099a3cf2d07ccff8886050c7fbce140fGlenn Kasten        if (right > GAIN_FLOAT_UNITY) {
4192c56f3426099a3cf2d07ccff8886050c7fbce140fGlenn Kasten            right = GAIN_FLOAT_UNITY;
4193c56f3426099a3cf2d07ccff8886050c7fbce140fGlenn Kasten        }
4194c56f3426099a3cf2d07ccff8886050c7fbce140fGlenn Kasten        right *= v;
4195bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    }
4196bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
4197bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    if (lastTrack) {
4198bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        if (left != mLeftVolFloat || right != mRightVolFloat) {
4199bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            mLeftVolFloat = left;
4200bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            mRightVolFloat = right;
4201bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
4202bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            // Convert volumes from float to 8.24
4203bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            uint32_t vl = (uint32_t)(left * (1 << 24));
4204bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            uint32_t vr = (uint32_t)(right * (1 << 24));
4205bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
4206bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            // Delegate volume control to effect in track effect chain if needed
4207bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            // only one effect chain can be present on DirectOutputThread, so if
4208bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            // there is one, the track is connected to it
4209bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            if (!mEffectChains.isEmpty()) {
4210bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                mEffectChains[0]->setVolume_l(&vl, &vr);
4211bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                left = (float)vl / (1 << 24);
4212bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                right = (float)vr / (1 << 24);
4213bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            }
4214bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            if (mOutput->stream->set_volume) {
4215bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                mOutput->stream->set_volume(mOutput->stream, left, right);
4216bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            }
4217bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        }
4218bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    }
4219bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent}
4220bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
4221bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
422281784c37c61b09289654b979567a42bf73cd2b12Eric LaurentAudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
422381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Vector< sp<Track> > *tracksToRemove
422481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent)
422581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
4226d595b7c858c481a07745674ce2d8a6690e980e74Eric Laurent    size_t count = mActiveTracks.size();
422781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mixer_state mixerStatus = MIXER_IDLE;
4228d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    bool doHwPause = false;
4229d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    bool doHwResume = false;
4230d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    bool flushPending = false;
423181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
423281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // find out which tracks need to be processed
4233d595b7c858c481a07745674ce2d8a6690e980e74Eric Laurent    for (size_t i = 0; i < count; i++) {
4234d595b7c858c481a07745674ce2d8a6690e980e74Eric Laurent        sp<Track> t = mActiveTracks[i].promote();
423581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // The track died recently
423681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (t == 0) {
4237d595b7c858c481a07745674ce2d8a6690e980e74Eric Laurent            continue;
423881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
423981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
424081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        Track* const track = t.get();
424181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        audio_track_cblk_t* cblk = track->cblk();
4242fd4779740ec3e9e865d5514464df26d015354388Eric Laurent        // Only consider last track started for volume and mixer state control.
4243fd4779740ec3e9e865d5514464df26d015354388Eric Laurent        // In theory an older track could underrun and restart after the new one starts
4244fd4779740ec3e9e865d5514464df26d015354388Eric Laurent        // but as we only care about the transition phase between two tracks on a
4245fd4779740ec3e9e865d5514464df26d015354388Eric Laurent        // direct output, it is not a problem to ignore the underrun case.
4246fd4779740ec3e9e865d5514464df26d015354388Eric Laurent        sp<Track> l = mLatestActiveTrack.promote();
4247fd4779740ec3e9e865d5514464df26d015354388Eric Laurent        bool last = l.get() == track;
424881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
4249d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent        if (mHwSupportsPause && track->isPausing()) {
4250d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent            track->setPaused();
4251d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent            if (last && !mHwPaused) {
4252d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent                doHwPause = true;
4253d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent                mHwPaused = true;
4254d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent            }
4255d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent            tracksToRemove->add(track);
4256d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent        } else if (track->isFlushPending()) {
4257d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent            track->flushAck();
4258d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent            if (last) {
4259d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent                flushPending = true;
4260d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent            }
4261d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent        } else if (mHwSupportsPause && track->isResumePending()){
4262d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent            track->resumeAck();
4263d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent            if (last) {
4264d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent                if (mHwPaused) {
4265d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent                    doHwResume = true;
4266d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent                    mHwPaused = false;
4267d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent                }
4268d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent            }
4269d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent        }
4270d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent
427181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // The first time a track is added we wait
427299adee3c3d9cde6819741a38163954808fea270aPhil Burk        // for all its buffers to be filled before processing it.
427399adee3c3d9cde6819741a38163954808fea270aPhil Burk        // Allow draining the buffer in case the client
427499adee3c3d9cde6819741a38163954808fea270aPhil Burk        // app does not call stop() and relies on underrun to stop:
427599adee3c3d9cde6819741a38163954808fea270aPhil Burk        // hence the test on (track->mRetryCount > 1).
427699adee3c3d9cde6819741a38163954808fea270aPhil Burk        // If retryCount<=1 then track is about to underrun and be removed.
427781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        uint32_t minFrames;
427899adee3c3d9cde6819741a38163954808fea270aPhil Burk        if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
427999adee3c3d9cde6819741a38163954808fea270aPhil Burk            && (track->mRetryCount > 1)) {
428081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            minFrames = mNormalFrameCount;
428181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        } else {
428281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            minFrames = 1;
428381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
4284bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
4285ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent        if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4286ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent                !track->isStopping_2() && !track->isStopped())
428781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        {
4288f20e1d8df84c5fbeeace0052d100982ae39bb7a4Glenn Kasten            ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
428981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
429081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if (track->mFillingUpStatus == Track::FS_FILLED) {
429181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                track->mFillingUpStatus = Track::FS_ACTIVE;
42921abbdb4429479975718421c4fef3f79ce7c820e3Eric Laurent                // make sure processVolume_l() will apply new volume even if 0
42931abbdb4429479975718421c4fef3f79ce7c820e3Eric Laurent                mLeftVolFloat = mRightVolFloat = -1.0;
4294d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent                if (!mHwSupportsPause) {
4295d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent                    track->resumeAck();
429681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
429781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
429881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
429981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // compute volume for this track
4300bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            processVolume_l(track, last);
4301bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            if (last) {
4302d595b7c858c481a07745674ce2d8a6690e980e74Eric Laurent                // reset retry count
4303d595b7c858c481a07745674ce2d8a6690e980e74Eric Laurent                track->mRetryCount = kMaxTrackRetriesDirect;
4304d595b7c858c481a07745674ce2d8a6690e980e74Eric Laurent                mActiveTrack = t;
4305d595b7c858c481a07745674ce2d8a6690e980e74Eric Laurent                mixerStatus = MIXER_TRACKS_READY;
43060f7b5f2b231caf87da9b20b74d086e5a9d6f4a9dEric Laurent                if (usesHwAvSync() && mHwPaused) {
43070f7b5f2b231caf87da9b20b74d086e5a9d6f4a9dEric Laurent                    doHwResume = true;
43080f7b5f2b231caf87da9b20b74d086e5a9d6f4a9dEric Laurent                    mHwPaused = false;
43090f7b5f2b231caf87da9b20b74d086e5a9d6f4a9dEric Laurent                }
4310d595b7c858c481a07745674ce2d8a6690e980e74Eric Laurent            }
431181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        } else {
4312d595b7c858c481a07745674ce2d8a6690e980e74Eric Laurent            // clear effect chain input buffer if the last active track started underruns
4313d595b7c858c481a07745674ce2d8a6690e980e74Eric Laurent            // to avoid sending previous audio buffer again to effects
4314fd4779740ec3e9e865d5514464df26d015354388Eric Laurent            if (!mEffectChains.isEmpty() && last) {
431581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                mEffectChains[0]->clearInputBuffer();
431681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
4317ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent            if (track->isStopping_1()) {
4318ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent                track->mState = TrackBase::STOPPING_2;
4319b369cafd67beb63dd0278dba543f519956208a7fEric Laurent                if (last && mHwPaused) {
4320b369cafd67beb63dd0278dba543f519956208a7fEric Laurent                     doHwResume = true;
4321b369cafd67beb63dd0278dba543f519956208a7fEric Laurent                     mHwPaused = false;
4322b369cafd67beb63dd0278dba543f519956208a7fEric Laurent                 }
4323ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent            }
4324ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent            if ((track->sharedBuffer() != 0) || track->isStopped() ||
4325ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent                    track->isStopping_2() || track->isPaused()) {
432681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // We have consumed all the buffers of this track.
432781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // Remove it from the list of active tracks.
4328ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent                size_t audioHALFrames;
4329ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent                if (audio_is_linear_pcm(mFormat)) {
4330ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent                    audioHALFrames = (latency_l() * mSampleRate) / 1000;
4331ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent                } else {
4332ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent                    audioHALFrames = 0;
4333ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent                }
4334ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent
433581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                size_t framesWritten = mBytesWritten / mFrameSize;
4336fd4779740ec3e9e865d5514464df26d015354388Eric Laurent                if (mStandby || !last ||
4337fd4779740ec3e9e865d5514464df26d015354388Eric Laurent                        track->presentationComplete(framesWritten, audioHALFrames)) {
4338ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent                    if (track->isStopping_2()) {
4339ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent                        track->mState = TrackBase::STOPPED;
4340ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent                    }
434181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    if (track->isStopped()) {
434281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                        track->reset();
434381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    }
4344d595b7c858c481a07745674ce2d8a6690e980e74Eric Laurent                    tracksToRemove->add(track);
434581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
434681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            } else {
434781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // No buffers for this track. Give it a few chances to
434881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // fill a buffer, then remove it from active list.
4349d595b7c858c481a07745674ce2d8a6690e980e74Eric Laurent                // Only consider last track started for mixer state control
435081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                if (--(track->mRetryCount) <= 0) {
435181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
4352d595b7c858c481a07745674ce2d8a6690e980e74Eric Laurent                    tracksToRemove->add(track);
4353a23f17ac334ff20a11ee63dd177cb1080e44c483Eric Laurent                    // indicate to client process that the track was disabled because of underrun;
4354a23f17ac334ff20a11ee63dd177cb1080e44c483Eric Laurent                    // it will then automatically call start() when data is available
4355a23f17ac334ff20a11ee63dd177cb1080e44c483Eric Laurent                    android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
4356bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                } else if (last) {
435781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    mixerStatus = MIXER_TRACKS_ENABLED;
43580f7b5f2b231caf87da9b20b74d086e5a9d6f4a9dEric Laurent                    if (usesHwAvSync() && !mHwPaused && !mStandby) {
43590f7b5f2b231caf87da9b20b74d086e5a9d6f4a9dEric Laurent                        doHwPause = true;
43600f7b5f2b231caf87da9b20b74d086e5a9d6f4a9dEric Laurent                        mHwPaused = true;
43610f7b5f2b231caf87da9b20b74d086e5a9d6f4a9dEric Laurent                    }
436281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
436381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
436481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
436581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
436681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
4367d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    // if an active track did not command a flush, check for pending flush on stopped tracks
4368d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    if (!flushPending) {
4369d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent        for (size_t i = 0; i < mTracks.size(); i++) {
4370d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent            if (mTracks[i]->isFlushPending()) {
4371d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent                mTracks[i]->flushAck();
4372d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent                flushPending = true;
4373d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent            }
4374d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent        }
4375d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    }
4376d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent
4377d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    // make sure the pause/flush/resume sequence is executed in the right order.
4378d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4379d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    // before flush and then resume HW. This can happen in case of pause/flush/resume
4380d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    // if resume is received before pause is executed.
4381d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    if (mHwSupportsPause && !mStandby &&
4382d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent            (doHwPause || (flushPending && !mHwPaused && (count != 0)))) {
4383d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent        mOutput->stream->pause(mOutput->stream);
4384d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    }
4385d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    if (flushPending) {
4386d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent        flushHw_l();
4387d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    }
4388d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    if (mHwSupportsPause && !mStandby && doHwResume) {
4389d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent        mOutput->stream->resume(mOutput->stream);
4390d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    }
439181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // remove all the tracks that need to be...
4392bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    removeTracks_l(*tracksToRemove);
439381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
439481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return mixerStatus;
439581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
439681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
439781784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::DirectOutputThread::threadLoop_mix()
439881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
439981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    size_t frameCount = mFrameCount;
44002098f2744cedf2dc3fa36f608aa965a34602e7c0Andy Hung    int8_t *curBuf = (int8_t *)mSinkBuffer;
440181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // output audio to hardware
440281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    while (frameCount) {
440334542acfa25c6413c87a94b6f7cc315a0c496277Glenn Kasten        AudioBufferProvider::Buffer buffer;
440481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        buffer.frameCount = frameCount;
4405062e67a26e0553dd142be622821f493df541f0c6Phil Burk        status_t status = mActiveTrack->getNextBuffer(&buffer);
4406062e67a26e0553dd142be622821f493df541f0c6Phil Burk        if (status != NO_ERROR || buffer.raw == NULL) {
440781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            memset(curBuf, 0, frameCount * mFrameSize);
440881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            break;
440981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
441081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
441181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        frameCount -= buffer.frameCount;
441281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        curBuf += buffer.frameCount * mFrameSize;
441381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mActiveTrack->releaseBuffer(&buffer);
441481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
44152098f2744cedf2dc3fa36f608aa965a34602e7c0Andy Hung    mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
441681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    sleepTime = 0;
441781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    standbyTime = systemTime() + standbyDelay;
441881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mActiveTrack.clear();
441981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
442081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
442181784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
442281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
4423d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    // do not write to HAL when paused
44240f7b5f2b231caf87da9b20b74d086e5a9d6f4a9dEric Laurent    if (mHwPaused || (usesHwAvSync() && mStandby)) {
4425d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent        sleepTime = idleSleepTime;
4426d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent        return;
4427d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    }
442881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (sleepTime == 0) {
442981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (mMixerStatus == MIXER_TRACKS_ENABLED) {
443081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            sleepTime = activeSleepTime;
443181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        } else {
443281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            sleepTime = idleSleepTime;
443381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
443481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
44352098f2744cedf2dc3fa36f608aa965a34602e7c0Andy Hung        memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
443681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sleepTime = 0;
443781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
443881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
443981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
4440d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurentvoid AudioFlinger::DirectOutputThread::threadLoop_exit()
4441d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent{
4442d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    {
4443d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent        Mutex::Autolock _l(mLock);
4444d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent        bool flushPending = false;
4445d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent        for (size_t i = 0; i < mTracks.size(); i++) {
4446d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent            if (mTracks[i]->isFlushPending()) {
4447d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent                mTracks[i]->flushAck();
4448d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent                flushPending = true;
4449d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent            }
4450d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent        }
4451d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent        if (flushPending) {
4452d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent            flushHw_l();
4453d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent        }
4454d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    }
4455d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    PlaybackThread::threadLoop_exit();
4456d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent}
4457d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent
4458d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent// must be called with thread mutex locked
4459d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurentbool AudioFlinger::DirectOutputThread::shouldStandby_l()
4460d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent{
4461d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    bool trackPaused = false;
4462b369cafd67beb63dd0278dba543f519956208a7fEric Laurent    bool trackStopped = false;
4463d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent
4464d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4465d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    // after a timeout and we will enter standby then.
4466d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    if (mTracks.size() > 0) {
4467d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent        trackPaused = mTracks[mTracks.size() - 1]->isPaused();
4468b369cafd67beb63dd0278dba543f519956208a7fEric Laurent        trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
4469b369cafd67beb63dd0278dba543f519956208a7fEric Laurent                           mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
4470d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    }
4471d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent
4472b369cafd67beb63dd0278dba543f519956208a7fEric Laurent    return !mStandby && !(trackPaused || (usesHwAvSync() && mHwPaused && !trackStopped));
4473d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent}
4474d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent
447581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// getTrackName_l() must be called with ThreadBase::mLock held
44760f11b51a57bc9062c4fe8af73747319cedabc5d6Glenn Kastenint AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
4477e8a1ced4da17dc6c07803dc2af8060f62a8389c1Andy Hung        audio_format_t format __unused, int sessionId __unused)
447881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
447981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return 0;
448081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
448181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
448281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// deleteTrackName_l() must be called with ThreadBase::mLock held
44830f11b51a57bc9062c4fe8af73747319cedabc5d6Glenn Kastenvoid AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
448481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
448581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
448681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
44871035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent// checkForNewParameter_l() must be called with ThreadBase::mLock held
44881035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurentbool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
44891035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                                                              status_t& status)
449081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
449181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    bool reconfig = false;
449281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
44931035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    status = NO_ERROR;
44941035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent
44951035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    AudioParameter param = AudioParameter(keyValuePair);
44961035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    int value;
44971035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
44981035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        // forward device change to effects that have requested to be
44991035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        // aware of attached audio device.
45001035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        if (value != AUDIO_DEVICE_NONE) {
45011035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            mOutDevice = value;
45021035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            for (size_t i = 0; i < mEffectChains.size(); i++) {
45031035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                mEffectChains[i]->setDevice_l(mOutDevice);
4504c125f38cd0ae35409a01b98a99e483550daa1313Glenn Kasten            }
4505c125f38cd0ae35409a01b98a99e483550daa1313Glenn Kasten        }
45061035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    }
45071035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
45081035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        // do not accept frame count changes if tracks are open as the track buffer
45091035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        // size depends on frame count and correct behavior would not be garantied
45101035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        // if frame count is changed after track creation
45111035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        if (!mTracks.isEmpty()) {
45121035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            status = INVALID_OPERATION;
45131035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        } else {
45141035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            reconfig = true;
451581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
45161035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    }
45171035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    if (status == NO_ERROR) {
45181035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
45191035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                                                keyValuePair.string());
45201035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        if (!mStandby && status == INVALID_OPERATION) {
4521062e67a26e0553dd142be622821f493df541f0c6Phil Burk            mOutput->standby();
45221035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            mStandby = true;
45231035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            mBytesWritten = 0;
452481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
45251035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                                                   keyValuePair.string());
45261035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        }
45271035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        if (status == NO_ERROR && reconfig) {
45281035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            readOutputParameters_l();
45291035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
453081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
453181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
45321035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent
453381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return reconfig;
453481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
453581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
453681784c37c61b09289654b979567a42bf73cd2b12Eric Laurentuint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
453781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
453881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    uint32_t time;
453981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (audio_is_linear_pcm(mFormat)) {
454081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        time = PlaybackThread::activeSleepTimeUs();
454181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    } else {
454281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        time = 10000;
454381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
454481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return time;
454581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
454681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
454781784c37c61b09289654b979567a42bf73cd2b12Eric Laurentuint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
454881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
454981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    uint32_t time;
455081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (audio_is_linear_pcm(mFormat)) {
455181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
455281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    } else {
455381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        time = 10000;
455481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
455581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return time;
455681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
455781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
455881784c37c61b09289654b979567a42bf73cd2b12Eric Laurentuint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
455981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
456081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    uint32_t time;
456181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (audio_is_linear_pcm(mFormat)) {
456281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
456381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    } else {
456481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        time = 10000;
456581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
456681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return time;
456781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
456881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
456981784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::DirectOutputThread::cacheParameters_l()
457081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
457181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    PlaybackThread::cacheParameters_l();
457281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
457381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // use shorter standby delay as on normal output to release
457481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // hardware resources as soon as possible
4575b369cafd67beb63dd0278dba543f519956208a7fEric Laurent    // no delay on outputs with HW A/V sync
4576b369cafd67beb63dd0278dba543f519956208a7fEric Laurent    if (usesHwAvSync()) {
4577b369cafd67beb63dd0278dba543f519956208a7fEric Laurent        standbyDelay = 0;
4578b369cafd67beb63dd0278dba543f519956208a7fEric Laurent    } else if (audio_is_linear_pcm(mFormat)) {
4579972a173d7d1de1a3b5a617aae3e2abb6e05ae02dEric Laurent        standbyDelay = microseconds(activeSleepTime*2);
4580972a173d7d1de1a3b5a617aae3e2abb6e05ae02dEric Laurent    } else {
4581972a173d7d1de1a3b5a617aae3e2abb6e05ae02dEric Laurent        standbyDelay = kOffloadStandbyDelayNs;
4582972a173d7d1de1a3b5a617aae3e2abb6e05ae02dEric Laurent    }
458381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
458481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
4585e659ef420dae0caae84ab78f9df8952acb9ad3a0Eric Laurentvoid AudioFlinger::DirectOutputThread::flushHw_l()
4586e659ef420dae0caae84ab78f9df8952acb9ad3a0Eric Laurent{
4587062e67a26e0553dd142be622821f493df541f0c6Phil Burk    mOutput->flush();
4588d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    mHwPaused = false;
4589e659ef420dae0caae84ab78f9df8952acb9ad3a0Eric Laurent}
4590e659ef420dae0caae84ab78f9df8952acb9ad3a0Eric Laurent
459181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// ----------------------------------------------------------------------------
459281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
4593bfb1b832079bbb9426f72f3863199a54aefd02daEric LaurentAudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
45944de95592980dba88a35b3dc8f3fd045588387a4fEric Laurent        const wp<AudioFlinger::PlaybackThread>& playbackThread)
4595bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    :   Thread(false /*canCallJava*/),
45964de95592980dba88a35b3dc8f3fd045588387a4fEric Laurent        mPlaybackThread(playbackThread),
45973b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent        mWriteAckSequence(0),
45983b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent        mDrainSequence(0)
4599bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent{
4600bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent}
4601bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
4602bfb1b832079bbb9426f72f3863199a54aefd02daEric LaurentAudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4603bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent{
4604bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent}
4605bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
4606bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurentvoid AudioFlinger::AsyncCallbackThread::onFirstRef()
4607bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent{
4608bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4609bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent}
4610bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
4611bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurentbool AudioFlinger::AsyncCallbackThread::threadLoop()
4612bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent{
4613bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    while (!exitPending()) {
46143b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent        uint32_t writeAckSequence;
46153b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent        uint32_t drainSequence;
4616bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
4617bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        {
4618bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            Mutex::Autolock _l(mLock);
461924a325d6f8c4bbf9330e6ce0c769d46e04266ffcHaynes Mathew George            while (!((mWriteAckSequence & 1) ||
462024a325d6f8c4bbf9330e6ce0c769d46e04266ffcHaynes Mathew George                     (mDrainSequence & 1) ||
462124a325d6f8c4bbf9330e6ce0c769d46e04266ffcHaynes Mathew George                     exitPending())) {
462224a325d6f8c4bbf9330e6ce0c769d46e04266ffcHaynes Mathew George                mWaitWorkCV.wait(mLock);
462324a325d6f8c4bbf9330e6ce0c769d46e04266ffcHaynes Mathew George            }
462424a325d6f8c4bbf9330e6ce0c769d46e04266ffcHaynes Mathew George
4625bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            if (exitPending()) {
4626bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                break;
4627bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            }
46283b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent            ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
46293b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent                  mWriteAckSequence, mDrainSequence);
46303b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent            writeAckSequence = mWriteAckSequence;
46313b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent            mWriteAckSequence &= ~1;
46323b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent            drainSequence = mDrainSequence;
46333b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent            mDrainSequence &= ~1;
4634bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        }
4635bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        {
46364de95592980dba88a35b3dc8f3fd045588387a4fEric Laurent            sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
46374de95592980dba88a35b3dc8f3fd045588387a4fEric Laurent            if (playbackThread != 0) {
46383b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent                if (writeAckSequence & 1) {
46394de95592980dba88a35b3dc8f3fd045588387a4fEric Laurent                    playbackThread->resetWriteBlocked(writeAckSequence >> 1);
4640bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                }
46413b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent                if (drainSequence & 1) {
46424de95592980dba88a35b3dc8f3fd045588387a4fEric Laurent                    playbackThread->resetDraining(drainSequence >> 1);
4643bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                }
4644bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            }
4645bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        }
4646bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    }
4647bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    return false;
4648bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent}
4649bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
4650bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurentvoid AudioFlinger::AsyncCallbackThread::exit()
4651bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent{
4652bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    ALOGV("AsyncCallbackThread::exit");
4653bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    Mutex::Autolock _l(mLock);
4654bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    requestExit();
4655bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    mWaitWorkCV.broadcast();
4656bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent}
4657bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
46583b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurentvoid AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
4659bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent{
4660bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    Mutex::Autolock _l(mLock);
46613b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent    // bit 0 is cleared
46623b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent    mWriteAckSequence = sequence << 1;
46633b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent}
46643b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent
46653b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurentvoid AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
46663b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent{
46673b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent    Mutex::Autolock _l(mLock);
46683b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent    // ignore unexpected callbacks
46693b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent    if (mWriteAckSequence & 2) {
46703b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent        mWriteAckSequence |= 1;
4671bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        mWaitWorkCV.signal();
4672bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    }
4673bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent}
4674bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
46753b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurentvoid AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
46763b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent{
46773b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent    Mutex::Autolock _l(mLock);
46783b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent    // bit 0 is cleared
46793b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent    mDrainSequence = sequence << 1;
46803b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent}
46813b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent
46823b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurentvoid AudioFlinger::AsyncCallbackThread::resetDraining()
4683bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent{
4684bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    Mutex::Autolock _l(mLock);
46853b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent    // ignore unexpected callbacks
46863b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent    if (mDrainSequence & 2) {
46873b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent        mDrainSequence |= 1;
4688bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        mWaitWorkCV.signal();
4689bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    }
4690bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent}
4691bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
4692bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
4693bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent// ----------------------------------------------------------------------------
4694bfb1b832079bbb9426f72f3863199a54aefd02daEric LaurentAudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
4695bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
4696bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    :   DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
4697d7e59228caad3867794d847f6bf163c6495e9506Eric Laurent        mPausedBytesRemaining(0)
4698bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent{
4699fd4779740ec3e9e865d5514464df26d015354388Eric Laurent    //FIXME: mStandby should be set to true by ThreadBase constructor
4700fd4779740ec3e9e865d5514464df26d015354388Eric Laurent    mStandby = true;
4701bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent}
4702bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
4703bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurentvoid AudioFlinger::OffloadThread::threadLoop_exit()
4704bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent{
4705bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    if (mFlushPending || mHwPaused) {
4706bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        // If a flush is pending or track was paused, just discard buffered data
4707bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        flushHw_l();
4708bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    } else {
4709bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        mMixerStatus = MIXER_DRAIN_ALL;
4710bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        threadLoop_drain();
4711bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    }
471256604aa3a56dc8e15532597a0a74b3c7b165e006Uday Gupta    if (mUseAsyncWrite) {
471356604aa3a56dc8e15532597a0a74b3c7b165e006Uday Gupta        ALOG_ASSERT(mCallbackThread != 0);
471456604aa3a56dc8e15532597a0a74b3c7b165e006Uday Gupta        mCallbackThread->exit();
471556604aa3a56dc8e15532597a0a74b3c7b165e006Uday Gupta    }
4716bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    PlaybackThread::threadLoop_exit();
4717bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent}
4718bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
4719bfb1b832079bbb9426f72f3863199a54aefd02daEric LaurentAudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
4720bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    Vector< sp<Track> > *tracksToRemove
4721bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent)
4722bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent{
4723bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    size_t count = mActiveTracks.size();
4724bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
4725bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    mixer_state mixerStatus = MIXER_IDLE;
4726972a173d7d1de1a3b5a617aae3e2abb6e05ae02dEric Laurent    bool doHwPause = false;
4727972a173d7d1de1a3b5a617aae3e2abb6e05ae02dEric Laurent    bool doHwResume = false;
4728972a173d7d1de1a3b5a617aae3e2abb6e05ae02dEric Laurent
4729ede6c3b8b1147bc425f7b923882f559a513fe23bEric Laurent    ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
4730ede6c3b8b1147bc425f7b923882f559a513fe23bEric Laurent
4731bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    // find out which tracks need to be processed
4732bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    for (size_t i = 0; i < count; i++) {
4733bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        sp<Track> t = mActiveTracks[i].promote();
4734bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        // The track died recently
4735bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        if (t == 0) {
4736bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            continue;
4737bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        }
4738bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        Track* const track = t.get();
4739bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        audio_track_cblk_t* cblk = track->cblk();
4740fd4779740ec3e9e865d5514464df26d015354388Eric Laurent        // Only consider last track started for volume and mixer state control.
4741fd4779740ec3e9e865d5514464df26d015354388Eric Laurent        // In theory an older track could underrun and restart after the new one starts
4742fd4779740ec3e9e865d5514464df26d015354388Eric Laurent        // but as we only care about the transition phase between two tracks on a
4743fd4779740ec3e9e865d5514464df26d015354388Eric Laurent        // direct output, it is not a problem to ignore the underrun case.
4744fd4779740ec3e9e865d5514464df26d015354388Eric Laurent        sp<Track> l = mLatestActiveTrack.promote();
4745fd4779740ec3e9e865d5514464df26d015354388Eric Laurent        bool last = l.get() == track;
4746fd4779740ec3e9e865d5514464df26d015354388Eric Laurent
47477844f679be8d94c5cdf017f53754cb68ee2f00daHaynes Mathew George        if (track->isInvalid()) {
47487844f679be8d94c5cdf017f53754cb68ee2f00daHaynes Mathew George            ALOGW("An invalidated track shouldn't be in active list");
47497844f679be8d94c5cdf017f53754cb68ee2f00daHaynes Mathew George            tracksToRemove->add(track);
47507844f679be8d94c5cdf017f53754cb68ee2f00daHaynes Mathew George            continue;
47517844f679be8d94c5cdf017f53754cb68ee2f00daHaynes Mathew George        }
47527844f679be8d94c5cdf017f53754cb68ee2f00daHaynes Mathew George
47537844f679be8d94c5cdf017f53754cb68ee2f00daHaynes Mathew George        if (track->mState == TrackBase::IDLE) {
47547844f679be8d94c5cdf017f53754cb68ee2f00daHaynes Mathew George            ALOGW("An idle track shouldn't be in active list");
47557844f679be8d94c5cdf017f53754cb68ee2f00daHaynes Mathew George            continue;
47567844f679be8d94c5cdf017f53754cb68ee2f00daHaynes Mathew George        }
47577844f679be8d94c5cdf017f53754cb68ee2f00daHaynes Mathew George
4758bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        if (track->isPausing()) {
4759bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            track->setPaused();
4760bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            if (last) {
4761bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                if (!mHwPaused) {
4762972a173d7d1de1a3b5a617aae3e2abb6e05ae02dEric Laurent                    doHwPause = true;
4763bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                    mHwPaused = true;
4764bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                }
4765bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                // If we were part way through writing the mixbuffer to
4766bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                // the HAL we must save this until we resume
4767bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                // BUG - this will be wrong if a different track is made active,
4768bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                // in that case we want to discard the pending data in the
4769bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                // mixbuffer and tell the client to present it again when the
4770bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                // track is resumed
4771bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                mPausedWriteLength = mCurrentWriteLength;
4772bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                mPausedBytesRemaining = mBytesRemaining;
4773bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                mBytesRemaining = 0;    // stop writing
4774bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            }
4775bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            tracksToRemove->add(track);
47767844f679be8d94c5cdf017f53754cb68ee2f00daHaynes Mathew George        } else if (track->isFlushPending()) {
47777844f679be8d94c5cdf017f53754cb68ee2f00daHaynes Mathew George            track->flushAck();
47787844f679be8d94c5cdf017f53754cb68ee2f00daHaynes Mathew George            if (last) {
47797844f679be8d94c5cdf017f53754cb68ee2f00daHaynes Mathew George                mFlushPending = true;
47807844f679be8d94c5cdf017f53754cb68ee2f00daHaynes Mathew George            }
47812d3ca68363f723fbe269d3ce52dab4985dfc7154Haynes Mathew George        } else if (track->isResumePending()){
47822d3ca68363f723fbe269d3ce52dab4985dfc7154Haynes Mathew George            track->resumeAck();
47832d3ca68363f723fbe269d3ce52dab4985dfc7154Haynes Mathew George            if (last) {
47842d3ca68363f723fbe269d3ce52dab4985dfc7154Haynes Mathew George                if (mPausedBytesRemaining) {
47852d3ca68363f723fbe269d3ce52dab4985dfc7154Haynes Mathew George                    // Need to continue write that was interrupted
47862d3ca68363f723fbe269d3ce52dab4985dfc7154Haynes Mathew George                    mCurrentWriteLength = mPausedWriteLength;
47872d3ca68363f723fbe269d3ce52dab4985dfc7154Haynes Mathew George                    mBytesRemaining = mPausedBytesRemaining;
47882d3ca68363f723fbe269d3ce52dab4985dfc7154Haynes Mathew George                    mPausedBytesRemaining = 0;
47892d3ca68363f723fbe269d3ce52dab4985dfc7154Haynes Mathew George                }
47902d3ca68363f723fbe269d3ce52dab4985dfc7154Haynes Mathew George                if (mHwPaused) {
47912d3ca68363f723fbe269d3ce52dab4985dfc7154Haynes Mathew George                    doHwResume = true;
47922d3ca68363f723fbe269d3ce52dab4985dfc7154Haynes Mathew George                    mHwPaused = false;
47932d3ca68363f723fbe269d3ce52dab4985dfc7154Haynes Mathew George                    // threadLoop_mix() will handle the case that we need to
47942d3ca68363f723fbe269d3ce52dab4985dfc7154Haynes Mathew George                    // resume an interrupted write
47952d3ca68363f723fbe269d3ce52dab4985dfc7154Haynes Mathew George                }
47962d3ca68363f723fbe269d3ce52dab4985dfc7154Haynes Mathew George                // enable write to audio HAL
47972d3ca68363f723fbe269d3ce52dab4985dfc7154Haynes Mathew George                sleepTime = 0;
47982d3ca68363f723fbe269d3ce52dab4985dfc7154Haynes Mathew George
47992d3ca68363f723fbe269d3ce52dab4985dfc7154Haynes Mathew George                // Do not handle new data in this iteration even if track->framesReady()
48002d3ca68363f723fbe269d3ce52dab4985dfc7154Haynes Mathew George                mixerStatus = MIXER_TRACKS_ENABLED;
48012d3ca68363f723fbe269d3ce52dab4985dfc7154Haynes Mathew George            }
48022d3ca68363f723fbe269d3ce52dab4985dfc7154Haynes Mathew George        }  else if (track->framesReady() && track->isReady() &&
48033b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent                !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
4804f20e1d8df84c5fbeeace0052d100982ae39bb7a4Glenn Kasten            ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
4805bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            if (track->mFillingUpStatus == Track::FS_FILLED) {
4806bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                track->mFillingUpStatus = Track::FS_ACTIVE;
48071abbdb4429479975718421c4fef3f79ce7c820e3Eric Laurent                // make sure processVolume_l() will apply new volume even if 0
48081abbdb4429479975718421c4fef3f79ce7c820e3Eric Laurent                mLeftVolFloat = mRightVolFloat = -1.0;
4809bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            }
4810bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
4811bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            if (last) {
4812d7e59228caad3867794d847f6bf163c6495e9506Eric Laurent                sp<Track> previousTrack = mPreviousTrack.promote();
4813d7e59228caad3867794d847f6bf163c6495e9506Eric Laurent                if (previousTrack != 0) {
4814d7e59228caad3867794d847f6bf163c6495e9506Eric Laurent                    if (track != previousTrack.get()) {
48159da3d9573a18ffe08365557c706cf52f09118d1cEric Laurent                        // Flush any data still being written from last track
48169da3d9573a18ffe08365557c706cf52f09118d1cEric Laurent                        mBytesRemaining = 0;
48179da3d9573a18ffe08365557c706cf52f09118d1cEric Laurent                        if (mPausedBytesRemaining) {
48189da3d9573a18ffe08365557c706cf52f09118d1cEric Laurent                            // Last track was paused so we also need to flush saved
48199da3d9573a18ffe08365557c706cf52f09118d1cEric Laurent                            // mixbuffer state and invalidate track so that it will
48209da3d9573a18ffe08365557c706cf52f09118d1cEric Laurent                            // re-submit that unwritten data when it is next resumed
48219da3d9573a18ffe08365557c706cf52f09118d1cEric Laurent                            mPausedBytesRemaining = 0;
48229da3d9573a18ffe08365557c706cf52f09118d1cEric Laurent                            // Invalidate is a bit drastic - would be more efficient
48239da3d9573a18ffe08365557c706cf52f09118d1cEric Laurent                            // to have a flag to tell client that some of the
48249da3d9573a18ffe08365557c706cf52f09118d1cEric Laurent                            // previously written data was lost
4825d7e59228caad3867794d847f6bf163c6495e9506Eric Laurent                            previousTrack->invalidate();
48269da3d9573a18ffe08365557c706cf52f09118d1cEric Laurent                        }
48279da3d9573a18ffe08365557c706cf52f09118d1cEric Laurent                        // flush data already sent to the DSP if changing audio session as audio
48289da3d9573a18ffe08365557c706cf52f09118d1cEric Laurent                        // comes from a different source. Also invalidate previous track to force a
48299da3d9573a18ffe08365557c706cf52f09118d1cEric Laurent                        // seek when resuming.
4830d7e59228caad3867794d847f6bf163c6495e9506Eric Laurent                        if (previousTrack->sessionId() != track->sessionId()) {
4831d7e59228caad3867794d847f6bf163c6495e9506Eric Laurent                            previousTrack->invalidate();
48329da3d9573a18ffe08365557c706cf52f09118d1cEric Laurent                        }
48339da3d9573a18ffe08365557c706cf52f09118d1cEric Laurent                    }
48349da3d9573a18ffe08365557c706cf52f09118d1cEric Laurent                }
48359da3d9573a18ffe08365557c706cf52f09118d1cEric Laurent                mPreviousTrack = track;
4836bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                // reset retry count
4837bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                track->mRetryCount = kMaxTrackRetriesOffload;
4838bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                mActiveTrack = t;
4839bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                mixerStatus = MIXER_TRACKS_READY;
4840bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            }
4841bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        } else {
4842f20e1d8df84c5fbeeace0052d100982ae39bb7a4Glenn Kasten            ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
4843bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            if (track->isStopping_1()) {
4844bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                // Hardware buffer can hold a large amount of audio so we must
4845bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                // wait for all current track's data to drain before we say
4846bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                // that the track is stopped.
4847bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                if (mBytesRemaining == 0) {
4848bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                    // Only start draining when all data in mixbuffer
4849bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                    // has been written
4850bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                    ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4851bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                    track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
48526a51d7ed7062536ccc892c8850a34ed55cbc8d5cEric Laurent                    // do not drain if no data was ever sent to HAL (mStandby == true)
48536a51d7ed7062536ccc892c8850a34ed55cbc8d5cEric Laurent                    if (last && !mStandby) {
48541b9f9b134e732a48198e51f16424f330cbf03143Eric Laurent                        // do not modify drain sequence if we are already draining. This happens
48551b9f9b134e732a48198e51f16424f330cbf03143Eric Laurent                        // when resuming from pause after drain.
48561b9f9b134e732a48198e51f16424f330cbf03143Eric Laurent                        if ((mDrainSequence & 1) == 0) {
48571b9f9b134e732a48198e51f16424f330cbf03143Eric Laurent                            sleepTime = 0;
48581b9f9b134e732a48198e51f16424f330cbf03143Eric Laurent                            standbyTime = systemTime() + standbyDelay;
48591b9f9b134e732a48198e51f16424f330cbf03143Eric Laurent                            mixerStatus = MIXER_DRAIN_TRACK;
48601b9f9b134e732a48198e51f16424f330cbf03143Eric Laurent                            mDrainSequence += 2;
48611b9f9b134e732a48198e51f16424f330cbf03143Eric Laurent                        }
4862bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                        if (mHwPaused) {
4863bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                            // It is possible to move from PAUSED to STOPPING_1 without
4864bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                            // a resume so we must ensure hardware is running
48651b9f9b134e732a48198e51f16424f330cbf03143Eric Laurent                            doHwResume = true;
4866bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                            mHwPaused = false;
4867bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                        }
4868bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                    }
4869bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                }
4870bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            } else if (track->isStopping_2()) {
48716a51d7ed7062536ccc892c8850a34ed55cbc8d5cEric Laurent                // Drain has completed or we are in standby, signal presentation complete
48726a51d7ed7062536ccc892c8850a34ed55cbc8d5cEric Laurent                if (!(mDrainSequence & 1) || !last || mStandby) {
4873bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                    track->mState = TrackBase::STOPPED;
4874bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                    size_t audioHALFrames =
4875bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                            (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
4876bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                    size_t framesWritten =
4877062e67a26e0553dd142be622821f493df541f0c6Phil Burk                            mBytesWritten / mOutput->getFrameSize();
4878bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                    track->presentationComplete(framesWritten, audioHALFrames);
4879bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                    track->reset();
4880bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                    tracksToRemove->add(track);
4881bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                }
4882bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            } else {
4883bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                // No buffers for this track. Give it a few chances to
4884bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                // fill a buffer, then remove it from active list.
4885bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                if (--(track->mRetryCount) <= 0) {
4886bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                    ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
4887bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                          track->name());
4888bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                    tracksToRemove->add(track);
4889a23f17ac334ff20a11ee63dd177cb1080e44c483Eric Laurent                    // indicate to client process that the track was disabled because of underrun;
4890a23f17ac334ff20a11ee63dd177cb1080e44c483Eric Laurent                    // it will then automatically call start() when data is available
4891a23f17ac334ff20a11ee63dd177cb1080e44c483Eric Laurent                    android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
4892bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                } else if (last){
4893bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                    mixerStatus = MIXER_TRACKS_ENABLED;
4894bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent                }
4895bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent            }
4896bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        }
4897bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        // compute volume for this track
4898bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        processVolume_l(track, last);
4899bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    }
49006bf9ae20b3bd2dbb8f2e89ee167a6785222301cfEric Laurent
4901ea0fadeb5d81ef3cb7f9db458c9033d628bdb86aEric Laurent    // make sure the pause/flush/resume sequence is executed in the right order.
4902ea0fadeb5d81ef3cb7f9db458c9033d628bdb86aEric Laurent    // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4903ea0fadeb5d81ef3cb7f9db458c9033d628bdb86aEric Laurent    // before flush and then resume HW. This can happen in case of pause/flush/resume
4904ea0fadeb5d81ef3cb7f9db458c9033d628bdb86aEric Laurent    // if resume is received before pause is executed.
4905fd4779740ec3e9e865d5514464df26d015354388Eric Laurent    if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
4906972a173d7d1de1a3b5a617aae3e2abb6e05ae02dEric Laurent        mOutput->stream->pause(mOutput->stream);
4907972a173d7d1de1a3b5a617aae3e2abb6e05ae02dEric Laurent    }
49086bf9ae20b3bd2dbb8f2e89ee167a6785222301cfEric Laurent    if (mFlushPending) {
49096bf9ae20b3bd2dbb8f2e89ee167a6785222301cfEric Laurent        flushHw_l();
49106bf9ae20b3bd2dbb8f2e89ee167a6785222301cfEric Laurent        mFlushPending = false;
49116bf9ae20b3bd2dbb8f2e89ee167a6785222301cfEric Laurent    }
4912fd4779740ec3e9e865d5514464df26d015354388Eric Laurent    if (!mStandby && doHwResume) {
4913972a173d7d1de1a3b5a617aae3e2abb6e05ae02dEric Laurent        mOutput->stream->resume(mOutput->stream);
4914972a173d7d1de1a3b5a617aae3e2abb6e05ae02dEric Laurent    }
49156bf9ae20b3bd2dbb8f2e89ee167a6785222301cfEric Laurent
4916bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    // remove all the tracks that need to be...
4917bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    removeTracks_l(*tracksToRemove);
4918bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
4919bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    return mixerStatus;
4920bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent}
4921bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
4922bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent// must be called with thread mutex locked
4923bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurentbool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4924bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent{
49253b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent    ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
49263b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent          mWriteAckSequence, mDrainSequence);
49273b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent    if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
4928bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        return true;
4929bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    }
4930bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    return false;
4931bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent}
4932bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
4933bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurentbool AudioFlinger::OffloadThread::waitingAsyncCallback()
4934bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent{
4935bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    Mutex::Autolock _l(mLock);
4936bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    return waitingAsyncCallback_l();
4937bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent}
4938bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
4939bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurentvoid AudioFlinger::OffloadThread::flushHw_l()
4940bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent{
4941e659ef420dae0caae84ab78f9df8952acb9ad3a0Eric Laurent    DirectOutputThread::flushHw_l();
4942bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    // Flush anything still waiting in the mixbuffer
4943bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    mCurrentWriteLength = 0;
4944bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    mBytesRemaining = 0;
4945bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    mPausedWriteLength = 0;
4946bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    mPausedBytesRemaining = 0;
49470f02f265123b7ef2fd6ac09ff70cde26eb5559adHaynes Mathew George
4948bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    if (mUseAsyncWrite) {
49493b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent        // discard any pending drain or write ack by incrementing sequence
49503b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent        mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
49513b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent        mDrainSequence = (mDrainSequence + 2) & ~1;
4952bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent        ALOG_ASSERT(mCallbackThread != 0);
49533b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent        mCallbackThread->setWriteBlocked(mWriteAckSequence);
49543b4529e03c5fc7a44c22f9091ad15a269bfca3a8Eric Laurent        mCallbackThread->setDraining(mDrainSequence);
4955bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    }
4956bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent}
4957bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
49584c6a433d74d5ae8b9bc0557207e3ced43bf34a25Haynes Mathew Georgevoid AudioFlinger::OffloadThread::onAddNewTrack_l()
49594c6a433d74d5ae8b9bc0557207e3ced43bf34a25Haynes Mathew George{
49604c6a433d74d5ae8b9bc0557207e3ced43bf34a25Haynes Mathew George    sp<Track> previousTrack = mPreviousTrack.promote();
49614c6a433d74d5ae8b9bc0557207e3ced43bf34a25Haynes Mathew George    sp<Track> latestTrack = mLatestActiveTrack.promote();
49624c6a433d74d5ae8b9bc0557207e3ced43bf34a25Haynes Mathew George
49634c6a433d74d5ae8b9bc0557207e3ced43bf34a25Haynes Mathew George    if (previousTrack != 0 && latestTrack != 0 &&
49644c6a433d74d5ae8b9bc0557207e3ced43bf34a25Haynes Mathew George        (previousTrack->sessionId() != latestTrack->sessionId())) {
49654c6a433d74d5ae8b9bc0557207e3ced43bf34a25Haynes Mathew George        mFlushPending = true;
49664c6a433d74d5ae8b9bc0557207e3ced43bf34a25Haynes Mathew George    }
49674c6a433d74d5ae8b9bc0557207e3ced43bf34a25Haynes Mathew George    PlaybackThread::onAddNewTrack_l();
49684c6a433d74d5ae8b9bc0557207e3ced43bf34a25Haynes Mathew George}
49694c6a433d74d5ae8b9bc0557207e3ced43bf34a25Haynes Mathew George
4970bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent// ----------------------------------------------------------------------------
4971bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent
497281784c37c61b09289654b979567a42bf73cd2b12Eric LaurentAudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
497381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
497481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    :   MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
497581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                DUPLICATING),
497681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mWaitTimeMs(UINT_MAX)
497781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
497881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    addOutputTrack(mainThread);
497981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
498081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
498181784c37c61b09289654b979567a42bf73cd2b12Eric LaurentAudioFlinger::DuplicatingThread::~DuplicatingThread()
498281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
498381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    for (size_t i = 0; i < mOutputTracks.size(); i++) {
498481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mOutputTracks[i]->destroy();
498581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
498681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
498781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
498881784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::DuplicatingThread::threadLoop_mix()
498981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
499081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // mix buffers...
499181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (outputsReady(outputTracks)) {
499281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
499381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    } else {
499402b5708776ba2a9b4ff8c09008483aef7dbe38c7Eric Laurent        if (mMixerBufferValid) {
499502b5708776ba2a9b4ff8c09008483aef7dbe38c7Eric Laurent            memset(mMixerBuffer, 0, mMixerBufferSize);
499602b5708776ba2a9b4ff8c09008483aef7dbe38c7Eric Laurent        } else {
499702b5708776ba2a9b4ff8c09008483aef7dbe38c7Eric Laurent            memset(mSinkBuffer, 0, mSinkBufferSize);
499802b5708776ba2a9b4ff8c09008483aef7dbe38c7Eric Laurent        }
499981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
500081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    sleepTime = 0;
500181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    writeFrames = mNormalFrameCount;
500225c2dac12114699e90deb1c579cadebce7b91a97Andy Hung    mCurrentWriteLength = mSinkBufferSize;
500381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    standbyTime = systemTime() + standbyDelay;
500481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
500581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
500681784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
500781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
500881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (sleepTime == 0) {
500981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (mMixerStatus == MIXER_TRACKS_ENABLED) {
501081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            sleepTime = activeSleepTime;
501181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        } else {
501281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            sleepTime = idleSleepTime;
501381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
501481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    } else if (mBytesWritten != 0) {
501581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (mMixerStatus == MIXER_TRACKS_ENABLED) {
501681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            writeFrames = mNormalFrameCount;
501725c2dac12114699e90deb1c579cadebce7b91a97Andy Hung            memset(mSinkBuffer, 0, mSinkBufferSize);
501881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        } else {
501981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // flush remaining overflow buffers in output tracks
502081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            writeFrames = 0;
502181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
502281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sleepTime = 0;
502381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
502481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
502581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
5026bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurentssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
502781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
502881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    for (size_t i = 0; i < outputTracks.size(); i++) {
5029c25b84abdd7ff229d0af663fbf3a37bd9512939dAndy Hung        outputTracks[i]->write(mSinkBuffer, writeFrames);
503081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
50312c3740f01acca69c3e0bcc5e01bb0edc51b6777fEric Laurent    mStandby = false;
503225c2dac12114699e90deb1c579cadebce7b91a97Andy Hung    return (ssize_t)mSinkBufferSize;
503381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
503481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
503581784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::DuplicatingThread::threadLoop_standby()
503681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
503781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // DuplicatingThread implements standby by stopping all tracks
503881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    for (size_t i = 0; i < outputTracks.size(); i++) {
503981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        outputTracks[i]->stop();
504081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
504181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
504281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
504381784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::DuplicatingThread::saveOutputTracks()
504481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
504581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    outputTracks = mOutputTracks;
504681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
504781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
504881784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::DuplicatingThread::clearOutputTracks()
504981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
505081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    outputTracks.clear();
505181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
505281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
505381784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
505481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
505581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
5056c25b84abdd7ff229d0af663fbf3a37bd9512939dAndy Hung    // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5057c25b84abdd7ff229d0af663fbf3a37bd9512939dAndy Hung    // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5058c25b84abdd7ff229d0af663fbf3a37bd9512939dAndy Hung    // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5059c25b84abdd7ff229d0af663fbf3a37bd9512939dAndy Hung    const size_t frameCount =
5060c25b84abdd7ff229d0af663fbf3a37bd9512939dAndy Hung            3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5061c25b84abdd7ff229d0af663fbf3a37bd9512939dAndy Hung    // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5062c25b84abdd7ff229d0af663fbf3a37bd9512939dAndy Hung    // from different OutputTracks and their associated MixerThreads (e.g. one may
5063c25b84abdd7ff229d0af663fbf3a37bd9512939dAndy Hung    // nearly empty and the other may be dropping data).
5064c25b84abdd7ff229d0af663fbf3a37bd9512939dAndy Hung
5065c25b84abdd7ff229d0af663fbf3a37bd9512939dAndy Hung    sp<OutputTrack> outputTrack = new OutputTrack(thread,
506681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                                            this,
506781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                                            mSampleRate,
5068c25b84abdd7ff229d0af663fbf3a37bd9512939dAndy Hung                                            mFormat,
506981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                                            mChannelMask,
5070462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen                                            frameCount,
5071462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen                                            IPCThreadState::self()->getCallingUid());
507281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (outputTrack->cblk() != NULL) {
5073223fd5c9738e9665e495904d37d4632414b68c1eEric Laurent        thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
507481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mOutputTracks.add(outputTrack);
5075c25b84abdd7ff229d0af663fbf3a37bd9512939dAndy Hung        ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
507681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        updateWaitTime_l();
507781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
507881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
507981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
508081784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
508181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
508281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
508381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    for (size_t i = 0; i < mOutputTracks.size(); i++) {
508481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (mOutputTracks[i]->thread() == thread) {
508581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mOutputTracks[i]->destroy();
508681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            mOutputTracks.removeAt(i);
508781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            updateWaitTime_l();
508881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            return;
508981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
509081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
509181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
509281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
509381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
509481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// caller must hold mLock
509581784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::DuplicatingThread::updateWaitTime_l()
509681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
509781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mWaitTimeMs = UINT_MAX;
509881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    for (size_t i = 0; i < mOutputTracks.size(); i++) {
509981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
510081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (strong != 0) {
510181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
510281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            if (waitTimeMs < mWaitTimeMs) {
510381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                mWaitTimeMs = waitTimeMs;
510481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
510581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
510681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
510781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
510881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
510981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
511081784c37c61b09289654b979567a42bf73cd2b12Eric Laurentbool AudioFlinger::DuplicatingThread::outputsReady(
511181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        const SortedVector< sp<OutputTrack> > &outputTracks)
511281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
511381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    for (size_t i = 0; i < outputTracks.size(); i++) {
511481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sp<ThreadBase> thread = outputTracks[i]->thread().promote();
511581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (thread == 0) {
511681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
511781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    outputTracks[i].get());
511881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            return false;
511981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
512081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
512181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // see note at standby() declaration
512281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (playbackThread->standby() && !playbackThread->isSuspended()) {
512381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
512481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    thread.get());
512581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            return false;
512681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
512781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
512881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return true;
512981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
513081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
513181784c37c61b09289654b979567a42bf73cd2b12Eric Laurentuint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
513281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
513381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return (mWaitTimeMs * 1000) / 2;
513481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
513581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
513681784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::DuplicatingThread::cacheParameters_l()
513781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
513881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
513981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    updateWaitTime_l();
514081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
514181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    MixerThread::cacheParameters_l();
514281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
514381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
514481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// ----------------------------------------------------------------------------
514581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent//      Record
514681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// ----------------------------------------------------------------------------
514781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
514881784c37c61b09289654b979567a42bf73cd2b12Eric LaurentAudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
514981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                                         AudioStreamIn *input,
515081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                                         audio_io_handle_t id,
5151d3922f72601d82c6fc067a98916fda0bd1291c5fEric Laurent                                         audio_devices_t outDevice,
515246909e7eb074ce1b95b8a411eb71154f53f84f77Glenn Kasten                                         audio_devices_t inDevice
515346909e7eb074ce1b95b8a411eb71154f53f84f77Glenn Kasten#ifdef TEE_SINK
515446909e7eb074ce1b95b8a411eb71154f53f84f77Glenn Kasten                                         , const sp<NBAIO_Sink>& teeSink
515546909e7eb074ce1b95b8a411eb71154f53f84f77Glenn Kasten#endif
515646909e7eb074ce1b95b8a411eb71154f53f84f77Glenn Kasten                                         ) :
5157d3922f72601d82c6fc067a98916fda0bd1291c5fEric Laurent    ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
51586dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten    mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
5159deca2ae0a7cf8bc54ff3f30b7dc39bbc78b94c0dGlenn Kasten    // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
51604cc0a6a835c806d200ef83ef31fe5bef327c355cGlenn Kasten    mRsmpInRear(0)
516146909e7eb074ce1b95b8a411eb71154f53f84f77Glenn Kasten#ifdef TEE_SINK
516246909e7eb074ce1b95b8a411eb71154f53f84f77Glenn Kasten    , mTeeSink(teeSink)
516346909e7eb074ce1b95b8a411eb71154f53f84f77Glenn Kasten#endif
5164b880f5e5fc07397ddd09a94ba18bdf4fa62aae00Glenn Kasten    , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5165b880f5e5fc07397ddd09a94ba18bdf4fa62aae00Glenn Kasten            "RecordThreadRO", MemoryHeapBase::READ_ONLY))
51666dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    // mFastCapture below
51676dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    , mFastCaptureFutex(0)
51686dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    // mInputSource
51696dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    // mPipeSink
51706dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    // mPipeSource
51716dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    , mPipeFramesP2(0)
51726dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    // mPipeMemory
51736dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    // mFastCaptureNBLogWriter
51746e6704c06d61bc356e30c164081e5bcffb37920cGlenn Kasten    , mFastTrackAvail(false)
517581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
5176d7dca050c630bddbd73a6623271b34b4290460eeGlenn Kasten    snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5177d7dca050c630bddbd73a6623271b34b4290460eeGlenn Kasten    mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
517881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
5179deca2ae0a7cf8bc54ff3f30b7dc39bbc78b94c0dGlenn Kasten    readInputParameters_l();
51806dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten
51816dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    // create an NBAIO source for the HAL input stream, and negotiate
51826dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    mInputSource = new AudioStreamInSource(input->stream);
51836dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    size_t numCounterOffers = 0;
51846dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
51856dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
51866dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    ALOG_ASSERT(index == 0);
51876dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten
51886dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    // initialize fast capture depending on configuration
51896dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    bool initFastCapture;
51906dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    switch (kUseFastCapture) {
51916dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    case FastCapture_Never:
51926dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        initFastCapture = false;
51936dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        break;
51946dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    case FastCapture_Always:
51956dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        initFastCapture = true;
51966dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        break;
51976dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    case FastCapture_Static:
51986dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        uint32_t primaryOutputSampleRate;
51996dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        {
52006dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            AutoMutex _l(audioFlinger->mHardwareLock);
52016dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            primaryOutputSampleRate = audioFlinger->mPrimaryOutputSampleRate;
52026dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        }
52036dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        initFastCapture =
52046dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                // either capture sample rate is same as (a reasonable) primary output sample rate
52056dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                (((primaryOutputSampleRate == 44100 || primaryOutputSampleRate == 48000) &&
52066dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                    (mSampleRate == primaryOutputSampleRate)) ||
52076dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                // or primary output sample rate is unknown, and capture sample rate is reasonable
52086dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                ((primaryOutputSampleRate == 0) &&
52096dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                    ((mSampleRate == 44100 || mSampleRate == 48000)))) &&
52109f81de3452dfb2385bd57dc05456a045174a1ab1Glenn Kasten                // and the buffer size is < 12 ms
52119f81de3452dfb2385bd57dc05456a045174a1ab1Glenn Kasten                (mFrameCount * 1000) / mSampleRate < 12;
52126dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        break;
52136dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    // case FastCapture_Dynamic:
52146dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    }
52156dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten
52166dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    if (initFastCapture) {
5217d198b85a163330b03e7507c9e8bfeb5f4d958a6cGlenn Kasten        // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
52186dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        NBAIO_Format format = mInputSource->format();
521949d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten        size_t pipeFramesP2 = roundup(mSampleRate / 25);    // double-buffering of 20 ms each
52206dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
52216dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        void *pipeBuffer;
52226dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        const sp<MemoryDealer> roHeap(readOnlyHeap());
52236dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        sp<IMemory> pipeMemory;
52246dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        if ((roHeap == 0) ||
52256dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
52266dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                (pipeBuffer = pipeMemory->pointer()) == NULL) {
52276dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
52286dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            goto failed;
52296dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        }
52306dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        // pipe will be shared directly with fast clients, so clear to avoid leaking old information
52316dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        memset(pipeBuffer, 0, pipeSize);
52326dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
52336dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        const NBAIO_Format offers[1] = {format};
52346dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        size_t numCounterOffers = 0;
52356dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
52366dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        ALOG_ASSERT(index == 0);
52376dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        mPipeSink = pipe;
52386dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        PipeReader *pipeReader = new PipeReader(*pipe);
52396dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        numCounterOffers = 0;
52406dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
52416dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        ALOG_ASSERT(index == 0);
52426dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        mPipeSource = pipeReader;
52436dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        mPipeFramesP2 = pipeFramesP2;
52446dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        mPipeMemory = pipeMemory;
52456dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten
52466dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        // create fast capture
52476dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        mFastCapture = new FastCapture();
52486dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        FastCaptureStateQueue *sq = mFastCapture->sq();
52496dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten#ifdef STATE_QUEUE_DUMP
52506dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        // FIXME
52516dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten#endif
52526dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        FastCaptureState *state = sq->begin();
52536dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        state->mCblk = NULL;
52546dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        state->mInputSource = mInputSource.get();
52556dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        state->mInputSourceGen++;
52566dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        state->mPipeSink = pipe;
52576dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        state->mPipeSinkGen++;
52586dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        state->mFrameCount = mFrameCount;
52596dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        state->mCommand = FastCaptureState::COLD_IDLE;
52606dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        // already done in constructor initialization list
52616dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        //mFastCaptureFutex = 0;
52626dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        state->mColdFutexAddr = &mFastCaptureFutex;
52636dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        state->mColdGen++;
52646dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        state->mDumpState = &mFastCaptureDumpState;
52656dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten#ifdef TEE_SINK
52666dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        // FIXME
52676dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten#endif
52686dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
52696dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        state->mNBLogWriter = mFastCaptureNBLogWriter.get();
52706dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        sq->end();
52716dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
52726dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten
52736dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        // start the fast capture
52746dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
52756dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        pid_t tid = mFastCapture->getTid();
52766dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
52776dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        if (err != 0) {
52786dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
52796dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                    kPriorityFastCapture, getpid_cached, tid, err);
52806dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        }
52816dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten
52826dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten#ifdef AUDIO_WATCHDOG
52836dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        // FIXME
52846dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten#endif
52856dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten
52866e6704c06d61bc356e30c164081e5bcffb37920cGlenn Kasten        mFastTrackAvail = true;
52876dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    }
52886dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kastenfailed: ;
52896dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten
52906dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    // FIXME mNormalSource
529181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
529281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
529381784c37c61b09289654b979567a42bf73cd2b12Eric LaurentAudioFlinger::RecordThread::~RecordThread()
529481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
52956dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    if (mFastCapture != 0) {
52966dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        FastCaptureStateQueue *sq = mFastCapture->sq();
52976dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        FastCaptureState *state = sq->begin();
52986dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        if (state->mCommand == FastCaptureState::COLD_IDLE) {
52996dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            int32_t old = android_atomic_inc(&mFastCaptureFutex);
53006dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            if (old == -1) {
53016dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
53026dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            }
53036dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        }
53046dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        state->mCommand = FastCaptureState::EXIT;
53056dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        sq->end();
53066dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
53076dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        mFastCapture->join();
53086dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        mFastCapture.clear();
53096dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    }
53106dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
5311481fb67a595f23c5b7f5be84b06db9b84a41a42fGlenn Kasten    mAudioFlinger->unregisterWriter(mNBLogWriter);
531281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    delete[] mRsmpInBuffer;
531381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
531481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
531581784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::RecordThread::onFirstRef()
531681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
5317d7dca050c630bddbd73a6623271b34b4290460eeGlenn Kasten    run(mThreadName, PRIORITY_URGENT_AUDIO);
531881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
531981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
532081784c37c61b09289654b979567a42bf73cd2b12Eric Laurentbool AudioFlinger::RecordThread::threadLoop()
532181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
532281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    nsecs_t lastWarning = 0;
532381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
532481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    inputStandBy();
532581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
5326f10ffec18f930d92e1abe9200d60e746831841a7Glenn Kastenreacquire_wakelock:
5327f10ffec18f930d92e1abe9200d60e746831841a7Glenn Kasten    sp<RecordTrack> activeTrack;
53282b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten    int activeTracksGen;
5329f10ffec18f930d92e1abe9200d60e746831841a7Glenn Kasten    {
5330f10ffec18f930d92e1abe9200d60e746831841a7Glenn Kasten        Mutex::Autolock _l(mLock);
53312b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten        size_t size = mActiveTracks.size();
53322b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten        activeTracksGen = mActiveTracksGen;
53332b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten        if (size > 0) {
53342b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten            // FIXME an arbitrary choice
53352b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten            activeTrack = mActiveTracks[0];
53362b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten            acquireWakeLock_l(activeTrack->uid());
53372b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten            if (size > 1) {
53382b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten                SortedVector<int> tmp;
53392b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten                for (size_t i = 0; i < size; i++) {
53402b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten                    tmp.add(mActiveTracks[i]->uid());
53412b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten                }
53422b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten                updateWakeLockUids_l(tmp);
53432b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten            }
53442b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten        } else {
53452b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten            acquireWakeLock_l(-1);
53462b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten        }
5347f10ffec18f930d92e1abe9200d60e746831841a7Glenn Kasten    }
5348f10ffec18f930d92e1abe9200d60e746831841a7Glenn Kasten
53496dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten    // used to request a deferred sleep, to be executed later while mutex is unlocked
53506dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten    uint32_t sleepUs = 0;
53516dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten
53526dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten    // loop while there is work to do
53534ef0b463a56c19bad9197aa9f90d792090461429Glenn Kasten    for (;;) {
5354c527a7c2b1bfd26e8f3086e1b653d56e521379d9Glenn Kasten        Vector< sp<EffectChain> > effectChains;
53552cfbf88b89854f30b295e8ae26a031edb8d712f8Glenn Kasten
53565edadd46c76c5ff1c3edabf2ea943c2278e82e1cGlenn Kasten        // sleep with mutex unlocked
53576dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        if (sleepUs > 0) {
5358e77540228e1f60b1129a1615d2e43e0bf8015d3cGlenn Kasten            ATRACE_BEGIN("sleep");
53596dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten            usleep(sleepUs);
5360e77540228e1f60b1129a1615d2e43e0bf8015d3cGlenn Kasten            ATRACE_END();
53616dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten            sleepUs = 0;
53625edadd46c76c5ff1c3edabf2ea943c2278e82e1cGlenn Kasten        }
53635edadd46c76c5ff1c3edabf2ea943c2278e82e1cGlenn Kasten
53646dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        // activeTracks accumulates a copy of a subset of mActiveTracks
53656dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        Vector< sp<RecordTrack> > activeTracks;
53666dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten
5367735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten        // reference to the (first and only) active fast track
53686dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        sp<RecordTrack> fastTrack;
53691035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent
5370735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten        // reference to a fast track which is about to be removed
5371735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten        sp<RecordTrack> fastTrackToRemove;
5372735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten
537381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        { // scope for mLock
537481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            Mutex::Autolock _l(mLock);
5375000a4193dd82549192277fd4b9bb571d8a4c262fEric Laurent
5376021cf9634ab09c0753a40b7c9ef4ba603be5c3daEric Laurent            processConfigEvents_l();
5377f10ffec18f930d92e1abe9200d60e746831841a7Glenn Kasten
5378000a4193dd82549192277fd4b9bb571d8a4c262fEric Laurent            // check exitPending here because checkForNewParameters_l() and
5379000a4193dd82549192277fd4b9bb571d8a4c262fEric Laurent            // checkForNewParameters_l() can temporarily release mLock
5380000a4193dd82549192277fd4b9bb571d8a4c262fEric Laurent            if (exitPending()) {
5381000a4193dd82549192277fd4b9bb571d8a4c262fEric Laurent                break;
5382000a4193dd82549192277fd4b9bb571d8a4c262fEric Laurent            }
5383000a4193dd82549192277fd4b9bb571d8a4c262fEric Laurent
53842b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten            // if no active track(s), then standby and release wakelock
53852b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten            size_t size = mActiveTracks.size();
53862b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten            if (size == 0) {
538793e471f620454f7de73d190521568b1e25879767Glenn Kasten                standbyIfNotAlreadyInStandby();
53884ef0b463a56c19bad9197aa9f90d792090461429Glenn Kasten                // exitPending() can't become true here
538981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                releaseWakeLock_l();
539081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                ALOGV("RecordThread: loop stopping");
539181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                // go to sleep
539281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                mWaitWorkCV.wait(mLock);
539381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                ALOGV("RecordThread: loop starting");
5394f10ffec18f930d92e1abe9200d60e746831841a7Glenn Kasten                goto reacquire_wakelock;
5395f10ffec18f930d92e1abe9200d60e746831841a7Glenn Kasten            }
5396f10ffec18f930d92e1abe9200d60e746831841a7Glenn Kasten
53972b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten            if (mActiveTracksGen != activeTracksGen) {
53982b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten                activeTracksGen = mActiveTracksGen;
5399f10ffec18f930d92e1abe9200d60e746831841a7Glenn Kasten                SortedVector<int> tmp;
54002b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten                for (size_t i = 0; i < size; i++) {
54012b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten                    tmp.add(mActiveTracks[i]->uid());
54022b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten                }
5403f10ffec18f930d92e1abe9200d60e746831841a7Glenn Kasten                updateWakeLockUids_l(tmp);
540481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
54059e98235a9e9bb870e1c76911e3b4d00386a52c39Glenn Kasten
54066dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten            bool doBroadcast = false;
54076dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten            for (size_t i = 0; i < size; ) {
54089e98235a9e9bb870e1c76911e3b4d00386a52c39Glenn Kasten
54096dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                activeTrack = mActiveTracks[i];
54106dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                if (activeTrack->isTerminated()) {
5411735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten                    if (activeTrack->isFastTrack()) {
5412735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten                        ALOG_ASSERT(fastTrackToRemove == 0);
5413735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten                        fastTrackToRemove = activeTrack;
5414735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten                    }
54156dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    removeTrack_l(activeTrack);
54162b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten                    mActiveTracks.remove(activeTrack);
54172b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten                    mActiveTracksGen++;
54186dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    size--;
54199e98235a9e9bb870e1c76911e3b4d00386a52c39Glenn Kasten                    continue;
54209e98235a9e9bb870e1c76911e3b4d00386a52c39Glenn Kasten                }
54216dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten
54226dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                TrackBase::track_state activeTrackState = activeTrack->mState;
54236dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                switch (activeTrackState) {
54246dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten
54256dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                case TrackBase::PAUSING:
54266dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    mActiveTracks.remove(activeTrack);
54276dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    mActiveTracksGen++;
54286dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    doBroadcast = true;
54296dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    size--;
54306dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    continue;
54316dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten
54326dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                case TrackBase::STARTING_1:
54336dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    sleepUs = 10000;
54346dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    i++;
54356dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    continue;
54366dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten
54376dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                case TrackBase::STARTING_2:
54386dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    doBroadcast = true;
54396dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    mStandby = false;
54409e98235a9e9bb870e1c76911e3b4d00386a52c39Glenn Kasten                    activeTrack->mState = TrackBase::ACTIVE;
54416dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    break;
54426dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten
54436dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                case TrackBase::ACTIVE:
54446dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    break;
54456dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten
54466dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                case TrackBase::IDLE:
54476dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    i++;
54486dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    continue;
54496dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten
54506dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                default:
5451adad3d7d935da176ff24941b4ae9edf7340e9b96Glenn Kasten                    LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
54529e98235a9e9bb870e1c76911e3b4d00386a52c39Glenn Kasten                }
54532d94426cd3302cb1215c92c5f1c4b90c24ceb72bGlenn Kasten
54546dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                activeTracks.add(activeTrack);
54556dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                i++;
54562d94426cd3302cb1215c92c5f1c4b90c24ceb72bGlenn Kasten
54576dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                if (activeTrack->isFastTrack()) {
54586dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                    ALOG_ASSERT(!mFastTrackAvail);
54596dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                    ALOG_ASSERT(fastTrack == 0);
54606dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                    fastTrack = activeTrack;
54616dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                }
54626dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten            }
54636dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten            if (doBroadcast) {
54646dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                mStartStopCond.broadcast();
54656dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten            }
5466d9fc34fb0fcfcc739f868b116edf50c62af19d5eGlenn Kasten
54676dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten            // sleep if there are no active tracks to process
54686dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten            if (activeTracks.size() == 0) {
54696dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                if (sleepUs == 0) {
54706dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    sleepUs = kRecordThreadSleepUs;
54716dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                }
54726dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                continue;
547381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
54746dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten            sleepUs = 0;
54759e98235a9e9bb870e1c76911e3b4d00386a52c39Glenn Kasten
547681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            lockEffectChains_l(effectChains);
547781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
547881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
54796dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
54807165268ffa6c7b6b405b6afad82e2a346500e8eeGlenn Kasten
54816dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        size_t size = effectChains.size();
54826dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        for (size_t i = 0; i < size; i++) {
54831ba19cd7fcdf18ab6efab2a1b831affab9a46157Glenn Kasten            // thread mutex is not locked, but effect chain is locked
54841ba19cd7fcdf18ab6efab2a1b831affab9a46157Glenn Kasten            effectChains[i]->process_l();
54851ba19cd7fcdf18ab6efab2a1b831affab9a46157Glenn Kasten        }
548681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
5487735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten        // Push a new fast capture state if fast capture is not already running, or cblk change
54886dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        if (mFastCapture != 0) {
54896dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            FastCaptureStateQueue *sq = mFastCapture->sq();
54906dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            FastCaptureState *state = sq->begin();
5491735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten            bool didModify = false;
5492735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten            FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
54936dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
54946dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                    (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
54956dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                if (state->mCommand == FastCaptureState::COLD_IDLE) {
54966dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                    int32_t old = android_atomic_inc(&mFastCaptureFutex);
54976dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                    if (old == -1) {
54986dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                        (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
54996dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                    }
55006dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                }
55016dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                state->mCommand = FastCaptureState::READ_WRITE;
55026dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten#if 0   // FIXME
55036dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
5504fbdb2aceab7317aa44bc8f301a93eb49e17b2bceGlenn Kasten                        FastThreadDumpState::kSamplingNforLowRamDevice :
5505fbdb2aceab7317aa44bc8f301a93eb49e17b2bceGlenn Kasten                        FastThreadDumpState::kSamplingN);
55066dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten#endif
5507735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten                didModify = true;
5508735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten            }
5509735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten            audio_track_cblk_t *cblkOld = state->mCblk;
5510735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten            audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
5511735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten            if (cblkNew != cblkOld) {
5512735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten                state->mCblk = cblkNew;
5513735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten                // block until acked if removing a fast track
5514735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten                if (cblkOld != NULL) {
5515735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten                    block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
5516735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten                }
5517735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten                didModify = true;
5518735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten            }
5519735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten            sq->end(didModify);
5520735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten            if (didModify) {
5521735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten                sq->push(block);
55226dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten#if 0
55236dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                if (kUseFastCapture == FastCapture_Dynamic) {
55246dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                    mNormalSource = mPipeSource;
55256dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                }
55266dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten#endif
55276dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            }
55286dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        }
55296dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten
5530735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten        // now run the fast track destructor with thread mutex unlocked
5531735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten        fastTrackToRemove.clear();
5532735f45fbc37d7905ffb722f40727edbed82319b7Glenn Kasten
55336dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
55346dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        // Only the client(s) that are too slow will overrun. But if even the fastest client is too
55356dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        // slow, then this RecordThread will overrun by not calling HAL read often enough.
55366dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        // If destination is non-contiguous, first read past the nominal end of buffer, then
55376dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        // copy to the right place.  Permitted because mRsmpInBuffer was over-allocated.
55386dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten
55396dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
55406dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        ssize_t framesRead;
55416dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten
55426dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        // If an NBAIO source is present, use it to read the normal capture's data
55436dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        if (mPipeSource != 0) {
55446dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            size_t framesToRead = mBufferSize / mFrameSize;
55456dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            framesRead = mPipeSource->read(&mRsmpInBuffer[rear * mChannelCount],
55466dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                    framesToRead, AudioBufferProvider::kInvalidPTS);
55476dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            if (framesRead == 0) {
55486dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                // since pipe is non-blocking, simulate blocking input
55496dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                sleepUs = (framesToRead * 1000000LL) / mSampleRate;
55506dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            }
55516dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        // otherwise use the HAL / AudioStreamIn directly
55526dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        } else {
55536dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            ssize_t bytesRead = mInput->stream->read(mInput->stream,
55546dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                    &mRsmpInBuffer[rear * mChannelCount], mBufferSize);
55556dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            if (bytesRead < 0) {
55566dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                framesRead = bytesRead;
55576dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            } else {
55586dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                framesRead = bytesRead / mFrameSize;
55596dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            }
55606dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        }
55616dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten
55626dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
55636dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            ALOGE("read failed: framesRead=%d", framesRead);
55646dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten            // Force input into standby so that it tries to recover at next read attempt
55656dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten            inputStandBy();
55666dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten            sleepUs = kRecordThreadSleepUs;
55676dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        }
55686dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        if (framesRead <= 0) {
55693d61bc1ffc8afc8d7be3b0d4205c9b5ba6daf2e8Glenn Kasten            goto unlock;
55706dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        }
55716dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        ALOG_ASSERT(framesRead > 0);
55726dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten
55736dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        if (mTeeSink != 0) {
55746dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten            (void) mTeeSink->write(&mRsmpInBuffer[rear * mChannelCount], framesRead);
55756dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        }
55766dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        // If destination is non-contiguous, we now correct for reading past end of buffer.
55773d61bc1ffc8afc8d7be3b0d4205c9b5ba6daf2e8Glenn Kasten        {
55783d61bc1ffc8afc8d7be3b0d4205c9b5ba6daf2e8Glenn Kasten            size_t part1 = mRsmpInFramesP2 - rear;
55793d61bc1ffc8afc8d7be3b0d4205c9b5ba6daf2e8Glenn Kasten            if ((size_t) framesRead > part1) {
55803d61bc1ffc8afc8d7be3b0d4205c9b5ba6daf2e8Glenn Kasten                memcpy(mRsmpInBuffer, &mRsmpInBuffer[mRsmpInFramesP2 * mChannelCount],
55813d61bc1ffc8afc8d7be3b0d4205c9b5ba6daf2e8Glenn Kasten                        (framesRead - part1) * mFrameSize);
55823d61bc1ffc8afc8d7be3b0d4205c9b5ba6daf2e8Glenn Kasten            }
55836dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        }
55846dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        rear = mRsmpInRear += framesRead;
55856dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten
55866dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        size = activeTracks.size();
55876dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        // loop over each active track
55886dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        for (size_t i = 0; i < size; i++) {
55896dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten            activeTrack = activeTracks[i];
55906dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten
55916dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            // skip fast tracks, as those are handled directly by FastCapture
55926dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            if (activeTrack->isFastTrack()) {
55936dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                continue;
55946dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            }
55956dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten
559697a893eb34f8687485c88eaf15917974a203f20bAndy Hung            // TODO: Update the activeTrack buffer converter in case of reconfigure.
559797a893eb34f8687485c88eaf15917974a203f20bAndy Hung
55986dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten            enum {
55996dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                OVERRUN_UNKNOWN,
56006dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                OVERRUN_TRUE,
56016dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                OVERRUN_FALSE
56026dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten            } overrun = OVERRUN_UNKNOWN;
56036dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten
56046dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten            // loop over getNextBuffer to handle circular sink
56056dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten            for (;;) {
56066dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten
56076dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                activeTrack->mSink.frameCount = ~0;
56086dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
56096dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                size_t framesOut = activeTrack->mSink.frameCount;
56106dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
56116dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten
56126dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                int32_t front = activeTrack->mRsmpInFront;
56136dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                ssize_t filled = rear - front;
56146dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                size_t framesIn;
56156dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten
56166dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                if (filled < 0) {
56176dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    // should not happen, but treat like a massive overrun and re-sync
56186dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    framesIn = 0;
56196dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    activeTrack->mRsmpInFront = rear;
56206dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    overrun = OVERRUN_TRUE;
5621607fa3e928de696eba49f198af72d68e4591ca1bGlenn Kasten                } else if ((size_t) filled <= mRsmpInFrames) {
56226dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    framesIn = (size_t) filled;
56236dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                } else {
56246dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    // client is not keeping up with server, but give it latest data
5625607fa3e928de696eba49f198af72d68e4591ca1bGlenn Kasten                    framesIn = mRsmpInFrames;
5626607fa3e928de696eba49f198af72d68e4591ca1bGlenn Kasten                    activeTrack->mRsmpInFront = front = rear - framesIn;
56276dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    overrun = OVERRUN_TRUE;
56286dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                }
56296dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten
56304cc0a6a835c806d200ef83ef31fe5bef327c355cGlenn Kasten                if (framesOut == 0 || framesIn == 0) {
56314cc0a6a835c806d200ef83ef31fe5bef327c355cGlenn Kasten                    break;
56324cc0a6a835c806d200ef83ef31fe5bef327c355cGlenn Kasten                }
56334cc0a6a835c806d200ef83ef31fe5bef327c355cGlenn Kasten
563497a893eb34f8687485c88eaf15917974a203f20bAndy Hung                // process frames from the RecordThread buffer provider to the RecordTrack buffer
563597a893eb34f8687485c88eaf15917974a203f20bAndy Hung                framesOut = activeTrack->mRecordBufferConverter->convert(
563697a893eb34f8687485c88eaf15917974a203f20bAndy Hung                        activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
56378594843c15b4722ced39436fe9e64f3e57e7ace4Glenn Kasten
56386dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
56396dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    overrun = OVERRUN_FALSE;
56401ba19cd7fcdf18ab6efab2a1b831affab9a46157Glenn Kasten                }
564181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
56426dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                if (activeTrack->mFramesToDrop == 0) {
56436dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    if (framesOut > 0) {
56446dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                        activeTrack->mSink.frameCount = framesOut;
56456dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                        activeTrack->releaseBuffer(&activeTrack->mSink);
564681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    }
564781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                } else {
56486dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    // FIXME could do a partial drop of framesOut
56496dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    if (activeTrack->mFramesToDrop > 0) {
56506dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                        activeTrack->mFramesToDrop -= framesOut;
56516dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                        if (activeTrack->mFramesToDrop <= 0) {
565225f4aa83efaa9179e65a20583a6d441de2c3ff3fGlenn Kasten                            activeTrack->clearSyncStartEvent();
56536dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                        }
56546dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    } else {
56556dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                        activeTrack->mFramesToDrop += framesOut;
56566dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                        if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
56576dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                                activeTrack->mSyncStartEvent->isCancelled()) {
56586dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                            ALOGW("Synced record %s, session %d, trigger session %d",
56596dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                                  (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
56606dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                                  activeTrack->sessionId(),
56616dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                                  (activeTrack->mSyncStartEvent != 0) ?
56626dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                                          activeTrack->mSyncStartEvent->triggerSession() : 0);
566325f4aa83efaa9179e65a20583a6d441de2c3ff3fGlenn Kasten                            activeTrack->clearSyncStartEvent();
56646dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                        }
566581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    }
566681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
56676dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten
56686dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                if (framesOut == 0) {
56696dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    break;
56706dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                }
567181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
56726dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten
56736dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten            switch (overrun) {
56746dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten            case OVERRUN_TRUE:
56756dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                // client isn't retrieving buffers fast enough
56766dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                if (!activeTrack->setOverflow()) {
56776dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    nsecs_t now = systemTime();
56786dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    // FIXME should lastWarning per track?
56796dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    if ((now - lastWarning) > kWarningThrottleNs) {
56806dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                        ALOGW("RecordThread: buffer overflow");
56816dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                        lastWarning = now;
56826dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                    }
568381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
56846dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                break;
56856dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten            case OVERRUN_FALSE:
56866dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                activeTrack->clearOverflow();
56876dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                break;
56886dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten            case OVERRUN_UNKNOWN:
56896dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                break;
569081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
56916dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten
569281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
56931ba19cd7fcdf18ab6efab2a1b831affab9a46157Glenn Kasten
56943d61bc1ffc8afc8d7be3b0d4205c9b5ba6daf2e8Glenn Kastenunlock:
569581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // enable changes in effect chain
569681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        unlockEffectChains(effectChains);
5697c527a7c2b1bfd26e8f3086e1b653d56e521379d9Glenn Kasten        // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
569881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
569981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
570093e471f620454f7de73d190521568b1e25879767Glenn Kasten    standbyIfNotAlreadyInStandby();
570181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
570281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    {
570381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        Mutex::Autolock _l(mLock);
57049a54bc27876acd5d8be5b1fc3dc46701fe76fbb3Eric Laurent        for (size_t i = 0; i < mTracks.size(); i++) {
57059a54bc27876acd5d8be5b1fc3dc46701fe76fbb3Eric Laurent            sp<RecordTrack> track = mTracks[i];
57069a54bc27876acd5d8be5b1fc3dc46701fe76fbb3Eric Laurent            track->invalidate();
57079a54bc27876acd5d8be5b1fc3dc46701fe76fbb3Eric Laurent        }
57082b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten        mActiveTracks.clear();
57092b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten        mActiveTracksGen++;
571081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mStartStopCond.broadcast();
571181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
571281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
571381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    releaseWakeLock();
571481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
571581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    ALOGV("RecordThread %p exiting", this);
571681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return false;
571781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
571881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
571993e471f620454f7de73d190521568b1e25879767Glenn Kastenvoid AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
572081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
572181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (!mStandby) {
572281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        inputStandBy();
572381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mStandby = true;
572481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
572581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
572681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
572781784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::RecordThread::inputStandBy()
572881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
57296dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    // Idle the fast capture if it's currently running
57306dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    if (mFastCapture != 0) {
57316dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        FastCaptureStateQueue *sq = mFastCapture->sq();
57326dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        FastCaptureState *state = sq->begin();
57336dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        if (!(state->mCommand & FastCaptureState::IDLE)) {
57346dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            state->mCommand = FastCaptureState::COLD_IDLE;
57356dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            state->mColdFutexAddr = &mFastCaptureFutex;
57366dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            state->mColdGen++;
57376dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            mFastCaptureFutex = 0;
57386dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            sq->end();
57396dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
57406dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
57416dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten#if 0
57426dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            if (kUseFastCapture == FastCapture_Dynamic) {
57436dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                // FIXME
57446dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            }
57456dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten#endif
57466dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten#ifdef AUDIO_WATCHDOG
57476dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            // FIXME
57486dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten#endif
57496dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        } else {
57506dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            sq->end(false /*didModify*/);
57516dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        }
57526dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    }
575381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mInput->stream->common.standby(&mInput->stream->common);
575481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
575581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
575605997e21af6c4517f375def6563af4b9ebe95f39Glenn Kasten// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
5757e198c360d5e75a9b2097844c495c10902e7e8500Glenn Kastensp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
575881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        const sp<AudioFlinger::Client>& client,
575981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        uint32_t sampleRate,
576081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        audio_format_t format,
576181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        audio_channel_mask_t channelMask,
576274935e44734c1ec235c2b6677db3e0dbefa5ddb8Glenn Kasten        size_t *pFrameCount,
576381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        int sessionId,
57647df8c0b799d8f52d6386e03313286dbd7d5cdc7cGlenn Kasten        size_t *notificationFrames,
5765462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen        int uid,
5766ddb0ccf3fb6fe8da8c71a6deb30561b821f3c0a2Glenn Kasten        IAudioFlinger::track_flags_t *flags,
576781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        pid_t tid,
576881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        status_t *status)
576981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
577074935e44734c1ec235c2b6677db3e0dbefa5ddb8Glenn Kasten    size_t frameCount = *pFrameCount;
577181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    sp<RecordTrack> track;
577281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    status_t lStatus;
577381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
577490e58b1fefc8caf70b34301a92bc86179580b6fcGlenn Kasten    // client expresses a preference for FAST, but we get the final say
577590e58b1fefc8caf70b34301a92bc86179580b6fcGlenn Kasten    if (*flags & IAudioFlinger::TRACK_FAST) {
577690e58b1fefc8caf70b34301a92bc86179580b6fcGlenn Kasten      if (
5777b7fbf7ecc6b034243ec64f79f3113675b5e3c941Glenn Kasten            // we formerly checked for a callback handler (non-0 tid),
5778b7fbf7ecc6b034243ec64f79f3113675b5e3c941Glenn Kasten            // but that is no longer required for TRANSFER_OBTAIN mode
5779b7fbf7ecc6b034243ec64f79f3113675b5e3c941Glenn Kasten            //
57807410591dad836434c72ddee66680802708b70c10Glenn Kasten            // frame count is not specified, or is exactly the pipe depth
57817410591dad836434c72ddee66680802708b70c10Glenn Kasten            ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
57823a6c90aa0617666d9abc94c02b752d9eb3d64772Glenn Kasten            // PCM data
57833a6c90aa0617666d9abc94c02b752d9eb3d64772Glenn Kasten            audio_is_linear_pcm(format) &&
57846dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            // native format
57856dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            (format == mFormat) &&
57866dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            // native channel mask
57876dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            (channelMask == mChannelMask) &&
57886dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            // native hardware sample rate
578990e58b1fefc8caf70b34301a92bc86179580b6fcGlenn Kasten            (sampleRate == mSampleRate) &&
57903a6c90aa0617666d9abc94c02b752d9eb3d64772Glenn Kasten            // record thread has an associated fast capture
57916dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            hasFastCapture() &&
57926dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            // there are sufficient fast track slots available
57936dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten            mFastTrackAvail
579490e58b1fefc8caf70b34301a92bc86179580b6fcGlenn Kasten        ) {
57957410591dad836434c72ddee66680802708b70c10Glenn Kasten        ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u",
579690e58b1fefc8caf70b34301a92bc86179580b6fcGlenn Kasten                frameCount, mFrameCount);
579790e58b1fefc8caf70b34301a92bc86179580b6fcGlenn Kasten      } else {
57987410591dad836434c72ddee66680802708b70c10Glenn Kasten        ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u "
57997410591dad836434c72ddee66680802708b70c10Glenn Kasten                "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
58006dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten                "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
58017410591dad836434c72ddee66680802708b70c10Glenn Kasten                frameCount, mFrameCount, mPipeFramesP2,
58027410591dad836434c72ddee66680802708b70c10Glenn Kasten                format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
58037410591dad836434c72ddee66680802708b70c10Glenn Kasten                hasFastCapture(), tid, mFastTrackAvail);
580490e58b1fefc8caf70b34301a92bc86179580b6fcGlenn Kasten        *flags &= ~IAudioFlinger::TRACK_FAST;
58057410591dad836434c72ddee66680802708b70c10Glenn Kasten      }
58067410591dad836434c72ddee66680802708b70c10Glenn Kasten    }
58077410591dad836434c72ddee66680802708b70c10Glenn Kasten
58087410591dad836434c72ddee66680802708b70c10Glenn Kasten    // compute track buffer size in frames, and suggest the notification frame count
58097410591dad836434c72ddee66680802708b70c10Glenn Kasten    if (*flags & IAudioFlinger::TRACK_FAST) {
58107410591dad836434c72ddee66680802708b70c10Glenn Kasten        // fast track: frame count is exactly the pipe depth
58117410591dad836434c72ddee66680802708b70c10Glenn Kasten        frameCount = mPipeFramesP2;
58127410591dad836434c72ddee66680802708b70c10Glenn Kasten        // ignore requested notificationFrames, and always notify exactly once every HAL buffer
58137410591dad836434c72ddee66680802708b70c10Glenn Kasten        *notificationFrames = mFrameCount;
58147410591dad836434c72ddee66680802708b70c10Glenn Kasten    } else {
581549d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten        // not fast track: max notification period is resampled equivalent of one HAL buffer time
581649d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten        //                 or 20 ms if there is a fast capture
581749d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten        // TODO This could be a roundupRatio inline, and const
581849d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten        size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
581949d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten                * sampleRate + mSampleRate - 1) / mSampleRate;
582049d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten        // minimum number of notification periods is at least kMinNotifications,
582149d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten        // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
582249d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten        static const size_t kMinNotifications = 3;
582349d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten        static const uint32_t kMinMs = 30;
582449d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten        // TODO This could be a roundupRatio inline
582549d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten        const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
582649d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten        // TODO This could be a roundupRatio inline
582749d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten        const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
582849d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten                maxNotificationFrames;
582949d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten        const size_t minFrameCount = maxNotificationFrames *
583049d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten                max(kMinNotifications, minNotificationsByMs);
583149d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten        frameCount = max(frameCount, minFrameCount);
583249d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten        if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
583349d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten            *notificationFrames = maxNotificationFrames;
58347410591dad836434c72ddee66680802708b70c10Glenn Kasten        }
583590e58b1fefc8caf70b34301a92bc86179580b6fcGlenn Kasten    }
583674935e44734c1ec235c2b6677db3e0dbefa5ddb8Glenn Kasten    *pFrameCount = frameCount;
583790e58b1fefc8caf70b34301a92bc86179580b6fcGlenn Kasten
583815e5798908ccac14e10c84834eaf08c42931bd06Glenn Kasten    lStatus = initCheck();
583915e5798908ccac14e10c84834eaf08c42931bd06Glenn Kasten    if (lStatus != NO_ERROR) {
584015e5798908ccac14e10c84834eaf08c42931bd06Glenn Kasten        ALOGE("createRecordTrack_l() audio driver not initialized");
584115e5798908ccac14e10c84834eaf08c42931bd06Glenn Kasten        goto Exit;
584215e5798908ccac14e10c84834eaf08c42931bd06Glenn Kasten    }
584381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
584481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    { // scope for mLock
584581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        Mutex::Autolock _l(mLock);
584681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
584781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        track = new RecordTrack(this, client, sampleRate,
584883b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent                      format, channelMask, frameCount, NULL, sessionId, uid,
584983b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent                      *flags, TrackBase::TYPE_DEFAULT);
585081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
5851030033342a6ea17003e6af38a56c7edc6d2ead01Glenn Kasten        lStatus = track->initCheck();
5852030033342a6ea17003e6af38a56c7edc6d2ead01Glenn Kasten        if (lStatus != NO_ERROR) {
585335295078ab59c8c5d143a54d5a55557c3ca62c51Glenn Kasten            ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
585403e9e83c47ab4a518da0a1f36b8f702f59221c95Haynes Mathew George            // track must be cleared from the caller as the caller has the AF lock
585581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            goto Exit;
585681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
585781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mTracks.add(track);
585881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
585981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
586081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
586181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                        mAudioFlinger->btNrecIsOff();
586281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
586381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
586490e58b1fefc8caf70b34301a92bc86179580b6fcGlenn Kasten
586590e58b1fefc8caf70b34301a92bc86179580b6fcGlenn Kasten        if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
586690e58b1fefc8caf70b34301a92bc86179580b6fcGlenn Kasten            pid_t callingPid = IPCThreadState::self()->getCallingPid();
586790e58b1fefc8caf70b34301a92bc86179580b6fcGlenn Kasten            // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
586890e58b1fefc8caf70b34301a92bc86179580b6fcGlenn Kasten            // so ask activity manager to do this on our behalf
586990e58b1fefc8caf70b34301a92bc86179580b6fcGlenn Kasten            sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
587090e58b1fefc8caf70b34301a92bc86179580b6fcGlenn Kasten        }
587181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
587205997e21af6c4517f375def6563af4b9ebe95f39Glenn Kasten
587381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    lStatus = NO_ERROR;
587481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
587581784c37c61b09289654b979567a42bf73cd2b12Eric LaurentExit:
58769156ef3e11b68cc4b6d3cea77f1f63673855a6d1Glenn Kasten    *status = lStatus;
587781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return track;
587881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
587981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
588081784c37c61b09289654b979567a42bf73cd2b12Eric Laurentstatus_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
588181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                                           AudioSystem::sync_event_t event,
588281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                                           int triggerSession)
588381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
588481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
588581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    sp<ThreadBase> strongMe = this;
588681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    status_t status = NO_ERROR;
588781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
588881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (event == AudioSystem::SYNC_EVENT_NONE) {
588925f4aa83efaa9179e65a20583a6d441de2c3ff3fGlenn Kasten        recordTrack->clearSyncStartEvent();
589081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    } else if (event != AudioSystem::SYNC_EVENT_SAME) {
58916dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
589281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                                       triggerSession,
589381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                                       recordTrack->sessionId(),
589481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                                       syncStartEventCallback,
58956dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                                       recordTrack);
589681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // Sync event can be cancelled by the trigger session if the track is not in a
589781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // compatible state in which case we start record immediately
58986dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        if (recordTrack->mSyncStartEvent->isCancelled()) {
589925f4aa83efaa9179e65a20583a6d441de2c3ff3fGlenn Kasten            recordTrack->clearSyncStartEvent();
590081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        } else {
590181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
59026dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten            recordTrack->mFramesToDrop = -
59034cc0a6a835c806d200ef83ef31fe5bef327c355cGlenn Kasten                    ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
590481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
590581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
590681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
590781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    {
590847c2070b2ce8aedb7300c0aad91caccf3c383841Glenn Kasten        // This section is a rendezvous between binder thread executing start() and RecordThread
590981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        AutoMutex lock(mLock);
59106dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        if (mActiveTracks.indexOf(recordTrack) >= 0) {
59116dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten            if (recordTrack->mState == TrackBase::PAUSING) {
59126dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                ALOGV("active record track PAUSING -> ACTIVE");
5913f10ffec18f930d92e1abe9200d60e746831841a7Glenn Kasten                recordTrack->mState = TrackBase::ACTIVE;
59146dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten            } else {
59156dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten                ALOGV("active record track state %d", recordTrack->mState);
591681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
591781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            return status;
591881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
591981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
59204cc0a6a835c806d200ef83ef31fe5bef327c355cGlenn Kasten        // TODO consider other ways of handling this, such as changing the state to :STARTING and
59214cc0a6a835c806d200ef83ef31fe5bef327c355cGlenn Kasten        //      adding the track to mActiveTracks after returning from AudioSystem::startInput(),
59224cc0a6a835c806d200ef83ef31fe5bef327c355cGlenn Kasten        //      or using a separate command thread
59236dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        recordTrack->mState = TrackBase::STARTING_1;
59242b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten        mActiveTracks.add(recordTrack);
59252b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten        mActiveTracksGen++;
592683b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent        status_t status = NO_ERROR;
592783b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent        if (recordTrack->isExternalTrack()) {
592883b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent            mLock.unlock();
59294dc680607181e6a76f4e91a39366c4f5dfb7b03eEric Laurent            status = AudioSystem::startInput(mId, (audio_session_t)recordTrack->sessionId());
593083b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent            mLock.lock();
593183b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent            // FIXME should verify that recordTrack is still in mActiveTracks
593283b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent            if (status != NO_ERROR) {
593383b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent                mActiveTracks.remove(recordTrack);
593483b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent                mActiveTracksGen++;
593583b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent                recordTrack->clearSyncStartEvent();
593683b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent                ALOGV("RecordThread::start error %d", status);
593783b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent                return status;
593883b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent            }
593981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
59406dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        // Catch up with current buffer indices if thread is already running.
59416dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        // This is what makes a new client discard all buffered data.  If the track's mRsmpInFront
59426dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        // was initialized to some value closer to the thread's mRsmpInFront, then the track could
59436dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        // see previously buffered data before it called start(), but with greater risk of overrun.
59446dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten
59456dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        recordTrack->mRsmpInFront = mRsmpInRear;
59466dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        recordTrack->mRsmpInUnrel = 0;
594797a893eb34f8687485c88eaf15917974a203f20bAndy Hung        // clear any converter state as new data will be discontinuous
594897a893eb34f8687485c88eaf15917974a203f20bAndy Hung        recordTrack->mRecordBufferConverter->reset();
59496dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        recordTrack->mState = TrackBase::STARTING_2;
595081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        // signal thread to start
595181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mWaitWorkCV.broadcast();
59522b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten        if (mActiveTracks.indexOf(recordTrack) < 0) {
595381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            ALOGV("Record failed to start");
595481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            status = BAD_VALUE;
595581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            goto startError;
595681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
595781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        return status;
595881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
59597c027248e1a4ccd5b22bc4deafb03e2d87ac8f38Glenn Kasten
596081784c37c61b09289654b979567a42bf73cd2b12Eric LaurentstartError:
596183b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent    if (recordTrack->isExternalTrack()) {
59624dc680607181e6a76f4e91a39366c4f5dfb7b03eEric Laurent        AudioSystem::stopInput(mId, (audio_session_t)recordTrack->sessionId());
596383b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent    }
596425f4aa83efaa9179e65a20583a6d441de2c3ff3fGlenn Kasten    recordTrack->clearSyncStartEvent();
59656dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten    // FIXME I wonder why we do not reset the state here?
596681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return status;
596781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
596881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
596981784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
597081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
597181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    sp<SyncEvent> strongEvent = event.promote();
597281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
597381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (strongEvent != 0) {
59748ea16e4b0a7d398d26887c18675b3899de5d779dEric Laurent        sp<RefBase> ptr = strongEvent->cookie().promote();
59758ea16e4b0a7d398d26887c18675b3899de5d779dEric Laurent        if (ptr != 0) {
59768ea16e4b0a7d398d26887c18675b3899de5d779dEric Laurent            RecordTrack *recordTrack = (RecordTrack *)ptr.get();
59778ea16e4b0a7d398d26887c18675b3899de5d779dEric Laurent            recordTrack->handleSyncStartEvent(strongEvent);
59788ea16e4b0a7d398d26887c18675b3899de5d779dEric Laurent        }
597981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
598081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
598181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
5982a8356f663014e7d4c27869629af83d8bb3441e19Glenn Kastenbool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
598381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    ALOGV("RecordThread::stop");
5984a8356f663014e7d4c27869629af83d8bb3441e19Glenn Kasten    AutoMutex _l(mLock);
59852b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten    if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
598681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        return false;
598781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
598847c2070b2ce8aedb7300c0aad91caccf3c383841Glenn Kasten    // note that threadLoop may still be processing the track at this point [without lock]
598981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    recordTrack->mState = TrackBase::PAUSING;
599081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // do not wait for mStartStopCond if exiting
599181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (exitPending()) {
599281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        return true;
599381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
599447c2070b2ce8aedb7300c0aad91caccf3c383841Glenn Kasten    // FIXME incorrect usage of wait: no explicit predicate or loop
599581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mStartStopCond.wait(mLock);
59962b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten    // if we have been restarted, recordTrack is in mActiveTracks here
59972b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten    if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
599881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        ALOGV("Record stopped OK");
599981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        return true;
600081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
600181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return false;
600281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
600381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
60040f11b51a57bc9062c4fe8af73747319cedabc5d6Glenn Kastenbool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
600581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
600681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return false;
600781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
600881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
60090f11b51a57bc9062c4fe8af73747319cedabc5d6Glenn Kastenstatus_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
601081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
601181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#if 0   // This branch is currently dead code, but is preserved in case it will be needed in future
601281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (!isValidSyncEvent(event)) {
601381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        return BAD_VALUE;
601481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
601581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
601681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    int eventSession = event->triggerSession();
601781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    status_t ret = NAME_NOT_FOUND;
601881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
601981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
602081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
602181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    for (size_t i = 0; i < mTracks.size(); i++) {
602281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sp<RecordTrack> track = mTracks[i];
602381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (eventSession == track->sessionId()) {
602481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            (void) track->setSyncEvent(event);
602581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            ret = NO_ERROR;
602681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
602781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
602881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return ret;
602981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#else
603081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return BAD_VALUE;
603181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent#endif
603281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
603381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
603481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// destroyTrack_l() must be called with ThreadBase::mLock held
603581784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
603681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
6037bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    track->terminate();
6038bfb1b832079bbb9426f72f3863199a54aefd02daEric Laurent    track->mState = TrackBase::STOPPED;
603981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // active tracks are removed by threadLoop()
60402b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten    if (mActiveTracks.indexOf(track) < 0) {
604181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        removeTrack_l(track);
604281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
604381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
604481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
604581784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
604681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
604781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mTracks.remove(track);
604881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // need anything related to effects here?
60496dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    if (track->isFastTrack()) {
60506dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        ALOG_ASSERT(!mFastTrackAvail);
60516dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten        mFastTrackAvail = true;
60526dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    }
605381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
605481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
605581784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
605681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
605781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    dumpInternals(fd, args);
605881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    dumpTracks(fd, args);
605981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    dumpEffectChains(fd, args);
606081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
606181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
606281784c37c61b09289654b979567a42bf73cd2b12Eric Laurentvoid AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
606381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
606487cebadd48710e42474756fc3513df678de045ceElliott Hughes    dprintf(fd, "\nInput thread %p:\n", this);
606581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
606644182c206f7c5584ef2cf504da6be98fab665dbfGlenn Kasten    dumpBase(fd, args);
606744182c206f7c5584ef2cf504da6be98fab665dbfGlenn Kasten
606844182c206f7c5584ef2cf504da6be98fab665dbfGlenn Kasten    if (mActiveTracks.size() == 0) {
606987cebadd48710e42474756fc3513df678de045ceElliott Hughes        dprintf(fd, "  No active record clients\n");
607081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
60716e6704c06d61bc356e30c164081e5bcffb37920cGlenn Kasten    dprintf(fd, "  Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
60726dbb5e3336cfff1ad51d429fcb847307c06efd61Glenn Kasten    dprintf(fd, "  Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
607317c9c998afed5ed9df7495eeed5822f3ed53ebecGlenn Kasten
607417c9c998afed5ed9df7495eeed5822f3ed53ebecGlenn Kasten    //  Make a non-atomic copy of fast capture dump state so it won't change underneath us
607517c9c998afed5ed9df7495eeed5822f3ed53ebecGlenn Kasten    const FastCaptureDumpState copy(mFastCaptureDumpState);
607617c9c998afed5ed9df7495eeed5822f3ed53ebecGlenn Kasten    copy.dump(fd);
607781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
607881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
60790f11b51a57bc9062c4fe8af73747319cedabc5d6Glenn Kastenvoid AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
608081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
608181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    const size_t SIZE = 256;
608281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    char buffer[SIZE];
608381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    String8 result;
608481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
6085b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen    size_t numtracks = mTracks.size();
6086b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen    size_t numactive = mActiveTracks.size();
6087b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen    size_t numactiveseen = 0;
608887cebadd48710e42474756fc3513df678de045ceElliott Hughes    dprintf(fd, "  %d Tracks", numtracks);
6089b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen    if (numtracks) {
609087cebadd48710e42474756fc3513df678de045ceElliott Hughes        dprintf(fd, " of which %d are active\n", numactive);
6091b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        RecordTrack::appendDumpHeader(result);
6092b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        for (size_t i = 0; i < numtracks ; ++i) {
6093b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen            sp<RecordTrack> track = mTracks[i];
6094b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen            if (track != 0) {
6095b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen                bool active = mActiveTracks.indexOf(track) >= 0;
6096b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen                if (active) {
6097b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen                    numactiveseen++;
6098b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen                }
6099b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen                track->dump(buffer, SIZE, active);
6100b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen                result.append(buffer);
6101b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen            }
610281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
6103b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen    } else {
610487cebadd48710e42474756fc3513df678de045ceElliott Hughes        dprintf(fd, "\n");
610581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
610681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
6107b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen    if (numactiveseen != numactive) {
6108b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        snprintf(buffer, SIZE, "  The following tracks are in the active list but"
6109b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen                " not in the track list\n");
611081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        result.append(buffer);
611181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        RecordTrack::appendDumpHeader(result);
6112b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen        for (size_t i = 0; i < numactive; ++i) {
61132b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten            sp<RecordTrack> track = mActiveTracks[i];
6114b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen            if (mTracks.indexOf(track) < 0) {
6115b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen                track->dump(buffer, SIZE, true);
6116b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen                result.append(buffer);
6117b220884bf3129253cc5bc8d030bc475411ea4911Marco Nelissen            }
61182b806406ac1ec680b6fe3aaa84c54bdc4e43ad8dGlenn Kasten        }
611981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
612081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
612181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    write(fd, result.string(), result.size());
612281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
612381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
612481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// AudioBufferProvider interface
61256dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kastenstatus_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
61266dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
612781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
61286dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten    RecordTrack *activeTrack = mRecordTrack;
61296dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten    sp<ThreadBase> threadBase = activeTrack->mThread.promote();
61306dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten    if (threadBase == 0) {
61316dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        buffer->frameCount = 0;
6132607fa3e928de696eba49f198af72d68e4591ca1bGlenn Kasten        buffer->raw = NULL;
61336dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        return NOT_ENOUGH_DATA;
61346dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten    }
61356dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten    RecordThread *recordThread = (RecordThread *) threadBase.get();
61366dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten    int32_t rear = recordThread->mRsmpInRear;
61376dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten    int32_t front = activeTrack->mRsmpInFront;
61388594843c15b4722ced39436fe9e64f3e57e7ace4Glenn Kasten    ssize_t filled = rear - front;
61396dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten    // FIXME should not be P2 (don't want to increase latency)
61406dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten    // FIXME if client not keeping up, discard
6141607fa3e928de696eba49f198af72d68e4591ca1bGlenn Kasten    LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
61428594843c15b4722ced39436fe9e64f3e57e7ace4Glenn Kasten    // 'filled' may be non-contiguous, so return only the first contiguous chunk
61436dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten    front &= recordThread->mRsmpInFramesP2 - 1;
61446dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten    size_t part1 = recordThread->mRsmpInFramesP2 - front;
61458594843c15b4722ced39436fe9e64f3e57e7ace4Glenn Kasten    if (part1 > (size_t) filled) {
61468594843c15b4722ced39436fe9e64f3e57e7ace4Glenn Kasten        part1 = filled;
61478594843c15b4722ced39436fe9e64f3e57e7ace4Glenn Kasten    }
61488594843c15b4722ced39436fe9e64f3e57e7ace4Glenn Kasten    size_t ask = buffer->frameCount;
61498594843c15b4722ced39436fe9e64f3e57e7ace4Glenn Kasten    ALOG_ASSERT(ask > 0);
61508594843c15b4722ced39436fe9e64f3e57e7ace4Glenn Kasten    if (part1 > ask) {
61518594843c15b4722ced39436fe9e64f3e57e7ace4Glenn Kasten        part1 = ask;
61528594843c15b4722ced39436fe9e64f3e57e7ace4Glenn Kasten    }
61538594843c15b4722ced39436fe9e64f3e57e7ace4Glenn Kasten    if (part1 == 0) {
61548594843c15b4722ced39436fe9e64f3e57e7ace4Glenn Kasten        // Higher-level should keep mRsmpInBuffer full, and not call resampler if empty
6155607fa3e928de696eba49f198af72d68e4591ca1bGlenn Kasten        LOG_ALWAYS_FATAL("RecordThread::getNextBuffer() starved");
61568594843c15b4722ced39436fe9e64f3e57e7ace4Glenn Kasten        buffer->raw = NULL;
61578594843c15b4722ced39436fe9e64f3e57e7ace4Glenn Kasten        buffer->frameCount = 0;
61586dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        activeTrack->mRsmpInUnrel = 0;
61598594843c15b4722ced39436fe9e64f3e57e7ace4Glenn Kasten        return NOT_ENOUGH_DATA;
61608594843c15b4722ced39436fe9e64f3e57e7ace4Glenn Kasten    }
61618594843c15b4722ced39436fe9e64f3e57e7ace4Glenn Kasten
61626dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten    buffer->raw = recordThread->mRsmpInBuffer + front * recordThread->mChannelCount;
61638594843c15b4722ced39436fe9e64f3e57e7ace4Glenn Kasten    buffer->frameCount = part1;
61646dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten    activeTrack->mRsmpInUnrel = part1;
616581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return NO_ERROR;
616681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
616781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
616881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// AudioBufferProvider interface
61696dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kastenvoid AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
61706dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten        AudioBufferProvider::Buffer* buffer)
617181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
61726dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten    RecordTrack *activeTrack = mRecordTrack;
61738594843c15b4722ced39436fe9e64f3e57e7ace4Glenn Kasten    size_t stepCount = buffer->frameCount;
61748594843c15b4722ced39436fe9e64f3e57e7ace4Glenn Kasten    if (stepCount == 0) {
61758594843c15b4722ced39436fe9e64f3e57e7ace4Glenn Kasten        return;
61768594843c15b4722ced39436fe9e64f3e57e7ace4Glenn Kasten    }
61776dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten    ALOG_ASSERT(stepCount <= activeTrack->mRsmpInUnrel);
61786dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten    activeTrack->mRsmpInUnrel -= stepCount;
61796dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten    activeTrack->mRsmpInFront += stepCount;
61808594843c15b4722ced39436fe9e64f3e57e7ace4Glenn Kasten    buffer->raw = NULL;
618181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    buffer->frameCount = 0;
618281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
618381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
618497a893eb34f8687485c88eaf15917974a203f20bAndy HungAudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
618597a893eb34f8687485c88eaf15917974a203f20bAndy Hung        audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
618697a893eb34f8687485c88eaf15917974a203f20bAndy Hung        uint32_t srcSampleRate,
618797a893eb34f8687485c88eaf15917974a203f20bAndy Hung        audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
618897a893eb34f8687485c88eaf15917974a203f20bAndy Hung        uint32_t dstSampleRate) :
618997a893eb34f8687485c88eaf15917974a203f20bAndy Hung            mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
619097a893eb34f8687485c88eaf15917974a203f20bAndy Hung            // mSrcFormat
619197a893eb34f8687485c88eaf15917974a203f20bAndy Hung            // mSrcSampleRate
619297a893eb34f8687485c88eaf15917974a203f20bAndy Hung            // mDstChannelMask
619397a893eb34f8687485c88eaf15917974a203f20bAndy Hung            // mDstFormat
619497a893eb34f8687485c88eaf15917974a203f20bAndy Hung            // mDstSampleRate
619597a893eb34f8687485c88eaf15917974a203f20bAndy Hung            // mSrcChannelCount
619697a893eb34f8687485c88eaf15917974a203f20bAndy Hung            // mDstChannelCount
619797a893eb34f8687485c88eaf15917974a203f20bAndy Hung            // mDstFrameSize
619897a893eb34f8687485c88eaf15917974a203f20bAndy Hung            mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
619997a893eb34f8687485c88eaf15917974a203f20bAndy Hung            mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpOutFrameCount(0)
620097a893eb34f8687485c88eaf15917974a203f20bAndy Hung{
620197a893eb34f8687485c88eaf15917974a203f20bAndy Hung    (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
620297a893eb34f8687485c88eaf15917974a203f20bAndy Hung            dstChannelMask, dstFormat, dstSampleRate);
620397a893eb34f8687485c88eaf15917974a203f20bAndy Hung}
620497a893eb34f8687485c88eaf15917974a203f20bAndy Hung
620597a893eb34f8687485c88eaf15917974a203f20bAndy HungAudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
620697a893eb34f8687485c88eaf15917974a203f20bAndy Hung    free(mBuf);
620797a893eb34f8687485c88eaf15917974a203f20bAndy Hung    delete mResampler;
620897a893eb34f8687485c88eaf15917974a203f20bAndy Hung    free(mRsmpOutBuffer);
620997a893eb34f8687485c88eaf15917974a203f20bAndy Hung}
621097a893eb34f8687485c88eaf15917974a203f20bAndy Hung
621197a893eb34f8687485c88eaf15917974a203f20bAndy Hungsize_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
621297a893eb34f8687485c88eaf15917974a203f20bAndy Hung        AudioBufferProvider *provider, size_t frames)
621397a893eb34f8687485c88eaf15917974a203f20bAndy Hung{
621497a893eb34f8687485c88eaf15917974a203f20bAndy Hung    if (mSrcSampleRate == mDstSampleRate) {
621597a893eb34f8687485c88eaf15917974a203f20bAndy Hung        ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
621697a893eb34f8687485c88eaf15917974a203f20bAndy Hung                mSrcSampleRate, mSrcFormat, mDstFormat);
621797a893eb34f8687485c88eaf15917974a203f20bAndy Hung
621897a893eb34f8687485c88eaf15917974a203f20bAndy Hung        AudioBufferProvider::Buffer buffer;
621997a893eb34f8687485c88eaf15917974a203f20bAndy Hung        for (size_t i = frames; i > 0; ) {
622097a893eb34f8687485c88eaf15917974a203f20bAndy Hung            buffer.frameCount = i;
622197a893eb34f8687485c88eaf15917974a203f20bAndy Hung            status_t status = provider->getNextBuffer(&buffer, 0);
622297a893eb34f8687485c88eaf15917974a203f20bAndy Hung            if (status != OK || buffer.frameCount == 0) {
622397a893eb34f8687485c88eaf15917974a203f20bAndy Hung                frames -= i; // cannot fill request.
622497a893eb34f8687485c88eaf15917974a203f20bAndy Hung                break;
622597a893eb34f8687485c88eaf15917974a203f20bAndy Hung            }
622697a893eb34f8687485c88eaf15917974a203f20bAndy Hung            // convert to destination buffer
622797a893eb34f8687485c88eaf15917974a203f20bAndy Hung            convert(dst, buffer.raw, buffer.frameCount);
622897a893eb34f8687485c88eaf15917974a203f20bAndy Hung
622997a893eb34f8687485c88eaf15917974a203f20bAndy Hung            dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
623097a893eb34f8687485c88eaf15917974a203f20bAndy Hung            i -= buffer.frameCount;
623197a893eb34f8687485c88eaf15917974a203f20bAndy Hung            provider->releaseBuffer(&buffer);
623297a893eb34f8687485c88eaf15917974a203f20bAndy Hung        }
623397a893eb34f8687485c88eaf15917974a203f20bAndy Hung    } else {
623497a893eb34f8687485c88eaf15917974a203f20bAndy Hung         ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
623597a893eb34f8687485c88eaf15917974a203f20bAndy Hung                 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
623697a893eb34f8687485c88eaf15917974a203f20bAndy Hung
623797a893eb34f8687485c88eaf15917974a203f20bAndy Hung        // reallocate mRsmpOutBuffer as needed; we will grow but never shrink
623897a893eb34f8687485c88eaf15917974a203f20bAndy Hung        if (mRsmpOutFrameCount < frames) {
623997a893eb34f8687485c88eaf15917974a203f20bAndy Hung            // FIXME why does each track need it's own mRsmpOutBuffer? can't they share?
624097a893eb34f8687485c88eaf15917974a203f20bAndy Hung            free(mRsmpOutBuffer);
624197a893eb34f8687485c88eaf15917974a203f20bAndy Hung            // resampler always outputs stereo (FOR NOW)
624297a893eb34f8687485c88eaf15917974a203f20bAndy Hung            (void)posix_memalign(&mRsmpOutBuffer, 32, frames * FCC_2 * sizeof(int32_t) /*Q4.27*/);
624397a893eb34f8687485c88eaf15917974a203f20bAndy Hung            mRsmpOutFrameCount = frames;
624497a893eb34f8687485c88eaf15917974a203f20bAndy Hung        }
624597a893eb34f8687485c88eaf15917974a203f20bAndy Hung        // resampler accumulates, but we only have one source track
624697a893eb34f8687485c88eaf15917974a203f20bAndy Hung        memset(mRsmpOutBuffer, 0, frames * FCC_2 * sizeof(int32_t));
624797a893eb34f8687485c88eaf15917974a203f20bAndy Hung        frames = mResampler->resample((int32_t*)mRsmpOutBuffer, frames, provider);
624897a893eb34f8687485c88eaf15917974a203f20bAndy Hung
624997a893eb34f8687485c88eaf15917974a203f20bAndy Hung        // convert to destination buffer
625097a893eb34f8687485c88eaf15917974a203f20bAndy Hung        convert(dst, mRsmpOutBuffer, frames);
625197a893eb34f8687485c88eaf15917974a203f20bAndy Hung    }
625297a893eb34f8687485c88eaf15917974a203f20bAndy Hung    return frames;
625397a893eb34f8687485c88eaf15917974a203f20bAndy Hung}
625497a893eb34f8687485c88eaf15917974a203f20bAndy Hung
625597a893eb34f8687485c88eaf15917974a203f20bAndy Hungstatus_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
625697a893eb34f8687485c88eaf15917974a203f20bAndy Hung        audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
625797a893eb34f8687485c88eaf15917974a203f20bAndy Hung        uint32_t srcSampleRate,
625897a893eb34f8687485c88eaf15917974a203f20bAndy Hung        audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
625997a893eb34f8687485c88eaf15917974a203f20bAndy Hung        uint32_t dstSampleRate)
626097a893eb34f8687485c88eaf15917974a203f20bAndy Hung{
626197a893eb34f8687485c88eaf15917974a203f20bAndy Hung    // quick evaluation if there is any change.
626297a893eb34f8687485c88eaf15917974a203f20bAndy Hung    if (mSrcFormat == srcFormat
626397a893eb34f8687485c88eaf15917974a203f20bAndy Hung            && mSrcChannelMask == srcChannelMask
626497a893eb34f8687485c88eaf15917974a203f20bAndy Hung            && mSrcSampleRate == srcSampleRate
626597a893eb34f8687485c88eaf15917974a203f20bAndy Hung            && mDstFormat == dstFormat
626697a893eb34f8687485c88eaf15917974a203f20bAndy Hung            && mDstChannelMask == dstChannelMask
626797a893eb34f8687485c88eaf15917974a203f20bAndy Hung            && mDstSampleRate == dstSampleRate) {
626897a893eb34f8687485c88eaf15917974a203f20bAndy Hung        return NO_ERROR;
626997a893eb34f8687485c88eaf15917974a203f20bAndy Hung    }
627097a893eb34f8687485c88eaf15917974a203f20bAndy Hung
627197a893eb34f8687485c88eaf15917974a203f20bAndy Hung    const bool valid =
627297a893eb34f8687485c88eaf15917974a203f20bAndy Hung            audio_is_input_channel(srcChannelMask)
627397a893eb34f8687485c88eaf15917974a203f20bAndy Hung            && audio_is_input_channel(dstChannelMask)
627497a893eb34f8687485c88eaf15917974a203f20bAndy Hung            && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
627597a893eb34f8687485c88eaf15917974a203f20bAndy Hung            && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
627697a893eb34f8687485c88eaf15917974a203f20bAndy Hung            && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
627797a893eb34f8687485c88eaf15917974a203f20bAndy Hung            ; // no upsampling checks for now
627897a893eb34f8687485c88eaf15917974a203f20bAndy Hung    if (!valid) {
627997a893eb34f8687485c88eaf15917974a203f20bAndy Hung        return BAD_VALUE;
628097a893eb34f8687485c88eaf15917974a203f20bAndy Hung    }
628197a893eb34f8687485c88eaf15917974a203f20bAndy Hung
628297a893eb34f8687485c88eaf15917974a203f20bAndy Hung    mSrcFormat = srcFormat;
628397a893eb34f8687485c88eaf15917974a203f20bAndy Hung    mSrcChannelMask = srcChannelMask;
628497a893eb34f8687485c88eaf15917974a203f20bAndy Hung    mSrcSampleRate = srcSampleRate;
628597a893eb34f8687485c88eaf15917974a203f20bAndy Hung    mDstFormat = dstFormat;
628697a893eb34f8687485c88eaf15917974a203f20bAndy Hung    mDstChannelMask = dstChannelMask;
628797a893eb34f8687485c88eaf15917974a203f20bAndy Hung    mDstSampleRate = dstSampleRate;
628897a893eb34f8687485c88eaf15917974a203f20bAndy Hung
628997a893eb34f8687485c88eaf15917974a203f20bAndy Hung    // compute derived parameters
629097a893eb34f8687485c88eaf15917974a203f20bAndy Hung    mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
629197a893eb34f8687485c88eaf15917974a203f20bAndy Hung    mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
629297a893eb34f8687485c88eaf15917974a203f20bAndy Hung    mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
629397a893eb34f8687485c88eaf15917974a203f20bAndy Hung
629497a893eb34f8687485c88eaf15917974a203f20bAndy Hung    // do we need a format buffer?
629597a893eb34f8687485c88eaf15917974a203f20bAndy Hung    if (mSrcFormat != mDstFormat && mDstChannelCount != mSrcChannelCount) {
629697a893eb34f8687485c88eaf15917974a203f20bAndy Hung        mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
629797a893eb34f8687485c88eaf15917974a203f20bAndy Hung    } else {
629897a893eb34f8687485c88eaf15917974a203f20bAndy Hung        mBufFrameSize = 0;
629997a893eb34f8687485c88eaf15917974a203f20bAndy Hung    }
630097a893eb34f8687485c88eaf15917974a203f20bAndy Hung    mBufFrames = 0; // force the buffer to be resized.
630197a893eb34f8687485c88eaf15917974a203f20bAndy Hung
630297a893eb34f8687485c88eaf15917974a203f20bAndy Hung    // do we need to resample?
630397a893eb34f8687485c88eaf15917974a203f20bAndy Hung    if (mSrcSampleRate != mDstSampleRate) {
630497a893eb34f8687485c88eaf15917974a203f20bAndy Hung        if (mResampler != NULL) {
630597a893eb34f8687485c88eaf15917974a203f20bAndy Hung            delete mResampler;
630697a893eb34f8687485c88eaf15917974a203f20bAndy Hung        }
630797a893eb34f8687485c88eaf15917974a203f20bAndy Hung        mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_16_BIT,
630897a893eb34f8687485c88eaf15917974a203f20bAndy Hung                mSrcChannelCount, mDstSampleRate); // may seem confusing...
630997a893eb34f8687485c88eaf15917974a203f20bAndy Hung        mResampler->setSampleRate(mSrcSampleRate);
631097a893eb34f8687485c88eaf15917974a203f20bAndy Hung        mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
631197a893eb34f8687485c88eaf15917974a203f20bAndy Hung    }
631297a893eb34f8687485c88eaf15917974a203f20bAndy Hung    return NO_ERROR;
631397a893eb34f8687485c88eaf15917974a203f20bAndy Hung}
631497a893eb34f8687485c88eaf15917974a203f20bAndy Hung
631597a893eb34f8687485c88eaf15917974a203f20bAndy Hungvoid AudioFlinger::RecordThread::RecordBufferConverter::convert(
631697a893eb34f8687485c88eaf15917974a203f20bAndy Hung        void *dst, /*const*/ void *src, size_t frames)
631797a893eb34f8687485c88eaf15917974a203f20bAndy Hung{
631897a893eb34f8687485c88eaf15917974a203f20bAndy Hung    // check if a memcpy will do
631997a893eb34f8687485c88eaf15917974a203f20bAndy Hung    if (mResampler == NULL
632097a893eb34f8687485c88eaf15917974a203f20bAndy Hung            && mSrcChannelCount == mDstChannelCount
632197a893eb34f8687485c88eaf15917974a203f20bAndy Hung            && mSrcFormat == mDstFormat) {
632297a893eb34f8687485c88eaf15917974a203f20bAndy Hung        memcpy(dst, src,
632397a893eb34f8687485c88eaf15917974a203f20bAndy Hung                frames * mDstChannelCount * audio_bytes_per_sample(mDstFormat));
632497a893eb34f8687485c88eaf15917974a203f20bAndy Hung        return;
632597a893eb34f8687485c88eaf15917974a203f20bAndy Hung    }
632697a893eb34f8687485c88eaf15917974a203f20bAndy Hung    // reallocate buffer if needed
632797a893eb34f8687485c88eaf15917974a203f20bAndy Hung    if (mBufFrameSize != 0 && mBufFrames < frames) {
632897a893eb34f8687485c88eaf15917974a203f20bAndy Hung        free(mBuf);
632997a893eb34f8687485c88eaf15917974a203f20bAndy Hung        mBufFrames = frames;
633097a893eb34f8687485c88eaf15917974a203f20bAndy Hung        (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
633197a893eb34f8687485c88eaf15917974a203f20bAndy Hung    }
633297a893eb34f8687485c88eaf15917974a203f20bAndy Hung    // do processing
633397a893eb34f8687485c88eaf15917974a203f20bAndy Hung    if (mResampler != NULL) {
633497a893eb34f8687485c88eaf15917974a203f20bAndy Hung        // src channel count is always >= 2.
633597a893eb34f8687485c88eaf15917974a203f20bAndy Hung        void *dstBuf = mBuf != NULL ? mBuf : dst;
633697a893eb34f8687485c88eaf15917974a203f20bAndy Hung        // ditherAndClamp() works as long as all buffers returned by
633797a893eb34f8687485c88eaf15917974a203f20bAndy Hung        // activeTrack->getNextBuffer() are 32 bit aligned which should be always true.
633897a893eb34f8687485c88eaf15917974a203f20bAndy Hung        if (mDstChannelCount == 1) {
633997a893eb34f8687485c88eaf15917974a203f20bAndy Hung            // the resampler always outputs stereo samples.
634097a893eb34f8687485c88eaf15917974a203f20bAndy Hung            // FIXME: this rewrites back into src
634197a893eb34f8687485c88eaf15917974a203f20bAndy Hung            ditherAndClamp((int32_t *)src, (const int32_t *)src, frames);
634297a893eb34f8687485c88eaf15917974a203f20bAndy Hung            downmix_to_mono_i16_from_stereo_i16((int16_t *)dstBuf,
634397a893eb34f8687485c88eaf15917974a203f20bAndy Hung                    (const int16_t *)src, frames);
634497a893eb34f8687485c88eaf15917974a203f20bAndy Hung        } else {
634597a893eb34f8687485c88eaf15917974a203f20bAndy Hung            ditherAndClamp((int32_t *)dstBuf, (const int32_t *)src, frames);
634697a893eb34f8687485c88eaf15917974a203f20bAndy Hung        }
634797a893eb34f8687485c88eaf15917974a203f20bAndy Hung    } else if (mSrcChannelCount != mDstChannelCount) {
634897a893eb34f8687485c88eaf15917974a203f20bAndy Hung        void *dstBuf = mBuf != NULL ? mBuf : dst;
634997a893eb34f8687485c88eaf15917974a203f20bAndy Hung        if (mSrcChannelCount == 1) {
635097a893eb34f8687485c88eaf15917974a203f20bAndy Hung            upmix_to_stereo_i16_from_mono_i16((int16_t *)dstBuf, (const int16_t *)src,
635197a893eb34f8687485c88eaf15917974a203f20bAndy Hung                    frames);
635297a893eb34f8687485c88eaf15917974a203f20bAndy Hung        } else {
635397a893eb34f8687485c88eaf15917974a203f20bAndy Hung            downmix_to_mono_i16_from_stereo_i16((int16_t *)dstBuf,
635497a893eb34f8687485c88eaf15917974a203f20bAndy Hung                    (const int16_t *)src, frames);
635597a893eb34f8687485c88eaf15917974a203f20bAndy Hung        }
635697a893eb34f8687485c88eaf15917974a203f20bAndy Hung    }
635797a893eb34f8687485c88eaf15917974a203f20bAndy Hung    if (mSrcFormat != mDstFormat) {
635897a893eb34f8687485c88eaf15917974a203f20bAndy Hung        void *srcBuf = mBuf != NULL ? mBuf : src;
635997a893eb34f8687485c88eaf15917974a203f20bAndy Hung        memcpy_by_audio_format(dst, mDstFormat, srcBuf, mSrcFormat,
636097a893eb34f8687485c88eaf15917974a203f20bAndy Hung                frames * mDstChannelCount);
636197a893eb34f8687485c88eaf15917974a203f20bAndy Hung    }
636297a893eb34f8687485c88eaf15917974a203f20bAndy Hung}
636397a893eb34f8687485c88eaf15917974a203f20bAndy Hung
63641035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurentbool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
63651035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                                                        status_t& status)
636681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
636781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    bool reconfig = false;
636881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
63691035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    status = NO_ERROR;
63701035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent
63711035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    audio_format_t reqFormat = mFormat;
63721035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    uint32_t samplingRate = mSampleRate;
63731035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
63741035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent
63751035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    AudioParameter param = AudioParameter(keyValuePair);
63761035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    int value;
63771035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    // TODO Investigate when this code runs. Check with audio policy when a sample rate and
63781035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    //      channel count change can be requested. Do we mandate the first client defines the
63791035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    //      HAL sampling rate and channel count or do we allow changes on the fly?
63801035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
63811035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        samplingRate = value;
63821035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        reconfig = true;
63831035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    }
63841035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
638597a893eb34f8687485c88eaf15917974a203f20bAndy Hung        if (!audio_is_linear_pcm((audio_format_t) value)) {
63861035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            status = BAD_VALUE;
63871035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        } else {
63881035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            reqFormat = (audio_format_t) value;
638981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            reconfig = true;
639081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
63911035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    }
63921035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
63931035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        audio_channel_mask_t mask = (audio_channel_mask_t) value;
63941035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        if (mask != AUDIO_CHANNEL_IN_MONO && mask != AUDIO_CHANNEL_IN_STEREO) {
63951035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            status = BAD_VALUE;
63961035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        } else {
63971035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            channelMask = mask;
63981035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            reconfig = true;
639981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
64001035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    }
64011035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
64021035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        // do not accept frame count changes if tracks are open as the track buffer
64031035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        // size depends on frame count and correct behavior would not be guaranteed
64041035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        // if frame count is changed after track creation
64051035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        if (mActiveTracks.size() > 0) {
64061035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            status = INVALID_OPERATION;
64071035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        } else {
64081035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            reconfig = true;
640981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
64101035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    }
64111035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
64121035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        // forward device change to effects that have requested to be
64131035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        // aware of attached audio device.
64141035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        for (size_t i = 0; i < mEffectChains.size(); i++) {
64151035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            mEffectChains[i]->setDevice_l(value);
641681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
641781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
64181035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        // store input device and output device but do not forward output device to audio HAL.
64191035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        // Note that status is ignored by the caller for output device
64201035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        // (see AudioFlinger::setParameters()
64211035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        if (audio_is_output_devices(value)) {
64221035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            mOutDevice = value;
64231035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            status = BAD_VALUE;
64241035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        } else {
64251035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            mInDevice = value;
64261035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            // disable AEC and NS if the device is a BT SCO headset supporting those
64271035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            // pre processings
64281035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            if (mTracks.size() > 0) {
64291035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
64301035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                                    mAudioFlinger->btNrecIsOff();
64311035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                for (size_t i = 0; i < mTracks.size(); i++) {
64321035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                    sp<RecordTrack> track = mTracks[i];
64331035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                    setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
64341035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                    setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
643581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                }
643681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
643781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
64381035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    }
64391035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
64401035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            mAudioSource != (audio_source_t)value) {
64411035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        // forward device change to effects that have requested to be
64421035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        // aware of attached audio device.
64431035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        for (size_t i = 0; i < mEffectChains.size(); i++) {
64441035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            mEffectChains[i]->setAudioSource_l((audio_source_t)value);
644581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
64461035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        mAudioSource = (audio_source_t)value;
64471035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    }
6448e198c360d5e75a9b2097844c495c10902e7e8500Glenn Kasten
64491035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent    if (status == NO_ERROR) {
64501035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        status = mInput->stream->common.set_parameters(&mInput->stream->common,
64511035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                keyValuePair.string());
64521035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        if (status == INVALID_OPERATION) {
64531035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            inputStandBy();
645481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            status = mInput->stream->common.set_parameters(&mInput->stream->common,
645581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent                    keyValuePair.string());
64561035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        }
64571035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent        if (reconfig) {
64581035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            if (status == BAD_VALUE &&
645997a893eb34f8687485c88eaf15917974a203f20bAndy Hung                audio_is_linear_pcm(mInput->stream->common.get_format(&mInput->stream->common)) &&
646097a893eb34f8687485c88eaf15917974a203f20bAndy Hung                audio_is_linear_pcm(reqFormat) &&
64611035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                (mInput->stream->common.get_sample_rate(&mInput->stream->common)
646297a893eb34f8687485c88eaf15917974a203f20bAndy Hung                        <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate)) &&
6463e541269be94f3a1072932d51537905b120ef4733Andy Hung                audio_channel_count_from_in_mask(
6464e541269be94f3a1072932d51537905b120ef4733Andy Hung                        mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
64651035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                (channelMask == AUDIO_CHANNEL_IN_MONO ||
64661035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                        channelMask == AUDIO_CHANNEL_IN_STEREO)) {
64671035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                status = NO_ERROR;
646881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
64691035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent            if (status == NO_ERROR) {
64701035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                readInputParameters_l();
64711035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent                sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
647281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            }
647381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
647481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
64751035194cee4fbd57e35ea15c56e66cd09b63d56eEric Laurent
647681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return reconfig;
647781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
647881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
647981784c37c61b09289654b979567a42bf73cd2b12Eric LaurentString8 AudioFlinger::RecordThread::getParameters(const String8& keys)
648081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
648181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
648281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (initCheck() != NO_ERROR) {
6483d8ea699dc8e7dac58bb32e9cdb31b0758da25817Glenn Kasten        return String8();
648481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
648581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
6486d8ea699dc8e7dac58bb32e9cdb31b0758da25817Glenn Kasten    char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
6487d8ea699dc8e7dac58bb32e9cdb31b0758da25817Glenn Kasten    const String8 out_s8(s);
648881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    free(s);
648981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return out_s8;
649081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
649181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
6492021cf9634ab09c0753a40b7c9ef4ba603be5c3daEric Laurentvoid AudioFlinger::RecordThread::audioConfigChanged(int event, int param __unused) {
649381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    AudioSystem::OutputDescriptor desc;
6494b2737d0b33c17e408d96d6f9eeaa3381479c94c7Glenn Kasten    const void *param2 = NULL;
649581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
649681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    switch (event) {
649781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    case AudioSystem::INPUT_OPENED:
649881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    case AudioSystem::INPUT_CONFIG_CHANGED:
6499fad226abd12435dbcd232f7de396f1a097b2bd5fGlenn Kasten        desc.channelMask = mChannelMask;
650081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        desc.samplingRate = mSampleRate;
650181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        desc.format = mFormat;
650281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        desc.frameCount = mFrameCount;
650381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        desc.latency = 0;
650481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        param2 = &desc;
650581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        break;
650681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
650781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    case AudioSystem::INPUT_CLOSED:
650881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    default:
650981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        break;
651081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
6511021cf9634ab09c0753a40b7c9ef4ba603be5c3daEric Laurent    mAudioFlinger->audioConfigChanged(event, mId, param2);
651281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
651381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
6514deca2ae0a7cf8bc54ff3f30b7dc39bbc78b94c0dGlenn Kastenvoid AudioFlinger::RecordThread::readInputParameters_l()
651581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
651681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
651781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
6518e541269be94f3a1072932d51537905b120ef4733Andy Hung    mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
6519463be250de73907965faa6a216c00312bf81e049Andy Hung    mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
6520463be250de73907965faa6a216c00312bf81e049Andy Hung    mFormat = mHALFormat;
6521291bb6d8947c5b0c062f0895d623c529259bfa39Glenn Kasten    if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
6522cac3daa6332bf6d1f7d26adc4a9915f3d7992dd9Glenn Kasten        ALOGE("HAL format %#x not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
6523291bb6d8947c5b0c062f0895d623c529259bfa39Glenn Kasten    }
6524665470b36f202bcc8ee2f7417f68fd2608dd07c1Eric Laurent    mFrameSize = audio_stream_in_frame_size(mInput->stream);
6525548efc94813c1dec6e8cf6c085ae41ccb04827f1Glenn Kasten    mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
6526548efc94813c1dec6e8cf6c085ae41ccb04827f1Glenn Kasten    mFrameCount = mBufferSize / mFrameSize;
65276dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten    // This is the formula for calculating the temporary buffer size.
6528e842614837e5401adf77e90485300c288b9a7876Glenn Kasten    // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
65298594843c15b4722ced39436fe9e64f3e57e7ace4Glenn Kasten    // 1 full output buffer, regardless of the alignment of the available input.
6530e842614837e5401adf77e90485300c288b9a7876Glenn Kasten    // The value is somewhat arbitrary, and could probably be even larger.
65316dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten    // A larger value should allow more old data to be read after a track calls start(),
65326dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten    // without increasing latency.
653397a893eb34f8687485c88eaf15917974a203f20bAndy Hung    //
653497a893eb34f8687485c88eaf15917974a203f20bAndy Hung    // Note this is independent of the maximum downsampling ratio permitted for capture.
6535e842614837e5401adf77e90485300c288b9a7876Glenn Kasten    mRsmpInFrames = mFrameCount * 7;
65368594843c15b4722ced39436fe9e64f3e57e7ace4Glenn Kasten    mRsmpInFramesP2 = roundup(mRsmpInFrames);
65376dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten    delete[] mRsmpInBuffer;
653849d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten
653949d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten    // TODO optimize audio capture buffer sizes ...
654049d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten    // Here we calculate the size of the sliding buffer used as a source
654149d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten    // for resampling.  mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
654249d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten    // For current HAL frame counts, this is usually 2048 = 40 ms.  It would
654349d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten    // be better to have it derived from the pipe depth in the long term.
654449d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten    // The current value is higher than necessary.  However it should not add to latency.
654549d00ad9164ea5ce48c85765a2b6460d9b457d38Glenn Kasten
65468594843c15b4722ced39436fe9e64f3e57e7ace4Glenn Kasten    // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
65478594843c15b4722ced39436fe9e64f3e57e7ace4Glenn Kasten    mRsmpInBuffer = new int16_t[(mRsmpInFramesP2 + mFrameCount - 1) * mChannelCount];
65486dd62fb91d82dedcfa3ab38c02eb0940b4ba932aGlenn Kasten
65494cc0a6a835c806d200ef83ef31fe5bef327c355cGlenn Kasten    // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
65504cc0a6a835c806d200ef83ef31fe5bef327c355cGlenn Kasten    // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
655181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
655281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
65535f972c031d4061f4f037c9fda1ea4bd9b6a756cdGlenn Kastenuint32_t AudioFlinger::RecordThread::getInputFramesLost()
655481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
655581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
655681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (initCheck() != NO_ERROR) {
655781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        return 0;
655881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
655981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
656081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return mInput->stream->get_input_frames_lost(mInput->stream);
656181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
656281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
656381784c37c61b09289654b979567a42bf73cd2b12Eric Laurentuint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
656481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
656581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
656681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    uint32_t result = 0;
656781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (getEffectChain_l(sessionId) != 0) {
656881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        result = EFFECT_SESSION;
656981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
657081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
657181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    for (size_t i = 0; i < mTracks.size(); ++i) {
657281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (sessionId == mTracks[i]->sessionId()) {
657381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            result |= TRACK_SESSION;
657481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            break;
657581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
657681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
657781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
657881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return result;
657981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
658081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
658181784c37c61b09289654b979567a42bf73cd2b12Eric LaurentKeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
658281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
658381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    KeyedVector<int, bool> ids;
658481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
658581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    for (size_t j = 0; j < mTracks.size(); ++j) {
658681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        sp<RecordThread::RecordTrack> track = mTracks[j];
658781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        int sessionId = track->sessionId();
658881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        if (ids.indexOfKey(sessionId) < 0) {
658981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            ids.add(sessionId, true);
659081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        }
659181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
659281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return ids;
659381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
659481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
659581784c37c61b09289654b979567a42bf73cd2b12Eric LaurentAudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
659681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
659781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    Mutex::Autolock _l(mLock);
659881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    AudioStreamIn *input = mInput;
659981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mInput = NULL;
660081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return input;
660181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
660281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
660381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent// this method must always be called either with ThreadBase mLock held or inside the thread loop
660481784c37c61b09289654b979567a42bf73cd2b12Eric Laurentaudio_stream_t* AudioFlinger::RecordThread::stream() const
660581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
660681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (mInput == NULL) {
660781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        return NULL;
660881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
660981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return &mInput->stream->common;
661081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
661181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
661281784c37c61b09289654b979567a42bf73cd2b12Eric Laurentstatus_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
661381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
661481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    // only one chain per input thread
661581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (mEffectChains.size() != 0) {
6616aaa44478a373232d8416657035a9020f9c7aa7c3Eric Laurent        ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
661781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        return INVALID_OPERATION;
661881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
661981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
6620aaa44478a373232d8416657035a9020f9c7aa7c3Eric Laurent    chain->setThread(this);
662181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    chain->setInBuffer(NULL);
662281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    chain->setOutBuffer(NULL);
662381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
662481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    checkSuspendOnAddEffectChain_l(chain);
662581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
66261b92868010b5c1409692a86f6b27e4a265b64c1aEric Laurent    // make sure enabled pre processing effects state is communicated to the HAL as we
66271b92868010b5c1409692a86f6b27e4a265b64c1aEric Laurent    // just moved them to a new input stream.
66281b92868010b5c1409692a86f6b27e4a265b64c1aEric Laurent    chain->syncHalEffectsState();
66291b92868010b5c1409692a86f6b27e4a265b64c1aEric Laurent
663081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    mEffectChains.add(chain);
663181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
663281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return NO_ERROR;
663381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
663481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
663581784c37c61b09289654b979567a42bf73cd2b12Eric Laurentsize_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
663681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent{
663781784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
663881784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    ALOGW_IF(mEffectChains.size() != 1,
663981784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            "removeEffectChain_l() %p invalid chain size %d on thread %p",
664081784c37c61b09289654b979567a42bf73cd2b12Eric Laurent            chain.get(), mEffectChains.size(), this);
664181784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    if (mEffectChains.size() == 1) {
664281784c37c61b09289654b979567a42bf73cd2b12Eric Laurent        mEffectChains.removeAt(0);
664381784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    }
664481784c37c61b09289654b979567a42bf73cd2b12Eric Laurent    return 0;
664581784c37c61b09289654b979567a42bf73cd2b12Eric Laurent}
664681784c37c61b09289654b979567a42bf73cd2b12Eric Laurent
66471c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurentstatus_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
66481c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent                                                          audio_patch_handle_t *handle)
66491c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent{
66501c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent    status_t status = NO_ERROR;
66511c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent    if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
66521c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent        // store new device and send to effects
66531c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent        mInDevice = patch->sources[0].ext.device.type;
66541c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent        for (size_t i = 0; i < mEffectChains.size(); i++) {
66551c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent            mEffectChains[i]->setDevice_l(mInDevice);
66561c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent        }
66571c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent
66581c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent        // disable AEC and NS if the device is a BT SCO headset supporting those
66591c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent        // pre processings
66601c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent        if (mTracks.size() > 0) {
66611c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent            bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
66621c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent                                mAudioFlinger->btNrecIsOff();
66631c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent            for (size_t i = 0; i < mTracks.size(); i++) {
66641c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent                sp<RecordTrack> track = mTracks[i];
66651c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent                setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
66661c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent                setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
66671c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent            }
66681c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent        }
66691c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent
66701c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent        // store new source and send to effects
66711c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent        if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
66721c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent            mAudioSource = patch->sinks[0].ext.mix.usecase.source;
66731c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent            for (size_t i = 0; i < mEffectChains.size(); i++) {
66741c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent                mEffectChains[i]->setAudioSource_l(mAudioSource);
66751c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent            }
66761c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent        }
66771c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent
66781c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent        audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
66791c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent        status = hwDevice->create_audio_patch(hwDevice,
66801c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent                                               patch->num_sources,
66811c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent                                               patch->sources,
66821c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent                                               patch->num_sinks,
66831c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent                                               patch->sinks,
66841c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent                                               handle);
66851c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent    } else {
66861c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent        ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
66871c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent    }
66881c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent    return status;
66891c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent}
66901c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent
66911c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurentstatus_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
66921c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent{
66931c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent    status_t status = NO_ERROR;
66941c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent    if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
66951c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent        audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
66961c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent        status = hwDevice->release_audio_patch(hwDevice, handle);
66971c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent    } else {
66981c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent        ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
66991c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent    }
67001c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent    return status;
67011c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent}
67021c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent
670383b8808faad1e91690c64d7007348be8d9ebde73Eric Laurentvoid AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
670483b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent{
670583b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent    Mutex::Autolock _l(mLock);
670683b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent    mTracks.add(record);
670783b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent}
670883b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent
670983b8808faad1e91690c64d7007348be8d9ebde73Eric Laurentvoid AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
671083b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent{
671183b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent    Mutex::Autolock _l(mLock);
671283b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent    destroyTrack_l(record);
671383b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent}
671483b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent
671583b8808faad1e91690c64d7007348be8d9ebde73Eric Laurentvoid AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
671683b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent{
671783b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent    ThreadBase::getAudioPortConfig(config);
671883b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent    config->role = AUDIO_PORT_ROLE_SINK;
671983b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent    config->ext.mix.hw_module = mInput->audioHwDev->handle();
672083b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent    config->ext.mix.usecase.source = mAudioSource;
672183b8808faad1e91690c64d7007348be8d9ebde73Eric Laurent}
67221c333e252cbca3337c1bedbc57a005f3b7d23fdbEric Laurent
672363238efb0d674758902918e3cdaac322126484b7Glenn Kasten} // namespace android
6724