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