Threads.cpp revision 59fe010bcc072597852454a2ec53d7b0a2002a3b
15821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)/* 25821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)** 35821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)** Copyright 2012, The Android Open Source Project 45821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)** 55821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)** Licensed under the Apache License, Version 2.0 (the "License"); 65821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)** you may not use this file except in compliance with the License. 75821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)** You may obtain a copy of the License at 85821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)** 95821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)** http://www.apache.org/licenses/LICENSE-2.0 105821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)** 115821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)** Unless required by applicable law or agreed to in writing, software 125821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)** distributed under the License is distributed on an "AS IS" BASIS, 135821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 145821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)** See the License for the specific language governing permissions and 155821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)** limitations under the License. 165821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)*/ 175821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 185821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 195821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#define LOG_TAG "AudioFlinger" 205821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//#define LOG_NDEBUG 0 215821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#define ATRACE_TAG ATRACE_TAG_AUDIO 225821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 235821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "Configuration.h" 245821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include <math.h> 255821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include <fcntl.h> 265821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include <sys/stat.h> 275821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include <cutils/properties.h> 285821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include <media/AudioParameter.h> 295821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include <utils/Log.h> 305821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include <utils/Trace.h> 315821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 325821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include <private/media/AudioTrackShared.h> 335821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include <hardware/audio.h> 345821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include <audio_effects/effect_ns.h> 355821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include <audio_effects/effect_aec.h> 365821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include <audio_utils/primitives.h> 375821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 385821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// NBAIO implementations 395821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include <media/nbaio/AudioStreamOutSink.h> 405821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include <media/nbaio/MonoPipe.h> 415821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include <media/nbaio/MonoPipeReader.h> 425821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include <media/nbaio/Pipe.h> 435821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include <media/nbaio/PipeReader.h> 445821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include <media/nbaio/SourceAudioBufferProvider.h> 455821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 465821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include <powermanager/PowerManager.h> 475821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 485821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include <common_time/cc_helper.h> 495821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include <common_time/local_clock.h> 505821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 515821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "AudioFlinger.h" 525821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "AudioMixer.h" 535821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "FastMixer.h" 545821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "ServiceUtilities.h" 555821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "SchedulingPolicyService.h" 565821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 575821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#ifdef ADD_BATTERY_DATA 585821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include <media/IMediaPlayerService.h> 595821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include <media/IMediaDeathNotifier.h> 605821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#endif 615821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 625821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#ifdef DEBUG_CPU_USAGE 635821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include <cpustats/CentralTendencyStatistics.h> 645821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include <cpustats/ThreadCpuUsage.h> 655821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#endif 665821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 675821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// ---------------------------------------------------------------------------- 685821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 695821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// Note: the following macro is used for extremely verbose logging message. In 705821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to 715821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// 0; but one side effect of this is to turn all LOGV's as well. Some messages 725821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// are so verbose that we want to suppress them even when we have ALOG_ASSERT 735821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// turned on. Do not uncomment the #def below unless you really know what you 745821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// are doing and want to see all of the extremely verbose messages. 755821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//#define VERY_VERY_VERBOSE_LOGGING 765821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#ifdef VERY_VERY_VERBOSE_LOGGING 775821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#define ALOGVV ALOGV 785821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#else 795821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#define ALOGVV(a...) do { } while(0) 805821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#endif 815821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 825821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)namespace android { 835821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 845821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// retry counts for buffer fill timeout 855821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// 50 * ~20msecs = 1 second 865821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)static const int8_t kMaxTrackRetries = 50; 875821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)static const int8_t kMaxTrackStartupRetries = 50; 885821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// allow less retry attempts on direct output thread. 895821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// direct outputs can be a scarce resource in audio hardware and should 905821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// be released as quickly as possible. 915821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)static const int8_t kMaxTrackRetriesDirect = 2; 925821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 935821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// don't warn about blocked writes or record buffer overflows more often than this 945821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)static const nsecs_t kWarningThrottleNs = seconds(5); 955821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 965821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// RecordThread loop sleep time upon application overrun or audio HAL read error 975821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)static const int kRecordThreadSleepUs = 5000; 985821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 995821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// maximum time to wait for setParameters to complete 1005821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)static const nsecs_t kSetParametersTimeoutNs = seconds(2); 1015821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 1025821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// minimum sleep time for the mixer thread loop when tracks are active but in underrun 1035821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)static const uint32_t kMinThreadSleepTimeUs = 5000; 1045821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// maximum divider applied to the active sleep time in the mixer thread loop 1055821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)static const uint32_t kMaxThreadSleepTimeShift = 2; 1065821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 1075821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// minimum normal mix buffer size, expressed in milliseconds rather than frames 1085821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)static const uint32_t kMinNormalMixBufferSizeMs = 20; 1095821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// maximum normal mix buffer size 1105821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)static const uint32_t kMaxNormalMixBufferSizeMs = 24; 1115821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 1125821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// Offloaded output thread standby delay: allows track transition without going to standby 1135821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)static const nsecs_t kOffloadStandbyDelayNs = seconds(1); 1145821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 1155821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// Whether to use fast mixer 1165821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)static const enum { 1175821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) FastMixer_Never, // never initialize or use: for debugging only 1185821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) FastMixer_Always, // always initialize and use, even if not needed: for debugging only 1195821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) // normal mixer multiplier is 1 1205821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) FastMixer_Static, // initialize if needed, then use all the time if initialized, 1215821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) // multiplier is calculated based on min & max normal mixer buffer size 1225821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load, 1235821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) // multiplier is calculated based on min & max normal mixer buffer size 1245821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) // FIXME for FastMixer_Dynamic: 1255821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) // Supporting this option will require fixing HALs that can't handle large writes. 1265821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) // For example, one HAL implementation returns an error from a large write, 1275821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) // and another HAL implementation corrupts memory, possibly in the sample rate converter. 1285821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) // We could either fix the HAL implementations, or provide a wrapper that breaks 1295821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) // up large writes into smaller ones, and the wrapper would need to deal with scheduler. 1305821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)} kUseFastMixer = FastMixer_Static; 1315821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 1325821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// Priorities for requestPriority 1335821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)static const int kPriorityAudioApp = 2; 1345821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)static const int kPriorityFastMixer = 3; 1355821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 1365821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// IAudioFlinger::createTrack() reports back to client the total size of shared memory area 1375821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// for the track. The client then sub-divides this into smaller buffers for its use. 1385821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// Currently the client uses double-buffering by default, but doesn't tell us about that. 1395821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// So for now we just assume that client is double-buffered. 1405821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// FIXME It would be better for client to tell AudioFlinger whether it wants double-buffering or 1415821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// N-buffering, so AudioFlinger could allocate the right amount of memory. 1425821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// See the client's minBufCount and mNotificationFramesAct calculations for details. 1435821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)static const int kFastTrackMultiplier = 1; 1445821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 1455821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// ---------------------------------------------------------------------------- 1465821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 1475821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#ifdef ADD_BATTERY_DATA 1485821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// To collect the amplifier usage 1495821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)static void addBatteryData(uint32_t params) { 1505821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService(); 1515821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) if (service == NULL) { 1525821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) // it already logged 1535821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) return; 1545821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) } 1555821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 1565821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) service->addBatteryData(params); 1575821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)} 1585821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#endif 1595821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 1605821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 1615821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// ---------------------------------------------------------------------------- 1625821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// CPU Stats 1635821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// ---------------------------------------------------------------------------- 1645821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 1655821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)class CpuStats { 1665821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)public: 1675821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) CpuStats(); 1685821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) void sample(const String8 &title); 1695821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#ifdef DEBUG_CPU_USAGE 1705821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)private: 1715821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns 1725821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns 1735821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 1745821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles 1755821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 1765821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) int mCpuNum; // thread's current CPU number 1775821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) int mCpukHz; // frequency of thread's current CPU in kHz 1785821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#endif 1795821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)}; 1805821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 1815821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)CpuStats::CpuStats() 1825821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#ifdef DEBUG_CPU_USAGE 1835821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) : mCpuNum(-1), mCpukHz(-1) 1845821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#endif 1855821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles){ 1865821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)} 1875821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 1885821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)void CpuStats::sample(const String8 &title) { 1895821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#ifdef DEBUG_CPU_USAGE 1905821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) // get current thread's delta CPU time in wall clock ns 1915821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) double wcNs; 1925821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) bool valid = mCpuUsage.sampleAndEnable(wcNs); 1935821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 1945821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) // record sample for wall clock statistics 1955821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) if (valid) { 1965821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) mWcStats.sample(wcNs); 1975821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) } 1985821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 1995821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) // get the current CPU number 2005821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) int cpuNum = sched_getcpu(); 2015821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 2025821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) // get the current CPU frequency in kHz 2035821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) int cpukHz = mCpuUsage.getCpukHz(cpuNum); 2045821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 2055821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) // check if either CPU number or frequency changed 2065821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) if (cpuNum != mCpuNum || cpukHz != mCpukHz) { 2075821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) mCpuNum = cpuNum; 2085821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) mCpukHz = cpukHz; 2095821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) // ignore sample for purposes of cycles 2105821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) valid = false; 2115821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) } 2125821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 2135821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) // if no change in CPU number or frequency, then record sample for cycle statistics 2145821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) if (valid && mCpukHz > 0) { 2155821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) double cycles = wcNs * cpukHz * 0.000001; 2165821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) mHzStats.sample(cycles); 2175821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) } 2185821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 2195821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) unsigned n = mWcStats.n(); 2205821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) // mCpuUsage.elapsed() is expensive, so don't call it every loop 2215821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) if ((n & 127) == 1) { 2225821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) long long elapsed = mCpuUsage.elapsed(); 2235821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) { 2245821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) double perLoop = elapsed / (double) n; 2255821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) double perLoop100 = perLoop * 0.01; 2265821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) double perLoop1k = perLoop * 0.001; 2275821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) double mean = mWcStats.mean(); 2285821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) double stddev = mWcStats.stddev(); 2295821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) double minimum = mWcStats.minimum(); 2305821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) double maximum = mWcStats.maximum(); 2315821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) double meanCycles = mHzStats.mean(); 2325821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) double stddevCycles = mHzStats.stddev(); 2335821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) double minCycles = mHzStats.minimum(); 2345821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) double maxCycles = mHzStats.maximum(); 2355821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) mCpuUsage.resetElapsed(); 2365821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) mWcStats.reset(); 2375821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) mHzStats.reset(); 2385821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) ALOGD("CPU usage for %s over past %.1f secs\n" 2395821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) " (%u mixer loops at %.1f mean ms per loop):\n" 2405821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n" 2415821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n" 2425821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f", 2435821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) title.string(), 2445821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) elapsed * .000000001, n, perLoop * .000001, 2455821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) mean * .001, 2465821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) stddev * .001, 2475821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) minimum * .001, 2485821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) maximum * .001, 2495821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) mean / perLoop100, 2505821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) stddev / perLoop100, 2515821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) minimum / perLoop100, 2525821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) maximum / perLoop100, 2535821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) meanCycles / perLoop1k, 2545821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) stddevCycles / perLoop1k, 2555821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) minCycles / perLoop1k, 2565821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) maxCycles / perLoop1k); 2575821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 2585821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) } 2595821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) } 2605821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#endif 2615821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)}; 2625821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 2635821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// ---------------------------------------------------------------------------- 2645821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// ThreadBase 2655821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// ---------------------------------------------------------------------------- 2665821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 2675821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id, 2685821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) audio_devices_t outDevice, audio_devices_t inDevice, type_t type) 2695821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) : Thread(false /*canCallJava*/), 2705821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) mType(type), 2715821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) mAudioFlinger(audioFlinger), 2725821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, and mFormat are 2735821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) // set by PlaybackThread::readOutputParameters() or RecordThread::readInputParameters() 2745821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) mParamStatus(NO_ERROR), 2755821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) mStandby(false), mOutDevice(outDevice), mInDevice(inDevice), 2765821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id), 2775821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) // mName will be set by concrete (non-virtual) subclass 2785821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) mDeathRecipient(new PMDeathRecipient(this)) 2795821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles){ 2805821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)} 2815821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 2825821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)AudioFlinger::ThreadBase::~ThreadBase() 2835821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles){ 2845821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) // mConfigEvents should be empty, but just in case it isn't, free the memory it owns 2855821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) for (size_t i = 0; i < mConfigEvents.size(); i++) { 2865821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) delete mConfigEvents[i]; 2875821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) } 2885821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) mConfigEvents.clear(); 2895821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 2905821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) mParamCond.broadcast(); 2915821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) // do not lock the mutex in destructor 2925821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) releaseWakeLock_l(); 2935821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) if (mPowerManager != 0) { 2945821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) sp<IBinder> binder = mPowerManager->asBinder(); 2955821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) binder->unlinkToDeath(mDeathRecipient); 2965821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) } 2975821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)} 2985821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 2995821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)void AudioFlinger::ThreadBase::exit() 3005821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles){ 3015821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) ALOGV("ThreadBase::exit"); 3025821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) // do any cleanup required for exit to succeed 3035821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) preExit(); 3045821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) { 3055821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) // This lock prevents the following race in thread (uniprocessor for illustration): 3065821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) // if (!exitPending()) { 3075821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) // // context switch from here to exit() 3085821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) // // exit() calls requestExit(), what exitPending() observes 3095821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) // // exit() calls signal(), which is dropped since no waiters 3105821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) // // context switch back from exit() to here 3115821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) // mWaitWorkCV.wait(...); 3125821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) // // now thread is hung 3135821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) // } 3145821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) AutoMutex lock(mLock); 3155821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) requestExit(); 3165821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) mWaitWorkCV.broadcast(); 3175821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) } 3185821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) // When Thread::requestExitAndWait is made virtual and this method is renamed to 3195821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();" 3205821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) requestExitAndWait(); 3215821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)} 3225821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 3235821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs) 3245821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles){ 3255821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) status_t status; 3265821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 3275821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string()); 3285821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) Mutex::Autolock _l(mLock); 3295821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 3305821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) mNewParameters.add(keyValuePairs); 3315821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) mWaitWorkCV.signal(); 3325821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) // wait condition with timeout in case the thread loop has exited 3335821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) // before the request could be processed 3345821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) { 3355821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) status = mParamStatus; 3365821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) mWaitWorkCV.signal(); 3375821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) } else { 3385821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) status = TIMED_OUT; 3395821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) } 3405821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) return status; 3415821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)} 3425821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 3435821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param) 3445821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles){ 3455821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) Mutex::Autolock _l(mLock); 3465821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) sendIoConfigEvent_l(event, param); 3475821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)} 3485821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 3495821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// sendIoConfigEvent_l() must be called with ThreadBase::mLock held 3505821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param) 3515821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles){ 3525821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) IoConfigEvent *ioEvent = new IoConfigEvent(event, param); 3535821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) mConfigEvents.add(static_cast<ConfigEvent *>(ioEvent)); 3545821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) ALOGV("sendIoConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, 3555821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) param); 3565821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) mWaitWorkCV.signal(); 3575821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)} 3585821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 3595821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held 3605821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio) 3615821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles){ 3625821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) PrioConfigEvent *prioEvent = new PrioConfigEvent(pid, tid, prio); 3635821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) mConfigEvents.add(static_cast<ConfigEvent *>(prioEvent)); 3645821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) ALOGV("sendPrioConfigEvent_l() num events %d pid %d, tid %d prio %d", 3655821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) mConfigEvents.size(), pid, tid, prio); 3665821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) mWaitWorkCV.signal(); 3675821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)} 3685821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 3695821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)void AudioFlinger::ThreadBase::processConfigEvents() 3705821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles){ 3715821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) mLock.lock(); 3725821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) while (!mConfigEvents.isEmpty()) { 3735821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size()); 3745821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) ConfigEvent *event = mConfigEvents[0]; 3755821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) mConfigEvents.removeAt(0); 3765821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) // release mLock before locking AudioFlinger mLock: lock order is always 3775821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) // AudioFlinger then ThreadBase to avoid cross deadlock 3785821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) mLock.unlock(); 3795821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) switch(event->type()) { 3805821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) case CFG_EVENT_PRIO: { 3815821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) PrioConfigEvent *prioEvent = static_cast<PrioConfigEvent *>(event); 3825821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) // FIXME Need to understand why this has be done asynchronously 3835821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) int err = requestPriority(prioEvent->pid(), prioEvent->tid(), prioEvent->prio(), 3845821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) true /*asynchronous*/); 3855821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) if (err != 0) { 3865821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; " 3875821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) "error %d", 3885821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) prioEvent->prio(), prioEvent->pid(), prioEvent->tid(), err); 3895821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) } 3905821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) } break; 3915821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) case CFG_EVENT_IO: { 3925821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) IoConfigEvent *ioEvent = static_cast<IoConfigEvent *>(event); 3935821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) mAudioFlinger->mLock.lock(); 3945821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) audioConfigChanged_l(ioEvent->event(), ioEvent->param()); 3955821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) mAudioFlinger->mLock.unlock(); 3965821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) } break; 3975821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) default: 3985821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) ALOGE("processConfigEvents() unknown event type %d", event->type()); 3995821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) break; 4005821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) } 4015821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) delete event; 4025821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) mLock.lock(); 4035821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) } 4045821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) mLock.unlock(); 4055821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)} 4065821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 4075821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args) 4085821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles){ 4095821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) const size_t SIZE = 256; 4105821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) char buffer[SIZE]; 4115821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) String8 result; 4125821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 4135821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) bool locked = AudioFlinger::dumpTryLock(mLock); 4145821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) if (!locked) { 4155821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this); 4165821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) write(fd, buffer, strlen(buffer)); 4175821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) } 4185821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 4195821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) snprintf(buffer, SIZE, "io handle: %d\n", mId); 4205821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) result.append(buffer); 4215821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) snprintf(buffer, SIZE, "TID: %d\n", getTid()); 4225821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) result.append(buffer); 4235821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) snprintf(buffer, SIZE, "standby: %d\n", mStandby); 4245821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) result.append(buffer); 4255821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) snprintf(buffer, SIZE, "Sample rate: %u\n", mSampleRate); 4265821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) result.append(buffer); 4275821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount); 4285821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) result.append(buffer); 4295821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) snprintf(buffer, SIZE, "Channel Count: %u\n", mChannelCount); 4305821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) result.append(buffer); 4315821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask); 4325821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) result.append(buffer); 4335821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) snprintf(buffer, SIZE, "Format: %d\n", mFormat); 4345821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) result.append(buffer); 4355821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize); 4365821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) result.append(buffer); 4375821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 4385821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) snprintf(buffer, SIZE, "\nPending setParameters commands: \n"); 4395821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) result.append(buffer); 4405821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) result.append(" Index Command"); 4415821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) for (size_t i = 0; i < mNewParameters.size(); ++i) { 4425821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) snprintf(buffer, SIZE, "\n %02d ", i); 4435821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) result.append(buffer); 4445821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) result.append(mNewParameters[i]); 4455821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) } 4465821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 4475821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) snprintf(buffer, SIZE, "\n\nPending config events: \n"); 4485821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) result.append(buffer); 4495821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) for (size_t i = 0; i < mConfigEvents.size(); i++) { 4505821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) mConfigEvents[i]->dump(buffer, SIZE); 4515821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) result.append(buffer); 4525821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) } 4535821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) result.append("\n"); 4545821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 4555821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) write(fd, result.string(), result.size()); 4565821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 4575821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) if (locked) { 4585821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) mLock.unlock(); 4595821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) } 4605821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)} 4615821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 4625821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args) 4635821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles){ 4645821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) const size_t SIZE = 256; 4655821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) char buffer[SIZE]; 4665821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) String8 result; 4675821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 4685821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size()); 4695821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) write(fd, buffer, strlen(buffer)); 4705821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 4715821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) for (size_t i = 0; i < mEffectChains.size(); ++i) { 4725821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) sp<EffectChain> chain = mEffectChains[i]; 4735821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) if (chain != 0) { 4745821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) chain->dump(fd, args); 4755821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) } 4765821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) } 4775821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)} 4785821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 4795821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)void AudioFlinger::ThreadBase::acquireWakeLock() 4805821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles){ 4815821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) Mutex::Autolock _l(mLock); 4825821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) acquireWakeLock_l(); 4835821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)} 4845821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 4855821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)void AudioFlinger::ThreadBase::acquireWakeLock_l() 4865821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles){ 4875821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) if (mPowerManager == 0) { 4885821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) // use checkService() to avoid blocking if power service is not up yet 4895821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) sp<IBinder> binder = 4905821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) defaultServiceManager()->checkService(String16("power")); 4915821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) if (binder == 0) { 4925821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) ALOGW("Thread %s cannot connect to the power manager service", mName); 4935821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) } else { 4945821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) mPowerManager = interface_cast<IPowerManager>(binder); 4955821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) binder->linkToDeath(mDeathRecipient); 4965821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) } 4975821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) } 4985821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) if (mPowerManager != 0) { 4995821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) sp<IBinder> binder = new BBinder(); 5005821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK, 5015821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) binder, 5025821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) String16(mName), 5035821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) String16("media")); 5045821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) if (status == NO_ERROR) { 5055821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) mWakeLockToken = binder; 5065821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) } 5075821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) ALOGV("acquireWakeLock_l() %s status %d", mName, status); 5085821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) } 5095821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)} 5105821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 5115821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)void AudioFlinger::ThreadBase::releaseWakeLock() 5125821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles){ 5135821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) Mutex::Autolock _l(mLock); 5145821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) releaseWakeLock_l(); 5155821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)} 5165821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 5175821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)void AudioFlinger::ThreadBase::releaseWakeLock_l() 5185821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles){ 5195821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) if (mWakeLockToken != 0) { 5205821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) ALOGV("releaseWakeLock_l() %s", mName); 5215821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) if (mPowerManager != 0) { 5225821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) mPowerManager->releaseWakeLock(mWakeLockToken, 0); 5235821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) } 5245821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) mWakeLockToken.clear(); 5255821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) } 5265821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)} 5275821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 5285821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)void AudioFlinger::ThreadBase::clearPowerManager() 5295821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles){ 5305821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) Mutex::Autolock _l(mLock); 5315821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) releaseWakeLock_l(); 5325821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) mPowerManager.clear(); 5335821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)} 5345821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 5355821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who) 5365821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles){ 5375821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) sp<ThreadBase> thread = mThread.promote(); 5385821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) if (thread != 0) { 5395821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) thread->clearPowerManager(); 5405821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) } 5415821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) ALOGW("power manager service died !!!"); 5425821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)} 5435821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 5445821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)void AudioFlinger::ThreadBase::setEffectSuspended( 5455821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) const effect_uuid_t *type, bool suspend, int sessionId) 5465821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles){ 5475821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) Mutex::Autolock _l(mLock); 5485821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) setEffectSuspended_l(type, suspend, sessionId); 5495821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)} 5505821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 5515821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)void AudioFlinger::ThreadBase::setEffectSuspended_l( 5525821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) const effect_uuid_t *type, bool suspend, int sessionId) 5535821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles){ 5545821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) sp<EffectChain> chain = getEffectChain_l(sessionId); 5555821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) if (chain != 0) { 5565821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) if (type != NULL) { 5575821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) chain->setEffectSuspended_l(type, suspend); 5585821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) } else { 5595821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) chain->setEffectSuspendedAll_l(suspend); 5605821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) } 5615821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) } 5625821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 5635821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) updateSuspendedSessions_l(type, suspend, sessionId); 5645821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)} 5655821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 5665821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain) 5675821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles){ 5685821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId()); 5695821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) if (index < 0) { 5705821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) return; 5715821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) } 5725821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 5735821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects = 5745821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) mSuspendedSessions.valueAt(index); 5755821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 5765821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) for (size_t i = 0; i < sessionEffects.size(); i++) { 5775821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i); 5785821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) for (int j = 0; j < desc->mRefCount; j++) { 5795821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) { 5805821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) chain->setEffectSuspendedAll_l(true); 5815821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) } else { 5825821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x", 5835821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) desc->mType.timeLow); 5845821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) chain->setEffectSuspended_l(&desc->mType, true); 5855821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) } 5865821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) } 5875821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) } 5885821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)} 5895821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 5905821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type, 5915821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) bool suspend, 5925821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) int sessionId) 5935821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles){ 5945821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) ssize_t index = mSuspendedSessions.indexOfKey(sessionId); 5955821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 5965821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects; 5975821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 5985821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) if (suspend) { 5995821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) if (index >= 0) { 6005821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) sessionEffects = mSuspendedSessions.valueAt(index); 6015821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) } else { 6025821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) mSuspendedSessions.add(sessionId, sessionEffects); 6035821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) } 6045821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) } else { 6055821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) if (index < 0) { 6065821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) return; 607 } 608 sessionEffects = mSuspendedSessions.valueAt(index); 609 } 610 611 612 int key = EffectChain::kKeyForSuspendAll; 613 if (type != NULL) { 614 key = type->timeLow; 615 } 616 index = sessionEffects.indexOfKey(key); 617 618 sp<SuspendedSessionDesc> desc; 619 if (suspend) { 620 if (index >= 0) { 621 desc = sessionEffects.valueAt(index); 622 } else { 623 desc = new SuspendedSessionDesc(); 624 if (type != NULL) { 625 desc->mType = *type; 626 } 627 sessionEffects.add(key, desc); 628 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key); 629 } 630 desc->mRefCount++; 631 } else { 632 if (index < 0) { 633 return; 634 } 635 desc = sessionEffects.valueAt(index); 636 if (--desc->mRefCount == 0) { 637 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key); 638 sessionEffects.removeItemsAt(index); 639 if (sessionEffects.isEmpty()) { 640 ALOGV("updateSuspendedSessions_l() restore removing session %d", 641 sessionId); 642 mSuspendedSessions.removeItem(sessionId); 643 } 644 } 645 } 646 if (!sessionEffects.isEmpty()) { 647 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects); 648 } 649} 650 651void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect, 652 bool enabled, 653 int sessionId) 654{ 655 Mutex::Autolock _l(mLock); 656 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId); 657} 658 659void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect, 660 bool enabled, 661 int sessionId) 662{ 663 if (mType != RECORD) { 664 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on 665 // another session. This gives the priority to well behaved effect control panels 666 // and applications not using global effects. 667 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect 668 // global effects 669 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) { 670 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX); 671 } 672 } 673 674 sp<EffectChain> chain = getEffectChain_l(sessionId); 675 if (chain != 0) { 676 chain->checkSuspendOnEffectEnabled(effect, enabled); 677 } 678} 679 680// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held 681sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l( 682 const sp<AudioFlinger::Client>& client, 683 const sp<IEffectClient>& effectClient, 684 int32_t priority, 685 int sessionId, 686 effect_descriptor_t *desc, 687 int *enabled, 688 status_t *status 689 ) 690{ 691 sp<EffectModule> effect; 692 sp<EffectHandle> handle; 693 status_t lStatus; 694 sp<EffectChain> chain; 695 bool chainCreated = false; 696 bool effectCreated = false; 697 bool effectRegistered = false; 698 699 lStatus = initCheck(); 700 if (lStatus != NO_ERROR) { 701 ALOGW("createEffect_l() Audio driver not initialized."); 702 goto Exit; 703 } 704 705 // Allow global effects only on offloaded and mixer threads 706 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) { 707 switch (mType) { 708 case MIXER: 709 case OFFLOAD: 710 break; 711 case DIRECT: 712 case DUPLICATING: 713 case RECORD: 714 default: 715 ALOGW("createEffect_l() Cannot add global effect %s on thread %s", desc->name, mName); 716 lStatus = BAD_VALUE; 717 goto Exit; 718 } 719 } 720 721 // Only Pre processor effects are allowed on input threads and only on input threads 722 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) { 723 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d", 724 desc->name, desc->flags, mType); 725 lStatus = BAD_VALUE; 726 goto Exit; 727 } 728 729 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId); 730 731 { // scope for mLock 732 Mutex::Autolock _l(mLock); 733 734 // check for existing effect chain with the requested audio session 735 chain = getEffectChain_l(sessionId); 736 if (chain == 0) { 737 // create a new chain for this session 738 ALOGV("createEffect_l() new effect chain for session %d", sessionId); 739 chain = new EffectChain(this, sessionId); 740 addEffectChain_l(chain); 741 chain->setStrategy(getStrategyForSession_l(sessionId)); 742 chainCreated = true; 743 } else { 744 effect = chain->getEffectFromDesc_l(desc); 745 } 746 747 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get()); 748 749 if (effect == 0) { 750 int id = mAudioFlinger->nextUniqueId(); 751 // Check CPU and memory usage 752 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id); 753 if (lStatus != NO_ERROR) { 754 goto Exit; 755 } 756 effectRegistered = true; 757 // create a new effect module if none present in the chain 758 effect = new EffectModule(this, chain, desc, id, sessionId); 759 lStatus = effect->status(); 760 if (lStatus != NO_ERROR) { 761 goto Exit; 762 } 763 effect->setOffloaded(mType == OFFLOAD, mId); 764 765 lStatus = chain->addEffect_l(effect); 766 if (lStatus != NO_ERROR) { 767 goto Exit; 768 } 769 effectCreated = true; 770 771 effect->setDevice(mOutDevice); 772 effect->setDevice(mInDevice); 773 effect->setMode(mAudioFlinger->getMode()); 774 effect->setAudioSource(mAudioSource); 775 } 776 // create effect handle and connect it to effect module 777 handle = new EffectHandle(effect, client, effectClient, priority); 778 lStatus = effect->addHandle(handle.get()); 779 if (enabled != NULL) { 780 *enabled = (int)effect->isEnabled(); 781 } 782 } 783 784Exit: 785 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) { 786 Mutex::Autolock _l(mLock); 787 if (effectCreated) { 788 chain->removeEffect_l(effect); 789 } 790 if (effectRegistered) { 791 AudioSystem::unregisterEffect(effect->id()); 792 } 793 if (chainCreated) { 794 removeEffectChain_l(chain); 795 } 796 handle.clear(); 797 } 798 799 if (status != NULL) { 800 *status = lStatus; 801 } 802 return handle; 803} 804 805sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId) 806{ 807 Mutex::Autolock _l(mLock); 808 return getEffect_l(sessionId, effectId); 809} 810 811sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId) 812{ 813 sp<EffectChain> chain = getEffectChain_l(sessionId); 814 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0; 815} 816 817// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and 818// PlaybackThread::mLock held 819status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect) 820{ 821 // check for existing effect chain with the requested audio session 822 int sessionId = effect->sessionId(); 823 sp<EffectChain> chain = getEffectChain_l(sessionId); 824 bool chainCreated = false; 825 826 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(), 827 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x", 828 this, effect->desc().name, effect->desc().flags); 829 830 if (chain == 0) { 831 // create a new chain for this session 832 ALOGV("addEffect_l() new effect chain for session %d", sessionId); 833 chain = new EffectChain(this, sessionId); 834 addEffectChain_l(chain); 835 chain->setStrategy(getStrategyForSession_l(sessionId)); 836 chainCreated = true; 837 } 838 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get()); 839 840 if (chain->getEffectFromId_l(effect->id()) != 0) { 841 ALOGW("addEffect_l() %p effect %s already present in chain %p", 842 this, effect->desc().name, chain.get()); 843 return BAD_VALUE; 844 } 845 846 effect->setOffloaded(mType == OFFLOAD, mId); 847 848 status_t status = chain->addEffect_l(effect); 849 if (status != NO_ERROR) { 850 if (chainCreated) { 851 removeEffectChain_l(chain); 852 } 853 return status; 854 } 855 856 effect->setDevice(mOutDevice); 857 effect->setDevice(mInDevice); 858 effect->setMode(mAudioFlinger->getMode()); 859 effect->setAudioSource(mAudioSource); 860 return NO_ERROR; 861} 862 863void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) { 864 865 ALOGV("removeEffect_l() %p effect %p", this, effect.get()); 866 effect_descriptor_t desc = effect->desc(); 867 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 868 detachAuxEffect_l(effect->id()); 869 } 870 871 sp<EffectChain> chain = effect->chain().promote(); 872 if (chain != 0) { 873 // remove effect chain if removing last effect 874 if (chain->removeEffect_l(effect) == 0) { 875 removeEffectChain_l(chain); 876 } 877 } else { 878 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get()); 879 } 880} 881 882void AudioFlinger::ThreadBase::lockEffectChains_l( 883 Vector< sp<AudioFlinger::EffectChain> >& effectChains) 884{ 885 effectChains = mEffectChains; 886 for (size_t i = 0; i < mEffectChains.size(); i++) { 887 mEffectChains[i]->lock(); 888 } 889} 890 891void AudioFlinger::ThreadBase::unlockEffectChains( 892 const Vector< sp<AudioFlinger::EffectChain> >& effectChains) 893{ 894 for (size_t i = 0; i < effectChains.size(); i++) { 895 effectChains[i]->unlock(); 896 } 897} 898 899sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId) 900{ 901 Mutex::Autolock _l(mLock); 902 return getEffectChain_l(sessionId); 903} 904 905sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const 906{ 907 size_t size = mEffectChains.size(); 908 for (size_t i = 0; i < size; i++) { 909 if (mEffectChains[i]->sessionId() == sessionId) { 910 return mEffectChains[i]; 911 } 912 } 913 return 0; 914} 915 916void AudioFlinger::ThreadBase::setMode(audio_mode_t mode) 917{ 918 Mutex::Autolock _l(mLock); 919 size_t size = mEffectChains.size(); 920 for (size_t i = 0; i < size; i++) { 921 mEffectChains[i]->setMode_l(mode); 922 } 923} 924 925void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect, 926 EffectHandle *handle, 927 bool unpinIfLast) { 928 929 Mutex::Autolock _l(mLock); 930 ALOGV("disconnectEffect() %p effect %p", this, effect.get()); 931 // delete the effect module if removing last handle on it 932 if (effect->removeHandle(handle) == 0) { 933 if (!effect->isPinned() || unpinIfLast) { 934 removeEffect_l(effect); 935 AudioSystem::unregisterEffect(effect->id()); 936 } 937 } 938} 939 940// ---------------------------------------------------------------------------- 941// Playback 942// ---------------------------------------------------------------------------- 943 944AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger, 945 AudioStreamOut* output, 946 audio_io_handle_t id, 947 audio_devices_t device, 948 type_t type) 949 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type), 950 mNormalFrameCount(0), mMixBuffer(NULL), 951 mAllocMixBuffer(NULL), mSuspended(0), mBytesWritten(0), 952 // mStreamTypes[] initialized in constructor body 953 mOutput(output), 954 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false), 955 mMixerStatus(MIXER_IDLE), 956 mMixerStatusIgnoringFastTracks(MIXER_IDLE), 957 standbyDelay(AudioFlinger::mStandbyTimeInNsecs), 958 mBytesRemaining(0), 959 mCurrentWriteLength(0), 960 mUseAsyncWrite(false), 961 mWriteAckSequence(0), 962 mDrainSequence(0), 963 mSignalPending(false), 964 mScreenState(AudioFlinger::mScreenState), 965 // index 0 is reserved for normal mixer's submix 966 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1), 967 // mLatchD, mLatchQ, 968 mLatchDValid(false), mLatchQValid(false) 969{ 970 snprintf(mName, kNameLength, "AudioOut_%X", id); 971 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName); 972 973 // Assumes constructor is called by AudioFlinger with it's mLock held, but 974 // it would be safer to explicitly pass initial masterVolume/masterMute as 975 // parameter. 976 // 977 // If the HAL we are using has support for master volume or master mute, 978 // then do not attenuate or mute during mixing (just leave the volume at 1.0 979 // and the mute set to false). 980 mMasterVolume = audioFlinger->masterVolume_l(); 981 mMasterMute = audioFlinger->masterMute_l(); 982 if (mOutput && mOutput->audioHwDev) { 983 if (mOutput->audioHwDev->canSetMasterVolume()) { 984 mMasterVolume = 1.0; 985 } 986 987 if (mOutput->audioHwDev->canSetMasterMute()) { 988 mMasterMute = false; 989 } 990 } 991 992 readOutputParameters(); 993 994 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor 995 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile 996 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT; 997 stream = (audio_stream_type_t) (stream + 1)) { 998 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream); 999 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream); 1000 } 1001 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here, 1002 // because mAudioFlinger doesn't have one to copy from 1003} 1004 1005AudioFlinger::PlaybackThread::~PlaybackThread() 1006{ 1007 mAudioFlinger->unregisterWriter(mNBLogWriter); 1008 delete [] mAllocMixBuffer; 1009} 1010 1011void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args) 1012{ 1013 dumpInternals(fd, args); 1014 dumpTracks(fd, args); 1015 dumpEffectChains(fd, args); 1016} 1017 1018void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args) 1019{ 1020 const size_t SIZE = 256; 1021 char buffer[SIZE]; 1022 String8 result; 1023 1024 result.appendFormat("Output thread %p stream volumes in dB:\n ", this); 1025 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) { 1026 const stream_type_t *st = &mStreamTypes[i]; 1027 if (i > 0) { 1028 result.appendFormat(", "); 1029 } 1030 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume)); 1031 if (st->mute) { 1032 result.append("M"); 1033 } 1034 } 1035 result.append("\n"); 1036 write(fd, result.string(), result.length()); 1037 result.clear(); 1038 1039 snprintf(buffer, SIZE, "Output thread %p tracks\n", this); 1040 result.append(buffer); 1041 Track::appendDumpHeader(result); 1042 for (size_t i = 0; i < mTracks.size(); ++i) { 1043 sp<Track> track = mTracks[i]; 1044 if (track != 0) { 1045 track->dump(buffer, SIZE); 1046 result.append(buffer); 1047 } 1048 } 1049 1050 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this); 1051 result.append(buffer); 1052 Track::appendDumpHeader(result); 1053 for (size_t i = 0; i < mActiveTracks.size(); ++i) { 1054 sp<Track> track = mActiveTracks[i].promote(); 1055 if (track != 0) { 1056 track->dump(buffer, SIZE); 1057 result.append(buffer); 1058 } 1059 } 1060 write(fd, result.string(), result.size()); 1061 1062 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way. 1063 FastTrackUnderruns underruns = getFastTrackUnderruns(0); 1064 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n", 1065 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty); 1066} 1067 1068void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args) 1069{ 1070 const size_t SIZE = 256; 1071 char buffer[SIZE]; 1072 String8 result; 1073 1074 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this); 1075 result.append(buffer); 1076 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount); 1077 result.append(buffer); 1078 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", 1079 ns2ms(systemTime() - mLastWriteTime)); 1080 result.append(buffer); 1081 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites); 1082 result.append(buffer); 1083 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites); 1084 result.append(buffer); 1085 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite); 1086 result.append(buffer); 1087 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended); 1088 result.append(buffer); 1089 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer); 1090 result.append(buffer); 1091 write(fd, result.string(), result.size()); 1092 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask); 1093 1094 dumpBase(fd, args); 1095} 1096 1097// Thread virtuals 1098status_t AudioFlinger::PlaybackThread::readyToRun() 1099{ 1100 status_t status = initCheck(); 1101 if (status == NO_ERROR) { 1102 ALOGI("AudioFlinger's thread %p ready to run", this); 1103 } else { 1104 ALOGE("No working audio driver found."); 1105 } 1106 return status; 1107} 1108 1109void AudioFlinger::PlaybackThread::onFirstRef() 1110{ 1111 run(mName, ANDROID_PRIORITY_URGENT_AUDIO); 1112} 1113 1114// ThreadBase virtuals 1115void AudioFlinger::PlaybackThread::preExit() 1116{ 1117 ALOGV(" preExit()"); 1118 // FIXME this is using hard-coded strings but in the future, this functionality will be 1119 // converted to use audio HAL extensions required to support tunneling 1120 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1"); 1121} 1122 1123// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held 1124sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l( 1125 const sp<AudioFlinger::Client>& client, 1126 audio_stream_type_t streamType, 1127 uint32_t sampleRate, 1128 audio_format_t format, 1129 audio_channel_mask_t channelMask, 1130 size_t frameCount, 1131 const sp<IMemory>& sharedBuffer, 1132 int sessionId, 1133 IAudioFlinger::track_flags_t *flags, 1134 pid_t tid, 1135 status_t *status) 1136{ 1137 sp<Track> track; 1138 status_t lStatus; 1139 1140 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0; 1141 1142 // client expresses a preference for FAST, but we get the final say 1143 if (*flags & IAudioFlinger::TRACK_FAST) { 1144 if ( 1145 // not timed 1146 (!isTimed) && 1147 // either of these use cases: 1148 ( 1149 // use case 1: shared buffer with any frame count 1150 ( 1151 (sharedBuffer != 0) 1152 ) || 1153 // use case 2: callback handler and frame count is default or at least as large as HAL 1154 ( 1155 (tid != -1) && 1156 ((frameCount == 0) || 1157 (frameCount >= (mFrameCount * kFastTrackMultiplier))) 1158 ) 1159 ) && 1160 // PCM data 1161 audio_is_linear_pcm(format) && 1162 // mono or stereo 1163 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) || 1164 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) && 1165#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE 1166 // hardware sample rate 1167 (sampleRate == mSampleRate) && 1168#endif 1169 // normal mixer has an associated fast mixer 1170 hasFastMixer() && 1171 // there are sufficient fast track slots available 1172 (mFastTrackAvailMask != 0) 1173 // FIXME test that MixerThread for this fast track has a capable output HAL 1174 // FIXME add a permission test also? 1175 ) { 1176 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count 1177 if (frameCount == 0) { 1178 frameCount = mFrameCount * kFastTrackMultiplier; 1179 } 1180 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d", 1181 frameCount, mFrameCount); 1182 } else { 1183 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d " 1184 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u " 1185 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x", 1186 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format, 1187 audio_is_linear_pcm(format), 1188 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask); 1189 *flags &= ~IAudioFlinger::TRACK_FAST; 1190 // For compatibility with AudioTrack calculation, buffer depth is forced 1191 // to be at least 2 x the normal mixer frame count and cover audio hardware latency. 1192 // This is probably too conservative, but legacy application code may depend on it. 1193 // If you change this calculation, also review the start threshold which is related. 1194 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream); 1195 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate); 1196 if (minBufCount < 2) { 1197 minBufCount = 2; 1198 } 1199 size_t minFrameCount = mNormalFrameCount * minBufCount; 1200 if (frameCount < minFrameCount) { 1201 frameCount = minFrameCount; 1202 } 1203 } 1204 } 1205 1206 if (mType == DIRECT) { 1207 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) { 1208 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) { 1209 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %d, channelMask 0x%08x " 1210 "for output %p with format %d", 1211 sampleRate, format, channelMask, mOutput, mFormat); 1212 lStatus = BAD_VALUE; 1213 goto Exit; 1214 } 1215 } 1216 } else if (mType == OFFLOAD) { 1217 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) { 1218 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \"" 1219 "for output %p with format %d", 1220 sampleRate, format, channelMask, mOutput, mFormat); 1221 lStatus = BAD_VALUE; 1222 goto Exit; 1223 } 1224 } else { 1225 if ((format & AUDIO_FORMAT_MAIN_MASK) != AUDIO_FORMAT_PCM) { 1226 ALOGE("createTrack_l() Bad parameter: format %d \"" 1227 "for output %p with format %d", 1228 format, mOutput, mFormat); 1229 lStatus = BAD_VALUE; 1230 goto Exit; 1231 } 1232 // Resampler implementation limits input sampling rate to 2 x output sampling rate. 1233 if (sampleRate > mSampleRate*2) { 1234 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate); 1235 lStatus = BAD_VALUE; 1236 goto Exit; 1237 } 1238 } 1239 1240 lStatus = initCheck(); 1241 if (lStatus != NO_ERROR) { 1242 ALOGE("Audio driver not initialized."); 1243 goto Exit; 1244 } 1245 1246 { // scope for mLock 1247 Mutex::Autolock _l(mLock); 1248 1249 // all tracks in same audio session must share the same routing strategy otherwise 1250 // conflicts will happen when tracks are moved from one output to another by audio policy 1251 // manager 1252 uint32_t strategy = AudioSystem::getStrategyForStream(streamType); 1253 for (size_t i = 0; i < mTracks.size(); ++i) { 1254 sp<Track> t = mTracks[i]; 1255 if (t != 0 && !t->isOutputTrack()) { 1256 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType()); 1257 if (sessionId == t->sessionId() && strategy != actual) { 1258 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u", 1259 strategy, actual); 1260 lStatus = BAD_VALUE; 1261 goto Exit; 1262 } 1263 } 1264 } 1265 1266 if (!isTimed) { 1267 track = new Track(this, client, streamType, sampleRate, format, 1268 channelMask, frameCount, sharedBuffer, sessionId, *flags); 1269 } else { 1270 track = TimedTrack::create(this, client, streamType, sampleRate, format, 1271 channelMask, frameCount, sharedBuffer, sessionId); 1272 } 1273 if (track == 0 || track->getCblk() == NULL || track->name() < 0) { 1274 lStatus = NO_MEMORY; 1275 goto Exit; 1276 } 1277 1278 mTracks.add(track); 1279 1280 sp<EffectChain> chain = getEffectChain_l(sessionId); 1281 if (chain != 0) { 1282 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer()); 1283 track->setMainBuffer(chain->inBuffer()); 1284 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType())); 1285 chain->incTrackCnt(); 1286 } 1287 1288 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) { 1289 pid_t callingPid = IPCThreadState::self()->getCallingPid(); 1290 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful, 1291 // so ask activity manager to do this on our behalf 1292 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp); 1293 } 1294 } 1295 1296 lStatus = NO_ERROR; 1297 1298Exit: 1299 if (status) { 1300 *status = lStatus; 1301 } 1302 return track; 1303} 1304 1305uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const 1306{ 1307 return latency; 1308} 1309 1310uint32_t AudioFlinger::PlaybackThread::latency() const 1311{ 1312 Mutex::Autolock _l(mLock); 1313 return latency_l(); 1314} 1315uint32_t AudioFlinger::PlaybackThread::latency_l() const 1316{ 1317 if (initCheck() == NO_ERROR) { 1318 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream)); 1319 } else { 1320 return 0; 1321 } 1322} 1323 1324void AudioFlinger::PlaybackThread::setMasterVolume(float value) 1325{ 1326 Mutex::Autolock _l(mLock); 1327 // Don't apply master volume in SW if our HAL can do it for us. 1328 if (mOutput && mOutput->audioHwDev && 1329 mOutput->audioHwDev->canSetMasterVolume()) { 1330 mMasterVolume = 1.0; 1331 } else { 1332 mMasterVolume = value; 1333 } 1334} 1335 1336void AudioFlinger::PlaybackThread::setMasterMute(bool muted) 1337{ 1338 Mutex::Autolock _l(mLock); 1339 // Don't apply master mute in SW if our HAL can do it for us. 1340 if (mOutput && mOutput->audioHwDev && 1341 mOutput->audioHwDev->canSetMasterMute()) { 1342 mMasterMute = false; 1343 } else { 1344 mMasterMute = muted; 1345 } 1346} 1347 1348void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value) 1349{ 1350 Mutex::Autolock _l(mLock); 1351 mStreamTypes[stream].volume = value; 1352 broadcast_l(); 1353} 1354 1355void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted) 1356{ 1357 Mutex::Autolock _l(mLock); 1358 mStreamTypes[stream].mute = muted; 1359 broadcast_l(); 1360} 1361 1362float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const 1363{ 1364 Mutex::Autolock _l(mLock); 1365 return mStreamTypes[stream].volume; 1366} 1367 1368// addTrack_l() must be called with ThreadBase::mLock held 1369status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track) 1370{ 1371 status_t status = ALREADY_EXISTS; 1372 1373 // set retry count for buffer fill 1374 track->mRetryCount = kMaxTrackStartupRetries; 1375 if (mActiveTracks.indexOf(track) < 0) { 1376 // the track is newly added, make sure it fills up all its 1377 // buffers before playing. This is to ensure the client will 1378 // effectively get the latency it requested. 1379 if (!track->isOutputTrack()) { 1380 TrackBase::track_state state = track->mState; 1381 mLock.unlock(); 1382 status = AudioSystem::startOutput(mId, track->streamType(), track->sessionId()); 1383 mLock.lock(); 1384 // abort track was stopped/paused while we released the lock 1385 if (state != track->mState) { 1386 if (status == NO_ERROR) { 1387 mLock.unlock(); 1388 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId()); 1389 mLock.lock(); 1390 } 1391 return INVALID_OPERATION; 1392 } 1393 // abort if start is rejected by audio policy manager 1394 if (status != NO_ERROR) { 1395 return PERMISSION_DENIED; 1396 } 1397#ifdef ADD_BATTERY_DATA 1398 // to track the speaker usage 1399 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart); 1400#endif 1401 } 1402 1403 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING; 1404 track->mResetDone = false; 1405 track->mPresentationCompleteFrames = 0; 1406 mActiveTracks.add(track); 1407 sp<EffectChain> chain = getEffectChain_l(track->sessionId()); 1408 if (chain != 0) { 1409 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), 1410 track->sessionId()); 1411 chain->incActiveTrackCnt(); 1412 } 1413 1414 status = NO_ERROR; 1415 } 1416 1417 ALOGV("signal playback thread"); 1418 broadcast_l(); 1419 1420 return status; 1421} 1422 1423bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track) 1424{ 1425 track->terminate(); 1426 // active tracks are removed by threadLoop() 1427 bool trackActive = (mActiveTracks.indexOf(track) >= 0); 1428 track->mState = TrackBase::STOPPED; 1429 if (!trackActive) { 1430 removeTrack_l(track); 1431 } else if (track->isFastTrack() || track->isOffloaded()) { 1432 track->mState = TrackBase::STOPPING_1; 1433 } 1434 1435 return trackActive; 1436} 1437 1438void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track) 1439{ 1440 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE); 1441 mTracks.remove(track); 1442 deleteTrackName_l(track->name()); 1443 // redundant as track is about to be destroyed, for dumpsys only 1444 track->mName = -1; 1445 if (track->isFastTrack()) { 1446 int index = track->mFastIndex; 1447 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks); 1448 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index))); 1449 mFastTrackAvailMask |= 1 << index; 1450 // redundant as track is about to be destroyed, for dumpsys only 1451 track->mFastIndex = -1; 1452 } 1453 sp<EffectChain> chain = getEffectChain_l(track->sessionId()); 1454 if (chain != 0) { 1455 chain->decTrackCnt(); 1456 } 1457} 1458 1459void AudioFlinger::PlaybackThread::broadcast_l() 1460{ 1461 // Thread could be blocked waiting for async 1462 // so signal it to handle state changes immediately 1463 // If threadLoop is currently unlocked a signal of mWaitWorkCV will 1464 // be lost so we also flag to prevent it blocking on mWaitWorkCV 1465 mSignalPending = true; 1466 mWaitWorkCV.broadcast(); 1467} 1468 1469String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys) 1470{ 1471 Mutex::Autolock _l(mLock); 1472 if (initCheck() != NO_ERROR) { 1473 return String8(); 1474 } 1475 1476 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string()); 1477 const String8 out_s8(s); 1478 free(s); 1479 return out_s8; 1480} 1481 1482// audioConfigChanged_l() must be called with AudioFlinger::mLock held 1483void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) { 1484 AudioSystem::OutputDescriptor desc; 1485 void *param2 = NULL; 1486 1487 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, 1488 param); 1489 1490 switch (event) { 1491 case AudioSystem::OUTPUT_OPENED: 1492 case AudioSystem::OUTPUT_CONFIG_CHANGED: 1493 desc.channelMask = mChannelMask; 1494 desc.samplingRate = mSampleRate; 1495 desc.format = mFormat; 1496 desc.frameCount = mNormalFrameCount; // FIXME see 1497 // AudioFlinger::frameCount(audio_io_handle_t) 1498 desc.latency = latency(); 1499 param2 = &desc; 1500 break; 1501 1502 case AudioSystem::STREAM_CONFIG_CHANGED: 1503 param2 = ¶m; 1504 case AudioSystem::OUTPUT_CLOSED: 1505 default: 1506 break; 1507 } 1508 mAudioFlinger->audioConfigChanged_l(event, mId, param2); 1509} 1510 1511void AudioFlinger::PlaybackThread::writeCallback() 1512{ 1513 ALOG_ASSERT(mCallbackThread != 0); 1514 mCallbackThread->resetWriteBlocked(); 1515} 1516 1517void AudioFlinger::PlaybackThread::drainCallback() 1518{ 1519 ALOG_ASSERT(mCallbackThread != 0); 1520 mCallbackThread->resetDraining(); 1521} 1522 1523void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence) 1524{ 1525 Mutex::Autolock _l(mLock); 1526 // reject out of sequence requests 1527 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) { 1528 mWriteAckSequence &= ~1; 1529 mWaitWorkCV.signal(); 1530 } 1531} 1532 1533void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence) 1534{ 1535 Mutex::Autolock _l(mLock); 1536 // reject out of sequence requests 1537 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) { 1538 mDrainSequence &= ~1; 1539 mWaitWorkCV.signal(); 1540 } 1541} 1542 1543// static 1544int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event, 1545 void *param, 1546 void *cookie) 1547{ 1548 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie; 1549 ALOGV("asyncCallback() event %d", event); 1550 switch (event) { 1551 case STREAM_CBK_EVENT_WRITE_READY: 1552 me->writeCallback(); 1553 break; 1554 case STREAM_CBK_EVENT_DRAIN_READY: 1555 me->drainCallback(); 1556 break; 1557 default: 1558 ALOGW("asyncCallback() unknown event %d", event); 1559 break; 1560 } 1561 return 0; 1562} 1563 1564void AudioFlinger::PlaybackThread::readOutputParameters() 1565{ 1566 // unfortunately we have no way of recovering from errors here, hence the LOG_FATAL 1567 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common); 1568 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common); 1569 if (!audio_is_output_channel(mChannelMask)) { 1570 LOG_FATAL("HAL channel mask %#x not valid for output", mChannelMask); 1571 } 1572 if ((mType == MIXER || mType == DUPLICATING) && mChannelMask != AUDIO_CHANNEL_OUT_STEREO) { 1573 LOG_FATAL("HAL channel mask %#x not supported for mixed output; " 1574 "must be AUDIO_CHANNEL_OUT_STEREO", mChannelMask); 1575 } 1576 mChannelCount = popcount(mChannelMask); 1577 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common); 1578 if (!audio_is_valid_format(mFormat)) { 1579 LOG_FATAL("HAL format %d not valid for output", mFormat); 1580 } 1581 if ((mType == MIXER || mType == DUPLICATING) && mFormat != AUDIO_FORMAT_PCM_16_BIT) { 1582 LOG_FATAL("HAL format %d not supported for mixed output; must be AUDIO_FORMAT_PCM_16_BIT", 1583 mFormat); 1584 } 1585 mFrameSize = audio_stream_frame_size(&mOutput->stream->common); 1586 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize; 1587 if (mFrameCount & 15) { 1588 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames", 1589 mFrameCount); 1590 } 1591 1592 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) && 1593 (mOutput->stream->set_callback != NULL)) { 1594 if (mOutput->stream->set_callback(mOutput->stream, 1595 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) { 1596 mUseAsyncWrite = true; 1597 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this); 1598 } 1599 } 1600 1601 // Calculate size of normal mix buffer relative to the HAL output buffer size 1602 double multiplier = 1.0; 1603 if (mType == MIXER && (kUseFastMixer == FastMixer_Static || 1604 kUseFastMixer == FastMixer_Dynamic)) { 1605 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000; 1606 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000; 1607 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer 1608 minNormalFrameCount = (minNormalFrameCount + 15) & ~15; 1609 maxNormalFrameCount = maxNormalFrameCount & ~15; 1610 if (maxNormalFrameCount < minNormalFrameCount) { 1611 maxNormalFrameCount = minNormalFrameCount; 1612 } 1613 multiplier = (double) minNormalFrameCount / (double) mFrameCount; 1614 if (multiplier <= 1.0) { 1615 multiplier = 1.0; 1616 } else if (multiplier <= 2.0) { 1617 if (2 * mFrameCount <= maxNormalFrameCount) { 1618 multiplier = 2.0; 1619 } else { 1620 multiplier = (double) maxNormalFrameCount / (double) mFrameCount; 1621 } 1622 } else { 1623 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL 1624 // SRC (it would be unusual for the normal mix buffer size to not be a multiple of fast 1625 // track, but we sometimes have to do this to satisfy the maximum frame count 1626 // constraint) 1627 // FIXME this rounding up should not be done if no HAL SRC 1628 uint32_t truncMult = (uint32_t) multiplier; 1629 if ((truncMult & 1)) { 1630 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) { 1631 ++truncMult; 1632 } 1633 } 1634 multiplier = (double) truncMult; 1635 } 1636 } 1637 mNormalFrameCount = multiplier * mFrameCount; 1638 // round up to nearest 16 frames to satisfy AudioMixer 1639 mNormalFrameCount = (mNormalFrameCount + 15) & ~15; 1640 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount, 1641 mNormalFrameCount); 1642 1643 delete[] mAllocMixBuffer; 1644 size_t align = (mFrameSize < sizeof(int16_t)) ? sizeof(int16_t) : mFrameSize; 1645 mAllocMixBuffer = new int8_t[mNormalFrameCount * mFrameSize + align - 1]; 1646 mMixBuffer = (int16_t *) ((((size_t)mAllocMixBuffer + align - 1) / align) * align); 1647 memset(mMixBuffer, 0, mNormalFrameCount * mFrameSize); 1648 1649 // force reconfiguration of effect chains and engines to take new buffer size and audio 1650 // parameters into account 1651 // Note that mLock is not held when readOutputParameters() is called from the constructor 1652 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't 1653 // matter. 1654 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains 1655 Vector< sp<EffectChain> > effectChains = mEffectChains; 1656 for (size_t i = 0; i < effectChains.size(); i ++) { 1657 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false); 1658 } 1659} 1660 1661 1662status_t AudioFlinger::PlaybackThread::getRenderPosition(size_t *halFrames, size_t *dspFrames) 1663{ 1664 if (halFrames == NULL || dspFrames == NULL) { 1665 return BAD_VALUE; 1666 } 1667 Mutex::Autolock _l(mLock); 1668 if (initCheck() != NO_ERROR) { 1669 return INVALID_OPERATION; 1670 } 1671 size_t framesWritten = mBytesWritten / mFrameSize; 1672 *halFrames = framesWritten; 1673 1674 if (isSuspended()) { 1675 // return an estimation of rendered frames when the output is suspended 1676 size_t latencyFrames = (latency_l() * mSampleRate) / 1000; 1677 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0; 1678 return NO_ERROR; 1679 } else { 1680 return mOutput->stream->get_render_position(mOutput->stream, dspFrames); 1681 } 1682} 1683 1684uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const 1685{ 1686 Mutex::Autolock _l(mLock); 1687 uint32_t result = 0; 1688 if (getEffectChain_l(sessionId) != 0) { 1689 result = EFFECT_SESSION; 1690 } 1691 1692 for (size_t i = 0; i < mTracks.size(); ++i) { 1693 sp<Track> track = mTracks[i]; 1694 if (sessionId == track->sessionId() && !track->isInvalid()) { 1695 result |= TRACK_SESSION; 1696 break; 1697 } 1698 } 1699 1700 return result; 1701} 1702 1703uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId) 1704{ 1705 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that 1706 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected 1707 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) { 1708 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC); 1709 } 1710 for (size_t i = 0; i < mTracks.size(); i++) { 1711 sp<Track> track = mTracks[i]; 1712 if (sessionId == track->sessionId() && !track->isInvalid()) { 1713 return AudioSystem::getStrategyForStream(track->streamType()); 1714 } 1715 } 1716 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC); 1717} 1718 1719 1720AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const 1721{ 1722 Mutex::Autolock _l(mLock); 1723 return mOutput; 1724} 1725 1726AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput() 1727{ 1728 Mutex::Autolock _l(mLock); 1729 AudioStreamOut *output = mOutput; 1730 mOutput = NULL; 1731 // FIXME FastMixer might also have a raw ptr to mOutputSink; 1732 // must push a NULL and wait for ack 1733 mOutputSink.clear(); 1734 mPipeSink.clear(); 1735 mNormalSink.clear(); 1736 return output; 1737} 1738 1739// this method must always be called either with ThreadBase mLock held or inside the thread loop 1740audio_stream_t* AudioFlinger::PlaybackThread::stream() const 1741{ 1742 if (mOutput == NULL) { 1743 return NULL; 1744 } 1745 return &mOutput->stream->common; 1746} 1747 1748uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const 1749{ 1750 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000); 1751} 1752 1753status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event) 1754{ 1755 if (!isValidSyncEvent(event)) { 1756 return BAD_VALUE; 1757 } 1758 1759 Mutex::Autolock _l(mLock); 1760 1761 for (size_t i = 0; i < mTracks.size(); ++i) { 1762 sp<Track> track = mTracks[i]; 1763 if (event->triggerSession() == track->sessionId()) { 1764 (void) track->setSyncEvent(event); 1765 return NO_ERROR; 1766 } 1767 } 1768 1769 return NAME_NOT_FOUND; 1770} 1771 1772bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const 1773{ 1774 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE; 1775} 1776 1777void AudioFlinger::PlaybackThread::threadLoop_removeTracks( 1778 const Vector< sp<Track> >& tracksToRemove) 1779{ 1780 size_t count = tracksToRemove.size(); 1781 if (count) { 1782 for (size_t i = 0 ; i < count ; i++) { 1783 const sp<Track>& track = tracksToRemove.itemAt(i); 1784 if (!track->isOutputTrack()) { 1785 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId()); 1786#ifdef ADD_BATTERY_DATA 1787 // to track the speaker usage 1788 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop); 1789#endif 1790 if (track->isTerminated()) { 1791 AudioSystem::releaseOutput(mId); 1792 } 1793 } 1794 } 1795 } 1796} 1797 1798void AudioFlinger::PlaybackThread::checkSilentMode_l() 1799{ 1800 if (!mMasterMute) { 1801 char value[PROPERTY_VALUE_MAX]; 1802 if (property_get("ro.audio.silent", value, "0") > 0) { 1803 char *endptr; 1804 unsigned long ul = strtoul(value, &endptr, 0); 1805 if (*endptr == '\0' && ul != 0) { 1806 ALOGD("Silence is golden"); 1807 // The setprop command will not allow a property to be changed after 1808 // the first time it is set, so we don't have to worry about un-muting. 1809 setMasterMute_l(true); 1810 } 1811 } 1812 } 1813} 1814 1815// shared by MIXER and DIRECT, overridden by DUPLICATING 1816ssize_t AudioFlinger::PlaybackThread::threadLoop_write() 1817{ 1818 // FIXME rewrite to reduce number of system calls 1819 mLastWriteTime = systemTime(); 1820 mInWrite = true; 1821 ssize_t bytesWritten; 1822 1823 // If an NBAIO sink is present, use it to write the normal mixer's submix 1824 if (mNormalSink != 0) { 1825#define mBitShift 2 // FIXME 1826 size_t count = mBytesRemaining >> mBitShift; 1827 size_t offset = (mCurrentWriteLength - mBytesRemaining) >> 1; 1828 ATRACE_BEGIN("write"); 1829 // update the setpoint when AudioFlinger::mScreenState changes 1830 uint32_t screenState = AudioFlinger::mScreenState; 1831 if (screenState != mScreenState) { 1832 mScreenState = screenState; 1833 MonoPipe *pipe = (MonoPipe *)mPipeSink.get(); 1834 if (pipe != NULL) { 1835 pipe->setAvgFrames((mScreenState & 1) ? 1836 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2); 1837 } 1838 } 1839 ssize_t framesWritten = mNormalSink->write(mMixBuffer + offset, count); 1840 ATRACE_END(); 1841 if (framesWritten > 0) { 1842 bytesWritten = framesWritten << mBitShift; 1843 } else { 1844 bytesWritten = framesWritten; 1845 } 1846 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp); 1847 if (status == NO_ERROR) { 1848 size_t totalFramesWritten = mNormalSink->framesWritten(); 1849 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) { 1850 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition; 1851 mLatchDValid = true; 1852 } 1853 } 1854 // otherwise use the HAL / AudioStreamOut directly 1855 } else { 1856 // Direct output and offload threads 1857 size_t offset = (mCurrentWriteLength - mBytesRemaining) / sizeof(int16_t); 1858 if (mUseAsyncWrite) { 1859 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request"); 1860 mWriteAckSequence += 2; 1861 mWriteAckSequence |= 1; 1862 ALOG_ASSERT(mCallbackThread != 0); 1863 mCallbackThread->setWriteBlocked(mWriteAckSequence); 1864 } 1865 // FIXME We should have an implementation of timestamps for direct output threads. 1866 // They are used e.g for multichannel PCM playback over HDMI. 1867 bytesWritten = mOutput->stream->write(mOutput->stream, 1868 mMixBuffer + offset, mBytesRemaining); 1869 if (mUseAsyncWrite && 1870 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) { 1871 // do not wait for async callback in case of error of full write 1872 mWriteAckSequence &= ~1; 1873 ALOG_ASSERT(mCallbackThread != 0); 1874 mCallbackThread->setWriteBlocked(mWriteAckSequence); 1875 } 1876 } 1877 1878 mNumWrites++; 1879 mInWrite = false; 1880 1881 return bytesWritten; 1882} 1883 1884void AudioFlinger::PlaybackThread::threadLoop_drain() 1885{ 1886 if (mOutput->stream->drain) { 1887 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full"); 1888 if (mUseAsyncWrite) { 1889 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request"); 1890 mDrainSequence |= 1; 1891 ALOG_ASSERT(mCallbackThread != 0); 1892 mCallbackThread->setDraining(mDrainSequence); 1893 } 1894 mOutput->stream->drain(mOutput->stream, 1895 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY 1896 : AUDIO_DRAIN_ALL); 1897 } 1898} 1899 1900void AudioFlinger::PlaybackThread::threadLoop_exit() 1901{ 1902 // Default implementation has nothing to do 1903} 1904 1905/* 1906The derived values that are cached: 1907 - mixBufferSize from frame count * frame size 1908 - activeSleepTime from activeSleepTimeUs() 1909 - idleSleepTime from idleSleepTimeUs() 1910 - standbyDelay from mActiveSleepTimeUs (DIRECT only) 1911 - maxPeriod from frame count and sample rate (MIXER only) 1912 1913The parameters that affect these derived values are: 1914 - frame count 1915 - frame size 1916 - sample rate 1917 - device type: A2DP or not 1918 - device latency 1919 - format: PCM or not 1920 - active sleep time 1921 - idle sleep time 1922*/ 1923 1924void AudioFlinger::PlaybackThread::cacheParameters_l() 1925{ 1926 mixBufferSize = mNormalFrameCount * mFrameSize; 1927 activeSleepTime = activeSleepTimeUs(); 1928 idleSleepTime = idleSleepTimeUs(); 1929} 1930 1931void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType) 1932{ 1933 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d", 1934 this, streamType, mTracks.size()); 1935 Mutex::Autolock _l(mLock); 1936 1937 size_t size = mTracks.size(); 1938 for (size_t i = 0; i < size; i++) { 1939 sp<Track> t = mTracks[i]; 1940 if (t->streamType() == streamType) { 1941 t->invalidate(); 1942 } 1943 } 1944} 1945 1946status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain) 1947{ 1948 int session = chain->sessionId(); 1949 int16_t *buffer = mMixBuffer; 1950 bool ownsBuffer = false; 1951 1952 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session); 1953 if (session > 0) { 1954 // Only one effect chain can be present in direct output thread and it uses 1955 // the mix buffer as input 1956 if (mType != DIRECT) { 1957 size_t numSamples = mNormalFrameCount * mChannelCount; 1958 buffer = new int16_t[numSamples]; 1959 memset(buffer, 0, numSamples * sizeof(int16_t)); 1960 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session); 1961 ownsBuffer = true; 1962 } 1963 1964 // Attach all tracks with same session ID to this chain. 1965 for (size_t i = 0; i < mTracks.size(); ++i) { 1966 sp<Track> track = mTracks[i]; 1967 if (session == track->sessionId()) { 1968 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), 1969 buffer); 1970 track->setMainBuffer(buffer); 1971 chain->incTrackCnt(); 1972 } 1973 } 1974 1975 // indicate all active tracks in the chain 1976 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) { 1977 sp<Track> track = mActiveTracks[i].promote(); 1978 if (track == 0) { 1979 continue; 1980 } 1981 if (session == track->sessionId()) { 1982 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session); 1983 chain->incActiveTrackCnt(); 1984 } 1985 } 1986 } 1987 1988 chain->setInBuffer(buffer, ownsBuffer); 1989 chain->setOutBuffer(mMixBuffer); 1990 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect 1991 // chains list in order to be processed last as it contains output stage effects 1992 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before 1993 // session AUDIO_SESSION_OUTPUT_STAGE to be processed 1994 // after track specific effects and before output stage 1995 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and 1996 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX 1997 // Effect chain for other sessions are inserted at beginning of effect 1998 // chains list to be processed before output mix effects. Relative order between other 1999 // sessions is not important 2000 size_t size = mEffectChains.size(); 2001 size_t i = 0; 2002 for (i = 0; i < size; i++) { 2003 if (mEffectChains[i]->sessionId() < session) { 2004 break; 2005 } 2006 } 2007 mEffectChains.insertAt(chain, i); 2008 checkSuspendOnAddEffectChain_l(chain); 2009 2010 return NO_ERROR; 2011} 2012 2013size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain) 2014{ 2015 int session = chain->sessionId(); 2016 2017 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session); 2018 2019 for (size_t i = 0; i < mEffectChains.size(); i++) { 2020 if (chain == mEffectChains[i]) { 2021 mEffectChains.removeAt(i); 2022 // detach all active tracks from the chain 2023 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) { 2024 sp<Track> track = mActiveTracks[i].promote(); 2025 if (track == 0) { 2026 continue; 2027 } 2028 if (session == track->sessionId()) { 2029 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d", 2030 chain.get(), session); 2031 chain->decActiveTrackCnt(); 2032 } 2033 } 2034 2035 // detach all tracks with same session ID from this chain 2036 for (size_t i = 0; i < mTracks.size(); ++i) { 2037 sp<Track> track = mTracks[i]; 2038 if (session == track->sessionId()) { 2039 track->setMainBuffer(mMixBuffer); 2040 chain->decTrackCnt(); 2041 } 2042 } 2043 break; 2044 } 2045 } 2046 return mEffectChains.size(); 2047} 2048 2049status_t AudioFlinger::PlaybackThread::attachAuxEffect( 2050 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId) 2051{ 2052 Mutex::Autolock _l(mLock); 2053 return attachAuxEffect_l(track, EffectId); 2054} 2055 2056status_t AudioFlinger::PlaybackThread::attachAuxEffect_l( 2057 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId) 2058{ 2059 status_t status = NO_ERROR; 2060 2061 if (EffectId == 0) { 2062 track->setAuxBuffer(0, NULL); 2063 } else { 2064 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX 2065 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId); 2066 if (effect != 0) { 2067 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 2068 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer()); 2069 } else { 2070 status = INVALID_OPERATION; 2071 } 2072 } else { 2073 status = BAD_VALUE; 2074 } 2075 } 2076 return status; 2077} 2078 2079void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId) 2080{ 2081 for (size_t i = 0; i < mTracks.size(); ++i) { 2082 sp<Track> track = mTracks[i]; 2083 if (track->auxEffectId() == effectId) { 2084 attachAuxEffect_l(track, 0); 2085 } 2086 } 2087} 2088 2089bool AudioFlinger::PlaybackThread::threadLoop() 2090{ 2091 Vector< sp<Track> > tracksToRemove; 2092 2093 standbyTime = systemTime(); 2094 2095 // MIXER 2096 nsecs_t lastWarning = 0; 2097 2098 // DUPLICATING 2099 // FIXME could this be made local to while loop? 2100 writeFrames = 0; 2101 2102 cacheParameters_l(); 2103 sleepTime = idleSleepTime; 2104 2105 if (mType == MIXER) { 2106 sleepTimeShift = 0; 2107 } 2108 2109 CpuStats cpuStats; 2110 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid())); 2111 2112 acquireWakeLock(); 2113 2114 // mNBLogWriter->log can only be called while thread mutex mLock is held. 2115 // So if you need to log when mutex is unlocked, set logString to a non-NULL string, 2116 // and then that string will be logged at the next convenient opportunity. 2117 const char *logString = NULL; 2118 2119 checkSilentMode_l(); 2120 2121 while (!exitPending()) 2122 { 2123 cpuStats.sample(myName); 2124 2125 Vector< sp<EffectChain> > effectChains; 2126 2127 processConfigEvents(); 2128 2129 { // scope for mLock 2130 2131 Mutex::Autolock _l(mLock); 2132 2133 if (logString != NULL) { 2134 mNBLogWriter->logTimestamp(); 2135 mNBLogWriter->log(logString); 2136 logString = NULL; 2137 } 2138 2139 if (mLatchDValid) { 2140 mLatchQ = mLatchD; 2141 mLatchDValid = false; 2142 mLatchQValid = true; 2143 } 2144 2145 if (checkForNewParameters_l()) { 2146 cacheParameters_l(); 2147 } 2148 2149 saveOutputTracks(); 2150 if (mSignalPending) { 2151 // A signal was raised while we were unlocked 2152 mSignalPending = false; 2153 } else if (waitingAsyncCallback_l()) { 2154 if (exitPending()) { 2155 break; 2156 } 2157 releaseWakeLock_l(); 2158 ALOGV("wait async completion"); 2159 mWaitWorkCV.wait(mLock); 2160 ALOGV("async completion/wake"); 2161 acquireWakeLock_l(); 2162 standbyTime = systemTime() + standbyDelay; 2163 sleepTime = 0; 2164 2165 continue; 2166 } 2167 if ((!mActiveTracks.size() && systemTime() > standbyTime) || 2168 isSuspended()) { 2169 // put audio hardware into standby after short delay 2170 if (shouldStandby_l()) { 2171 2172 threadLoop_standby(); 2173 2174 mStandby = true; 2175 } 2176 2177 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) { 2178 // we're about to wait, flush the binder command buffer 2179 IPCThreadState::self()->flushCommands(); 2180 2181 clearOutputTracks(); 2182 2183 if (exitPending()) { 2184 break; 2185 } 2186 2187 releaseWakeLock_l(); 2188 // wait until we have something to do... 2189 ALOGV("%s going to sleep", myName.string()); 2190 mWaitWorkCV.wait(mLock); 2191 ALOGV("%s waking up", myName.string()); 2192 acquireWakeLock_l(); 2193 2194 mMixerStatus = MIXER_IDLE; 2195 mMixerStatusIgnoringFastTracks = MIXER_IDLE; 2196 mBytesWritten = 0; 2197 mBytesRemaining = 0; 2198 checkSilentMode_l(); 2199 2200 standbyTime = systemTime() + standbyDelay; 2201 sleepTime = idleSleepTime; 2202 if (mType == MIXER) { 2203 sleepTimeShift = 0; 2204 } 2205 2206 continue; 2207 } 2208 } 2209 // mMixerStatusIgnoringFastTracks is also updated internally 2210 mMixerStatus = prepareTracks_l(&tracksToRemove); 2211 2212 // prevent any changes in effect chain list and in each effect chain 2213 // during mixing and effect process as the audio buffers could be deleted 2214 // or modified if an effect is created or deleted 2215 lockEffectChains_l(effectChains); 2216 } 2217 2218 if (mBytesRemaining == 0) { 2219 mCurrentWriteLength = 0; 2220 if (mMixerStatus == MIXER_TRACKS_READY) { 2221 // threadLoop_mix() sets mCurrentWriteLength 2222 threadLoop_mix(); 2223 } else if ((mMixerStatus != MIXER_DRAIN_TRACK) 2224 && (mMixerStatus != MIXER_DRAIN_ALL)) { 2225 // threadLoop_sleepTime sets sleepTime to 0 if data 2226 // must be written to HAL 2227 threadLoop_sleepTime(); 2228 if (sleepTime == 0) { 2229 mCurrentWriteLength = mixBufferSize; 2230 } 2231 } 2232 mBytesRemaining = mCurrentWriteLength; 2233 if (isSuspended()) { 2234 sleepTime = suspendSleepTimeUs(); 2235 // simulate write to HAL when suspended 2236 mBytesWritten += mixBufferSize; 2237 mBytesRemaining = 0; 2238 } 2239 2240 // only process effects if we're going to write 2241 if (sleepTime == 0 && mType != OFFLOAD) { 2242 for (size_t i = 0; i < effectChains.size(); i ++) { 2243 effectChains[i]->process_l(); 2244 } 2245 } 2246 } 2247 // Process effect chains for offloaded thread even if no audio 2248 // was read from audio track: process only updates effect state 2249 // and thus does have to be synchronized with audio writes but may have 2250 // to be called while waiting for async write callback 2251 if (mType == OFFLOAD) { 2252 for (size_t i = 0; i < effectChains.size(); i ++) { 2253 effectChains[i]->process_l(); 2254 } 2255 } 2256 2257 // enable changes in effect chain 2258 unlockEffectChains(effectChains); 2259 2260 if (!waitingAsyncCallback()) { 2261 // sleepTime == 0 means we must write to audio hardware 2262 if (sleepTime == 0) { 2263 if (mBytesRemaining) { 2264 ssize_t ret = threadLoop_write(); 2265 if (ret < 0) { 2266 mBytesRemaining = 0; 2267 } else { 2268 mBytesWritten += ret; 2269 mBytesRemaining -= ret; 2270 } 2271 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) || 2272 (mMixerStatus == MIXER_DRAIN_ALL)) { 2273 threadLoop_drain(); 2274 } 2275if (mType == MIXER) { 2276 // write blocked detection 2277 nsecs_t now = systemTime(); 2278 nsecs_t delta = now - mLastWriteTime; 2279 if (!mStandby && delta > maxPeriod) { 2280 mNumDelayedWrites++; 2281 if ((now - lastWarning) > kWarningThrottleNs) { 2282 ATRACE_NAME("underrun"); 2283 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p", 2284 ns2ms(delta), mNumDelayedWrites, this); 2285 lastWarning = now; 2286 } 2287 } 2288} 2289 2290 mStandby = false; 2291 } else { 2292 usleep(sleepTime); 2293 } 2294 } 2295 2296 // Finally let go of removed track(s), without the lock held 2297 // since we can't guarantee the destructors won't acquire that 2298 // same lock. This will also mutate and push a new fast mixer state. 2299 threadLoop_removeTracks(tracksToRemove); 2300 tracksToRemove.clear(); 2301 2302 // FIXME I don't understand the need for this here; 2303 // it was in the original code but maybe the 2304 // assignment in saveOutputTracks() makes this unnecessary? 2305 clearOutputTracks(); 2306 2307 // Effect chains will be actually deleted here if they were removed from 2308 // mEffectChains list during mixing or effects processing 2309 effectChains.clear(); 2310 2311 // FIXME Note that the above .clear() is no longer necessary since effectChains 2312 // is now local to this block, but will keep it for now (at least until merge done). 2313 } 2314 2315 threadLoop_exit(); 2316 2317 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ... 2318 if (mType == MIXER || mType == DIRECT || mType == OFFLOAD) { 2319 // put output stream into standby mode 2320 if (!mStandby) { 2321 mOutput->stream->common.standby(&mOutput->stream->common); 2322 } 2323 } 2324 2325 releaseWakeLock(); 2326 2327 ALOGV("Thread %p type %d exiting", this, mType); 2328 return false; 2329} 2330 2331// removeTracks_l() must be called with ThreadBase::mLock held 2332void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove) 2333{ 2334 size_t count = tracksToRemove.size(); 2335 if (count) { 2336 for (size_t i=0 ; i<count ; i++) { 2337 const sp<Track>& track = tracksToRemove.itemAt(i); 2338 mActiveTracks.remove(track); 2339 ALOGV("removeTracks_l removing track on session %d", track->sessionId()); 2340 sp<EffectChain> chain = getEffectChain_l(track->sessionId()); 2341 if (chain != 0) { 2342 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), 2343 track->sessionId()); 2344 chain->decActiveTrackCnt(); 2345 } 2346 if (track->isTerminated()) { 2347 removeTrack_l(track); 2348 } 2349 } 2350 } 2351 2352} 2353 2354status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp) 2355{ 2356 if (mNormalSink != 0) { 2357 return mNormalSink->getTimestamp(timestamp); 2358 } 2359 if (mType == OFFLOAD && mOutput->stream->get_presentation_position) { 2360 uint64_t position64; 2361 int ret = mOutput->stream->get_presentation_position( 2362 mOutput->stream, &position64, ×tamp.mTime); 2363 if (ret == 0) { 2364 timestamp.mPosition = (uint32_t)position64; 2365 return NO_ERROR; 2366 } 2367 } 2368 return INVALID_OPERATION; 2369} 2370// ---------------------------------------------------------------------------- 2371 2372AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, 2373 audio_io_handle_t id, audio_devices_t device, type_t type) 2374 : PlaybackThread(audioFlinger, output, id, device, type), 2375 // mAudioMixer below 2376 // mFastMixer below 2377 mFastMixerFutex(0) 2378 // mOutputSink below 2379 // mPipeSink below 2380 // mNormalSink below 2381{ 2382 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type); 2383 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, " 2384 "mFrameCount=%d, mNormalFrameCount=%d", 2385 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount, 2386 mNormalFrameCount); 2387 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate); 2388 2389 // FIXME - Current mixer implementation only supports stereo output 2390 if (mChannelCount != FCC_2) { 2391 ALOGE("Invalid audio hardware channel count %d", mChannelCount); 2392 } 2393 2394 // create an NBAIO sink for the HAL output stream, and negotiate 2395 mOutputSink = new AudioStreamOutSink(output->stream); 2396 size_t numCounterOffers = 0; 2397 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)}; 2398 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers); 2399 ALOG_ASSERT(index == 0); 2400 2401 // initialize fast mixer depending on configuration 2402 bool initFastMixer; 2403 switch (kUseFastMixer) { 2404 case FastMixer_Never: 2405 initFastMixer = false; 2406 break; 2407 case FastMixer_Always: 2408 initFastMixer = true; 2409 break; 2410 case FastMixer_Static: 2411 case FastMixer_Dynamic: 2412 initFastMixer = mFrameCount < mNormalFrameCount; 2413 break; 2414 } 2415 if (initFastMixer) { 2416 2417 // create a MonoPipe to connect our submix to FastMixer 2418 NBAIO_Format format = mOutputSink->format(); 2419 // This pipe depth compensates for scheduling latency of the normal mixer thread. 2420 // When it wakes up after a maximum latency, it runs a few cycles quickly before 2421 // finally blocking. Note the pipe implementation rounds up the request to a power of 2. 2422 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/); 2423 const NBAIO_Format offers[1] = {format}; 2424 size_t numCounterOffers = 0; 2425 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers); 2426 ALOG_ASSERT(index == 0); 2427 monoPipe->setAvgFrames((mScreenState & 1) ? 2428 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2); 2429 mPipeSink = monoPipe; 2430 2431#ifdef TEE_SINK 2432 if (mTeeSinkOutputEnabled) { 2433 // create a Pipe to archive a copy of FastMixer's output for dumpsys 2434 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, format); 2435 numCounterOffers = 0; 2436 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers); 2437 ALOG_ASSERT(index == 0); 2438 mTeeSink = teeSink; 2439 PipeReader *teeSource = new PipeReader(*teeSink); 2440 numCounterOffers = 0; 2441 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers); 2442 ALOG_ASSERT(index == 0); 2443 mTeeSource = teeSource; 2444 } 2445#endif 2446 2447 // create fast mixer and configure it initially with just one fast track for our submix 2448 mFastMixer = new FastMixer(); 2449 FastMixerStateQueue *sq = mFastMixer->sq(); 2450#ifdef STATE_QUEUE_DUMP 2451 sq->setObserverDump(&mStateQueueObserverDump); 2452 sq->setMutatorDump(&mStateQueueMutatorDump); 2453#endif 2454 FastMixerState *state = sq->begin(); 2455 FastTrack *fastTrack = &state->mFastTracks[0]; 2456 // wrap the source side of the MonoPipe to make it an AudioBufferProvider 2457 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe)); 2458 fastTrack->mVolumeProvider = NULL; 2459 fastTrack->mGeneration++; 2460 state->mFastTracksGen++; 2461 state->mTrackMask = 1; 2462 // fast mixer will use the HAL output sink 2463 state->mOutputSink = mOutputSink.get(); 2464 state->mOutputSinkGen++; 2465 state->mFrameCount = mFrameCount; 2466 state->mCommand = FastMixerState::COLD_IDLE; 2467 // already done in constructor initialization list 2468 //mFastMixerFutex = 0; 2469 state->mColdFutexAddr = &mFastMixerFutex; 2470 state->mColdGen++; 2471 state->mDumpState = &mFastMixerDumpState; 2472#ifdef TEE_SINK 2473 state->mTeeSink = mTeeSink.get(); 2474#endif 2475 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer"); 2476 state->mNBLogWriter = mFastMixerNBLogWriter.get(); 2477 sq->end(); 2478 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED); 2479 2480 // start the fast mixer 2481 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO); 2482 pid_t tid = mFastMixer->getTid(); 2483 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer); 2484 if (err != 0) { 2485 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d", 2486 kPriorityFastMixer, getpid_cached, tid, err); 2487 } 2488 2489#ifdef AUDIO_WATCHDOG 2490 // create and start the watchdog 2491 mAudioWatchdog = new AudioWatchdog(); 2492 mAudioWatchdog->setDump(&mAudioWatchdogDump); 2493 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO); 2494 tid = mAudioWatchdog->getTid(); 2495 err = requestPriority(getpid_cached, tid, kPriorityFastMixer); 2496 if (err != 0) { 2497 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d", 2498 kPriorityFastMixer, getpid_cached, tid, err); 2499 } 2500#endif 2501 2502 } else { 2503 mFastMixer = NULL; 2504 } 2505 2506 switch (kUseFastMixer) { 2507 case FastMixer_Never: 2508 case FastMixer_Dynamic: 2509 mNormalSink = mOutputSink; 2510 break; 2511 case FastMixer_Always: 2512 mNormalSink = mPipeSink; 2513 break; 2514 case FastMixer_Static: 2515 mNormalSink = initFastMixer ? mPipeSink : mOutputSink; 2516 break; 2517 } 2518} 2519 2520AudioFlinger::MixerThread::~MixerThread() 2521{ 2522 if (mFastMixer != NULL) { 2523 FastMixerStateQueue *sq = mFastMixer->sq(); 2524 FastMixerState *state = sq->begin(); 2525 if (state->mCommand == FastMixerState::COLD_IDLE) { 2526 int32_t old = android_atomic_inc(&mFastMixerFutex); 2527 if (old == -1) { 2528 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1); 2529 } 2530 } 2531 state->mCommand = FastMixerState::EXIT; 2532 sq->end(); 2533 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED); 2534 mFastMixer->join(); 2535 // Though the fast mixer thread has exited, it's state queue is still valid. 2536 // We'll use that extract the final state which contains one remaining fast track 2537 // corresponding to our sub-mix. 2538 state = sq->begin(); 2539 ALOG_ASSERT(state->mTrackMask == 1); 2540 FastTrack *fastTrack = &state->mFastTracks[0]; 2541 ALOG_ASSERT(fastTrack->mBufferProvider != NULL); 2542 delete fastTrack->mBufferProvider; 2543 sq->end(false /*didModify*/); 2544 delete mFastMixer; 2545#ifdef AUDIO_WATCHDOG 2546 if (mAudioWatchdog != 0) { 2547 mAudioWatchdog->requestExit(); 2548 mAudioWatchdog->requestExitAndWait(); 2549 mAudioWatchdog.clear(); 2550 } 2551#endif 2552 } 2553 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter); 2554 delete mAudioMixer; 2555} 2556 2557 2558uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const 2559{ 2560 if (mFastMixer != NULL) { 2561 MonoPipe *pipe = (MonoPipe *)mPipeSink.get(); 2562 latency += (pipe->getAvgFrames() * 1000) / mSampleRate; 2563 } 2564 return latency; 2565} 2566 2567 2568void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove) 2569{ 2570 PlaybackThread::threadLoop_removeTracks(tracksToRemove); 2571} 2572 2573ssize_t AudioFlinger::MixerThread::threadLoop_write() 2574{ 2575 // FIXME we should only do one push per cycle; confirm this is true 2576 // Start the fast mixer if it's not already running 2577 if (mFastMixer != NULL) { 2578 FastMixerStateQueue *sq = mFastMixer->sq(); 2579 FastMixerState *state = sq->begin(); 2580 if (state->mCommand != FastMixerState::MIX_WRITE && 2581 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) { 2582 if (state->mCommand == FastMixerState::COLD_IDLE) { 2583 int32_t old = android_atomic_inc(&mFastMixerFutex); 2584 if (old == -1) { 2585 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1); 2586 } 2587#ifdef AUDIO_WATCHDOG 2588 if (mAudioWatchdog != 0) { 2589 mAudioWatchdog->resume(); 2590 } 2591#endif 2592 } 2593 state->mCommand = FastMixerState::MIX_WRITE; 2594 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ? 2595 FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN); 2596 sq->end(); 2597 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED); 2598 if (kUseFastMixer == FastMixer_Dynamic) { 2599 mNormalSink = mPipeSink; 2600 } 2601 } else { 2602 sq->end(false /*didModify*/); 2603 } 2604 } 2605 return PlaybackThread::threadLoop_write(); 2606} 2607 2608void AudioFlinger::MixerThread::threadLoop_standby() 2609{ 2610 // Idle the fast mixer if it's currently running 2611 if (mFastMixer != NULL) { 2612 FastMixerStateQueue *sq = mFastMixer->sq(); 2613 FastMixerState *state = sq->begin(); 2614 if (!(state->mCommand & FastMixerState::IDLE)) { 2615 state->mCommand = FastMixerState::COLD_IDLE; 2616 state->mColdFutexAddr = &mFastMixerFutex; 2617 state->mColdGen++; 2618 mFastMixerFutex = 0; 2619 sq->end(); 2620 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now 2621 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED); 2622 if (kUseFastMixer == FastMixer_Dynamic) { 2623 mNormalSink = mOutputSink; 2624 } 2625#ifdef AUDIO_WATCHDOG 2626 if (mAudioWatchdog != 0) { 2627 mAudioWatchdog->pause(); 2628 } 2629#endif 2630 } else { 2631 sq->end(false /*didModify*/); 2632 } 2633 } 2634 PlaybackThread::threadLoop_standby(); 2635} 2636 2637// Empty implementation for standard mixer 2638// Overridden for offloaded playback 2639void AudioFlinger::PlaybackThread::flushOutput_l() 2640{ 2641} 2642 2643bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l() 2644{ 2645 return false; 2646} 2647 2648bool AudioFlinger::PlaybackThread::shouldStandby_l() 2649{ 2650 return !mStandby; 2651} 2652 2653bool AudioFlinger::PlaybackThread::waitingAsyncCallback() 2654{ 2655 Mutex::Autolock _l(mLock); 2656 return waitingAsyncCallback_l(); 2657} 2658 2659// shared by MIXER and DIRECT, overridden by DUPLICATING 2660void AudioFlinger::PlaybackThread::threadLoop_standby() 2661{ 2662 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended); 2663 mOutput->stream->common.standby(&mOutput->stream->common); 2664 if (mUseAsyncWrite != 0) { 2665 // discard any pending drain or write ack by incrementing sequence 2666 mWriteAckSequence = (mWriteAckSequence + 2) & ~1; 2667 mDrainSequence = (mDrainSequence + 2) & ~1; 2668 ALOG_ASSERT(mCallbackThread != 0); 2669 mCallbackThread->setWriteBlocked(mWriteAckSequence); 2670 mCallbackThread->setDraining(mDrainSequence); 2671 } 2672} 2673 2674void AudioFlinger::MixerThread::threadLoop_mix() 2675{ 2676 // obtain the presentation timestamp of the next output buffer 2677 int64_t pts; 2678 status_t status = INVALID_OPERATION; 2679 2680 if (mNormalSink != 0) { 2681 status = mNormalSink->getNextWriteTimestamp(&pts); 2682 } else { 2683 status = mOutputSink->getNextWriteTimestamp(&pts); 2684 } 2685 2686 if (status != NO_ERROR) { 2687 pts = AudioBufferProvider::kInvalidPTS; 2688 } 2689 2690 // mix buffers... 2691 mAudioMixer->process(pts); 2692 mCurrentWriteLength = mixBufferSize; 2693 // increase sleep time progressively when application underrun condition clears. 2694 // Only increase sleep time if the mixer is ready for two consecutive times to avoid 2695 // that a steady state of alternating ready/not ready conditions keeps the sleep time 2696 // such that we would underrun the audio HAL. 2697 if ((sleepTime == 0) && (sleepTimeShift > 0)) { 2698 sleepTimeShift--; 2699 } 2700 sleepTime = 0; 2701 standbyTime = systemTime() + standbyDelay; 2702 //TODO: delay standby when effects have a tail 2703} 2704 2705void AudioFlinger::MixerThread::threadLoop_sleepTime() 2706{ 2707 // If no tracks are ready, sleep once for the duration of an output 2708 // buffer size, then write 0s to the output 2709 if (sleepTime == 0) { 2710 if (mMixerStatus == MIXER_TRACKS_ENABLED) { 2711 sleepTime = activeSleepTime >> sleepTimeShift; 2712 if (sleepTime < kMinThreadSleepTimeUs) { 2713 sleepTime = kMinThreadSleepTimeUs; 2714 } 2715 // reduce sleep time in case of consecutive application underruns to avoid 2716 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer 2717 // duration we would end up writing less data than needed by the audio HAL if 2718 // the condition persists. 2719 if (sleepTimeShift < kMaxThreadSleepTimeShift) { 2720 sleepTimeShift++; 2721 } 2722 } else { 2723 sleepTime = idleSleepTime; 2724 } 2725 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) { 2726 memset (mMixBuffer, 0, mixBufferSize); 2727 sleepTime = 0; 2728 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED), 2729 "anticipated start"); 2730 } 2731 // TODO add standby time extension fct of effect tail 2732} 2733 2734// prepareTracks_l() must be called with ThreadBase::mLock held 2735AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l( 2736 Vector< sp<Track> > *tracksToRemove) 2737{ 2738 2739 mixer_state mixerStatus = MIXER_IDLE; 2740 // find out which tracks need to be processed 2741 size_t count = mActiveTracks.size(); 2742 size_t mixedTracks = 0; 2743 size_t tracksWithEffect = 0; 2744 // counts only _active_ fast tracks 2745 size_t fastTracks = 0; 2746 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset 2747 2748 float masterVolume = mMasterVolume; 2749 bool masterMute = mMasterMute; 2750 2751 if (masterMute) { 2752 masterVolume = 0; 2753 } 2754 // Delegate master volume control to effect in output mix effect chain if needed 2755 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX); 2756 if (chain != 0) { 2757 uint32_t v = (uint32_t)(masterVolume * (1 << 24)); 2758 chain->setVolume_l(&v, &v); 2759 masterVolume = (float)((v + (1 << 23)) >> 24); 2760 chain.clear(); 2761 } 2762 2763 // prepare a new state to push 2764 FastMixerStateQueue *sq = NULL; 2765 FastMixerState *state = NULL; 2766 bool didModify = false; 2767 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED; 2768 if (mFastMixer != NULL) { 2769 sq = mFastMixer->sq(); 2770 state = sq->begin(); 2771 } 2772 2773 for (size_t i=0 ; i<count ; i++) { 2774 const sp<Track> t = mActiveTracks[i].promote(); 2775 if (t == 0) { 2776 continue; 2777 } 2778 2779 // this const just means the local variable doesn't change 2780 Track* const track = t.get(); 2781 2782 // process fast tracks 2783 if (track->isFastTrack()) { 2784 2785 // It's theoretically possible (though unlikely) for a fast track to be created 2786 // and then removed within the same normal mix cycle. This is not a problem, as 2787 // the track never becomes active so it's fast mixer slot is never touched. 2788 // The converse, of removing an (active) track and then creating a new track 2789 // at the identical fast mixer slot within the same normal mix cycle, 2790 // is impossible because the slot isn't marked available until the end of each cycle. 2791 int j = track->mFastIndex; 2792 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks); 2793 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j))); 2794 FastTrack *fastTrack = &state->mFastTracks[j]; 2795 2796 // Determine whether the track is currently in underrun condition, 2797 // and whether it had a recent underrun. 2798 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j]; 2799 FastTrackUnderruns underruns = ftDump->mUnderruns; 2800 uint32_t recentFull = (underruns.mBitFields.mFull - 2801 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK; 2802 uint32_t recentPartial = (underruns.mBitFields.mPartial - 2803 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK; 2804 uint32_t recentEmpty = (underruns.mBitFields.mEmpty - 2805 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK; 2806 uint32_t recentUnderruns = recentPartial + recentEmpty; 2807 track->mObservedUnderruns = underruns; 2808 // don't count underruns that occur while stopping or pausing 2809 // or stopped which can occur when flush() is called while active 2810 if (!(track->isStopping() || track->isPausing() || track->isStopped()) && 2811 recentUnderruns > 0) { 2812 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun 2813 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount); 2814 } 2815 2816 // This is similar to the state machine for normal tracks, 2817 // with a few modifications for fast tracks. 2818 bool isActive = true; 2819 switch (track->mState) { 2820 case TrackBase::STOPPING_1: 2821 // track stays active in STOPPING_1 state until first underrun 2822 if (recentUnderruns > 0 || track->isTerminated()) { 2823 track->mState = TrackBase::STOPPING_2; 2824 } 2825 break; 2826 case TrackBase::PAUSING: 2827 // ramp down is not yet implemented 2828 track->setPaused(); 2829 break; 2830 case TrackBase::RESUMING: 2831 // ramp up is not yet implemented 2832 track->mState = TrackBase::ACTIVE; 2833 break; 2834 case TrackBase::ACTIVE: 2835 if (recentFull > 0 || recentPartial > 0) { 2836 // track has provided at least some frames recently: reset retry count 2837 track->mRetryCount = kMaxTrackRetries; 2838 } 2839 if (recentUnderruns == 0) { 2840 // no recent underruns: stay active 2841 break; 2842 } 2843 // there has recently been an underrun of some kind 2844 if (track->sharedBuffer() == 0) { 2845 // were any of the recent underruns "empty" (no frames available)? 2846 if (recentEmpty == 0) { 2847 // no, then ignore the partial underruns as they are allowed indefinitely 2848 break; 2849 } 2850 // there has recently been an "empty" underrun: decrement the retry counter 2851 if (--(track->mRetryCount) > 0) { 2852 break; 2853 } 2854 // indicate to client process that the track was disabled because of underrun; 2855 // it will then automatically call start() when data is available 2856 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags); 2857 // remove from active list, but state remains ACTIVE [confusing but true] 2858 isActive = false; 2859 break; 2860 } 2861 // fall through 2862 case TrackBase::STOPPING_2: 2863 case TrackBase::PAUSED: 2864 case TrackBase::STOPPED: 2865 case TrackBase::FLUSHED: // flush() while active 2866 // Check for presentation complete if track is inactive 2867 // We have consumed all the buffers of this track. 2868 // This would be incomplete if we auto-paused on underrun 2869 { 2870 size_t audioHALFrames = 2871 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000; 2872 size_t framesWritten = mBytesWritten / mFrameSize; 2873 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) { 2874 // track stays in active list until presentation is complete 2875 break; 2876 } 2877 } 2878 if (track->isStopping_2()) { 2879 track->mState = TrackBase::STOPPED; 2880 } 2881 if (track->isStopped()) { 2882 // Can't reset directly, as fast mixer is still polling this track 2883 // track->reset(); 2884 // So instead mark this track as needing to be reset after push with ack 2885 resetMask |= 1 << i; 2886 } 2887 isActive = false; 2888 break; 2889 case TrackBase::IDLE: 2890 default: 2891 LOG_FATAL("unexpected track state %d", track->mState); 2892 } 2893 2894 if (isActive) { 2895 // was it previously inactive? 2896 if (!(state->mTrackMask & (1 << j))) { 2897 ExtendedAudioBufferProvider *eabp = track; 2898 VolumeProvider *vp = track; 2899 fastTrack->mBufferProvider = eabp; 2900 fastTrack->mVolumeProvider = vp; 2901 fastTrack->mSampleRate = track->mSampleRate; 2902 fastTrack->mChannelMask = track->mChannelMask; 2903 fastTrack->mGeneration++; 2904 state->mTrackMask |= 1 << j; 2905 didModify = true; 2906 // no acknowledgement required for newly active tracks 2907 } 2908 // cache the combined master volume and stream type volume for fast mixer; this 2909 // lacks any synchronization or barrier so VolumeProvider may read a stale value 2910 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume; 2911 ++fastTracks; 2912 } else { 2913 // was it previously active? 2914 if (state->mTrackMask & (1 << j)) { 2915 fastTrack->mBufferProvider = NULL; 2916 fastTrack->mGeneration++; 2917 state->mTrackMask &= ~(1 << j); 2918 didModify = true; 2919 // If any fast tracks were removed, we must wait for acknowledgement 2920 // because we're about to decrement the last sp<> on those tracks. 2921 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED; 2922 } else { 2923 LOG_FATAL("fast track %d should have been active", j); 2924 } 2925 tracksToRemove->add(track); 2926 // Avoids a misleading display in dumpsys 2927 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL; 2928 } 2929 continue; 2930 } 2931 2932 { // local variable scope to avoid goto warning 2933 2934 audio_track_cblk_t* cblk = track->cblk(); 2935 2936 // The first time a track is added we wait 2937 // for all its buffers to be filled before processing it 2938 int name = track->name(); 2939 // make sure that we have enough frames to mix one full buffer. 2940 // enforce this condition only once to enable draining the buffer in case the client 2941 // app does not call stop() and relies on underrun to stop: 2942 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed 2943 // during last round 2944 size_t desiredFrames; 2945 uint32_t sr = track->sampleRate(); 2946 if (sr == mSampleRate) { 2947 desiredFrames = mNormalFrameCount; 2948 } else { 2949 // +1 for rounding and +1 for additional sample needed for interpolation 2950 desiredFrames = (mNormalFrameCount * sr) / mSampleRate + 1 + 1; 2951 // add frames already consumed but not yet released by the resampler 2952 // because cblk->framesReady() will include these frames 2953 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name()); 2954 // the minimum track buffer size is normally twice the number of frames necessary 2955 // to fill one buffer and the resampler should not leave more than one buffer worth 2956 // of unreleased frames after each pass, but just in case... 2957 ALOG_ASSERT(desiredFrames <= cblk->frameCount_); 2958 } 2959 uint32_t minFrames = 1; 2960 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() && 2961 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) { 2962 minFrames = desiredFrames; 2963 } 2964 // It's not safe to call framesReady() for a static buffer track, so assume it's ready 2965 size_t framesReady; 2966 if (track->sharedBuffer() == 0) { 2967 framesReady = track->framesReady(); 2968 } else if (track->isStopped()) { 2969 framesReady = 0; 2970 } else { 2971 framesReady = 1; 2972 } 2973 if ((framesReady >= minFrames) && track->isReady() && 2974 !track->isPaused() && !track->isTerminated()) 2975 { 2976 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this); 2977 2978 mixedTracks++; 2979 2980 // track->mainBuffer() != mMixBuffer means there is an effect chain 2981 // connected to the track 2982 chain.clear(); 2983 if (track->mainBuffer() != mMixBuffer) { 2984 chain = getEffectChain_l(track->sessionId()); 2985 // Delegate volume control to effect in track effect chain if needed 2986 if (chain != 0) { 2987 tracksWithEffect++; 2988 } else { 2989 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on " 2990 "session %d", 2991 name, track->sessionId()); 2992 } 2993 } 2994 2995 2996 int param = AudioMixer::VOLUME; 2997 if (track->mFillingUpStatus == Track::FS_FILLED) { 2998 // no ramp for the first volume setting 2999 track->mFillingUpStatus = Track::FS_ACTIVE; 3000 if (track->mState == TrackBase::RESUMING) { 3001 track->mState = TrackBase::ACTIVE; 3002 param = AudioMixer::RAMP_VOLUME; 3003 } 3004 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL); 3005 // FIXME should not make a decision based on mServer 3006 } else if (cblk->mServer != 0) { 3007 // If the track is stopped before the first frame was mixed, 3008 // do not apply ramp 3009 param = AudioMixer::RAMP_VOLUME; 3010 } 3011 3012 // compute volume for this track 3013 uint32_t vl, vr, va; 3014 if (track->isPausing() || mStreamTypes[track->streamType()].mute) { 3015 vl = vr = va = 0; 3016 if (track->isPausing()) { 3017 track->setPaused(); 3018 } 3019 } else { 3020 3021 // read original volumes with volume control 3022 float typeVolume = mStreamTypes[track->streamType()].volume; 3023 float v = masterVolume * typeVolume; 3024 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy; 3025 uint32_t vlr = proxy->getVolumeLR(); 3026 vl = vlr & 0xFFFF; 3027 vr = vlr >> 16; 3028 // track volumes come from shared memory, so can't be trusted and must be clamped 3029 if (vl > MAX_GAIN_INT) { 3030 ALOGV("Track left volume out of range: %04X", vl); 3031 vl = MAX_GAIN_INT; 3032 } 3033 if (vr > MAX_GAIN_INT) { 3034 ALOGV("Track right volume out of range: %04X", vr); 3035 vr = MAX_GAIN_INT; 3036 } 3037 // now apply the master volume and stream type volume 3038 vl = (uint32_t)(v * vl) << 12; 3039 vr = (uint32_t)(v * vr) << 12; 3040 // assuming master volume and stream type volume each go up to 1.0, 3041 // vl and vr are now in 8.24 format 3042 3043 uint16_t sendLevel = proxy->getSendLevel_U4_12(); 3044 // send level comes from shared memory and so may be corrupt 3045 if (sendLevel > MAX_GAIN_INT) { 3046 ALOGV("Track send level out of range: %04X", sendLevel); 3047 sendLevel = MAX_GAIN_INT; 3048 } 3049 va = (uint32_t)(v * sendLevel); 3050 } 3051 3052 // Delegate volume control to effect in track effect chain if needed 3053 if (chain != 0 && chain->setVolume_l(&vl, &vr)) { 3054 // Do not ramp volume if volume is controlled by effect 3055 param = AudioMixer::VOLUME; 3056 track->mHasVolumeController = true; 3057 } else { 3058 // force no volume ramp when volume controller was just disabled or removed 3059 // from effect chain to avoid volume spike 3060 if (track->mHasVolumeController) { 3061 param = AudioMixer::VOLUME; 3062 } 3063 track->mHasVolumeController = false; 3064 } 3065 3066 // Convert volumes from 8.24 to 4.12 format 3067 // This additional clamping is needed in case chain->setVolume_l() overshot 3068 vl = (vl + (1 << 11)) >> 12; 3069 if (vl > MAX_GAIN_INT) { 3070 vl = MAX_GAIN_INT; 3071 } 3072 vr = (vr + (1 << 11)) >> 12; 3073 if (vr > MAX_GAIN_INT) { 3074 vr = MAX_GAIN_INT; 3075 } 3076 3077 if (va > MAX_GAIN_INT) { 3078 va = MAX_GAIN_INT; // va is uint32_t, so no need to check for - 3079 } 3080 3081 // XXX: these things DON'T need to be done each time 3082 mAudioMixer->setBufferProvider(name, track); 3083 mAudioMixer->enable(name); 3084 3085 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl); 3086 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr); 3087 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va); 3088 mAudioMixer->setParameter( 3089 name, 3090 AudioMixer::TRACK, 3091 AudioMixer::FORMAT, (void *)track->format()); 3092 mAudioMixer->setParameter( 3093 name, 3094 AudioMixer::TRACK, 3095 AudioMixer::CHANNEL_MASK, (void *)track->channelMask()); 3096 // limit track sample rate to 2 x output sample rate, which changes at re-configuration 3097 uint32_t maxSampleRate = mSampleRate * 2; 3098 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate(); 3099 if (reqSampleRate == 0) { 3100 reqSampleRate = mSampleRate; 3101 } else if (reqSampleRate > maxSampleRate) { 3102 reqSampleRate = maxSampleRate; 3103 } 3104 mAudioMixer->setParameter( 3105 name, 3106 AudioMixer::RESAMPLE, 3107 AudioMixer::SAMPLE_RATE, 3108 (void *)reqSampleRate); 3109 mAudioMixer->setParameter( 3110 name, 3111 AudioMixer::TRACK, 3112 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer()); 3113 mAudioMixer->setParameter( 3114 name, 3115 AudioMixer::TRACK, 3116 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer()); 3117 3118 // reset retry count 3119 track->mRetryCount = kMaxTrackRetries; 3120 3121 // If one track is ready, set the mixer ready if: 3122 // - the mixer was not ready during previous round OR 3123 // - no other track is not ready 3124 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY || 3125 mixerStatus != MIXER_TRACKS_ENABLED) { 3126 mixerStatus = MIXER_TRACKS_READY; 3127 } 3128 } else { 3129 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) { 3130 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames); 3131 } 3132 // clear effect chain input buffer if an active track underruns to avoid sending 3133 // previous audio buffer again to effects 3134 chain = getEffectChain_l(track->sessionId()); 3135 if (chain != 0) { 3136 chain->clearInputBuffer(); 3137 } 3138 3139 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this); 3140 if ((track->sharedBuffer() != 0) || track->isTerminated() || 3141 track->isStopped() || track->isPaused()) { 3142 // We have consumed all the buffers of this track. 3143 // Remove it from the list of active tracks. 3144 // TODO: use actual buffer filling status instead of latency when available from 3145 // audio HAL 3146 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000; 3147 size_t framesWritten = mBytesWritten / mFrameSize; 3148 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) { 3149 if (track->isStopped()) { 3150 track->reset(); 3151 } 3152 tracksToRemove->add(track); 3153 } 3154 } else { 3155 // No buffers for this track. Give it a few chances to 3156 // fill a buffer, then remove it from active list. 3157 if (--(track->mRetryCount) <= 0) { 3158 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this); 3159 tracksToRemove->add(track); 3160 // indicate to client process that the track was disabled because of underrun; 3161 // it will then automatically call start() when data is available 3162 android_atomic_or(CBLK_DISABLED, &cblk->mFlags); 3163 // If one track is not ready, mark the mixer also not ready if: 3164 // - the mixer was ready during previous round OR 3165 // - no other track is ready 3166 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY || 3167 mixerStatus != MIXER_TRACKS_READY) { 3168 mixerStatus = MIXER_TRACKS_ENABLED; 3169 } 3170 } 3171 mAudioMixer->disable(name); 3172 } 3173 3174 } // local variable scope to avoid goto warning 3175track_is_ready: ; 3176 3177 } 3178 3179 // Push the new FastMixer state if necessary 3180 bool pauseAudioWatchdog = false; 3181 if (didModify) { 3182 state->mFastTracksGen++; 3183 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle 3184 if (kUseFastMixer == FastMixer_Dynamic && 3185 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) { 3186 state->mCommand = FastMixerState::COLD_IDLE; 3187 state->mColdFutexAddr = &mFastMixerFutex; 3188 state->mColdGen++; 3189 mFastMixerFutex = 0; 3190 if (kUseFastMixer == FastMixer_Dynamic) { 3191 mNormalSink = mOutputSink; 3192 } 3193 // If we go into cold idle, need to wait for acknowledgement 3194 // so that fast mixer stops doing I/O. 3195 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED; 3196 pauseAudioWatchdog = true; 3197 } 3198 } 3199 if (sq != NULL) { 3200 sq->end(didModify); 3201 sq->push(block); 3202 } 3203#ifdef AUDIO_WATCHDOG 3204 if (pauseAudioWatchdog && mAudioWatchdog != 0) { 3205 mAudioWatchdog->pause(); 3206 } 3207#endif 3208 3209 // Now perform the deferred reset on fast tracks that have stopped 3210 while (resetMask != 0) { 3211 size_t i = __builtin_ctz(resetMask); 3212 ALOG_ASSERT(i < count); 3213 resetMask &= ~(1 << i); 3214 sp<Track> t = mActiveTracks[i].promote(); 3215 if (t == 0) { 3216 continue; 3217 } 3218 Track* track = t.get(); 3219 ALOG_ASSERT(track->isFastTrack() && track->isStopped()); 3220 track->reset(); 3221 } 3222 3223 // remove all the tracks that need to be... 3224 removeTracks_l(*tracksToRemove); 3225 3226 // mix buffer must be cleared if all tracks are connected to an 3227 // effect chain as in this case the mixer will not write to 3228 // mix buffer and track effects will accumulate into it 3229 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || 3230 (mixedTracks == 0 && fastTracks > 0))) { 3231 // FIXME as a performance optimization, should remember previous zero status 3232 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t)); 3233 } 3234 3235 // if any fast tracks, then status is ready 3236 mMixerStatusIgnoringFastTracks = mixerStatus; 3237 if (fastTracks > 0) { 3238 mixerStatus = MIXER_TRACKS_READY; 3239 } 3240 return mixerStatus; 3241} 3242 3243// getTrackName_l() must be called with ThreadBase::mLock held 3244int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId) 3245{ 3246 return mAudioMixer->getTrackName(channelMask, sessionId); 3247} 3248 3249// deleteTrackName_l() must be called with ThreadBase::mLock held 3250void AudioFlinger::MixerThread::deleteTrackName_l(int name) 3251{ 3252 ALOGV("remove track (%d) and delete from mixer", name); 3253 mAudioMixer->deleteTrackName(name); 3254} 3255 3256// checkForNewParameters_l() must be called with ThreadBase::mLock held 3257bool AudioFlinger::MixerThread::checkForNewParameters_l() 3258{ 3259 // if !&IDLE, holds the FastMixer state to restore after new parameters processed 3260 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE; 3261 bool reconfig = false; 3262 3263 while (!mNewParameters.isEmpty()) { 3264 3265 if (mFastMixer != NULL) { 3266 FastMixerStateQueue *sq = mFastMixer->sq(); 3267 FastMixerState *state = sq->begin(); 3268 if (!(state->mCommand & FastMixerState::IDLE)) { 3269 previousCommand = state->mCommand; 3270 state->mCommand = FastMixerState::HOT_IDLE; 3271 sq->end(); 3272 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED); 3273 } else { 3274 sq->end(false /*didModify*/); 3275 } 3276 } 3277 3278 status_t status = NO_ERROR; 3279 String8 keyValuePair = mNewParameters[0]; 3280 AudioParameter param = AudioParameter(keyValuePair); 3281 int value; 3282 3283 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) { 3284 reconfig = true; 3285 } 3286 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) { 3287 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) { 3288 status = BAD_VALUE; 3289 } else { 3290 reconfig = true; 3291 } 3292 } 3293 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) { 3294 if ((audio_channel_mask_t) value != AUDIO_CHANNEL_OUT_STEREO) { 3295 status = BAD_VALUE; 3296 } else { 3297 reconfig = true; 3298 } 3299 } 3300 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) { 3301 // do not accept frame count changes if tracks are open as the track buffer 3302 // size depends on frame count and correct behavior would not be guaranteed 3303 // if frame count is changed after track creation 3304 if (!mTracks.isEmpty()) { 3305 status = INVALID_OPERATION; 3306 } else { 3307 reconfig = true; 3308 } 3309 } 3310 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) { 3311#ifdef ADD_BATTERY_DATA 3312 // when changing the audio output device, call addBatteryData to notify 3313 // the change 3314 if (mOutDevice != value) { 3315 uint32_t params = 0; 3316 // check whether speaker is on 3317 if (value & AUDIO_DEVICE_OUT_SPEAKER) { 3318 params |= IMediaPlayerService::kBatteryDataSpeakerOn; 3319 } 3320 3321 audio_devices_t deviceWithoutSpeaker 3322 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER; 3323 // check if any other device (except speaker) is on 3324 if (value & deviceWithoutSpeaker ) { 3325 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn; 3326 } 3327 3328 if (params != 0) { 3329 addBatteryData(params); 3330 } 3331 } 3332#endif 3333 3334 // forward device change to effects that have requested to be 3335 // aware of attached audio device. 3336 if (value != AUDIO_DEVICE_NONE) { 3337 mOutDevice = value; 3338 for (size_t i = 0; i < mEffectChains.size(); i++) { 3339 mEffectChains[i]->setDevice_l(mOutDevice); 3340 } 3341 } 3342 } 3343 3344 if (status == NO_ERROR) { 3345 status = mOutput->stream->common.set_parameters(&mOutput->stream->common, 3346 keyValuePair.string()); 3347 if (!mStandby && status == INVALID_OPERATION) { 3348 mOutput->stream->common.standby(&mOutput->stream->common); 3349 mStandby = true; 3350 mBytesWritten = 0; 3351 status = mOutput->stream->common.set_parameters(&mOutput->stream->common, 3352 keyValuePair.string()); 3353 } 3354 if (status == NO_ERROR && reconfig) { 3355 readOutputParameters(); 3356 delete mAudioMixer; 3357 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate); 3358 for (size_t i = 0; i < mTracks.size() ; i++) { 3359 int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId); 3360 if (name < 0) { 3361 break; 3362 } 3363 mTracks[i]->mName = name; 3364 } 3365 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED); 3366 } 3367 } 3368 3369 mNewParameters.removeAt(0); 3370 3371 mParamStatus = status; 3372 mParamCond.signal(); 3373 // wait for condition with time out in case the thread calling ThreadBase::setParameters() 3374 // already timed out waiting for the status and will never signal the condition. 3375 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs); 3376 } 3377 3378 if (!(previousCommand & FastMixerState::IDLE)) { 3379 ALOG_ASSERT(mFastMixer != NULL); 3380 FastMixerStateQueue *sq = mFastMixer->sq(); 3381 FastMixerState *state = sq->begin(); 3382 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE); 3383 state->mCommand = previousCommand; 3384 sq->end(); 3385 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED); 3386 } 3387 3388 return reconfig; 3389} 3390 3391 3392void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args) 3393{ 3394 const size_t SIZE = 256; 3395 char buffer[SIZE]; 3396 String8 result; 3397 3398 PlaybackThread::dumpInternals(fd, args); 3399 3400 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames()); 3401 result.append(buffer); 3402 write(fd, result.string(), result.size()); 3403 3404 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us 3405 const FastMixerDumpState copy(mFastMixerDumpState); 3406 copy.dump(fd); 3407 3408#ifdef STATE_QUEUE_DUMP 3409 // Similar for state queue 3410 StateQueueObserverDump observerCopy = mStateQueueObserverDump; 3411 observerCopy.dump(fd); 3412 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump; 3413 mutatorCopy.dump(fd); 3414#endif 3415 3416#ifdef TEE_SINK 3417 // Write the tee output to a .wav file 3418 dumpTee(fd, mTeeSource, mId); 3419#endif 3420 3421#ifdef AUDIO_WATCHDOG 3422 if (mAudioWatchdog != 0) { 3423 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us 3424 AudioWatchdogDump wdCopy = mAudioWatchdogDump; 3425 wdCopy.dump(fd); 3426 } 3427#endif 3428} 3429 3430uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const 3431{ 3432 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2; 3433} 3434 3435uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const 3436{ 3437 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000); 3438} 3439 3440void AudioFlinger::MixerThread::cacheParameters_l() 3441{ 3442 PlaybackThread::cacheParameters_l(); 3443 3444 // FIXME: Relaxed timing because of a certain device that can't meet latency 3445 // Should be reduced to 2x after the vendor fixes the driver issue 3446 // increase threshold again due to low power audio mode. The way this warning 3447 // threshold is calculated and its usefulness should be reconsidered anyway. 3448 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15; 3449} 3450 3451// ---------------------------------------------------------------------------- 3452 3453AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, 3454 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device) 3455 : PlaybackThread(audioFlinger, output, id, device, DIRECT) 3456 // mLeftVolFloat, mRightVolFloat 3457{ 3458} 3459 3460AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, 3461 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, 3462 ThreadBase::type_t type) 3463 : PlaybackThread(audioFlinger, output, id, device, type) 3464 // mLeftVolFloat, mRightVolFloat 3465{ 3466} 3467 3468AudioFlinger::DirectOutputThread::~DirectOutputThread() 3469{ 3470} 3471 3472void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack) 3473{ 3474 audio_track_cblk_t* cblk = track->cblk(); 3475 float left, right; 3476 3477 if (mMasterMute || mStreamTypes[track->streamType()].mute) { 3478 left = right = 0; 3479 } else { 3480 float typeVolume = mStreamTypes[track->streamType()].volume; 3481 float v = mMasterVolume * typeVolume; 3482 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy; 3483 uint32_t vlr = proxy->getVolumeLR(); 3484 float v_clamped = v * (vlr & 0xFFFF); 3485 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN; 3486 left = v_clamped/MAX_GAIN; 3487 v_clamped = v * (vlr >> 16); 3488 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN; 3489 right = v_clamped/MAX_GAIN; 3490 } 3491 3492 if (lastTrack) { 3493 if (left != mLeftVolFloat || right != mRightVolFloat) { 3494 mLeftVolFloat = left; 3495 mRightVolFloat = right; 3496 3497 // Convert volumes from float to 8.24 3498 uint32_t vl = (uint32_t)(left * (1 << 24)); 3499 uint32_t vr = (uint32_t)(right * (1 << 24)); 3500 3501 // Delegate volume control to effect in track effect chain if needed 3502 // only one effect chain can be present on DirectOutputThread, so if 3503 // there is one, the track is connected to it 3504 if (!mEffectChains.isEmpty()) { 3505 mEffectChains[0]->setVolume_l(&vl, &vr); 3506 left = (float)vl / (1 << 24); 3507 right = (float)vr / (1 << 24); 3508 } 3509 if (mOutput->stream->set_volume) { 3510 mOutput->stream->set_volume(mOutput->stream, left, right); 3511 } 3512 } 3513 } 3514} 3515 3516 3517AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l( 3518 Vector< sp<Track> > *tracksToRemove 3519) 3520{ 3521 size_t count = mActiveTracks.size(); 3522 mixer_state mixerStatus = MIXER_IDLE; 3523 3524 // find out which tracks need to be processed 3525 for (size_t i = 0; i < count; i++) { 3526 sp<Track> t = mActiveTracks[i].promote(); 3527 // The track died recently 3528 if (t == 0) { 3529 continue; 3530 } 3531 3532 Track* const track = t.get(); 3533 audio_track_cblk_t* cblk = track->cblk(); 3534 3535 // The first time a track is added we wait 3536 // for all its buffers to be filled before processing it 3537 uint32_t minFrames; 3538 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) { 3539 minFrames = mNormalFrameCount; 3540 } else { 3541 minFrames = 1; 3542 } 3543 // Only consider last track started for volume and mixer state control. 3544 // This is the last entry in mActiveTracks unless a track underruns. 3545 // As we only care about the transition phase between two tracks on a 3546 // direct output, it is not a problem to ignore the underrun case. 3547 bool last = (i == (count - 1)); 3548 3549 if ((track->framesReady() >= minFrames) && track->isReady() && 3550 !track->isPaused() && !track->isTerminated()) 3551 { 3552 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer); 3553 3554 if (track->mFillingUpStatus == Track::FS_FILLED) { 3555 track->mFillingUpStatus = Track::FS_ACTIVE; 3556 // make sure processVolume_l() will apply new volume even if 0 3557 mLeftVolFloat = mRightVolFloat = -1.0; 3558 if (track->mState == TrackBase::RESUMING) { 3559 track->mState = TrackBase::ACTIVE; 3560 } 3561 } 3562 3563 // compute volume for this track 3564 processVolume_l(track, last); 3565 if (last) { 3566 // reset retry count 3567 track->mRetryCount = kMaxTrackRetriesDirect; 3568 mActiveTrack = t; 3569 mixerStatus = MIXER_TRACKS_READY; 3570 } 3571 } else { 3572 // clear effect chain input buffer if the last active track started underruns 3573 // to avoid sending previous audio buffer again to effects 3574 if (!mEffectChains.isEmpty() && (i == (count -1))) { 3575 mEffectChains[0]->clearInputBuffer(); 3576 } 3577 3578 ALOGVV("track %d s=%08x [NOT READY]", track->name(), cblk->mServer); 3579 if ((track->sharedBuffer() != 0) || track->isTerminated() || 3580 track->isStopped() || track->isPaused()) { 3581 // We have consumed all the buffers of this track. 3582 // Remove it from the list of active tracks. 3583 // TODO: implement behavior for compressed audio 3584 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000; 3585 size_t framesWritten = mBytesWritten / mFrameSize; 3586 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) { 3587 if (track->isStopped()) { 3588 track->reset(); 3589 } 3590 tracksToRemove->add(track); 3591 } 3592 } else { 3593 // No buffers for this track. Give it a few chances to 3594 // fill a buffer, then remove it from active list. 3595 // Only consider last track started for mixer state control 3596 if (--(track->mRetryCount) <= 0) { 3597 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name()); 3598 tracksToRemove->add(track); 3599 } else if (last) { 3600 mixerStatus = MIXER_TRACKS_ENABLED; 3601 } 3602 } 3603 } 3604 } 3605 3606 // remove all the tracks that need to be... 3607 removeTracks_l(*tracksToRemove); 3608 3609 return mixerStatus; 3610} 3611 3612void AudioFlinger::DirectOutputThread::threadLoop_mix() 3613{ 3614 size_t frameCount = mFrameCount; 3615 int8_t *curBuf = (int8_t *)mMixBuffer; 3616 // output audio to hardware 3617 while (frameCount) { 3618 AudioBufferProvider::Buffer buffer; 3619 buffer.frameCount = frameCount; 3620 mActiveTrack->getNextBuffer(&buffer); 3621 if (buffer.raw == NULL) { 3622 memset(curBuf, 0, frameCount * mFrameSize); 3623 break; 3624 } 3625 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize); 3626 frameCount -= buffer.frameCount; 3627 curBuf += buffer.frameCount * mFrameSize; 3628 mActiveTrack->releaseBuffer(&buffer); 3629 } 3630 mCurrentWriteLength = curBuf - (int8_t *)mMixBuffer; 3631 sleepTime = 0; 3632 standbyTime = systemTime() + standbyDelay; 3633 mActiveTrack.clear(); 3634} 3635 3636void AudioFlinger::DirectOutputThread::threadLoop_sleepTime() 3637{ 3638 if (sleepTime == 0) { 3639 if (mMixerStatus == MIXER_TRACKS_ENABLED) { 3640 sleepTime = activeSleepTime; 3641 } else { 3642 sleepTime = idleSleepTime; 3643 } 3644 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) { 3645 memset(mMixBuffer, 0, mFrameCount * mFrameSize); 3646 sleepTime = 0; 3647 } 3648} 3649 3650// getTrackName_l() must be called with ThreadBase::mLock held 3651int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask, 3652 int sessionId) 3653{ 3654 return 0; 3655} 3656 3657// deleteTrackName_l() must be called with ThreadBase::mLock held 3658void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name) 3659{ 3660} 3661 3662// checkForNewParameters_l() must be called with ThreadBase::mLock held 3663bool AudioFlinger::DirectOutputThread::checkForNewParameters_l() 3664{ 3665 bool reconfig = false; 3666 3667 while (!mNewParameters.isEmpty()) { 3668 status_t status = NO_ERROR; 3669 String8 keyValuePair = mNewParameters[0]; 3670 AudioParameter param = AudioParameter(keyValuePair); 3671 int value; 3672 3673 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) { 3674 // do not accept frame count changes if tracks are open as the track buffer 3675 // size depends on frame count and correct behavior would not be garantied 3676 // if frame count is changed after track creation 3677 if (!mTracks.isEmpty()) { 3678 status = INVALID_OPERATION; 3679 } else { 3680 reconfig = true; 3681 } 3682 } 3683 if (status == NO_ERROR) { 3684 status = mOutput->stream->common.set_parameters(&mOutput->stream->common, 3685 keyValuePair.string()); 3686 if (!mStandby && status == INVALID_OPERATION) { 3687 mOutput->stream->common.standby(&mOutput->stream->common); 3688 mStandby = true; 3689 mBytesWritten = 0; 3690 status = mOutput->stream->common.set_parameters(&mOutput->stream->common, 3691 keyValuePair.string()); 3692 } 3693 if (status == NO_ERROR && reconfig) { 3694 readOutputParameters(); 3695 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED); 3696 } 3697 } 3698 3699 mNewParameters.removeAt(0); 3700 3701 mParamStatus = status; 3702 mParamCond.signal(); 3703 // wait for condition with time out in case the thread calling ThreadBase::setParameters() 3704 // already timed out waiting for the status and will never signal the condition. 3705 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs); 3706 } 3707 return reconfig; 3708} 3709 3710uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const 3711{ 3712 uint32_t time; 3713 if (audio_is_linear_pcm(mFormat)) { 3714 time = PlaybackThread::activeSleepTimeUs(); 3715 } else { 3716 time = 10000; 3717 } 3718 return time; 3719} 3720 3721uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const 3722{ 3723 uint32_t time; 3724 if (audio_is_linear_pcm(mFormat)) { 3725 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2; 3726 } else { 3727 time = 10000; 3728 } 3729 return time; 3730} 3731 3732uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const 3733{ 3734 uint32_t time; 3735 if (audio_is_linear_pcm(mFormat)) { 3736 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000); 3737 } else { 3738 time = 10000; 3739 } 3740 return time; 3741} 3742 3743void AudioFlinger::DirectOutputThread::cacheParameters_l() 3744{ 3745 PlaybackThread::cacheParameters_l(); 3746 3747 // use shorter standby delay as on normal output to release 3748 // hardware resources as soon as possible 3749 if (audio_is_linear_pcm(mFormat)) { 3750 standbyDelay = microseconds(activeSleepTime*2); 3751 } else { 3752 standbyDelay = kOffloadStandbyDelayNs; 3753 } 3754} 3755 3756// ---------------------------------------------------------------------------- 3757 3758AudioFlinger::AsyncCallbackThread::AsyncCallbackThread( 3759 const wp<AudioFlinger::PlaybackThread>& playbackThread) 3760 : Thread(false /*canCallJava*/), 3761 mPlaybackThread(playbackThread), 3762 mWriteAckSequence(0), 3763 mDrainSequence(0) 3764{ 3765} 3766 3767AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread() 3768{ 3769} 3770 3771void AudioFlinger::AsyncCallbackThread::onFirstRef() 3772{ 3773 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO); 3774} 3775 3776bool AudioFlinger::AsyncCallbackThread::threadLoop() 3777{ 3778 while (!exitPending()) { 3779 uint32_t writeAckSequence; 3780 uint32_t drainSequence; 3781 3782 { 3783 Mutex::Autolock _l(mLock); 3784 mWaitWorkCV.wait(mLock); 3785 if (exitPending()) { 3786 break; 3787 } 3788 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d", 3789 mWriteAckSequence, mDrainSequence); 3790 writeAckSequence = mWriteAckSequence; 3791 mWriteAckSequence &= ~1; 3792 drainSequence = mDrainSequence; 3793 mDrainSequence &= ~1; 3794 } 3795 { 3796 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote(); 3797 if (playbackThread != 0) { 3798 if (writeAckSequence & 1) { 3799 playbackThread->resetWriteBlocked(writeAckSequence >> 1); 3800 } 3801 if (drainSequence & 1) { 3802 playbackThread->resetDraining(drainSequence >> 1); 3803 } 3804 } 3805 } 3806 } 3807 return false; 3808} 3809 3810void AudioFlinger::AsyncCallbackThread::exit() 3811{ 3812 ALOGV("AsyncCallbackThread::exit"); 3813 Mutex::Autolock _l(mLock); 3814 requestExit(); 3815 mWaitWorkCV.broadcast(); 3816} 3817 3818void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence) 3819{ 3820 Mutex::Autolock _l(mLock); 3821 // bit 0 is cleared 3822 mWriteAckSequence = sequence << 1; 3823} 3824 3825void AudioFlinger::AsyncCallbackThread::resetWriteBlocked() 3826{ 3827 Mutex::Autolock _l(mLock); 3828 // ignore unexpected callbacks 3829 if (mWriteAckSequence & 2) { 3830 mWriteAckSequence |= 1; 3831 mWaitWorkCV.signal(); 3832 } 3833} 3834 3835void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence) 3836{ 3837 Mutex::Autolock _l(mLock); 3838 // bit 0 is cleared 3839 mDrainSequence = sequence << 1; 3840} 3841 3842void AudioFlinger::AsyncCallbackThread::resetDraining() 3843{ 3844 Mutex::Autolock _l(mLock); 3845 // ignore unexpected callbacks 3846 if (mDrainSequence & 2) { 3847 mDrainSequence |= 1; 3848 mWaitWorkCV.signal(); 3849 } 3850} 3851 3852 3853// ---------------------------------------------------------------------------- 3854AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger, 3855 AudioStreamOut* output, audio_io_handle_t id, uint32_t device) 3856 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD), 3857 mHwPaused(false), 3858 mPausedBytesRemaining(0) 3859{ 3860} 3861 3862AudioFlinger::OffloadThread::~OffloadThread() 3863{ 3864 mPreviousTrack.clear(); 3865} 3866 3867void AudioFlinger::OffloadThread::threadLoop_exit() 3868{ 3869 if (mFlushPending || mHwPaused) { 3870 // If a flush is pending or track was paused, just discard buffered data 3871 flushHw_l(); 3872 } else { 3873 mMixerStatus = MIXER_DRAIN_ALL; 3874 threadLoop_drain(); 3875 } 3876 mCallbackThread->exit(); 3877 PlaybackThread::threadLoop_exit(); 3878} 3879 3880AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l( 3881 Vector< sp<Track> > *tracksToRemove 3882) 3883{ 3884 size_t count = mActiveTracks.size(); 3885 3886 mixer_state mixerStatus = MIXER_IDLE; 3887 bool doHwPause = false; 3888 bool doHwResume = false; 3889 3890 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count); 3891 3892 // find out which tracks need to be processed 3893 for (size_t i = 0; i < count; i++) { 3894 sp<Track> t = mActiveTracks[i].promote(); 3895 // The track died recently 3896 if (t == 0) { 3897 continue; 3898 } 3899 Track* const track = t.get(); 3900 audio_track_cblk_t* cblk = track->cblk(); 3901 if (mPreviousTrack != NULL) { 3902 if (t != mPreviousTrack) { 3903 // Flush any data still being written from last track 3904 mBytesRemaining = 0; 3905 if (mPausedBytesRemaining) { 3906 // Last track was paused so we also need to flush saved 3907 // mixbuffer state and invalidate track so that it will 3908 // re-submit that unwritten data when it is next resumed 3909 mPausedBytesRemaining = 0; 3910 // Invalidate is a bit drastic - would be more efficient 3911 // to have a flag to tell client that some of the 3912 // previously written data was lost 3913 mPreviousTrack->invalidate(); 3914 } 3915 } 3916 } 3917 mPreviousTrack = t; 3918 bool last = (i == (count - 1)); 3919 if (track->isPausing()) { 3920 track->setPaused(); 3921 if (last) { 3922 if (!mHwPaused) { 3923 doHwPause = true; 3924 mHwPaused = true; 3925 } 3926 // If we were part way through writing the mixbuffer to 3927 // the HAL we must save this until we resume 3928 // BUG - this will be wrong if a different track is made active, 3929 // in that case we want to discard the pending data in the 3930 // mixbuffer and tell the client to present it again when the 3931 // track is resumed 3932 mPausedWriteLength = mCurrentWriteLength; 3933 mPausedBytesRemaining = mBytesRemaining; 3934 mBytesRemaining = 0; // stop writing 3935 } 3936 tracksToRemove->add(track); 3937 } else if (track->framesReady() && track->isReady() && 3938 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) { 3939 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer); 3940 if (track->mFillingUpStatus == Track::FS_FILLED) { 3941 track->mFillingUpStatus = Track::FS_ACTIVE; 3942 // make sure processVolume_l() will apply new volume even if 0 3943 mLeftVolFloat = mRightVolFloat = -1.0; 3944 if (track->mState == TrackBase::RESUMING) { 3945 track->mState = TrackBase::ACTIVE; 3946 if (last) { 3947 if (mPausedBytesRemaining) { 3948 // Need to continue write that was interrupted 3949 mCurrentWriteLength = mPausedWriteLength; 3950 mBytesRemaining = mPausedBytesRemaining; 3951 mPausedBytesRemaining = 0; 3952 } 3953 if (mHwPaused) { 3954 doHwResume = true; 3955 mHwPaused = false; 3956 // threadLoop_mix() will handle the case that we need to 3957 // resume an interrupted write 3958 } 3959 // enable write to audio HAL 3960 sleepTime = 0; 3961 } 3962 } 3963 } 3964 3965 if (last) { 3966 // reset retry count 3967 track->mRetryCount = kMaxTrackRetriesOffload; 3968 mActiveTrack = t; 3969 mixerStatus = MIXER_TRACKS_READY; 3970 } 3971 } else { 3972 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer); 3973 if (track->isStopping_1()) { 3974 // Hardware buffer can hold a large amount of audio so we must 3975 // wait for all current track's data to drain before we say 3976 // that the track is stopped. 3977 if (mBytesRemaining == 0) { 3978 // Only start draining when all data in mixbuffer 3979 // has been written 3980 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2"); 3981 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain 3982 if (last) { 3983 sleepTime = 0; 3984 standbyTime = systemTime() + standbyDelay; 3985 mixerStatus = MIXER_DRAIN_TRACK; 3986 mDrainSequence += 2; 3987 if (mHwPaused) { 3988 // It is possible to move from PAUSED to STOPPING_1 without 3989 // a resume so we must ensure hardware is running 3990 mOutput->stream->resume(mOutput->stream); 3991 mHwPaused = false; 3992 } 3993 } 3994 } 3995 } else if (track->isStopping_2()) { 3996 // Drain has completed, signal presentation complete 3997 if (!(mDrainSequence & 1) || !last) { 3998 track->mState = TrackBase::STOPPED; 3999 size_t audioHALFrames = 4000 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000; 4001 size_t framesWritten = 4002 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common); 4003 track->presentationComplete(framesWritten, audioHALFrames); 4004 track->reset(); 4005 tracksToRemove->add(track); 4006 } 4007 } else { 4008 // No buffers for this track. Give it a few chances to 4009 // fill a buffer, then remove it from active list. 4010 if (--(track->mRetryCount) <= 0) { 4011 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list", 4012 track->name()); 4013 tracksToRemove->add(track); 4014 } else if (last){ 4015 mixerStatus = MIXER_TRACKS_ENABLED; 4016 } 4017 } 4018 } 4019 // compute volume for this track 4020 processVolume_l(track, last); 4021 } 4022 4023 // make sure the pause/flush/resume sequence is executed in the right order 4024 if (doHwPause) { 4025 mOutput->stream->pause(mOutput->stream); 4026 } 4027 if (mFlushPending) { 4028 flushHw_l(); 4029 mFlushPending = false; 4030 } 4031 if (doHwResume) { 4032 mOutput->stream->resume(mOutput->stream); 4033 } 4034 4035 // remove all the tracks that need to be... 4036 removeTracks_l(*tracksToRemove); 4037 4038 return mixerStatus; 4039} 4040 4041void AudioFlinger::OffloadThread::flushOutput_l() 4042{ 4043 mFlushPending = true; 4044} 4045 4046// must be called with thread mutex locked 4047bool AudioFlinger::OffloadThread::waitingAsyncCallback_l() 4048{ 4049 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d", 4050 mWriteAckSequence, mDrainSequence); 4051 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) { 4052 return true; 4053 } 4054 return false; 4055} 4056 4057// must be called with thread mutex locked 4058bool AudioFlinger::OffloadThread::shouldStandby_l() 4059{ 4060 bool TrackPaused = false; 4061 4062 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack 4063 // after a timeout and we will enter standby then. 4064 if (mTracks.size() > 0) { 4065 TrackPaused = mTracks[mTracks.size() - 1]->isPaused(); 4066 } 4067 4068 return !mStandby && !TrackPaused; 4069} 4070 4071 4072bool AudioFlinger::OffloadThread::waitingAsyncCallback() 4073{ 4074 Mutex::Autolock _l(mLock); 4075 return waitingAsyncCallback_l(); 4076} 4077 4078void AudioFlinger::OffloadThread::flushHw_l() 4079{ 4080 mOutput->stream->flush(mOutput->stream); 4081 // Flush anything still waiting in the mixbuffer 4082 mCurrentWriteLength = 0; 4083 mBytesRemaining = 0; 4084 mPausedWriteLength = 0; 4085 mPausedBytesRemaining = 0; 4086 if (mUseAsyncWrite) { 4087 // discard any pending drain or write ack by incrementing sequence 4088 mWriteAckSequence = (mWriteAckSequence + 2) & ~1; 4089 mDrainSequence = (mDrainSequence + 2) & ~1; 4090 ALOG_ASSERT(mCallbackThread != 0); 4091 mCallbackThread->setWriteBlocked(mWriteAckSequence); 4092 mCallbackThread->setDraining(mDrainSequence); 4093 } 4094} 4095 4096// ---------------------------------------------------------------------------- 4097 4098AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, 4099 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id) 4100 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(), 4101 DUPLICATING), 4102 mWaitTimeMs(UINT_MAX) 4103{ 4104 addOutputTrack(mainThread); 4105} 4106 4107AudioFlinger::DuplicatingThread::~DuplicatingThread() 4108{ 4109 for (size_t i = 0; i < mOutputTracks.size(); i++) { 4110 mOutputTracks[i]->destroy(); 4111 } 4112} 4113 4114void AudioFlinger::DuplicatingThread::threadLoop_mix() 4115{ 4116 // mix buffers... 4117 if (outputsReady(outputTracks)) { 4118 mAudioMixer->process(AudioBufferProvider::kInvalidPTS); 4119 } else { 4120 memset(mMixBuffer, 0, mixBufferSize); 4121 } 4122 sleepTime = 0; 4123 writeFrames = mNormalFrameCount; 4124 mCurrentWriteLength = mixBufferSize; 4125 standbyTime = systemTime() + standbyDelay; 4126} 4127 4128void AudioFlinger::DuplicatingThread::threadLoop_sleepTime() 4129{ 4130 if (sleepTime == 0) { 4131 if (mMixerStatus == MIXER_TRACKS_ENABLED) { 4132 sleepTime = activeSleepTime; 4133 } else { 4134 sleepTime = idleSleepTime; 4135 } 4136 } else if (mBytesWritten != 0) { 4137 if (mMixerStatus == MIXER_TRACKS_ENABLED) { 4138 writeFrames = mNormalFrameCount; 4139 memset(mMixBuffer, 0, mixBufferSize); 4140 } else { 4141 // flush remaining overflow buffers in output tracks 4142 writeFrames = 0; 4143 } 4144 sleepTime = 0; 4145 } 4146} 4147 4148ssize_t AudioFlinger::DuplicatingThread::threadLoop_write() 4149{ 4150 for (size_t i = 0; i < outputTracks.size(); i++) { 4151 outputTracks[i]->write(mMixBuffer, writeFrames); 4152 } 4153 return (ssize_t)mixBufferSize; 4154} 4155 4156void AudioFlinger::DuplicatingThread::threadLoop_standby() 4157{ 4158 // DuplicatingThread implements standby by stopping all tracks 4159 for (size_t i = 0; i < outputTracks.size(); i++) { 4160 outputTracks[i]->stop(); 4161 } 4162} 4163 4164void AudioFlinger::DuplicatingThread::saveOutputTracks() 4165{ 4166 outputTracks = mOutputTracks; 4167} 4168 4169void AudioFlinger::DuplicatingThread::clearOutputTracks() 4170{ 4171 outputTracks.clear(); 4172} 4173 4174void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread) 4175{ 4176 Mutex::Autolock _l(mLock); 4177 // FIXME explain this formula 4178 size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate(); 4179 OutputTrack *outputTrack = new OutputTrack(thread, 4180 this, 4181 mSampleRate, 4182 mFormat, 4183 mChannelMask, 4184 frameCount); 4185 if (outputTrack->cblk() != NULL) { 4186 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f); 4187 mOutputTracks.add(outputTrack); 4188 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread); 4189 updateWaitTime_l(); 4190 } 4191} 4192 4193void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread) 4194{ 4195 Mutex::Autolock _l(mLock); 4196 for (size_t i = 0; i < mOutputTracks.size(); i++) { 4197 if (mOutputTracks[i]->thread() == thread) { 4198 mOutputTracks[i]->destroy(); 4199 mOutputTracks.removeAt(i); 4200 updateWaitTime_l(); 4201 return; 4202 } 4203 } 4204 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread); 4205} 4206 4207// caller must hold mLock 4208void AudioFlinger::DuplicatingThread::updateWaitTime_l() 4209{ 4210 mWaitTimeMs = UINT_MAX; 4211 for (size_t i = 0; i < mOutputTracks.size(); i++) { 4212 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote(); 4213 if (strong != 0) { 4214 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate(); 4215 if (waitTimeMs < mWaitTimeMs) { 4216 mWaitTimeMs = waitTimeMs; 4217 } 4218 } 4219 } 4220} 4221 4222 4223bool AudioFlinger::DuplicatingThread::outputsReady( 4224 const SortedVector< sp<OutputTrack> > &outputTracks) 4225{ 4226 for (size_t i = 0; i < outputTracks.size(); i++) { 4227 sp<ThreadBase> thread = outputTracks[i]->thread().promote(); 4228 if (thread == 0) { 4229 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", 4230 outputTracks[i].get()); 4231 return false; 4232 } 4233 PlaybackThread *playbackThread = (PlaybackThread *)thread.get(); 4234 // see note at standby() declaration 4235 if (playbackThread->standby() && !playbackThread->isSuspended()) { 4236 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), 4237 thread.get()); 4238 return false; 4239 } 4240 } 4241 return true; 4242} 4243 4244uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const 4245{ 4246 return (mWaitTimeMs * 1000) / 2; 4247} 4248 4249void AudioFlinger::DuplicatingThread::cacheParameters_l() 4250{ 4251 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first 4252 updateWaitTime_l(); 4253 4254 MixerThread::cacheParameters_l(); 4255} 4256 4257// ---------------------------------------------------------------------------- 4258// Record 4259// ---------------------------------------------------------------------------- 4260 4261AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger, 4262 AudioStreamIn *input, 4263 uint32_t sampleRate, 4264 audio_channel_mask_t channelMask, 4265 audio_io_handle_t id, 4266 audio_devices_t outDevice, 4267 audio_devices_t inDevice 4268#ifdef TEE_SINK 4269 , const sp<NBAIO_Sink>& teeSink 4270#endif 4271 ) : 4272 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD), 4273 mInput(input), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL), 4274 // mRsmpInIndex and mBufferSize set by readInputParameters() 4275 mReqChannelCount(popcount(channelMask)), 4276 mReqSampleRate(sampleRate) 4277 // mBytesRead is only meaningful while active, and so is cleared in start() 4278 // (but might be better to also clear here for dump?) 4279#ifdef TEE_SINK 4280 , mTeeSink(teeSink) 4281#endif 4282{ 4283 snprintf(mName, kNameLength, "AudioIn_%X", id); 4284 4285 readInputParameters(); 4286 4287} 4288 4289 4290AudioFlinger::RecordThread::~RecordThread() 4291{ 4292 delete[] mRsmpInBuffer; 4293 delete mResampler; 4294 delete[] mRsmpOutBuffer; 4295} 4296 4297void AudioFlinger::RecordThread::onFirstRef() 4298{ 4299 run(mName, PRIORITY_URGENT_AUDIO); 4300} 4301 4302status_t AudioFlinger::RecordThread::readyToRun() 4303{ 4304 status_t status = initCheck(); 4305 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this); 4306 return status; 4307} 4308 4309bool AudioFlinger::RecordThread::threadLoop() 4310{ 4311 AudioBufferProvider::Buffer buffer; 4312 sp<RecordTrack> activeTrack; 4313 Vector< sp<EffectChain> > effectChains; 4314 4315 nsecs_t lastWarning = 0; 4316 4317 inputStandBy(); 4318 acquireWakeLock(); 4319 4320 // used to verify we've read at least once before evaluating how many bytes were read 4321 bool readOnce = false; 4322 4323 // start recording 4324 while (!exitPending()) { 4325 4326 processConfigEvents(); 4327 4328 { // scope for mLock 4329 Mutex::Autolock _l(mLock); 4330 checkForNewParameters_l(); 4331 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) { 4332 standby(); 4333 4334 if (exitPending()) { 4335 break; 4336 } 4337 4338 releaseWakeLock_l(); 4339 ALOGV("RecordThread: loop stopping"); 4340 // go to sleep 4341 mWaitWorkCV.wait(mLock); 4342 ALOGV("RecordThread: loop starting"); 4343 acquireWakeLock_l(); 4344 continue; 4345 } 4346 if (mActiveTrack != 0) { 4347 if (mActiveTrack->isTerminated()) { 4348 removeTrack_l(mActiveTrack); 4349 mActiveTrack.clear(); 4350 } else if (mActiveTrack->mState == TrackBase::PAUSING) { 4351 standby(); 4352 mActiveTrack.clear(); 4353 mStartStopCond.broadcast(); 4354 } else if (mActiveTrack->mState == TrackBase::RESUMING) { 4355 if (mReqChannelCount != mActiveTrack->channelCount()) { 4356 mActiveTrack.clear(); 4357 mStartStopCond.broadcast(); 4358 } else if (readOnce) { 4359 // record start succeeds only if first read from audio input 4360 // succeeds 4361 if (mBytesRead >= 0) { 4362 mActiveTrack->mState = TrackBase::ACTIVE; 4363 } else { 4364 mActiveTrack.clear(); 4365 } 4366 mStartStopCond.broadcast(); 4367 } 4368 mStandby = false; 4369 } 4370 } 4371 4372 lockEffectChains_l(effectChains); 4373 } 4374 4375 if (mActiveTrack != 0) { 4376 if (mActiveTrack->mState != TrackBase::ACTIVE && 4377 mActiveTrack->mState != TrackBase::RESUMING) { 4378 unlockEffectChains(effectChains); 4379 usleep(kRecordThreadSleepUs); 4380 continue; 4381 } 4382 for (size_t i = 0; i < effectChains.size(); i ++) { 4383 effectChains[i]->process_l(); 4384 } 4385 4386 buffer.frameCount = mFrameCount; 4387 status_t status = mActiveTrack->getNextBuffer(&buffer); 4388 if (status == NO_ERROR) { 4389 readOnce = true; 4390 size_t framesOut = buffer.frameCount; 4391 if (mResampler == NULL) { 4392 // no resampling 4393 while (framesOut) { 4394 size_t framesIn = mFrameCount - mRsmpInIndex; 4395 if (framesIn) { 4396 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize; 4397 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * 4398 mActiveTrack->mFrameSize; 4399 if (framesIn > framesOut) 4400 framesIn = framesOut; 4401 mRsmpInIndex += framesIn; 4402 framesOut -= framesIn; 4403 if (mChannelCount == mReqChannelCount) { 4404 memcpy(dst, src, framesIn * mFrameSize); 4405 } else { 4406 if (mChannelCount == 1) { 4407 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst, 4408 (int16_t *)src, framesIn); 4409 } else { 4410 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst, 4411 (int16_t *)src, framesIn); 4412 } 4413 } 4414 } 4415 if (framesOut && mFrameCount == mRsmpInIndex) { 4416 void *readInto; 4417 if (framesOut == mFrameCount && mChannelCount == mReqChannelCount) { 4418 readInto = buffer.raw; 4419 framesOut = 0; 4420 } else { 4421 readInto = mRsmpInBuffer; 4422 mRsmpInIndex = 0; 4423 } 4424 mBytesRead = mInput->stream->read(mInput->stream, readInto, 4425 mBufferSize); 4426 if (mBytesRead <= 0) { 4427 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE)) 4428 { 4429 ALOGE("Error reading audio input"); 4430 // Force input into standby so that it tries to 4431 // recover at next read attempt 4432 inputStandBy(); 4433 usleep(kRecordThreadSleepUs); 4434 } 4435 mRsmpInIndex = mFrameCount; 4436 framesOut = 0; 4437 buffer.frameCount = 0; 4438 } 4439#ifdef TEE_SINK 4440 else if (mTeeSink != 0) { 4441 (void) mTeeSink->write(readInto, 4442 mBytesRead >> Format_frameBitShift(mTeeSink->format())); 4443 } 4444#endif 4445 } 4446 } 4447 } else { 4448 // resampling 4449 4450 // resampler accumulates, but we only have one source track 4451 memset(mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t)); 4452 // alter output frame count as if we were expecting stereo samples 4453 if (mChannelCount == 1 && mReqChannelCount == 1) { 4454 framesOut >>= 1; 4455 } 4456 mResampler->resample(mRsmpOutBuffer, framesOut, 4457 this /* AudioBufferProvider* */); 4458 // ditherAndClamp() works as long as all buffers returned by 4459 // mActiveTrack->getNextBuffer() are 32 bit aligned which should be always true. 4460 if (mChannelCount == 2 && mReqChannelCount == 1) { 4461 // temporarily type pun mRsmpOutBuffer from Q19.12 to int16_t 4462 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut); 4463 // the resampler always outputs stereo samples: 4464 // do post stereo to mono conversion 4465 downmix_to_mono_i16_from_stereo_i16(buffer.i16, (int16_t *)mRsmpOutBuffer, 4466 framesOut); 4467 } else { 4468 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut); 4469 } 4470 // now done with mRsmpOutBuffer 4471 4472 } 4473 if (mFramestoDrop == 0) { 4474 mActiveTrack->releaseBuffer(&buffer); 4475 } else { 4476 if (mFramestoDrop > 0) { 4477 mFramestoDrop -= buffer.frameCount; 4478 if (mFramestoDrop <= 0) { 4479 clearSyncStartEvent(); 4480 } 4481 } else { 4482 mFramestoDrop += buffer.frameCount; 4483 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 || 4484 mSyncStartEvent->isCancelled()) { 4485 ALOGW("Synced record %s, session %d, trigger session %d", 4486 (mFramestoDrop >= 0) ? "timed out" : "cancelled", 4487 mActiveTrack->sessionId(), 4488 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0); 4489 clearSyncStartEvent(); 4490 } 4491 } 4492 } 4493 mActiveTrack->clearOverflow(); 4494 } 4495 // client isn't retrieving buffers fast enough 4496 else { 4497 if (!mActiveTrack->setOverflow()) { 4498 nsecs_t now = systemTime(); 4499 if ((now - lastWarning) > kWarningThrottleNs) { 4500 ALOGW("RecordThread: buffer overflow"); 4501 lastWarning = now; 4502 } 4503 } 4504 // Release the processor for a while before asking for a new buffer. 4505 // This will give the application more chance to read from the buffer and 4506 // clear the overflow. 4507 usleep(kRecordThreadSleepUs); 4508 } 4509 } 4510 // enable changes in effect chain 4511 unlockEffectChains(effectChains); 4512 effectChains.clear(); 4513 } 4514 4515 standby(); 4516 4517 { 4518 Mutex::Autolock _l(mLock); 4519 for (size_t i = 0; i < mTracks.size(); i++) { 4520 sp<RecordTrack> track = mTracks[i]; 4521 track->invalidate(); 4522 } 4523 mActiveTrack.clear(); 4524 mStartStopCond.broadcast(); 4525 } 4526 4527 releaseWakeLock(); 4528 4529 ALOGV("RecordThread %p exiting", this); 4530 return false; 4531} 4532 4533void AudioFlinger::RecordThread::standby() 4534{ 4535 if (!mStandby) { 4536 inputStandBy(); 4537 mStandby = true; 4538 } 4539} 4540 4541void AudioFlinger::RecordThread::inputStandBy() 4542{ 4543 mInput->stream->common.standby(&mInput->stream->common); 4544} 4545 4546sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l( 4547 const sp<AudioFlinger::Client>& client, 4548 uint32_t sampleRate, 4549 audio_format_t format, 4550 audio_channel_mask_t channelMask, 4551 size_t frameCount, 4552 int sessionId, 4553 IAudioFlinger::track_flags_t *flags, 4554 pid_t tid, 4555 status_t *status) 4556{ 4557 sp<RecordTrack> track; 4558 status_t lStatus; 4559 4560 lStatus = initCheck(); 4561 if (lStatus != NO_ERROR) { 4562 ALOGE("Audio driver not initialized."); 4563 goto Exit; 4564 } 4565 4566 // client expresses a preference for FAST, but we get the final say 4567 if (*flags & IAudioFlinger::TRACK_FAST) { 4568 if ( 4569 // use case: callback handler and frame count is default or at least as large as HAL 4570 ( 4571 (tid != -1) && 4572 ((frameCount == 0) || 4573 (frameCount >= (mFrameCount * kFastTrackMultiplier))) 4574 ) && 4575 // FIXME when record supports non-PCM data, also check for audio_is_linear_pcm(format) 4576 // mono or stereo 4577 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) || 4578 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) && 4579 // hardware sample rate 4580 (sampleRate == mSampleRate) && 4581 // record thread has an associated fast recorder 4582 hasFastRecorder() 4583 // FIXME test that RecordThread for this fast track has a capable output HAL 4584 // FIXME add a permission test also? 4585 ) { 4586 // if frameCount not specified, then it defaults to fast recorder (HAL) frame count 4587 if (frameCount == 0) { 4588 frameCount = mFrameCount * kFastTrackMultiplier; 4589 } 4590 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d", 4591 frameCount, mFrameCount); 4592 } else { 4593 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%d " 4594 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u " 4595 "hasFastRecorder=%d tid=%d", 4596 frameCount, mFrameCount, format, 4597 audio_is_linear_pcm(format), 4598 channelMask, sampleRate, mSampleRate, hasFastRecorder(), tid); 4599 *flags &= ~IAudioFlinger::TRACK_FAST; 4600 // For compatibility with AudioRecord calculation, buffer depth is forced 4601 // to be at least 2 x the record thread frame count and cover audio hardware latency. 4602 // This is probably too conservative, but legacy application code may depend on it. 4603 // If you change this calculation, also review the start threshold which is related. 4604 uint32_t latencyMs = 50; // FIXME mInput->stream->get_latency(mInput->stream); 4605 size_t mNormalFrameCount = 2048; // FIXME 4606 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate); 4607 if (minBufCount < 2) { 4608 minBufCount = 2; 4609 } 4610 size_t minFrameCount = mNormalFrameCount * minBufCount; 4611 if (frameCount < minFrameCount) { 4612 frameCount = minFrameCount; 4613 } 4614 } 4615 } 4616 4617 // FIXME use flags and tid similar to createTrack_l() 4618 4619 { // scope for mLock 4620 Mutex::Autolock _l(mLock); 4621 4622 track = new RecordTrack(this, client, sampleRate, 4623 format, channelMask, frameCount, sessionId); 4624 4625 if (track->getCblk() == 0) { 4626 lStatus = NO_MEMORY; 4627 goto Exit; 4628 } 4629 mTracks.add(track); 4630 4631 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings 4632 bool suspend = audio_is_bluetooth_sco_device(mInDevice) && 4633 mAudioFlinger->btNrecIsOff(); 4634 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId); 4635 setEffectSuspended_l(FX_IID_NS, suspend, sessionId); 4636 4637 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) { 4638 pid_t callingPid = IPCThreadState::self()->getCallingPid(); 4639 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful, 4640 // so ask activity manager to do this on our behalf 4641 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp); 4642 } 4643 } 4644 lStatus = NO_ERROR; 4645 4646Exit: 4647 if (status) { 4648 *status = lStatus; 4649 } 4650 return track; 4651} 4652 4653status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack, 4654 AudioSystem::sync_event_t event, 4655 int triggerSession) 4656{ 4657 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession); 4658 sp<ThreadBase> strongMe = this; 4659 status_t status = NO_ERROR; 4660 4661 if (event == AudioSystem::SYNC_EVENT_NONE) { 4662 clearSyncStartEvent(); 4663 } else if (event != AudioSystem::SYNC_EVENT_SAME) { 4664 mSyncStartEvent = mAudioFlinger->createSyncEvent(event, 4665 triggerSession, 4666 recordTrack->sessionId(), 4667 syncStartEventCallback, 4668 this); 4669 // Sync event can be cancelled by the trigger session if the track is not in a 4670 // compatible state in which case we start record immediately 4671 if (mSyncStartEvent->isCancelled()) { 4672 clearSyncStartEvent(); 4673 } else { 4674 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs 4675 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000); 4676 } 4677 } 4678 4679 { 4680 AutoMutex lock(mLock); 4681 if (mActiveTrack != 0) { 4682 if (recordTrack != mActiveTrack.get()) { 4683 status = -EBUSY; 4684 } else if (mActiveTrack->mState == TrackBase::PAUSING) { 4685 mActiveTrack->mState = TrackBase::ACTIVE; 4686 } 4687 return status; 4688 } 4689 4690 recordTrack->mState = TrackBase::IDLE; 4691 mActiveTrack = recordTrack; 4692 mLock.unlock(); 4693 status_t status = AudioSystem::startInput(mId); 4694 mLock.lock(); 4695 if (status != NO_ERROR) { 4696 mActiveTrack.clear(); 4697 clearSyncStartEvent(); 4698 return status; 4699 } 4700 mRsmpInIndex = mFrameCount; 4701 mBytesRead = 0; 4702 if (mResampler != NULL) { 4703 mResampler->reset(); 4704 } 4705 mActiveTrack->mState = TrackBase::RESUMING; 4706 // signal thread to start 4707 ALOGV("Signal record thread"); 4708 mWaitWorkCV.broadcast(); 4709 // do not wait for mStartStopCond if exiting 4710 if (exitPending()) { 4711 mActiveTrack.clear(); 4712 status = INVALID_OPERATION; 4713 goto startError; 4714 } 4715 mStartStopCond.wait(mLock); 4716 if (mActiveTrack == 0) { 4717 ALOGV("Record failed to start"); 4718 status = BAD_VALUE; 4719 goto startError; 4720 } 4721 ALOGV("Record started OK"); 4722 return status; 4723 } 4724 4725startError: 4726 AudioSystem::stopInput(mId); 4727 clearSyncStartEvent(); 4728 return status; 4729} 4730 4731void AudioFlinger::RecordThread::clearSyncStartEvent() 4732{ 4733 if (mSyncStartEvent != 0) { 4734 mSyncStartEvent->cancel(); 4735 } 4736 mSyncStartEvent.clear(); 4737 mFramestoDrop = 0; 4738} 4739 4740void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event) 4741{ 4742 sp<SyncEvent> strongEvent = event.promote(); 4743 4744 if (strongEvent != 0) { 4745 RecordThread *me = (RecordThread *)strongEvent->cookie(); 4746 me->handleSyncStartEvent(strongEvent); 4747 } 4748} 4749 4750void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event) 4751{ 4752 if (event == mSyncStartEvent) { 4753 // TODO: use actual buffer filling status instead of 2 buffers when info is available 4754 // from audio HAL 4755 mFramestoDrop = mFrameCount * 2; 4756 } 4757} 4758 4759bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) { 4760 ALOGV("RecordThread::stop"); 4761 AutoMutex _l(mLock); 4762 if (recordTrack != mActiveTrack.get() || recordTrack->mState == TrackBase::PAUSING) { 4763 return false; 4764 } 4765 recordTrack->mState = TrackBase::PAUSING; 4766 // do not wait for mStartStopCond if exiting 4767 if (exitPending()) { 4768 return true; 4769 } 4770 mStartStopCond.wait(mLock); 4771 // if we have been restarted, recordTrack == mActiveTrack.get() here 4772 if (exitPending() || recordTrack != mActiveTrack.get()) { 4773 ALOGV("Record stopped OK"); 4774 return true; 4775 } 4776 return false; 4777} 4778 4779bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event) const 4780{ 4781 return false; 4782} 4783 4784status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event) 4785{ 4786#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future 4787 if (!isValidSyncEvent(event)) { 4788 return BAD_VALUE; 4789 } 4790 4791 int eventSession = event->triggerSession(); 4792 status_t ret = NAME_NOT_FOUND; 4793 4794 Mutex::Autolock _l(mLock); 4795 4796 for (size_t i = 0; i < mTracks.size(); i++) { 4797 sp<RecordTrack> track = mTracks[i]; 4798 if (eventSession == track->sessionId()) { 4799 (void) track->setSyncEvent(event); 4800 ret = NO_ERROR; 4801 } 4802 } 4803 return ret; 4804#else 4805 return BAD_VALUE; 4806#endif 4807} 4808 4809// destroyTrack_l() must be called with ThreadBase::mLock held 4810void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track) 4811{ 4812 track->terminate(); 4813 track->mState = TrackBase::STOPPED; 4814 // active tracks are removed by threadLoop() 4815 if (mActiveTrack != track) { 4816 removeTrack_l(track); 4817 } 4818} 4819 4820void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track) 4821{ 4822 mTracks.remove(track); 4823 // need anything related to effects here? 4824} 4825 4826void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args) 4827{ 4828 dumpInternals(fd, args); 4829 dumpTracks(fd, args); 4830 dumpEffectChains(fd, args); 4831} 4832 4833void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args) 4834{ 4835 const size_t SIZE = 256; 4836 char buffer[SIZE]; 4837 String8 result; 4838 4839 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this); 4840 result.append(buffer); 4841 4842 if (mActiveTrack != 0) { 4843 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex); 4844 result.append(buffer); 4845 snprintf(buffer, SIZE, "Buffer size: %u bytes\n", mBufferSize); 4846 result.append(buffer); 4847 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL)); 4848 result.append(buffer); 4849 snprintf(buffer, SIZE, "Out channel count: %u\n", mReqChannelCount); 4850 result.append(buffer); 4851 snprintf(buffer, SIZE, "Out sample rate: %u\n", mReqSampleRate); 4852 result.append(buffer); 4853 } else { 4854 result.append("No active record client\n"); 4855 } 4856 4857 write(fd, result.string(), result.size()); 4858 4859 dumpBase(fd, args); 4860} 4861 4862void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args) 4863{ 4864 const size_t SIZE = 256; 4865 char buffer[SIZE]; 4866 String8 result; 4867 4868 snprintf(buffer, SIZE, "Input thread %p tracks\n", this); 4869 result.append(buffer); 4870 RecordTrack::appendDumpHeader(result); 4871 for (size_t i = 0; i < mTracks.size(); ++i) { 4872 sp<RecordTrack> track = mTracks[i]; 4873 if (track != 0) { 4874 track->dump(buffer, SIZE); 4875 result.append(buffer); 4876 } 4877 } 4878 4879 if (mActiveTrack != 0) { 4880 snprintf(buffer, SIZE, "\nInput thread %p active tracks\n", this); 4881 result.append(buffer); 4882 RecordTrack::appendDumpHeader(result); 4883 mActiveTrack->dump(buffer, SIZE); 4884 result.append(buffer); 4885 4886 } 4887 write(fd, result.string(), result.size()); 4888} 4889 4890// AudioBufferProvider interface 4891status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts) 4892{ 4893 size_t framesReq = buffer->frameCount; 4894 size_t framesReady = mFrameCount - mRsmpInIndex; 4895 int channelCount; 4896 4897 if (framesReady == 0) { 4898 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mBufferSize); 4899 if (mBytesRead <= 0) { 4900 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE)) { 4901 ALOGE("RecordThread::getNextBuffer() Error reading audio input"); 4902 // Force input into standby so that it tries to 4903 // recover at next read attempt 4904 inputStandBy(); 4905 usleep(kRecordThreadSleepUs); 4906 } 4907 buffer->raw = NULL; 4908 buffer->frameCount = 0; 4909 return NOT_ENOUGH_DATA; 4910 } 4911 mRsmpInIndex = 0; 4912 framesReady = mFrameCount; 4913 } 4914 4915 if (framesReq > framesReady) { 4916 framesReq = framesReady; 4917 } 4918 4919 if (mChannelCount == 1 && mReqChannelCount == 2) { 4920 channelCount = 1; 4921 } else { 4922 channelCount = 2; 4923 } 4924 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount; 4925 buffer->frameCount = framesReq; 4926 return NO_ERROR; 4927} 4928 4929// AudioBufferProvider interface 4930void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer) 4931{ 4932 mRsmpInIndex += buffer->frameCount; 4933 buffer->frameCount = 0; 4934} 4935 4936bool AudioFlinger::RecordThread::checkForNewParameters_l() 4937{ 4938 bool reconfig = false; 4939 4940 while (!mNewParameters.isEmpty()) { 4941 status_t status = NO_ERROR; 4942 String8 keyValuePair = mNewParameters[0]; 4943 AudioParameter param = AudioParameter(keyValuePair); 4944 int value; 4945 audio_format_t reqFormat = mFormat; 4946 uint32_t reqSamplingRate = mReqSampleRate; 4947 uint32_t reqChannelCount = mReqChannelCount; 4948 4949 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) { 4950 reqSamplingRate = value; 4951 reconfig = true; 4952 } 4953 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) { 4954 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) { 4955 status = BAD_VALUE; 4956 } else { 4957 reqFormat = (audio_format_t) value; 4958 reconfig = true; 4959 } 4960 } 4961 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) { 4962 reqChannelCount = popcount(value); 4963 reconfig = true; 4964 } 4965 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) { 4966 // do not accept frame count changes if tracks are open as the track buffer 4967 // size depends on frame count and correct behavior would not be guaranteed 4968 // if frame count is changed after track creation 4969 if (mActiveTrack != 0) { 4970 status = INVALID_OPERATION; 4971 } else { 4972 reconfig = true; 4973 } 4974 } 4975 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) { 4976 // forward device change to effects that have requested to be 4977 // aware of attached audio device. 4978 for (size_t i = 0; i < mEffectChains.size(); i++) { 4979 mEffectChains[i]->setDevice_l(value); 4980 } 4981 4982 // store input device and output device but do not forward output device to audio HAL. 4983 // Note that status is ignored by the caller for output device 4984 // (see AudioFlinger::setParameters() 4985 if (audio_is_output_devices(value)) { 4986 mOutDevice = value; 4987 status = BAD_VALUE; 4988 } else { 4989 mInDevice = value; 4990 // disable AEC and NS if the device is a BT SCO headset supporting those 4991 // pre processings 4992 if (mTracks.size() > 0) { 4993 bool suspend = audio_is_bluetooth_sco_device(mInDevice) && 4994 mAudioFlinger->btNrecIsOff(); 4995 for (size_t i = 0; i < mTracks.size(); i++) { 4996 sp<RecordTrack> track = mTracks[i]; 4997 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId()); 4998 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId()); 4999 } 5000 } 5001 } 5002 } 5003 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR && 5004 mAudioSource != (audio_source_t)value) { 5005 // forward device change to effects that have requested to be 5006 // aware of attached audio device. 5007 for (size_t i = 0; i < mEffectChains.size(); i++) { 5008 mEffectChains[i]->setAudioSource_l((audio_source_t)value); 5009 } 5010 mAudioSource = (audio_source_t)value; 5011 } 5012 if (status == NO_ERROR) { 5013 status = mInput->stream->common.set_parameters(&mInput->stream->common, 5014 keyValuePair.string()); 5015 if (status == INVALID_OPERATION) { 5016 inputStandBy(); 5017 status = mInput->stream->common.set_parameters(&mInput->stream->common, 5018 keyValuePair.string()); 5019 } 5020 if (reconfig) { 5021 if (status == BAD_VALUE && 5022 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) && 5023 reqFormat == AUDIO_FORMAT_PCM_16_BIT && 5024 (mInput->stream->common.get_sample_rate(&mInput->stream->common) 5025 <= (2 * reqSamplingRate)) && 5026 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) 5027 <= FCC_2 && 5028 (reqChannelCount <= FCC_2)) { 5029 status = NO_ERROR; 5030 } 5031 if (status == NO_ERROR) { 5032 readInputParameters(); 5033 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED); 5034 } 5035 } 5036 } 5037 5038 mNewParameters.removeAt(0); 5039 5040 mParamStatus = status; 5041 mParamCond.signal(); 5042 // wait for condition with time out in case the thread calling ThreadBase::setParameters() 5043 // already timed out waiting for the status and will never signal the condition. 5044 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs); 5045 } 5046 return reconfig; 5047} 5048 5049String8 AudioFlinger::RecordThread::getParameters(const String8& keys) 5050{ 5051 Mutex::Autolock _l(mLock); 5052 if (initCheck() != NO_ERROR) { 5053 return String8(); 5054 } 5055 5056 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string()); 5057 const String8 out_s8(s); 5058 free(s); 5059 return out_s8; 5060} 5061 5062void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) { 5063 AudioSystem::OutputDescriptor desc; 5064 void *param2 = NULL; 5065 5066 switch (event) { 5067 case AudioSystem::INPUT_OPENED: 5068 case AudioSystem::INPUT_CONFIG_CHANGED: 5069 desc.channelMask = mChannelMask; 5070 desc.samplingRate = mSampleRate; 5071 desc.format = mFormat; 5072 desc.frameCount = mFrameCount; 5073 desc.latency = 0; 5074 param2 = &desc; 5075 break; 5076 5077 case AudioSystem::INPUT_CLOSED: 5078 default: 5079 break; 5080 } 5081 mAudioFlinger->audioConfigChanged_l(event, mId, param2); 5082} 5083 5084void AudioFlinger::RecordThread::readInputParameters() 5085{ 5086 delete[] mRsmpInBuffer; 5087 // mRsmpInBuffer is always assigned a new[] below 5088 delete[] mRsmpOutBuffer; 5089 mRsmpOutBuffer = NULL; 5090 delete mResampler; 5091 mResampler = NULL; 5092 5093 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common); 5094 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common); 5095 mChannelCount = popcount(mChannelMask); 5096 mFormat = mInput->stream->common.get_format(&mInput->stream->common); 5097 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) { 5098 ALOGE("HAL format %d not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat); 5099 } 5100 mFrameSize = audio_stream_frame_size(&mInput->stream->common); 5101 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common); 5102 mFrameCount = mBufferSize / mFrameSize; 5103 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount]; 5104 5105 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2) 5106 { 5107 int channelCount; 5108 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid 5109 // stereo to mono post process as the resampler always outputs stereo. 5110 if (mChannelCount == 1 && mReqChannelCount == 2) { 5111 channelCount = 1; 5112 } else { 5113 channelCount = 2; 5114 } 5115 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate); 5116 mResampler->setSampleRate(mSampleRate); 5117 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN); 5118 mRsmpOutBuffer = new int32_t[mFrameCount * FCC_2]; 5119 5120 // optmization: if mono to mono, alter input frame count as if we were inputing 5121 // stereo samples 5122 if (mChannelCount == 1 && mReqChannelCount == 1) { 5123 mFrameCount >>= 1; 5124 } 5125 5126 } 5127 mRsmpInIndex = mFrameCount; 5128} 5129 5130unsigned int AudioFlinger::RecordThread::getInputFramesLost() 5131{ 5132 Mutex::Autolock _l(mLock); 5133 if (initCheck() != NO_ERROR) { 5134 return 0; 5135 } 5136 5137 return mInput->stream->get_input_frames_lost(mInput->stream); 5138} 5139 5140uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const 5141{ 5142 Mutex::Autolock _l(mLock); 5143 uint32_t result = 0; 5144 if (getEffectChain_l(sessionId) != 0) { 5145 result = EFFECT_SESSION; 5146 } 5147 5148 for (size_t i = 0; i < mTracks.size(); ++i) { 5149 if (sessionId == mTracks[i]->sessionId()) { 5150 result |= TRACK_SESSION; 5151 break; 5152 } 5153 } 5154 5155 return result; 5156} 5157 5158KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const 5159{ 5160 KeyedVector<int, bool> ids; 5161 Mutex::Autolock _l(mLock); 5162 for (size_t j = 0; j < mTracks.size(); ++j) { 5163 sp<RecordThread::RecordTrack> track = mTracks[j]; 5164 int sessionId = track->sessionId(); 5165 if (ids.indexOfKey(sessionId) < 0) { 5166 ids.add(sessionId, true); 5167 } 5168 } 5169 return ids; 5170} 5171 5172AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput() 5173{ 5174 Mutex::Autolock _l(mLock); 5175 AudioStreamIn *input = mInput; 5176 mInput = NULL; 5177 return input; 5178} 5179 5180// this method must always be called either with ThreadBase mLock held or inside the thread loop 5181audio_stream_t* AudioFlinger::RecordThread::stream() const 5182{ 5183 if (mInput == NULL) { 5184 return NULL; 5185 } 5186 return &mInput->stream->common; 5187} 5188 5189status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain) 5190{ 5191 // only one chain per input thread 5192 if (mEffectChains.size() != 0) { 5193 return INVALID_OPERATION; 5194 } 5195 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this); 5196 5197 chain->setInBuffer(NULL); 5198 chain->setOutBuffer(NULL); 5199 5200 checkSuspendOnAddEffectChain_l(chain); 5201 5202 mEffectChains.add(chain); 5203 5204 return NO_ERROR; 5205} 5206 5207size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain) 5208{ 5209 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this); 5210 ALOGW_IF(mEffectChains.size() != 1, 5211 "removeEffectChain_l() %p invalid chain size %d on thread %p", 5212 chain.get(), mEffectChains.size(), this); 5213 if (mEffectChains.size() == 1) { 5214 mEffectChains.removeAt(0); 5215 } 5216 return 0; 5217} 5218 5219}; // namespace android 5220