blob: 4ec16c1c110ffb525f0e2482379a1354ffc6e2fa [file] [log] [blame]
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001/* //device/include/server/AudioFlinger/AudioFlinger.cpp
2**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
Eric Laurent7d850f22010-07-09 13:34:17 -070020//#define LOG_NDEBUG 0
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070021
22#include <math.h>
23#include <signal.h>
24#include <sys/time.h>
25#include <sys/resource.h>
26
Mathias Agopian07952722009-05-19 19:08:10 -070027#include <binder/IServiceManager.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070028#include <utils/Log.h>
Mathias Agopian07952722009-05-19 19:08:10 -070029#include <binder/Parcel.h>
30#include <binder/IPCThreadState.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070031#include <utils/String16.h>
32#include <utils/threads.h>
33
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080034#include <cutils/properties.h>
35
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070036#include <media/AudioTrack.h>
37#include <media/AudioRecord.h>
38
39#include <private/media/AudioTrackShared.h>
Eric Laurent65b65452010-06-01 23:49:17 -070040#include <private/media/AudioEffectShared.h>
The Android Open Source Project9266c552009-01-15 16:12:10 -080041#include <hardware_legacy/AudioHardwareInterface.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070042
43#include "AudioMixer.h"
44#include "AudioFlinger.h"
45
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080046#ifdef WITH_A2DP
47#include "A2dpAudioInterface.h"
48#endif
49
Glenn Kasten871c16c2010-03-05 12:18:01 -080050#ifdef LVMX
51#include "lifevibes.h"
52#endif
53
Eric Laurent53334cd2010-06-23 17:38:20 -070054#include <media/EffectsFactoryApi.h>
Eric Laurentdf9b81c2010-07-02 08:12:41 -070055#include <media/EffectVisualizerApi.h>
Eric Laurent65b65452010-06-01 23:49:17 -070056
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057// ----------------------------------------------------------------------------
58// the sim build doesn't have gettid
59
60#ifndef HAVE_GETTID
61# define gettid getpid
62#endif
63
64// ----------------------------------------------------------------------------
65
Eric Laurent8ed6ed02010-07-13 04:45:46 -070066extern const char * const gEffectLibPath;
67
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070068namespace android {
69
The Android Open Source Project10592532009-03-18 17:39:46 -070070static const char* kDeadlockedString = "AudioFlinger may be deadlocked\n";
71static const char* kHardwareLockedString = "Hardware lock is taken\n";
72
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080073//static const nsecs_t kStandbyTimeInNsecs = seconds(3);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070074static const float MAX_GAIN = 4096.0f;
Eric Laurent65b65452010-06-01 23:49:17 -070075static const float MAX_GAIN_INT = 0x1000;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070076
77// retry counts for buffer fill timeout
78// 50 * ~20msecs = 1 second
79static const int8_t kMaxTrackRetries = 50;
80static const int8_t kMaxTrackStartupRetries = 50;
Eric Laurentef9500f2010-03-11 14:47:00 -080081// allow less retry attempts on direct output thread.
82// direct outputs can be a scarce resource in audio hardware and should
83// be released as quickly as possible.
84static const int8_t kMaxTrackRetriesDirect = 2;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070085
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -070086static const int kDumpLockRetries = 50;
87static const int kDumpLockSleep = 20000;
88
Dave Sparksd0ac8c02009-09-30 03:09:03 -070089static const nsecs_t kWarningThrottle = seconds(5);
90
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070092#define AUDIOFLINGER_SECURITY_ENABLED 1
93
94// ----------------------------------------------------------------------------
95
96static bool recordingAllowed() {
97#ifndef HAVE_ANDROID_OS
98 return true;
99#endif
100#if AUDIOFLINGER_SECURITY_ENABLED
101 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
102 bool ok = checkCallingPermission(String16("android.permission.RECORD_AUDIO"));
103 if (!ok) LOGE("Request requires android.permission.RECORD_AUDIO");
104 return ok;
105#else
106 if (!checkCallingPermission(String16("android.permission.RECORD_AUDIO")))
107 LOGW("WARNING: Need to add android.permission.RECORD_AUDIO to manifest");
108 return true;
109#endif
110}
111
112static bool settingsAllowed() {
113#ifndef HAVE_ANDROID_OS
114 return true;
115#endif
116#if AUDIOFLINGER_SECURITY_ENABLED
117 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
118 bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
119 if (!ok) LOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
120 return ok;
121#else
122 if (!checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS")))
123 LOGW("WARNING: Need to add android.permission.MODIFY_AUDIO_SETTINGS to manifest");
124 return true;
125#endif
126}
127
128// ----------------------------------------------------------------------------
129
130AudioFlinger::AudioFlinger()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800131 : BnAudioFlinger(),
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700132 mAudioHardware(0), mMasterVolume(1.0f), mMasterMute(false), mNextUniqueId(1)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700133{
Eric Laurent01635942011-01-18 18:39:02 -0800134 Mutex::Autolock _l(mLock);
135
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700136 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -0700137
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700138 mAudioHardware = AudioHardwareInterface::create();
Eric Laurenta553c252009-07-17 12:17:14 -0700139
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700140 mHardwareStatus = AUDIO_HW_INIT;
141 if (mAudioHardware->initCheck() == NO_ERROR) {
Eric Laurent01635942011-01-18 18:39:02 -0800142 AutoMutex lock(mHardwareLock);
Eric Laurent53334cd2010-06-23 17:38:20 -0700143 mMode = AudioSystem::MODE_NORMAL;
Eric Laurent01635942011-01-18 18:39:02 -0800144 mHardwareStatus = AUDIO_HW_SET_MODE;
145 mAudioHardware->setMode(mMode);
146 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
147 mAudioHardware->setMasterVolume(1.0f);
148 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -0700149 } else {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700150 LOGE("Couldn't even initialize the stubbed audio hardware!");
151 }
Glenn Kasten871c16c2010-03-05 12:18:01 -0800152#ifdef LVMX
153 LifeVibes::init();
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700154 mLifeVibesClientPid = -1;
Glenn Kasten871c16c2010-03-05 12:18:01 -0800155#endif
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700156}
157
158AudioFlinger::~AudioFlinger()
159{
Eric Laurent7954c462009-08-28 10:39:03 -0700160 while (!mRecordThreads.isEmpty()) {
161 // closeInput() will remove first entry from mRecordThreads
162 closeInput(mRecordThreads.keyAt(0));
163 }
164 while (!mPlaybackThreads.isEmpty()) {
165 // closeOutput() will remove first entry from mPlaybackThreads
166 closeOutput(mPlaybackThreads.keyAt(0));
167 }
168 if (mAudioHardware) {
169 delete mAudioHardware;
170 }
The Android Open Source Projectb7986892009-01-09 17:51:23 -0800171}
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800172
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700173
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700174
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700175status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
176{
177 const size_t SIZE = 256;
178 char buffer[SIZE];
179 String8 result;
180
181 result.append("Clients:\n");
182 for (size_t i = 0; i < mClients.size(); ++i) {
183 wp<Client> wClient = mClients.valueAt(i);
184 if (wClient != 0) {
185 sp<Client> client = wClient.promote();
186 if (client != 0) {
187 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
188 result.append(buffer);
189 }
190 }
191 }
192 write(fd, result.string(), result.size());
193 return NO_ERROR;
194}
195
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700196
197status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
198{
199 const size_t SIZE = 256;
200 char buffer[SIZE];
201 String8 result;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700202 int hardwareStatus = mHardwareStatus;
Eric Laurenta553c252009-07-17 12:17:14 -0700203
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700204 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700205 result.append(buffer);
206 write(fd, result.string(), result.size());
207 return NO_ERROR;
208}
209
210status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
211{
212 const size_t SIZE = 256;
213 char buffer[SIZE];
214 String8 result;
215 snprintf(buffer, SIZE, "Permission Denial: "
216 "can't dump AudioFlinger from pid=%d, uid=%d\n",
217 IPCThreadState::self()->getCallingPid(),
218 IPCThreadState::self()->getCallingUid());
219 result.append(buffer);
220 write(fd, result.string(), result.size());
221 return NO_ERROR;
222}
223
The Android Open Source Project10592532009-03-18 17:39:46 -0700224static bool tryLock(Mutex& mutex)
225{
226 bool locked = false;
227 for (int i = 0; i < kDumpLockRetries; ++i) {
228 if (mutex.tryLock() == NO_ERROR) {
229 locked = true;
230 break;
231 }
232 usleep(kDumpLockSleep);
233 }
234 return locked;
235}
236
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700237status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
238{
239 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
240 dumpPermissionDenial(fd, args);
241 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -0700242 // get state of hardware lock
243 bool hardwareLocked = tryLock(mHardwareLock);
244 if (!hardwareLocked) {
245 String8 result(kHardwareLockedString);
246 write(fd, result.string(), result.size());
247 } else {
248 mHardwareLock.unlock();
249 }
250
251 bool locked = tryLock(mLock);
252
253 // failed to lock - AudioFlinger is probably deadlocked
254 if (!locked) {
255 String8 result(kDeadlockedString);
256 write(fd, result.string(), result.size());
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700257 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700258
259 dumpClients(fd, args);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700260 dumpInternals(fd, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800261
Eric Laurenta553c252009-07-17 12:17:14 -0700262 // dump playback threads
263 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700264 mPlaybackThreads.valueAt(i)->dump(fd, args);
Eric Laurenta553c252009-07-17 12:17:14 -0700265 }
266
267 // dump record threads
Eric Laurent102313a2009-07-23 13:35:01 -0700268 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700269 mRecordThreads.valueAt(i)->dump(fd, args);
Eric Laurenta553c252009-07-17 12:17:14 -0700270 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800271
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700272 if (mAudioHardware) {
273 mAudioHardware->dumpState(fd, args);
274 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700275 if (locked) mLock.unlock();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700276 }
277 return NO_ERROR;
278}
279
Eric Laurenta553c252009-07-17 12:17:14 -0700280
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700281// IAudioFlinger interface
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800282
283
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700284sp<IAudioTrack> AudioFlinger::createTrack(
285 pid_t pid,
286 int streamType,
287 uint32_t sampleRate,
288 int format,
289 int channelCount,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800290 int frameCount,
291 uint32_t flags,
292 const sp<IMemory>& sharedBuffer,
Eric Laurentddb78e72009-07-28 08:44:33 -0700293 int output,
Eric Laurent65b65452010-06-01 23:49:17 -0700294 int *sessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800295 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700296{
Eric Laurenta553c252009-07-17 12:17:14 -0700297 sp<PlaybackThread::Track> track;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700298 sp<TrackHandle> trackHandle;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700299 sp<Client> client;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800300 wp<Client> wclient;
301 status_t lStatus;
Eric Laurent65b65452010-06-01 23:49:17 -0700302 int lSessionId;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700303
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800304 if (streamType >= AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800305 LOGE("invalid stream type");
306 lStatus = BAD_VALUE;
307 goto Exit;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700308 }
309
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800310 {
311 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700312 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent493941b2010-07-28 01:32:47 -0700313 PlaybackThread *effectThread = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -0700314 if (thread == NULL) {
315 LOGE("unknown output thread");
316 lStatus = BAD_VALUE;
317 goto Exit;
318 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800319
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800320 wclient = mClients.valueFor(pid);
321
322 if (wclient != NULL) {
323 client = wclient.promote();
324 } else {
325 client = new Client(this, pid);
326 mClients.add(pid, client);
327 }
Eric Laurent65b65452010-06-01 23:49:17 -0700328
Eric Laurent65b65452010-06-01 23:49:17 -0700329 LOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700330 if (sessionId != NULL && *sessionId != AudioSystem::SESSION_OUTPUT_MIX) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700331 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent493941b2010-07-28 01:32:47 -0700332 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
333 if (mPlaybackThreads.keyAt(i) != output) {
334 // prevent same audio session on different output threads
335 uint32_t sessions = t->hasAudioSession(*sessionId);
336 if (sessions & PlaybackThread::TRACK_SESSION) {
337 lStatus = BAD_VALUE;
338 goto Exit;
339 }
340 // check if an effect with same session ID is waiting for a track to be created
341 if (sessions & PlaybackThread::EFFECT_SESSION) {
342 effectThread = t.get();
343 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700344 }
345 }
Eric Laurent65b65452010-06-01 23:49:17 -0700346 lSessionId = *sessionId;
347 } else {
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700348 // if no audio session id is provided, create one here
Eric Laurentf3d6dd02010-11-18 08:40:16 -0800349 lSessionId = nextUniqueId_l();
Eric Laurent65b65452010-06-01 23:49:17 -0700350 if (sessionId != NULL) {
351 *sessionId = lSessionId;
352 }
353 }
354 LOGV("createTrack() lSessionId: %d", lSessionId);
355
Eric Laurenta553c252009-07-17 12:17:14 -0700356 track = thread->createTrack_l(client, streamType, sampleRate, format,
Eric Laurent65b65452010-06-01 23:49:17 -0700357 channelCount, frameCount, sharedBuffer, lSessionId, &lStatus);
Eric Laurent493941b2010-07-28 01:32:47 -0700358
359 // move effect chain to this output thread if an effect on same session was waiting
360 // for a track to be created
361 if (lStatus == NO_ERROR && effectThread != NULL) {
362 Mutex::Autolock _dl(thread->mLock);
363 Mutex::Autolock _sl(effectThread->mLock);
364 moveEffectChain_l(lSessionId, effectThread, thread, true);
365 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700366 }
367 if (lStatus == NO_ERROR) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800368 trackHandle = new TrackHandle(track);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700369 } else {
Eric Laurentb9481d82009-09-17 05:12:56 -0700370 // remove local strong reference to Client before deleting the Track so that the Client
371 // destructor is called by the TrackBase destructor with mLock held
372 client.clear();
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700373 track.clear();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800374 }
375
376Exit:
377 if(status) {
378 *status = lStatus;
379 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700380 return trackHandle;
381}
382
Eric Laurentddb78e72009-07-28 08:44:33 -0700383uint32_t AudioFlinger::sampleRate(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700384{
Eric Laurenta553c252009-07-17 12:17:14 -0700385 Mutex::Autolock _l(mLock);
386 PlaybackThread *thread = checkPlaybackThread_l(output);
387 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700388 LOGW("sampleRate() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700389 return 0;
390 }
391 return thread->sampleRate();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700392}
393
Eric Laurentddb78e72009-07-28 08:44:33 -0700394int AudioFlinger::channelCount(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700395{
Eric Laurenta553c252009-07-17 12:17:14 -0700396 Mutex::Autolock _l(mLock);
397 PlaybackThread *thread = checkPlaybackThread_l(output);
398 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700399 LOGW("channelCount() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700400 return 0;
401 }
402 return thread->channelCount();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700403}
404
Eric Laurentddb78e72009-07-28 08:44:33 -0700405int AudioFlinger::format(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700406{
Eric Laurenta553c252009-07-17 12:17:14 -0700407 Mutex::Autolock _l(mLock);
408 PlaybackThread *thread = checkPlaybackThread_l(output);
409 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700410 LOGW("format() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700411 return 0;
412 }
413 return thread->format();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700414}
415
Eric Laurentddb78e72009-07-28 08:44:33 -0700416size_t AudioFlinger::frameCount(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700417{
Eric Laurenta553c252009-07-17 12:17:14 -0700418 Mutex::Autolock _l(mLock);
419 PlaybackThread *thread = checkPlaybackThread_l(output);
420 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700421 LOGW("frameCount() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700422 return 0;
423 }
424 return thread->frameCount();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700425}
426
Eric Laurentddb78e72009-07-28 08:44:33 -0700427uint32_t AudioFlinger::latency(int output) const
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800428{
Eric Laurenta553c252009-07-17 12:17:14 -0700429 Mutex::Autolock _l(mLock);
430 PlaybackThread *thread = checkPlaybackThread_l(output);
431 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700432 LOGW("latency() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700433 return 0;
434 }
435 return thread->latency();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800436}
437
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700438status_t AudioFlinger::setMasterVolume(float value)
439{
440 // check calling permissions
441 if (!settingsAllowed()) {
442 return PERMISSION_DENIED;
443 }
444
445 // when hw supports master volume, don't scale in sw mixer
Eric Laurent01635942011-01-18 18:39:02 -0800446 { // scope for the lock
447 AutoMutex lock(mHardwareLock);
448 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
449 if (mAudioHardware->setMasterVolume(value) == NO_ERROR) {
450 value = 1.0f;
451 }
452 mHardwareStatus = AUDIO_HW_IDLE;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700453 }
Eric Laurenta553c252009-07-17 12:17:14 -0700454
Eric Laurent01635942011-01-18 18:39:02 -0800455 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700456 mMasterVolume = value;
457 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700458 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700459
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700460 return NO_ERROR;
461}
462
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700463status_t AudioFlinger::setMode(int mode)
464{
Eric Laurent53334cd2010-06-23 17:38:20 -0700465 status_t ret;
466
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700467 // check calling permissions
468 if (!settingsAllowed()) {
469 return PERMISSION_DENIED;
470 }
471 if ((mode < 0) || (mode >= AudioSystem::NUM_MODES)) {
472 LOGW("Illegal value: setMode(%d)", mode);
473 return BAD_VALUE;
474 }
475
Eric Laurent53334cd2010-06-23 17:38:20 -0700476 { // scope for the lock
477 AutoMutex lock(mHardwareLock);
478 mHardwareStatus = AUDIO_HW_SET_MODE;
479 ret = mAudioHardware->setMode(mode);
480 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten871c16c2010-03-05 12:18:01 -0800481 }
Eric Laurent53334cd2010-06-23 17:38:20 -0700482
483 if (NO_ERROR == ret) {
484 Mutex::Autolock _l(mLock);
485 mMode = mode;
486 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
487 mPlaybackThreads.valueAt(i)->setMode(mode);
488#ifdef LVMX
489 LifeVibes::setMode(mode);
Glenn Kasten871c16c2010-03-05 12:18:01 -0800490#endif
Eric Laurent53334cd2010-06-23 17:38:20 -0700491 }
492
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700493 return ret;
494}
495
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700496status_t AudioFlinger::setMicMute(bool state)
497{
498 // check calling permissions
499 if (!settingsAllowed()) {
500 return PERMISSION_DENIED;
501 }
502
503 AutoMutex lock(mHardwareLock);
504 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
505 status_t ret = mAudioHardware->setMicMute(state);
506 mHardwareStatus = AUDIO_HW_IDLE;
507 return ret;
508}
509
510bool AudioFlinger::getMicMute() const
511{
512 bool state = AudioSystem::MODE_INVALID;
513 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
514 mAudioHardware->getMicMute(&state);
515 mHardwareStatus = AUDIO_HW_IDLE;
516 return state;
517}
518
519status_t AudioFlinger::setMasterMute(bool muted)
520{
521 // check calling permissions
522 if (!settingsAllowed()) {
523 return PERMISSION_DENIED;
524 }
Eric Laurenta553c252009-07-17 12:17:14 -0700525
Eric Laurent01635942011-01-18 18:39:02 -0800526 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700527 mMasterMute = muted;
528 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700529 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Eric Laurenta553c252009-07-17 12:17:14 -0700530
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700531 return NO_ERROR;
532}
533
534float AudioFlinger::masterVolume() const
535{
Eric Laurenta553c252009-07-17 12:17:14 -0700536 return mMasterVolume;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700537}
538
539bool AudioFlinger::masterMute() const
540{
Eric Laurenta553c252009-07-17 12:17:14 -0700541 return mMasterMute;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700542}
543
Eric Laurentddb78e72009-07-28 08:44:33 -0700544status_t AudioFlinger::setStreamVolume(int stream, float value, int output)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700545{
546 // check calling permissions
547 if (!settingsAllowed()) {
548 return PERMISSION_DENIED;
549 }
550
Eric Laurenta553c252009-07-17 12:17:14 -0700551 if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700552 return BAD_VALUE;
553 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800554
Eric Laurenta553c252009-07-17 12:17:14 -0700555 AutoMutex lock(mLock);
556 PlaybackThread *thread = NULL;
557 if (output) {
558 thread = checkPlaybackThread_l(output);
559 if (thread == NULL) {
560 return BAD_VALUE;
561 }
562 }
563
Eric Laurenta553c252009-07-17 12:17:14 -0700564 mStreamTypes[stream].volume = value;
565
566 if (thread == NULL) {
Eric Laurent415f3e22009-10-21 08:14:22 -0700567 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700568 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Eric Laurent415f3e22009-10-21 08:14:22 -0700569 }
Eric Laurenta553c252009-07-17 12:17:14 -0700570 } else {
571 thread->setStreamVolume(stream, value);
572 }
Eric Laurentef028272009-04-21 07:56:33 -0700573
Eric Laurent415f3e22009-10-21 08:14:22 -0700574 return NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700575}
576
577status_t AudioFlinger::setStreamMute(int stream, bool muted)
578{
579 // check calling permissions
580 if (!settingsAllowed()) {
581 return PERMISSION_DENIED;
582 }
583
Eric Laurenta553c252009-07-17 12:17:14 -0700584 if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES ||
Eric Laurenteeea9222009-03-26 01:57:59 -0700585 uint32_t(stream) == AudioSystem::ENFORCED_AUDIBLE) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700586 return BAD_VALUE;
587 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700588
Eric Laurent01635942011-01-18 18:39:02 -0800589 AutoMutex lock(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700590 mStreamTypes[stream].mute = muted;
591 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700592 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800593
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700594 return NO_ERROR;
595}
596
Eric Laurentddb78e72009-07-28 08:44:33 -0700597float AudioFlinger::streamVolume(int stream, int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700598{
Eric Laurenta553c252009-07-17 12:17:14 -0700599 if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700600 return 0.0f;
601 }
Eric Laurenta553c252009-07-17 12:17:14 -0700602
603 AutoMutex lock(mLock);
604 float volume;
605 if (output) {
606 PlaybackThread *thread = checkPlaybackThread_l(output);
607 if (thread == NULL) {
608 return 0.0f;
609 }
610 volume = thread->streamVolume(stream);
611 } else {
612 volume = mStreamTypes[stream].volume;
613 }
614
Eric Laurentef028272009-04-21 07:56:33 -0700615 return volume;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700616}
617
618bool AudioFlinger::streamMute(int stream) const
619{
Eric Laurenta553c252009-07-17 12:17:14 -0700620 if (stream < 0 || stream >= (int)AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700621 return true;
622 }
Eric Laurenta553c252009-07-17 12:17:14 -0700623
624 return mStreamTypes[stream].mute;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700625}
626
Eric Laurentddb78e72009-07-28 08:44:33 -0700627status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700628{
Eric Laurenta553c252009-07-17 12:17:14 -0700629 status_t result;
630
Eric Laurentddb78e72009-07-28 08:44:33 -0700631 LOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
Eric Laurenta553c252009-07-17 12:17:14 -0700632 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
633 // check calling permissions
634 if (!settingsAllowed()) {
635 return PERMISSION_DENIED;
The Android Open Source Project9266c552009-01-15 16:12:10 -0800636 }
Eric Laurenta553c252009-07-17 12:17:14 -0700637
Glenn Kasten871c16c2010-03-05 12:18:01 -0800638#ifdef LVMX
639 AudioParameter param = AudioParameter(keyValuePairs);
640 LifeVibes::setParameters(ioHandle,keyValuePairs);
641 String8 key = String8(AudioParameter::keyRouting);
642 int device;
643 if (NO_ERROR != param.getInt(key, device)) {
644 device = -1;
645 }
646
647 key = String8(LifevibesTag);
648 String8 value;
649 int musicEnabled = -1;
650 if (NO_ERROR == param.get(key, value)) {
651 if (value == LifevibesEnable) {
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700652 mLifeVibesClientPid = IPCThreadState::self()->getCallingPid();
Glenn Kasten871c16c2010-03-05 12:18:01 -0800653 musicEnabled = 1;
654 } else if (value == LifevibesDisable) {
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700655 mLifeVibesClientPid = -1;
Glenn Kasten871c16c2010-03-05 12:18:01 -0800656 musicEnabled = 0;
657 }
658 }
659#endif
660
Eric Laurenta553c252009-07-17 12:17:14 -0700661 // ioHandle == 0 means the parameters are global to the audio hardware interface
662 if (ioHandle == 0) {
663 AutoMutex lock(mHardwareLock);
664 mHardwareStatus = AUDIO_SET_PARAMETER;
665 result = mAudioHardware->setParameters(keyValuePairs);
Glenn Kasten871c16c2010-03-05 12:18:01 -0800666#ifdef LVMX
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700667 if (musicEnabled != -1) {
Glenn Kasten871c16c2010-03-05 12:18:01 -0800668 LifeVibes::enableMusic((bool) musicEnabled);
669 }
670#endif
Eric Laurenta553c252009-07-17 12:17:14 -0700671 mHardwareStatus = AUDIO_HW_IDLE;
672 return result;
673 }
674
Eric Laurentb7d94602009-09-29 11:12:57 -0700675 // hold a strong ref on thread in case closeOutput() or closeInput() is called
676 // and the thread is exited once the lock is released
677 sp<ThreadBase> thread;
678 {
679 Mutex::Autolock _l(mLock);
680 thread = checkPlaybackThread_l(ioHandle);
681 if (thread == NULL) {
682 thread = checkRecordThread_l(ioHandle);
683 }
Eric Laurenta553c252009-07-17 12:17:14 -0700684 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700685 if (thread != NULL) {
Glenn Kasten871c16c2010-03-05 12:18:01 -0800686 result = thread->setParameters(keyValuePairs);
687#ifdef LVMX
688 if ((NO_ERROR == result) && (device != -1)) {
689 LifeVibes::setDevice(LifeVibes::threadIdToAudioOutputType(thread->id()), device);
690 }
691#endif
692 return result;
Eric Laurenta553c252009-07-17 12:17:14 -0700693 }
Eric Laurenta553c252009-07-17 12:17:14 -0700694 return BAD_VALUE;
695}
696
Eric Laurentddb78e72009-07-28 08:44:33 -0700697String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
Eric Laurenta553c252009-07-17 12:17:14 -0700698{
Eric Laurentddb78e72009-07-28 08:44:33 -0700699// LOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
Eric Laurenta553c252009-07-17 12:17:14 -0700700// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
701
702 if (ioHandle == 0) {
703 return mAudioHardware->getParameters(keys);
704 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700705
706 Mutex::Autolock _l(mLock);
707
Eric Laurenta553c252009-07-17 12:17:14 -0700708 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
709 if (playbackThread != NULL) {
710 return playbackThread->getParameters(keys);
711 }
712 RecordThread *recordThread = checkRecordThread_l(ioHandle);
713 if (recordThread != NULL) {
714 return recordThread->getParameters(keys);
715 }
716 return String8("");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700717}
718
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800719size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
720{
721 return mAudioHardware->getInputBufferSize(sampleRate, format, channelCount);
722}
723
Eric Laurent47d0a922010-02-26 02:47:27 -0800724unsigned int AudioFlinger::getInputFramesLost(int ioHandle)
725{
726 if (ioHandle == 0) {
727 return 0;
728 }
729
730 Mutex::Autolock _l(mLock);
731
732 RecordThread *recordThread = checkRecordThread_l(ioHandle);
733 if (recordThread != NULL) {
734 return recordThread->getInputFramesLost();
735 }
736 return 0;
737}
738
Eric Laurent415f3e22009-10-21 08:14:22 -0700739status_t AudioFlinger::setVoiceVolume(float value)
740{
741 // check calling permissions
742 if (!settingsAllowed()) {
743 return PERMISSION_DENIED;
744 }
745
746 AutoMutex lock(mHardwareLock);
747 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
748 status_t ret = mAudioHardware->setVoiceVolume(value);
749 mHardwareStatus = AUDIO_HW_IDLE;
750
751 return ret;
752}
753
Eric Laurent0986e792010-01-19 17:37:09 -0800754status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int output)
755{
756 status_t status;
757
758 Mutex::Autolock _l(mLock);
759
760 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
761 if (playbackThread != NULL) {
762 return playbackThread->getRenderPosition(halFrames, dspFrames);
763 }
764
765 return BAD_VALUE;
766}
767
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800768void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
769{
Eric Laurenta553c252009-07-17 12:17:14 -0700770
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800771 Mutex::Autolock _l(mLock);
772
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700773 int pid = IPCThreadState::self()->getCallingPid();
774 if (mNotificationClients.indexOfKey(pid) < 0) {
775 sp<NotificationClient> notificationClient = new NotificationClient(this,
776 client,
777 pid);
778 LOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Eric Laurenta553c252009-07-17 12:17:14 -0700779
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700780 mNotificationClients.add(pid, notificationClient);
Eric Laurenta553c252009-07-17 12:17:14 -0700781
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700782 sp<IBinder> binder = client->asBinder();
783 binder->linkToDeath(notificationClient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800784
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700785 // the config change is always sent from playback or record threads to avoid deadlock
786 // with AudioSystem::gLock
787 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
788 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
789 }
Eric Laurenta553c252009-07-17 12:17:14 -0700790
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700791 for (size_t i = 0; i < mRecordThreads.size(); i++) {
792 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800793 }
794 }
795}
796
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700797void AudioFlinger::removeNotificationClient(pid_t pid)
798{
799 Mutex::Autolock _l(mLock);
800
801 int index = mNotificationClients.indexOfKey(pid);
802 if (index >= 0) {
803 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
804 LOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
805#ifdef LVMX
806 if (pid == mLifeVibesClientPid) {
807 LOGV("Disabling lifevibes");
808 LifeVibes::enableMusic(false);
809 mLifeVibesClientPid = -1;
810 }
811#endif
812 mNotificationClients.removeItem(pid);
813 }
814}
815
Eric Laurent296a0ec2009-09-15 07:10:12 -0700816// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700817void AudioFlinger::audioConfigChanged_l(int event, int ioHandle, void *param2)
818{
Eric Laurent49f02be2009-11-19 09:00:56 -0800819 size_t size = mNotificationClients.size();
820 for (size_t i = 0; i < size; i++) {
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700821 mNotificationClients.valueAt(i)->client()->ioConfigChanged(event, ioHandle, param2);
Eric Laurenta553c252009-07-17 12:17:14 -0700822 }
823}
824
Eric Laurentb9481d82009-09-17 05:12:56 -0700825// removeClient_l() must be called with AudioFlinger::mLock held
826void AudioFlinger::removeClient_l(pid_t pid)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700827{
Eric Laurentb9481d82009-09-17 05:12:56 -0700828 LOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700829 mClients.removeItem(pid);
830}
831
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700832
Eric Laurenta553c252009-07-17 12:17:14 -0700833// ----------------------------------------------------------------------------
834
Eric Laurent49f02be2009-11-19 09:00:56 -0800835AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, int id)
Eric Laurenta553c252009-07-17 12:17:14 -0700836 : Thread(false),
837 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
Eric Laurentb0a01472010-05-14 05:45:46 -0700838 mFrameSize(1), mFormat(0), mStandby(false), mId(id), mExiting(false)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700839{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800840}
841
Eric Laurenta553c252009-07-17 12:17:14 -0700842AudioFlinger::ThreadBase::~ThreadBase()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800843{
Eric Laurent8fce46a2009-08-04 09:45:33 -0700844 mParamCond.broadcast();
845 mNewParameters.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800846}
847
Eric Laurenta553c252009-07-17 12:17:14 -0700848void AudioFlinger::ThreadBase::exit()
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700849{
Eric Laurentb7d94602009-09-29 11:12:57 -0700850 // keep a strong ref on ourself so that we wont get
Eric Laurenta553c252009-07-17 12:17:14 -0700851 // destroyed in the middle of requestExitAndWait()
852 sp <ThreadBase> strongMe = this;
853
854 LOGV("ThreadBase::exit");
855 {
856 AutoMutex lock(&mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -0800857 mExiting = true;
Eric Laurenta553c252009-07-17 12:17:14 -0700858 requestExit();
859 mWaitWorkCV.signal();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700860 }
Eric Laurenta553c252009-07-17 12:17:14 -0700861 requestExitAndWait();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700862}
Eric Laurenta553c252009-07-17 12:17:14 -0700863
864uint32_t AudioFlinger::ThreadBase::sampleRate() const
865{
866 return mSampleRate;
867}
868
869int AudioFlinger::ThreadBase::channelCount() const
870{
Eric Laurentb0a01472010-05-14 05:45:46 -0700871 return (int)mChannelCount;
Eric Laurenta553c252009-07-17 12:17:14 -0700872}
873
874int AudioFlinger::ThreadBase::format() const
875{
876 return mFormat;
877}
878
879size_t AudioFlinger::ThreadBase::frameCount() const
880{
881 return mFrameCount;
882}
883
884status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
885{
Eric Laurent8fce46a2009-08-04 09:45:33 -0700886 status_t status;
Eric Laurenta553c252009-07-17 12:17:14 -0700887
Eric Laurent8fce46a2009-08-04 09:45:33 -0700888 LOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Eric Laurenta553c252009-07-17 12:17:14 -0700889 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700890
Eric Laurent8fce46a2009-08-04 09:45:33 -0700891 mNewParameters.add(keyValuePairs);
Eric Laurenta553c252009-07-17 12:17:14 -0700892 mWaitWorkCV.signal();
Eric Laurentb7d94602009-09-29 11:12:57 -0700893 // wait condition with timeout in case the thread loop has exited
894 // before the request could be processed
895 if (mParamCond.waitRelative(mLock, seconds(2)) == NO_ERROR) {
896 status = mParamStatus;
897 mWaitWorkCV.signal();
898 } else {
899 status = TIMED_OUT;
900 }
Eric Laurent8fce46a2009-08-04 09:45:33 -0700901 return status;
Eric Laurenta553c252009-07-17 12:17:14 -0700902}
903
904void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
905{
906 Mutex::Autolock _l(mLock);
Eric Laurent8fce46a2009-08-04 09:45:33 -0700907 sendConfigEvent_l(event, param);
908}
909
910// sendConfigEvent_l() must be called with ThreadBase::mLock held
911void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
912{
Eric Laurenta553c252009-07-17 12:17:14 -0700913 ConfigEvent *configEvent = new ConfigEvent();
914 configEvent->mEvent = event;
915 configEvent->mParam = param;
916 mConfigEvents.add(configEvent);
917 LOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
918 mWaitWorkCV.signal();
919}
920
921void AudioFlinger::ThreadBase::processConfigEvents()
922{
923 mLock.lock();
924 while(!mConfigEvents.isEmpty()) {
925 LOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
926 ConfigEvent *configEvent = mConfigEvents[0];
927 mConfigEvents.removeAt(0);
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700928 // release mLock before locking AudioFlinger mLock: lock order is always
929 // AudioFlinger then ThreadBase to avoid cross deadlock
Eric Laurenta553c252009-07-17 12:17:14 -0700930 mLock.unlock();
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700931 mAudioFlinger->mLock.lock();
932 audioConfigChanged_l(configEvent->mEvent, configEvent->mParam);
933 mAudioFlinger->mLock.unlock();
Eric Laurenta553c252009-07-17 12:17:14 -0700934 delete configEvent;
935 mLock.lock();
936 }
937 mLock.unlock();
938}
939
Eric Laurent3fdb1262009-11-07 00:01:32 -0800940status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
941{
942 const size_t SIZE = 256;
943 char buffer[SIZE];
944 String8 result;
945
946 bool locked = tryLock(mLock);
947 if (!locked) {
948 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
949 write(fd, buffer, strlen(buffer));
950 }
951
952 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
953 result.append(buffer);
954 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
955 result.append(buffer);
956 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
957 result.append(buffer);
958 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
959 result.append(buffer);
960 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
961 result.append(buffer);
962 snprintf(buffer, SIZE, "Frame size: %d\n", mFrameSize);
963 result.append(buffer);
964
965 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
966 result.append(buffer);
967 result.append(" Index Command");
968 for (size_t i = 0; i < mNewParameters.size(); ++i) {
969 snprintf(buffer, SIZE, "\n %02d ", i);
970 result.append(buffer);
971 result.append(mNewParameters[i]);
972 }
973
974 snprintf(buffer, SIZE, "\n\nPending config events: \n");
975 result.append(buffer);
976 snprintf(buffer, SIZE, " Index event param\n");
977 result.append(buffer);
978 for (size_t i = 0; i < mConfigEvents.size(); i++) {
979 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i]->mEvent, mConfigEvents[i]->mParam);
980 result.append(buffer);
981 }
982 result.append("\n");
983
984 write(fd, result.string(), result.size());
985
986 if (locked) {
987 mLock.unlock();
988 }
989 return NO_ERROR;
990}
991
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800992
993// ----------------------------------------------------------------------------
994
Eric Laurent65b65452010-06-01 23:49:17 -0700995AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Eric Laurent49f02be2009-11-19 09:00:56 -0800996 : ThreadBase(audioFlinger, id),
Eric Laurentd5603c12009-08-06 08:49:39 -0700997 mMixBuffer(0), mSuspended(0), mBytesWritten(0), mOutput(output),
Eric Laurent65b65452010-06-01 23:49:17 -0700998 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
999 mDevice(device)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001000{
Eric Laurenta553c252009-07-17 12:17:14 -07001001 readOutputParameters();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001002
Eric Laurenta553c252009-07-17 12:17:14 -07001003 mMasterVolume = mAudioFlinger->masterVolume();
1004 mMasterMute = mAudioFlinger->masterMute();
1005
1006 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
1007 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
1008 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001009 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001010}
1011
Eric Laurenta553c252009-07-17 12:17:14 -07001012AudioFlinger::PlaybackThread::~PlaybackThread()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001013{
1014 delete [] mMixBuffer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001015}
1016
Eric Laurenta553c252009-07-17 12:17:14 -07001017status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001018{
1019 dumpInternals(fd, args);
1020 dumpTracks(fd, args);
Eric Laurent65b65452010-06-01 23:49:17 -07001021 dumpEffectChains(fd, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001022 return NO_ERROR;
1023}
1024
Eric Laurenta553c252009-07-17 12:17:14 -07001025status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001026{
1027 const size_t SIZE = 256;
1028 char buffer[SIZE];
1029 String8 result;
1030
Eric Laurenta553c252009-07-17 12:17:14 -07001031 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001032 result.append(buffer);
Eric Laurent65b65452010-06-01 23:49:17 -07001033 result.append(" Name Clien Typ Fmt Chn Session Buf S M F SRate LeftV RighV Serv User Main buf Aux Buf\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001034 for (size_t i = 0; i < mTracks.size(); ++i) {
Eric Laurentd3b4d0c2009-03-31 14:34:35 -07001035 sp<Track> track = mTracks[i];
1036 if (track != 0) {
1037 track->dump(buffer, SIZE);
1038 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001039 }
1040 }
1041
Eric Laurenta553c252009-07-17 12:17:14 -07001042 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001043 result.append(buffer);
Eric Laurent65b65452010-06-01 23:49:17 -07001044 result.append(" Name Clien Typ Fmt Chn Session Buf S M F SRate LeftV RighV Serv User Main buf Aux Buf\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001045 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Eric Laurentd3b4d0c2009-03-31 14:34:35 -07001046 wp<Track> wTrack = mActiveTracks[i];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001047 if (wTrack != 0) {
1048 sp<Track> track = wTrack.promote();
1049 if (track != 0) {
1050 track->dump(buffer, SIZE);
1051 result.append(buffer);
1052 }
1053 }
1054 }
1055 write(fd, result.string(), result.size());
1056 return NO_ERROR;
1057}
1058
Eric Laurent65b65452010-06-01 23:49:17 -07001059status_t AudioFlinger::PlaybackThread::dumpEffectChains(int fd, const Vector<String16>& args)
1060{
1061 const size_t SIZE = 256;
1062 char buffer[SIZE];
1063 String8 result;
1064
1065 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1066 write(fd, buffer, strlen(buffer));
1067
1068 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1069 sp<EffectChain> chain = mEffectChains[i];
1070 if (chain != 0) {
1071 chain->dump(fd, args);
1072 }
1073 }
1074 return NO_ERROR;
1075}
1076
Eric Laurenta553c252009-07-17 12:17:14 -07001077status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001078{
1079 const size_t SIZE = 256;
1080 char buffer[SIZE];
1081 String8 result;
1082
Eric Laurent3fdb1262009-11-07 00:01:32 -08001083 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001084 result.append(buffer);
1085 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1086 result.append(buffer);
1087 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1088 result.append(buffer);
1089 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1090 result.append(buffer);
1091 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1092 result.append(buffer);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08001093 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1094 result.append(buffer);
Eric Laurent65b65452010-06-01 23:49:17 -07001095 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1096 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001097 write(fd, result.string(), result.size());
Eric Laurent3fdb1262009-11-07 00:01:32 -08001098
1099 dumpBase(fd, args);
1100
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001101 return NO_ERROR;
1102}
1103
1104// Thread virtuals
Eric Laurenta553c252009-07-17 12:17:14 -07001105status_t AudioFlinger::PlaybackThread::readyToRun()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001106{
1107 if (mSampleRate == 0) {
1108 LOGE("No working audio driver found.");
1109 return NO_INIT;
1110 }
Eric Laurenta553c252009-07-17 12:17:14 -07001111 LOGI("AudioFlinger's thread %p ready to run", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001112 return NO_ERROR;
1113}
1114
Eric Laurenta553c252009-07-17 12:17:14 -07001115void AudioFlinger::PlaybackThread::onFirstRef()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001116{
1117 const size_t SIZE = 256;
1118 char buffer[SIZE];
1119
Eric Laurenta553c252009-07-17 12:17:14 -07001120 snprintf(buffer, SIZE, "Playback Thread %p", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001121
1122 run(buffer, ANDROID_PRIORITY_URGENT_AUDIO);
1123}
1124
Eric Laurenta553c252009-07-17 12:17:14 -07001125// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1126sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001127 const sp<AudioFlinger::Client>& client,
1128 int streamType,
1129 uint32_t sampleRate,
1130 int format,
1131 int channelCount,
1132 int frameCount,
1133 const sp<IMemory>& sharedBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -07001134 int sessionId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001135 status_t *status)
1136{
1137 sp<Track> track;
1138 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07001139
1140 if (mType == DIRECT) {
Eric Laurentb0a01472010-05-14 05:45:46 -07001141 if (sampleRate != mSampleRate || format != mFormat || channelCount != (int)mChannelCount) {
Eric Laurenta553c252009-07-17 12:17:14 -07001142 LOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelCount %d for output %p",
1143 sampleRate, format, channelCount, mOutput);
1144 lStatus = BAD_VALUE;
1145 goto Exit;
1146 }
1147 } else {
1148 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1149 if (sampleRate > mSampleRate*2) {
1150 LOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
1151 lStatus = BAD_VALUE;
1152 goto Exit;
1153 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001154 }
1155
Eric Laurenta553c252009-07-17 12:17:14 -07001156 if (mOutput == 0) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001157 LOGE("Audio driver not initialized.");
1158 lStatus = NO_INIT;
1159 goto Exit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001160 }
1161
Eric Laurenta553c252009-07-17 12:17:14 -07001162 { // scope for mLock
1163 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001164
1165 // all tracks in same audio session must share the same routing strategy otherwise
1166 // conflicts will happen when tracks are moved from one output to another by audio policy
1167 // manager
1168 uint32_t strategy =
1169 AudioSystem::getStrategyForStream((AudioSystem::stream_type)streamType);
1170 for (size_t i = 0; i < mTracks.size(); ++i) {
1171 sp<Track> t = mTracks[i];
1172 if (t != 0) {
1173 if (sessionId == t->sessionId() &&
1174 strategy != AudioSystem::getStrategyForStream((AudioSystem::stream_type)t->type())) {
1175 lStatus = BAD_VALUE;
1176 goto Exit;
1177 }
1178 }
1179 }
1180
Eric Laurenta553c252009-07-17 12:17:14 -07001181 track = new Track(this, client, streamType, sampleRate, format,
Eric Laurent65b65452010-06-01 23:49:17 -07001182 channelCount, frameCount, sharedBuffer, sessionId);
Eric Laurent73b60352009-11-09 04:45:39 -08001183 if (track->getCblk() == NULL || track->name() < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07001184 lStatus = NO_MEMORY;
1185 goto Exit;
1186 }
1187 mTracks.add(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001188
1189 sp<EffectChain> chain = getEffectChain_l(sessionId);
1190 if (chain != 0) {
1191 LOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1192 track->setMainBuffer(chain->inBuffer());
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001193 chain->setStrategy(AudioSystem::getStrategyForStream((AudioSystem::stream_type)track->type()));
Eric Laurent65b65452010-06-01 23:49:17 -07001194 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001195 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001196 lStatus = NO_ERROR;
1197
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001198Exit:
1199 if(status) {
1200 *status = lStatus;
1201 }
1202 return track;
1203}
1204
Eric Laurenta553c252009-07-17 12:17:14 -07001205uint32_t AudioFlinger::PlaybackThread::latency() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001206{
1207 if (mOutput) {
1208 return mOutput->latency();
1209 }
1210 else {
1211 return 0;
1212 }
1213}
1214
Eric Laurenta553c252009-07-17 12:17:14 -07001215status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001216{
Glenn Kasten871c16c2010-03-05 12:18:01 -08001217#ifdef LVMX
1218 int audioOutputType = LifeVibes::getMixerType(mId, mType);
1219 if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType)) {
1220 LifeVibes::setMasterVolume(audioOutputType, value);
1221 }
1222#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001223 mMasterVolume = value;
1224 return NO_ERROR;
1225}
1226
Eric Laurenta553c252009-07-17 12:17:14 -07001227status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001228{
Glenn Kasten871c16c2010-03-05 12:18:01 -08001229#ifdef LVMX
1230 int audioOutputType = LifeVibes::getMixerType(mId, mType);
1231 if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType)) {
1232 LifeVibes::setMasterMute(audioOutputType, muted);
1233 }
1234#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001235 mMasterMute = muted;
1236 return NO_ERROR;
1237}
1238
Eric Laurenta553c252009-07-17 12:17:14 -07001239float AudioFlinger::PlaybackThread::masterVolume() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001240{
1241 return mMasterVolume;
1242}
1243
Eric Laurenta553c252009-07-17 12:17:14 -07001244bool AudioFlinger::PlaybackThread::masterMute() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001245{
1246 return mMasterMute;
1247}
1248
Eric Laurenta553c252009-07-17 12:17:14 -07001249status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001250{
Glenn Kasten871c16c2010-03-05 12:18:01 -08001251#ifdef LVMX
1252 int audioOutputType = LifeVibes::getMixerType(mId, mType);
1253 if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType)) {
1254 LifeVibes::setStreamVolume(audioOutputType, stream, value);
1255 }
1256#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001257 mStreamTypes[stream].volume = value;
1258 return NO_ERROR;
1259}
1260
Eric Laurenta553c252009-07-17 12:17:14 -07001261status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001262{
Glenn Kasten871c16c2010-03-05 12:18:01 -08001263#ifdef LVMX
1264 int audioOutputType = LifeVibes::getMixerType(mId, mType);
1265 if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType)) {
1266 LifeVibes::setStreamMute(audioOutputType, stream, muted);
1267 }
1268#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001269 mStreamTypes[stream].mute = muted;
1270 return NO_ERROR;
1271}
1272
Eric Laurenta553c252009-07-17 12:17:14 -07001273float AudioFlinger::PlaybackThread::streamVolume(int stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001274{
1275 return mStreamTypes[stream].volume;
1276}
1277
Eric Laurenta553c252009-07-17 12:17:14 -07001278bool AudioFlinger::PlaybackThread::streamMute(int stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001279{
1280 return mStreamTypes[stream].mute;
1281}
1282
Eric Laurenta553c252009-07-17 12:17:14 -07001283// addTrack_l() must be called with ThreadBase::mLock held
1284status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001285{
1286 status_t status = ALREADY_EXISTS;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001287
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001288 // set retry count for buffer fill
1289 track->mRetryCount = kMaxTrackStartupRetries;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001290 if (mActiveTracks.indexOf(track) < 0) {
1291 // the track is newly added, make sure it fills up all its
1292 // buffers before playing. This is to ensure the client will
1293 // effectively get the latency it requested.
1294 track->mFillingUpStatus = Track::FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001295 track->mResetDone = false;
Eric Laurenta553c252009-07-17 12:17:14 -07001296 mActiveTracks.add(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001297 if (track->mainBuffer() != mMixBuffer) {
1298 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1299 if (chain != 0) {
1300 LOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
1301 chain->startTrack();
1302 }
1303 }
1304
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001305 status = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001306 }
Eric Laurenta553c252009-07-17 12:17:14 -07001307
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001308 LOGV("mWaitWorkCV.broadcast");
Eric Laurenta553c252009-07-17 12:17:14 -07001309 mWaitWorkCV.broadcast();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001310
1311 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001312}
1313
Eric Laurenta553c252009-07-17 12:17:14 -07001314// destroyTrack_l() must be called with ThreadBase::mLock held
1315void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001316{
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001317 track->mState = TrackBase::TERMINATED;
1318 if (mActiveTracks.indexOf(track) < 0) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001319 mTracks.remove(track);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001320 deleteTrackName_l(track->name());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001321 }
1322}
1323
Eric Laurenta553c252009-07-17 12:17:14 -07001324String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001325{
Eric Laurenta553c252009-07-17 12:17:14 -07001326 return mOutput->getParameters(keys);
1327}
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001328
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001329// destroyTrack_l() must be called with AudioFlinger::mLock held
1330void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
Eric Laurenta553c252009-07-17 12:17:14 -07001331 AudioSystem::OutputDescriptor desc;
1332 void *param2 = 0;
1333
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001334 LOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Eric Laurenta553c252009-07-17 12:17:14 -07001335
1336 switch (event) {
1337 case AudioSystem::OUTPUT_OPENED:
1338 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Eric Laurentb0a01472010-05-14 05:45:46 -07001339 desc.channels = mChannels;
Eric Laurenta553c252009-07-17 12:17:14 -07001340 desc.samplingRate = mSampleRate;
1341 desc.format = mFormat;
1342 desc.frameCount = mFrameCount;
1343 desc.latency = latency();
1344 param2 = &desc;
1345 break;
1346
1347 case AudioSystem::STREAM_CONFIG_CHANGED:
1348 param2 = &param;
1349 case AudioSystem::OUTPUT_CLOSED:
1350 default:
1351 break;
1352 }
Eric Laurent49f02be2009-11-19 09:00:56 -08001353 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurenta553c252009-07-17 12:17:14 -07001354}
1355
1356void AudioFlinger::PlaybackThread::readOutputParameters()
1357{
1358 mSampleRate = mOutput->sampleRate();
Eric Laurentb0a01472010-05-14 05:45:46 -07001359 mChannels = mOutput->channels();
1360 mChannelCount = (uint16_t)AudioSystem::popCount(mChannels);
Eric Laurenta553c252009-07-17 12:17:14 -07001361 mFormat = mOutput->format();
Eric Laurentb0a01472010-05-14 05:45:46 -07001362 mFrameSize = (uint16_t)mOutput->frameSize();
Eric Laurenta553c252009-07-17 12:17:14 -07001363 mFrameCount = mOutput->bufferSize() / mFrameSize;
1364
Eric Laurenta553c252009-07-17 12:17:14 -07001365 // FIXME - Current mixer implementation only supports stereo output: Always
1366 // Allocate a stereo buffer even if HW output is mono.
Eric Laurent65b65452010-06-01 23:49:17 -07001367 if (mMixBuffer != NULL) delete[] mMixBuffer;
Eric Laurenta553c252009-07-17 12:17:14 -07001368 mMixBuffer = new int16_t[mFrameCount * 2];
1369 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
Eric Laurent65b65452010-06-01 23:49:17 -07001370
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001371 // force reconfiguration of effect chains and engines to take new buffer size and audio
1372 // parameters into account
1373 // Note that mLock is not held when readOutputParameters() is called from the constructor
1374 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1375 // matter.
1376 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1377 Vector< sp<EffectChain> > effectChains = mEffectChains;
1378 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent493941b2010-07-28 01:32:47 -07001379 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001380 }
Eric Laurenta553c252009-07-17 12:17:14 -07001381}
1382
Eric Laurent0986e792010-01-19 17:37:09 -08001383status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1384{
1385 if (halFrames == 0 || dspFrames == 0) {
1386 return BAD_VALUE;
1387 }
1388 if (mOutput == 0) {
1389 return INVALID_OPERATION;
1390 }
1391 *halFrames = mBytesWritten/mOutput->frameSize();
1392
1393 return mOutput->getRenderPosition(dspFrames);
1394}
1395
Eric Laurent493941b2010-07-28 01:32:47 -07001396uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Eric Laurent65b65452010-06-01 23:49:17 -07001397{
1398 Mutex::Autolock _l(mLock);
Eric Laurent493941b2010-07-28 01:32:47 -07001399 uint32_t result = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07001400 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent493941b2010-07-28 01:32:47 -07001401 result = EFFECT_SESSION;
Eric Laurent65b65452010-06-01 23:49:17 -07001402 }
1403
1404 for (size_t i = 0; i < mTracks.size(); ++i) {
1405 sp<Track> track = mTracks[i];
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001406 if (sessionId == track->sessionId() &&
1407 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent493941b2010-07-28 01:32:47 -07001408 result |= TRACK_SESSION;
1409 break;
Eric Laurent65b65452010-06-01 23:49:17 -07001410 }
1411 }
1412
Eric Laurent493941b2010-07-28 01:32:47 -07001413 return result;
Eric Laurent65b65452010-06-01 23:49:17 -07001414}
1415
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001416uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1417{
1418 // session AudioSystem::SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
1419 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
1420 if (sessionId == AudioSystem::SESSION_OUTPUT_MIX) {
1421 return AudioSystem::getStrategyForStream(AudioSystem::MUSIC);
1422 }
1423 for (size_t i = 0; i < mTracks.size(); i++) {
1424 sp<Track> track = mTracks[i];
1425 if (sessionId == track->sessionId() &&
1426 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
1427 return AudioSystem::getStrategyForStream((AudioSystem::stream_type) track->type());
1428 }
1429 }
1430 return AudioSystem::getStrategyForStream(AudioSystem::MUSIC);
1431}
1432
Eric Laurent65b65452010-06-01 23:49:17 -07001433sp<AudioFlinger::EffectChain> AudioFlinger::PlaybackThread::getEffectChain(int sessionId)
1434{
1435 Mutex::Autolock _l(mLock);
1436 return getEffectChain_l(sessionId);
1437}
1438
1439sp<AudioFlinger::EffectChain> AudioFlinger::PlaybackThread::getEffectChain_l(int sessionId)
1440{
1441 sp<EffectChain> chain;
1442
1443 size_t size = mEffectChains.size();
1444 for (size_t i = 0; i < size; i++) {
1445 if (mEffectChains[i]->sessionId() == sessionId) {
1446 chain = mEffectChains[i];
1447 break;
1448 }
1449 }
1450 return chain;
1451}
1452
Eric Laurent53334cd2010-06-23 17:38:20 -07001453void AudioFlinger::PlaybackThread::setMode(uint32_t mode)
1454{
1455 Mutex::Autolock _l(mLock);
1456 size_t size = mEffectChains.size();
1457 for (size_t i = 0; i < size; i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07001458 mEffectChains[i]->setMode_l(mode);
Eric Laurent53334cd2010-06-23 17:38:20 -07001459 }
1460}
1461
Eric Laurenta553c252009-07-17 12:17:14 -07001462// ----------------------------------------------------------------------------
1463
Eric Laurent65b65452010-06-01 23:49:17 -07001464AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
1465 : PlaybackThread(audioFlinger, output, id, device),
Eric Laurenta553c252009-07-17 12:17:14 -07001466 mAudioMixer(0)
1467{
1468 mType = PlaybackThread::MIXER;
1469 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1470
1471 // FIXME - Current mixer implementation only supports stereo output
1472 if (mChannelCount == 1) {
1473 LOGE("Invalid audio hardware channel count");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001474 }
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001475}
1476
Eric Laurenta553c252009-07-17 12:17:14 -07001477AudioFlinger::MixerThread::~MixerThread()
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001478{
Eric Laurenta553c252009-07-17 12:17:14 -07001479 delete mAudioMixer;
1480}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001481
Eric Laurenta553c252009-07-17 12:17:14 -07001482bool AudioFlinger::MixerThread::threadLoop()
1483{
Eric Laurenta553c252009-07-17 12:17:14 -07001484 Vector< sp<Track> > tracksToRemove;
Eric Laurent059b4be2009-11-09 23:32:22 -08001485 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001486 nsecs_t standbyTime = systemTime();
1487 size_t mixBufferSize = mFrameCount * mFrameSize;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001488 // FIXME: Relaxed timing because of a certain device that can't meet latency
1489 // Should be reduced to 2x after the vendor fixes the driver issue
1490 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
1491 nsecs_t lastWarning = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08001492 bool longStandbyExit = false;
1493 uint32_t activeSleepTime = activeSleepTimeUs();
1494 uint32_t idleSleepTime = idleSleepTimeUs();
1495 uint32_t sleepTime = idleSleepTime;
Eric Laurent65b65452010-06-01 23:49:17 -07001496 Vector< sp<EffectChain> > effectChains;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001497
Eric Laurenta553c252009-07-17 12:17:14 -07001498 while (!exitPending())
1499 {
1500 processConfigEvents();
1501
Eric Laurent059b4be2009-11-09 23:32:22 -08001502 mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001503 { // scope for mLock
1504
1505 Mutex::Autolock _l(mLock);
1506
1507 if (checkForNewParameters_l()) {
1508 mixBufferSize = mFrameCount * mFrameSize;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001509 // FIXME: Relaxed timing because of a certain device that can't meet latency
1510 // Should be reduced to 2x after the vendor fixes the driver issue
1511 maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
Eric Laurent059b4be2009-11-09 23:32:22 -08001512 activeSleepTime = activeSleepTimeUs();
1513 idleSleepTime = idleSleepTimeUs();
Eric Laurenta553c252009-07-17 12:17:14 -07001514 }
1515
1516 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1517
1518 // put audio hardware into standby after short delay
1519 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1520 mSuspended) {
1521 if (!mStandby) {
1522 LOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
1523 mOutput->standby();
1524 mStandby = true;
1525 mBytesWritten = 0;
1526 }
1527
1528 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1529 // we're about to wait, flush the binder command buffer
1530 IPCThreadState::self()->flushCommands();
1531
1532 if (exitPending()) break;
1533
1534 // wait until we have something to do...
1535 LOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
1536 mWaitWorkCV.wait(mLock);
1537 LOGV("MixerThread %p TID %d waking up\n", this, gettid());
1538
1539 if (mMasterMute == false) {
1540 char value[PROPERTY_VALUE_MAX];
1541 property_get("ro.audio.silent", value, "0");
1542 if (atoi(value)) {
1543 LOGD("Silence is golden");
1544 setMasterMute(true);
1545 }
1546 }
1547
1548 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent059b4be2009-11-09 23:32:22 -08001549 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07001550 continue;
1551 }
1552 }
1553
Eric Laurent059b4be2009-11-09 23:32:22 -08001554 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07001555
1556 // prevent any changes in effect chain list and in each effect chain
1557 // during mixing and effect process as the audio buffers could be deleted
1558 // or modified if an effect is created or deleted
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001559 lockEffectChains_l(effectChains);
Eric Laurenta553c252009-07-17 12:17:14 -07001560 }
1561
Eric Laurent059b4be2009-11-09 23:32:22 -08001562 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07001563 // mix buffers...
Eric Laurent65b65452010-06-01 23:49:17 -07001564 mAudioMixer->process();
Eric Laurentf69a3f82009-09-22 00:35:48 -07001565 sleepTime = 0;
1566 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent65b65452010-06-01 23:49:17 -07001567 //TODO: delay standby when effects have a tail
Eric Laurent96c08a62009-09-07 08:38:38 -07001568 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07001569 // If no tracks are ready, sleep once for the duration of an output
1570 // buffer size, then write 0s to the output
1571 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08001572 if (mixerStatus == MIXER_TRACKS_ENABLED) {
1573 sleepTime = activeSleepTime;
1574 } else {
1575 sleepTime = idleSleepTime;
1576 }
1577 } else if (mBytesWritten != 0 ||
1578 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Eric Laurent65b65452010-06-01 23:49:17 -07001579 memset (mMixBuffer, 0, mixBufferSize);
Eric Laurent96c08a62009-09-07 08:38:38 -07001580 sleepTime = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08001581 LOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Eric Laurent96c08a62009-09-07 08:38:38 -07001582 }
Eric Laurent65b65452010-06-01 23:49:17 -07001583 // TODO add standby time extension fct of effect tail
Eric Laurentf69a3f82009-09-22 00:35:48 -07001584 }
1585
1586 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07001587 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07001588 }
1589 // sleepTime == 0 means we must write to audio hardware
1590 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07001591 for (size_t i = 0; i < effectChains.size(); i ++) {
1592 effectChains[i]->process_l();
1593 }
1594 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001595 unlockEffectChains(effectChains);
Glenn Kasten871c16c2010-03-05 12:18:01 -08001596#ifdef LVMX
1597 int audioOutputType = LifeVibes::getMixerType(mId, mType);
1598 if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType)) {
Eric Laurent65b65452010-06-01 23:49:17 -07001599 LifeVibes::process(audioOutputType, mMixBuffer, mixBufferSize);
Glenn Kasten871c16c2010-03-05 12:18:01 -08001600 }
1601#endif
Eric Laurent65b65452010-06-01 23:49:17 -07001602 mLastWriteTime = systemTime();
1603 mInWrite = true;
1604 mBytesWritten += mixBufferSize;
1605
1606 int bytesWritten = (int)mOutput->write(mMixBuffer, mixBufferSize);
Eric Laurent0986e792010-01-19 17:37:09 -08001607 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07001608 mNumWrites++;
1609 mInWrite = false;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001610 nsecs_t now = systemTime();
1611 nsecs_t delta = now - mLastWriteTime;
Eric Laurentf69a3f82009-09-22 00:35:48 -07001612 if (delta > maxPeriod) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07001613 mNumDelayedWrites++;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001614 if ((now - lastWarning) > kWarningThrottle) {
1615 LOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
1616 ns2ms(delta), mNumDelayedWrites, this);
1617 lastWarning = now;
1618 }
Eric Laurent059b4be2009-11-09 23:32:22 -08001619 if (mStandby) {
1620 longStandbyExit = true;
1621 }
Eric Laurenta553c252009-07-17 12:17:14 -07001622 }
Eric Laurent059b4be2009-11-09 23:32:22 -08001623 mStandby = false;
Eric Laurentf69a3f82009-09-22 00:35:48 -07001624 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07001625 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001626 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07001627 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07001628 }
1629
1630 // finally let go of all our tracks, without the lock held
1631 // since we can't guarantee the destructors won't acquire that
1632 // same lock.
1633 tracksToRemove.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07001634
1635 // Effect chains will be actually deleted here if they were removed from
1636 // mEffectChains list during mixing or effects processing
1637 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07001638 }
1639
1640 if (!mStandby) {
1641 mOutput->standby();
1642 }
Eric Laurenta553c252009-07-17 12:17:14 -07001643
1644 LOGV("MixerThread %p exiting", this);
1645 return false;
1646}
1647
1648// prepareTracks_l() must be called with ThreadBase::mLock held
Eric Laurent059b4be2009-11-09 23:32:22 -08001649uint32_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
Eric Laurenta553c252009-07-17 12:17:14 -07001650{
1651
Eric Laurent059b4be2009-11-09 23:32:22 -08001652 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001653 // find out which tracks need to be processed
1654 size_t count = activeTracks.size();
Eric Laurent65b65452010-06-01 23:49:17 -07001655 size_t mixedTracks = 0;
1656 size_t tracksWithEffect = 0;
Glenn Kasten871c16c2010-03-05 12:18:01 -08001657
1658 float masterVolume = mMasterVolume;
1659 bool masterMute = mMasterMute;
1660
Eric Laurent8cc93b92010-08-11 05:20:11 -07001661 if (masterMute) {
1662 masterVolume = 0;
1663 }
Glenn Kasten871c16c2010-03-05 12:18:01 -08001664#ifdef LVMX
1665 bool tracksConnectedChanged = false;
1666 bool stateChanged = false;
1667
1668 int audioOutputType = LifeVibes::getMixerType(mId, mType);
1669 if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType))
1670 {
1671 int activeTypes = 0;
1672 for (size_t i=0 ; i<count ; i++) {
1673 sp<Track> t = activeTracks[i].promote();
1674 if (t == 0) continue;
1675 Track* const track = t.get();
1676 int iTracktype=track->type();
1677 activeTypes |= 1<<track->type();
1678 }
1679 LifeVibes::computeVolumes(audioOutputType, activeTypes, tracksConnectedChanged, stateChanged, masterVolume, masterMute);
1680 }
1681#endif
Eric Laurent65b65452010-06-01 23:49:17 -07001682 // Delegate master volume control to effect in output mix effect chain if needed
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001683 sp<EffectChain> chain = getEffectChain_l(AudioSystem::SESSION_OUTPUT_MIX);
Eric Laurent65b65452010-06-01 23:49:17 -07001684 if (chain != 0) {
Eric Laurent8cc93b92010-08-11 05:20:11 -07001685 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurent76c40f72010-07-15 12:50:15 -07001686 chain->setVolume_l(&v, &v);
Eric Laurent65b65452010-06-01 23:49:17 -07001687 masterVolume = (float)((v + (1 << 23)) >> 24);
1688 chain.clear();
1689 }
Glenn Kasten871c16c2010-03-05 12:18:01 -08001690
Eric Laurenta553c252009-07-17 12:17:14 -07001691 for (size_t i=0 ; i<count ; i++) {
1692 sp<Track> t = activeTracks[i].promote();
1693 if (t == 0) continue;
1694
1695 Track* const track = t.get();
1696 audio_track_cblk_t* cblk = track->cblk();
1697
1698 // The first time a track is added we wait
1699 // for all its buffers to be filled before processing it
1700 mAudioMixer->setActiveTrack(track->name());
Eric Laurent9a30fc12010-10-05 14:41:42 -07001701 if (cblk->framesReady() && track->isReady() &&
Eric Laurent71f37cd2010-03-31 12:21:17 -07001702 !track->isPaused() && !track->isTerminated())
Eric Laurenta553c252009-07-17 12:17:14 -07001703 {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08001704 //LOGV("track %d u=%08x, s=%08x [OK] on thread %p", track->name(), cblk->user, cblk->server, this);
Eric Laurenta553c252009-07-17 12:17:14 -07001705
Eric Laurent65b65452010-06-01 23:49:17 -07001706 mixedTracks++;
1707
1708 // track->mainBuffer() != mMixBuffer means there is an effect chain
1709 // connected to the track
1710 chain.clear();
1711 if (track->mainBuffer() != mMixBuffer) {
1712 chain = getEffectChain_l(track->sessionId());
1713 // Delegate volume control to effect in track effect chain if needed
1714 if (chain != 0) {
1715 tracksWithEffect++;
1716 } else {
1717 LOGW("prepareTracks_l(): track %08x attached to effect but no chain found on session %d",
1718 track->name(), track->sessionId());
1719 }
1720 }
1721
1722
1723 int param = AudioMixer::VOLUME;
1724 if (track->mFillingUpStatus == Track::FS_FILLED) {
1725 // no ramp for the first volume setting
1726 track->mFillingUpStatus = Track::FS_ACTIVE;
1727 if (track->mState == TrackBase::RESUMING) {
1728 track->mState = TrackBase::ACTIVE;
1729 param = AudioMixer::RAMP_VOLUME;
1730 }
1731 } else if (cblk->server != 0) {
1732 // If the track is stopped before the first frame was mixed,
1733 // do not apply ramp
1734 param = AudioMixer::RAMP_VOLUME;
1735 }
1736
Eric Laurenta553c252009-07-17 12:17:14 -07001737 // compute volume for this track
Eric Laurent27a2fdf2010-09-10 17:44:44 -07001738 uint32_t vl, vr, va;
Eric Laurent2a6b80b2010-07-29 23:43:43 -07001739 if (track->isMuted() || track->isPausing() ||
Eric Laurenta553c252009-07-17 12:17:14 -07001740 mStreamTypes[track->type()].mute) {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07001741 vl = vr = va = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07001742 if (track->isPausing()) {
1743 track->setPaused();
1744 }
1745 } else {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07001746
Glenn Kasten871c16c2010-03-05 12:18:01 -08001747 // read original volumes with volume control
Eric Laurenta553c252009-07-17 12:17:14 -07001748 float typeVolume = mStreamTypes[track->type()].volume;
Glenn Kasten871c16c2010-03-05 12:18:01 -08001749#ifdef LVMX
1750 bool streamMute=false;
1751 // read the volume from the LivesVibes audio engine.
1752 if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType))
1753 {
1754 LifeVibes::getStreamVolumes(audioOutputType, track->type(), &typeVolume, &streamMute);
1755 if (streamMute) {
1756 typeVolume = 0;
1757 }
1758 }
1759#endif
1760 float v = masterVolume * typeVolume;
Eric Laurent27a2fdf2010-09-10 17:44:44 -07001761 vl = (uint32_t)(v * cblk->volume[0]) << 12;
1762 vr = (uint32_t)(v * cblk->volume[1]) << 12;
Eric Laurenta553c252009-07-17 12:17:14 -07001763
Eric Laurent27a2fdf2010-09-10 17:44:44 -07001764 va = (uint32_t)(v * cblk->sendLevel);
Eric Laurenta553c252009-07-17 12:17:14 -07001765 }
Eric Laurent27a2fdf2010-09-10 17:44:44 -07001766 // Delegate volume control to effect in track effect chain if needed
1767 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
1768 // Do not ramp volume if volume is controlled by effect
1769 param = AudioMixer::VOLUME;
1770 track->mHasVolumeController = true;
1771 } else {
1772 // force no volume ramp when volume controller was just disabled or removed
1773 // from effect chain to avoid volume spike
1774 if (track->mHasVolumeController) {
1775 param = AudioMixer::VOLUME;
1776 }
1777 track->mHasVolumeController = false;
1778 }
1779
1780 // Convert volumes from 8.24 to 4.12 format
1781 int16_t left, right, aux;
1782 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
1783 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
1784 left = int16_t(v_clamped);
1785 v_clamped = (vr + (1 << 11)) >> 12;
1786 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
1787 right = int16_t(v_clamped);
1788
1789 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
1790 aux = int16_t(va);
Eric Laurent65b65452010-06-01 23:49:17 -07001791
Glenn Kasten871c16c2010-03-05 12:18:01 -08001792#ifdef LVMX
1793 if ( tracksConnectedChanged || stateChanged )
1794 {
1795 // only do the ramp when the volume is changed by the user / application
1796 param = AudioMixer::VOLUME;
1797 }
1798#endif
Eric Laurent65b65452010-06-01 23:49:17 -07001799
1800 // XXX: these things DON'T need to be done each time
1801 mAudioMixer->setBufferProvider(track);
1802 mAudioMixer->enable(AudioMixer::MIXING);
1803
1804 mAudioMixer->setParameter(param, AudioMixer::VOLUME0, (void *)left);
1805 mAudioMixer->setParameter(param, AudioMixer::VOLUME1, (void *)right);
1806 mAudioMixer->setParameter(param, AudioMixer::AUXLEVEL, (void *)aux);
Eric Laurenta553c252009-07-17 12:17:14 -07001807 mAudioMixer->setParameter(
1808 AudioMixer::TRACK,
Eric Laurent65b65452010-06-01 23:49:17 -07001809 AudioMixer::FORMAT, (void *)track->format());
Eric Laurenta553c252009-07-17 12:17:14 -07001810 mAudioMixer->setParameter(
1811 AudioMixer::TRACK,
Eric Laurent65b65452010-06-01 23:49:17 -07001812 AudioMixer::CHANNEL_COUNT, (void *)track->channelCount());
Eric Laurenta553c252009-07-17 12:17:14 -07001813 mAudioMixer->setParameter(
1814 AudioMixer::RESAMPLE,
1815 AudioMixer::SAMPLE_RATE,
Eric Laurent65b65452010-06-01 23:49:17 -07001816 (void *)(cblk->sampleRate));
1817 mAudioMixer->setParameter(
1818 AudioMixer::TRACK,
1819 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
1820 mAudioMixer->setParameter(
1821 AudioMixer::TRACK,
1822 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
Eric Laurenta553c252009-07-17 12:17:14 -07001823
1824 // reset retry count
1825 track->mRetryCount = kMaxTrackRetries;
Eric Laurent059b4be2009-11-09 23:32:22 -08001826 mixerStatus = MIXER_TRACKS_READY;
Eric Laurenta553c252009-07-17 12:17:14 -07001827 } else {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08001828 //LOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", track->name(), cblk->user, cblk->server, this);
Eric Laurenta553c252009-07-17 12:17:14 -07001829 if (track->isStopped()) {
1830 track->reset();
1831 }
1832 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
1833 // We have consumed all the buffers of this track.
1834 // Remove it from the list of active tracks.
1835 tracksToRemove->add(track);
Eric Laurenta553c252009-07-17 12:17:14 -07001836 } else {
1837 // No buffers for this track. Give it a few chances to
1838 // fill a buffer, then remove it from active list.
1839 if (--(track->mRetryCount) <= 0) {
Eric Laurent62443f52009-10-05 20:29:18 -07001840 LOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", track->name(), this);
Eric Laurenta553c252009-07-17 12:17:14 -07001841 tracksToRemove->add(track);
Eric Laurent4712baa2010-09-30 16:12:31 -07001842 // indicate to client process that the track was disabled because of underrun
1843 cblk->flags |= CBLK_DISABLED_ON;
Eric Laurent059b4be2009-11-09 23:32:22 -08001844 } else if (mixerStatus != MIXER_TRACKS_READY) {
1845 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07001846 }
Eric Laurenta553c252009-07-17 12:17:14 -07001847 }
Eric Laurent65b65452010-06-01 23:49:17 -07001848 mAudioMixer->disable(AudioMixer::MIXING);
Eric Laurenta553c252009-07-17 12:17:14 -07001849 }
1850 }
1851
1852 // remove all the tracks that need to be...
1853 count = tracksToRemove->size();
1854 if (UNLIKELY(count)) {
1855 for (size_t i=0 ; i<count ; i++) {
1856 const sp<Track>& track = tracksToRemove->itemAt(i);
1857 mActiveTracks.remove(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001858 if (track->mainBuffer() != mMixBuffer) {
1859 chain = getEffectChain_l(track->sessionId());
1860 if (chain != 0) {
1861 LOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
1862 chain->stopTrack();
1863 }
1864 }
Eric Laurenta553c252009-07-17 12:17:14 -07001865 if (track->isTerminated()) {
1866 mTracks.remove(track);
1867 deleteTrackName_l(track->mName);
1868 }
1869 }
1870 }
1871
Eric Laurent65b65452010-06-01 23:49:17 -07001872 // mix buffer must be cleared if all tracks are connected to an
1873 // effect chain as in this case the mixer will not write to
1874 // mix buffer and track effects will accumulate into it
1875 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
1876 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
1877 }
1878
Eric Laurent059b4be2009-11-09 23:32:22 -08001879 return mixerStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07001880}
1881
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001882void AudioFlinger::MixerThread::invalidateTracks(int streamType)
Eric Laurenta553c252009-07-17 12:17:14 -07001883{
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001884 LOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
1885 this, streamType, mTracks.size());
Eric Laurenta553c252009-07-17 12:17:14 -07001886 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001887
Eric Laurenta553c252009-07-17 12:17:14 -07001888 size_t size = mTracks.size();
1889 for (size_t i = 0; i < size; i++) {
1890 sp<Track> t = mTracks[i];
1891 if (t->type() == streamType) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001892 t->mCblk->lock.lock();
1893 t->mCblk->flags |= CBLK_INVALID_ON;
1894 t->mCblk->cv.signal();
1895 t->mCblk->lock.unlock();
Eric Laurenta553c252009-07-17 12:17:14 -07001896 }
Eric Laurent53334cd2010-06-23 17:38:20 -07001897 }
1898}
Eric Laurenta553c252009-07-17 12:17:14 -07001899
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001900
Eric Laurenta553c252009-07-17 12:17:14 -07001901// getTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001902int AudioFlinger::MixerThread::getTrackName_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001903{
1904 return mAudioMixer->getTrackName();
1905}
1906
Eric Laurenta553c252009-07-17 12:17:14 -07001907// deleteTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001908void AudioFlinger::MixerThread::deleteTrackName_l(int name)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001909{
Eric Laurent0a080292009-12-07 10:53:10 -08001910 LOGV("remove track (%d) and delete from mixer", name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001911 mAudioMixer->deleteTrackName(name);
1912}
1913
Eric Laurenta553c252009-07-17 12:17:14 -07001914// checkForNewParameters_l() must be called with ThreadBase::mLock held
1915bool AudioFlinger::MixerThread::checkForNewParameters_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001916{
Eric Laurenta553c252009-07-17 12:17:14 -07001917 bool reconfig = false;
1918
Eric Laurent8fce46a2009-08-04 09:45:33 -07001919 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07001920 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07001921 String8 keyValuePair = mNewParameters[0];
1922 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07001923 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07001924
Eric Laurenta553c252009-07-17 12:17:14 -07001925 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
1926 reconfig = true;
1927 }
1928 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
1929 if (value != AudioSystem::PCM_16_BIT) {
1930 status = BAD_VALUE;
1931 } else {
1932 reconfig = true;
1933 }
1934 }
1935 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
1936 if (value != AudioSystem::CHANNEL_OUT_STEREO) {
1937 status = BAD_VALUE;
1938 } else {
1939 reconfig = true;
1940 }
1941 }
1942 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
1943 // do not accept frame count changes if tracks are open as the track buffer
1944 // size depends on frame count and correct behavior would not be garantied
1945 // if frame count is changed after track creation
1946 if (!mTracks.isEmpty()) {
1947 status = INVALID_OPERATION;
1948 } else {
1949 reconfig = true;
1950 }
1951 }
Eric Laurent65b65452010-06-01 23:49:17 -07001952 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
1953 // forward device change to effects that have requested to be
1954 // aware of attached audio device.
1955 mDevice = (uint32_t)value;
1956 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07001957 mEffectChains[i]->setDevice_l(mDevice);
Eric Laurent65b65452010-06-01 23:49:17 -07001958 }
1959 }
1960
Eric Laurenta553c252009-07-17 12:17:14 -07001961 if (status == NO_ERROR) {
Eric Laurent8fce46a2009-08-04 09:45:33 -07001962 status = mOutput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07001963 if (!mStandby && status == INVALID_OPERATION) {
1964 mOutput->standby();
1965 mStandby = true;
1966 mBytesWritten = 0;
Eric Laurent8fce46a2009-08-04 09:45:33 -07001967 status = mOutput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07001968 }
1969 if (status == NO_ERROR && reconfig) {
1970 delete mAudioMixer;
1971 readOutputParameters();
1972 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1973 for (size_t i = 0; i < mTracks.size() ; i++) {
1974 int name = getTrackName_l();
1975 if (name < 0) break;
1976 mTracks[i]->mName = name;
Eric Laurent6f7e0972009-08-10 08:15:12 -07001977 // limit track sample rate to 2 x new output sample rate
1978 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
1979 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
1980 }
Eric Laurenta553c252009-07-17 12:17:14 -07001981 }
Eric Laurent8fce46a2009-08-04 09:45:33 -07001982 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07001983 }
1984 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08001985
1986 mNewParameters.removeAt(0);
1987
Eric Laurenta553c252009-07-17 12:17:14 -07001988 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07001989 mParamCond.signal();
Eric Laurent8fce46a2009-08-04 09:45:33 -07001990 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07001991 }
1992 return reconfig;
1993}
1994
1995status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
1996{
1997 const size_t SIZE = 256;
1998 char buffer[SIZE];
1999 String8 result;
2000
2001 PlaybackThread::dumpInternals(fd, args);
2002
2003 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2004 result.append(buffer);
2005 write(fd, result.string(), result.size());
2006 return NO_ERROR;
2007}
2008
Eric Laurent059b4be2009-11-09 23:32:22 -08002009uint32_t AudioFlinger::MixerThread::activeSleepTimeUs()
Eric Laurent62443f52009-10-05 20:29:18 -07002010{
Eric Laurent059b4be2009-11-09 23:32:22 -08002011 return (uint32_t)(mOutput->latency() * 1000) / 2;
2012}
2013
2014uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2015{
Eric Laurenta54d7d32010-07-29 06:50:24 -07002016 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Eric Laurent62443f52009-10-05 20:29:18 -07002017}
2018
Eric Laurent8448a792010-08-18 18:13:17 -07002019uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2020{
2021 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2022}
2023
Eric Laurenta553c252009-07-17 12:17:14 -07002024// ----------------------------------------------------------------------------
Eric Laurent65b65452010-06-01 23:49:17 -07002025AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
2026 : PlaybackThread(audioFlinger, output, id, device)
Eric Laurenta553c252009-07-17 12:17:14 -07002027{
2028 mType = PlaybackThread::DIRECT;
2029}
2030
2031AudioFlinger::DirectOutputThread::~DirectOutputThread()
2032{
2033}
2034
2035
Eric Laurent65b65452010-06-01 23:49:17 -07002036static inline int16_t clamp16(int32_t sample)
2037{
2038 if ((sample>>15) ^ (sample>>31))
2039 sample = 0x7FFF ^ (sample>>31);
2040 return sample;
2041}
2042
2043static inline
2044int32_t mul(int16_t in, int16_t v)
2045{
2046#if defined(__arm__) && !defined(__thumb__)
2047 int32_t out;
2048 asm( "smulbb %[out], %[in], %[v] \n"
2049 : [out]"=r"(out)
2050 : [in]"%r"(in), [v]"r"(v)
2051 : );
2052 return out;
2053#else
2054 return in * int32_t(v);
2055#endif
2056}
2057
2058void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2059{
2060 // Do not apply volume on compressed audio
2061 if (!AudioSystem::isLinearPCM(mFormat)) {
2062 return;
2063 }
2064
2065 // convert to signed 16 bit before volume calculation
2066 if (mFormat == AudioSystem::PCM_8_BIT) {
2067 size_t count = mFrameCount * mChannelCount;
2068 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2069 int16_t *dst = mMixBuffer + count-1;
2070 while(count--) {
2071 *dst-- = (int16_t)(*src--^0x80) << 8;
2072 }
2073 }
2074
2075 size_t frameCount = mFrameCount;
2076 int16_t *out = mMixBuffer;
2077 if (ramp) {
2078 if (mChannelCount == 1) {
2079 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2080 int32_t vlInc = d / (int32_t)frameCount;
2081 int32_t vl = ((int32_t)mLeftVolShort << 16);
2082 do {
2083 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2084 out++;
2085 vl += vlInc;
2086 } while (--frameCount);
2087
2088 } else {
2089 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2090 int32_t vlInc = d / (int32_t)frameCount;
2091 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2092 int32_t vrInc = d / (int32_t)frameCount;
2093 int32_t vl = ((int32_t)mLeftVolShort << 16);
2094 int32_t vr = ((int32_t)mRightVolShort << 16);
2095 do {
2096 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2097 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2098 out += 2;
2099 vl += vlInc;
2100 vr += vrInc;
2101 } while (--frameCount);
2102 }
2103 } else {
2104 if (mChannelCount == 1) {
2105 do {
2106 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2107 out++;
2108 } while (--frameCount);
2109 } else {
2110 do {
2111 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2112 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2113 out += 2;
2114 } while (--frameCount);
2115 }
2116 }
2117
2118 // convert back to unsigned 8 bit after volume calculation
2119 if (mFormat == AudioSystem::PCM_8_BIT) {
2120 size_t count = mFrameCount * mChannelCount;
2121 int16_t *src = mMixBuffer;
2122 uint8_t *dst = (uint8_t *)mMixBuffer;
2123 while(count--) {
2124 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2125 }
2126 }
2127
2128 mLeftVolShort = leftVol;
2129 mRightVolShort = rightVol;
2130}
2131
Eric Laurenta553c252009-07-17 12:17:14 -07002132bool AudioFlinger::DirectOutputThread::threadLoop()
2133{
Eric Laurent059b4be2009-11-09 23:32:22 -08002134 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002135 sp<Track> trackToRemove;
2136 sp<Track> activeTrack;
2137 nsecs_t standbyTime = systemTime();
2138 int8_t *curBuf;
2139 size_t mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent059b4be2009-11-09 23:32:22 -08002140 uint32_t activeSleepTime = activeSleepTimeUs();
2141 uint32_t idleSleepTime = idleSleepTimeUs();
2142 uint32_t sleepTime = idleSleepTime;
Eric Laurentef9500f2010-03-11 14:47:00 -08002143 // use shorter standby delay as on normal output to release
2144 // hardware resources as soon as possible
2145 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
Eric Laurent059b4be2009-11-09 23:32:22 -08002146
Eric Laurenta553c252009-07-17 12:17:14 -07002147 while (!exitPending())
2148 {
Eric Laurent65b65452010-06-01 23:49:17 -07002149 bool rampVolume;
2150 uint16_t leftVol;
2151 uint16_t rightVol;
2152 Vector< sp<EffectChain> > effectChains;
2153
Eric Laurenta553c252009-07-17 12:17:14 -07002154 processConfigEvents();
2155
Eric Laurent059b4be2009-11-09 23:32:22 -08002156 mixerStatus = MIXER_IDLE;
2157
Eric Laurenta553c252009-07-17 12:17:14 -07002158 { // scope for the mLock
2159
2160 Mutex::Autolock _l(mLock);
2161
2162 if (checkForNewParameters_l()) {
2163 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent059b4be2009-11-09 23:32:22 -08002164 activeSleepTime = activeSleepTimeUs();
2165 idleSleepTime = idleSleepTimeUs();
Eric Laurentef9500f2010-03-11 14:47:00 -08002166 standbyDelay = microseconds(activeSleepTime*2);
Eric Laurenta553c252009-07-17 12:17:14 -07002167 }
2168
2169 // put audio hardware into standby after short delay
2170 if UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2171 mSuspended) {
2172 // wait until we have something to do...
2173 if (!mStandby) {
2174 LOGV("Audio hardware entering standby, mixer %p\n", this);
2175 mOutput->standby();
2176 mStandby = true;
2177 mBytesWritten = 0;
2178 }
2179
2180 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2181 // we're about to wait, flush the binder command buffer
2182 IPCThreadState::self()->flushCommands();
2183
2184 if (exitPending()) break;
2185
2186 LOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
2187 mWaitWorkCV.wait(mLock);
2188 LOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
2189
2190 if (mMasterMute == false) {
2191 char value[PROPERTY_VALUE_MAX];
2192 property_get("ro.audio.silent", value, "0");
2193 if (atoi(value)) {
2194 LOGD("Silence is golden");
2195 setMasterMute(true);
2196 }
2197 }
2198
Eric Laurentef9500f2010-03-11 14:47:00 -08002199 standbyTime = systemTime() + standbyDelay;
Eric Laurent059b4be2009-11-09 23:32:22 -08002200 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07002201 continue;
2202 }
2203 }
2204
Eric Laurent65b65452010-06-01 23:49:17 -07002205 effectChains = mEffectChains;
2206
Eric Laurenta553c252009-07-17 12:17:14 -07002207 // find out which tracks need to be processed
2208 if (mActiveTracks.size() != 0) {
2209 sp<Track> t = mActiveTracks[0].promote();
2210 if (t == 0) continue;
2211
2212 Track* const track = t.get();
2213 audio_track_cblk_t* cblk = track->cblk();
2214
2215 // The first time a track is added we wait
2216 // for all its buffers to be filled before processing it
Eric Laurent9a30fc12010-10-05 14:41:42 -07002217 if (cblk->framesReady() && track->isReady() &&
Eric Laurent380558b2010-04-09 06:11:48 -07002218 !track->isPaused() && !track->isTerminated())
Eric Laurenta553c252009-07-17 12:17:14 -07002219 {
2220 //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
2221
Eric Laurent65b65452010-06-01 23:49:17 -07002222 if (track->mFillingUpStatus == Track::FS_FILLED) {
2223 track->mFillingUpStatus = Track::FS_ACTIVE;
2224 mLeftVolFloat = mRightVolFloat = 0;
2225 mLeftVolShort = mRightVolShort = 0;
2226 if (track->mState == TrackBase::RESUMING) {
2227 track->mState = TrackBase::ACTIVE;
2228 rampVolume = true;
2229 }
2230 } else if (cblk->server != 0) {
2231 // If the track is stopped before the first frame was mixed,
2232 // do not apply ramp
2233 rampVolume = true;
2234 }
Eric Laurenta553c252009-07-17 12:17:14 -07002235 // compute volume for this track
2236 float left, right;
2237 if (track->isMuted() || mMasterMute || track->isPausing() ||
2238 mStreamTypes[track->type()].mute) {
2239 left = right = 0;
2240 if (track->isPausing()) {
2241 track->setPaused();
2242 }
2243 } else {
2244 float typeVolume = mStreamTypes[track->type()].volume;
2245 float v = mMasterVolume * typeVolume;
2246 float v_clamped = v * cblk->volume[0];
2247 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2248 left = v_clamped/MAX_GAIN;
2249 v_clamped = v * cblk->volume[1];
2250 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2251 right = v_clamped/MAX_GAIN;
2252 }
2253
Eric Laurent65b65452010-06-01 23:49:17 -07002254 if (left != mLeftVolFloat || right != mRightVolFloat) {
2255 mLeftVolFloat = left;
2256 mRightVolFloat = right;
Eric Laurenta553c252009-07-17 12:17:14 -07002257
Eric Laurent65b65452010-06-01 23:49:17 -07002258 // If audio HAL implements volume control,
2259 // force software volume to nominal value
2260 if (mOutput->setVolume(left, right) == NO_ERROR) {
2261 left = 1.0f;
2262 right = 1.0f;
Eric Laurenta553c252009-07-17 12:17:14 -07002263 }
Eric Laurent65b65452010-06-01 23:49:17 -07002264
2265 // Convert volumes from float to 8.24
2266 uint32_t vl = (uint32_t)(left * (1 << 24));
2267 uint32_t vr = (uint32_t)(right * (1 << 24));
2268
2269 // Delegate volume control to effect in track effect chain if needed
2270 // only one effect chain can be present on DirectOutputThread, so if
2271 // there is one, the track is connected to it
2272 if (!effectChains.isEmpty()) {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002273 // Do not ramp volume if volume is controlled by effect
Eric Laurent76c40f72010-07-15 12:50:15 -07002274 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002275 rampVolume = false;
2276 }
2277 }
2278
2279 // Convert volumes from 8.24 to 4.12 format
2280 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2281 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2282 leftVol = (uint16_t)v_clamped;
2283 v_clamped = (vr + (1 << 11)) >> 12;
2284 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2285 rightVol = (uint16_t)v_clamped;
2286 } else {
2287 leftVol = mLeftVolShort;
2288 rightVol = mRightVolShort;
2289 rampVolume = false;
Eric Laurenta553c252009-07-17 12:17:14 -07002290 }
2291
2292 // reset retry count
Eric Laurentef9500f2010-03-11 14:47:00 -08002293 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurenta553c252009-07-17 12:17:14 -07002294 activeTrack = t;
Eric Laurent059b4be2009-11-09 23:32:22 -08002295 mixerStatus = MIXER_TRACKS_READY;
Eric Laurenta553c252009-07-17 12:17:14 -07002296 } else {
2297 //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
2298 if (track->isStopped()) {
2299 track->reset();
2300 }
2301 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2302 // We have consumed all the buffers of this track.
2303 // Remove it from the list of active tracks.
2304 trackToRemove = track;
2305 } else {
2306 // No buffers for this track. Give it a few chances to
2307 // fill a buffer, then remove it from active list.
2308 if (--(track->mRetryCount) <= 0) {
2309 LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
2310 trackToRemove = track;
Eric Laurent059b4be2009-11-09 23:32:22 -08002311 } else {
2312 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07002313 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002314 }
Eric Laurenta553c252009-07-17 12:17:14 -07002315 }
2316 }
2317
2318 // remove all the tracks that need to be...
2319 if (UNLIKELY(trackToRemove != 0)) {
2320 mActiveTracks.remove(trackToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07002321 if (!effectChains.isEmpty()) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002322 LOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
2323 trackToRemove->sessionId());
Eric Laurent65b65452010-06-01 23:49:17 -07002324 effectChains[0]->stopTrack();
2325 }
Eric Laurenta553c252009-07-17 12:17:14 -07002326 if (trackToRemove->isTerminated()) {
2327 mTracks.remove(trackToRemove);
2328 deleteTrackName_l(trackToRemove->mName);
2329 }
2330 }
Eric Laurent65b65452010-06-01 23:49:17 -07002331
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002332 lockEffectChains_l(effectChains);
Eric Laurenta553c252009-07-17 12:17:14 -07002333 }
2334
Eric Laurent059b4be2009-11-09 23:32:22 -08002335 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002336 AudioBufferProvider::Buffer buffer;
2337 size_t frameCount = mFrameCount;
2338 curBuf = (int8_t *)mMixBuffer;
2339 // output audio to hardware
Eric Laurent65b65452010-06-01 23:49:17 -07002340 while (frameCount) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002341 buffer.frameCount = frameCount;
2342 activeTrack->getNextBuffer(&buffer);
2343 if (UNLIKELY(buffer.raw == 0)) {
2344 memset(curBuf, 0, frameCount * mFrameSize);
2345 break;
2346 }
2347 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2348 frameCount -= buffer.frameCount;
2349 curBuf += buffer.frameCount * mFrameSize;
2350 activeTrack->releaseBuffer(&buffer);
2351 }
2352 sleepTime = 0;
Eric Laurentef9500f2010-03-11 14:47:00 -08002353 standbyTime = systemTime() + standbyDelay;
Eric Laurent96c08a62009-09-07 08:38:38 -07002354 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07002355 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002356 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2357 sleepTime = activeSleepTime;
2358 } else {
2359 sleepTime = idleSleepTime;
2360 }
Eric Laurent62443f52009-10-05 20:29:18 -07002361 } else if (mBytesWritten != 0 && AudioSystem::isLinearPCM(mFormat)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002362 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent96c08a62009-09-07 08:38:38 -07002363 sleepTime = 0;
Eric Laurent96c08a62009-09-07 08:38:38 -07002364 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002365 }
Eric Laurent96c08a62009-09-07 08:38:38 -07002366
Eric Laurentf69a3f82009-09-22 00:35:48 -07002367 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07002368 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07002369 }
2370 // sleepTime == 0 means we must write to audio hardware
2371 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07002372 if (mixerStatus == MIXER_TRACKS_READY) {
2373 applyVolume(leftVol, rightVol, rampVolume);
2374 }
2375 for (size_t i = 0; i < effectChains.size(); i ++) {
2376 effectChains[i]->process_l();
2377 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002378 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07002379
Eric Laurentf69a3f82009-09-22 00:35:48 -07002380 mLastWriteTime = systemTime();
2381 mInWrite = true;
Eric Laurent0986e792010-01-19 17:37:09 -08002382 mBytesWritten += mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002383 int bytesWritten = (int)mOutput->write(mMixBuffer, mixBufferSize);
Eric Laurent0986e792010-01-19 17:37:09 -08002384 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002385 mNumWrites++;
2386 mInWrite = false;
2387 mStandby = false;
2388 } else {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002389 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002390 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07002391 }
2392
2393 // finally let go of removed track, without the lock held
2394 // since we can't guarantee the destructors won't acquire that
2395 // same lock.
2396 trackToRemove.clear();
2397 activeTrack.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07002398
2399 // Effect chains will be actually deleted here if they were removed from
2400 // mEffectChains list during mixing or effects processing
2401 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07002402 }
2403
2404 if (!mStandby) {
2405 mOutput->standby();
2406 }
Eric Laurenta553c252009-07-17 12:17:14 -07002407
2408 LOGV("DirectOutputThread %p exiting", this);
2409 return false;
2410}
2411
2412// getTrackName_l() must be called with ThreadBase::mLock held
2413int AudioFlinger::DirectOutputThread::getTrackName_l()
2414{
2415 return 0;
2416}
2417
2418// deleteTrackName_l() must be called with ThreadBase::mLock held
2419void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2420{
2421}
2422
2423// checkForNewParameters_l() must be called with ThreadBase::mLock held
2424bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2425{
2426 bool reconfig = false;
2427
Eric Laurent8fce46a2009-08-04 09:45:33 -07002428 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07002429 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002430 String8 keyValuePair = mNewParameters[0];
2431 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002432 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002433
Eric Laurenta553c252009-07-17 12:17:14 -07002434 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2435 // do not accept frame count changes if tracks are open as the track buffer
2436 // size depends on frame count and correct behavior would not be garantied
2437 // if frame count is changed after track creation
2438 if (!mTracks.isEmpty()) {
2439 status = INVALID_OPERATION;
2440 } else {
2441 reconfig = true;
2442 }
2443 }
2444 if (status == NO_ERROR) {
Eric Laurent8fce46a2009-08-04 09:45:33 -07002445 status = mOutput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002446 if (!mStandby && status == INVALID_OPERATION) {
2447 mOutput->standby();
2448 mStandby = true;
2449 mBytesWritten = 0;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002450 status = mOutput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002451 }
2452 if (status == NO_ERROR && reconfig) {
2453 readOutputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07002454 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07002455 }
2456 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08002457
2458 mNewParameters.removeAt(0);
2459
Eric Laurenta553c252009-07-17 12:17:14 -07002460 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07002461 mParamCond.signal();
Eric Laurent8fce46a2009-08-04 09:45:33 -07002462 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07002463 }
2464 return reconfig;
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08002465}
2466
Eric Laurent059b4be2009-11-09 23:32:22 -08002467uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
Eric Laurent62443f52009-10-05 20:29:18 -07002468{
2469 uint32_t time;
2470 if (AudioSystem::isLinearPCM(mFormat)) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002471 time = (uint32_t)(mOutput->latency() * 1000) / 2;
2472 } else {
2473 time = 10000;
2474 }
2475 return time;
2476}
2477
2478uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2479{
2480 uint32_t time;
2481 if (AudioSystem::isLinearPCM(mFormat)) {
Eric Laurenta54d7d32010-07-29 06:50:24 -07002482 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Eric Laurent62443f52009-10-05 20:29:18 -07002483 } else {
2484 time = 10000;
2485 }
2486 return time;
2487}
2488
Eric Laurent8448a792010-08-18 18:13:17 -07002489uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2490{
2491 uint32_t time;
2492 if (AudioSystem::isLinearPCM(mFormat)) {
2493 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2494 } else {
2495 time = 10000;
2496 }
2497 return time;
2498}
2499
2500
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002501// ----------------------------------------------------------------------------
2502
Eric Laurent49f02be2009-11-19 09:00:56 -08002503AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread, int id)
Eric Laurent65b65452010-06-01 23:49:17 -07002504 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device()), mWaitTimeMs(UINT_MAX)
Eric Laurenta553c252009-07-17 12:17:14 -07002505{
2506 mType = PlaybackThread::DUPLICATING;
2507 addOutputTrack(mainThread);
2508}
2509
2510AudioFlinger::DuplicatingThread::~DuplicatingThread()
2511{
Eric Laurent0a080292009-12-07 10:53:10 -08002512 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2513 mOutputTracks[i]->destroy();
2514 }
Eric Laurenta553c252009-07-17 12:17:14 -07002515 mOutputTracks.clear();
2516}
2517
2518bool AudioFlinger::DuplicatingThread::threadLoop()
2519{
Eric Laurenta553c252009-07-17 12:17:14 -07002520 Vector< sp<Track> > tracksToRemove;
Eric Laurent059b4be2009-11-09 23:32:22 -08002521 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002522 nsecs_t standbyTime = systemTime();
2523 size_t mixBufferSize = mFrameCount*mFrameSize;
2524 SortedVector< sp<OutputTrack> > outputTracks;
Eric Laurent62443f52009-10-05 20:29:18 -07002525 uint32_t writeFrames = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08002526 uint32_t activeSleepTime = activeSleepTimeUs();
2527 uint32_t idleSleepTime = idleSleepTimeUs();
2528 uint32_t sleepTime = idleSleepTime;
Eric Laurent65b65452010-06-01 23:49:17 -07002529 Vector< sp<EffectChain> > effectChains;
Eric Laurenta553c252009-07-17 12:17:14 -07002530
2531 while (!exitPending())
2532 {
2533 processConfigEvents();
2534
Eric Laurent059b4be2009-11-09 23:32:22 -08002535 mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002536 { // scope for the mLock
2537
2538 Mutex::Autolock _l(mLock);
2539
2540 if (checkForNewParameters_l()) {
2541 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002542 updateWaitTime();
Eric Laurent059b4be2009-11-09 23:32:22 -08002543 activeSleepTime = activeSleepTimeUs();
2544 idleSleepTime = idleSleepTimeUs();
Eric Laurenta553c252009-07-17 12:17:14 -07002545 }
2546
2547 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
2548
2549 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2550 outputTracks.add(mOutputTracks[i]);
2551 }
2552
2553 // put audio hardware into standby after short delay
2554 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
2555 mSuspended) {
2556 if (!mStandby) {
2557 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurenta553c252009-07-17 12:17:14 -07002558 outputTracks[i]->stop();
Eric Laurenta553c252009-07-17 12:17:14 -07002559 }
2560 mStandby = true;
2561 mBytesWritten = 0;
2562 }
2563
2564 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
2565 // we're about to wait, flush the binder command buffer
2566 IPCThreadState::self()->flushCommands();
2567 outputTracks.clear();
2568
2569 if (exitPending()) break;
2570
2571 LOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
2572 mWaitWorkCV.wait(mLock);
2573 LOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
2574 if (mMasterMute == false) {
2575 char value[PROPERTY_VALUE_MAX];
2576 property_get("ro.audio.silent", value, "0");
2577 if (atoi(value)) {
2578 LOGD("Silence is golden");
2579 setMasterMute(true);
2580 }
2581 }
2582
2583 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent059b4be2009-11-09 23:32:22 -08002584 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07002585 continue;
2586 }
2587 }
2588
Eric Laurent059b4be2009-11-09 23:32:22 -08002589 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07002590
2591 // prevent any changes in effect chain list and in each effect chain
2592 // during mixing and effect process as the audio buffers could be deleted
2593 // or modified if an effect is created or deleted
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002594 lockEffectChains_l(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002595 }
Eric Laurenta553c252009-07-17 12:17:14 -07002596
Eric Laurent059b4be2009-11-09 23:32:22 -08002597 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurenta553c252009-07-17 12:17:14 -07002598 // mix buffers...
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002599 if (outputsReady(outputTracks)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002600 mAudioMixer->process();
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002601 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07002602 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002603 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002604 sleepTime = 0;
Eric Laurent62443f52009-10-05 20:29:18 -07002605 writeFrames = mFrameCount;
Eric Laurenta553c252009-07-17 12:17:14 -07002606 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07002607 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002608 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2609 sleepTime = activeSleepTime;
2610 } else {
2611 sleepTime = idleSleepTime;
2612 }
Eric Laurent62443f52009-10-05 20:29:18 -07002613 } else if (mBytesWritten != 0) {
2614 // flush remaining overflow buffers in output tracks
2615 for (size_t i = 0; i < outputTracks.size(); i++) {
2616 if (outputTracks[i]->isActive()) {
2617 sleepTime = 0;
2618 writeFrames = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07002619 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent62443f52009-10-05 20:29:18 -07002620 break;
2621 }
2622 }
Eric Laurenta553c252009-07-17 12:17:14 -07002623 }
2624 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002625
2626 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07002627 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07002628 }
2629 // sleepTime == 0 means we must write to audio hardware
2630 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07002631 for (size_t i = 0; i < effectChains.size(); i ++) {
2632 effectChains[i]->process_l();
2633 }
2634 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002635 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07002636
Eric Laurent62443f52009-10-05 20:29:18 -07002637 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002638 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurent65b65452010-06-01 23:49:17 -07002639 outputTracks[i]->write(mMixBuffer, writeFrames);
Eric Laurenta553c252009-07-17 12:17:14 -07002640 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002641 mStandby = false;
2642 mBytesWritten += mixBufferSize;
Eric Laurenta553c252009-07-17 12:17:14 -07002643 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07002644 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002645 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002646 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07002647 }
2648
2649 // finally let go of all our tracks, without the lock held
2650 // since we can't guarantee the destructors won't acquire that
2651 // same lock.
2652 tracksToRemove.clear();
2653 outputTracks.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07002654
2655 // Effect chains will be actually deleted here if they were removed from
2656 // mEffectChains list during mixing or effects processing
2657 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07002658 }
2659
Eric Laurenta553c252009-07-17 12:17:14 -07002660 return false;
2661}
2662
2663void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
2664{
2665 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
2666 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002667 this,
Eric Laurenta553c252009-07-17 12:17:14 -07002668 mSampleRate,
2669 mFormat,
2670 mChannelCount,
2671 frameCount);
Eric Laurent6c30a712009-08-10 23:22:32 -07002672 if (outputTrack->cblk() != NULL) {
2673 thread->setStreamVolume(AudioSystem::NUM_STREAM_TYPES, 1.0f);
2674 mOutputTracks.add(outputTrack);
2675 LOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002676 updateWaitTime();
Eric Laurent6c30a712009-08-10 23:22:32 -07002677 }
Eric Laurenta553c252009-07-17 12:17:14 -07002678}
2679
2680void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
2681{
2682 Mutex::Autolock _l(mLock);
2683 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2684 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
Eric Laurent6c30a712009-08-10 23:22:32 -07002685 mOutputTracks[i]->destroy();
Eric Laurenta553c252009-07-17 12:17:14 -07002686 mOutputTracks.removeAt(i);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002687 updateWaitTime();
Eric Laurenta553c252009-07-17 12:17:14 -07002688 return;
2689 }
2690 }
2691 LOGV("removeOutputTrack(): unkonwn thread: %p", thread);
2692}
2693
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002694void AudioFlinger::DuplicatingThread::updateWaitTime()
2695{
2696 mWaitTimeMs = UINT_MAX;
2697 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2698 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
2699 if (strong != NULL) {
2700 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
2701 if (waitTimeMs < mWaitTimeMs) {
2702 mWaitTimeMs = waitTimeMs;
2703 }
2704 }
2705 }
2706}
2707
2708
2709bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
2710{
2711 for (size_t i = 0; i < outputTracks.size(); i++) {
2712 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
2713 if (thread == 0) {
2714 LOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
2715 return false;
2716 }
2717 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2718 if (playbackThread->standby() && !playbackThread->isSuspended()) {
2719 LOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
2720 return false;
2721 }
2722 }
2723 return true;
2724}
2725
2726uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
2727{
2728 return (mWaitTimeMs * 1000) / 2;
2729}
2730
Eric Laurenta553c252009-07-17 12:17:14 -07002731// ----------------------------------------------------------------------------
2732
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002733// TrackBase constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07002734AudioFlinger::ThreadBase::TrackBase::TrackBase(
2735 const wp<ThreadBase>& thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002736 const sp<Client>& client,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002737 uint32_t sampleRate,
2738 int format,
2739 int channelCount,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002740 int frameCount,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002741 uint32_t flags,
Eric Laurent65b65452010-06-01 23:49:17 -07002742 const sp<IMemory>& sharedBuffer,
2743 int sessionId)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002744 : RefBase(),
Eric Laurenta553c252009-07-17 12:17:14 -07002745 mThread(thread),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002746 mClient(client),
Eric Laurent8a77a992009-09-09 05:16:08 -07002747 mCblk(0),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002748 mFrameCount(0),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002749 mState(IDLE),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002750 mClientTid(-1),
2751 mFormat(format),
Eric Laurent65b65452010-06-01 23:49:17 -07002752 mFlags(flags & ~SYSTEM_FLAGS_MASK),
2753 mSessionId(sessionId)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002754{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002755 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
2756
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002757 // LOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002758 size_t size = sizeof(audio_track_cblk_t);
2759 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
2760 if (sharedBuffer == 0) {
2761 size += bufferSize;
2762 }
2763
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002764 if (client != NULL) {
2765 mCblkMemory = client->heap()->allocate(size);
2766 if (mCblkMemory != 0) {
2767 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
2768 if (mCblk) { // construct the shared structure in-place.
2769 new(mCblk) audio_track_cblk_t();
2770 // clear all buffers
2771 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07002772 mCblk->sampleRate = sampleRate;
Eric Laurentb0a01472010-05-14 05:45:46 -07002773 mCblk->channelCount = (uint8_t)channelCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002774 if (sharedBuffer == 0) {
2775 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2776 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2777 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent4712baa2010-09-30 16:12:31 -07002778 // written to buffer (other flags are cleared)
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002779 mCblk->flags = CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002780 } else {
2781 mBuffer = sharedBuffer->pointer();
2782 }
2783 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002784 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002785 } else {
2786 LOGE("not enough memory for AudioTrack size=%u", size);
2787 client->heap()->dump("AudioTrack");
2788 return;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002789 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002790 } else {
2791 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
2792 if (mCblk) { // construct the shared structure in-place.
2793 new(mCblk) audio_track_cblk_t();
2794 // clear all buffers
2795 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07002796 mCblk->sampleRate = sampleRate;
Eric Laurentb0a01472010-05-14 05:45:46 -07002797 mCblk->channelCount = (uint8_t)channelCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002798 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2799 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2800 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent4712baa2010-09-30 16:12:31 -07002801 // written to buffer (other flags are cleared)
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002802 mCblk->flags = CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002803 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
2804 }
2805 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002806}
2807
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002808AudioFlinger::ThreadBase::TrackBase::~TrackBase()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002809{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002810 if (mCblk) {
Eric Laurenta553c252009-07-17 12:17:14 -07002811 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
2812 if (mClient == NULL) {
2813 delete mCblk;
2814 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002815 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002816 mCblkMemory.clear(); // and free the shared memory
Eric Laurentb9481d82009-09-17 05:12:56 -07002817 if (mClient != NULL) {
2818 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
2819 mClient.clear();
2820 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002821}
2822
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002823void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002824{
2825 buffer->raw = 0;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002826 mFrameCount = buffer->frameCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002827 step();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002828 buffer->frameCount = 0;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002829}
2830
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002831bool AudioFlinger::ThreadBase::TrackBase::step() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002832 bool result;
2833 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002834
2835 result = cblk->stepServer(mFrameCount);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002836 if (!result) {
2837 LOGV("stepServer failed acquiring cblk mutex");
2838 mFlags |= STEPSERVER_FAILED;
2839 }
2840 return result;
2841}
2842
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002843void AudioFlinger::ThreadBase::TrackBase::reset() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002844 audio_track_cblk_t* cblk = this->cblk();
2845
2846 cblk->user = 0;
2847 cblk->server = 0;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002848 cblk->userBase = 0;
2849 cblk->serverBase = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002850 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002851 LOGV("TrackBase::reset");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002852}
2853
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002854sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002855{
2856 return mCblkMemory;
2857}
2858
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002859int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
The Android Open Source Project10592532009-03-18 17:39:46 -07002860 return (int)mCblk->sampleRate;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002861}
2862
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002863int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
Eric Laurentb0a01472010-05-14 05:45:46 -07002864 return (int)mCblk->channelCount;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002865}
2866
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002867void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002868 audio_track_cblk_t* cblk = this->cblk();
Eric Laurenta553c252009-07-17 12:17:14 -07002869 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
2870 int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002871
2872 // Check validity of returned pointer in case the track control block would have been corrupted.
Eric Laurenta553c252009-07-17 12:17:14 -07002873 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
2874 ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
The Android Open Source Project10592532009-03-18 17:39:46 -07002875 LOGE("TrackBase::getBuffer buffer out of range:\n start: %p, end %p , mBuffer %p mBufferEnd %p\n \
Eric Laurentb0a01472010-05-14 05:45:46 -07002876 server %d, serverBase %d, user %d, userBase %d, channelCount %d",
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002877 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Eric Laurentb0a01472010-05-14 05:45:46 -07002878 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, cblk->channelCount);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002879 return 0;
2880 }
2881
2882 return bufferStart;
2883}
2884
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002885// ----------------------------------------------------------------------------
2886
Eric Laurenta553c252009-07-17 12:17:14 -07002887// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
2888AudioFlinger::PlaybackThread::Track::Track(
2889 const wp<ThreadBase>& thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002890 const sp<Client>& client,
2891 int streamType,
2892 uint32_t sampleRate,
2893 int format,
2894 int channelCount,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002895 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07002896 const sp<IMemory>& sharedBuffer,
2897 int sessionId)
2898 : TrackBase(thread, client, sampleRate, format, channelCount, frameCount, 0, sharedBuffer, sessionId),
Eric Laurenta92ebfa2010-08-31 13:50:07 -07002899 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
2900 mAuxEffectId(0), mHasVolumeController(false)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002901{
Eric Laurent8a77a992009-09-09 05:16:08 -07002902 if (mCblk != NULL) {
2903 sp<ThreadBase> baseThread = thread.promote();
2904 if (baseThread != 0) {
2905 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
2906 mName = playbackThread->getTrackName_l();
Eric Laurent65b65452010-06-01 23:49:17 -07002907 mMainBuffer = playbackThread->mixBuffer();
Eric Laurent8a77a992009-09-09 05:16:08 -07002908 }
2909 LOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2910 if (mName < 0) {
2911 LOGE("no more track names available");
2912 }
2913 mVolume[0] = 1.0f;
2914 mVolume[1] = 1.0f;
2915 mStreamType = streamType;
2916 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
2917 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
2918 mCblk->frameSize = AudioSystem::isLinearPCM(format) ? channelCount * sizeof(int16_t) : sizeof(int8_t);
Eric Laurenta553c252009-07-17 12:17:14 -07002919 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002920}
2921
Eric Laurenta553c252009-07-17 12:17:14 -07002922AudioFlinger::PlaybackThread::Track::~Track()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002923{
Eric Laurenta553c252009-07-17 12:17:14 -07002924 LOGV("PlaybackThread::Track destructor");
2925 sp<ThreadBase> thread = mThread.promote();
2926 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08002927 Mutex::Autolock _l(thread->mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07002928 mState = TERMINATED;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002929 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002930}
2931
Eric Laurenta553c252009-07-17 12:17:14 -07002932void AudioFlinger::PlaybackThread::Track::destroy()
2933{
2934 // NOTE: destroyTrack_l() can remove a strong reference to this Track
2935 // by removing it from mTracks vector, so there is a risk that this Tracks's
2936 // desctructor is called. As the destructor needs to lock mLock,
2937 // we must acquire a strong reference on this Track before locking mLock
2938 // here so that the destructor is called only when exiting this function.
2939 // On the other hand, as long as Track::destroy() is only called by
2940 // TrackHandle destructor, the TrackHandle still holds a strong ref on
2941 // this Track with its member mTrack.
2942 sp<Track> keep(this);
2943 { // scope for mLock
2944 sp<ThreadBase> thread = mThread.promote();
2945 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08002946 if (!isOutputTrack()) {
2947 if (mState == ACTIVE || mState == RESUMING) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002948 AudioSystem::stopOutput(thread->id(),
2949 (AudioSystem::stream_type)mStreamType,
2950 mSessionId);
Eric Laurentac196e12009-12-01 02:17:41 -08002951 }
2952 AudioSystem::releaseOutput(thread->id());
Eric Laurent49f02be2009-11-19 09:00:56 -08002953 }
Eric Laurenta553c252009-07-17 12:17:14 -07002954 Mutex::Autolock _l(thread->mLock);
2955 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2956 playbackThread->destroyTrack_l(this);
2957 }
2958 }
2959}
2960
2961void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002962{
Eric Laurent65b65452010-06-01 23:49:17 -07002963 snprintf(buffer, size, " %05d %05d %03u %03u %03u %05u %04u %1d %1d %1d %05u %05u %05u 0x%08x 0x%08x 0x%08x 0x%08x\n",
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002964 mName - AudioMixer::TRACK0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002965 (mClient == NULL) ? getpid() : mClient->pid(),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002966 mStreamType,
2967 mFormat,
Eric Laurentb0a01472010-05-14 05:45:46 -07002968 mCblk->channelCount,
Eric Laurent65b65452010-06-01 23:49:17 -07002969 mSessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002970 mFrameCount,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002971 mState,
2972 mMute,
2973 mFillingUpStatus,
2974 mCblk->sampleRate,
2975 mCblk->volume[0],
2976 mCblk->volume[1],
2977 mCblk->server,
Eric Laurent65b65452010-06-01 23:49:17 -07002978 mCblk->user,
2979 (int)mMainBuffer,
2980 (int)mAuxBuffer);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002981}
2982
Eric Laurenta553c252009-07-17 12:17:14 -07002983status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002984{
2985 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002986 uint32_t framesReady;
2987 uint32_t framesReq = buffer->frameCount;
2988
2989 // Check if last stepServer failed, try to step now
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002990 if (mFlags & TrackBase::STEPSERVER_FAILED) {
2991 if (!step()) goto getNextBuffer_exit;
2992 LOGV("stepServer recovered");
2993 mFlags &= ~TrackBase::STEPSERVER_FAILED;
2994 }
2995
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002996 framesReady = cblk->framesReady();
2997
2998 if (LIKELY(framesReady)) {
2999 uint32_t s = cblk->server;
3000 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3001
3002 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3003 if (framesReq > framesReady) {
3004 framesReq = framesReady;
3005 }
3006 if (s + framesReq > bufferEnd) {
3007 framesReq = bufferEnd - s;
3008 }
3009
3010 buffer->raw = getBuffer(s, framesReq);
3011 if (buffer->raw == 0) goto getNextBuffer_exit;
3012
3013 buffer->frameCount = framesReq;
3014 return NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003015 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003016
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003017getNextBuffer_exit:
3018 buffer->raw = 0;
3019 buffer->frameCount = 0;
Eric Laurent62443f52009-10-05 20:29:18 -07003020 LOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003021 return NOT_ENOUGH_DATA;
3022}
3023
Eric Laurenta553c252009-07-17 12:17:14 -07003024bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurent9a30fc12010-10-05 14:41:42 -07003025 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003026
3027 if (mCblk->framesReady() >= mCblk->frameCount ||
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003028 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003029 mFillingUpStatus = FS_FILLED;
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003030 mCblk->flags &= ~CBLK_FORCEREADY_MSK;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003031 return true;
3032 }
3033 return false;
3034}
3035
Eric Laurenta553c252009-07-17 12:17:14 -07003036status_t AudioFlinger::PlaybackThread::Track::start()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003037{
Eric Laurent49f02be2009-11-19 09:00:56 -08003038 status_t status = NO_ERROR;
Eric Laurent0d7e0482010-07-19 06:24:46 -07003039 LOGV("start(%d), calling thread %d session %d",
3040 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Eric Laurenta553c252009-07-17 12:17:14 -07003041 sp<ThreadBase> thread = mThread.promote();
3042 if (thread != 0) {
3043 Mutex::Autolock _l(thread->mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08003044 int state = mState;
3045 // here the track could be either new, or restarted
3046 // in both cases "unstop" the track
3047 if (mState == PAUSED) {
3048 mState = TrackBase::RESUMING;
3049 LOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
3050 } else {
3051 mState = TrackBase::ACTIVE;
3052 LOGV("? => ACTIVE (%d) on thread %p", mName, this);
3053 }
3054
3055 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3056 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003057 status = AudioSystem::startOutput(thread->id(),
3058 (AudioSystem::stream_type)mStreamType,
3059 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003060 thread->mLock.lock();
3061 }
3062 if (status == NO_ERROR) {
3063 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3064 playbackThread->addTrack_l(this);
3065 } else {
3066 mState = state;
3067 }
3068 } else {
3069 status = BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -07003070 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003071 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003072}
3073
Eric Laurenta553c252009-07-17 12:17:14 -07003074void AudioFlinger::PlaybackThread::Track::stop()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003075{
Eric Laurenta553c252009-07-17 12:17:14 -07003076 LOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3077 sp<ThreadBase> thread = mThread.promote();
3078 if (thread != 0) {
3079 Mutex::Autolock _l(thread->mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08003080 int state = mState;
Eric Laurenta553c252009-07-17 12:17:14 -07003081 if (mState > STOPPED) {
3082 mState = STOPPED;
3083 // If the track is not active (PAUSED and buffers full), flush buffers
3084 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3085 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3086 reset();
3087 }
Eric Laurent62443f52009-10-05 20:29:18 -07003088 LOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003089 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003090 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3091 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003092 AudioSystem::stopOutput(thread->id(),
3093 (AudioSystem::stream_type)mStreamType,
3094 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003095 thread->mLock.lock();
3096 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003097 }
3098}
3099
Eric Laurenta553c252009-07-17 12:17:14 -07003100void AudioFlinger::PlaybackThread::Track::pause()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003101{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003102 LOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurenta553c252009-07-17 12:17:14 -07003103 sp<ThreadBase> thread = mThread.promote();
3104 if (thread != 0) {
3105 Mutex::Autolock _l(thread->mLock);
3106 if (mState == ACTIVE || mState == RESUMING) {
3107 mState = PAUSING;
Eric Laurent62443f52009-10-05 20:29:18 -07003108 LOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurent49f02be2009-11-19 09:00:56 -08003109 if (!isOutputTrack()) {
3110 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003111 AudioSystem::stopOutput(thread->id(),
3112 (AudioSystem::stream_type)mStreamType,
3113 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003114 thread->mLock.lock();
3115 }
Eric Laurenta553c252009-07-17 12:17:14 -07003116 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003117 }
3118}
3119
Eric Laurenta553c252009-07-17 12:17:14 -07003120void AudioFlinger::PlaybackThread::Track::flush()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003121{
3122 LOGV("flush(%d)", mName);
Eric Laurenta553c252009-07-17 12:17:14 -07003123 sp<ThreadBase> thread = mThread.promote();
3124 if (thread != 0) {
3125 Mutex::Autolock _l(thread->mLock);
3126 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3127 return;
3128 }
3129 // No point remaining in PAUSED state after a flush => go to
3130 // STOPPED state
3131 mState = STOPPED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003132
Eric Laurenta553c252009-07-17 12:17:14 -07003133 mCblk->lock.lock();
3134 // NOTE: reset() will reset cblk->user and cblk->server with
3135 // the risk that at the same time, the AudioMixer is trying to read
3136 // data. In this case, getNextBuffer() would return a NULL pointer
3137 // as audio buffer => the AudioMixer code MUST always test that pointer
3138 // returned by getNextBuffer() is not NULL!
3139 reset();
3140 mCblk->lock.unlock();
3141 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003142}
3143
Eric Laurenta553c252009-07-17 12:17:14 -07003144void AudioFlinger::PlaybackThread::Track::reset()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003145{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003146 // Do not reset twice to avoid discarding data written just after a flush and before
3147 // the audioflinger thread detects the track is stopped.
3148 if (!mResetDone) {
3149 TrackBase::reset();
3150 // Force underrun condition to avoid false underrun callback until first data is
3151 // written to buffer
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003152 mCblk->flags |= CBLK_UNDERRUN_ON;
3153 mCblk->flags &= ~CBLK_FORCEREADY_MSK;
Eric Laurenta553c252009-07-17 12:17:14 -07003154 mFillingUpStatus = FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003155 mResetDone = true;
3156 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003157}
3158
Eric Laurenta553c252009-07-17 12:17:14 -07003159void AudioFlinger::PlaybackThread::Track::mute(bool muted)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003160{
3161 mMute = muted;
3162}
3163
Eric Laurenta553c252009-07-17 12:17:14 -07003164void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003165{
3166 mVolume[0] = left;
3167 mVolume[1] = right;
3168}
3169
Eric Laurent65b65452010-06-01 23:49:17 -07003170status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3171{
3172 status_t status = DEAD_OBJECT;
3173 sp<ThreadBase> thread = mThread.promote();
3174 if (thread != 0) {
3175 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3176 status = playbackThread->attachAuxEffect(this, EffectId);
3177 }
3178 return status;
3179}
3180
3181void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3182{
3183 mAuxEffectId = EffectId;
3184 mAuxBuffer = buffer;
3185}
3186
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003187// ----------------------------------------------------------------------------
3188
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003189// RecordTrack constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07003190AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3191 const wp<ThreadBase>& thread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003192 const sp<Client>& client,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003193 uint32_t sampleRate,
3194 int format,
3195 int channelCount,
3196 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07003197 uint32_t flags,
3198 int sessionId)
Eric Laurenta553c252009-07-17 12:17:14 -07003199 : TrackBase(thread, client, sampleRate, format,
Eric Laurent65b65452010-06-01 23:49:17 -07003200 channelCount, frameCount, flags, 0, sessionId),
Eric Laurenta553c252009-07-17 12:17:14 -07003201 mOverflow(false)
3202{
Eric Laurent8a77a992009-09-09 05:16:08 -07003203 if (mCblk != NULL) {
3204 LOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
3205 if (format == AudioSystem::PCM_16_BIT) {
3206 mCblk->frameSize = channelCount * sizeof(int16_t);
3207 } else if (format == AudioSystem::PCM_8_BIT) {
3208 mCblk->frameSize = channelCount * sizeof(int8_t);
3209 } else {
3210 mCblk->frameSize = sizeof(int8_t);
3211 }
3212 }
Eric Laurenta553c252009-07-17 12:17:14 -07003213}
3214
3215AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003216{
Eric Laurent49f02be2009-11-19 09:00:56 -08003217 sp<ThreadBase> thread = mThread.promote();
3218 if (thread != 0) {
3219 AudioSystem::releaseInput(thread->id());
3220 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003221}
3222
Eric Laurenta553c252009-07-17 12:17:14 -07003223status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003224{
3225 audio_track_cblk_t* cblk = this->cblk();
3226 uint32_t framesAvail;
3227 uint32_t framesReq = buffer->frameCount;
3228
3229 // Check if last stepServer failed, try to step now
3230 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3231 if (!step()) goto getNextBuffer_exit;
3232 LOGV("stepServer recovered");
3233 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3234 }
3235
3236 framesAvail = cblk->framesAvailable_l();
3237
3238 if (LIKELY(framesAvail)) {
3239 uint32_t s = cblk->server;
3240 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3241
3242 if (framesReq > framesAvail) {
3243 framesReq = framesAvail;
3244 }
3245 if (s + framesReq > bufferEnd) {
3246 framesReq = bufferEnd - s;
3247 }
3248
3249 buffer->raw = getBuffer(s, framesReq);
3250 if (buffer->raw == 0) goto getNextBuffer_exit;
3251
3252 buffer->frameCount = framesReq;
3253 return NO_ERROR;
3254 }
3255
3256getNextBuffer_exit:
3257 buffer->raw = 0;
3258 buffer->frameCount = 0;
3259 return NOT_ENOUGH_DATA;
3260}
3261
Eric Laurenta553c252009-07-17 12:17:14 -07003262status_t AudioFlinger::RecordThread::RecordTrack::start()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003263{
Eric Laurenta553c252009-07-17 12:17:14 -07003264 sp<ThreadBase> thread = mThread.promote();
3265 if (thread != 0) {
3266 RecordThread *recordThread = (RecordThread *)thread.get();
3267 return recordThread->start(this);
Eric Laurent49f02be2009-11-19 09:00:56 -08003268 } else {
3269 return BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -07003270 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003271}
3272
Eric Laurenta553c252009-07-17 12:17:14 -07003273void AudioFlinger::RecordThread::RecordTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003274{
Eric Laurenta553c252009-07-17 12:17:14 -07003275 sp<ThreadBase> thread = mThread.promote();
3276 if (thread != 0) {
3277 RecordThread *recordThread = (RecordThread *)thread.get();
3278 recordThread->stop(this);
3279 TrackBase::reset();
3280 // Force overerrun condition to avoid false overrun callback until first data is
3281 // read from buffer
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003282 mCblk->flags |= CBLK_UNDERRUN_ON;
Eric Laurenta553c252009-07-17 12:17:14 -07003283 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003284}
3285
Eric Laurent3fdb1262009-11-07 00:01:32 -08003286void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3287{
Eric Laurent65b65452010-06-01 23:49:17 -07003288 snprintf(buffer, size, " %05d %03u %03u %05d %04u %01d %05u %08x %08x\n",
Eric Laurent3fdb1262009-11-07 00:01:32 -08003289 (mClient == NULL) ? getpid() : mClient->pid(),
3290 mFormat,
Eric Laurentb0a01472010-05-14 05:45:46 -07003291 mCblk->channelCount,
Eric Laurent65b65452010-06-01 23:49:17 -07003292 mSessionId,
Eric Laurent3fdb1262009-11-07 00:01:32 -08003293 mFrameCount,
3294 mState,
3295 mCblk->sampleRate,
3296 mCblk->server,
3297 mCblk->user);
3298}
3299
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003300
3301// ----------------------------------------------------------------------------
3302
Eric Laurenta553c252009-07-17 12:17:14 -07003303AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3304 const wp<ThreadBase>& thread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003305 DuplicatingThread *sourceThread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003306 uint32_t sampleRate,
3307 int format,
3308 int channelCount,
3309 int frameCount)
Eric Laurent65b65452010-06-01 23:49:17 -07003310 : Track(thread, NULL, AudioSystem::NUM_STREAM_TYPES, sampleRate, format, channelCount, frameCount, NULL, 0),
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003311 mActive(false), mSourceThread(sourceThread)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003312{
Eric Laurenta553c252009-07-17 12:17:14 -07003313
3314 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
Eric Laurent6c30a712009-08-10 23:22:32 -07003315 if (mCblk != NULL) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003316 mCblk->flags |= CBLK_DIRECTION_OUT;
Eric Laurent6c30a712009-08-10 23:22:32 -07003317 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
3318 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
3319 mOutBuffer.frameCount = 0;
Eric Laurent6c30a712009-08-10 23:22:32 -07003320 playbackThread->mTracks.add(this);
Eric Laurentb0a01472010-05-14 05:45:46 -07003321 LOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, mCblk->frameCount %d, mCblk->sampleRate %d, mCblk->channelCount %d mBufferEnd %p",
3322 mCblk, mBuffer, mCblk->buffers, mCblk->frameCount, mCblk->sampleRate, mCblk->channelCount, mBufferEnd);
Eric Laurent6c30a712009-08-10 23:22:32 -07003323 } else {
3324 LOGW("Error creating output track on thread %p", playbackThread);
3325 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003326}
3327
Eric Laurenta553c252009-07-17 12:17:14 -07003328AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003329{
Eric Laurent6c30a712009-08-10 23:22:32 -07003330 clearBufferQueue();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003331}
3332
Eric Laurenta553c252009-07-17 12:17:14 -07003333status_t AudioFlinger::PlaybackThread::OutputTrack::start()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003334{
3335 status_t status = Track::start();
Eric Laurenta553c252009-07-17 12:17:14 -07003336 if (status != NO_ERROR) {
3337 return status;
3338 }
3339
3340 mActive = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003341 mRetryCount = 127;
3342 return status;
3343}
3344
Eric Laurenta553c252009-07-17 12:17:14 -07003345void AudioFlinger::PlaybackThread::OutputTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003346{
3347 Track::stop();
3348 clearBufferQueue();
3349 mOutBuffer.frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003350 mActive = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003351}
3352
Eric Laurenta553c252009-07-17 12:17:14 -07003353bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003354{
3355 Buffer *pInBuffer;
3356 Buffer inBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003357 uint32_t channelCount = mCblk->channelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003358 bool outputBufferFull = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003359 inBuffer.frameCount = frames;
3360 inBuffer.i16 = data;
Eric Laurenta553c252009-07-17 12:17:14 -07003361
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003362 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
Eric Laurenta553c252009-07-17 12:17:14 -07003363
Eric Laurent62443f52009-10-05 20:29:18 -07003364 if (!mActive && frames != 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003365 start();
3366 sp<ThreadBase> thread = mThread.promote();
3367 if (thread != 0) {
3368 MixerThread *mixerThread = (MixerThread *)thread.get();
3369 if (mCblk->frameCount > frames){
3370 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3371 uint32_t startFrames = (mCblk->frameCount - frames);
3372 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003373 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
Eric Laurenta553c252009-07-17 12:17:14 -07003374 pInBuffer->frameCount = startFrames;
3375 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003376 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
Eric Laurenta553c252009-07-17 12:17:14 -07003377 mBufferQueue.add(pInBuffer);
3378 } else {
3379 LOGW ("OutputTrack::write() %p no more buffers in queue", this);
3380 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003381 }
Eric Laurenta553c252009-07-17 12:17:14 -07003382 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003383 }
3384
Eric Laurenta553c252009-07-17 12:17:14 -07003385 while (waitTimeLeftMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003386 // First write pending buffers, then new data
3387 if (mBufferQueue.size()) {
3388 pInBuffer = mBufferQueue.itemAt(0);
3389 } else {
3390 pInBuffer = &inBuffer;
3391 }
Eric Laurenta553c252009-07-17 12:17:14 -07003392
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003393 if (pInBuffer->frameCount == 0) {
3394 break;
3395 }
Eric Laurenta553c252009-07-17 12:17:14 -07003396
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003397 if (mOutBuffer.frameCount == 0) {
3398 mOutBuffer.frameCount = pInBuffer->frameCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003399 nsecs_t startTime = systemTime();
3400 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003401 LOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Eric Laurenta553c252009-07-17 12:17:14 -07003402 outputBufferFull = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003403 break;
3404 }
Eric Laurenta553c252009-07-17 12:17:14 -07003405 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
Eric Laurenta553c252009-07-17 12:17:14 -07003406 if (waitTimeLeftMs >= waitTimeMs) {
3407 waitTimeLeftMs -= waitTimeMs;
3408 } else {
3409 waitTimeLeftMs = 0;
3410 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003411 }
Eric Laurenta553c252009-07-17 12:17:14 -07003412
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003413 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
Eric Laurentb0a01472010-05-14 05:45:46 -07003414 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003415 mCblk->stepUser(outFrames);
3416 pInBuffer->frameCount -= outFrames;
Eric Laurentb0a01472010-05-14 05:45:46 -07003417 pInBuffer->i16 += outFrames * channelCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003418 mOutBuffer.frameCount -= outFrames;
Eric Laurentb0a01472010-05-14 05:45:46 -07003419 mOutBuffer.i16 += outFrames * channelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003420
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003421 if (pInBuffer->frameCount == 0) {
3422 if (mBufferQueue.size()) {
3423 mBufferQueue.removeAt(0);
3424 delete [] pInBuffer->mBuffer;
3425 delete pInBuffer;
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003426 LOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003427 } else {
3428 break;
3429 }
3430 }
3431 }
Eric Laurenta553c252009-07-17 12:17:14 -07003432
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003433 // If we could not write all frames, allocate a buffer and queue it for next time.
3434 if (inBuffer.frameCount) {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003435 sp<ThreadBase> thread = mThread.promote();
3436 if (thread != 0 && !thread->standby()) {
3437 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3438 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003439 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003440 pInBuffer->frameCount = inBuffer.frameCount;
3441 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003442 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003443 mBufferQueue.add(pInBuffer);
3444 LOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
3445 } else {
3446 LOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
3447 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003448 }
3449 }
Eric Laurenta553c252009-07-17 12:17:14 -07003450
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003451 // Calling write() with a 0 length buffer, means that no more data will be written:
Eric Laurenta553c252009-07-17 12:17:14 -07003452 // If no more buffers are pending, fill output track buffer to make sure it is started
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003453 // by output mixer.
Eric Laurenta553c252009-07-17 12:17:14 -07003454 if (frames == 0 && mBufferQueue.size() == 0) {
3455 if (mCblk->user < mCblk->frameCount) {
3456 frames = mCblk->frameCount - mCblk->user;
3457 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003458 pInBuffer->mBuffer = new int16_t[frames * channelCount];
Eric Laurenta553c252009-07-17 12:17:14 -07003459 pInBuffer->frameCount = frames;
3460 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003461 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
Eric Laurenta553c252009-07-17 12:17:14 -07003462 mBufferQueue.add(pInBuffer);
Eric Laurent62443f52009-10-05 20:29:18 -07003463 } else if (mActive) {
Eric Laurenta553c252009-07-17 12:17:14 -07003464 stop();
3465 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003466 }
3467
Eric Laurenta553c252009-07-17 12:17:14 -07003468 return outputBufferFull;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003469}
3470
Eric Laurenta553c252009-07-17 12:17:14 -07003471status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003472{
3473 int active;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003474 status_t result;
3475 audio_track_cblk_t* cblk = mCblk;
3476 uint32_t framesReq = buffer->frameCount;
3477
Eric Laurenta553c252009-07-17 12:17:14 -07003478// LOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003479 buffer->frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003480
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003481 uint32_t framesAvail = cblk->framesAvailable();
3482
Eric Laurenta553c252009-07-17 12:17:14 -07003483
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003484 if (framesAvail == 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003485 Mutex::Autolock _l(cblk->lock);
3486 goto start_loop_here;
3487 while (framesAvail == 0) {
3488 active = mActive;
3489 if (UNLIKELY(!active)) {
3490 LOGV("Not active and NO_MORE_BUFFERS");
3491 return AudioTrack::NO_MORE_BUFFERS;
3492 }
3493 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3494 if (result != NO_ERROR) {
3495 return AudioTrack::NO_MORE_BUFFERS;
3496 }
3497 // read the server count again
3498 start_loop_here:
3499 framesAvail = cblk->framesAvailable_l();
3500 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003501 }
3502
Eric Laurenta553c252009-07-17 12:17:14 -07003503// if (framesAvail < framesReq) {
3504// return AudioTrack::NO_MORE_BUFFERS;
3505// }
3506
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003507 if (framesReq > framesAvail) {
3508 framesReq = framesAvail;
3509 }
3510
3511 uint32_t u = cblk->user;
3512 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
3513
3514 if (u + framesReq > bufferEnd) {
3515 framesReq = bufferEnd - u;
3516 }
3517
3518 buffer->frameCount = framesReq;
3519 buffer->raw = (void *)cblk->buffer(u);
3520 return NO_ERROR;
3521}
3522
3523
Eric Laurenta553c252009-07-17 12:17:14 -07003524void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003525{
3526 size_t size = mBufferQueue.size();
3527 Buffer *pBuffer;
Eric Laurenta553c252009-07-17 12:17:14 -07003528
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003529 for (size_t i = 0; i < size; i++) {
3530 pBuffer = mBufferQueue.itemAt(i);
3531 delete [] pBuffer->mBuffer;
3532 delete pBuffer;
3533 }
3534 mBufferQueue.clear();
3535}
3536
3537// ----------------------------------------------------------------------------
3538
3539AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
3540 : RefBase(),
3541 mAudioFlinger(audioFlinger),
Mathias Agopian6faf7892010-01-25 19:00:00 -08003542 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003543 mPid(pid)
3544{
3545 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
3546}
3547
Eric Laurentb9481d82009-09-17 05:12:56 -07003548// Client destructor must be called with AudioFlinger::mLock held
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003549AudioFlinger::Client::~Client()
3550{
Eric Laurentb9481d82009-09-17 05:12:56 -07003551 mAudioFlinger->removeClient_l(mPid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003552}
3553
3554const sp<MemoryDealer>& AudioFlinger::Client::heap() const
3555{
3556 return mMemoryDealer;
3557}
3558
3559// ----------------------------------------------------------------------------
3560
Eric Laurent4f0f17d2010-05-12 02:05:53 -07003561AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
3562 const sp<IAudioFlingerClient>& client,
3563 pid_t pid)
3564 : mAudioFlinger(audioFlinger), mPid(pid), mClient(client)
3565{
3566}
3567
3568AudioFlinger::NotificationClient::~NotificationClient()
3569{
3570 mClient.clear();
3571}
3572
3573void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
3574{
3575 sp<NotificationClient> keep(this);
3576 {
3577 mAudioFlinger->removeNotificationClient(mPid);
3578 }
3579}
3580
3581// ----------------------------------------------------------------------------
3582
Eric Laurenta553c252009-07-17 12:17:14 -07003583AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003584 : BnAudioTrack(),
3585 mTrack(track)
3586{
3587}
3588
3589AudioFlinger::TrackHandle::~TrackHandle() {
3590 // just stop the track on deletion, associated resources
3591 // will be freed from the main thread once all pending buffers have
3592 // been played. Unless it's not in the active track list, in which
3593 // case we free everything now...
3594 mTrack->destroy();
3595}
3596
3597status_t AudioFlinger::TrackHandle::start() {
3598 return mTrack->start();
3599}
3600
3601void AudioFlinger::TrackHandle::stop() {
3602 mTrack->stop();
3603}
3604
3605void AudioFlinger::TrackHandle::flush() {
3606 mTrack->flush();
3607}
3608
3609void AudioFlinger::TrackHandle::mute(bool e) {
3610 mTrack->mute(e);
3611}
3612
3613void AudioFlinger::TrackHandle::pause() {
3614 mTrack->pause();
3615}
3616
3617void AudioFlinger::TrackHandle::setVolume(float left, float right) {
3618 mTrack->setVolume(left, right);
3619}
3620
3621sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
3622 return mTrack->getCblk();
3623}
3624
Eric Laurent65b65452010-06-01 23:49:17 -07003625status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
3626{
3627 return mTrack->attachAuxEffect(EffectId);
3628}
3629
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003630status_t AudioFlinger::TrackHandle::onTransact(
3631 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3632{
3633 return BnAudioTrack::onTransact(code, data, reply, flags);
3634}
3635
3636// ----------------------------------------------------------------------------
3637
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003638sp<IAudioRecord> AudioFlinger::openRecord(
3639 pid_t pid,
Eric Laurentddb78e72009-07-28 08:44:33 -07003640 int input,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003641 uint32_t sampleRate,
3642 int format,
3643 int channelCount,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003644 int frameCount,
3645 uint32_t flags,
Eric Laurent65b65452010-06-01 23:49:17 -07003646 int *sessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003647 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003648{
Eric Laurenta553c252009-07-17 12:17:14 -07003649 sp<RecordThread::RecordTrack> recordTrack;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003650 sp<RecordHandle> recordHandle;
3651 sp<Client> client;
3652 wp<Client> wclient;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003653 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07003654 RecordThread *thread;
3655 size_t inFrameCount;
Eric Laurent65b65452010-06-01 23:49:17 -07003656 int lSessionId;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003657
3658 // check calling permissions
3659 if (!recordingAllowed()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003660 lStatus = PERMISSION_DENIED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003661 goto Exit;
3662 }
3663
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003664 // add client to list
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003665 { // scope for mLock
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003666 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07003667 thread = checkRecordThread_l(input);
3668 if (thread == NULL) {
3669 lStatus = BAD_VALUE;
3670 goto Exit;
3671 }
3672
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003673 wclient = mClients.valueFor(pid);
3674 if (wclient != NULL) {
3675 client = wclient.promote();
3676 } else {
3677 client = new Client(this, pid);
3678 mClients.add(pid, client);
3679 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003680
Eric Laurent65b65452010-06-01 23:49:17 -07003681 // If no audio session id is provided, create one here
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003682 if (sessionId != NULL && *sessionId != AudioSystem::SESSION_OUTPUT_MIX) {
Eric Laurent65b65452010-06-01 23:49:17 -07003683 lSessionId = *sessionId;
3684 } else {
Eric Laurentf3d6dd02010-11-18 08:40:16 -08003685 lSessionId = nextUniqueId_l();
Eric Laurent65b65452010-06-01 23:49:17 -07003686 if (sessionId != NULL) {
3687 *sessionId = lSessionId;
3688 }
3689 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003690 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurenta553c252009-07-17 12:17:14 -07003691 recordTrack = new RecordThread::RecordTrack(thread, client, sampleRate,
Eric Laurent65b65452010-06-01 23:49:17 -07003692 format, channelCount, frameCount, flags, lSessionId);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003693 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003694 if (recordTrack->getCblk() == NULL) {
Eric Laurentb9481d82009-09-17 05:12:56 -07003695 // remove local strong reference to Client before deleting the RecordTrack so that the Client
3696 // destructor is called by the TrackBase destructor with mLock held
3697 client.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003698 recordTrack.clear();
3699 lStatus = NO_MEMORY;
3700 goto Exit;
3701 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003702
3703 // return to handle to client
3704 recordHandle = new RecordHandle(recordTrack);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003705 lStatus = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003706
3707Exit:
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003708 if (status) {
3709 *status = lStatus;
3710 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003711 return recordHandle;
3712}
3713
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003714// ----------------------------------------------------------------------------
3715
Eric Laurenta553c252009-07-17 12:17:14 -07003716AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003717 : BnAudioRecord(),
3718 mRecordTrack(recordTrack)
3719{
3720}
3721
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003722AudioFlinger::RecordHandle::~RecordHandle() {
3723 stop();
3724}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003725
3726status_t AudioFlinger::RecordHandle::start() {
3727 LOGV("RecordHandle::start()");
3728 return mRecordTrack->start();
3729}
3730
3731void AudioFlinger::RecordHandle::stop() {
3732 LOGV("RecordHandle::stop()");
3733 mRecordTrack->stop();
3734}
3735
3736sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
3737 return mRecordTrack->getCblk();
3738}
3739
3740status_t AudioFlinger::RecordHandle::onTransact(
3741 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3742{
3743 return BnAudioRecord::onTransact(code, data, reply, flags);
3744}
3745
3746// ----------------------------------------------------------------------------
3747
Eric Laurent49f02be2009-11-19 09:00:56 -08003748AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger, AudioStreamIn *input, uint32_t sampleRate, uint32_t channels, int id) :
3749 ThreadBase(audioFlinger, id),
Eric Laurenta553c252009-07-17 12:17:14 -07003750 mInput(input), mResampler(0), mRsmpOutBuffer(0), mRsmpInBuffer(0)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003751{
Eric Laurenta553c252009-07-17 12:17:14 -07003752 mReqChannelCount = AudioSystem::popCount(channels);
3753 mReqSampleRate = sampleRate;
3754 readInputParameters();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003755}
3756
Eric Laurenta553c252009-07-17 12:17:14 -07003757
3758AudioFlinger::RecordThread::~RecordThread()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003759{
Eric Laurenta553c252009-07-17 12:17:14 -07003760 delete[] mRsmpInBuffer;
3761 if (mResampler != 0) {
3762 delete mResampler;
3763 delete[] mRsmpOutBuffer;
3764 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003765}
3766
Eric Laurenta553c252009-07-17 12:17:14 -07003767void AudioFlinger::RecordThread::onFirstRef()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003768{
Eric Laurenta553c252009-07-17 12:17:14 -07003769 const size_t SIZE = 256;
3770 char buffer[SIZE];
3771
3772 snprintf(buffer, SIZE, "Record Thread %p", this);
3773
3774 run(buffer, PRIORITY_URGENT_AUDIO);
3775}
Eric Laurent49f02be2009-11-19 09:00:56 -08003776
Eric Laurenta553c252009-07-17 12:17:14 -07003777bool AudioFlinger::RecordThread::threadLoop()
3778{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003779 AudioBufferProvider::Buffer buffer;
Eric Laurenta553c252009-07-17 12:17:14 -07003780 sp<RecordTrack> activeTrack;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003781
Eric Laurent4712baa2010-09-30 16:12:31 -07003782 nsecs_t lastWarning = 0;
3783
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003784 // start recording
3785 while (!exitPending()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003786
Eric Laurenta553c252009-07-17 12:17:14 -07003787 processConfigEvents();
3788
3789 { // scope for mLock
3790 Mutex::Autolock _l(mLock);
3791 checkForNewParameters_l();
3792 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
3793 if (!mStandby) {
3794 mInput->standby();
3795 mStandby = true;
3796 }
3797
3798 if (exitPending()) break;
3799
3800 LOGV("RecordThread: loop stopping");
3801 // go to sleep
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003802 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07003803 LOGV("RecordThread: loop starting");
3804 continue;
3805 }
3806 if (mActiveTrack != 0) {
3807 if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08003808 if (!mStandby) {
3809 mInput->standby();
3810 mStandby = true;
3811 }
Eric Laurenta553c252009-07-17 12:17:14 -07003812 mActiveTrack.clear();
3813 mStartStopCond.broadcast();
3814 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
Eric Laurenta553c252009-07-17 12:17:14 -07003815 if (mReqChannelCount != mActiveTrack->channelCount()) {
3816 mActiveTrack.clear();
Eric Laurent9cc489a22009-12-05 05:20:01 -08003817 mStartStopCond.broadcast();
3818 } else if (mBytesRead != 0) {
3819 // record start succeeds only if first read from audio input
3820 // succeeds
3821 if (mBytesRead > 0) {
3822 mActiveTrack->mState = TrackBase::ACTIVE;
3823 } else {
3824 mActiveTrack.clear();
3825 }
3826 mStartStopCond.broadcast();
Eric Laurenta553c252009-07-17 12:17:14 -07003827 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08003828 mStandby = false;
Eric Laurenta553c252009-07-17 12:17:14 -07003829 }
Eric Laurenta553c252009-07-17 12:17:14 -07003830 }
3831 }
3832
3833 if (mActiveTrack != 0) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08003834 if (mActiveTrack->mState != TrackBase::ACTIVE &&
3835 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent49f02be2009-11-19 09:00:56 -08003836 usleep(5000);
3837 continue;
3838 }
Eric Laurenta553c252009-07-17 12:17:14 -07003839 buffer.frameCount = mFrameCount;
3840 if (LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
3841 size_t framesOut = buffer.frameCount;
3842 if (mResampler == 0) {
3843 // no resampling
3844 while (framesOut) {
3845 size_t framesIn = mFrameCount - mRsmpInIndex;
3846 if (framesIn) {
3847 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
3848 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
3849 if (framesIn > framesOut)
3850 framesIn = framesOut;
3851 mRsmpInIndex += framesIn;
3852 framesOut -= framesIn;
Eric Laurentb0a01472010-05-14 05:45:46 -07003853 if ((int)mChannelCount == mReqChannelCount ||
Eric Laurenta553c252009-07-17 12:17:14 -07003854 mFormat != AudioSystem::PCM_16_BIT) {
3855 memcpy(dst, src, framesIn * mFrameSize);
3856 } else {
3857 int16_t *src16 = (int16_t *)src;
3858 int16_t *dst16 = (int16_t *)dst;
3859 if (mChannelCount == 1) {
3860 while (framesIn--) {
3861 *dst16++ = *src16;
3862 *dst16++ = *src16++;
3863 }
3864 } else {
3865 while (framesIn--) {
3866 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
3867 src16 += 2;
3868 }
3869 }
3870 }
3871 }
3872 if (framesOut && mFrameCount == mRsmpInIndex) {
Eric Laurenta553c252009-07-17 12:17:14 -07003873 if (framesOut == mFrameCount &&
Eric Laurentb0a01472010-05-14 05:45:46 -07003874 ((int)mChannelCount == mReqChannelCount || mFormat != AudioSystem::PCM_16_BIT)) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08003875 mBytesRead = mInput->read(buffer.raw, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07003876 framesOut = 0;
3877 } else {
Eric Laurent9cc489a22009-12-05 05:20:01 -08003878 mBytesRead = mInput->read(mRsmpInBuffer, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07003879 mRsmpInIndex = 0;
3880 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08003881 if (mBytesRead < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003882 LOGE("Error reading audio input");
Eric Laurent9cc489a22009-12-05 05:20:01 -08003883 if (mActiveTrack->mState == TrackBase::ACTIVE) {
Eric Laurentba8811f2010-03-02 18:38:06 -08003884 // Force input into standby so that it tries to
3885 // recover at next read attempt
3886 mInput->standby();
3887 usleep(5000);
Eric Laurent9cc489a22009-12-05 05:20:01 -08003888 }
Eric Laurenta553c252009-07-17 12:17:14 -07003889 mRsmpInIndex = mFrameCount;
3890 framesOut = 0;
3891 buffer.frameCount = 0;
3892 }
3893 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003894 }
3895 } else {
Eric Laurenta553c252009-07-17 12:17:14 -07003896 // resampling
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003897
Eric Laurenta553c252009-07-17 12:17:14 -07003898 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
3899 // alter output frame count as if we were expecting stereo samples
3900 if (mChannelCount == 1 && mReqChannelCount == 1) {
3901 framesOut >>= 1;
3902 }
3903 mResampler->resample(mRsmpOutBuffer, framesOut, this);
3904 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
3905 // are 32 bit aligned which should be always true.
3906 if (mChannelCount == 2 && mReqChannelCount == 1) {
3907 AudioMixer::ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
3908 // the resampler always outputs stereo samples: do post stereo to mono conversion
3909 int16_t *src = (int16_t *)mRsmpOutBuffer;
3910 int16_t *dst = buffer.i16;
3911 while (framesOut--) {
3912 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
3913 src += 2;
3914 }
3915 } else {
3916 AudioMixer::ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
3917 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003918
Eric Laurenta553c252009-07-17 12:17:14 -07003919 }
3920 mActiveTrack->releaseBuffer(&buffer);
3921 mActiveTrack->overflow();
3922 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003923 // client isn't retrieving buffers fast enough
3924 else {
Eric Laurent4712baa2010-09-30 16:12:31 -07003925 if (!mActiveTrack->setOverflow()) {
3926 nsecs_t now = systemTime();
3927 if ((now - lastWarning) > kWarningThrottle) {
3928 LOGW("RecordThread: buffer overflow");
3929 lastWarning = now;
3930 }
3931 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003932 // Release the processor for a while before asking for a new buffer.
3933 // This will give the application more chance to read from the buffer and
3934 // clear the overflow.
3935 usleep(5000);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003936 }
3937 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003938 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003939
Eric Laurenta553c252009-07-17 12:17:14 -07003940 if (!mStandby) {
3941 mInput->standby();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003942 }
Eric Laurenta553c252009-07-17 12:17:14 -07003943 mActiveTrack.clear();
3944
Eric Laurent49f02be2009-11-19 09:00:56 -08003945 mStartStopCond.broadcast();
3946
Eric Laurenta553c252009-07-17 12:17:14 -07003947 LOGV("RecordThread %p exiting", this);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003948 return false;
3949}
3950
Eric Laurenta553c252009-07-17 12:17:14 -07003951status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003952{
Eric Laurenta553c252009-07-17 12:17:14 -07003953 LOGV("RecordThread::start");
Eric Laurent49f02be2009-11-19 09:00:56 -08003954 sp <ThreadBase> strongMe = this;
3955 status_t status = NO_ERROR;
3956 {
3957 AutoMutex lock(&mLock);
3958 if (mActiveTrack != 0) {
3959 if (recordTrack != mActiveTrack.get()) {
3960 status = -EBUSY;
3961 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08003962 mActiveTrack->mState = TrackBase::ACTIVE;
Eric Laurent49f02be2009-11-19 09:00:56 -08003963 }
3964 return status;
3965 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003966
Eric Laurent49f02be2009-11-19 09:00:56 -08003967 recordTrack->mState = TrackBase::IDLE;
3968 mActiveTrack = recordTrack;
3969 mLock.unlock();
3970 status_t status = AudioSystem::startInput(mId);
3971 mLock.lock();
3972 if (status != NO_ERROR) {
3973 mActiveTrack.clear();
3974 return status;
3975 }
3976 mActiveTrack->mState = TrackBase::RESUMING;
Eric Laurent9cc489a22009-12-05 05:20:01 -08003977 mRsmpInIndex = mFrameCount;
3978 mBytesRead = 0;
Eric Laurent49f02be2009-11-19 09:00:56 -08003979 // signal thread to start
3980 LOGV("Signal record thread");
3981 mWaitWorkCV.signal();
3982 // do not wait for mStartStopCond if exiting
3983 if (mExiting) {
3984 mActiveTrack.clear();
3985 status = INVALID_OPERATION;
3986 goto startError;
3987 }
3988 mStartStopCond.wait(mLock);
3989 if (mActiveTrack == 0) {
3990 LOGV("Record failed to start");
3991 status = BAD_VALUE;
3992 goto startError;
3993 }
Eric Laurenta553c252009-07-17 12:17:14 -07003994 LOGV("Record started OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08003995 return status;
Eric Laurenta553c252009-07-17 12:17:14 -07003996 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003997startError:
3998 AudioSystem::stopInput(mId);
3999 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004000}
4001
Eric Laurenta553c252009-07-17 12:17:14 -07004002void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
4003 LOGV("RecordThread::stop");
Eric Laurent49f02be2009-11-19 09:00:56 -08004004 sp <ThreadBase> strongMe = this;
4005 {
4006 AutoMutex lock(&mLock);
4007 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4008 mActiveTrack->mState = TrackBase::PAUSING;
4009 // do not wait for mStartStopCond if exiting
4010 if (mExiting) {
4011 return;
4012 }
4013 mStartStopCond.wait(mLock);
4014 // if we have been restarted, recordTrack == mActiveTrack.get() here
4015 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4016 mLock.unlock();
4017 AudioSystem::stopInput(mId);
4018 mLock.lock();
Eric Laurent9cc489a22009-12-05 05:20:01 -08004019 LOGV("Record stopped OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08004020 }
4021 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004022 }
4023}
4024
Eric Laurenta553c252009-07-17 12:17:14 -07004025status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004026{
4027 const size_t SIZE = 256;
4028 char buffer[SIZE];
4029 String8 result;
4030 pid_t pid = 0;
4031
Eric Laurent3fdb1262009-11-07 00:01:32 -08004032 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4033 result.append(buffer);
4034
4035 if (mActiveTrack != 0) {
4036 result.append("Active Track:\n");
Eric Laurent65b65452010-06-01 23:49:17 -07004037 result.append(" Clien Fmt Chn Session Buf S SRate Serv User\n");
Eric Laurent3fdb1262009-11-07 00:01:32 -08004038 mActiveTrack->dump(buffer, SIZE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004039 result.append(buffer);
Eric Laurent3fdb1262009-11-07 00:01:32 -08004040
4041 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4042 result.append(buffer);
4043 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4044 result.append(buffer);
4045 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != 0));
4046 result.append(buffer);
4047 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4048 result.append(buffer);
4049 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4050 result.append(buffer);
4051
4052
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004053 } else {
4054 result.append("No record client\n");
4055 }
4056 write(fd, result.string(), result.size());
Eric Laurent3fdb1262009-11-07 00:01:32 -08004057
4058 dumpBase(fd, args);
4059
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004060 return NO_ERROR;
4061}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004062
Eric Laurenta553c252009-07-17 12:17:14 -07004063status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4064{
4065 size_t framesReq = buffer->frameCount;
4066 size_t framesReady = mFrameCount - mRsmpInIndex;
4067 int channelCount;
4068
4069 if (framesReady == 0) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08004070 mBytesRead = mInput->read(mRsmpInBuffer, mInputBytes);
4071 if (mBytesRead < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07004072 LOGE("RecordThread::getNextBuffer() Error reading audio input");
Eric Laurent9cc489a22009-12-05 05:20:01 -08004073 if (mActiveTrack->mState == TrackBase::ACTIVE) {
Eric Laurentba8811f2010-03-02 18:38:06 -08004074 // Force input into standby so that it tries to
4075 // recover at next read attempt
4076 mInput->standby();
4077 usleep(5000);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004078 }
Eric Laurenta553c252009-07-17 12:17:14 -07004079 buffer->raw = 0;
4080 buffer->frameCount = 0;
4081 return NOT_ENOUGH_DATA;
4082 }
4083 mRsmpInIndex = 0;
4084 framesReady = mFrameCount;
4085 }
4086
4087 if (framesReq > framesReady) {
4088 framesReq = framesReady;
4089 }
4090
4091 if (mChannelCount == 1 && mReqChannelCount == 2) {
4092 channelCount = 1;
4093 } else {
4094 channelCount = 2;
4095 }
4096 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4097 buffer->frameCount = framesReq;
4098 return NO_ERROR;
4099}
4100
4101void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4102{
4103 mRsmpInIndex += buffer->frameCount;
4104 buffer->frameCount = 0;
4105}
4106
4107bool AudioFlinger::RecordThread::checkForNewParameters_l()
4108{
4109 bool reconfig = false;
4110
Eric Laurent8fce46a2009-08-04 09:45:33 -07004111 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07004112 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07004113 String8 keyValuePair = mNewParameters[0];
4114 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07004115 int value;
4116 int reqFormat = mFormat;
4117 int reqSamplingRate = mReqSampleRate;
4118 int reqChannelCount = mReqChannelCount;
Eric Laurent8fce46a2009-08-04 09:45:33 -07004119
Eric Laurenta553c252009-07-17 12:17:14 -07004120 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4121 reqSamplingRate = value;
4122 reconfig = true;
4123 }
4124 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
4125 reqFormat = value;
4126 reconfig = true;
4127 }
4128 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
4129 reqChannelCount = AudioSystem::popCount(value);
4130 reconfig = true;
4131 }
4132 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4133 // do not accept frame count changes if tracks are open as the track buffer
4134 // size depends on frame count and correct behavior would not be garantied
4135 // if frame count is changed after track creation
4136 if (mActiveTrack != 0) {
4137 status = INVALID_OPERATION;
4138 } else {
4139 reconfig = true;
4140 }
4141 }
4142 if (status == NO_ERROR) {
Eric Laurent8fce46a2009-08-04 09:45:33 -07004143 status = mInput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07004144 if (status == INVALID_OPERATION) {
4145 mInput->standby();
Eric Laurent8fce46a2009-08-04 09:45:33 -07004146 status = mInput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07004147 }
4148 if (reconfig) {
4149 if (status == BAD_VALUE &&
4150 reqFormat == mInput->format() && reqFormat == AudioSystem::PCM_16_BIT &&
4151 ((int)mInput->sampleRate() <= 2 * reqSamplingRate) &&
4152 (AudioSystem::popCount(mInput->channels()) < 3) && (reqChannelCount < 3)) {
4153 status = NO_ERROR;
4154 }
4155 if (status == NO_ERROR) {
4156 readInputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07004157 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07004158 }
4159 }
4160 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08004161
4162 mNewParameters.removeAt(0);
4163
Eric Laurenta553c252009-07-17 12:17:14 -07004164 mParamStatus = status;
4165 mParamCond.signal();
Eric Laurent8fce46a2009-08-04 09:45:33 -07004166 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07004167 }
4168 return reconfig;
4169}
4170
4171String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4172{
4173 return mInput->getParameters(keys);
4174}
4175
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004176void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
Eric Laurenta553c252009-07-17 12:17:14 -07004177 AudioSystem::OutputDescriptor desc;
4178 void *param2 = 0;
4179
4180 switch (event) {
4181 case AudioSystem::INPUT_OPENED:
4182 case AudioSystem::INPUT_CONFIG_CHANGED:
Eric Laurentb0a01472010-05-14 05:45:46 -07004183 desc.channels = mChannels;
Eric Laurenta553c252009-07-17 12:17:14 -07004184 desc.samplingRate = mSampleRate;
4185 desc.format = mFormat;
4186 desc.frameCount = mFrameCount;
4187 desc.latency = 0;
4188 param2 = &desc;
4189 break;
4190
4191 case AudioSystem::INPUT_CLOSED:
4192 default:
4193 break;
4194 }
Eric Laurent49f02be2009-11-19 09:00:56 -08004195 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurenta553c252009-07-17 12:17:14 -07004196}
4197
4198void AudioFlinger::RecordThread::readInputParameters()
4199{
4200 if (mRsmpInBuffer) delete mRsmpInBuffer;
4201 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
4202 if (mResampler) delete mResampler;
4203 mResampler = 0;
4204
4205 mSampleRate = mInput->sampleRate();
Eric Laurentb0a01472010-05-14 05:45:46 -07004206 mChannels = mInput->channels();
4207 mChannelCount = (uint16_t)AudioSystem::popCount(mChannels);
Eric Laurenta553c252009-07-17 12:17:14 -07004208 mFormat = mInput->format();
Eric Laurentb0a01472010-05-14 05:45:46 -07004209 mFrameSize = (uint16_t)mInput->frameSize();
Eric Laurenta553c252009-07-17 12:17:14 -07004210 mInputBytes = mInput->bufferSize();
4211 mFrameCount = mInputBytes / mFrameSize;
4212 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4213
4214 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4215 {
4216 int channelCount;
4217 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4218 // stereo to mono post process as the resampler always outputs stereo.
4219 if (mChannelCount == 1 && mReqChannelCount == 2) {
4220 channelCount = 1;
4221 } else {
4222 channelCount = 2;
4223 }
4224 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4225 mResampler->setSampleRate(mSampleRate);
4226 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4227 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4228
4229 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4230 if (mChannelCount == 1 && mReqChannelCount == 1) {
4231 mFrameCount >>= 1;
4232 }
4233
4234 }
4235 mRsmpInIndex = mFrameCount;
4236}
4237
Eric Laurent47d0a922010-02-26 02:47:27 -08004238unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4239{
4240 return mInput->getInputFramesLost();
4241}
4242
Eric Laurenta553c252009-07-17 12:17:14 -07004243// ----------------------------------------------------------------------------
4244
Eric Laurentddb78e72009-07-28 08:44:33 -07004245int AudioFlinger::openOutput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07004246 uint32_t *pSamplingRate,
4247 uint32_t *pFormat,
4248 uint32_t *pChannels,
4249 uint32_t *pLatencyMs,
4250 uint32_t flags)
4251{
4252 status_t status;
4253 PlaybackThread *thread = NULL;
4254 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4255 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4256 uint32_t format = pFormat ? *pFormat : 0;
4257 uint32_t channels = pChannels ? *pChannels : 0;
4258 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
4259
4260 LOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
4261 pDevices ? *pDevices : 0,
4262 samplingRate,
4263 format,
4264 channels,
4265 flags);
4266
4267 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004268 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004269 }
4270 Mutex::Autolock _l(mLock);
4271
4272 AudioStreamOut *output = mAudioHardware->openOutputStream(*pDevices,
4273 (int *)&format,
4274 &channels,
4275 &samplingRate,
4276 &status);
4277 LOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
4278 output,
4279 samplingRate,
4280 format,
4281 channels,
4282 status);
4283
4284 mHardwareStatus = AUDIO_HW_IDLE;
4285 if (output != 0) {
Eric Laurentf3d6dd02010-11-18 08:40:16 -08004286 int id = nextUniqueId_l();
Eric Laurenta553c252009-07-17 12:17:14 -07004287 if ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) ||
4288 (format != AudioSystem::PCM_16_BIT) ||
4289 (channels != AudioSystem::CHANNEL_OUT_STEREO)) {
Eric Laurent65b65452010-06-01 23:49:17 -07004290 thread = new DirectOutputThread(this, output, id, *pDevices);
4291 LOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004292 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07004293 thread = new MixerThread(this, output, id, *pDevices);
4294 LOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Glenn Kasten871c16c2010-03-05 12:18:01 -08004295
4296#ifdef LVMX
4297 unsigned bitsPerSample =
4298 (format == AudioSystem::PCM_16_BIT) ? 16 :
4299 ((format == AudioSystem::PCM_8_BIT) ? 8 : 0);
4300 unsigned channelCount = (channels == AudioSystem::CHANNEL_OUT_STEREO) ? 2 : 1;
4301 int audioOutputType = LifeVibes::threadIdToAudioOutputType(thread->id());
4302
4303 LifeVibes::init_aot(audioOutputType, samplingRate, bitsPerSample, channelCount);
4304 LifeVibes::setDevice(audioOutputType, *pDevices);
4305#endif
4306
Eric Laurenta553c252009-07-17 12:17:14 -07004307 }
Eric Laurent65b65452010-06-01 23:49:17 -07004308 mPlaybackThreads.add(id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004309
4310 if (pSamplingRate) *pSamplingRate = samplingRate;
4311 if (pFormat) *pFormat = format;
4312 if (pChannels) *pChannels = channels;
4313 if (pLatencyMs) *pLatencyMs = thread->latency();
Eric Laurent9cc489a22009-12-05 05:20:01 -08004314
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004315 // notify client processes of the new output creation
4316 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004317 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004318 }
4319
Eric Laurent9cc489a22009-12-05 05:20:01 -08004320 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004321}
4322
Eric Laurentddb78e72009-07-28 08:44:33 -07004323int AudioFlinger::openDuplicateOutput(int output1, int output2)
Eric Laurenta553c252009-07-17 12:17:14 -07004324{
4325 Mutex::Autolock _l(mLock);
Eric Laurentddb78e72009-07-28 08:44:33 -07004326 MixerThread *thread1 = checkMixerThread_l(output1);
4327 MixerThread *thread2 = checkMixerThread_l(output2);
Eric Laurenta553c252009-07-17 12:17:14 -07004328
Eric Laurentddb78e72009-07-28 08:44:33 -07004329 if (thread1 == NULL || thread2 == NULL) {
4330 LOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
4331 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004332 }
4333
Eric Laurentf3d6dd02010-11-18 08:40:16 -08004334 int id = nextUniqueId_l();
Eric Laurent65b65452010-06-01 23:49:17 -07004335 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
Eric Laurentddb78e72009-07-28 08:44:33 -07004336 thread->addOutputTrack(thread2);
Eric Laurent65b65452010-06-01 23:49:17 -07004337 mPlaybackThreads.add(id, thread);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004338 // notify client processes of the new output creation
4339 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004340 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004341}
4342
Eric Laurentddb78e72009-07-28 08:44:33 -07004343status_t AudioFlinger::closeOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004344{
Eric Laurent49018a52009-08-04 08:37:05 -07004345 // keep strong reference on the playback thread so that
4346 // it is not destroyed while exit() is executed
4347 sp <PlaybackThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07004348 {
4349 Mutex::Autolock _l(mLock);
4350 thread = checkPlaybackThread_l(output);
4351 if (thread == NULL) {
4352 return BAD_VALUE;
4353 }
4354
Eric Laurentddb78e72009-07-28 08:44:33 -07004355 LOGV("closeOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004356
4357 if (thread->type() == PlaybackThread::MIXER) {
4358 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004359 if (mPlaybackThreads.valueAt(i)->type() == PlaybackThread::DUPLICATING) {
4360 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Eric Laurent49018a52009-08-04 08:37:05 -07004361 dupThread->removeOutputTrack((MixerThread *)thread.get());
Eric Laurenta553c252009-07-17 12:17:14 -07004362 }
4363 }
4364 }
Eric Laurent296a0ec2009-09-15 07:10:12 -07004365 void *param2 = 0;
Eric Laurent49f02be2009-11-19 09:00:56 -08004366 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
Eric Laurentddb78e72009-07-28 08:44:33 -07004367 mPlaybackThreads.removeItem(output);
Eric Laurenta553c252009-07-17 12:17:14 -07004368 }
4369 thread->exit();
4370
Eric Laurent49018a52009-08-04 08:37:05 -07004371 if (thread->type() != PlaybackThread::DUPLICATING) {
4372 mAudioHardware->closeOutputStream(thread->getOutput());
4373 }
Eric Laurenta553c252009-07-17 12:17:14 -07004374 return NO_ERROR;
4375}
4376
Eric Laurentddb78e72009-07-28 08:44:33 -07004377status_t AudioFlinger::suspendOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004378{
4379 Mutex::Autolock _l(mLock);
4380 PlaybackThread *thread = checkPlaybackThread_l(output);
4381
4382 if (thread == NULL) {
4383 return BAD_VALUE;
4384 }
4385
Eric Laurentddb78e72009-07-28 08:44:33 -07004386 LOGV("suspendOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004387 thread->suspend();
4388
4389 return NO_ERROR;
4390}
4391
Eric Laurentddb78e72009-07-28 08:44:33 -07004392status_t AudioFlinger::restoreOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004393{
4394 Mutex::Autolock _l(mLock);
4395 PlaybackThread *thread = checkPlaybackThread_l(output);
4396
4397 if (thread == NULL) {
4398 return BAD_VALUE;
4399 }
4400
Eric Laurentddb78e72009-07-28 08:44:33 -07004401 LOGV("restoreOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004402
4403 thread->restore();
4404
4405 return NO_ERROR;
4406}
4407
Eric Laurentddb78e72009-07-28 08:44:33 -07004408int AudioFlinger::openInput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07004409 uint32_t *pSamplingRate,
4410 uint32_t *pFormat,
4411 uint32_t *pChannels,
4412 uint32_t acoustics)
4413{
4414 status_t status;
4415 RecordThread *thread = NULL;
4416 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4417 uint32_t format = pFormat ? *pFormat : 0;
4418 uint32_t channels = pChannels ? *pChannels : 0;
4419 uint32_t reqSamplingRate = samplingRate;
4420 uint32_t reqFormat = format;
4421 uint32_t reqChannels = channels;
4422
4423 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004424 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004425 }
4426 Mutex::Autolock _l(mLock);
4427
4428 AudioStreamIn *input = mAudioHardware->openInputStream(*pDevices,
4429 (int *)&format,
4430 &channels,
4431 &samplingRate,
4432 &status,
4433 (AudioSystem::audio_in_acoustics)acoustics);
4434 LOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
4435 input,
4436 samplingRate,
4437 format,
4438 channels,
4439 acoustics,
4440 status);
4441
4442 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
4443 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
4444 // or stereo to mono conversions on 16 bit PCM inputs.
4445 if (input == 0 && status == BAD_VALUE &&
4446 reqFormat == format && format == AudioSystem::PCM_16_BIT &&
4447 (samplingRate <= 2 * reqSamplingRate) &&
4448 (AudioSystem::popCount(channels) < 3) && (AudioSystem::popCount(reqChannels) < 3)) {
4449 LOGV("openInput() reopening with proposed sampling rate and channels");
4450 input = mAudioHardware->openInputStream(*pDevices,
4451 (int *)&format,
4452 &channels,
4453 &samplingRate,
4454 &status,
4455 (AudioSystem::audio_in_acoustics)acoustics);
4456 }
4457
4458 if (input != 0) {
Eric Laurentf3d6dd02010-11-18 08:40:16 -08004459 int id = nextUniqueId_l();
Eric Laurenta553c252009-07-17 12:17:14 -07004460 // Start record thread
Eric Laurent65b65452010-06-01 23:49:17 -07004461 thread = new RecordThread(this, input, reqSamplingRate, reqChannels, id);
4462 mRecordThreads.add(id, thread);
4463 LOGV("openInput() created record thread: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004464 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
4465 if (pFormat) *pFormat = format;
4466 if (pChannels) *pChannels = reqChannels;
4467
4468 input->standby();
Eric Laurent9cc489a22009-12-05 05:20:01 -08004469
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004470 // notify client processes of the new input creation
4471 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004472 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004473 }
4474
Eric Laurent9cc489a22009-12-05 05:20:01 -08004475 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004476}
4477
Eric Laurentddb78e72009-07-28 08:44:33 -07004478status_t AudioFlinger::closeInput(int input)
Eric Laurenta553c252009-07-17 12:17:14 -07004479{
Eric Laurent49018a52009-08-04 08:37:05 -07004480 // keep strong reference on the record thread so that
4481 // it is not destroyed while exit() is executed
4482 sp <RecordThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07004483 {
4484 Mutex::Autolock _l(mLock);
4485 thread = checkRecordThread_l(input);
4486 if (thread == NULL) {
4487 return BAD_VALUE;
4488 }
4489
Eric Laurentddb78e72009-07-28 08:44:33 -07004490 LOGV("closeInput() %d", input);
Eric Laurent296a0ec2009-09-15 07:10:12 -07004491 void *param2 = 0;
Eric Laurent49f02be2009-11-19 09:00:56 -08004492 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
Eric Laurentddb78e72009-07-28 08:44:33 -07004493 mRecordThreads.removeItem(input);
Eric Laurenta553c252009-07-17 12:17:14 -07004494 }
4495 thread->exit();
4496
Eric Laurent49018a52009-08-04 08:37:05 -07004497 mAudioHardware->closeInputStream(thread->getInput());
4498
Eric Laurenta553c252009-07-17 12:17:14 -07004499 return NO_ERROR;
4500}
4501
Eric Laurentddb78e72009-07-28 08:44:33 -07004502status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004503{
4504 Mutex::Autolock _l(mLock);
4505 MixerThread *dstThread = checkMixerThread_l(output);
4506 if (dstThread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004507 LOGW("setStreamOutput() bad output id %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004508 return BAD_VALUE;
4509 }
4510
Eric Laurentddb78e72009-07-28 08:44:33 -07004511 LOGV("setStreamOutput() stream %d to output %d", stream, output);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004512 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
Eric Laurenta553c252009-07-17 12:17:14 -07004513
4514 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004515 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurenta553c252009-07-17 12:17:14 -07004516 if (thread != dstThread &&
4517 thread->type() != PlaybackThread::DIRECT) {
4518 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004519 srcThread->invalidateTracks(stream);
Eric Laurenta553c252009-07-17 12:17:14 -07004520 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004521 }
Eric Laurentd069f322009-09-01 05:56:26 -07004522
Eric Laurenta553c252009-07-17 12:17:14 -07004523 return NO_ERROR;
4524}
4525
Eric Laurent65b65452010-06-01 23:49:17 -07004526
4527int AudioFlinger::newAudioSessionId()
4528{
Eric Laurentf3d6dd02010-11-18 08:40:16 -08004529 AutoMutex _l(mLock);
4530 return nextUniqueId_l();
Eric Laurent65b65452010-06-01 23:49:17 -07004531}
4532
Eric Laurenta553c252009-07-17 12:17:14 -07004533// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07004534AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
Eric Laurenta553c252009-07-17 12:17:14 -07004535{
4536 PlaybackThread *thread = NULL;
Eric Laurentddb78e72009-07-28 08:44:33 -07004537 if (mPlaybackThreads.indexOfKey(output) >= 0) {
4538 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
Eric Laurenta553c252009-07-17 12:17:14 -07004539 }
Eric Laurenta553c252009-07-17 12:17:14 -07004540 return thread;
4541}
4542
4543// checkMixerThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07004544AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
Eric Laurenta553c252009-07-17 12:17:14 -07004545{
4546 PlaybackThread *thread = checkPlaybackThread_l(output);
4547 if (thread != NULL) {
4548 if (thread->type() == PlaybackThread::DIRECT) {
4549 thread = NULL;
4550 }
4551 }
4552 return (MixerThread *)thread;
4553}
4554
4555// checkRecordThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07004556AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
Eric Laurenta553c252009-07-17 12:17:14 -07004557{
4558 RecordThread *thread = NULL;
Eric Laurentddb78e72009-07-28 08:44:33 -07004559 if (mRecordThreads.indexOfKey(input) >= 0) {
4560 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
Eric Laurenta553c252009-07-17 12:17:14 -07004561 }
Eric Laurenta553c252009-07-17 12:17:14 -07004562 return thread;
4563}
4564
Eric Laurentf3d6dd02010-11-18 08:40:16 -08004565// nextUniqueId_l() must be called with AudioFlinger::mLock held
4566int AudioFlinger::nextUniqueId_l()
Eric Laurent65b65452010-06-01 23:49:17 -07004567{
Eric Laurentf3d6dd02010-11-18 08:40:16 -08004568 return mNextUniqueId++;
Eric Laurent65b65452010-06-01 23:49:17 -07004569}
4570
4571// ----------------------------------------------------------------------------
4572// Effect management
4573// ----------------------------------------------------------------------------
4574
4575
4576status_t AudioFlinger::loadEffectLibrary(const char *libPath, int *handle)
4577{
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004578 // check calling permissions
4579 if (!settingsAllowed()) {
4580 return PERMISSION_DENIED;
4581 }
4582 // only allow libraries loaded from /system/lib/soundfx for now
4583 if (strncmp(gEffectLibPath, libPath, strlen(gEffectLibPath)) != 0) {
4584 return PERMISSION_DENIED;
4585 }
4586
Eric Laurent65b65452010-06-01 23:49:17 -07004587 Mutex::Autolock _l(mLock);
4588 return EffectLoadLibrary(libPath, handle);
4589}
4590
4591status_t AudioFlinger::unloadEffectLibrary(int handle)
4592{
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004593 // check calling permissions
4594 if (!settingsAllowed()) {
4595 return PERMISSION_DENIED;
4596 }
4597
Eric Laurent65b65452010-06-01 23:49:17 -07004598 Mutex::Autolock _l(mLock);
4599 return EffectUnloadLibrary(handle);
4600}
4601
4602status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects)
4603{
4604 Mutex::Autolock _l(mLock);
4605 return EffectQueryNumberEffects(numEffects);
4606}
4607
Eric Laurent53334cd2010-06-23 17:38:20 -07004608status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor)
Eric Laurent65b65452010-06-01 23:49:17 -07004609{
4610 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07004611 return EffectQueryEffect(index, descriptor);
Eric Laurent65b65452010-06-01 23:49:17 -07004612}
4613
4614status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid, effect_descriptor_t *descriptor)
4615{
4616 Mutex::Autolock _l(mLock);
4617 return EffectGetDescriptor(pUuid, descriptor);
4618}
4619
Eric Laurentdf9b81c2010-07-02 08:12:41 -07004620
4621// this UUID must match the one defined in media/libeffects/EffectVisualizer.cpp
4622static const effect_uuid_t VISUALIZATION_UUID_ =
4623 {0xd069d9e0, 0x8329, 0x11df, 0x9168, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}};
4624
Eric Laurent65b65452010-06-01 23:49:17 -07004625sp<IEffect> AudioFlinger::createEffect(pid_t pid,
4626 effect_descriptor_t *pDesc,
4627 const sp<IEffectClient>& effectClient,
4628 int32_t priority,
4629 int output,
4630 int sessionId,
4631 status_t *status,
4632 int *id,
4633 int *enabled)
4634{
4635 status_t lStatus = NO_ERROR;
4636 sp<EffectHandle> handle;
4637 effect_interface_t itfe;
4638 effect_descriptor_t desc;
4639 sp<Client> client;
4640 wp<Client> wclient;
4641
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004642 LOGV("createEffect pid %d, client %p, priority %d, sessionId %d, output %d",
4643 pid, effectClient.get(), priority, sessionId, output);
Eric Laurent65b65452010-06-01 23:49:17 -07004644
4645 if (pDesc == NULL) {
4646 lStatus = BAD_VALUE;
4647 goto Exit;
4648 }
4649
Eric Laurent98c92592010-09-23 16:10:16 -07004650 // check audio settings permission for global effects
4651 if (sessionId == AudioSystem::SESSION_OUTPUT_MIX && !settingsAllowed()) {
4652 lStatus = PERMISSION_DENIED;
4653 goto Exit;
4654 }
4655
4656 // Session AudioSystem::SESSION_OUTPUT_STAGE is reserved for output stage effects
4657 // that can only be created by audio policy manager (running in same process)
4658 if (sessionId == AudioSystem::SESSION_OUTPUT_STAGE && getpid() != pid) {
4659 lStatus = PERMISSION_DENIED;
4660 goto Exit;
4661 }
4662
4663 // check recording permission for visualizer
4664 if ((memcmp(&pDesc->type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0 ||
4665 memcmp(&pDesc->uuid, &VISUALIZATION_UUID_, sizeof(effect_uuid_t)) == 0) &&
4666 !recordingAllowed()) {
4667 lStatus = PERMISSION_DENIED;
4668 goto Exit;
4669 }
4670
4671 if (output == 0) {
4672 if (sessionId == AudioSystem::SESSION_OUTPUT_STAGE) {
4673 // output must be specified by AudioPolicyManager when using session
4674 // AudioSystem::SESSION_OUTPUT_STAGE
4675 lStatus = BAD_VALUE;
4676 goto Exit;
4677 } else if (sessionId == AudioSystem::SESSION_OUTPUT_MIX) {
4678 // if the output returned by getOutputForEffect() is removed before we lock the
4679 // mutex below, the call to checkPlaybackThread_l(output) below will detect it
4680 // and we will exit safely
4681 output = AudioSystem::getOutputForEffect(&desc);
4682 }
4683 }
4684
Eric Laurent65b65452010-06-01 23:49:17 -07004685 {
4686 Mutex::Autolock _l(mLock);
4687
Eric Laurentdf9b81c2010-07-02 08:12:41 -07004688
Eric Laurent65b65452010-06-01 23:49:17 -07004689 if (!EffectIsNullUuid(&pDesc->uuid)) {
4690 // if uuid is specified, request effect descriptor
4691 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
4692 if (lStatus < 0) {
4693 LOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
4694 goto Exit;
4695 }
4696 } else {
4697 // if uuid is not specified, look for an available implementation
4698 // of the required type in effect factory
4699 if (EffectIsNullUuid(&pDesc->type)) {
4700 LOGW("createEffect() no effect type");
4701 lStatus = BAD_VALUE;
4702 goto Exit;
4703 }
4704 uint32_t numEffects = 0;
4705 effect_descriptor_t d;
4706 bool found = false;
4707
4708 lStatus = EffectQueryNumberEffects(&numEffects);
4709 if (lStatus < 0) {
4710 LOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
4711 goto Exit;
4712 }
Eric Laurent53334cd2010-06-23 17:38:20 -07004713 for (uint32_t i = 0; i < numEffects; i++) {
4714 lStatus = EffectQueryEffect(i, &desc);
Eric Laurent65b65452010-06-01 23:49:17 -07004715 if (lStatus < 0) {
Eric Laurent53334cd2010-06-23 17:38:20 -07004716 LOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07004717 continue;
4718 }
4719 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
4720 // If matching type found save effect descriptor. If the session is
4721 // 0 and the effect is not auxiliary, continue enumeration in case
4722 // an auxiliary version of this effect type is available
4723 found = true;
4724 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004725 if (sessionId != AudioSystem::SESSION_OUTPUT_MIX ||
Eric Laurent65b65452010-06-01 23:49:17 -07004726 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
4727 break;
4728 }
4729 }
4730 }
4731 if (!found) {
4732 lStatus = BAD_VALUE;
4733 LOGW("createEffect() effect not found");
4734 goto Exit;
4735 }
4736 // For same effect type, chose auxiliary version over insert version if
4737 // connect to output mix (Compliance to OpenSL ES)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004738 if (sessionId == AudioSystem::SESSION_OUTPUT_MIX &&
Eric Laurent65b65452010-06-01 23:49:17 -07004739 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
4740 memcpy(&desc, &d, sizeof(effect_descriptor_t));
4741 }
4742 }
4743
4744 // Do not allow auxiliary effects on a session different from 0 (output mix)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004745 if (sessionId != AudioSystem::SESSION_OUTPUT_MIX &&
Eric Laurent65b65452010-06-01 23:49:17 -07004746 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
4747 lStatus = INVALID_OPERATION;
4748 goto Exit;
4749 }
4750
4751 // return effect descriptor
4752 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
4753
4754 // If output is not specified try to find a matching audio session ID in one of the
4755 // output threads.
Eric Laurent98c92592010-09-23 16:10:16 -07004756 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
4757 // because of code checking output when entering the function.
Eric Laurent65b65452010-06-01 23:49:17 -07004758 if (output == 0) {
Eric Laurent98c92592010-09-23 16:10:16 -07004759 // look for the thread where the specified audio session is present
4760 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
4761 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
4762 output = mPlaybackThreads.keyAt(i);
4763 break;
Eric Laurent493941b2010-07-28 01:32:47 -07004764 }
Eric Laurent65b65452010-06-01 23:49:17 -07004765 }
Eric Laurent98c92592010-09-23 16:10:16 -07004766 // If no output thread contains the requested session ID, default to
4767 // first output. The effect chain will be moved to the correct output
4768 // thread when a track with the same session ID is created
4769 if (output == 0 && mPlaybackThreads.size()) {
4770 output = mPlaybackThreads.keyAt(0);
4771 }
Eric Laurent65b65452010-06-01 23:49:17 -07004772 }
Eric Laurent98c92592010-09-23 16:10:16 -07004773 LOGV("createEffect() got output %d for effect %s", output, desc.name);
Eric Laurent65b65452010-06-01 23:49:17 -07004774 PlaybackThread *thread = checkPlaybackThread_l(output);
4775 if (thread == NULL) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004776 LOGE("createEffect() unknown output thread");
Eric Laurent65b65452010-06-01 23:49:17 -07004777 lStatus = BAD_VALUE;
4778 goto Exit;
4779 }
4780
Eric Laurent98c92592010-09-23 16:10:16 -07004781 // TODO: allow attachment of effect to inputs
4782
Eric Laurent65b65452010-06-01 23:49:17 -07004783 wclient = mClients.valueFor(pid);
4784
4785 if (wclient != NULL) {
4786 client = wclient.promote();
4787 } else {
4788 client = new Client(this, pid);
4789 mClients.add(pid, client);
4790 }
4791
4792 // create effect on selected output trhead
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004793 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
4794 &desc, enabled, &lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07004795 if (handle != 0 && id != NULL) {
4796 *id = handle->id();
4797 }
4798 }
4799
4800Exit:
4801 if(status) {
4802 *status = lStatus;
4803 }
4804 return handle;
4805}
4806
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004807status_t AudioFlinger::moveEffects(int session, int srcOutput, int dstOutput)
4808{
4809 LOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
4810 session, srcOutput, dstOutput);
4811 Mutex::Autolock _l(mLock);
4812 if (srcOutput == dstOutput) {
4813 LOGW("moveEffects() same dst and src outputs %d", dstOutput);
4814 return NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07004815 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004816 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
4817 if (srcThread == NULL) {
4818 LOGW("moveEffects() bad srcOutput %d", srcOutput);
4819 return BAD_VALUE;
Eric Laurent53334cd2010-06-23 17:38:20 -07004820 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004821 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
4822 if (dstThread == NULL) {
4823 LOGW("moveEffects() bad dstOutput %d", dstOutput);
4824 return BAD_VALUE;
4825 }
4826
4827 Mutex::Autolock _dl(dstThread->mLock);
4828 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent493941b2010-07-28 01:32:47 -07004829 moveEffectChain_l(session, srcThread, dstThread, false);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004830
Eric Laurent53334cd2010-06-23 17:38:20 -07004831 return NO_ERROR;
4832}
4833
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004834// moveEffectChain_l mustbe called with both srcThread and dstThread mLocks held
4835status_t AudioFlinger::moveEffectChain_l(int session,
4836 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent493941b2010-07-28 01:32:47 -07004837 AudioFlinger::PlaybackThread *dstThread,
4838 bool reRegister)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004839{
4840 LOGV("moveEffectChain_l() session %d from thread %p to thread %p",
4841 session, srcThread, dstThread);
4842
4843 sp<EffectChain> chain = srcThread->getEffectChain_l(session);
4844 if (chain == 0) {
4845 LOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
4846 session, srcThread);
4847 return INVALID_OPERATION;
4848 }
4849
Eric Laurent493941b2010-07-28 01:32:47 -07004850 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004851 // so that a new chain is created with correct parameters when first effect is added. This is
4852 // otherwise unecessary as removeEffect_l() will remove the chain when last effect is
4853 // removed.
4854 srcThread->removeEffectChain_l(chain);
4855
4856 // transfer all effects one by one so that new effect chain is created on new thread with
4857 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent493941b2010-07-28 01:32:47 -07004858 int dstOutput = dstThread->id();
4859 sp<EffectChain> dstChain;
4860 uint32_t strategy;
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004861 sp<EffectModule> effect = chain->getEffectFromId_l(0);
4862 while (effect != 0) {
4863 srcThread->removeEffect_l(effect);
4864 dstThread->addEffect_l(effect);
Eric Laurent493941b2010-07-28 01:32:47 -07004865 // if the move request is not received from audio policy manager, the effect must be
4866 // re-registered with the new strategy and output
4867 if (dstChain == 0) {
4868 dstChain = effect->chain().promote();
4869 if (dstChain == 0) {
4870 LOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
4871 srcThread->addEffect_l(effect);
4872 return NO_INIT;
4873 }
4874 strategy = dstChain->strategy();
4875 }
4876 if (reRegister) {
4877 AudioSystem::unregisterEffect(effect->id());
4878 AudioSystem::registerEffect(&effect->desc(),
4879 dstOutput,
4880 strategy,
4881 session,
4882 effect->id());
4883 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004884 effect = chain->getEffectFromId_l(0);
4885 }
4886
4887 return NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07004888}
4889
Eric Laurent65b65452010-06-01 23:49:17 -07004890// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
4891sp<AudioFlinger::EffectHandle> AudioFlinger::PlaybackThread::createEffect_l(
4892 const sp<AudioFlinger::Client>& client,
4893 const sp<IEffectClient>& effectClient,
4894 int32_t priority,
4895 int sessionId,
4896 effect_descriptor_t *desc,
4897 int *enabled,
4898 status_t *status
4899 )
4900{
4901 sp<EffectModule> effect;
4902 sp<EffectHandle> handle;
4903 status_t lStatus;
4904 sp<Track> track;
4905 sp<EffectChain> chain;
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004906 bool chainCreated = false;
Eric Laurent65b65452010-06-01 23:49:17 -07004907 bool effectCreated = false;
Eric Laurent53334cd2010-06-23 17:38:20 -07004908 bool effectRegistered = false;
Eric Laurent65b65452010-06-01 23:49:17 -07004909
4910 if (mOutput == 0) {
4911 LOGW("createEffect_l() Audio driver not initialized.");
4912 lStatus = NO_INIT;
4913 goto Exit;
4914 }
4915
4916 // Do not allow auxiliary effect on session other than 0
4917 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY &&
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004918 sessionId != AudioSystem::SESSION_OUTPUT_MIX) {
4919 LOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
4920 desc->name, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07004921 lStatus = BAD_VALUE;
4922 goto Exit;
4923 }
4924
4925 // Do not allow effects with session ID 0 on direct output or duplicating threads
4926 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004927 if (sessionId == AudioSystem::SESSION_OUTPUT_MIX && mType != MIXER) {
4928 LOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
4929 desc->name, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07004930 lStatus = BAD_VALUE;
4931 goto Exit;
4932 }
4933
4934 LOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
4935
4936 { // scope for mLock
4937 Mutex::Autolock _l(mLock);
4938
4939 // check for existing effect chain with the requested audio session
4940 chain = getEffectChain_l(sessionId);
4941 if (chain == 0) {
4942 // create a new chain for this session
4943 LOGV("createEffect_l() new effect chain for session %d", sessionId);
4944 chain = new EffectChain(this, sessionId);
4945 addEffectChain_l(chain);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004946 chain->setStrategy(getStrategyForSession_l(sessionId));
4947 chainCreated = true;
Eric Laurent65b65452010-06-01 23:49:17 -07004948 } else {
Eric Laurent76c40f72010-07-15 12:50:15 -07004949 effect = chain->getEffectFromDesc_l(desc);
Eric Laurent65b65452010-06-01 23:49:17 -07004950 }
4951
4952 LOGV("createEffect_l() got effect %p on chain %p", effect == 0 ? 0 : effect.get(), chain.get());
4953
4954 if (effect == 0) {
Eric Laurentf3d6dd02010-11-18 08:40:16 -08004955 int id = mAudioFlinger->nextUniqueId_l();
Eric Laurent53334cd2010-06-23 17:38:20 -07004956 // Check CPU and memory usage
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004957 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Eric Laurent53334cd2010-06-23 17:38:20 -07004958 if (lStatus != NO_ERROR) {
4959 goto Exit;
4960 }
4961 effectRegistered = true;
Eric Laurent65b65452010-06-01 23:49:17 -07004962 // create a new effect module if none present in the chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004963 effect = new EffectModule(this, chain, desc, id, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07004964 lStatus = effect->status();
4965 if (lStatus != NO_ERROR) {
4966 goto Exit;
4967 }
Eric Laurent76c40f72010-07-15 12:50:15 -07004968 lStatus = chain->addEffect_l(effect);
Eric Laurent65b65452010-06-01 23:49:17 -07004969 if (lStatus != NO_ERROR) {
4970 goto Exit;
4971 }
Eric Laurent53334cd2010-06-23 17:38:20 -07004972 effectCreated = true;
Eric Laurent65b65452010-06-01 23:49:17 -07004973
4974 effect->setDevice(mDevice);
Eric Laurent53334cd2010-06-23 17:38:20 -07004975 effect->setMode(mAudioFlinger->getMode());
Eric Laurent65b65452010-06-01 23:49:17 -07004976 }
4977 // create effect handle and connect it to effect module
4978 handle = new EffectHandle(effect, client, effectClient, priority);
4979 lStatus = effect->addHandle(handle);
4980 if (enabled) {
4981 *enabled = (int)effect->isEnabled();
4982 }
4983 }
4984
4985Exit:
4986 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004987 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07004988 if (effectCreated) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004989 chain->removeEffect_l(effect);
Eric Laurent65b65452010-06-01 23:49:17 -07004990 }
Eric Laurent53334cd2010-06-23 17:38:20 -07004991 if (effectRegistered) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004992 AudioSystem::unregisterEffect(effect->id());
4993 }
4994 if (chainCreated) {
4995 removeEffectChain_l(chain);
Eric Laurent53334cd2010-06-23 17:38:20 -07004996 }
Eric Laurent65b65452010-06-01 23:49:17 -07004997 handle.clear();
4998 }
4999
5000 if(status) {
5001 *status = lStatus;
5002 }
5003 return handle;
5004}
5005
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005006// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5007// PlaybackThread::mLock held
5008status_t AudioFlinger::PlaybackThread::addEffect_l(const sp<EffectModule>& effect)
5009{
5010 // check for existing effect chain with the requested audio session
5011 int sessionId = effect->sessionId();
5012 sp<EffectChain> chain = getEffectChain_l(sessionId);
5013 bool chainCreated = false;
5014
5015 if (chain == 0) {
5016 // create a new chain for this session
5017 LOGV("addEffect_l() new effect chain for session %d", sessionId);
5018 chain = new EffectChain(this, sessionId);
5019 addEffectChain_l(chain);
5020 chain->setStrategy(getStrategyForSession_l(sessionId));
5021 chainCreated = true;
5022 }
5023 LOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
5024
5025 if (chain->getEffectFromId_l(effect->id()) != 0) {
5026 LOGW("addEffect_l() %p effect %s already present in chain %p",
5027 this, effect->desc().name, chain.get());
5028 return BAD_VALUE;
5029 }
5030
5031 status_t status = chain->addEffect_l(effect);
5032 if (status != NO_ERROR) {
5033 if (chainCreated) {
5034 removeEffectChain_l(chain);
5035 }
5036 return status;
5037 }
5038
5039 effect->setDevice(mDevice);
5040 effect->setMode(mAudioFlinger->getMode());
5041 return NO_ERROR;
5042}
5043
5044void AudioFlinger::PlaybackThread::removeEffect_l(const sp<EffectModule>& effect) {
5045
5046 LOGV("removeEffect_l() %p effect %p", this, effect.get());
Eric Laurent53334cd2010-06-23 17:38:20 -07005047 effect_descriptor_t desc = effect->desc();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005048 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5049 detachAuxEffect_l(effect->id());
5050 }
5051
5052 sp<EffectChain> chain = effect->chain().promote();
5053 if (chain != 0) {
5054 // remove effect chain if removing last effect
5055 if (chain->removeEffect_l(effect) == 0) {
5056 removeEffectChain_l(chain);
5057 }
5058 } else {
5059 LOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
5060 }
5061}
5062
5063void AudioFlinger::PlaybackThread::disconnectEffect(const sp<EffectModule>& effect,
5064 const wp<EffectHandle>& handle) {
Eric Laurent53334cd2010-06-23 17:38:20 -07005065 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005066 LOGV("disconnectEffect() %p effect %p", this, effect.get());
Eric Laurent53334cd2010-06-23 17:38:20 -07005067 // delete the effect module if removing last handle on it
5068 if (effect->removeHandle(handle) == 0) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005069 removeEffect_l(effect);
5070 AudioSystem::unregisterEffect(effect->id());
Eric Laurent53334cd2010-06-23 17:38:20 -07005071 }
5072}
5073
Eric Laurent65b65452010-06-01 23:49:17 -07005074status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5075{
5076 int session = chain->sessionId();
5077 int16_t *buffer = mMixBuffer;
Eric Laurent53334cd2010-06-23 17:38:20 -07005078 bool ownsBuffer = false;
Eric Laurent65b65452010-06-01 23:49:17 -07005079
5080 LOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Eric Laurent53334cd2010-06-23 17:38:20 -07005081 if (session > 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07005082 // Only one effect chain can be present in direct output thread and it uses
5083 // the mix buffer as input
5084 if (mType != DIRECT) {
5085 size_t numSamples = mFrameCount * mChannelCount;
5086 buffer = new int16_t[numSamples];
5087 memset(buffer, 0, numSamples * sizeof(int16_t));
5088 LOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
5089 ownsBuffer = true;
5090 }
Eric Laurent65b65452010-06-01 23:49:17 -07005091
Eric Laurent53334cd2010-06-23 17:38:20 -07005092 // Attach all tracks with same session ID to this chain.
5093 for (size_t i = 0; i < mTracks.size(); ++i) {
5094 sp<Track> track = mTracks[i];
5095 if (session == track->sessionId()) {
5096 LOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
5097 track->setMainBuffer(buffer);
5098 }
5099 }
5100
5101 // indicate all active tracks in the chain
5102 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5103 sp<Track> track = mActiveTracks[i].promote();
5104 if (track == 0) continue;
5105 if (session == track->sessionId()) {
5106 LOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
5107 chain->startTrack();
5108 }
Eric Laurent65b65452010-06-01 23:49:17 -07005109 }
5110 }
5111
Eric Laurent53334cd2010-06-23 17:38:20 -07005112 chain->setInBuffer(buffer, ownsBuffer);
5113 chain->setOutBuffer(mMixBuffer);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005114 // Effect chain for session AudioSystem::SESSION_OUTPUT_STAGE is inserted at end of effect
5115 // chains list in order to be processed last as it contains output stage effects
5116 // Effect chain for session AudioSystem::SESSION_OUTPUT_MIX is inserted before
5117 // session AudioSystem::SESSION_OUTPUT_STAGE to be processed
Eric Laurent53334cd2010-06-23 17:38:20 -07005118 // after track specific effects and before output stage
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005119 // It is therefore mandatory that AudioSystem::SESSION_OUTPUT_MIX == 0 and
5120 // that AudioSystem::SESSION_OUTPUT_STAGE < AudioSystem::SESSION_OUTPUT_MIX
5121 // Effect chain for other sessions are inserted at beginning of effect
5122 // chains list to be processed before output mix effects. Relative order between other
5123 // sessions is not important
Eric Laurent53334cd2010-06-23 17:38:20 -07005124 size_t size = mEffectChains.size();
5125 size_t i = 0;
5126 for (i = 0; i < size; i++) {
5127 if (mEffectChains[i]->sessionId() < session) break;
Eric Laurent65b65452010-06-01 23:49:17 -07005128 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005129 mEffectChains.insertAt(chain, i);
Eric Laurent65b65452010-06-01 23:49:17 -07005130
5131 return NO_ERROR;
5132}
5133
5134size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
5135{
5136 int session = chain->sessionId();
5137
5138 LOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
5139
5140 for (size_t i = 0; i < mEffectChains.size(); i++) {
5141 if (chain == mEffectChains[i]) {
5142 mEffectChains.removeAt(i);
5143 // detach all tracks with same session ID from this chain
5144 for (size_t i = 0; i < mTracks.size(); ++i) {
5145 sp<Track> track = mTracks[i];
5146 if (session == track->sessionId()) {
5147 track->setMainBuffer(mMixBuffer);
5148 }
5149 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005150 break;
Eric Laurent65b65452010-06-01 23:49:17 -07005151 }
5152 }
5153 return mEffectChains.size();
5154}
5155
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005156void AudioFlinger::PlaybackThread::lockEffectChains_l(
5157 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
Eric Laurent65b65452010-06-01 23:49:17 -07005158{
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005159 effectChains = mEffectChains;
Eric Laurent65b65452010-06-01 23:49:17 -07005160 for (size_t i = 0; i < mEffectChains.size(); i++) {
5161 mEffectChains[i]->lock();
5162 }
5163}
5164
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005165void AudioFlinger::PlaybackThread::unlockEffectChains(
5166 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
Eric Laurent65b65452010-06-01 23:49:17 -07005167{
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005168 for (size_t i = 0; i < effectChains.size(); i++) {
5169 effectChains[i]->unlock();
Eric Laurent65b65452010-06-01 23:49:17 -07005170 }
5171}
5172
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005173
Eric Laurent65b65452010-06-01 23:49:17 -07005174sp<AudioFlinger::EffectModule> AudioFlinger::PlaybackThread::getEffect_l(int sessionId, int effectId)
5175{
5176 sp<EffectModule> effect;
5177
5178 sp<EffectChain> chain = getEffectChain_l(sessionId);
5179 if (chain != 0) {
Eric Laurent76c40f72010-07-15 12:50:15 -07005180 effect = chain->getEffectFromId_l(effectId);
Eric Laurent65b65452010-06-01 23:49:17 -07005181 }
5182 return effect;
5183}
5184
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005185status_t AudioFlinger::PlaybackThread::attachAuxEffect(
5186 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Eric Laurent65b65452010-06-01 23:49:17 -07005187{
5188 Mutex::Autolock _l(mLock);
5189 return attachAuxEffect_l(track, EffectId);
5190}
5191
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005192status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
5193 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Eric Laurent65b65452010-06-01 23:49:17 -07005194{
5195 status_t status = NO_ERROR;
5196
5197 if (EffectId == 0) {
5198 track->setAuxBuffer(0, NULL);
5199 } else {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005200 // Auxiliary effects are always in audio session AudioSystem::SESSION_OUTPUT_MIX
5201 sp<EffectModule> effect = getEffect_l(AudioSystem::SESSION_OUTPUT_MIX, EffectId);
Eric Laurent65b65452010-06-01 23:49:17 -07005202 if (effect != 0) {
5203 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5204 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
5205 } else {
5206 status = INVALID_OPERATION;
5207 }
5208 } else {
5209 status = BAD_VALUE;
5210 }
5211 }
5212 return status;
5213}
5214
5215void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
5216{
5217 for (size_t i = 0; i < mTracks.size(); ++i) {
5218 sp<Track> track = mTracks[i];
5219 if (track->auxEffectId() == effectId) {
5220 attachAuxEffect_l(track, 0);
5221 }
5222 }
5223}
5224
5225// ----------------------------------------------------------------------------
5226// EffectModule implementation
5227// ----------------------------------------------------------------------------
5228
5229#undef LOG_TAG
5230#define LOG_TAG "AudioFlinger::EffectModule"
5231
5232AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
5233 const wp<AudioFlinger::EffectChain>& chain,
5234 effect_descriptor_t *desc,
5235 int id,
5236 int sessionId)
5237 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
5238 mStatus(NO_INIT), mState(IDLE)
5239{
5240 LOGV("Constructor %p", this);
5241 int lStatus;
5242 sp<ThreadBase> thread = mThread.promote();
5243 if (thread == 0) {
5244 return;
5245 }
5246 PlaybackThread *p = (PlaybackThread *)thread.get();
5247
5248 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
5249
5250 // create effect engine from effect factory
Eric Laurent53334cd2010-06-23 17:38:20 -07005251 mStatus = EffectCreate(&desc->uuid, sessionId, p->id(), &mEffectInterface);
5252
Eric Laurent65b65452010-06-01 23:49:17 -07005253 if (mStatus != NO_ERROR) {
5254 return;
5255 }
5256 lStatus = init();
5257 if (lStatus < 0) {
5258 mStatus = lStatus;
5259 goto Error;
5260 }
5261
5262 LOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
5263 return;
5264Error:
5265 EffectRelease(mEffectInterface);
5266 mEffectInterface = NULL;
5267 LOGV("Constructor Error %d", mStatus);
5268}
5269
5270AudioFlinger::EffectModule::~EffectModule()
5271{
5272 LOGV("Destructor %p", this);
5273 if (mEffectInterface != NULL) {
5274 // release effect engine
5275 EffectRelease(mEffectInterface);
5276 }
5277}
5278
5279status_t AudioFlinger::EffectModule::addHandle(sp<EffectHandle>& handle)
5280{
5281 status_t status;
5282
5283 Mutex::Autolock _l(mLock);
5284 // First handle in mHandles has highest priority and controls the effect module
5285 int priority = handle->priority();
5286 size_t size = mHandles.size();
5287 sp<EffectHandle> h;
5288 size_t i;
5289 for (i = 0; i < size; i++) {
5290 h = mHandles[i].promote();
5291 if (h == 0) continue;
5292 if (h->priority() <= priority) break;
5293 }
5294 // if inserted in first place, move effect control from previous owner to this handle
5295 if (i == 0) {
5296 if (h != 0) {
5297 h->setControl(false, true);
5298 }
5299 handle->setControl(true, false);
5300 status = NO_ERROR;
5301 } else {
5302 status = ALREADY_EXISTS;
5303 }
5304 mHandles.insertAt(handle, i);
5305 return status;
5306}
5307
5308size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
5309{
5310 Mutex::Autolock _l(mLock);
5311 size_t size = mHandles.size();
5312 size_t i;
5313 for (i = 0; i < size; i++) {
5314 if (mHandles[i] == handle) break;
5315 }
5316 if (i == size) {
5317 return size;
5318 }
5319 mHandles.removeAt(i);
5320 size = mHandles.size();
5321 // if removed from first place, move effect control from this handle to next in line
5322 if (i == 0 && size != 0) {
5323 sp<EffectHandle> h = mHandles[0].promote();
5324 if (h != 0) {
5325 h->setControl(true, true);
5326 }
5327 }
5328
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07005329 // Release effect engine here so that it is done immediately. Otherwise it will be released
5330 // by the destructor when the last strong reference on the this object is released which can
5331 // happen after next process is called on this effect.
5332 if (size == 0 && mEffectInterface != NULL) {
5333 // release effect engine
5334 EffectRelease(mEffectInterface);
5335 mEffectInterface = NULL;
5336 }
5337
Eric Laurent65b65452010-06-01 23:49:17 -07005338 return size;
5339}
5340
5341void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle)
5342{
5343 // keep a strong reference on this EffectModule to avoid calling the
5344 // destructor before we exit
5345 sp<EffectModule> keep(this);
Eric Laurent53334cd2010-06-23 17:38:20 -07005346 {
5347 sp<ThreadBase> thread = mThread.promote();
5348 if (thread != 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07005349 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurent53334cd2010-06-23 17:38:20 -07005350 playbackThread->disconnectEffect(keep, handle);
Eric Laurent65b65452010-06-01 23:49:17 -07005351 }
5352 }
5353}
5354
Eric Laurent7d850f22010-07-09 13:34:17 -07005355void AudioFlinger::EffectModule::updateState() {
5356 Mutex::Autolock _l(mLock);
5357
5358 switch (mState) {
5359 case RESTART:
5360 reset_l();
5361 // FALL THROUGH
5362
5363 case STARTING:
5364 // clear auxiliary effect input buffer for next accumulation
5365 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5366 memset(mConfig.inputCfg.buffer.raw,
5367 0,
5368 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
5369 }
5370 start_l();
5371 mState = ACTIVE;
5372 break;
5373 case STOPPING:
5374 stop_l();
5375 mDisableWaitCnt = mMaxDisableWaitCnt;
5376 mState = STOPPED;
5377 break;
5378 case STOPPED:
5379 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
5380 // turn off sequence.
5381 if (--mDisableWaitCnt == 0) {
5382 reset_l();
5383 mState = IDLE;
5384 }
5385 break;
5386 default: //IDLE , ACTIVE
5387 break;
5388 }
5389}
5390
Eric Laurent65b65452010-06-01 23:49:17 -07005391void AudioFlinger::EffectModule::process()
5392{
5393 Mutex::Autolock _l(mLock);
5394
Eric Laurent7d850f22010-07-09 13:34:17 -07005395 if (mEffectInterface == NULL ||
5396 mConfig.inputCfg.buffer.raw == NULL ||
5397 mConfig.outputCfg.buffer.raw == NULL) {
Eric Laurent65b65452010-06-01 23:49:17 -07005398 return;
5399 }
5400
Eric Laurenta92ebfa2010-08-31 13:50:07 -07005401 if (isProcessEnabled()) {
Eric Laurent65b65452010-06-01 23:49:17 -07005402 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
5403 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5404 AudioMixer::ditherAndClamp(mConfig.inputCfg.buffer.s32,
5405 mConfig.inputCfg.buffer.s32,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005406 mConfig.inputCfg.buffer.frameCount/2);
Eric Laurent65b65452010-06-01 23:49:17 -07005407 }
5408
Eric Laurent65b65452010-06-01 23:49:17 -07005409 // do the actual processing in the effect engine
Eric Laurent7d850f22010-07-09 13:34:17 -07005410 int ret = (*mEffectInterface)->process(mEffectInterface,
5411 &mConfig.inputCfg.buffer,
5412 &mConfig.outputCfg.buffer);
5413
5414 // force transition to IDLE state when engine is ready
5415 if (mState == STOPPED && ret == -ENODATA) {
5416 mDisableWaitCnt = 1;
5417 }
Eric Laurent65b65452010-06-01 23:49:17 -07005418
5419 // clear auxiliary effect input buffer for next accumulation
5420 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent67b5ed32011-01-19 18:36:13 -08005421 memset(mConfig.inputCfg.buffer.raw, 0,
5422 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Eric Laurent65b65452010-06-01 23:49:17 -07005423 }
5424 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent67b5ed32011-01-19 18:36:13 -08005425 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
5426 // If an insert effect is idle and input buffer is different from output buffer,
5427 // accumulate input onto output
Eric Laurent65b65452010-06-01 23:49:17 -07005428 sp<EffectChain> chain = mChain.promote();
5429 if (chain != 0 && chain->activeTracks() != 0) {
Eric Laurent67b5ed32011-01-19 18:36:13 -08005430 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
5431 int16_t *in = mConfig.inputCfg.buffer.s16;
5432 int16_t *out = mConfig.outputCfg.buffer.s16;
5433 for (size_t i = 0; i < frameCnt; i++) {
5434 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Eric Laurent65b65452010-06-01 23:49:17 -07005435 }
Eric Laurent65b65452010-06-01 23:49:17 -07005436 }
5437 }
5438}
5439
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005440void AudioFlinger::EffectModule::reset_l()
Eric Laurent65b65452010-06-01 23:49:17 -07005441{
5442 if (mEffectInterface == NULL) {
5443 return;
5444 }
5445 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
5446}
5447
5448status_t AudioFlinger::EffectModule::configure()
5449{
5450 uint32_t channels;
5451 if (mEffectInterface == NULL) {
5452 return NO_INIT;
5453 }
5454
5455 sp<ThreadBase> thread = mThread.promote();
5456 if (thread == 0) {
5457 return DEAD_OBJECT;
5458 }
5459
5460 // TODO: handle configuration of effects replacing track process
5461 if (thread->channelCount() == 1) {
5462 channels = CHANNEL_MONO;
5463 } else {
5464 channels = CHANNEL_STEREO;
5465 }
5466
5467 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5468 mConfig.inputCfg.channels = CHANNEL_MONO;
5469 } else {
5470 mConfig.inputCfg.channels = channels;
5471 }
5472 mConfig.outputCfg.channels = channels;
Eric Laurent53334cd2010-06-23 17:38:20 -07005473 mConfig.inputCfg.format = SAMPLE_FORMAT_PCM_S15;
5474 mConfig.outputCfg.format = SAMPLE_FORMAT_PCM_S15;
Eric Laurent65b65452010-06-01 23:49:17 -07005475 mConfig.inputCfg.samplingRate = thread->sampleRate();
5476 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
5477 mConfig.inputCfg.bufferProvider.cookie = NULL;
5478 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
5479 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
5480 mConfig.outputCfg.bufferProvider.cookie = NULL;
5481 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
5482 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
5483 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
5484 // Insert effect:
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005485 // - in session AudioSystem::SESSION_OUTPUT_MIX or AudioSystem::SESSION_OUTPUT_STAGE,
5486 // always overwrites output buffer: input buffer == output buffer
Eric Laurent65b65452010-06-01 23:49:17 -07005487 // - in other sessions:
5488 // last effect in the chain accumulates in output buffer: input buffer != output buffer
5489 // other effect: overwrites output buffer: input buffer == output buffer
5490 // Auxiliary effect:
5491 // accumulates in output buffer: input buffer != output buffer
5492 // Therefore: accumulate <=> input buffer != output buffer
5493 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
5494 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
5495 } else {
5496 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
5497 }
5498 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
5499 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
5500 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
5501 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
5502
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005503 LOGV("configure() %p thread %p buffer %p framecount %d",
5504 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
5505
Eric Laurent65b65452010-06-01 23:49:17 -07005506 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005507 uint32_t size = sizeof(int);
5508 status_t status = (*mEffectInterface)->command(mEffectInterface,
5509 EFFECT_CMD_CONFIGURE,
5510 sizeof(effect_config_t),
5511 &mConfig,
5512 &size,
5513 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005514 if (status == 0) {
5515 status = cmdStatus;
5516 }
Eric Laurent7d850f22010-07-09 13:34:17 -07005517
5518 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
5519 (1000 * mConfig.outputCfg.buffer.frameCount);
5520
Eric Laurent65b65452010-06-01 23:49:17 -07005521 return status;
5522}
5523
5524status_t AudioFlinger::EffectModule::init()
5525{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005526 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07005527 if (mEffectInterface == NULL) {
5528 return NO_INIT;
5529 }
5530 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005531 uint32_t size = sizeof(status_t);
5532 status_t status = (*mEffectInterface)->command(mEffectInterface,
5533 EFFECT_CMD_INIT,
5534 0,
5535 NULL,
5536 &size,
5537 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005538 if (status == 0) {
5539 status = cmdStatus;
5540 }
5541 return status;
5542}
5543
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005544status_t AudioFlinger::EffectModule::start_l()
Eric Laurent65b65452010-06-01 23:49:17 -07005545{
5546 if (mEffectInterface == NULL) {
5547 return NO_INIT;
5548 }
5549 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005550 uint32_t size = sizeof(status_t);
5551 status_t status = (*mEffectInterface)->command(mEffectInterface,
5552 EFFECT_CMD_ENABLE,
5553 0,
5554 NULL,
5555 &size,
5556 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005557 if (status == 0) {
5558 status = cmdStatus;
5559 }
5560 return status;
5561}
5562
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005563status_t AudioFlinger::EffectModule::stop_l()
Eric Laurent65b65452010-06-01 23:49:17 -07005564{
5565 if (mEffectInterface == NULL) {
5566 return NO_INIT;
5567 }
5568 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005569 uint32_t size = sizeof(status_t);
5570 status_t status = (*mEffectInterface)->command(mEffectInterface,
5571 EFFECT_CMD_DISABLE,
5572 0,
5573 NULL,
5574 &size,
5575 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005576 if (status == 0) {
5577 status = cmdStatus;
5578 }
5579 return status;
5580}
5581
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005582status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
5583 uint32_t cmdSize,
5584 void *pCmdData,
5585 uint32_t *replySize,
5586 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07005587{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005588 Mutex::Autolock _l(mLock);
5589// LOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Eric Laurent65b65452010-06-01 23:49:17 -07005590
5591 if (mEffectInterface == NULL) {
5592 return NO_INIT;
5593 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005594 status_t status = (*mEffectInterface)->command(mEffectInterface,
5595 cmdCode,
5596 cmdSize,
5597 pCmdData,
5598 replySize,
5599 pReplyData);
Eric Laurent65b65452010-06-01 23:49:17 -07005600 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005601 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Eric Laurent65b65452010-06-01 23:49:17 -07005602 for (size_t i = 1; i < mHandles.size(); i++) {
5603 sp<EffectHandle> h = mHandles[i].promote();
5604 if (h != 0) {
5605 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
5606 }
5607 }
5608 }
5609 return status;
5610}
5611
5612status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
5613{
5614 Mutex::Autolock _l(mLock);
5615 LOGV("setEnabled %p enabled %d", this, enabled);
5616
5617 if (enabled != isEnabled()) {
5618 switch (mState) {
5619 // going from disabled to enabled
5620 case IDLE:
Eric Laurent7d850f22010-07-09 13:34:17 -07005621 mState = STARTING;
5622 break;
5623 case STOPPED:
5624 mState = RESTART;
Eric Laurent65b65452010-06-01 23:49:17 -07005625 break;
5626 case STOPPING:
5627 mState = ACTIVE;
5628 break;
Eric Laurent65b65452010-06-01 23:49:17 -07005629
5630 // going from enabled to disabled
Eric Laurent7d850f22010-07-09 13:34:17 -07005631 case RESTART:
Eric Laurenta92ebfa2010-08-31 13:50:07 -07005632 mState = STOPPED;
5633 break;
Eric Laurent65b65452010-06-01 23:49:17 -07005634 case STARTING:
Eric Laurent7d850f22010-07-09 13:34:17 -07005635 mState = IDLE;
Eric Laurent65b65452010-06-01 23:49:17 -07005636 break;
5637 case ACTIVE:
5638 mState = STOPPING;
5639 break;
5640 }
5641 for (size_t i = 1; i < mHandles.size(); i++) {
5642 sp<EffectHandle> h = mHandles[i].promote();
5643 if (h != 0) {
5644 h->setEnabled(enabled);
5645 }
5646 }
5647 }
5648 return NO_ERROR;
5649}
5650
5651bool AudioFlinger::EffectModule::isEnabled()
5652{
5653 switch (mState) {
Eric Laurent7d850f22010-07-09 13:34:17 -07005654 case RESTART:
Eric Laurent65b65452010-06-01 23:49:17 -07005655 case STARTING:
5656 case ACTIVE:
5657 return true;
5658 case IDLE:
5659 case STOPPING:
5660 case STOPPED:
5661 default:
5662 return false;
5663 }
5664}
5665
Eric Laurenta92ebfa2010-08-31 13:50:07 -07005666bool AudioFlinger::EffectModule::isProcessEnabled()
5667{
5668 switch (mState) {
5669 case RESTART:
5670 case ACTIVE:
5671 case STOPPING:
5672 case STOPPED:
5673 return true;
5674 case IDLE:
5675 case STARTING:
5676 default:
5677 return false;
5678 }
5679}
5680
Eric Laurent65b65452010-06-01 23:49:17 -07005681status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
5682{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005683 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07005684 status_t status = NO_ERROR;
5685
5686 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
5687 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurenta92ebfa2010-08-31 13:50:07 -07005688 if (isProcessEnabled() &&
Eric Laurent0d7e0482010-07-19 06:24:46 -07005689 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
5690 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Eric Laurent65b65452010-06-01 23:49:17 -07005691 status_t cmdStatus;
5692 uint32_t volume[2];
5693 uint32_t *pVolume = NULL;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005694 uint32_t size = sizeof(volume);
Eric Laurent65b65452010-06-01 23:49:17 -07005695 volume[0] = *left;
5696 volume[1] = *right;
5697 if (controller) {
5698 pVolume = volume;
5699 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005700 status = (*mEffectInterface)->command(mEffectInterface,
5701 EFFECT_CMD_SET_VOLUME,
5702 size,
5703 volume,
5704 &size,
5705 pVolume);
Eric Laurent65b65452010-06-01 23:49:17 -07005706 if (controller && status == NO_ERROR && size == sizeof(volume)) {
5707 *left = volume[0];
5708 *right = volume[1];
5709 }
5710 }
5711 return status;
5712}
5713
5714status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
5715{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005716 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07005717 status_t status = NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07005718 if ((mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
5719 // convert device bit field from AudioSystem to EffectApi format.
5720 device = deviceAudioSystemToEffectApi(device);
5721 if (device == 0) {
5722 return BAD_VALUE;
5723 }
Eric Laurent65b65452010-06-01 23:49:17 -07005724 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005725 uint32_t size = sizeof(status_t);
5726 status = (*mEffectInterface)->command(mEffectInterface,
5727 EFFECT_CMD_SET_DEVICE,
5728 sizeof(uint32_t),
5729 &device,
5730 &size,
5731 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005732 if (status == NO_ERROR) {
5733 status = cmdStatus;
5734 }
5735 }
5736 return status;
5737}
5738
Eric Laurent53334cd2010-06-23 17:38:20 -07005739status_t AudioFlinger::EffectModule::setMode(uint32_t mode)
5740{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005741 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07005742 status_t status = NO_ERROR;
5743 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
5744 // convert audio mode from AudioSystem to EffectApi format.
5745 int effectMode = modeAudioSystemToEffectApi(mode);
5746 if (effectMode < 0) {
5747 return BAD_VALUE;
5748 }
5749 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005750 uint32_t size = sizeof(status_t);
5751 status = (*mEffectInterface)->command(mEffectInterface,
5752 EFFECT_CMD_SET_AUDIO_MODE,
5753 sizeof(int),
5754 &effectMode,
5755 &size,
5756 &cmdStatus);
Eric Laurent53334cd2010-06-23 17:38:20 -07005757 if (status == NO_ERROR) {
5758 status = cmdStatus;
5759 }
5760 }
5761 return status;
5762}
5763
5764// update this table when AudioSystem::audio_devices or audio_device_e (in EffectApi.h) are modified
5765const uint32_t AudioFlinger::EffectModule::sDeviceConvTable[] = {
5766 DEVICE_EARPIECE, // AudioSystem::DEVICE_OUT_EARPIECE
5767 DEVICE_SPEAKER, // AudioSystem::DEVICE_OUT_SPEAKER
5768 DEVICE_WIRED_HEADSET, // case AudioSystem::DEVICE_OUT_WIRED_HEADSET
5769 DEVICE_WIRED_HEADPHONE, // AudioSystem::DEVICE_OUT_WIRED_HEADPHONE
5770 DEVICE_BLUETOOTH_SCO, // AudioSystem::DEVICE_OUT_BLUETOOTH_SCO
5771 DEVICE_BLUETOOTH_SCO_HEADSET, // AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_HEADSET
5772 DEVICE_BLUETOOTH_SCO_CARKIT, // AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_CARKIT
5773 DEVICE_BLUETOOTH_A2DP, // AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP
5774 DEVICE_BLUETOOTH_A2DP_HEADPHONES, // AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES
5775 DEVICE_BLUETOOTH_A2DP_SPEAKER, // AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER
5776 DEVICE_AUX_DIGITAL // AudioSystem::DEVICE_OUT_AUX_DIGITAL
5777};
5778
5779uint32_t AudioFlinger::EffectModule::deviceAudioSystemToEffectApi(uint32_t device)
5780{
5781 uint32_t deviceOut = 0;
5782 while (device) {
5783 const uint32_t i = 31 - __builtin_clz(device);
5784 device &= ~(1 << i);
5785 if (i >= sizeof(sDeviceConvTable)/sizeof(uint32_t)) {
5786 LOGE("device convertion error for AudioSystem device 0x%08x", device);
5787 return 0;
5788 }
5789 deviceOut |= (uint32_t)sDeviceConvTable[i];
5790 }
5791 return deviceOut;
5792}
5793
5794// update this table when AudioSystem::audio_mode or audio_mode_e (in EffectApi.h) are modified
5795const uint32_t AudioFlinger::EffectModule::sModeConvTable[] = {
5796 AUDIO_MODE_NORMAL, // AudioSystem::MODE_NORMAL
5797 AUDIO_MODE_RINGTONE, // AudioSystem::MODE_RINGTONE
Jean-Michel Trivi8f677d62010-11-15 12:11:32 -08005798 AUDIO_MODE_IN_CALL, // AudioSystem::MODE_IN_CALL
5799 AUDIO_MODE_IN_CALL // AudioSystem::MODE_IN_COMMUNICATION, same conversion as for MODE_IN_CALL
Eric Laurent53334cd2010-06-23 17:38:20 -07005800};
5801
5802int AudioFlinger::EffectModule::modeAudioSystemToEffectApi(uint32_t mode)
5803{
5804 int modeOut = -1;
5805 if (mode < sizeof(sModeConvTable) / sizeof(uint32_t)) {
5806 modeOut = (int)sModeConvTable[mode];
5807 }
5808 return modeOut;
5809}
Eric Laurent65b65452010-06-01 23:49:17 -07005810
5811status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
5812{
5813 const size_t SIZE = 256;
5814 char buffer[SIZE];
5815 String8 result;
5816
5817 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
5818 result.append(buffer);
5819
5820 bool locked = tryLock(mLock);
5821 // failed to lock - AudioFlinger is probably deadlocked
5822 if (!locked) {
5823 result.append("\t\tCould not lock Fx mutex:\n");
5824 }
5825
5826 result.append("\t\tSession Status State Engine:\n");
5827 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
5828 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
5829 result.append(buffer);
5830
5831 result.append("\t\tDescriptor:\n");
5832 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
5833 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
5834 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
5835 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
5836 result.append(buffer);
5837 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
5838 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
5839 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
5840 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
5841 result.append(buffer);
5842 snprintf(buffer, SIZE, "\t\t- apiVersion: %04X\n\t\t- flags: %08X\n",
5843 mDescriptor.apiVersion,
5844 mDescriptor.flags);
5845 result.append(buffer);
5846 snprintf(buffer, SIZE, "\t\t- name: %s\n",
5847 mDescriptor.name);
5848 result.append(buffer);
5849 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
5850 mDescriptor.implementor);
5851 result.append(buffer);
5852
5853 result.append("\t\t- Input configuration:\n");
5854 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
5855 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
5856 (uint32_t)mConfig.inputCfg.buffer.raw,
5857 mConfig.inputCfg.buffer.frameCount,
5858 mConfig.inputCfg.samplingRate,
5859 mConfig.inputCfg.channels,
5860 mConfig.inputCfg.format);
5861 result.append(buffer);
5862
5863 result.append("\t\t- Output configuration:\n");
5864 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
5865 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
5866 (uint32_t)mConfig.outputCfg.buffer.raw,
5867 mConfig.outputCfg.buffer.frameCount,
5868 mConfig.outputCfg.samplingRate,
5869 mConfig.outputCfg.channels,
5870 mConfig.outputCfg.format);
5871 result.append(buffer);
5872
5873 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
5874 result.append(buffer);
5875 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
5876 for (size_t i = 0; i < mHandles.size(); ++i) {
5877 sp<EffectHandle> handle = mHandles[i].promote();
5878 if (handle != 0) {
5879 handle->dump(buffer, SIZE);
5880 result.append(buffer);
5881 }
5882 }
5883
5884 result.append("\n");
5885
5886 write(fd, result.string(), result.length());
5887
5888 if (locked) {
5889 mLock.unlock();
5890 }
5891
5892 return NO_ERROR;
5893}
5894
5895// ----------------------------------------------------------------------------
5896// EffectHandle implementation
5897// ----------------------------------------------------------------------------
5898
5899#undef LOG_TAG
5900#define LOG_TAG "AudioFlinger::EffectHandle"
5901
5902AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
5903 const sp<AudioFlinger::Client>& client,
5904 const sp<IEffectClient>& effectClient,
5905 int32_t priority)
5906 : BnEffect(),
5907 mEffect(effect), mEffectClient(effectClient), mClient(client), mPriority(priority), mHasControl(false)
5908{
5909 LOGV("constructor %p", this);
5910
5911 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
5912 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
5913 if (mCblkMemory != 0) {
5914 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
5915
5916 if (mCblk) {
5917 new(mCblk) effect_param_cblk_t();
5918 mBuffer = (uint8_t *)mCblk + bufOffset;
5919 }
5920 } else {
5921 LOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
5922 return;
5923 }
5924}
5925
5926AudioFlinger::EffectHandle::~EffectHandle()
5927{
5928 LOGV("Destructor %p", this);
5929 disconnect();
5930}
5931
5932status_t AudioFlinger::EffectHandle::enable()
5933{
5934 if (!mHasControl) return INVALID_OPERATION;
5935 if (mEffect == 0) return DEAD_OBJECT;
5936
5937 return mEffect->setEnabled(true);
5938}
5939
5940status_t AudioFlinger::EffectHandle::disable()
5941{
5942 if (!mHasControl) return INVALID_OPERATION;
5943 if (mEffect == NULL) return DEAD_OBJECT;
5944
5945 return mEffect->setEnabled(false);
5946}
5947
5948void AudioFlinger::EffectHandle::disconnect()
5949{
5950 if (mEffect == 0) {
5951 return;
5952 }
5953 mEffect->disconnect(this);
5954 // release sp on module => module destructor can be called now
5955 mEffect.clear();
5956 if (mCblk) {
5957 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
5958 }
5959 mCblkMemory.clear(); // and free the shared memory
5960 if (mClient != 0) {
5961 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
5962 mClient.clear();
5963 }
5964}
5965
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005966status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
5967 uint32_t cmdSize,
5968 void *pCmdData,
5969 uint32_t *replySize,
5970 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07005971{
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005972// LOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
5973// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Eric Laurent65b65452010-06-01 23:49:17 -07005974
5975 // only get parameter command is permitted for applications not controlling the effect
5976 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
5977 return INVALID_OPERATION;
5978 }
5979 if (mEffect == 0) return DEAD_OBJECT;
5980
5981 // handle commands that are not forwarded transparently to effect engine
5982 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
5983 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
5984 // no risk to block the whole media server process or mixer threads is we are stuck here
5985 Mutex::Autolock _l(mCblk->lock);
5986 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
5987 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
5988 mCblk->serverIndex = 0;
5989 mCblk->clientIndex = 0;
5990 return BAD_VALUE;
5991 }
5992 status_t status = NO_ERROR;
5993 while (mCblk->serverIndex < mCblk->clientIndex) {
5994 int reply;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005995 uint32_t rsize = sizeof(int);
Eric Laurent65b65452010-06-01 23:49:17 -07005996 int *p = (int *)(mBuffer + mCblk->serverIndex);
5997 int size = *p++;
Eric Laurent53334cd2010-06-23 17:38:20 -07005998 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
5999 LOGW("command(): invalid parameter block size");
6000 break;
6001 }
Eric Laurent65b65452010-06-01 23:49:17 -07006002 effect_param_t *param = (effect_param_t *)p;
Eric Laurent53334cd2010-06-23 17:38:20 -07006003 if (param->psize == 0 || param->vsize == 0) {
6004 LOGW("command(): null parameter or value size");
6005 mCblk->serverIndex += size;
6006 continue;
6007 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006008 uint32_t psize = sizeof(effect_param_t) +
6009 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
6010 param->vsize;
6011 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
6012 psize,
6013 p,
6014 &rsize,
6015 &reply);
Eric Laurente65280c2010-09-02 11:56:55 -07006016 // stop at first error encountered
6017 if (ret != NO_ERROR) {
Eric Laurent65b65452010-06-01 23:49:17 -07006018 status = ret;
Eric Laurente65280c2010-09-02 11:56:55 -07006019 *(int *)pReplyData = reply;
6020 break;
6021 } else if (reply != NO_ERROR) {
6022 *(int *)pReplyData = reply;
6023 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006024 }
6025 mCblk->serverIndex += size;
6026 }
6027 mCblk->serverIndex = 0;
6028 mCblk->clientIndex = 0;
6029 return status;
6030 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurente65280c2010-09-02 11:56:55 -07006031 *(int *)pReplyData = NO_ERROR;
Eric Laurent65b65452010-06-01 23:49:17 -07006032 return enable();
6033 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurente65280c2010-09-02 11:56:55 -07006034 *(int *)pReplyData = NO_ERROR;
Eric Laurent65b65452010-06-01 23:49:17 -07006035 return disable();
6036 }
6037
6038 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
6039}
6040
6041sp<IMemory> AudioFlinger::EffectHandle::getCblk() const {
6042 return mCblkMemory;
6043}
6044
6045void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal)
6046{
6047 LOGV("setControl %p control %d", this, hasControl);
6048
6049 mHasControl = hasControl;
6050 if (signal && mEffectClient != 0) {
6051 mEffectClient->controlStatusChanged(hasControl);
6052 }
6053}
6054
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006055void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
6056 uint32_t cmdSize,
6057 void *pCmdData,
6058 uint32_t replySize,
6059 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07006060{
6061 if (mEffectClient != 0) {
6062 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
6063 }
6064}
6065
6066
6067
6068void AudioFlinger::EffectHandle::setEnabled(bool enabled)
6069{
6070 if (mEffectClient != 0) {
6071 mEffectClient->enableStatusChanged(enabled);
6072 }
6073}
6074
6075status_t AudioFlinger::EffectHandle::onTransact(
6076 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6077{
6078 return BnEffect::onTransact(code, data, reply, flags);
6079}
6080
6081
6082void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
6083{
6084 bool locked = tryLock(mCblk->lock);
6085
6086 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
6087 (mClient == NULL) ? getpid() : mClient->pid(),
6088 mPriority,
6089 mHasControl,
6090 !locked,
6091 mCblk->clientIndex,
6092 mCblk->serverIndex
6093 );
6094
6095 if (locked) {
6096 mCblk->lock.unlock();
6097 }
6098}
6099
6100#undef LOG_TAG
6101#define LOG_TAG "AudioFlinger::EffectChain"
6102
6103AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
6104 int sessionId)
Eric Laurent76c40f72010-07-15 12:50:15 -07006105 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mOwnInBuffer(false),
Eric Laurent2a6b80b2010-07-29 23:43:43 -07006106 mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
6107 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Eric Laurent65b65452010-06-01 23:49:17 -07006108{
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006109 mStrategy = AudioSystem::getStrategyForStream(AudioSystem::MUSIC);
Eric Laurent65b65452010-06-01 23:49:17 -07006110}
6111
6112AudioFlinger::EffectChain::~EffectChain()
6113{
6114 if (mOwnInBuffer) {
6115 delete mInBuffer;
6116 }
6117
6118}
6119
Eric Laurent76c40f72010-07-15 12:50:15 -07006120// getEffectFromDesc_l() must be called with PlaybackThread::mLock held
6121sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Eric Laurent65b65452010-06-01 23:49:17 -07006122{
6123 sp<EffectModule> effect;
6124 size_t size = mEffects.size();
6125
6126 for (size_t i = 0; i < size; i++) {
6127 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
6128 effect = mEffects[i];
6129 break;
6130 }
6131 }
6132 return effect;
6133}
6134
Eric Laurent76c40f72010-07-15 12:50:15 -07006135// getEffectFromId_l() must be called with PlaybackThread::mLock held
6136sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Eric Laurent65b65452010-06-01 23:49:17 -07006137{
6138 sp<EffectModule> effect;
6139 size_t size = mEffects.size();
6140
6141 for (size_t i = 0; i < size; i++) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006142 // by convention, return first effect if id provided is 0 (0 is never a valid id)
6143 if (id == 0 || mEffects[i]->id() == id) {
Eric Laurent65b65452010-06-01 23:49:17 -07006144 effect = mEffects[i];
6145 break;
6146 }
6147 }
6148 return effect;
6149}
6150
6151// Must be called with EffectChain::mLock locked
6152void AudioFlinger::EffectChain::process_l()
6153{
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07006154 sp<ThreadBase> thread = mThread.promote();
6155 if (thread == 0) {
6156 LOGW("process_l(): cannot promote mixer thread");
6157 return;
6158 }
6159 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
6160 bool isGlobalSession = (mSessionId == AudioSystem::SESSION_OUTPUT_MIX) ||
6161 (mSessionId == AudioSystem::SESSION_OUTPUT_STAGE);
6162 bool tracksOnSession = false;
6163 if (!isGlobalSession) {
6164 tracksOnSession =
6165 playbackThread->hasAudioSession(mSessionId) & PlaybackThread::TRACK_SESSION;
6166 }
6167
Eric Laurent65b65452010-06-01 23:49:17 -07006168 size_t size = mEffects.size();
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07006169 // do not process effect if no track is present in same audio session
6170 if (isGlobalSession || tracksOnSession) {
6171 for (size_t i = 0; i < size; i++) {
6172 mEffects[i]->process();
6173 }
Eric Laurent65b65452010-06-01 23:49:17 -07006174 }
Eric Laurent7d850f22010-07-09 13:34:17 -07006175 for (size_t i = 0; i < size; i++) {
6176 mEffects[i]->updateState();
6177 }
Eric Laurent65b65452010-06-01 23:49:17 -07006178 // if no track is active, input buffer must be cleared here as the mixer process
6179 // will not do it
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07006180 if (tracksOnSession &&
6181 activeTracks() == 0) {
6182 size_t numSamples = playbackThread->frameCount() * playbackThread->channelCount();
6183 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
Eric Laurent65b65452010-06-01 23:49:17 -07006184 }
6185}
6186
Eric Laurent76c40f72010-07-15 12:50:15 -07006187// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006188status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Eric Laurent65b65452010-06-01 23:49:17 -07006189{
6190 effect_descriptor_t desc = effect->desc();
6191 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
6192
6193 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006194 effect->setChain(this);
6195 sp<ThreadBase> thread = mThread.promote();
6196 if (thread == 0) {
6197 return NO_INIT;
6198 }
6199 effect->setThread(thread);
Eric Laurent65b65452010-06-01 23:49:17 -07006200
6201 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6202 // Auxiliary effects are inserted at the beginning of mEffects vector as
6203 // they are processed first and accumulated in chain input buffer
6204 mEffects.insertAt(effect, 0);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006205
Eric Laurent65b65452010-06-01 23:49:17 -07006206 // the input buffer for auxiliary effect contains mono samples in
6207 // 32 bit format. This is to avoid saturation in AudoMixer
6208 // accumulation stage. Saturation is done in EffectModule::process() before
6209 // calling the process in effect engine
6210 size_t numSamples = thread->frameCount();
6211 int32_t *buffer = new int32_t[numSamples];
6212 memset(buffer, 0, numSamples * sizeof(int32_t));
6213 effect->setInBuffer((int16_t *)buffer);
6214 // auxiliary effects output samples to chain input buffer for further processing
6215 // by insert effects
6216 effect->setOutBuffer(mInBuffer);
6217 } else {
6218 // Insert effects are inserted at the end of mEffects vector as they are processed
6219 // after track and auxiliary effects.
Eric Laurent53334cd2010-06-23 17:38:20 -07006220 // Insert effect order as a function of indicated preference:
6221 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
6222 // another effect is present
6223 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
6224 // last effect claiming first position
6225 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
6226 // first effect claiming last position
Eric Laurent65b65452010-06-01 23:49:17 -07006227 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
Eric Laurent53334cd2010-06-23 17:38:20 -07006228 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
6229 // already present
Eric Laurent65b65452010-06-01 23:49:17 -07006230
6231 int size = (int)mEffects.size();
6232 int idx_insert = size;
6233 int idx_insert_first = -1;
6234 int idx_insert_last = -1;
6235
6236 for (int i = 0; i < size; i++) {
6237 effect_descriptor_t d = mEffects[i]->desc();
6238 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
6239 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
6240 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
6241 // check invalid effect chaining combinations
6242 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
Eric Laurent53334cd2010-06-23 17:38:20 -07006243 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Eric Laurent76c40f72010-07-15 12:50:15 -07006244 LOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Eric Laurent65b65452010-06-01 23:49:17 -07006245 return INVALID_OPERATION;
6246 }
Eric Laurent53334cd2010-06-23 17:38:20 -07006247 // remember position of first insert effect and by default
6248 // select this as insert position for new effect
Eric Laurent65b65452010-06-01 23:49:17 -07006249 if (idx_insert == size) {
6250 idx_insert = i;
6251 }
Eric Laurent53334cd2010-06-23 17:38:20 -07006252 // remember position of last insert effect claiming
6253 // first position
Eric Laurent65b65452010-06-01 23:49:17 -07006254 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
6255 idx_insert_first = i;
6256 }
Eric Laurent53334cd2010-06-23 17:38:20 -07006257 // remember position of first insert effect claiming
6258 // last position
6259 if (iPref == EFFECT_FLAG_INSERT_LAST &&
6260 idx_insert_last == -1) {
Eric Laurent65b65452010-06-01 23:49:17 -07006261 idx_insert_last = i;
6262 }
6263 }
6264 }
6265
Eric Laurent53334cd2010-06-23 17:38:20 -07006266 // modify idx_insert from first position if needed
6267 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
6268 if (idx_insert_last != -1) {
6269 idx_insert = idx_insert_last;
6270 } else {
6271 idx_insert = size;
6272 }
6273 } else {
6274 if (idx_insert_first != -1) {
6275 idx_insert = idx_insert_first + 1;
6276 }
Eric Laurent65b65452010-06-01 23:49:17 -07006277 }
6278
6279 // always read samples from chain input buffer
6280 effect->setInBuffer(mInBuffer);
6281
6282 // if last effect in the chain, output samples to chain
6283 // output buffer, otherwise to chain input buffer
6284 if (idx_insert == size) {
6285 if (idx_insert != 0) {
6286 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
6287 mEffects[idx_insert-1]->configure();
6288 }
6289 effect->setOutBuffer(mOutBuffer);
6290 } else {
6291 effect->setOutBuffer(mInBuffer);
6292 }
Eric Laurent53334cd2010-06-23 17:38:20 -07006293 mEffects.insertAt(effect, idx_insert);
Eric Laurent65b65452010-06-01 23:49:17 -07006294
Eric Laurent76c40f72010-07-15 12:50:15 -07006295 LOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Eric Laurent65b65452010-06-01 23:49:17 -07006296 }
6297 effect->configure();
6298 return NO_ERROR;
6299}
6300
Eric Laurent76c40f72010-07-15 12:50:15 -07006301// removeEffect_l() must be called with PlaybackThread::mLock held
6302size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Eric Laurent65b65452010-06-01 23:49:17 -07006303{
6304 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07006305 int size = (int)mEffects.size();
6306 int i;
6307 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
6308
6309 for (i = 0; i < size; i++) {
6310 if (effect == mEffects[i]) {
6311 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
6312 delete[] effect->inBuffer();
6313 } else {
6314 if (i == size - 1 && i != 0) {
6315 mEffects[i - 1]->setOutBuffer(mOutBuffer);
6316 mEffects[i - 1]->configure();
6317 }
6318 }
6319 mEffects.removeAt(i);
Eric Laurent76c40f72010-07-15 12:50:15 -07006320 LOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Eric Laurent65b65452010-06-01 23:49:17 -07006321 break;
6322 }
6323 }
Eric Laurent65b65452010-06-01 23:49:17 -07006324
6325 return mEffects.size();
6326}
6327
Eric Laurent76c40f72010-07-15 12:50:15 -07006328// setDevice_l() must be called with PlaybackThread::mLock held
6329void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Eric Laurent65b65452010-06-01 23:49:17 -07006330{
6331 size_t size = mEffects.size();
6332 for (size_t i = 0; i < size; i++) {
6333 mEffects[i]->setDevice(device);
6334 }
6335}
6336
Eric Laurent76c40f72010-07-15 12:50:15 -07006337// setMode_l() must be called with PlaybackThread::mLock held
6338void AudioFlinger::EffectChain::setMode_l(uint32_t mode)
Eric Laurent53334cd2010-06-23 17:38:20 -07006339{
6340 size_t size = mEffects.size();
6341 for (size_t i = 0; i < size; i++) {
6342 mEffects[i]->setMode(mode);
6343 }
6344}
6345
Eric Laurent76c40f72010-07-15 12:50:15 -07006346// setVolume_l() must be called with PlaybackThread::mLock held
6347bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Eric Laurent65b65452010-06-01 23:49:17 -07006348{
6349 uint32_t newLeft = *left;
6350 uint32_t newRight = *right;
6351 bool hasControl = false;
Eric Laurent76c40f72010-07-15 12:50:15 -07006352 int ctrlIdx = -1;
6353 size_t size = mEffects.size();
Eric Laurent65b65452010-06-01 23:49:17 -07006354
Eric Laurent76c40f72010-07-15 12:50:15 -07006355 // first update volume controller
6356 for (size_t i = size; i > 0; i--) {
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006357 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurent76c40f72010-07-15 12:50:15 -07006358 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
6359 ctrlIdx = i - 1;
Eric Laurent0d7e0482010-07-19 06:24:46 -07006360 hasControl = true;
Eric Laurent76c40f72010-07-15 12:50:15 -07006361 break;
6362 }
6363 }
6364
6365 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurent0d7e0482010-07-19 06:24:46 -07006366 if (hasControl) {
6367 *left = mNewLeftVolume;
6368 *right = mNewRightVolume;
6369 }
6370 return hasControl;
Eric Laurent76c40f72010-07-15 12:50:15 -07006371 }
6372
6373 mVolumeCtrlIdx = ctrlIdx;
Eric Laurent0d7e0482010-07-19 06:24:46 -07006374 mLeftVolume = newLeft;
6375 mRightVolume = newRight;
Eric Laurent76c40f72010-07-15 12:50:15 -07006376
6377 // second get volume update from volume controller
6378 if (ctrlIdx >= 0) {
6379 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurent0d7e0482010-07-19 06:24:46 -07006380 mNewLeftVolume = newLeft;
6381 mNewRightVolume = newRight;
Eric Laurent65b65452010-06-01 23:49:17 -07006382 }
6383 // then indicate volume to all other effects in chain.
6384 // Pass altered volume to effects before volume controller
6385 // and requested volume to effects after controller
6386 uint32_t lVol = newLeft;
6387 uint32_t rVol = newRight;
Eric Laurent76c40f72010-07-15 12:50:15 -07006388
Eric Laurent65b65452010-06-01 23:49:17 -07006389 for (size_t i = 0; i < size; i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07006390 if ((int)i == ctrlIdx) continue;
6391 // this also works for ctrlIdx == -1 when there is no volume controller
6392 if ((int)i > ctrlIdx) {
Eric Laurent65b65452010-06-01 23:49:17 -07006393 lVol = *left;
6394 rVol = *right;
6395 }
6396 mEffects[i]->setVolume(&lVol, &rVol, false);
6397 }
6398 *left = newLeft;
6399 *right = newRight;
6400
6401 return hasControl;
6402}
6403
Eric Laurent65b65452010-06-01 23:49:17 -07006404status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
6405{
6406 const size_t SIZE = 256;
6407 char buffer[SIZE];
6408 String8 result;
6409
6410 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
6411 result.append(buffer);
6412
6413 bool locked = tryLock(mLock);
6414 // failed to lock - AudioFlinger is probably deadlocked
6415 if (!locked) {
6416 result.append("\tCould not lock mutex:\n");
6417 }
6418
Eric Laurent76c40f72010-07-15 12:50:15 -07006419 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
6420 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Eric Laurent65b65452010-06-01 23:49:17 -07006421 mEffects.size(),
6422 (uint32_t)mInBuffer,
6423 (uint32_t)mOutBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -07006424 mActiveTrackCnt);
6425 result.append(buffer);
6426 write(fd, result.string(), result.size());
6427
6428 for (size_t i = 0; i < mEffects.size(); ++i) {
6429 sp<EffectModule> effect = mEffects[i];
6430 if (effect != 0) {
6431 effect->dump(fd, args);
6432 }
6433 }
6434
6435 if (locked) {
6436 mLock.unlock();
6437 }
6438
6439 return NO_ERROR;
6440}
6441
6442#undef LOG_TAG
6443#define LOG_TAG "AudioFlinger"
6444
Eric Laurenta553c252009-07-17 12:17:14 -07006445// ----------------------------------------------------------------------------
6446
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07006447status_t AudioFlinger::onTransact(
6448 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6449{
6450 return BnAudioFlinger::onTransact(code, data, reply, flags);
6451}
6452
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07006453}; // namespace android