blob: b88e69d88580295eafe1a47dc5790e5e97a93fd9 [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{
134 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -0700135
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700136 mAudioHardware = AudioHardwareInterface::create();
Eric Laurenta553c252009-07-17 12:17:14 -0700137
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700138 mHardwareStatus = AUDIO_HW_INIT;
139 if (mAudioHardware->initCheck() == NO_ERROR) {
140 // open 16-bit output stream for s/w mixer
Eric Laurent53334cd2010-06-23 17:38:20 -0700141 mMode = AudioSystem::MODE_NORMAL;
142 setMode(mMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143
144 setMasterVolume(1.0f);
145 setMasterMute(false);
Eric Laurenta553c252009-07-17 12:17:14 -0700146 } else {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700147 LOGE("Couldn't even initialize the stubbed audio hardware!");
148 }
Glenn Kasten871c16c2010-03-05 12:18:01 -0800149#ifdef LVMX
150 LifeVibes::init();
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700151 mLifeVibesClientPid = -1;
Glenn Kasten871c16c2010-03-05 12:18:01 -0800152#endif
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700153}
154
155AudioFlinger::~AudioFlinger()
156{
Eric Laurent7954c462009-08-28 10:39:03 -0700157 while (!mRecordThreads.isEmpty()) {
158 // closeInput() will remove first entry from mRecordThreads
159 closeInput(mRecordThreads.keyAt(0));
160 }
161 while (!mPlaybackThreads.isEmpty()) {
162 // closeOutput() will remove first entry from mPlaybackThreads
163 closeOutput(mPlaybackThreads.keyAt(0));
164 }
165 if (mAudioHardware) {
166 delete mAudioHardware;
167 }
The Android Open Source Projectb7986892009-01-09 17:51:23 -0800168}
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800169
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700170
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700171
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700172status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
173{
174 const size_t SIZE = 256;
175 char buffer[SIZE];
176 String8 result;
177
178 result.append("Clients:\n");
179 for (size_t i = 0; i < mClients.size(); ++i) {
180 wp<Client> wClient = mClients.valueAt(i);
181 if (wClient != 0) {
182 sp<Client> client = wClient.promote();
183 if (client != 0) {
184 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
185 result.append(buffer);
186 }
187 }
188 }
189 write(fd, result.string(), result.size());
190 return NO_ERROR;
191}
192
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700193
194status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
195{
196 const size_t SIZE = 256;
197 char buffer[SIZE];
198 String8 result;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700199 int hardwareStatus = mHardwareStatus;
Eric Laurenta553c252009-07-17 12:17:14 -0700200
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700201 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700202 result.append(buffer);
203 write(fd, result.string(), result.size());
204 return NO_ERROR;
205}
206
207status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
208{
209 const size_t SIZE = 256;
210 char buffer[SIZE];
211 String8 result;
212 snprintf(buffer, SIZE, "Permission Denial: "
213 "can't dump AudioFlinger from pid=%d, uid=%d\n",
214 IPCThreadState::self()->getCallingPid(),
215 IPCThreadState::self()->getCallingUid());
216 result.append(buffer);
217 write(fd, result.string(), result.size());
218 return NO_ERROR;
219}
220
The Android Open Source Project10592532009-03-18 17:39:46 -0700221static bool tryLock(Mutex& mutex)
222{
223 bool locked = false;
224 for (int i = 0; i < kDumpLockRetries; ++i) {
225 if (mutex.tryLock() == NO_ERROR) {
226 locked = true;
227 break;
228 }
229 usleep(kDumpLockSleep);
230 }
231 return locked;
232}
233
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700234status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
235{
236 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
237 dumpPermissionDenial(fd, args);
238 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -0700239 // get state of hardware lock
240 bool hardwareLocked = tryLock(mHardwareLock);
241 if (!hardwareLocked) {
242 String8 result(kHardwareLockedString);
243 write(fd, result.string(), result.size());
244 } else {
245 mHardwareLock.unlock();
246 }
247
248 bool locked = tryLock(mLock);
249
250 // failed to lock - AudioFlinger is probably deadlocked
251 if (!locked) {
252 String8 result(kDeadlockedString);
253 write(fd, result.string(), result.size());
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700254 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700255
256 dumpClients(fd, args);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700257 dumpInternals(fd, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800258
Eric Laurenta553c252009-07-17 12:17:14 -0700259 // dump playback threads
260 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700261 mPlaybackThreads.valueAt(i)->dump(fd, args);
Eric Laurenta553c252009-07-17 12:17:14 -0700262 }
263
264 // dump record threads
Eric Laurent102313a2009-07-23 13:35:01 -0700265 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700266 mRecordThreads.valueAt(i)->dump(fd, args);
Eric Laurenta553c252009-07-17 12:17:14 -0700267 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800268
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700269 if (mAudioHardware) {
270 mAudioHardware->dumpState(fd, args);
271 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700272 if (locked) mLock.unlock();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700273 }
274 return NO_ERROR;
275}
276
Eric Laurenta553c252009-07-17 12:17:14 -0700277
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700278// IAudioFlinger interface
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800279
280
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700281sp<IAudioTrack> AudioFlinger::createTrack(
282 pid_t pid,
283 int streamType,
284 uint32_t sampleRate,
285 int format,
286 int channelCount,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800287 int frameCount,
288 uint32_t flags,
289 const sp<IMemory>& sharedBuffer,
Eric Laurentddb78e72009-07-28 08:44:33 -0700290 int output,
Eric Laurent65b65452010-06-01 23:49:17 -0700291 int *sessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800292 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700293{
Eric Laurenta553c252009-07-17 12:17:14 -0700294 sp<PlaybackThread::Track> track;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700295 sp<TrackHandle> trackHandle;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700296 sp<Client> client;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800297 wp<Client> wclient;
298 status_t lStatus;
Eric Laurent65b65452010-06-01 23:49:17 -0700299 int lSessionId;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700300
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800301 if (streamType >= AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800302 LOGE("invalid stream type");
303 lStatus = BAD_VALUE;
304 goto Exit;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700305 }
306
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800307 {
308 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700309 PlaybackThread *thread = checkPlaybackThread_l(output);
310 if (thread == NULL) {
311 LOGE("unknown output thread");
312 lStatus = BAD_VALUE;
313 goto Exit;
314 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800315
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800316 wclient = mClients.valueFor(pid);
317
318 if (wclient != NULL) {
319 client = wclient.promote();
320 } else {
321 client = new Client(this, pid);
322 mClients.add(pid, client);
323 }
Eric Laurent65b65452010-06-01 23:49:17 -0700324
Eric Laurent65b65452010-06-01 23:49:17 -0700325 LOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700326 if (sessionId != NULL && *sessionId != AudioSystem::SESSION_OUTPUT_MIX) {
327 // prevent same audio session on different output threads
328 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
329 if (mPlaybackThreads.keyAt(i) != output &&
330 mPlaybackThreads.valueAt(i)->hasAudioSession(*sessionId)) {
331 lStatus = BAD_VALUE;
332 goto Exit;
333 }
334 }
Eric Laurent65b65452010-06-01 23:49:17 -0700335 lSessionId = *sessionId;
336 } else {
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700337 // if no audio session id is provided, create one here
Eric Laurent65b65452010-06-01 23:49:17 -0700338 lSessionId = nextUniqueId();
339 if (sessionId != NULL) {
340 *sessionId = lSessionId;
341 }
342 }
343 LOGV("createTrack() lSessionId: %d", lSessionId);
344
Eric Laurenta553c252009-07-17 12:17:14 -0700345 track = thread->createTrack_l(client, streamType, sampleRate, format,
Eric Laurent65b65452010-06-01 23:49:17 -0700346 channelCount, frameCount, sharedBuffer, lSessionId, &lStatus);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700347 }
348 if (lStatus == NO_ERROR) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800349 trackHandle = new TrackHandle(track);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700350 } else {
Eric Laurentb9481d82009-09-17 05:12:56 -0700351 // remove local strong reference to Client before deleting the Track so that the Client
352 // destructor is called by the TrackBase destructor with mLock held
353 client.clear();
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700354 track.clear();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800355 }
356
357Exit:
358 if(status) {
359 *status = lStatus;
360 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700361 return trackHandle;
362}
363
Eric Laurentddb78e72009-07-28 08:44:33 -0700364uint32_t AudioFlinger::sampleRate(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700365{
Eric Laurenta553c252009-07-17 12:17:14 -0700366 Mutex::Autolock _l(mLock);
367 PlaybackThread *thread = checkPlaybackThread_l(output);
368 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700369 LOGW("sampleRate() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700370 return 0;
371 }
372 return thread->sampleRate();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700373}
374
Eric Laurentddb78e72009-07-28 08:44:33 -0700375int AudioFlinger::channelCount(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700376{
Eric Laurenta553c252009-07-17 12:17:14 -0700377 Mutex::Autolock _l(mLock);
378 PlaybackThread *thread = checkPlaybackThread_l(output);
379 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700380 LOGW("channelCount() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700381 return 0;
382 }
383 return thread->channelCount();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700384}
385
Eric Laurentddb78e72009-07-28 08:44:33 -0700386int AudioFlinger::format(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700387{
Eric Laurenta553c252009-07-17 12:17:14 -0700388 Mutex::Autolock _l(mLock);
389 PlaybackThread *thread = checkPlaybackThread_l(output);
390 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700391 LOGW("format() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700392 return 0;
393 }
394 return thread->format();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700395}
396
Eric Laurentddb78e72009-07-28 08:44:33 -0700397size_t AudioFlinger::frameCount(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700398{
Eric Laurenta553c252009-07-17 12:17:14 -0700399 Mutex::Autolock _l(mLock);
400 PlaybackThread *thread = checkPlaybackThread_l(output);
401 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700402 LOGW("frameCount() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700403 return 0;
404 }
405 return thread->frameCount();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700406}
407
Eric Laurentddb78e72009-07-28 08:44:33 -0700408uint32_t AudioFlinger::latency(int output) const
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800409{
Eric Laurenta553c252009-07-17 12:17:14 -0700410 Mutex::Autolock _l(mLock);
411 PlaybackThread *thread = checkPlaybackThread_l(output);
412 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700413 LOGW("latency() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700414 return 0;
415 }
416 return thread->latency();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800417}
418
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700419status_t AudioFlinger::setMasterVolume(float value)
420{
421 // check calling permissions
422 if (!settingsAllowed()) {
423 return PERMISSION_DENIED;
424 }
425
426 // when hw supports master volume, don't scale in sw mixer
427 AutoMutex lock(mHardwareLock);
428 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
429 if (mAudioHardware->setMasterVolume(value) == NO_ERROR) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800430 value = 1.0f;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700431 }
432 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -0700433
434 mMasterVolume = value;
435 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700436 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700437
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700438 return NO_ERROR;
439}
440
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700441status_t AudioFlinger::setMode(int mode)
442{
Eric Laurent53334cd2010-06-23 17:38:20 -0700443 status_t ret;
444
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700445 // check calling permissions
446 if (!settingsAllowed()) {
447 return PERMISSION_DENIED;
448 }
449 if ((mode < 0) || (mode >= AudioSystem::NUM_MODES)) {
450 LOGW("Illegal value: setMode(%d)", mode);
451 return BAD_VALUE;
452 }
453
Eric Laurent53334cd2010-06-23 17:38:20 -0700454 { // scope for the lock
455 AutoMutex lock(mHardwareLock);
456 mHardwareStatus = AUDIO_HW_SET_MODE;
457 ret = mAudioHardware->setMode(mode);
458 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten871c16c2010-03-05 12:18:01 -0800459 }
Eric Laurent53334cd2010-06-23 17:38:20 -0700460
461 if (NO_ERROR == ret) {
462 Mutex::Autolock _l(mLock);
463 mMode = mode;
464 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
465 mPlaybackThreads.valueAt(i)->setMode(mode);
466#ifdef LVMX
467 LifeVibes::setMode(mode);
Glenn Kasten871c16c2010-03-05 12:18:01 -0800468#endif
Eric Laurent53334cd2010-06-23 17:38:20 -0700469 }
470
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700471 return ret;
472}
473
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700474status_t AudioFlinger::setMicMute(bool state)
475{
476 // check calling permissions
477 if (!settingsAllowed()) {
478 return PERMISSION_DENIED;
479 }
480
481 AutoMutex lock(mHardwareLock);
482 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
483 status_t ret = mAudioHardware->setMicMute(state);
484 mHardwareStatus = AUDIO_HW_IDLE;
485 return ret;
486}
487
488bool AudioFlinger::getMicMute() const
489{
490 bool state = AudioSystem::MODE_INVALID;
491 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
492 mAudioHardware->getMicMute(&state);
493 mHardwareStatus = AUDIO_HW_IDLE;
494 return state;
495}
496
497status_t AudioFlinger::setMasterMute(bool muted)
498{
499 // check calling permissions
500 if (!settingsAllowed()) {
501 return PERMISSION_DENIED;
502 }
Eric Laurenta553c252009-07-17 12:17:14 -0700503
504 mMasterMute = muted;
505 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700506 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Eric Laurenta553c252009-07-17 12:17:14 -0700507
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700508 return NO_ERROR;
509}
510
511float AudioFlinger::masterVolume() const
512{
Eric Laurenta553c252009-07-17 12:17:14 -0700513 return mMasterVolume;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700514}
515
516bool AudioFlinger::masterMute() const
517{
Eric Laurenta553c252009-07-17 12:17:14 -0700518 return mMasterMute;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700519}
520
Eric Laurentddb78e72009-07-28 08:44:33 -0700521status_t AudioFlinger::setStreamVolume(int stream, float value, int output)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700522{
523 // check calling permissions
524 if (!settingsAllowed()) {
525 return PERMISSION_DENIED;
526 }
527
Eric Laurenta553c252009-07-17 12:17:14 -0700528 if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700529 return BAD_VALUE;
530 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800531
Eric Laurenta553c252009-07-17 12:17:14 -0700532 AutoMutex lock(mLock);
533 PlaybackThread *thread = NULL;
534 if (output) {
535 thread = checkPlaybackThread_l(output);
536 if (thread == NULL) {
537 return BAD_VALUE;
538 }
539 }
540
Eric Laurenta553c252009-07-17 12:17:14 -0700541 mStreamTypes[stream].volume = value;
542
543 if (thread == NULL) {
Eric Laurent415f3e22009-10-21 08:14:22 -0700544 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700545 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Eric Laurent415f3e22009-10-21 08:14:22 -0700546 }
Eric Laurenta553c252009-07-17 12:17:14 -0700547 } else {
548 thread->setStreamVolume(stream, value);
549 }
Eric Laurentef028272009-04-21 07:56:33 -0700550
Eric Laurent415f3e22009-10-21 08:14:22 -0700551 return NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700552}
553
554status_t AudioFlinger::setStreamMute(int stream, bool muted)
555{
556 // check calling permissions
557 if (!settingsAllowed()) {
558 return PERMISSION_DENIED;
559 }
560
Eric Laurenta553c252009-07-17 12:17:14 -0700561 if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES ||
Eric Laurenteeea9222009-03-26 01:57:59 -0700562 uint32_t(stream) == AudioSystem::ENFORCED_AUDIBLE) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700563 return BAD_VALUE;
564 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700565
Eric Laurenta553c252009-07-17 12:17:14 -0700566 mStreamTypes[stream].mute = muted;
567 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700568 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800569
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700570 return NO_ERROR;
571}
572
Eric Laurentddb78e72009-07-28 08:44:33 -0700573float AudioFlinger::streamVolume(int stream, int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700574{
Eric Laurenta553c252009-07-17 12:17:14 -0700575 if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700576 return 0.0f;
577 }
Eric Laurenta553c252009-07-17 12:17:14 -0700578
579 AutoMutex lock(mLock);
580 float volume;
581 if (output) {
582 PlaybackThread *thread = checkPlaybackThread_l(output);
583 if (thread == NULL) {
584 return 0.0f;
585 }
586 volume = thread->streamVolume(stream);
587 } else {
588 volume = mStreamTypes[stream].volume;
589 }
590
Eric Laurentef028272009-04-21 07:56:33 -0700591 return volume;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700592}
593
594bool AudioFlinger::streamMute(int stream) const
595{
Eric Laurenta553c252009-07-17 12:17:14 -0700596 if (stream < 0 || stream >= (int)AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700597 return true;
598 }
Eric Laurenta553c252009-07-17 12:17:14 -0700599
600 return mStreamTypes[stream].mute;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700601}
602
Eric Laurent23f25cd2010-01-25 08:49:09 -0800603bool AudioFlinger::isStreamActive(int stream) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700604{
Eric Laurent4e646332009-07-09 03:20:57 -0700605 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700606 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent23f25cd2010-01-25 08:49:09 -0800607 if (mPlaybackThreads.valueAt(i)->isStreamActive(stream)) {
Eric Laurenta553c252009-07-17 12:17:14 -0700608 return true;
609 }
610 }
611 return false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700612}
613
Eric Laurentddb78e72009-07-28 08:44:33 -0700614status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700615{
Eric Laurenta553c252009-07-17 12:17:14 -0700616 status_t result;
617
Eric Laurentddb78e72009-07-28 08:44:33 -0700618 LOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
Eric Laurenta553c252009-07-17 12:17:14 -0700619 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
620 // check calling permissions
621 if (!settingsAllowed()) {
622 return PERMISSION_DENIED;
The Android Open Source Project9266c552009-01-15 16:12:10 -0800623 }
Eric Laurenta553c252009-07-17 12:17:14 -0700624
Glenn Kasten871c16c2010-03-05 12:18:01 -0800625#ifdef LVMX
626 AudioParameter param = AudioParameter(keyValuePairs);
627 LifeVibes::setParameters(ioHandle,keyValuePairs);
628 String8 key = String8(AudioParameter::keyRouting);
629 int device;
630 if (NO_ERROR != param.getInt(key, device)) {
631 device = -1;
632 }
633
634 key = String8(LifevibesTag);
635 String8 value;
636 int musicEnabled = -1;
637 if (NO_ERROR == param.get(key, value)) {
638 if (value == LifevibesEnable) {
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700639 mLifeVibesClientPid = IPCThreadState::self()->getCallingPid();
Glenn Kasten871c16c2010-03-05 12:18:01 -0800640 musicEnabled = 1;
641 } else if (value == LifevibesDisable) {
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700642 mLifeVibesClientPid = -1;
Glenn Kasten871c16c2010-03-05 12:18:01 -0800643 musicEnabled = 0;
644 }
645 }
646#endif
647
Eric Laurenta553c252009-07-17 12:17:14 -0700648 // ioHandle == 0 means the parameters are global to the audio hardware interface
649 if (ioHandle == 0) {
650 AutoMutex lock(mHardwareLock);
651 mHardwareStatus = AUDIO_SET_PARAMETER;
652 result = mAudioHardware->setParameters(keyValuePairs);
Glenn Kasten871c16c2010-03-05 12:18:01 -0800653#ifdef LVMX
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700654 if (musicEnabled != -1) {
Glenn Kasten871c16c2010-03-05 12:18:01 -0800655 LifeVibes::enableMusic((bool) musicEnabled);
656 }
657#endif
Eric Laurenta553c252009-07-17 12:17:14 -0700658 mHardwareStatus = AUDIO_HW_IDLE;
659 return result;
660 }
661
Eric Laurentb7d94602009-09-29 11:12:57 -0700662 // hold a strong ref on thread in case closeOutput() or closeInput() is called
663 // and the thread is exited once the lock is released
664 sp<ThreadBase> thread;
665 {
666 Mutex::Autolock _l(mLock);
667 thread = checkPlaybackThread_l(ioHandle);
668 if (thread == NULL) {
669 thread = checkRecordThread_l(ioHandle);
670 }
Eric Laurenta553c252009-07-17 12:17:14 -0700671 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700672 if (thread != NULL) {
Glenn Kasten871c16c2010-03-05 12:18:01 -0800673 result = thread->setParameters(keyValuePairs);
674#ifdef LVMX
675 if ((NO_ERROR == result) && (device != -1)) {
676 LifeVibes::setDevice(LifeVibes::threadIdToAudioOutputType(thread->id()), device);
677 }
678#endif
679 return result;
Eric Laurenta553c252009-07-17 12:17:14 -0700680 }
Eric Laurenta553c252009-07-17 12:17:14 -0700681 return BAD_VALUE;
682}
683
Eric Laurentddb78e72009-07-28 08:44:33 -0700684String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
Eric Laurenta553c252009-07-17 12:17:14 -0700685{
Eric Laurentddb78e72009-07-28 08:44:33 -0700686// LOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
Eric Laurenta553c252009-07-17 12:17:14 -0700687// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
688
689 if (ioHandle == 0) {
690 return mAudioHardware->getParameters(keys);
691 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700692
693 Mutex::Autolock _l(mLock);
694
Eric Laurenta553c252009-07-17 12:17:14 -0700695 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
696 if (playbackThread != NULL) {
697 return playbackThread->getParameters(keys);
698 }
699 RecordThread *recordThread = checkRecordThread_l(ioHandle);
700 if (recordThread != NULL) {
701 return recordThread->getParameters(keys);
702 }
703 return String8("");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700704}
705
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800706size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
707{
708 return mAudioHardware->getInputBufferSize(sampleRate, format, channelCount);
709}
710
Eric Laurent47d0a922010-02-26 02:47:27 -0800711unsigned int AudioFlinger::getInputFramesLost(int ioHandle)
712{
713 if (ioHandle == 0) {
714 return 0;
715 }
716
717 Mutex::Autolock _l(mLock);
718
719 RecordThread *recordThread = checkRecordThread_l(ioHandle);
720 if (recordThread != NULL) {
721 return recordThread->getInputFramesLost();
722 }
723 return 0;
724}
725
Eric Laurent415f3e22009-10-21 08:14:22 -0700726status_t AudioFlinger::setVoiceVolume(float value)
727{
728 // check calling permissions
729 if (!settingsAllowed()) {
730 return PERMISSION_DENIED;
731 }
732
733 AutoMutex lock(mHardwareLock);
734 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
735 status_t ret = mAudioHardware->setVoiceVolume(value);
736 mHardwareStatus = AUDIO_HW_IDLE;
737
738 return ret;
739}
740
Eric Laurent0986e792010-01-19 17:37:09 -0800741status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int output)
742{
743 status_t status;
744
745 Mutex::Autolock _l(mLock);
746
747 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
748 if (playbackThread != NULL) {
749 return playbackThread->getRenderPosition(halFrames, dspFrames);
750 }
751
752 return BAD_VALUE;
753}
754
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800755void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
756{
Eric Laurenta553c252009-07-17 12:17:14 -0700757
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800758 Mutex::Autolock _l(mLock);
759
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700760 int pid = IPCThreadState::self()->getCallingPid();
761 if (mNotificationClients.indexOfKey(pid) < 0) {
762 sp<NotificationClient> notificationClient = new NotificationClient(this,
763 client,
764 pid);
765 LOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Eric Laurenta553c252009-07-17 12:17:14 -0700766
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700767 mNotificationClients.add(pid, notificationClient);
Eric Laurenta553c252009-07-17 12:17:14 -0700768
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700769 sp<IBinder> binder = client->asBinder();
770 binder->linkToDeath(notificationClient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800771
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700772 // the config change is always sent from playback or record threads to avoid deadlock
773 // with AudioSystem::gLock
774 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
775 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
776 }
Eric Laurenta553c252009-07-17 12:17:14 -0700777
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700778 for (size_t i = 0; i < mRecordThreads.size(); i++) {
779 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800780 }
781 }
782}
783
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700784void AudioFlinger::removeNotificationClient(pid_t pid)
785{
786 Mutex::Autolock _l(mLock);
787
788 int index = mNotificationClients.indexOfKey(pid);
789 if (index >= 0) {
790 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
791 LOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
792#ifdef LVMX
793 if (pid == mLifeVibesClientPid) {
794 LOGV("Disabling lifevibes");
795 LifeVibes::enableMusic(false);
796 mLifeVibesClientPid = -1;
797 }
798#endif
799 mNotificationClients.removeItem(pid);
800 }
801}
802
Eric Laurent296a0ec2009-09-15 07:10:12 -0700803// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700804void AudioFlinger::audioConfigChanged_l(int event, int ioHandle, void *param2)
805{
Eric Laurent49f02be2009-11-19 09:00:56 -0800806 size_t size = mNotificationClients.size();
807 for (size_t i = 0; i < size; i++) {
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700808 mNotificationClients.valueAt(i)->client()->ioConfigChanged(event, ioHandle, param2);
Eric Laurenta553c252009-07-17 12:17:14 -0700809 }
810}
811
Eric Laurentb9481d82009-09-17 05:12:56 -0700812// removeClient_l() must be called with AudioFlinger::mLock held
813void AudioFlinger::removeClient_l(pid_t pid)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700814{
Eric Laurentb9481d82009-09-17 05:12:56 -0700815 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 -0700816 mClients.removeItem(pid);
817}
818
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700819
Eric Laurenta553c252009-07-17 12:17:14 -0700820// ----------------------------------------------------------------------------
821
Eric Laurent49f02be2009-11-19 09:00:56 -0800822AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, int id)
Eric Laurenta553c252009-07-17 12:17:14 -0700823 : Thread(false),
824 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
Eric Laurentb0a01472010-05-14 05:45:46 -0700825 mFrameSize(1), mFormat(0), mStandby(false), mId(id), mExiting(false)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700826{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800827}
828
Eric Laurenta553c252009-07-17 12:17:14 -0700829AudioFlinger::ThreadBase::~ThreadBase()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830{
Eric Laurent8fce46a2009-08-04 09:45:33 -0700831 mParamCond.broadcast();
832 mNewParameters.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800833}
834
Eric Laurenta553c252009-07-17 12:17:14 -0700835void AudioFlinger::ThreadBase::exit()
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700836{
Eric Laurentb7d94602009-09-29 11:12:57 -0700837 // keep a strong ref on ourself so that we wont get
Eric Laurenta553c252009-07-17 12:17:14 -0700838 // destroyed in the middle of requestExitAndWait()
839 sp <ThreadBase> strongMe = this;
840
841 LOGV("ThreadBase::exit");
842 {
843 AutoMutex lock(&mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -0800844 mExiting = true;
Eric Laurenta553c252009-07-17 12:17:14 -0700845 requestExit();
846 mWaitWorkCV.signal();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700847 }
Eric Laurenta553c252009-07-17 12:17:14 -0700848 requestExitAndWait();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700849}
Eric Laurenta553c252009-07-17 12:17:14 -0700850
851uint32_t AudioFlinger::ThreadBase::sampleRate() const
852{
853 return mSampleRate;
854}
855
856int AudioFlinger::ThreadBase::channelCount() const
857{
Eric Laurentb0a01472010-05-14 05:45:46 -0700858 return (int)mChannelCount;
Eric Laurenta553c252009-07-17 12:17:14 -0700859}
860
861int AudioFlinger::ThreadBase::format() const
862{
863 return mFormat;
864}
865
866size_t AudioFlinger::ThreadBase::frameCount() const
867{
868 return mFrameCount;
869}
870
871status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
872{
Eric Laurent8fce46a2009-08-04 09:45:33 -0700873 status_t status;
Eric Laurenta553c252009-07-17 12:17:14 -0700874
Eric Laurent8fce46a2009-08-04 09:45:33 -0700875 LOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Eric Laurenta553c252009-07-17 12:17:14 -0700876 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700877
Eric Laurent8fce46a2009-08-04 09:45:33 -0700878 mNewParameters.add(keyValuePairs);
Eric Laurenta553c252009-07-17 12:17:14 -0700879 mWaitWorkCV.signal();
Eric Laurentb7d94602009-09-29 11:12:57 -0700880 // wait condition with timeout in case the thread loop has exited
881 // before the request could be processed
882 if (mParamCond.waitRelative(mLock, seconds(2)) == NO_ERROR) {
883 status = mParamStatus;
884 mWaitWorkCV.signal();
885 } else {
886 status = TIMED_OUT;
887 }
Eric Laurent8fce46a2009-08-04 09:45:33 -0700888 return status;
Eric Laurenta553c252009-07-17 12:17:14 -0700889}
890
891void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
892{
893 Mutex::Autolock _l(mLock);
Eric Laurent8fce46a2009-08-04 09:45:33 -0700894 sendConfigEvent_l(event, param);
895}
896
897// sendConfigEvent_l() must be called with ThreadBase::mLock held
898void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
899{
Eric Laurenta553c252009-07-17 12:17:14 -0700900 ConfigEvent *configEvent = new ConfigEvent();
901 configEvent->mEvent = event;
902 configEvent->mParam = param;
903 mConfigEvents.add(configEvent);
904 LOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
905 mWaitWorkCV.signal();
906}
907
908void AudioFlinger::ThreadBase::processConfigEvents()
909{
910 mLock.lock();
911 while(!mConfigEvents.isEmpty()) {
912 LOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
913 ConfigEvent *configEvent = mConfigEvents[0];
914 mConfigEvents.removeAt(0);
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700915 // release mLock before locking AudioFlinger mLock: lock order is always
916 // AudioFlinger then ThreadBase to avoid cross deadlock
Eric Laurenta553c252009-07-17 12:17:14 -0700917 mLock.unlock();
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700918 mAudioFlinger->mLock.lock();
919 audioConfigChanged_l(configEvent->mEvent, configEvent->mParam);
920 mAudioFlinger->mLock.unlock();
Eric Laurenta553c252009-07-17 12:17:14 -0700921 delete configEvent;
922 mLock.lock();
923 }
924 mLock.unlock();
925}
926
Eric Laurent3fdb1262009-11-07 00:01:32 -0800927status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
928{
929 const size_t SIZE = 256;
930 char buffer[SIZE];
931 String8 result;
932
933 bool locked = tryLock(mLock);
934 if (!locked) {
935 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
936 write(fd, buffer, strlen(buffer));
937 }
938
939 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
940 result.append(buffer);
941 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
942 result.append(buffer);
943 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
944 result.append(buffer);
945 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
946 result.append(buffer);
947 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
948 result.append(buffer);
949 snprintf(buffer, SIZE, "Frame size: %d\n", mFrameSize);
950 result.append(buffer);
951
952 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
953 result.append(buffer);
954 result.append(" Index Command");
955 for (size_t i = 0; i < mNewParameters.size(); ++i) {
956 snprintf(buffer, SIZE, "\n %02d ", i);
957 result.append(buffer);
958 result.append(mNewParameters[i]);
959 }
960
961 snprintf(buffer, SIZE, "\n\nPending config events: \n");
962 result.append(buffer);
963 snprintf(buffer, SIZE, " Index event param\n");
964 result.append(buffer);
965 for (size_t i = 0; i < mConfigEvents.size(); i++) {
966 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i]->mEvent, mConfigEvents[i]->mParam);
967 result.append(buffer);
968 }
969 result.append("\n");
970
971 write(fd, result.string(), result.size());
972
973 if (locked) {
974 mLock.unlock();
975 }
976 return NO_ERROR;
977}
978
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800979
980// ----------------------------------------------------------------------------
981
Eric Laurent65b65452010-06-01 23:49:17 -0700982AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Eric Laurent49f02be2009-11-19 09:00:56 -0800983 : ThreadBase(audioFlinger, id),
Eric Laurentd5603c12009-08-06 08:49:39 -0700984 mMixBuffer(0), mSuspended(0), mBytesWritten(0), mOutput(output),
Eric Laurent65b65452010-06-01 23:49:17 -0700985 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
986 mDevice(device)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800987{
Eric Laurenta553c252009-07-17 12:17:14 -0700988 readOutputParameters();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800989
Eric Laurenta553c252009-07-17 12:17:14 -0700990 mMasterVolume = mAudioFlinger->masterVolume();
991 mMasterMute = mAudioFlinger->masterMute();
992
993 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
994 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
995 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800996 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800997}
998
Eric Laurenta553c252009-07-17 12:17:14 -0700999AudioFlinger::PlaybackThread::~PlaybackThread()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001000{
1001 delete [] mMixBuffer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001002}
1003
Eric Laurenta553c252009-07-17 12:17:14 -07001004status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001005{
1006 dumpInternals(fd, args);
1007 dumpTracks(fd, args);
Eric Laurent65b65452010-06-01 23:49:17 -07001008 dumpEffectChains(fd, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001009 return NO_ERROR;
1010}
1011
Eric Laurenta553c252009-07-17 12:17:14 -07001012status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001013{
1014 const size_t SIZE = 256;
1015 char buffer[SIZE];
1016 String8 result;
1017
Eric Laurenta553c252009-07-17 12:17:14 -07001018 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001019 result.append(buffer);
Eric Laurent65b65452010-06-01 23:49:17 -07001020 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 -08001021 for (size_t i = 0; i < mTracks.size(); ++i) {
Eric Laurentd3b4d0c2009-03-31 14:34:35 -07001022 sp<Track> track = mTracks[i];
1023 if (track != 0) {
1024 track->dump(buffer, SIZE);
1025 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001026 }
1027 }
1028
Eric Laurenta553c252009-07-17 12:17:14 -07001029 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001030 result.append(buffer);
Eric Laurent65b65452010-06-01 23:49:17 -07001031 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 -08001032 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Eric Laurentd3b4d0c2009-03-31 14:34:35 -07001033 wp<Track> wTrack = mActiveTracks[i];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001034 if (wTrack != 0) {
1035 sp<Track> track = wTrack.promote();
1036 if (track != 0) {
1037 track->dump(buffer, SIZE);
1038 result.append(buffer);
1039 }
1040 }
1041 }
1042 write(fd, result.string(), result.size());
1043 return NO_ERROR;
1044}
1045
Eric Laurent65b65452010-06-01 23:49:17 -07001046status_t AudioFlinger::PlaybackThread::dumpEffectChains(int fd, const Vector<String16>& args)
1047{
1048 const size_t SIZE = 256;
1049 char buffer[SIZE];
1050 String8 result;
1051
1052 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1053 write(fd, buffer, strlen(buffer));
1054
1055 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1056 sp<EffectChain> chain = mEffectChains[i];
1057 if (chain != 0) {
1058 chain->dump(fd, args);
1059 }
1060 }
1061 return NO_ERROR;
1062}
1063
Eric Laurenta553c252009-07-17 12:17:14 -07001064status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001065{
1066 const size_t SIZE = 256;
1067 char buffer[SIZE];
1068 String8 result;
1069
Eric Laurent3fdb1262009-11-07 00:01:32 -08001070 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001071 result.append(buffer);
1072 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1073 result.append(buffer);
1074 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1075 result.append(buffer);
1076 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1077 result.append(buffer);
1078 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1079 result.append(buffer);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08001080 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1081 result.append(buffer);
Eric Laurent65b65452010-06-01 23:49:17 -07001082 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1083 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001084 write(fd, result.string(), result.size());
Eric Laurent3fdb1262009-11-07 00:01:32 -08001085
1086 dumpBase(fd, args);
1087
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001088 return NO_ERROR;
1089}
1090
1091// Thread virtuals
Eric Laurenta553c252009-07-17 12:17:14 -07001092status_t AudioFlinger::PlaybackThread::readyToRun()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001093{
1094 if (mSampleRate == 0) {
1095 LOGE("No working audio driver found.");
1096 return NO_INIT;
1097 }
Eric Laurenta553c252009-07-17 12:17:14 -07001098 LOGI("AudioFlinger's thread %p ready to run", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001099 return NO_ERROR;
1100}
1101
Eric Laurenta553c252009-07-17 12:17:14 -07001102void AudioFlinger::PlaybackThread::onFirstRef()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001103{
1104 const size_t SIZE = 256;
1105 char buffer[SIZE];
1106
Eric Laurenta553c252009-07-17 12:17:14 -07001107 snprintf(buffer, SIZE, "Playback Thread %p", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001108
1109 run(buffer, ANDROID_PRIORITY_URGENT_AUDIO);
1110}
1111
Eric Laurenta553c252009-07-17 12:17:14 -07001112// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1113sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001114 const sp<AudioFlinger::Client>& client,
1115 int streamType,
1116 uint32_t sampleRate,
1117 int format,
1118 int channelCount,
1119 int frameCount,
1120 const sp<IMemory>& sharedBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -07001121 int sessionId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001122 status_t *status)
1123{
1124 sp<Track> track;
1125 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07001126
1127 if (mType == DIRECT) {
Eric Laurentb0a01472010-05-14 05:45:46 -07001128 if (sampleRate != mSampleRate || format != mFormat || channelCount != (int)mChannelCount) {
Eric Laurenta553c252009-07-17 12:17:14 -07001129 LOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelCount %d for output %p",
1130 sampleRate, format, channelCount, mOutput);
1131 lStatus = BAD_VALUE;
1132 goto Exit;
1133 }
1134 } else {
1135 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1136 if (sampleRate > mSampleRate*2) {
1137 LOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
1138 lStatus = BAD_VALUE;
1139 goto Exit;
1140 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001141 }
1142
Eric Laurenta553c252009-07-17 12:17:14 -07001143 if (mOutput == 0) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001144 LOGE("Audio driver not initialized.");
1145 lStatus = NO_INIT;
1146 goto Exit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001147 }
1148
Eric Laurenta553c252009-07-17 12:17:14 -07001149 { // scope for mLock
1150 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001151
1152 // all tracks in same audio session must share the same routing strategy otherwise
1153 // conflicts will happen when tracks are moved from one output to another by audio policy
1154 // manager
1155 uint32_t strategy =
1156 AudioSystem::getStrategyForStream((AudioSystem::stream_type)streamType);
1157 for (size_t i = 0; i < mTracks.size(); ++i) {
1158 sp<Track> t = mTracks[i];
1159 if (t != 0) {
1160 if (sessionId == t->sessionId() &&
1161 strategy != AudioSystem::getStrategyForStream((AudioSystem::stream_type)t->type())) {
1162 lStatus = BAD_VALUE;
1163 goto Exit;
1164 }
1165 }
1166 }
1167
Eric Laurenta553c252009-07-17 12:17:14 -07001168 track = new Track(this, client, streamType, sampleRate, format,
Eric Laurent65b65452010-06-01 23:49:17 -07001169 channelCount, frameCount, sharedBuffer, sessionId);
Eric Laurent73b60352009-11-09 04:45:39 -08001170 if (track->getCblk() == NULL || track->name() < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07001171 lStatus = NO_MEMORY;
1172 goto Exit;
1173 }
1174 mTracks.add(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001175
1176 sp<EffectChain> chain = getEffectChain_l(sessionId);
1177 if (chain != 0) {
1178 LOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1179 track->setMainBuffer(chain->inBuffer());
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001180 chain->setStrategy(AudioSystem::getStrategyForStream((AudioSystem::stream_type)track->type()));
Eric Laurent65b65452010-06-01 23:49:17 -07001181 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001182 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001183 lStatus = NO_ERROR;
1184
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001185Exit:
1186 if(status) {
1187 *status = lStatus;
1188 }
1189 return track;
1190}
1191
Eric Laurenta553c252009-07-17 12:17:14 -07001192uint32_t AudioFlinger::PlaybackThread::latency() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001193{
1194 if (mOutput) {
1195 return mOutput->latency();
1196 }
1197 else {
1198 return 0;
1199 }
1200}
1201
Eric Laurenta553c252009-07-17 12:17:14 -07001202status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001203{
Glenn Kasten871c16c2010-03-05 12:18:01 -08001204#ifdef LVMX
1205 int audioOutputType = LifeVibes::getMixerType(mId, mType);
1206 if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType)) {
1207 LifeVibes::setMasterVolume(audioOutputType, value);
1208 }
1209#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001210 mMasterVolume = value;
1211 return NO_ERROR;
1212}
1213
Eric Laurenta553c252009-07-17 12:17:14 -07001214status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001215{
Glenn Kasten871c16c2010-03-05 12:18:01 -08001216#ifdef LVMX
1217 int audioOutputType = LifeVibes::getMixerType(mId, mType);
1218 if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType)) {
1219 LifeVibes::setMasterMute(audioOutputType, muted);
1220 }
1221#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001222 mMasterMute = muted;
1223 return NO_ERROR;
1224}
1225
Eric Laurenta553c252009-07-17 12:17:14 -07001226float AudioFlinger::PlaybackThread::masterVolume() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001227{
1228 return mMasterVolume;
1229}
1230
Eric Laurenta553c252009-07-17 12:17:14 -07001231bool AudioFlinger::PlaybackThread::masterMute() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001232{
1233 return mMasterMute;
1234}
1235
Eric Laurenta553c252009-07-17 12:17:14 -07001236status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001237{
Glenn Kasten871c16c2010-03-05 12:18:01 -08001238#ifdef LVMX
1239 int audioOutputType = LifeVibes::getMixerType(mId, mType);
1240 if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType)) {
1241 LifeVibes::setStreamVolume(audioOutputType, stream, value);
1242 }
1243#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001244 mStreamTypes[stream].volume = value;
1245 return NO_ERROR;
1246}
1247
Eric Laurenta553c252009-07-17 12:17:14 -07001248status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001249{
Glenn Kasten871c16c2010-03-05 12:18:01 -08001250#ifdef LVMX
1251 int audioOutputType = LifeVibes::getMixerType(mId, mType);
1252 if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType)) {
1253 LifeVibes::setStreamMute(audioOutputType, stream, muted);
1254 }
1255#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001256 mStreamTypes[stream].mute = muted;
1257 return NO_ERROR;
1258}
1259
Eric Laurenta553c252009-07-17 12:17:14 -07001260float AudioFlinger::PlaybackThread::streamVolume(int stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001261{
1262 return mStreamTypes[stream].volume;
1263}
1264
Eric Laurenta553c252009-07-17 12:17:14 -07001265bool AudioFlinger::PlaybackThread::streamMute(int stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001266{
1267 return mStreamTypes[stream].mute;
1268}
1269
Eric Laurent23f25cd2010-01-25 08:49:09 -08001270bool AudioFlinger::PlaybackThread::isStreamActive(int stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001271{
Eric Laurenta553c252009-07-17 12:17:14 -07001272 Mutex::Autolock _l(mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001273 size_t count = mActiveTracks.size();
1274 for (size_t i = 0 ; i < count ; ++i) {
1275 sp<Track> t = mActiveTracks[i].promote();
1276 if (t == 0) continue;
1277 Track* const track = t.get();
Eric Laurent23f25cd2010-01-25 08:49:09 -08001278 if (t->type() == stream)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001279 return true;
1280 }
1281 return false;
1282}
1283
Eric Laurenta553c252009-07-17 12:17:14 -07001284// addTrack_l() must be called with ThreadBase::mLock held
1285status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001286{
1287 status_t status = ALREADY_EXISTS;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001288
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001289 // set retry count for buffer fill
1290 track->mRetryCount = kMaxTrackStartupRetries;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001291 if (mActiveTracks.indexOf(track) < 0) {
1292 // the track is newly added, make sure it fills up all its
1293 // buffers before playing. This is to ensure the client will
1294 // effectively get the latency it requested.
1295 track->mFillingUpStatus = Track::FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001296 track->mResetDone = false;
Eric Laurenta553c252009-07-17 12:17:14 -07001297 mActiveTracks.add(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001298 if (track->mainBuffer() != mMixBuffer) {
1299 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1300 if (chain != 0) {
1301 LOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
1302 chain->startTrack();
1303 }
1304 }
1305
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001306 status = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001307 }
Eric Laurenta553c252009-07-17 12:17:14 -07001308
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001309 LOGV("mWaitWorkCV.broadcast");
Eric Laurenta553c252009-07-17 12:17:14 -07001310 mWaitWorkCV.broadcast();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001311
1312 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001313}
1314
Eric Laurenta553c252009-07-17 12:17:14 -07001315// destroyTrack_l() must be called with ThreadBase::mLock held
1316void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001317{
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001318 track->mState = TrackBase::TERMINATED;
1319 if (mActiveTracks.indexOf(track) < 0) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001320 mTracks.remove(track);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001321 deleteTrackName_l(track->name());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001322 }
1323}
1324
Eric Laurenta553c252009-07-17 12:17:14 -07001325String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001326{
Eric Laurenta553c252009-07-17 12:17:14 -07001327 return mOutput->getParameters(keys);
1328}
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001329
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001330// destroyTrack_l() must be called with AudioFlinger::mLock held
1331void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
Eric Laurenta553c252009-07-17 12:17:14 -07001332 AudioSystem::OutputDescriptor desc;
1333 void *param2 = 0;
1334
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001335 LOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Eric Laurenta553c252009-07-17 12:17:14 -07001336
1337 switch (event) {
1338 case AudioSystem::OUTPUT_OPENED:
1339 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Eric Laurentb0a01472010-05-14 05:45:46 -07001340 desc.channels = mChannels;
Eric Laurenta553c252009-07-17 12:17:14 -07001341 desc.samplingRate = mSampleRate;
1342 desc.format = mFormat;
1343 desc.frameCount = mFrameCount;
1344 desc.latency = latency();
1345 param2 = &desc;
1346 break;
1347
1348 case AudioSystem::STREAM_CONFIG_CHANGED:
1349 param2 = &param;
1350 case AudioSystem::OUTPUT_CLOSED:
1351 default:
1352 break;
1353 }
Eric Laurent49f02be2009-11-19 09:00:56 -08001354 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurenta553c252009-07-17 12:17:14 -07001355}
1356
1357void AudioFlinger::PlaybackThread::readOutputParameters()
1358{
1359 mSampleRate = mOutput->sampleRate();
Eric Laurentb0a01472010-05-14 05:45:46 -07001360 mChannels = mOutput->channels();
1361 mChannelCount = (uint16_t)AudioSystem::popCount(mChannels);
Eric Laurenta553c252009-07-17 12:17:14 -07001362 mFormat = mOutput->format();
Eric Laurentb0a01472010-05-14 05:45:46 -07001363 mFrameSize = (uint16_t)mOutput->frameSize();
Eric Laurenta553c252009-07-17 12:17:14 -07001364 mFrameCount = mOutput->bufferSize() / mFrameSize;
1365
Eric Laurenta553c252009-07-17 12:17:14 -07001366 // FIXME - Current mixer implementation only supports stereo output: Always
1367 // Allocate a stereo buffer even if HW output is mono.
Eric Laurent65b65452010-06-01 23:49:17 -07001368 if (mMixBuffer != NULL) delete[] mMixBuffer;
Eric Laurenta553c252009-07-17 12:17:14 -07001369 mMixBuffer = new int16_t[mFrameCount * 2];
1370 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
Eric Laurent65b65452010-06-01 23:49:17 -07001371
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001372 // force reconfiguration of effect chains and engines to take new buffer size and audio
1373 // parameters into account
1374 // Note that mLock is not held when readOutputParameters() is called from the constructor
1375 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1376 // matter.
1377 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1378 Vector< sp<EffectChain> > effectChains = mEffectChains;
1379 for (size_t i = 0; i < effectChains.size(); i ++) {
1380 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this);
1381 }
Eric Laurenta553c252009-07-17 12:17:14 -07001382}
1383
Eric Laurent0986e792010-01-19 17:37:09 -08001384status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1385{
1386 if (halFrames == 0 || dspFrames == 0) {
1387 return BAD_VALUE;
1388 }
1389 if (mOutput == 0) {
1390 return INVALID_OPERATION;
1391 }
1392 *halFrames = mBytesWritten/mOutput->frameSize();
1393
1394 return mOutput->getRenderPosition(dspFrames);
1395}
1396
Eric Laurent65b65452010-06-01 23:49:17 -07001397bool AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
1398{
1399 Mutex::Autolock _l(mLock);
1400 if (getEffectChain_l(sessionId) != 0) {
1401 return true;
1402 }
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 Laurent65b65452010-06-01 23:49:17 -07001408 return true;
1409 }
1410 }
1411
1412 return false;
1413}
1414
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001415uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1416{
1417 // session AudioSystem::SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
1418 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
1419 if (sessionId == AudioSystem::SESSION_OUTPUT_MIX) {
1420 return AudioSystem::getStrategyForStream(AudioSystem::MUSIC);
1421 }
1422 for (size_t i = 0; i < mTracks.size(); i++) {
1423 sp<Track> track = mTracks[i];
1424 if (sessionId == track->sessionId() &&
1425 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
1426 return AudioSystem::getStrategyForStream((AudioSystem::stream_type) track->type());
1427 }
1428 }
1429 return AudioSystem::getStrategyForStream(AudioSystem::MUSIC);
1430}
1431
Eric Laurent65b65452010-06-01 23:49:17 -07001432sp<AudioFlinger::EffectChain> AudioFlinger::PlaybackThread::getEffectChain(int sessionId)
1433{
1434 Mutex::Autolock _l(mLock);
1435 return getEffectChain_l(sessionId);
1436}
1437
1438sp<AudioFlinger::EffectChain> AudioFlinger::PlaybackThread::getEffectChain_l(int sessionId)
1439{
1440 sp<EffectChain> chain;
1441
1442 size_t size = mEffectChains.size();
1443 for (size_t i = 0; i < size; i++) {
1444 if (mEffectChains[i]->sessionId() == sessionId) {
1445 chain = mEffectChains[i];
1446 break;
1447 }
1448 }
1449 return chain;
1450}
1451
Eric Laurent53334cd2010-06-23 17:38:20 -07001452void AudioFlinger::PlaybackThread::setMode(uint32_t mode)
1453{
1454 Mutex::Autolock _l(mLock);
1455 size_t size = mEffectChains.size();
1456 for (size_t i = 0; i < size; i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07001457 mEffectChains[i]->setMode_l(mode);
Eric Laurent53334cd2010-06-23 17:38:20 -07001458 }
1459}
1460
Eric Laurenta553c252009-07-17 12:17:14 -07001461// ----------------------------------------------------------------------------
1462
Eric Laurent65b65452010-06-01 23:49:17 -07001463AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
1464 : PlaybackThread(audioFlinger, output, id, device),
Eric Laurenta553c252009-07-17 12:17:14 -07001465 mAudioMixer(0)
1466{
1467 mType = PlaybackThread::MIXER;
1468 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1469
1470 // FIXME - Current mixer implementation only supports stereo output
1471 if (mChannelCount == 1) {
1472 LOGE("Invalid audio hardware channel count");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001473 }
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001474}
1475
Eric Laurenta553c252009-07-17 12:17:14 -07001476AudioFlinger::MixerThread::~MixerThread()
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001477{
Eric Laurenta553c252009-07-17 12:17:14 -07001478 delete mAudioMixer;
1479}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001480
Eric Laurenta553c252009-07-17 12:17:14 -07001481bool AudioFlinger::MixerThread::threadLoop()
1482{
Eric Laurenta553c252009-07-17 12:17:14 -07001483 Vector< sp<Track> > tracksToRemove;
Eric Laurent059b4be2009-11-09 23:32:22 -08001484 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001485 nsecs_t standbyTime = systemTime();
1486 size_t mixBufferSize = mFrameCount * mFrameSize;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001487 // FIXME: Relaxed timing because of a certain device that can't meet latency
1488 // Should be reduced to 2x after the vendor fixes the driver issue
1489 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
1490 nsecs_t lastWarning = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08001491 bool longStandbyExit = false;
1492 uint32_t activeSleepTime = activeSleepTimeUs();
1493 uint32_t idleSleepTime = idleSleepTimeUs();
1494 uint32_t sleepTime = idleSleepTime;
Eric Laurent65b65452010-06-01 23:49:17 -07001495 Vector< sp<EffectChain> > effectChains;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001496
Eric Laurenta553c252009-07-17 12:17:14 -07001497 while (!exitPending())
1498 {
1499 processConfigEvents();
1500
Eric Laurent059b4be2009-11-09 23:32:22 -08001501 mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001502 { // scope for mLock
1503
1504 Mutex::Autolock _l(mLock);
1505
1506 if (checkForNewParameters_l()) {
1507 mixBufferSize = mFrameCount * mFrameSize;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001508 // FIXME: Relaxed timing because of a certain device that can't meet latency
1509 // Should be reduced to 2x after the vendor fixes the driver issue
1510 maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
Eric Laurent059b4be2009-11-09 23:32:22 -08001511 activeSleepTime = activeSleepTimeUs();
1512 idleSleepTime = idleSleepTimeUs();
Eric Laurenta553c252009-07-17 12:17:14 -07001513 }
1514
1515 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1516
1517 // put audio hardware into standby after short delay
1518 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1519 mSuspended) {
1520 if (!mStandby) {
1521 LOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
1522 mOutput->standby();
1523 mStandby = true;
1524 mBytesWritten = 0;
1525 }
1526
1527 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1528 // we're about to wait, flush the binder command buffer
1529 IPCThreadState::self()->flushCommands();
1530
1531 if (exitPending()) break;
1532
1533 // wait until we have something to do...
1534 LOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
1535 mWaitWorkCV.wait(mLock);
1536 LOGV("MixerThread %p TID %d waking up\n", this, gettid());
1537
1538 if (mMasterMute == false) {
1539 char value[PROPERTY_VALUE_MAX];
1540 property_get("ro.audio.silent", value, "0");
1541 if (atoi(value)) {
1542 LOGD("Silence is golden");
1543 setMasterMute(true);
1544 }
1545 }
1546
1547 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent059b4be2009-11-09 23:32:22 -08001548 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07001549 continue;
1550 }
1551 }
1552
Eric Laurent059b4be2009-11-09 23:32:22 -08001553 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07001554
1555 // prevent any changes in effect chain list and in each effect chain
1556 // during mixing and effect process as the audio buffers could be deleted
1557 // or modified if an effect is created or deleted
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001558 lockEffectChains_l(effectChains);
Eric Laurenta553c252009-07-17 12:17:14 -07001559 }
1560
Eric Laurent059b4be2009-11-09 23:32:22 -08001561 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07001562 // mix buffers...
Eric Laurent65b65452010-06-01 23:49:17 -07001563 mAudioMixer->process();
Eric Laurentf69a3f82009-09-22 00:35:48 -07001564 sleepTime = 0;
1565 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent65b65452010-06-01 23:49:17 -07001566 //TODO: delay standby when effects have a tail
Eric Laurent96c08a62009-09-07 08:38:38 -07001567 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07001568 // If no tracks are ready, sleep once for the duration of an output
1569 // buffer size, then write 0s to the output
1570 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08001571 if (mixerStatus == MIXER_TRACKS_ENABLED) {
1572 sleepTime = activeSleepTime;
1573 } else {
1574 sleepTime = idleSleepTime;
1575 }
1576 } else if (mBytesWritten != 0 ||
1577 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Eric Laurent65b65452010-06-01 23:49:17 -07001578 memset (mMixBuffer, 0, mixBufferSize);
Eric Laurent96c08a62009-09-07 08:38:38 -07001579 sleepTime = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08001580 LOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Eric Laurent96c08a62009-09-07 08:38:38 -07001581 }
Eric Laurent65b65452010-06-01 23:49:17 -07001582 // TODO add standby time extension fct of effect tail
Eric Laurentf69a3f82009-09-22 00:35:48 -07001583 }
1584
1585 if (mSuspended) {
Eric Laurent059b4be2009-11-09 23:32:22 -08001586 sleepTime = idleSleepTime;
Eric Laurentf69a3f82009-09-22 00:35:48 -07001587 }
1588 // sleepTime == 0 means we must write to audio hardware
1589 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07001590 for (size_t i = 0; i < effectChains.size(); i ++) {
1591 effectChains[i]->process_l();
1592 }
1593 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001594 unlockEffectChains(effectChains);
Glenn Kasten871c16c2010-03-05 12:18:01 -08001595#ifdef LVMX
1596 int audioOutputType = LifeVibes::getMixerType(mId, mType);
1597 if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType)) {
Eric Laurent65b65452010-06-01 23:49:17 -07001598 LifeVibes::process(audioOutputType, mMixBuffer, mixBufferSize);
Glenn Kasten871c16c2010-03-05 12:18:01 -08001599 }
1600#endif
Eric Laurent65b65452010-06-01 23:49:17 -07001601 mLastWriteTime = systemTime();
1602 mInWrite = true;
1603 mBytesWritten += mixBufferSize;
1604
1605 int bytesWritten = (int)mOutput->write(mMixBuffer, mixBufferSize);
Eric Laurent0986e792010-01-19 17:37:09 -08001606 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07001607 mNumWrites++;
1608 mInWrite = false;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001609 nsecs_t now = systemTime();
1610 nsecs_t delta = now - mLastWriteTime;
Eric Laurentf69a3f82009-09-22 00:35:48 -07001611 if (delta > maxPeriod) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07001612 mNumDelayedWrites++;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001613 if ((now - lastWarning) > kWarningThrottle) {
1614 LOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
1615 ns2ms(delta), mNumDelayedWrites, this);
1616 lastWarning = now;
1617 }
Eric Laurent059b4be2009-11-09 23:32:22 -08001618 if (mStandby) {
1619 longStandbyExit = true;
1620 }
Eric Laurenta553c252009-07-17 12:17:14 -07001621 }
Eric Laurent059b4be2009-11-09 23:32:22 -08001622 mStandby = false;
Eric Laurentf69a3f82009-09-22 00:35:48 -07001623 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07001624 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001625 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07001626 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07001627 }
1628
1629 // finally let go of all our tracks, without the lock held
1630 // since we can't guarantee the destructors won't acquire that
1631 // same lock.
1632 tracksToRemove.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07001633
1634 // Effect chains will be actually deleted here if they were removed from
1635 // mEffectChains list during mixing or effects processing
1636 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07001637 }
1638
1639 if (!mStandby) {
1640 mOutput->standby();
1641 }
Eric Laurenta553c252009-07-17 12:17:14 -07001642
1643 LOGV("MixerThread %p exiting", this);
1644 return false;
1645}
1646
1647// prepareTracks_l() must be called with ThreadBase::mLock held
Eric Laurent059b4be2009-11-09 23:32:22 -08001648uint32_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
Eric Laurenta553c252009-07-17 12:17:14 -07001649{
1650
Eric Laurent059b4be2009-11-09 23:32:22 -08001651 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001652 // find out which tracks need to be processed
1653 size_t count = activeTracks.size();
Eric Laurent65b65452010-06-01 23:49:17 -07001654 size_t mixedTracks = 0;
1655 size_t tracksWithEffect = 0;
Glenn Kasten871c16c2010-03-05 12:18:01 -08001656
1657 float masterVolume = mMasterVolume;
1658 bool masterMute = mMasterMute;
1659
1660#ifdef LVMX
1661 bool tracksConnectedChanged = false;
1662 bool stateChanged = false;
1663
1664 int audioOutputType = LifeVibes::getMixerType(mId, mType);
1665 if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType))
1666 {
1667 int activeTypes = 0;
1668 for (size_t i=0 ; i<count ; i++) {
1669 sp<Track> t = activeTracks[i].promote();
1670 if (t == 0) continue;
1671 Track* const track = t.get();
1672 int iTracktype=track->type();
1673 activeTypes |= 1<<track->type();
1674 }
1675 LifeVibes::computeVolumes(audioOutputType, activeTypes, tracksConnectedChanged, stateChanged, masterVolume, masterMute);
1676 }
1677#endif
Eric Laurent65b65452010-06-01 23:49:17 -07001678 // Delegate master volume control to effect in output mix effect chain if needed
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001679 sp<EffectChain> chain = getEffectChain_l(AudioSystem::SESSION_OUTPUT_MIX);
Eric Laurent65b65452010-06-01 23:49:17 -07001680 if (chain != 0) {
1681 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurent76c40f72010-07-15 12:50:15 -07001682 chain->setVolume_l(&v, &v);
Eric Laurent65b65452010-06-01 23:49:17 -07001683 masterVolume = (float)((v + (1 << 23)) >> 24);
1684 chain.clear();
1685 }
Glenn Kasten871c16c2010-03-05 12:18:01 -08001686
Eric Laurenta553c252009-07-17 12:17:14 -07001687 for (size_t i=0 ; i<count ; i++) {
1688 sp<Track> t = activeTracks[i].promote();
1689 if (t == 0) continue;
1690
1691 Track* const track = t.get();
1692 audio_track_cblk_t* cblk = track->cblk();
1693
1694 // The first time a track is added we wait
1695 // for all its buffers to be filled before processing it
1696 mAudioMixer->setActiveTrack(track->name());
1697 if (cblk->framesReady() && (track->isReady() || track->isStopped()) &&
Eric Laurent71f37cd2010-03-31 12:21:17 -07001698 !track->isPaused() && !track->isTerminated())
Eric Laurenta553c252009-07-17 12:17:14 -07001699 {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08001700 //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 -07001701
Eric Laurent65b65452010-06-01 23:49:17 -07001702 mixedTracks++;
1703
1704 // track->mainBuffer() != mMixBuffer means there is an effect chain
1705 // connected to the track
1706 chain.clear();
1707 if (track->mainBuffer() != mMixBuffer) {
1708 chain = getEffectChain_l(track->sessionId());
1709 // Delegate volume control to effect in track effect chain if needed
1710 if (chain != 0) {
1711 tracksWithEffect++;
1712 } else {
1713 LOGW("prepareTracks_l(): track %08x attached to effect but no chain found on session %d",
1714 track->name(), track->sessionId());
1715 }
1716 }
1717
1718
1719 int param = AudioMixer::VOLUME;
1720 if (track->mFillingUpStatus == Track::FS_FILLED) {
1721 // no ramp for the first volume setting
1722 track->mFillingUpStatus = Track::FS_ACTIVE;
1723 if (track->mState == TrackBase::RESUMING) {
1724 track->mState = TrackBase::ACTIVE;
1725 param = AudioMixer::RAMP_VOLUME;
1726 }
1727 } else if (cblk->server != 0) {
1728 // If the track is stopped before the first frame was mixed,
1729 // do not apply ramp
1730 param = AudioMixer::RAMP_VOLUME;
1731 }
1732
Eric Laurenta553c252009-07-17 12:17:14 -07001733 // compute volume for this track
Eric Laurent65b65452010-06-01 23:49:17 -07001734 int16_t left, right, aux;
Glenn Kasten871c16c2010-03-05 12:18:01 -08001735 if (track->isMuted() || masterMute || track->isPausing() ||
Eric Laurenta553c252009-07-17 12:17:14 -07001736 mStreamTypes[track->type()].mute) {
Eric Laurent65b65452010-06-01 23:49:17 -07001737 left = right = aux = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07001738 if (track->isPausing()) {
1739 track->setPaused();
1740 }
1741 } else {
Glenn Kasten871c16c2010-03-05 12:18:01 -08001742 // read original volumes with volume control
Eric Laurenta553c252009-07-17 12:17:14 -07001743 float typeVolume = mStreamTypes[track->type()].volume;
Glenn Kasten871c16c2010-03-05 12:18:01 -08001744#ifdef LVMX
1745 bool streamMute=false;
1746 // read the volume from the LivesVibes audio engine.
1747 if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType))
1748 {
1749 LifeVibes::getStreamVolumes(audioOutputType, track->type(), &typeVolume, &streamMute);
1750 if (streamMute) {
1751 typeVolume = 0;
1752 }
1753 }
1754#endif
1755 float v = masterVolume * typeVolume;
Eric Laurent65b65452010-06-01 23:49:17 -07001756 uint32_t vl = (uint32_t)(v * cblk->volume[0]) << 12;
1757 uint32_t vr = (uint32_t)(v * cblk->volume[1]) << 12;
Eric Laurenta553c252009-07-17 12:17:14 -07001758
Eric Laurent65b65452010-06-01 23:49:17 -07001759 // Delegate volume control to effect in track effect chain if needed
Eric Laurent76c40f72010-07-15 12:50:15 -07001760 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
Eric Laurent65b65452010-06-01 23:49:17 -07001761 // Do not ramp volume is volume is controlled by effect
1762 param = AudioMixer::VOLUME;
Eric Laurenta553c252009-07-17 12:17:14 -07001763 }
Eric Laurent65b65452010-06-01 23:49:17 -07001764
1765 // Convert volumes from 8.24 to 4.12 format
1766 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
1767 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
1768 left = int16_t(v_clamped);
1769 v_clamped = (vr + (1 << 11)) >> 12;
1770 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
1771 right = int16_t(v_clamped);
1772
1773 v_clamped = (uint32_t)(v * cblk->sendLevel);
1774 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
1775 aux = int16_t(v_clamped);
Eric Laurenta553c252009-07-17 12:17:14 -07001776 }
Eric Laurent65b65452010-06-01 23:49:17 -07001777
Glenn Kasten871c16c2010-03-05 12:18:01 -08001778#ifdef LVMX
1779 if ( tracksConnectedChanged || stateChanged )
1780 {
1781 // only do the ramp when the volume is changed by the user / application
1782 param = AudioMixer::VOLUME;
1783 }
1784#endif
Eric Laurent65b65452010-06-01 23:49:17 -07001785
1786 // XXX: these things DON'T need to be done each time
1787 mAudioMixer->setBufferProvider(track);
1788 mAudioMixer->enable(AudioMixer::MIXING);
1789
1790 mAudioMixer->setParameter(param, AudioMixer::VOLUME0, (void *)left);
1791 mAudioMixer->setParameter(param, AudioMixer::VOLUME1, (void *)right);
1792 mAudioMixer->setParameter(param, AudioMixer::AUXLEVEL, (void *)aux);
Eric Laurenta553c252009-07-17 12:17:14 -07001793 mAudioMixer->setParameter(
1794 AudioMixer::TRACK,
Eric Laurent65b65452010-06-01 23:49:17 -07001795 AudioMixer::FORMAT, (void *)track->format());
Eric Laurenta553c252009-07-17 12:17:14 -07001796 mAudioMixer->setParameter(
1797 AudioMixer::TRACK,
Eric Laurent65b65452010-06-01 23:49:17 -07001798 AudioMixer::CHANNEL_COUNT, (void *)track->channelCount());
Eric Laurenta553c252009-07-17 12:17:14 -07001799 mAudioMixer->setParameter(
1800 AudioMixer::RESAMPLE,
1801 AudioMixer::SAMPLE_RATE,
Eric Laurent65b65452010-06-01 23:49:17 -07001802 (void *)(cblk->sampleRate));
1803 mAudioMixer->setParameter(
1804 AudioMixer::TRACK,
1805 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
1806 mAudioMixer->setParameter(
1807 AudioMixer::TRACK,
1808 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
Eric Laurenta553c252009-07-17 12:17:14 -07001809
1810 // reset retry count
1811 track->mRetryCount = kMaxTrackRetries;
Eric Laurent059b4be2009-11-09 23:32:22 -08001812 mixerStatus = MIXER_TRACKS_READY;
Eric Laurenta553c252009-07-17 12:17:14 -07001813 } else {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08001814 //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 -07001815 if (track->isStopped()) {
1816 track->reset();
1817 }
1818 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
1819 // We have consumed all the buffers of this track.
1820 // Remove it from the list of active tracks.
1821 tracksToRemove->add(track);
Eric Laurenta553c252009-07-17 12:17:14 -07001822 } else {
1823 // No buffers for this track. Give it a few chances to
1824 // fill a buffer, then remove it from active list.
1825 if (--(track->mRetryCount) <= 0) {
Eric Laurent62443f52009-10-05 20:29:18 -07001826 LOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", track->name(), this);
Eric Laurenta553c252009-07-17 12:17:14 -07001827 tracksToRemove->add(track);
Eric Laurent059b4be2009-11-09 23:32:22 -08001828 } else if (mixerStatus != MIXER_TRACKS_READY) {
1829 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07001830 }
Eric Laurenta553c252009-07-17 12:17:14 -07001831 }
Eric Laurent65b65452010-06-01 23:49:17 -07001832 mAudioMixer->disable(AudioMixer::MIXING);
Eric Laurenta553c252009-07-17 12:17:14 -07001833 }
1834 }
1835
1836 // remove all the tracks that need to be...
1837 count = tracksToRemove->size();
1838 if (UNLIKELY(count)) {
1839 for (size_t i=0 ; i<count ; i++) {
1840 const sp<Track>& track = tracksToRemove->itemAt(i);
1841 mActiveTracks.remove(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001842 if (track->mainBuffer() != mMixBuffer) {
1843 chain = getEffectChain_l(track->sessionId());
1844 if (chain != 0) {
1845 LOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
1846 chain->stopTrack();
1847 }
1848 }
Eric Laurenta553c252009-07-17 12:17:14 -07001849 if (track->isTerminated()) {
1850 mTracks.remove(track);
1851 deleteTrackName_l(track->mName);
1852 }
1853 }
1854 }
1855
Eric Laurent65b65452010-06-01 23:49:17 -07001856 // mix buffer must be cleared if all tracks are connected to an
1857 // effect chain as in this case the mixer will not write to
1858 // mix buffer and track effects will accumulate into it
1859 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
1860 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
1861 }
1862
Eric Laurent059b4be2009-11-09 23:32:22 -08001863 return mixerStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07001864}
1865
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001866void AudioFlinger::MixerThread::invalidateTracks(int streamType)
Eric Laurenta553c252009-07-17 12:17:14 -07001867{
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001868 LOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
1869 this, streamType, mTracks.size());
Eric Laurenta553c252009-07-17 12:17:14 -07001870 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001871
Eric Laurenta553c252009-07-17 12:17:14 -07001872 size_t size = mTracks.size();
1873 for (size_t i = 0; i < size; i++) {
1874 sp<Track> t = mTracks[i];
1875 if (t->type() == streamType) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001876 t->mCblk->lock.lock();
1877 t->mCblk->flags |= CBLK_INVALID_ON;
1878 t->mCblk->cv.signal();
1879 t->mCblk->lock.unlock();
Eric Laurenta553c252009-07-17 12:17:14 -07001880 }
Eric Laurent53334cd2010-06-23 17:38:20 -07001881 }
1882}
Eric Laurenta553c252009-07-17 12:17:14 -07001883
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001884
Eric Laurenta553c252009-07-17 12:17:14 -07001885// getTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001886int AudioFlinger::MixerThread::getTrackName_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001887{
1888 return mAudioMixer->getTrackName();
1889}
1890
Eric Laurenta553c252009-07-17 12:17:14 -07001891// deleteTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001892void AudioFlinger::MixerThread::deleteTrackName_l(int name)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001893{
Eric Laurent0a080292009-12-07 10:53:10 -08001894 LOGV("remove track (%d) and delete from mixer", name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001895 mAudioMixer->deleteTrackName(name);
1896}
1897
Eric Laurenta553c252009-07-17 12:17:14 -07001898// checkForNewParameters_l() must be called with ThreadBase::mLock held
1899bool AudioFlinger::MixerThread::checkForNewParameters_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001900{
Eric Laurenta553c252009-07-17 12:17:14 -07001901 bool reconfig = false;
1902
Eric Laurent8fce46a2009-08-04 09:45:33 -07001903 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07001904 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07001905 String8 keyValuePair = mNewParameters[0];
1906 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07001907 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07001908
Eric Laurenta553c252009-07-17 12:17:14 -07001909 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
1910 reconfig = true;
1911 }
1912 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
1913 if (value != AudioSystem::PCM_16_BIT) {
1914 status = BAD_VALUE;
1915 } else {
1916 reconfig = true;
1917 }
1918 }
1919 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
1920 if (value != AudioSystem::CHANNEL_OUT_STEREO) {
1921 status = BAD_VALUE;
1922 } else {
1923 reconfig = true;
1924 }
1925 }
1926 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
1927 // do not accept frame count changes if tracks are open as the track buffer
1928 // size depends on frame count and correct behavior would not be garantied
1929 // if frame count is changed after track creation
1930 if (!mTracks.isEmpty()) {
1931 status = INVALID_OPERATION;
1932 } else {
1933 reconfig = true;
1934 }
1935 }
Eric Laurent65b65452010-06-01 23:49:17 -07001936 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
1937 // forward device change to effects that have requested to be
1938 // aware of attached audio device.
1939 mDevice = (uint32_t)value;
1940 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07001941 mEffectChains[i]->setDevice_l(mDevice);
Eric Laurent65b65452010-06-01 23:49:17 -07001942 }
1943 }
1944
Eric Laurenta553c252009-07-17 12:17:14 -07001945 if (status == NO_ERROR) {
Eric Laurent8fce46a2009-08-04 09:45:33 -07001946 status = mOutput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07001947 if (!mStandby && status == INVALID_OPERATION) {
1948 mOutput->standby();
1949 mStandby = true;
1950 mBytesWritten = 0;
Eric Laurent8fce46a2009-08-04 09:45:33 -07001951 status = mOutput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07001952 }
1953 if (status == NO_ERROR && reconfig) {
1954 delete mAudioMixer;
1955 readOutputParameters();
1956 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1957 for (size_t i = 0; i < mTracks.size() ; i++) {
1958 int name = getTrackName_l();
1959 if (name < 0) break;
1960 mTracks[i]->mName = name;
Eric Laurent6f7e0972009-08-10 08:15:12 -07001961 // limit track sample rate to 2 x new output sample rate
1962 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
1963 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
1964 }
Eric Laurenta553c252009-07-17 12:17:14 -07001965 }
Eric Laurent8fce46a2009-08-04 09:45:33 -07001966 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07001967 }
1968 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08001969
1970 mNewParameters.removeAt(0);
1971
Eric Laurenta553c252009-07-17 12:17:14 -07001972 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07001973 mParamCond.signal();
Eric Laurent8fce46a2009-08-04 09:45:33 -07001974 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07001975 }
1976 return reconfig;
1977}
1978
1979status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
1980{
1981 const size_t SIZE = 256;
1982 char buffer[SIZE];
1983 String8 result;
1984
1985 PlaybackThread::dumpInternals(fd, args);
1986
1987 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
1988 result.append(buffer);
1989 write(fd, result.string(), result.size());
1990 return NO_ERROR;
1991}
1992
Eric Laurent059b4be2009-11-09 23:32:22 -08001993uint32_t AudioFlinger::MixerThread::activeSleepTimeUs()
Eric Laurent62443f52009-10-05 20:29:18 -07001994{
Eric Laurent059b4be2009-11-09 23:32:22 -08001995 return (uint32_t)(mOutput->latency() * 1000) / 2;
1996}
1997
1998uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
1999{
2000 return (uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000;
Eric Laurent62443f52009-10-05 20:29:18 -07002001}
2002
Eric Laurenta553c252009-07-17 12:17:14 -07002003// ----------------------------------------------------------------------------
Eric Laurent65b65452010-06-01 23:49:17 -07002004AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
2005 : PlaybackThread(audioFlinger, output, id, device)
Eric Laurenta553c252009-07-17 12:17:14 -07002006{
2007 mType = PlaybackThread::DIRECT;
2008}
2009
2010AudioFlinger::DirectOutputThread::~DirectOutputThread()
2011{
2012}
2013
2014
Eric Laurent65b65452010-06-01 23:49:17 -07002015static inline int16_t clamp16(int32_t sample)
2016{
2017 if ((sample>>15) ^ (sample>>31))
2018 sample = 0x7FFF ^ (sample>>31);
2019 return sample;
2020}
2021
2022static inline
2023int32_t mul(int16_t in, int16_t v)
2024{
2025#if defined(__arm__) && !defined(__thumb__)
2026 int32_t out;
2027 asm( "smulbb %[out], %[in], %[v] \n"
2028 : [out]"=r"(out)
2029 : [in]"%r"(in), [v]"r"(v)
2030 : );
2031 return out;
2032#else
2033 return in * int32_t(v);
2034#endif
2035}
2036
2037void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2038{
2039 // Do not apply volume on compressed audio
2040 if (!AudioSystem::isLinearPCM(mFormat)) {
2041 return;
2042 }
2043
2044 // convert to signed 16 bit before volume calculation
2045 if (mFormat == AudioSystem::PCM_8_BIT) {
2046 size_t count = mFrameCount * mChannelCount;
2047 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2048 int16_t *dst = mMixBuffer + count-1;
2049 while(count--) {
2050 *dst-- = (int16_t)(*src--^0x80) << 8;
2051 }
2052 }
2053
2054 size_t frameCount = mFrameCount;
2055 int16_t *out = mMixBuffer;
2056 if (ramp) {
2057 if (mChannelCount == 1) {
2058 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2059 int32_t vlInc = d / (int32_t)frameCount;
2060 int32_t vl = ((int32_t)mLeftVolShort << 16);
2061 do {
2062 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2063 out++;
2064 vl += vlInc;
2065 } while (--frameCount);
2066
2067 } else {
2068 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2069 int32_t vlInc = d / (int32_t)frameCount;
2070 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2071 int32_t vrInc = d / (int32_t)frameCount;
2072 int32_t vl = ((int32_t)mLeftVolShort << 16);
2073 int32_t vr = ((int32_t)mRightVolShort << 16);
2074 do {
2075 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2076 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2077 out += 2;
2078 vl += vlInc;
2079 vr += vrInc;
2080 } while (--frameCount);
2081 }
2082 } else {
2083 if (mChannelCount == 1) {
2084 do {
2085 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2086 out++;
2087 } while (--frameCount);
2088 } else {
2089 do {
2090 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2091 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2092 out += 2;
2093 } while (--frameCount);
2094 }
2095 }
2096
2097 // convert back to unsigned 8 bit after volume calculation
2098 if (mFormat == AudioSystem::PCM_8_BIT) {
2099 size_t count = mFrameCount * mChannelCount;
2100 int16_t *src = mMixBuffer;
2101 uint8_t *dst = (uint8_t *)mMixBuffer;
2102 while(count--) {
2103 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2104 }
2105 }
2106
2107 mLeftVolShort = leftVol;
2108 mRightVolShort = rightVol;
2109}
2110
Eric Laurenta553c252009-07-17 12:17:14 -07002111bool AudioFlinger::DirectOutputThread::threadLoop()
2112{
Eric Laurent059b4be2009-11-09 23:32:22 -08002113 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002114 sp<Track> trackToRemove;
2115 sp<Track> activeTrack;
2116 nsecs_t standbyTime = systemTime();
2117 int8_t *curBuf;
2118 size_t mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent059b4be2009-11-09 23:32:22 -08002119 uint32_t activeSleepTime = activeSleepTimeUs();
2120 uint32_t idleSleepTime = idleSleepTimeUs();
2121 uint32_t sleepTime = idleSleepTime;
Eric Laurentef9500f2010-03-11 14:47:00 -08002122 // use shorter standby delay as on normal output to release
2123 // hardware resources as soon as possible
2124 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
Eric Laurent059b4be2009-11-09 23:32:22 -08002125
Eric Laurenta553c252009-07-17 12:17:14 -07002126 while (!exitPending())
2127 {
Eric Laurent65b65452010-06-01 23:49:17 -07002128 bool rampVolume;
2129 uint16_t leftVol;
2130 uint16_t rightVol;
2131 Vector< sp<EffectChain> > effectChains;
2132
Eric Laurenta553c252009-07-17 12:17:14 -07002133 processConfigEvents();
2134
Eric Laurent059b4be2009-11-09 23:32:22 -08002135 mixerStatus = MIXER_IDLE;
2136
Eric Laurenta553c252009-07-17 12:17:14 -07002137 { // scope for the mLock
2138
2139 Mutex::Autolock _l(mLock);
2140
2141 if (checkForNewParameters_l()) {
2142 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent059b4be2009-11-09 23:32:22 -08002143 activeSleepTime = activeSleepTimeUs();
2144 idleSleepTime = idleSleepTimeUs();
Eric Laurentef9500f2010-03-11 14:47:00 -08002145 standbyDelay = microseconds(activeSleepTime*2);
Eric Laurenta553c252009-07-17 12:17:14 -07002146 }
2147
2148 // put audio hardware into standby after short delay
2149 if UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2150 mSuspended) {
2151 // wait until we have something to do...
2152 if (!mStandby) {
2153 LOGV("Audio hardware entering standby, mixer %p\n", this);
2154 mOutput->standby();
2155 mStandby = true;
2156 mBytesWritten = 0;
2157 }
2158
2159 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2160 // we're about to wait, flush the binder command buffer
2161 IPCThreadState::self()->flushCommands();
2162
2163 if (exitPending()) break;
2164
2165 LOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
2166 mWaitWorkCV.wait(mLock);
2167 LOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
2168
2169 if (mMasterMute == false) {
2170 char value[PROPERTY_VALUE_MAX];
2171 property_get("ro.audio.silent", value, "0");
2172 if (atoi(value)) {
2173 LOGD("Silence is golden");
2174 setMasterMute(true);
2175 }
2176 }
2177
Eric Laurentef9500f2010-03-11 14:47:00 -08002178 standbyTime = systemTime() + standbyDelay;
Eric Laurent059b4be2009-11-09 23:32:22 -08002179 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07002180 continue;
2181 }
2182 }
2183
Eric Laurent65b65452010-06-01 23:49:17 -07002184 effectChains = mEffectChains;
2185
Eric Laurenta553c252009-07-17 12:17:14 -07002186 // find out which tracks need to be processed
2187 if (mActiveTracks.size() != 0) {
2188 sp<Track> t = mActiveTracks[0].promote();
2189 if (t == 0) continue;
2190
2191 Track* const track = t.get();
2192 audio_track_cblk_t* cblk = track->cblk();
2193
2194 // The first time a track is added we wait
2195 // for all its buffers to be filled before processing it
2196 if (cblk->framesReady() && (track->isReady() || track->isStopped()) &&
Eric Laurent380558b2010-04-09 06:11:48 -07002197 !track->isPaused() && !track->isTerminated())
Eric Laurenta553c252009-07-17 12:17:14 -07002198 {
2199 //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
2200
Eric Laurent65b65452010-06-01 23:49:17 -07002201 if (track->mFillingUpStatus == Track::FS_FILLED) {
2202 track->mFillingUpStatus = Track::FS_ACTIVE;
2203 mLeftVolFloat = mRightVolFloat = 0;
2204 mLeftVolShort = mRightVolShort = 0;
2205 if (track->mState == TrackBase::RESUMING) {
2206 track->mState = TrackBase::ACTIVE;
2207 rampVolume = true;
2208 }
2209 } else if (cblk->server != 0) {
2210 // If the track is stopped before the first frame was mixed,
2211 // do not apply ramp
2212 rampVolume = true;
2213 }
Eric Laurenta553c252009-07-17 12:17:14 -07002214 // compute volume for this track
2215 float left, right;
2216 if (track->isMuted() || mMasterMute || track->isPausing() ||
2217 mStreamTypes[track->type()].mute) {
2218 left = right = 0;
2219 if (track->isPausing()) {
2220 track->setPaused();
2221 }
2222 } else {
2223 float typeVolume = mStreamTypes[track->type()].volume;
2224 float v = mMasterVolume * typeVolume;
2225 float v_clamped = v * cblk->volume[0];
2226 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2227 left = v_clamped/MAX_GAIN;
2228 v_clamped = v * cblk->volume[1];
2229 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2230 right = v_clamped/MAX_GAIN;
2231 }
2232
Eric Laurent65b65452010-06-01 23:49:17 -07002233 if (left != mLeftVolFloat || right != mRightVolFloat) {
2234 mLeftVolFloat = left;
2235 mRightVolFloat = right;
Eric Laurenta553c252009-07-17 12:17:14 -07002236
Eric Laurent65b65452010-06-01 23:49:17 -07002237 // If audio HAL implements volume control,
2238 // force software volume to nominal value
2239 if (mOutput->setVolume(left, right) == NO_ERROR) {
2240 left = 1.0f;
2241 right = 1.0f;
Eric Laurenta553c252009-07-17 12:17:14 -07002242 }
Eric Laurent65b65452010-06-01 23:49:17 -07002243
2244 // Convert volumes from float to 8.24
2245 uint32_t vl = (uint32_t)(left * (1 << 24));
2246 uint32_t vr = (uint32_t)(right * (1 << 24));
2247
2248 // Delegate volume control to effect in track effect chain if needed
2249 // only one effect chain can be present on DirectOutputThread, so if
2250 // there is one, the track is connected to it
2251 if (!effectChains.isEmpty()) {
2252 // Do not ramp volume is volume is controlled by effect
Eric Laurent76c40f72010-07-15 12:50:15 -07002253 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002254 rampVolume = false;
2255 }
2256 }
2257
2258 // Convert volumes from 8.24 to 4.12 format
2259 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2260 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2261 leftVol = (uint16_t)v_clamped;
2262 v_clamped = (vr + (1 << 11)) >> 12;
2263 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2264 rightVol = (uint16_t)v_clamped;
2265 } else {
2266 leftVol = mLeftVolShort;
2267 rightVol = mRightVolShort;
2268 rampVolume = false;
Eric Laurenta553c252009-07-17 12:17:14 -07002269 }
2270
2271 // reset retry count
Eric Laurentef9500f2010-03-11 14:47:00 -08002272 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurenta553c252009-07-17 12:17:14 -07002273 activeTrack = t;
Eric Laurent059b4be2009-11-09 23:32:22 -08002274 mixerStatus = MIXER_TRACKS_READY;
Eric Laurenta553c252009-07-17 12:17:14 -07002275 } else {
2276 //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
2277 if (track->isStopped()) {
2278 track->reset();
2279 }
2280 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2281 // We have consumed all the buffers of this track.
2282 // Remove it from the list of active tracks.
2283 trackToRemove = track;
2284 } else {
2285 // No buffers for this track. Give it a few chances to
2286 // fill a buffer, then remove it from active list.
2287 if (--(track->mRetryCount) <= 0) {
2288 LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
2289 trackToRemove = track;
Eric Laurent059b4be2009-11-09 23:32:22 -08002290 } else {
2291 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07002292 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002293 }
Eric Laurenta553c252009-07-17 12:17:14 -07002294 }
2295 }
2296
2297 // remove all the tracks that need to be...
2298 if (UNLIKELY(trackToRemove != 0)) {
2299 mActiveTracks.remove(trackToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07002300 if (!effectChains.isEmpty()) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002301 LOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
2302 trackToRemove->sessionId());
Eric Laurent65b65452010-06-01 23:49:17 -07002303 effectChains[0]->stopTrack();
2304 }
Eric Laurenta553c252009-07-17 12:17:14 -07002305 if (trackToRemove->isTerminated()) {
2306 mTracks.remove(trackToRemove);
2307 deleteTrackName_l(trackToRemove->mName);
2308 }
2309 }
Eric Laurent65b65452010-06-01 23:49:17 -07002310
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002311 lockEffectChains_l(effectChains);
Eric Laurenta553c252009-07-17 12:17:14 -07002312 }
2313
Eric Laurent059b4be2009-11-09 23:32:22 -08002314 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002315 AudioBufferProvider::Buffer buffer;
2316 size_t frameCount = mFrameCount;
2317 curBuf = (int8_t *)mMixBuffer;
2318 // output audio to hardware
Eric Laurent65b65452010-06-01 23:49:17 -07002319 while (frameCount) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002320 buffer.frameCount = frameCount;
2321 activeTrack->getNextBuffer(&buffer);
2322 if (UNLIKELY(buffer.raw == 0)) {
2323 memset(curBuf, 0, frameCount * mFrameSize);
2324 break;
2325 }
2326 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2327 frameCount -= buffer.frameCount;
2328 curBuf += buffer.frameCount * mFrameSize;
2329 activeTrack->releaseBuffer(&buffer);
2330 }
2331 sleepTime = 0;
Eric Laurentef9500f2010-03-11 14:47:00 -08002332 standbyTime = systemTime() + standbyDelay;
Eric Laurent96c08a62009-09-07 08:38:38 -07002333 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07002334 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002335 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2336 sleepTime = activeSleepTime;
2337 } else {
2338 sleepTime = idleSleepTime;
2339 }
Eric Laurent62443f52009-10-05 20:29:18 -07002340 } else if (mBytesWritten != 0 && AudioSystem::isLinearPCM(mFormat)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002341 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent96c08a62009-09-07 08:38:38 -07002342 sleepTime = 0;
Eric Laurent96c08a62009-09-07 08:38:38 -07002343 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002344 }
Eric Laurent96c08a62009-09-07 08:38:38 -07002345
Eric Laurentf69a3f82009-09-22 00:35:48 -07002346 if (mSuspended) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002347 sleepTime = idleSleepTime;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002348 }
2349 // sleepTime == 0 means we must write to audio hardware
2350 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07002351 if (mixerStatus == MIXER_TRACKS_READY) {
2352 applyVolume(leftVol, rightVol, rampVolume);
2353 }
2354 for (size_t i = 0; i < effectChains.size(); i ++) {
2355 effectChains[i]->process_l();
2356 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002357 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07002358
Eric Laurentf69a3f82009-09-22 00:35:48 -07002359 mLastWriteTime = systemTime();
2360 mInWrite = true;
Eric Laurent0986e792010-01-19 17:37:09 -08002361 mBytesWritten += mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002362 int bytesWritten = (int)mOutput->write(mMixBuffer, mixBufferSize);
Eric Laurent0986e792010-01-19 17:37:09 -08002363 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002364 mNumWrites++;
2365 mInWrite = false;
2366 mStandby = false;
2367 } else {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002368 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002369 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07002370 }
2371
2372 // finally let go of removed track, without the lock held
2373 // since we can't guarantee the destructors won't acquire that
2374 // same lock.
2375 trackToRemove.clear();
2376 activeTrack.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07002377
2378 // Effect chains will be actually deleted here if they were removed from
2379 // mEffectChains list during mixing or effects processing
2380 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07002381 }
2382
2383 if (!mStandby) {
2384 mOutput->standby();
2385 }
Eric Laurenta553c252009-07-17 12:17:14 -07002386
2387 LOGV("DirectOutputThread %p exiting", this);
2388 return false;
2389}
2390
2391// getTrackName_l() must be called with ThreadBase::mLock held
2392int AudioFlinger::DirectOutputThread::getTrackName_l()
2393{
2394 return 0;
2395}
2396
2397// deleteTrackName_l() must be called with ThreadBase::mLock held
2398void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2399{
2400}
2401
2402// checkForNewParameters_l() must be called with ThreadBase::mLock held
2403bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2404{
2405 bool reconfig = false;
2406
Eric Laurent8fce46a2009-08-04 09:45:33 -07002407 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07002408 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002409 String8 keyValuePair = mNewParameters[0];
2410 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002411 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002412
Eric Laurenta553c252009-07-17 12:17:14 -07002413 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2414 // do not accept frame count changes if tracks are open as the track buffer
2415 // size depends on frame count and correct behavior would not be garantied
2416 // if frame count is changed after track creation
2417 if (!mTracks.isEmpty()) {
2418 status = INVALID_OPERATION;
2419 } else {
2420 reconfig = true;
2421 }
2422 }
2423 if (status == NO_ERROR) {
Eric Laurent8fce46a2009-08-04 09:45:33 -07002424 status = mOutput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002425 if (!mStandby && status == INVALID_OPERATION) {
2426 mOutput->standby();
2427 mStandby = true;
2428 mBytesWritten = 0;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002429 status = mOutput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002430 }
2431 if (status == NO_ERROR && reconfig) {
2432 readOutputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07002433 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07002434 }
2435 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08002436
2437 mNewParameters.removeAt(0);
2438
Eric Laurenta553c252009-07-17 12:17:14 -07002439 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07002440 mParamCond.signal();
Eric Laurent8fce46a2009-08-04 09:45:33 -07002441 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07002442 }
2443 return reconfig;
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08002444}
2445
Eric Laurent059b4be2009-11-09 23:32:22 -08002446uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
Eric Laurent62443f52009-10-05 20:29:18 -07002447{
2448 uint32_t time;
2449 if (AudioSystem::isLinearPCM(mFormat)) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002450 time = (uint32_t)(mOutput->latency() * 1000) / 2;
2451 } else {
2452 time = 10000;
2453 }
2454 return time;
2455}
2456
2457uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2458{
2459 uint32_t time;
2460 if (AudioSystem::isLinearPCM(mFormat)) {
2461 time = (uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000;
Eric Laurent62443f52009-10-05 20:29:18 -07002462 } else {
2463 time = 10000;
2464 }
2465 return time;
2466}
2467
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002468// ----------------------------------------------------------------------------
2469
Eric Laurent49f02be2009-11-19 09:00:56 -08002470AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread, int id)
Eric Laurent65b65452010-06-01 23:49:17 -07002471 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device()), mWaitTimeMs(UINT_MAX)
Eric Laurenta553c252009-07-17 12:17:14 -07002472{
2473 mType = PlaybackThread::DUPLICATING;
2474 addOutputTrack(mainThread);
2475}
2476
2477AudioFlinger::DuplicatingThread::~DuplicatingThread()
2478{
Eric Laurent0a080292009-12-07 10:53:10 -08002479 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2480 mOutputTracks[i]->destroy();
2481 }
Eric Laurenta553c252009-07-17 12:17:14 -07002482 mOutputTracks.clear();
2483}
2484
2485bool AudioFlinger::DuplicatingThread::threadLoop()
2486{
Eric Laurenta553c252009-07-17 12:17:14 -07002487 Vector< sp<Track> > tracksToRemove;
Eric Laurent059b4be2009-11-09 23:32:22 -08002488 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002489 nsecs_t standbyTime = systemTime();
2490 size_t mixBufferSize = mFrameCount*mFrameSize;
2491 SortedVector< sp<OutputTrack> > outputTracks;
Eric Laurent62443f52009-10-05 20:29:18 -07002492 uint32_t writeFrames = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08002493 uint32_t activeSleepTime = activeSleepTimeUs();
2494 uint32_t idleSleepTime = idleSleepTimeUs();
2495 uint32_t sleepTime = idleSleepTime;
Eric Laurent65b65452010-06-01 23:49:17 -07002496 Vector< sp<EffectChain> > effectChains;
Eric Laurenta553c252009-07-17 12:17:14 -07002497
2498 while (!exitPending())
2499 {
2500 processConfigEvents();
2501
Eric Laurent059b4be2009-11-09 23:32:22 -08002502 mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002503 { // scope for the mLock
2504
2505 Mutex::Autolock _l(mLock);
2506
2507 if (checkForNewParameters_l()) {
2508 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002509 updateWaitTime();
Eric Laurent059b4be2009-11-09 23:32:22 -08002510 activeSleepTime = activeSleepTimeUs();
2511 idleSleepTime = idleSleepTimeUs();
Eric Laurenta553c252009-07-17 12:17:14 -07002512 }
2513
2514 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
2515
2516 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2517 outputTracks.add(mOutputTracks[i]);
2518 }
2519
2520 // put audio hardware into standby after short delay
2521 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
2522 mSuspended) {
2523 if (!mStandby) {
2524 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurenta553c252009-07-17 12:17:14 -07002525 outputTracks[i]->stop();
Eric Laurenta553c252009-07-17 12:17:14 -07002526 }
2527 mStandby = true;
2528 mBytesWritten = 0;
2529 }
2530
2531 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
2532 // we're about to wait, flush the binder command buffer
2533 IPCThreadState::self()->flushCommands();
2534 outputTracks.clear();
2535
2536 if (exitPending()) break;
2537
2538 LOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
2539 mWaitWorkCV.wait(mLock);
2540 LOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
2541 if (mMasterMute == false) {
2542 char value[PROPERTY_VALUE_MAX];
2543 property_get("ro.audio.silent", value, "0");
2544 if (atoi(value)) {
2545 LOGD("Silence is golden");
2546 setMasterMute(true);
2547 }
2548 }
2549
2550 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent059b4be2009-11-09 23:32:22 -08002551 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07002552 continue;
2553 }
2554 }
2555
Eric Laurent059b4be2009-11-09 23:32:22 -08002556 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07002557
2558 // prevent any changes in effect chain list and in each effect chain
2559 // during mixing and effect process as the audio buffers could be deleted
2560 // or modified if an effect is created or deleted
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002561 lockEffectChains_l(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002562 }
Eric Laurenta553c252009-07-17 12:17:14 -07002563
Eric Laurent059b4be2009-11-09 23:32:22 -08002564 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurenta553c252009-07-17 12:17:14 -07002565 // mix buffers...
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002566 if (outputsReady(outputTracks)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002567 mAudioMixer->process();
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002568 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07002569 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002570 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002571 sleepTime = 0;
Eric Laurent62443f52009-10-05 20:29:18 -07002572 writeFrames = mFrameCount;
Eric Laurenta553c252009-07-17 12:17:14 -07002573 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07002574 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002575 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2576 sleepTime = activeSleepTime;
2577 } else {
2578 sleepTime = idleSleepTime;
2579 }
Eric Laurent62443f52009-10-05 20:29:18 -07002580 } else if (mBytesWritten != 0) {
2581 // flush remaining overflow buffers in output tracks
2582 for (size_t i = 0; i < outputTracks.size(); i++) {
2583 if (outputTracks[i]->isActive()) {
2584 sleepTime = 0;
2585 writeFrames = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07002586 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent62443f52009-10-05 20:29:18 -07002587 break;
2588 }
2589 }
Eric Laurenta553c252009-07-17 12:17:14 -07002590 }
2591 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002592
2593 if (mSuspended) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002594 sleepTime = idleSleepTime;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002595 }
2596 // sleepTime == 0 means we must write to audio hardware
2597 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07002598 for (size_t i = 0; i < effectChains.size(); i ++) {
2599 effectChains[i]->process_l();
2600 }
2601 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002602 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07002603
Eric Laurent62443f52009-10-05 20:29:18 -07002604 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002605 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurent65b65452010-06-01 23:49:17 -07002606 outputTracks[i]->write(mMixBuffer, writeFrames);
Eric Laurenta553c252009-07-17 12:17:14 -07002607 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002608 mStandby = false;
2609 mBytesWritten += mixBufferSize;
Eric Laurenta553c252009-07-17 12:17:14 -07002610 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07002611 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002612 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002613 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07002614 }
2615
2616 // finally let go of all our tracks, without the lock held
2617 // since we can't guarantee the destructors won't acquire that
2618 // same lock.
2619 tracksToRemove.clear();
2620 outputTracks.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07002621
2622 // Effect chains will be actually deleted here if they were removed from
2623 // mEffectChains list during mixing or effects processing
2624 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07002625 }
2626
Eric Laurenta553c252009-07-17 12:17:14 -07002627 return false;
2628}
2629
2630void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
2631{
2632 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
2633 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002634 this,
Eric Laurenta553c252009-07-17 12:17:14 -07002635 mSampleRate,
2636 mFormat,
2637 mChannelCount,
2638 frameCount);
Eric Laurent6c30a712009-08-10 23:22:32 -07002639 if (outputTrack->cblk() != NULL) {
2640 thread->setStreamVolume(AudioSystem::NUM_STREAM_TYPES, 1.0f);
2641 mOutputTracks.add(outputTrack);
2642 LOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002643 updateWaitTime();
Eric Laurent6c30a712009-08-10 23:22:32 -07002644 }
Eric Laurenta553c252009-07-17 12:17:14 -07002645}
2646
2647void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
2648{
2649 Mutex::Autolock _l(mLock);
2650 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2651 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
Eric Laurent6c30a712009-08-10 23:22:32 -07002652 mOutputTracks[i]->destroy();
Eric Laurenta553c252009-07-17 12:17:14 -07002653 mOutputTracks.removeAt(i);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002654 updateWaitTime();
Eric Laurenta553c252009-07-17 12:17:14 -07002655 return;
2656 }
2657 }
2658 LOGV("removeOutputTrack(): unkonwn thread: %p", thread);
2659}
2660
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002661void AudioFlinger::DuplicatingThread::updateWaitTime()
2662{
2663 mWaitTimeMs = UINT_MAX;
2664 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2665 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
2666 if (strong != NULL) {
2667 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
2668 if (waitTimeMs < mWaitTimeMs) {
2669 mWaitTimeMs = waitTimeMs;
2670 }
2671 }
2672 }
2673}
2674
2675
2676bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
2677{
2678 for (size_t i = 0; i < outputTracks.size(); i++) {
2679 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
2680 if (thread == 0) {
2681 LOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
2682 return false;
2683 }
2684 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2685 if (playbackThread->standby() && !playbackThread->isSuspended()) {
2686 LOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
2687 return false;
2688 }
2689 }
2690 return true;
2691}
2692
2693uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
2694{
2695 return (mWaitTimeMs * 1000) / 2;
2696}
2697
Eric Laurenta553c252009-07-17 12:17:14 -07002698// ----------------------------------------------------------------------------
2699
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002700// TrackBase constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07002701AudioFlinger::ThreadBase::TrackBase::TrackBase(
2702 const wp<ThreadBase>& thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002703 const sp<Client>& client,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002704 uint32_t sampleRate,
2705 int format,
2706 int channelCount,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002707 int frameCount,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002708 uint32_t flags,
Eric Laurent65b65452010-06-01 23:49:17 -07002709 const sp<IMemory>& sharedBuffer,
2710 int sessionId)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002711 : RefBase(),
Eric Laurenta553c252009-07-17 12:17:14 -07002712 mThread(thread),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002713 mClient(client),
Eric Laurent8a77a992009-09-09 05:16:08 -07002714 mCblk(0),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002715 mFrameCount(0),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002716 mState(IDLE),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002717 mClientTid(-1),
2718 mFormat(format),
Eric Laurent65b65452010-06-01 23:49:17 -07002719 mFlags(flags & ~SYSTEM_FLAGS_MASK),
2720 mSessionId(sessionId)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002721{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002722 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
2723
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002724 // LOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002725 size_t size = sizeof(audio_track_cblk_t);
2726 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
2727 if (sharedBuffer == 0) {
2728 size += bufferSize;
2729 }
2730
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002731 if (client != NULL) {
2732 mCblkMemory = client->heap()->allocate(size);
2733 if (mCblkMemory != 0) {
2734 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
2735 if (mCblk) { // construct the shared structure in-place.
2736 new(mCblk) audio_track_cblk_t();
2737 // clear all buffers
2738 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07002739 mCblk->sampleRate = sampleRate;
Eric Laurentb0a01472010-05-14 05:45:46 -07002740 mCblk->channelCount = (uint8_t)channelCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002741 if (sharedBuffer == 0) {
2742 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2743 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2744 // Force underrun condition to avoid false underrun callback until first data is
2745 // written to buffer
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002746 mCblk->flags = CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002747 } else {
2748 mBuffer = sharedBuffer->pointer();
2749 }
2750 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002751 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002752 } else {
2753 LOGE("not enough memory for AudioTrack size=%u", size);
2754 client->heap()->dump("AudioTrack");
2755 return;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002756 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002757 } else {
2758 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
2759 if (mCblk) { // construct the shared structure in-place.
2760 new(mCblk) audio_track_cblk_t();
2761 // clear all buffers
2762 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07002763 mCblk->sampleRate = sampleRate;
Eric Laurentb0a01472010-05-14 05:45:46 -07002764 mCblk->channelCount = (uint8_t)channelCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002765 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2766 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2767 // Force underrun condition to avoid false underrun callback until first data is
2768 // written to buffer
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002769 mCblk->flags = CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002770 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
2771 }
2772 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002773}
2774
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002775AudioFlinger::ThreadBase::TrackBase::~TrackBase()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002776{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002777 if (mCblk) {
Eric Laurenta553c252009-07-17 12:17:14 -07002778 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
2779 if (mClient == NULL) {
2780 delete mCblk;
2781 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002782 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002783 mCblkMemory.clear(); // and free the shared memory
Eric Laurentb9481d82009-09-17 05:12:56 -07002784 if (mClient != NULL) {
2785 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
2786 mClient.clear();
2787 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002788}
2789
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002790void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002791{
2792 buffer->raw = 0;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002793 mFrameCount = buffer->frameCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002794 step();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002795 buffer->frameCount = 0;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002796}
2797
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002798bool AudioFlinger::ThreadBase::TrackBase::step() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002799 bool result;
2800 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002801
2802 result = cblk->stepServer(mFrameCount);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002803 if (!result) {
2804 LOGV("stepServer failed acquiring cblk mutex");
2805 mFlags |= STEPSERVER_FAILED;
2806 }
2807 return result;
2808}
2809
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002810void AudioFlinger::ThreadBase::TrackBase::reset() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002811 audio_track_cblk_t* cblk = this->cblk();
2812
2813 cblk->user = 0;
2814 cblk->server = 0;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002815 cblk->userBase = 0;
2816 cblk->serverBase = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002817 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002818 LOGV("TrackBase::reset");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002819}
2820
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002821sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002822{
2823 return mCblkMemory;
2824}
2825
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002826int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
The Android Open Source Project10592532009-03-18 17:39:46 -07002827 return (int)mCblk->sampleRate;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002828}
2829
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002830int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
Eric Laurentb0a01472010-05-14 05:45:46 -07002831 return (int)mCblk->channelCount;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002832}
2833
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002834void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002835 audio_track_cblk_t* cblk = this->cblk();
Eric Laurenta553c252009-07-17 12:17:14 -07002836 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
2837 int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002838
2839 // Check validity of returned pointer in case the track control block would have been corrupted.
Eric Laurenta553c252009-07-17 12:17:14 -07002840 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
2841 ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
The Android Open Source Project10592532009-03-18 17:39:46 -07002842 LOGE("TrackBase::getBuffer buffer out of range:\n start: %p, end %p , mBuffer %p mBufferEnd %p\n \
Eric Laurentb0a01472010-05-14 05:45:46 -07002843 server %d, serverBase %d, user %d, userBase %d, channelCount %d",
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002844 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Eric Laurentb0a01472010-05-14 05:45:46 -07002845 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, cblk->channelCount);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002846 return 0;
2847 }
2848
2849 return bufferStart;
2850}
2851
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002852// ----------------------------------------------------------------------------
2853
Eric Laurenta553c252009-07-17 12:17:14 -07002854// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
2855AudioFlinger::PlaybackThread::Track::Track(
2856 const wp<ThreadBase>& thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002857 const sp<Client>& client,
2858 int streamType,
2859 uint32_t sampleRate,
2860 int format,
2861 int channelCount,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002862 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07002863 const sp<IMemory>& sharedBuffer,
2864 int sessionId)
2865 : TrackBase(thread, client, sampleRate, format, channelCount, frameCount, 0, sharedBuffer, sessionId),
2866 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL), mAuxEffectId(0)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002867{
Eric Laurent8a77a992009-09-09 05:16:08 -07002868 if (mCblk != NULL) {
2869 sp<ThreadBase> baseThread = thread.promote();
2870 if (baseThread != 0) {
2871 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
2872 mName = playbackThread->getTrackName_l();
Eric Laurent65b65452010-06-01 23:49:17 -07002873 mMainBuffer = playbackThread->mixBuffer();
Eric Laurent8a77a992009-09-09 05:16:08 -07002874 }
2875 LOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2876 if (mName < 0) {
2877 LOGE("no more track names available");
2878 }
2879 mVolume[0] = 1.0f;
2880 mVolume[1] = 1.0f;
2881 mStreamType = streamType;
2882 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
2883 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
2884 mCblk->frameSize = AudioSystem::isLinearPCM(format) ? channelCount * sizeof(int16_t) : sizeof(int8_t);
Eric Laurenta553c252009-07-17 12:17:14 -07002885 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002886}
2887
Eric Laurenta553c252009-07-17 12:17:14 -07002888AudioFlinger::PlaybackThread::Track::~Track()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002889{
Eric Laurenta553c252009-07-17 12:17:14 -07002890 LOGV("PlaybackThread::Track destructor");
2891 sp<ThreadBase> thread = mThread.promote();
2892 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08002893 Mutex::Autolock _l(thread->mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07002894 mState = TERMINATED;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002895 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002896}
2897
Eric Laurenta553c252009-07-17 12:17:14 -07002898void AudioFlinger::PlaybackThread::Track::destroy()
2899{
2900 // NOTE: destroyTrack_l() can remove a strong reference to this Track
2901 // by removing it from mTracks vector, so there is a risk that this Tracks's
2902 // desctructor is called. As the destructor needs to lock mLock,
2903 // we must acquire a strong reference on this Track before locking mLock
2904 // here so that the destructor is called only when exiting this function.
2905 // On the other hand, as long as Track::destroy() is only called by
2906 // TrackHandle destructor, the TrackHandle still holds a strong ref on
2907 // this Track with its member mTrack.
2908 sp<Track> keep(this);
2909 { // scope for mLock
2910 sp<ThreadBase> thread = mThread.promote();
2911 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08002912 if (!isOutputTrack()) {
2913 if (mState == ACTIVE || mState == RESUMING) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002914 AudioSystem::stopOutput(thread->id(),
2915 (AudioSystem::stream_type)mStreamType,
2916 mSessionId);
Eric Laurentac196e12009-12-01 02:17:41 -08002917 }
2918 AudioSystem::releaseOutput(thread->id());
Eric Laurent49f02be2009-11-19 09:00:56 -08002919 }
Eric Laurenta553c252009-07-17 12:17:14 -07002920 Mutex::Autolock _l(thread->mLock);
2921 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2922 playbackThread->destroyTrack_l(this);
2923 }
2924 }
2925}
2926
2927void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002928{
Eric Laurent65b65452010-06-01 23:49:17 -07002929 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 -07002930 mName - AudioMixer::TRACK0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002931 (mClient == NULL) ? getpid() : mClient->pid(),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002932 mStreamType,
2933 mFormat,
Eric Laurentb0a01472010-05-14 05:45:46 -07002934 mCblk->channelCount,
Eric Laurent65b65452010-06-01 23:49:17 -07002935 mSessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002936 mFrameCount,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002937 mState,
2938 mMute,
2939 mFillingUpStatus,
2940 mCblk->sampleRate,
2941 mCblk->volume[0],
2942 mCblk->volume[1],
2943 mCblk->server,
Eric Laurent65b65452010-06-01 23:49:17 -07002944 mCblk->user,
2945 (int)mMainBuffer,
2946 (int)mAuxBuffer);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002947}
2948
Eric Laurenta553c252009-07-17 12:17:14 -07002949status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002950{
2951 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002952 uint32_t framesReady;
2953 uint32_t framesReq = buffer->frameCount;
2954
2955 // Check if last stepServer failed, try to step now
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002956 if (mFlags & TrackBase::STEPSERVER_FAILED) {
2957 if (!step()) goto getNextBuffer_exit;
2958 LOGV("stepServer recovered");
2959 mFlags &= ~TrackBase::STEPSERVER_FAILED;
2960 }
2961
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002962 framesReady = cblk->framesReady();
2963
2964 if (LIKELY(framesReady)) {
2965 uint32_t s = cblk->server;
2966 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
2967
2968 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
2969 if (framesReq > framesReady) {
2970 framesReq = framesReady;
2971 }
2972 if (s + framesReq > bufferEnd) {
2973 framesReq = bufferEnd - s;
2974 }
2975
2976 buffer->raw = getBuffer(s, framesReq);
2977 if (buffer->raw == 0) goto getNextBuffer_exit;
2978
2979 buffer->frameCount = framesReq;
2980 return NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002981 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002982
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002983getNextBuffer_exit:
2984 buffer->raw = 0;
2985 buffer->frameCount = 0;
Eric Laurent62443f52009-10-05 20:29:18 -07002986 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 -07002987 return NOT_ENOUGH_DATA;
2988}
2989
Eric Laurenta553c252009-07-17 12:17:14 -07002990bool AudioFlinger::PlaybackThread::Track::isReady() const {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002991 if (mFillingUpStatus != FS_FILLING) return true;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002992
2993 if (mCblk->framesReady() >= mCblk->frameCount ||
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002994 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002995 mFillingUpStatus = FS_FILLED;
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002996 mCblk->flags &= ~CBLK_FORCEREADY_MSK;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002997 return true;
2998 }
2999 return false;
3000}
3001
Eric Laurenta553c252009-07-17 12:17:14 -07003002status_t AudioFlinger::PlaybackThread::Track::start()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003003{
Eric Laurent49f02be2009-11-19 09:00:56 -08003004 status_t status = NO_ERROR;
Eric Laurent0d7e0482010-07-19 06:24:46 -07003005 LOGV("start(%d), calling thread %d session %d",
3006 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Eric Laurenta553c252009-07-17 12:17:14 -07003007 sp<ThreadBase> thread = mThread.promote();
3008 if (thread != 0) {
3009 Mutex::Autolock _l(thread->mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08003010 int state = mState;
3011 // here the track could be either new, or restarted
3012 // in both cases "unstop" the track
3013 if (mState == PAUSED) {
3014 mState = TrackBase::RESUMING;
3015 LOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
3016 } else {
3017 mState = TrackBase::ACTIVE;
3018 LOGV("? => ACTIVE (%d) on thread %p", mName, this);
3019 }
3020
3021 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3022 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003023 status = AudioSystem::startOutput(thread->id(),
3024 (AudioSystem::stream_type)mStreamType,
3025 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003026 thread->mLock.lock();
3027 }
3028 if (status == NO_ERROR) {
3029 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3030 playbackThread->addTrack_l(this);
3031 } else {
3032 mState = state;
3033 }
3034 } else {
3035 status = BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -07003036 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003037 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003038}
3039
Eric Laurenta553c252009-07-17 12:17:14 -07003040void AudioFlinger::PlaybackThread::Track::stop()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003041{
Eric Laurenta553c252009-07-17 12:17:14 -07003042 LOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3043 sp<ThreadBase> thread = mThread.promote();
3044 if (thread != 0) {
3045 Mutex::Autolock _l(thread->mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08003046 int state = mState;
Eric Laurenta553c252009-07-17 12:17:14 -07003047 if (mState > STOPPED) {
3048 mState = STOPPED;
3049 // If the track is not active (PAUSED and buffers full), flush buffers
3050 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3051 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3052 reset();
3053 }
Eric Laurent62443f52009-10-05 20:29:18 -07003054 LOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003055 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003056 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3057 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003058 AudioSystem::stopOutput(thread->id(),
3059 (AudioSystem::stream_type)mStreamType,
3060 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003061 thread->mLock.lock();
3062 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003063 }
3064}
3065
Eric Laurenta553c252009-07-17 12:17:14 -07003066void AudioFlinger::PlaybackThread::Track::pause()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003067{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003068 LOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurenta553c252009-07-17 12:17:14 -07003069 sp<ThreadBase> thread = mThread.promote();
3070 if (thread != 0) {
3071 Mutex::Autolock _l(thread->mLock);
3072 if (mState == ACTIVE || mState == RESUMING) {
3073 mState = PAUSING;
Eric Laurent62443f52009-10-05 20:29:18 -07003074 LOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurent49f02be2009-11-19 09:00:56 -08003075 if (!isOutputTrack()) {
3076 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003077 AudioSystem::stopOutput(thread->id(),
3078 (AudioSystem::stream_type)mStreamType,
3079 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003080 thread->mLock.lock();
3081 }
Eric Laurenta553c252009-07-17 12:17:14 -07003082 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003083 }
3084}
3085
Eric Laurenta553c252009-07-17 12:17:14 -07003086void AudioFlinger::PlaybackThread::Track::flush()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003087{
3088 LOGV("flush(%d)", mName);
Eric Laurenta553c252009-07-17 12:17:14 -07003089 sp<ThreadBase> thread = mThread.promote();
3090 if (thread != 0) {
3091 Mutex::Autolock _l(thread->mLock);
3092 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3093 return;
3094 }
3095 // No point remaining in PAUSED state after a flush => go to
3096 // STOPPED state
3097 mState = STOPPED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003098
Eric Laurenta553c252009-07-17 12:17:14 -07003099 mCblk->lock.lock();
3100 // NOTE: reset() will reset cblk->user and cblk->server with
3101 // the risk that at the same time, the AudioMixer is trying to read
3102 // data. In this case, getNextBuffer() would return a NULL pointer
3103 // as audio buffer => the AudioMixer code MUST always test that pointer
3104 // returned by getNextBuffer() is not NULL!
3105 reset();
3106 mCblk->lock.unlock();
3107 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003108}
3109
Eric Laurenta553c252009-07-17 12:17:14 -07003110void AudioFlinger::PlaybackThread::Track::reset()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003111{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003112 // Do not reset twice to avoid discarding data written just after a flush and before
3113 // the audioflinger thread detects the track is stopped.
3114 if (!mResetDone) {
3115 TrackBase::reset();
3116 // Force underrun condition to avoid false underrun callback until first data is
3117 // written to buffer
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003118 mCblk->flags |= CBLK_UNDERRUN_ON;
3119 mCblk->flags &= ~CBLK_FORCEREADY_MSK;
Eric Laurenta553c252009-07-17 12:17:14 -07003120 mFillingUpStatus = FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003121 mResetDone = true;
3122 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003123}
3124
Eric Laurenta553c252009-07-17 12:17:14 -07003125void AudioFlinger::PlaybackThread::Track::mute(bool muted)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003126{
3127 mMute = muted;
3128}
3129
Eric Laurenta553c252009-07-17 12:17:14 -07003130void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003131{
3132 mVolume[0] = left;
3133 mVolume[1] = right;
3134}
3135
Eric Laurent65b65452010-06-01 23:49:17 -07003136status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3137{
3138 status_t status = DEAD_OBJECT;
3139 sp<ThreadBase> thread = mThread.promote();
3140 if (thread != 0) {
3141 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3142 status = playbackThread->attachAuxEffect(this, EffectId);
3143 }
3144 return status;
3145}
3146
3147void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3148{
3149 mAuxEffectId = EffectId;
3150 mAuxBuffer = buffer;
3151}
3152
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003153// ----------------------------------------------------------------------------
3154
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003155// RecordTrack constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07003156AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3157 const wp<ThreadBase>& thread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003158 const sp<Client>& client,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003159 uint32_t sampleRate,
3160 int format,
3161 int channelCount,
3162 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07003163 uint32_t flags,
3164 int sessionId)
Eric Laurenta553c252009-07-17 12:17:14 -07003165 : TrackBase(thread, client, sampleRate, format,
Eric Laurent65b65452010-06-01 23:49:17 -07003166 channelCount, frameCount, flags, 0, sessionId),
Eric Laurenta553c252009-07-17 12:17:14 -07003167 mOverflow(false)
3168{
Eric Laurent8a77a992009-09-09 05:16:08 -07003169 if (mCblk != NULL) {
3170 LOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
3171 if (format == AudioSystem::PCM_16_BIT) {
3172 mCblk->frameSize = channelCount * sizeof(int16_t);
3173 } else if (format == AudioSystem::PCM_8_BIT) {
3174 mCblk->frameSize = channelCount * sizeof(int8_t);
3175 } else {
3176 mCblk->frameSize = sizeof(int8_t);
3177 }
3178 }
Eric Laurenta553c252009-07-17 12:17:14 -07003179}
3180
3181AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003182{
Eric Laurent49f02be2009-11-19 09:00:56 -08003183 sp<ThreadBase> thread = mThread.promote();
3184 if (thread != 0) {
3185 AudioSystem::releaseInput(thread->id());
3186 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003187}
3188
Eric Laurenta553c252009-07-17 12:17:14 -07003189status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003190{
3191 audio_track_cblk_t* cblk = this->cblk();
3192 uint32_t framesAvail;
3193 uint32_t framesReq = buffer->frameCount;
3194
3195 // Check if last stepServer failed, try to step now
3196 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3197 if (!step()) goto getNextBuffer_exit;
3198 LOGV("stepServer recovered");
3199 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3200 }
3201
3202 framesAvail = cblk->framesAvailable_l();
3203
3204 if (LIKELY(framesAvail)) {
3205 uint32_t s = cblk->server;
3206 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3207
3208 if (framesReq > framesAvail) {
3209 framesReq = framesAvail;
3210 }
3211 if (s + framesReq > bufferEnd) {
3212 framesReq = bufferEnd - s;
3213 }
3214
3215 buffer->raw = getBuffer(s, framesReq);
3216 if (buffer->raw == 0) goto getNextBuffer_exit;
3217
3218 buffer->frameCount = framesReq;
3219 return NO_ERROR;
3220 }
3221
3222getNextBuffer_exit:
3223 buffer->raw = 0;
3224 buffer->frameCount = 0;
3225 return NOT_ENOUGH_DATA;
3226}
3227
Eric Laurenta553c252009-07-17 12:17:14 -07003228status_t AudioFlinger::RecordThread::RecordTrack::start()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003229{
Eric Laurenta553c252009-07-17 12:17:14 -07003230 sp<ThreadBase> thread = mThread.promote();
3231 if (thread != 0) {
3232 RecordThread *recordThread = (RecordThread *)thread.get();
3233 return recordThread->start(this);
Eric Laurent49f02be2009-11-19 09:00:56 -08003234 } else {
3235 return BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -07003236 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003237}
3238
Eric Laurenta553c252009-07-17 12:17:14 -07003239void AudioFlinger::RecordThread::RecordTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003240{
Eric Laurenta553c252009-07-17 12:17:14 -07003241 sp<ThreadBase> thread = mThread.promote();
3242 if (thread != 0) {
3243 RecordThread *recordThread = (RecordThread *)thread.get();
3244 recordThread->stop(this);
3245 TrackBase::reset();
3246 // Force overerrun condition to avoid false overrun callback until first data is
3247 // read from buffer
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003248 mCblk->flags |= CBLK_UNDERRUN_ON;
Eric Laurenta553c252009-07-17 12:17:14 -07003249 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003250}
3251
Eric Laurent3fdb1262009-11-07 00:01:32 -08003252void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3253{
Eric Laurent65b65452010-06-01 23:49:17 -07003254 snprintf(buffer, size, " %05d %03u %03u %05d %04u %01d %05u %08x %08x\n",
Eric Laurent3fdb1262009-11-07 00:01:32 -08003255 (mClient == NULL) ? getpid() : mClient->pid(),
3256 mFormat,
Eric Laurentb0a01472010-05-14 05:45:46 -07003257 mCblk->channelCount,
Eric Laurent65b65452010-06-01 23:49:17 -07003258 mSessionId,
Eric Laurent3fdb1262009-11-07 00:01:32 -08003259 mFrameCount,
3260 mState,
3261 mCblk->sampleRate,
3262 mCblk->server,
3263 mCblk->user);
3264}
3265
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003266
3267// ----------------------------------------------------------------------------
3268
Eric Laurenta553c252009-07-17 12:17:14 -07003269AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3270 const wp<ThreadBase>& thread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003271 DuplicatingThread *sourceThread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003272 uint32_t sampleRate,
3273 int format,
3274 int channelCount,
3275 int frameCount)
Eric Laurent65b65452010-06-01 23:49:17 -07003276 : Track(thread, NULL, AudioSystem::NUM_STREAM_TYPES, sampleRate, format, channelCount, frameCount, NULL, 0),
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003277 mActive(false), mSourceThread(sourceThread)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003278{
Eric Laurenta553c252009-07-17 12:17:14 -07003279
3280 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
Eric Laurent6c30a712009-08-10 23:22:32 -07003281 if (mCblk != NULL) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003282 mCblk->flags |= CBLK_DIRECTION_OUT;
Eric Laurent6c30a712009-08-10 23:22:32 -07003283 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
3284 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
3285 mOutBuffer.frameCount = 0;
Eric Laurent6c30a712009-08-10 23:22:32 -07003286 playbackThread->mTracks.add(this);
Eric Laurentb0a01472010-05-14 05:45:46 -07003287 LOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, mCblk->frameCount %d, mCblk->sampleRate %d, mCblk->channelCount %d mBufferEnd %p",
3288 mCblk, mBuffer, mCblk->buffers, mCblk->frameCount, mCblk->sampleRate, mCblk->channelCount, mBufferEnd);
Eric Laurent6c30a712009-08-10 23:22:32 -07003289 } else {
3290 LOGW("Error creating output track on thread %p", playbackThread);
3291 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003292}
3293
Eric Laurenta553c252009-07-17 12:17:14 -07003294AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003295{
Eric Laurent6c30a712009-08-10 23:22:32 -07003296 clearBufferQueue();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003297}
3298
Eric Laurenta553c252009-07-17 12:17:14 -07003299status_t AudioFlinger::PlaybackThread::OutputTrack::start()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003300{
3301 status_t status = Track::start();
Eric Laurenta553c252009-07-17 12:17:14 -07003302 if (status != NO_ERROR) {
3303 return status;
3304 }
3305
3306 mActive = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003307 mRetryCount = 127;
3308 return status;
3309}
3310
Eric Laurenta553c252009-07-17 12:17:14 -07003311void AudioFlinger::PlaybackThread::OutputTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003312{
3313 Track::stop();
3314 clearBufferQueue();
3315 mOutBuffer.frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003316 mActive = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003317}
3318
Eric Laurenta553c252009-07-17 12:17:14 -07003319bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003320{
3321 Buffer *pInBuffer;
3322 Buffer inBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003323 uint32_t channelCount = mCblk->channelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003324 bool outputBufferFull = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003325 inBuffer.frameCount = frames;
3326 inBuffer.i16 = data;
Eric Laurenta553c252009-07-17 12:17:14 -07003327
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003328 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
Eric Laurenta553c252009-07-17 12:17:14 -07003329
Eric Laurent62443f52009-10-05 20:29:18 -07003330 if (!mActive && frames != 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003331 start();
3332 sp<ThreadBase> thread = mThread.promote();
3333 if (thread != 0) {
3334 MixerThread *mixerThread = (MixerThread *)thread.get();
3335 if (mCblk->frameCount > frames){
3336 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3337 uint32_t startFrames = (mCblk->frameCount - frames);
3338 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003339 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
Eric Laurenta553c252009-07-17 12:17:14 -07003340 pInBuffer->frameCount = startFrames;
3341 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003342 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
Eric Laurenta553c252009-07-17 12:17:14 -07003343 mBufferQueue.add(pInBuffer);
3344 } else {
3345 LOGW ("OutputTrack::write() %p no more buffers in queue", this);
3346 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003347 }
Eric Laurenta553c252009-07-17 12:17:14 -07003348 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003349 }
3350
Eric Laurenta553c252009-07-17 12:17:14 -07003351 while (waitTimeLeftMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003352 // First write pending buffers, then new data
3353 if (mBufferQueue.size()) {
3354 pInBuffer = mBufferQueue.itemAt(0);
3355 } else {
3356 pInBuffer = &inBuffer;
3357 }
Eric Laurenta553c252009-07-17 12:17:14 -07003358
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003359 if (pInBuffer->frameCount == 0) {
3360 break;
3361 }
Eric Laurenta553c252009-07-17 12:17:14 -07003362
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003363 if (mOutBuffer.frameCount == 0) {
3364 mOutBuffer.frameCount = pInBuffer->frameCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003365 nsecs_t startTime = systemTime();
3366 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003367 LOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Eric Laurenta553c252009-07-17 12:17:14 -07003368 outputBufferFull = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003369 break;
3370 }
Eric Laurenta553c252009-07-17 12:17:14 -07003371 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
Eric Laurenta553c252009-07-17 12:17:14 -07003372 if (waitTimeLeftMs >= waitTimeMs) {
3373 waitTimeLeftMs -= waitTimeMs;
3374 } else {
3375 waitTimeLeftMs = 0;
3376 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003377 }
Eric Laurenta553c252009-07-17 12:17:14 -07003378
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003379 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
Eric Laurentb0a01472010-05-14 05:45:46 -07003380 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003381 mCblk->stepUser(outFrames);
3382 pInBuffer->frameCount -= outFrames;
Eric Laurentb0a01472010-05-14 05:45:46 -07003383 pInBuffer->i16 += outFrames * channelCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003384 mOutBuffer.frameCount -= outFrames;
Eric Laurentb0a01472010-05-14 05:45:46 -07003385 mOutBuffer.i16 += outFrames * channelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003386
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003387 if (pInBuffer->frameCount == 0) {
3388 if (mBufferQueue.size()) {
3389 mBufferQueue.removeAt(0);
3390 delete [] pInBuffer->mBuffer;
3391 delete pInBuffer;
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003392 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 -08003393 } else {
3394 break;
3395 }
3396 }
3397 }
Eric Laurenta553c252009-07-17 12:17:14 -07003398
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003399 // If we could not write all frames, allocate a buffer and queue it for next time.
3400 if (inBuffer.frameCount) {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003401 sp<ThreadBase> thread = mThread.promote();
3402 if (thread != 0 && !thread->standby()) {
3403 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3404 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003405 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003406 pInBuffer->frameCount = inBuffer.frameCount;
3407 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003408 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003409 mBufferQueue.add(pInBuffer);
3410 LOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
3411 } else {
3412 LOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
3413 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003414 }
3415 }
Eric Laurenta553c252009-07-17 12:17:14 -07003416
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003417 // Calling write() with a 0 length buffer, means that no more data will be written:
Eric Laurenta553c252009-07-17 12:17:14 -07003418 // 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 -08003419 // by output mixer.
Eric Laurenta553c252009-07-17 12:17:14 -07003420 if (frames == 0 && mBufferQueue.size() == 0) {
3421 if (mCblk->user < mCblk->frameCount) {
3422 frames = mCblk->frameCount - mCblk->user;
3423 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003424 pInBuffer->mBuffer = new int16_t[frames * channelCount];
Eric Laurenta553c252009-07-17 12:17:14 -07003425 pInBuffer->frameCount = frames;
3426 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003427 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
Eric Laurenta553c252009-07-17 12:17:14 -07003428 mBufferQueue.add(pInBuffer);
Eric Laurent62443f52009-10-05 20:29:18 -07003429 } else if (mActive) {
Eric Laurenta553c252009-07-17 12:17:14 -07003430 stop();
3431 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003432 }
3433
Eric Laurenta553c252009-07-17 12:17:14 -07003434 return outputBufferFull;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003435}
3436
Eric Laurenta553c252009-07-17 12:17:14 -07003437status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003438{
3439 int active;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003440 status_t result;
3441 audio_track_cblk_t* cblk = mCblk;
3442 uint32_t framesReq = buffer->frameCount;
3443
Eric Laurenta553c252009-07-17 12:17:14 -07003444// LOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003445 buffer->frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003446
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003447 uint32_t framesAvail = cblk->framesAvailable();
3448
Eric Laurenta553c252009-07-17 12:17:14 -07003449
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003450 if (framesAvail == 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003451 Mutex::Autolock _l(cblk->lock);
3452 goto start_loop_here;
3453 while (framesAvail == 0) {
3454 active = mActive;
3455 if (UNLIKELY(!active)) {
3456 LOGV("Not active and NO_MORE_BUFFERS");
3457 return AudioTrack::NO_MORE_BUFFERS;
3458 }
3459 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3460 if (result != NO_ERROR) {
3461 return AudioTrack::NO_MORE_BUFFERS;
3462 }
3463 // read the server count again
3464 start_loop_here:
3465 framesAvail = cblk->framesAvailable_l();
3466 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003467 }
3468
Eric Laurenta553c252009-07-17 12:17:14 -07003469// if (framesAvail < framesReq) {
3470// return AudioTrack::NO_MORE_BUFFERS;
3471// }
3472
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003473 if (framesReq > framesAvail) {
3474 framesReq = framesAvail;
3475 }
3476
3477 uint32_t u = cblk->user;
3478 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
3479
3480 if (u + framesReq > bufferEnd) {
3481 framesReq = bufferEnd - u;
3482 }
3483
3484 buffer->frameCount = framesReq;
3485 buffer->raw = (void *)cblk->buffer(u);
3486 return NO_ERROR;
3487}
3488
3489
Eric Laurenta553c252009-07-17 12:17:14 -07003490void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003491{
3492 size_t size = mBufferQueue.size();
3493 Buffer *pBuffer;
Eric Laurenta553c252009-07-17 12:17:14 -07003494
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003495 for (size_t i = 0; i < size; i++) {
3496 pBuffer = mBufferQueue.itemAt(i);
3497 delete [] pBuffer->mBuffer;
3498 delete pBuffer;
3499 }
3500 mBufferQueue.clear();
3501}
3502
3503// ----------------------------------------------------------------------------
3504
3505AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
3506 : RefBase(),
3507 mAudioFlinger(audioFlinger),
Mathias Agopian6faf7892010-01-25 19:00:00 -08003508 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003509 mPid(pid)
3510{
3511 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
3512}
3513
Eric Laurentb9481d82009-09-17 05:12:56 -07003514// Client destructor must be called with AudioFlinger::mLock held
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003515AudioFlinger::Client::~Client()
3516{
Eric Laurentb9481d82009-09-17 05:12:56 -07003517 mAudioFlinger->removeClient_l(mPid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003518}
3519
3520const sp<MemoryDealer>& AudioFlinger::Client::heap() const
3521{
3522 return mMemoryDealer;
3523}
3524
3525// ----------------------------------------------------------------------------
3526
Eric Laurent4f0f17d2010-05-12 02:05:53 -07003527AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
3528 const sp<IAudioFlingerClient>& client,
3529 pid_t pid)
3530 : mAudioFlinger(audioFlinger), mPid(pid), mClient(client)
3531{
3532}
3533
3534AudioFlinger::NotificationClient::~NotificationClient()
3535{
3536 mClient.clear();
3537}
3538
3539void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
3540{
3541 sp<NotificationClient> keep(this);
3542 {
3543 mAudioFlinger->removeNotificationClient(mPid);
3544 }
3545}
3546
3547// ----------------------------------------------------------------------------
3548
Eric Laurenta553c252009-07-17 12:17:14 -07003549AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003550 : BnAudioTrack(),
3551 mTrack(track)
3552{
3553}
3554
3555AudioFlinger::TrackHandle::~TrackHandle() {
3556 // just stop the track on deletion, associated resources
3557 // will be freed from the main thread once all pending buffers have
3558 // been played. Unless it's not in the active track list, in which
3559 // case we free everything now...
3560 mTrack->destroy();
3561}
3562
3563status_t AudioFlinger::TrackHandle::start() {
3564 return mTrack->start();
3565}
3566
3567void AudioFlinger::TrackHandle::stop() {
3568 mTrack->stop();
3569}
3570
3571void AudioFlinger::TrackHandle::flush() {
3572 mTrack->flush();
3573}
3574
3575void AudioFlinger::TrackHandle::mute(bool e) {
3576 mTrack->mute(e);
3577}
3578
3579void AudioFlinger::TrackHandle::pause() {
3580 mTrack->pause();
3581}
3582
3583void AudioFlinger::TrackHandle::setVolume(float left, float right) {
3584 mTrack->setVolume(left, right);
3585}
3586
3587sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
3588 return mTrack->getCblk();
3589}
3590
Eric Laurent65b65452010-06-01 23:49:17 -07003591status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
3592{
3593 return mTrack->attachAuxEffect(EffectId);
3594}
3595
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003596status_t AudioFlinger::TrackHandle::onTransact(
3597 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3598{
3599 return BnAudioTrack::onTransact(code, data, reply, flags);
3600}
3601
3602// ----------------------------------------------------------------------------
3603
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003604sp<IAudioRecord> AudioFlinger::openRecord(
3605 pid_t pid,
Eric Laurentddb78e72009-07-28 08:44:33 -07003606 int input,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003607 uint32_t sampleRate,
3608 int format,
3609 int channelCount,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003610 int frameCount,
3611 uint32_t flags,
Eric Laurent65b65452010-06-01 23:49:17 -07003612 int *sessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003613 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003614{
Eric Laurenta553c252009-07-17 12:17:14 -07003615 sp<RecordThread::RecordTrack> recordTrack;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003616 sp<RecordHandle> recordHandle;
3617 sp<Client> client;
3618 wp<Client> wclient;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003619 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07003620 RecordThread *thread;
3621 size_t inFrameCount;
Eric Laurent65b65452010-06-01 23:49:17 -07003622 int lSessionId;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003623
3624 // check calling permissions
3625 if (!recordingAllowed()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003626 lStatus = PERMISSION_DENIED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003627 goto Exit;
3628 }
3629
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003630 // add client to list
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003631 { // scope for mLock
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003632 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07003633 thread = checkRecordThread_l(input);
3634 if (thread == NULL) {
3635 lStatus = BAD_VALUE;
3636 goto Exit;
3637 }
3638
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003639 wclient = mClients.valueFor(pid);
3640 if (wclient != NULL) {
3641 client = wclient.promote();
3642 } else {
3643 client = new Client(this, pid);
3644 mClients.add(pid, client);
3645 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003646
Eric Laurent65b65452010-06-01 23:49:17 -07003647 // If no audio session id is provided, create one here
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003648 if (sessionId != NULL && *sessionId != AudioSystem::SESSION_OUTPUT_MIX) {
Eric Laurent65b65452010-06-01 23:49:17 -07003649 lSessionId = *sessionId;
3650 } else {
3651 lSessionId = nextUniqueId();
3652 if (sessionId != NULL) {
3653 *sessionId = lSessionId;
3654 }
3655 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003656 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurenta553c252009-07-17 12:17:14 -07003657 recordTrack = new RecordThread::RecordTrack(thread, client, sampleRate,
Eric Laurent65b65452010-06-01 23:49:17 -07003658 format, channelCount, frameCount, flags, lSessionId);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003659 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003660 if (recordTrack->getCblk() == NULL) {
Eric Laurentb9481d82009-09-17 05:12:56 -07003661 // remove local strong reference to Client before deleting the RecordTrack so that the Client
3662 // destructor is called by the TrackBase destructor with mLock held
3663 client.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003664 recordTrack.clear();
3665 lStatus = NO_MEMORY;
3666 goto Exit;
3667 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003668
3669 // return to handle to client
3670 recordHandle = new RecordHandle(recordTrack);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003671 lStatus = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003672
3673Exit:
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003674 if (status) {
3675 *status = lStatus;
3676 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003677 return recordHandle;
3678}
3679
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003680// ----------------------------------------------------------------------------
3681
Eric Laurenta553c252009-07-17 12:17:14 -07003682AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003683 : BnAudioRecord(),
3684 mRecordTrack(recordTrack)
3685{
3686}
3687
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003688AudioFlinger::RecordHandle::~RecordHandle() {
3689 stop();
3690}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003691
3692status_t AudioFlinger::RecordHandle::start() {
3693 LOGV("RecordHandle::start()");
3694 return mRecordTrack->start();
3695}
3696
3697void AudioFlinger::RecordHandle::stop() {
3698 LOGV("RecordHandle::stop()");
3699 mRecordTrack->stop();
3700}
3701
3702sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
3703 return mRecordTrack->getCblk();
3704}
3705
3706status_t AudioFlinger::RecordHandle::onTransact(
3707 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3708{
3709 return BnAudioRecord::onTransact(code, data, reply, flags);
3710}
3711
3712// ----------------------------------------------------------------------------
3713
Eric Laurent49f02be2009-11-19 09:00:56 -08003714AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger, AudioStreamIn *input, uint32_t sampleRate, uint32_t channels, int id) :
3715 ThreadBase(audioFlinger, id),
Eric Laurenta553c252009-07-17 12:17:14 -07003716 mInput(input), mResampler(0), mRsmpOutBuffer(0), mRsmpInBuffer(0)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003717{
Eric Laurenta553c252009-07-17 12:17:14 -07003718 mReqChannelCount = AudioSystem::popCount(channels);
3719 mReqSampleRate = sampleRate;
3720 readInputParameters();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003721}
3722
Eric Laurenta553c252009-07-17 12:17:14 -07003723
3724AudioFlinger::RecordThread::~RecordThread()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003725{
Eric Laurenta553c252009-07-17 12:17:14 -07003726 delete[] mRsmpInBuffer;
3727 if (mResampler != 0) {
3728 delete mResampler;
3729 delete[] mRsmpOutBuffer;
3730 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003731}
3732
Eric Laurenta553c252009-07-17 12:17:14 -07003733void AudioFlinger::RecordThread::onFirstRef()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003734{
Eric Laurenta553c252009-07-17 12:17:14 -07003735 const size_t SIZE = 256;
3736 char buffer[SIZE];
3737
3738 snprintf(buffer, SIZE, "Record Thread %p", this);
3739
3740 run(buffer, PRIORITY_URGENT_AUDIO);
3741}
Eric Laurent49f02be2009-11-19 09:00:56 -08003742
Eric Laurenta553c252009-07-17 12:17:14 -07003743bool AudioFlinger::RecordThread::threadLoop()
3744{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003745 AudioBufferProvider::Buffer buffer;
Eric Laurenta553c252009-07-17 12:17:14 -07003746 sp<RecordTrack> activeTrack;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003747
3748 // start recording
3749 while (!exitPending()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003750
Eric Laurenta553c252009-07-17 12:17:14 -07003751 processConfigEvents();
3752
3753 { // scope for mLock
3754 Mutex::Autolock _l(mLock);
3755 checkForNewParameters_l();
3756 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
3757 if (!mStandby) {
3758 mInput->standby();
3759 mStandby = true;
3760 }
3761
3762 if (exitPending()) break;
3763
3764 LOGV("RecordThread: loop stopping");
3765 // go to sleep
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003766 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07003767 LOGV("RecordThread: loop starting");
3768 continue;
3769 }
3770 if (mActiveTrack != 0) {
3771 if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08003772 if (!mStandby) {
3773 mInput->standby();
3774 mStandby = true;
3775 }
Eric Laurenta553c252009-07-17 12:17:14 -07003776 mActiveTrack.clear();
3777 mStartStopCond.broadcast();
3778 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
Eric Laurenta553c252009-07-17 12:17:14 -07003779 if (mReqChannelCount != mActiveTrack->channelCount()) {
3780 mActiveTrack.clear();
Eric Laurent9cc489a22009-12-05 05:20:01 -08003781 mStartStopCond.broadcast();
3782 } else if (mBytesRead != 0) {
3783 // record start succeeds only if first read from audio input
3784 // succeeds
3785 if (mBytesRead > 0) {
3786 mActiveTrack->mState = TrackBase::ACTIVE;
3787 } else {
3788 mActiveTrack.clear();
3789 }
3790 mStartStopCond.broadcast();
Eric Laurenta553c252009-07-17 12:17:14 -07003791 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08003792 mStandby = false;
Eric Laurenta553c252009-07-17 12:17:14 -07003793 }
Eric Laurenta553c252009-07-17 12:17:14 -07003794 }
3795 }
3796
3797 if (mActiveTrack != 0) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08003798 if (mActiveTrack->mState != TrackBase::ACTIVE &&
3799 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent49f02be2009-11-19 09:00:56 -08003800 usleep(5000);
3801 continue;
3802 }
Eric Laurenta553c252009-07-17 12:17:14 -07003803 buffer.frameCount = mFrameCount;
3804 if (LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
3805 size_t framesOut = buffer.frameCount;
3806 if (mResampler == 0) {
3807 // no resampling
3808 while (framesOut) {
3809 size_t framesIn = mFrameCount - mRsmpInIndex;
3810 if (framesIn) {
3811 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
3812 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
3813 if (framesIn > framesOut)
3814 framesIn = framesOut;
3815 mRsmpInIndex += framesIn;
3816 framesOut -= framesIn;
Eric Laurentb0a01472010-05-14 05:45:46 -07003817 if ((int)mChannelCount == mReqChannelCount ||
Eric Laurenta553c252009-07-17 12:17:14 -07003818 mFormat != AudioSystem::PCM_16_BIT) {
3819 memcpy(dst, src, framesIn * mFrameSize);
3820 } else {
3821 int16_t *src16 = (int16_t *)src;
3822 int16_t *dst16 = (int16_t *)dst;
3823 if (mChannelCount == 1) {
3824 while (framesIn--) {
3825 *dst16++ = *src16;
3826 *dst16++ = *src16++;
3827 }
3828 } else {
3829 while (framesIn--) {
3830 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
3831 src16 += 2;
3832 }
3833 }
3834 }
3835 }
3836 if (framesOut && mFrameCount == mRsmpInIndex) {
Eric Laurenta553c252009-07-17 12:17:14 -07003837 if (framesOut == mFrameCount &&
Eric Laurentb0a01472010-05-14 05:45:46 -07003838 ((int)mChannelCount == mReqChannelCount || mFormat != AudioSystem::PCM_16_BIT)) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08003839 mBytesRead = mInput->read(buffer.raw, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07003840 framesOut = 0;
3841 } else {
Eric Laurent9cc489a22009-12-05 05:20:01 -08003842 mBytesRead = mInput->read(mRsmpInBuffer, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07003843 mRsmpInIndex = 0;
3844 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08003845 if (mBytesRead < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003846 LOGE("Error reading audio input");
Eric Laurent9cc489a22009-12-05 05:20:01 -08003847 if (mActiveTrack->mState == TrackBase::ACTIVE) {
Eric Laurentba8811f2010-03-02 18:38:06 -08003848 // Force input into standby so that it tries to
3849 // recover at next read attempt
3850 mInput->standby();
3851 usleep(5000);
Eric Laurent9cc489a22009-12-05 05:20:01 -08003852 }
Eric Laurenta553c252009-07-17 12:17:14 -07003853 mRsmpInIndex = mFrameCount;
3854 framesOut = 0;
3855 buffer.frameCount = 0;
3856 }
3857 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003858 }
3859 } else {
Eric Laurenta553c252009-07-17 12:17:14 -07003860 // resampling
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003861
Eric Laurenta553c252009-07-17 12:17:14 -07003862 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
3863 // alter output frame count as if we were expecting stereo samples
3864 if (mChannelCount == 1 && mReqChannelCount == 1) {
3865 framesOut >>= 1;
3866 }
3867 mResampler->resample(mRsmpOutBuffer, framesOut, this);
3868 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
3869 // are 32 bit aligned which should be always true.
3870 if (mChannelCount == 2 && mReqChannelCount == 1) {
3871 AudioMixer::ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
3872 // the resampler always outputs stereo samples: do post stereo to mono conversion
3873 int16_t *src = (int16_t *)mRsmpOutBuffer;
3874 int16_t *dst = buffer.i16;
3875 while (framesOut--) {
3876 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
3877 src += 2;
3878 }
3879 } else {
3880 AudioMixer::ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
3881 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003882
Eric Laurenta553c252009-07-17 12:17:14 -07003883 }
3884 mActiveTrack->releaseBuffer(&buffer);
3885 mActiveTrack->overflow();
3886 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003887 // client isn't retrieving buffers fast enough
3888 else {
Eric Laurenta553c252009-07-17 12:17:14 -07003889 if (!mActiveTrack->setOverflow())
3890 LOGW("RecordThread: buffer overflow");
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003891 // Release the processor for a while before asking for a new buffer.
3892 // This will give the application more chance to read from the buffer and
3893 // clear the overflow.
3894 usleep(5000);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003895 }
3896 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003897 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003898
Eric Laurenta553c252009-07-17 12:17:14 -07003899 if (!mStandby) {
3900 mInput->standby();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003901 }
Eric Laurenta553c252009-07-17 12:17:14 -07003902 mActiveTrack.clear();
3903
Eric Laurent49f02be2009-11-19 09:00:56 -08003904 mStartStopCond.broadcast();
3905
Eric Laurenta553c252009-07-17 12:17:14 -07003906 LOGV("RecordThread %p exiting", this);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003907 return false;
3908}
3909
Eric Laurenta553c252009-07-17 12:17:14 -07003910status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003911{
Eric Laurenta553c252009-07-17 12:17:14 -07003912 LOGV("RecordThread::start");
Eric Laurent49f02be2009-11-19 09:00:56 -08003913 sp <ThreadBase> strongMe = this;
3914 status_t status = NO_ERROR;
3915 {
3916 AutoMutex lock(&mLock);
3917 if (mActiveTrack != 0) {
3918 if (recordTrack != mActiveTrack.get()) {
3919 status = -EBUSY;
3920 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08003921 mActiveTrack->mState = TrackBase::ACTIVE;
Eric Laurent49f02be2009-11-19 09:00:56 -08003922 }
3923 return status;
3924 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003925
Eric Laurent49f02be2009-11-19 09:00:56 -08003926 recordTrack->mState = TrackBase::IDLE;
3927 mActiveTrack = recordTrack;
3928 mLock.unlock();
3929 status_t status = AudioSystem::startInput(mId);
3930 mLock.lock();
3931 if (status != NO_ERROR) {
3932 mActiveTrack.clear();
3933 return status;
3934 }
3935 mActiveTrack->mState = TrackBase::RESUMING;
Eric Laurent9cc489a22009-12-05 05:20:01 -08003936 mRsmpInIndex = mFrameCount;
3937 mBytesRead = 0;
Eric Laurent49f02be2009-11-19 09:00:56 -08003938 // signal thread to start
3939 LOGV("Signal record thread");
3940 mWaitWorkCV.signal();
3941 // do not wait for mStartStopCond if exiting
3942 if (mExiting) {
3943 mActiveTrack.clear();
3944 status = INVALID_OPERATION;
3945 goto startError;
3946 }
3947 mStartStopCond.wait(mLock);
3948 if (mActiveTrack == 0) {
3949 LOGV("Record failed to start");
3950 status = BAD_VALUE;
3951 goto startError;
3952 }
Eric Laurenta553c252009-07-17 12:17:14 -07003953 LOGV("Record started OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08003954 return status;
Eric Laurenta553c252009-07-17 12:17:14 -07003955 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003956startError:
3957 AudioSystem::stopInput(mId);
3958 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003959}
3960
Eric Laurenta553c252009-07-17 12:17:14 -07003961void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
3962 LOGV("RecordThread::stop");
Eric Laurent49f02be2009-11-19 09:00:56 -08003963 sp <ThreadBase> strongMe = this;
3964 {
3965 AutoMutex lock(&mLock);
3966 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
3967 mActiveTrack->mState = TrackBase::PAUSING;
3968 // do not wait for mStartStopCond if exiting
3969 if (mExiting) {
3970 return;
3971 }
3972 mStartStopCond.wait(mLock);
3973 // if we have been restarted, recordTrack == mActiveTrack.get() here
3974 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
3975 mLock.unlock();
3976 AudioSystem::stopInput(mId);
3977 mLock.lock();
Eric Laurent9cc489a22009-12-05 05:20:01 -08003978 LOGV("Record stopped OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08003979 }
3980 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003981 }
3982}
3983
Eric Laurenta553c252009-07-17 12:17:14 -07003984status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003985{
3986 const size_t SIZE = 256;
3987 char buffer[SIZE];
3988 String8 result;
3989 pid_t pid = 0;
3990
Eric Laurent3fdb1262009-11-07 00:01:32 -08003991 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
3992 result.append(buffer);
3993
3994 if (mActiveTrack != 0) {
3995 result.append("Active Track:\n");
Eric Laurent65b65452010-06-01 23:49:17 -07003996 result.append(" Clien Fmt Chn Session Buf S SRate Serv User\n");
Eric Laurent3fdb1262009-11-07 00:01:32 -08003997 mActiveTrack->dump(buffer, SIZE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003998 result.append(buffer);
Eric Laurent3fdb1262009-11-07 00:01:32 -08003999
4000 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4001 result.append(buffer);
4002 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4003 result.append(buffer);
4004 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != 0));
4005 result.append(buffer);
4006 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4007 result.append(buffer);
4008 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4009 result.append(buffer);
4010
4011
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004012 } else {
4013 result.append("No record client\n");
4014 }
4015 write(fd, result.string(), result.size());
Eric Laurent3fdb1262009-11-07 00:01:32 -08004016
4017 dumpBase(fd, args);
4018
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004019 return NO_ERROR;
4020}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004021
Eric Laurenta553c252009-07-17 12:17:14 -07004022status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4023{
4024 size_t framesReq = buffer->frameCount;
4025 size_t framesReady = mFrameCount - mRsmpInIndex;
4026 int channelCount;
4027
4028 if (framesReady == 0) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08004029 mBytesRead = mInput->read(mRsmpInBuffer, mInputBytes);
4030 if (mBytesRead < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07004031 LOGE("RecordThread::getNextBuffer() Error reading audio input");
Eric Laurent9cc489a22009-12-05 05:20:01 -08004032 if (mActiveTrack->mState == TrackBase::ACTIVE) {
Eric Laurentba8811f2010-03-02 18:38:06 -08004033 // Force input into standby so that it tries to
4034 // recover at next read attempt
4035 mInput->standby();
4036 usleep(5000);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004037 }
Eric Laurenta553c252009-07-17 12:17:14 -07004038 buffer->raw = 0;
4039 buffer->frameCount = 0;
4040 return NOT_ENOUGH_DATA;
4041 }
4042 mRsmpInIndex = 0;
4043 framesReady = mFrameCount;
4044 }
4045
4046 if (framesReq > framesReady) {
4047 framesReq = framesReady;
4048 }
4049
4050 if (mChannelCount == 1 && mReqChannelCount == 2) {
4051 channelCount = 1;
4052 } else {
4053 channelCount = 2;
4054 }
4055 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4056 buffer->frameCount = framesReq;
4057 return NO_ERROR;
4058}
4059
4060void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4061{
4062 mRsmpInIndex += buffer->frameCount;
4063 buffer->frameCount = 0;
4064}
4065
4066bool AudioFlinger::RecordThread::checkForNewParameters_l()
4067{
4068 bool reconfig = false;
4069
Eric Laurent8fce46a2009-08-04 09:45:33 -07004070 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07004071 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07004072 String8 keyValuePair = mNewParameters[0];
4073 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07004074 int value;
4075 int reqFormat = mFormat;
4076 int reqSamplingRate = mReqSampleRate;
4077 int reqChannelCount = mReqChannelCount;
Eric Laurent8fce46a2009-08-04 09:45:33 -07004078
Eric Laurenta553c252009-07-17 12:17:14 -07004079 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4080 reqSamplingRate = value;
4081 reconfig = true;
4082 }
4083 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
4084 reqFormat = value;
4085 reconfig = true;
4086 }
4087 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
4088 reqChannelCount = AudioSystem::popCount(value);
4089 reconfig = true;
4090 }
4091 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4092 // do not accept frame count changes if tracks are open as the track buffer
4093 // size depends on frame count and correct behavior would not be garantied
4094 // if frame count is changed after track creation
4095 if (mActiveTrack != 0) {
4096 status = INVALID_OPERATION;
4097 } else {
4098 reconfig = true;
4099 }
4100 }
4101 if (status == NO_ERROR) {
Eric Laurent8fce46a2009-08-04 09:45:33 -07004102 status = mInput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07004103 if (status == INVALID_OPERATION) {
4104 mInput->standby();
Eric Laurent8fce46a2009-08-04 09:45:33 -07004105 status = mInput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07004106 }
4107 if (reconfig) {
4108 if (status == BAD_VALUE &&
4109 reqFormat == mInput->format() && reqFormat == AudioSystem::PCM_16_BIT &&
4110 ((int)mInput->sampleRate() <= 2 * reqSamplingRate) &&
4111 (AudioSystem::popCount(mInput->channels()) < 3) && (reqChannelCount < 3)) {
4112 status = NO_ERROR;
4113 }
4114 if (status == NO_ERROR) {
4115 readInputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07004116 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07004117 }
4118 }
4119 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08004120
4121 mNewParameters.removeAt(0);
4122
Eric Laurenta553c252009-07-17 12:17:14 -07004123 mParamStatus = status;
4124 mParamCond.signal();
Eric Laurent8fce46a2009-08-04 09:45:33 -07004125 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07004126 }
4127 return reconfig;
4128}
4129
4130String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4131{
4132 return mInput->getParameters(keys);
4133}
4134
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004135void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
Eric Laurenta553c252009-07-17 12:17:14 -07004136 AudioSystem::OutputDescriptor desc;
4137 void *param2 = 0;
4138
4139 switch (event) {
4140 case AudioSystem::INPUT_OPENED:
4141 case AudioSystem::INPUT_CONFIG_CHANGED:
Eric Laurentb0a01472010-05-14 05:45:46 -07004142 desc.channels = mChannels;
Eric Laurenta553c252009-07-17 12:17:14 -07004143 desc.samplingRate = mSampleRate;
4144 desc.format = mFormat;
4145 desc.frameCount = mFrameCount;
4146 desc.latency = 0;
4147 param2 = &desc;
4148 break;
4149
4150 case AudioSystem::INPUT_CLOSED:
4151 default:
4152 break;
4153 }
Eric Laurent49f02be2009-11-19 09:00:56 -08004154 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurenta553c252009-07-17 12:17:14 -07004155}
4156
4157void AudioFlinger::RecordThread::readInputParameters()
4158{
4159 if (mRsmpInBuffer) delete mRsmpInBuffer;
4160 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
4161 if (mResampler) delete mResampler;
4162 mResampler = 0;
4163
4164 mSampleRate = mInput->sampleRate();
Eric Laurentb0a01472010-05-14 05:45:46 -07004165 mChannels = mInput->channels();
4166 mChannelCount = (uint16_t)AudioSystem::popCount(mChannels);
Eric Laurenta553c252009-07-17 12:17:14 -07004167 mFormat = mInput->format();
Eric Laurentb0a01472010-05-14 05:45:46 -07004168 mFrameSize = (uint16_t)mInput->frameSize();
Eric Laurenta553c252009-07-17 12:17:14 -07004169 mInputBytes = mInput->bufferSize();
4170 mFrameCount = mInputBytes / mFrameSize;
4171 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4172
4173 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4174 {
4175 int channelCount;
4176 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4177 // stereo to mono post process as the resampler always outputs stereo.
4178 if (mChannelCount == 1 && mReqChannelCount == 2) {
4179 channelCount = 1;
4180 } else {
4181 channelCount = 2;
4182 }
4183 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4184 mResampler->setSampleRate(mSampleRate);
4185 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4186 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4187
4188 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4189 if (mChannelCount == 1 && mReqChannelCount == 1) {
4190 mFrameCount >>= 1;
4191 }
4192
4193 }
4194 mRsmpInIndex = mFrameCount;
4195}
4196
Eric Laurent47d0a922010-02-26 02:47:27 -08004197unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4198{
4199 return mInput->getInputFramesLost();
4200}
4201
Eric Laurenta553c252009-07-17 12:17:14 -07004202// ----------------------------------------------------------------------------
4203
Eric Laurentddb78e72009-07-28 08:44:33 -07004204int AudioFlinger::openOutput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07004205 uint32_t *pSamplingRate,
4206 uint32_t *pFormat,
4207 uint32_t *pChannels,
4208 uint32_t *pLatencyMs,
4209 uint32_t flags)
4210{
4211 status_t status;
4212 PlaybackThread *thread = NULL;
4213 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4214 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4215 uint32_t format = pFormat ? *pFormat : 0;
4216 uint32_t channels = pChannels ? *pChannels : 0;
4217 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
4218
4219 LOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
4220 pDevices ? *pDevices : 0,
4221 samplingRate,
4222 format,
4223 channels,
4224 flags);
4225
4226 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004227 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004228 }
4229 Mutex::Autolock _l(mLock);
4230
4231 AudioStreamOut *output = mAudioHardware->openOutputStream(*pDevices,
4232 (int *)&format,
4233 &channels,
4234 &samplingRate,
4235 &status);
4236 LOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
4237 output,
4238 samplingRate,
4239 format,
4240 channels,
4241 status);
4242
4243 mHardwareStatus = AUDIO_HW_IDLE;
4244 if (output != 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07004245 int id = nextUniqueId();
Eric Laurenta553c252009-07-17 12:17:14 -07004246 if ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) ||
4247 (format != AudioSystem::PCM_16_BIT) ||
4248 (channels != AudioSystem::CHANNEL_OUT_STEREO)) {
Eric Laurent65b65452010-06-01 23:49:17 -07004249 thread = new DirectOutputThread(this, output, id, *pDevices);
4250 LOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004251 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07004252 thread = new MixerThread(this, output, id, *pDevices);
4253 LOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Glenn Kasten871c16c2010-03-05 12:18:01 -08004254
4255#ifdef LVMX
4256 unsigned bitsPerSample =
4257 (format == AudioSystem::PCM_16_BIT) ? 16 :
4258 ((format == AudioSystem::PCM_8_BIT) ? 8 : 0);
4259 unsigned channelCount = (channels == AudioSystem::CHANNEL_OUT_STEREO) ? 2 : 1;
4260 int audioOutputType = LifeVibes::threadIdToAudioOutputType(thread->id());
4261
4262 LifeVibes::init_aot(audioOutputType, samplingRate, bitsPerSample, channelCount);
4263 LifeVibes::setDevice(audioOutputType, *pDevices);
4264#endif
4265
Eric Laurenta553c252009-07-17 12:17:14 -07004266 }
Eric Laurent65b65452010-06-01 23:49:17 -07004267 mPlaybackThreads.add(id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004268
4269 if (pSamplingRate) *pSamplingRate = samplingRate;
4270 if (pFormat) *pFormat = format;
4271 if (pChannels) *pChannels = channels;
4272 if (pLatencyMs) *pLatencyMs = thread->latency();
Eric Laurent9cc489a22009-12-05 05:20:01 -08004273
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004274 // notify client processes of the new output creation
4275 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004276 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004277 }
4278
Eric Laurent9cc489a22009-12-05 05:20:01 -08004279 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004280}
4281
Eric Laurentddb78e72009-07-28 08:44:33 -07004282int AudioFlinger::openDuplicateOutput(int output1, int output2)
Eric Laurenta553c252009-07-17 12:17:14 -07004283{
4284 Mutex::Autolock _l(mLock);
Eric Laurentddb78e72009-07-28 08:44:33 -07004285 MixerThread *thread1 = checkMixerThread_l(output1);
4286 MixerThread *thread2 = checkMixerThread_l(output2);
Eric Laurenta553c252009-07-17 12:17:14 -07004287
Eric Laurentddb78e72009-07-28 08:44:33 -07004288 if (thread1 == NULL || thread2 == NULL) {
4289 LOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
4290 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004291 }
4292
Eric Laurent65b65452010-06-01 23:49:17 -07004293 int id = nextUniqueId();
4294 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
Eric Laurentddb78e72009-07-28 08:44:33 -07004295 thread->addOutputTrack(thread2);
Eric Laurent65b65452010-06-01 23:49:17 -07004296 mPlaybackThreads.add(id, thread);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004297 // notify client processes of the new output creation
4298 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004299 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004300}
4301
Eric Laurentddb78e72009-07-28 08:44:33 -07004302status_t AudioFlinger::closeOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004303{
Eric Laurent49018a52009-08-04 08:37:05 -07004304 // keep strong reference on the playback thread so that
4305 // it is not destroyed while exit() is executed
4306 sp <PlaybackThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07004307 {
4308 Mutex::Autolock _l(mLock);
4309 thread = checkPlaybackThread_l(output);
4310 if (thread == NULL) {
4311 return BAD_VALUE;
4312 }
4313
Eric Laurentddb78e72009-07-28 08:44:33 -07004314 LOGV("closeOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004315
4316 if (thread->type() == PlaybackThread::MIXER) {
4317 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004318 if (mPlaybackThreads.valueAt(i)->type() == PlaybackThread::DUPLICATING) {
4319 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Eric Laurent49018a52009-08-04 08:37:05 -07004320 dupThread->removeOutputTrack((MixerThread *)thread.get());
Eric Laurenta553c252009-07-17 12:17:14 -07004321 }
4322 }
4323 }
Eric Laurent296a0ec2009-09-15 07:10:12 -07004324 void *param2 = 0;
Eric Laurent49f02be2009-11-19 09:00:56 -08004325 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
Eric Laurentddb78e72009-07-28 08:44:33 -07004326 mPlaybackThreads.removeItem(output);
Eric Laurenta553c252009-07-17 12:17:14 -07004327 }
4328 thread->exit();
4329
Eric Laurent49018a52009-08-04 08:37:05 -07004330 if (thread->type() != PlaybackThread::DUPLICATING) {
4331 mAudioHardware->closeOutputStream(thread->getOutput());
4332 }
Eric Laurenta553c252009-07-17 12:17:14 -07004333 return NO_ERROR;
4334}
4335
Eric Laurentddb78e72009-07-28 08:44:33 -07004336status_t AudioFlinger::suspendOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004337{
4338 Mutex::Autolock _l(mLock);
4339 PlaybackThread *thread = checkPlaybackThread_l(output);
4340
4341 if (thread == NULL) {
4342 return BAD_VALUE;
4343 }
4344
Eric Laurentddb78e72009-07-28 08:44:33 -07004345 LOGV("suspendOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004346 thread->suspend();
4347
4348 return NO_ERROR;
4349}
4350
Eric Laurentddb78e72009-07-28 08:44:33 -07004351status_t AudioFlinger::restoreOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004352{
4353 Mutex::Autolock _l(mLock);
4354 PlaybackThread *thread = checkPlaybackThread_l(output);
4355
4356 if (thread == NULL) {
4357 return BAD_VALUE;
4358 }
4359
Eric Laurentddb78e72009-07-28 08:44:33 -07004360 LOGV("restoreOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004361
4362 thread->restore();
4363
4364 return NO_ERROR;
4365}
4366
Eric Laurentddb78e72009-07-28 08:44:33 -07004367int AudioFlinger::openInput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07004368 uint32_t *pSamplingRate,
4369 uint32_t *pFormat,
4370 uint32_t *pChannels,
4371 uint32_t acoustics)
4372{
4373 status_t status;
4374 RecordThread *thread = NULL;
4375 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4376 uint32_t format = pFormat ? *pFormat : 0;
4377 uint32_t channels = pChannels ? *pChannels : 0;
4378 uint32_t reqSamplingRate = samplingRate;
4379 uint32_t reqFormat = format;
4380 uint32_t reqChannels = channels;
4381
4382 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004383 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004384 }
4385 Mutex::Autolock _l(mLock);
4386
4387 AudioStreamIn *input = mAudioHardware->openInputStream(*pDevices,
4388 (int *)&format,
4389 &channels,
4390 &samplingRate,
4391 &status,
4392 (AudioSystem::audio_in_acoustics)acoustics);
4393 LOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
4394 input,
4395 samplingRate,
4396 format,
4397 channels,
4398 acoustics,
4399 status);
4400
4401 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
4402 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
4403 // or stereo to mono conversions on 16 bit PCM inputs.
4404 if (input == 0 && status == BAD_VALUE &&
4405 reqFormat == format && format == AudioSystem::PCM_16_BIT &&
4406 (samplingRate <= 2 * reqSamplingRate) &&
4407 (AudioSystem::popCount(channels) < 3) && (AudioSystem::popCount(reqChannels) < 3)) {
4408 LOGV("openInput() reopening with proposed sampling rate and channels");
4409 input = mAudioHardware->openInputStream(*pDevices,
4410 (int *)&format,
4411 &channels,
4412 &samplingRate,
4413 &status,
4414 (AudioSystem::audio_in_acoustics)acoustics);
4415 }
4416
4417 if (input != 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07004418 int id = nextUniqueId();
Eric Laurenta553c252009-07-17 12:17:14 -07004419 // Start record thread
Eric Laurent65b65452010-06-01 23:49:17 -07004420 thread = new RecordThread(this, input, reqSamplingRate, reqChannels, id);
4421 mRecordThreads.add(id, thread);
4422 LOGV("openInput() created record thread: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004423 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
4424 if (pFormat) *pFormat = format;
4425 if (pChannels) *pChannels = reqChannels;
4426
4427 input->standby();
Eric Laurent9cc489a22009-12-05 05:20:01 -08004428
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004429 // notify client processes of the new input creation
4430 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004431 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004432 }
4433
Eric Laurent9cc489a22009-12-05 05:20:01 -08004434 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004435}
4436
Eric Laurentddb78e72009-07-28 08:44:33 -07004437status_t AudioFlinger::closeInput(int input)
Eric Laurenta553c252009-07-17 12:17:14 -07004438{
Eric Laurent49018a52009-08-04 08:37:05 -07004439 // keep strong reference on the record thread so that
4440 // it is not destroyed while exit() is executed
4441 sp <RecordThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07004442 {
4443 Mutex::Autolock _l(mLock);
4444 thread = checkRecordThread_l(input);
4445 if (thread == NULL) {
4446 return BAD_VALUE;
4447 }
4448
Eric Laurentddb78e72009-07-28 08:44:33 -07004449 LOGV("closeInput() %d", input);
Eric Laurent296a0ec2009-09-15 07:10:12 -07004450 void *param2 = 0;
Eric Laurent49f02be2009-11-19 09:00:56 -08004451 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
Eric Laurentddb78e72009-07-28 08:44:33 -07004452 mRecordThreads.removeItem(input);
Eric Laurenta553c252009-07-17 12:17:14 -07004453 }
4454 thread->exit();
4455
Eric Laurent49018a52009-08-04 08:37:05 -07004456 mAudioHardware->closeInputStream(thread->getInput());
4457
Eric Laurenta553c252009-07-17 12:17:14 -07004458 return NO_ERROR;
4459}
4460
Eric Laurentddb78e72009-07-28 08:44:33 -07004461status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004462{
4463 Mutex::Autolock _l(mLock);
4464 MixerThread *dstThread = checkMixerThread_l(output);
4465 if (dstThread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004466 LOGW("setStreamOutput() bad output id %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004467 return BAD_VALUE;
4468 }
4469
Eric Laurentddb78e72009-07-28 08:44:33 -07004470 LOGV("setStreamOutput() stream %d to output %d", stream, output);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004471 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
Eric Laurenta553c252009-07-17 12:17:14 -07004472
4473 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004474 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurenta553c252009-07-17 12:17:14 -07004475 if (thread != dstThread &&
4476 thread->type() != PlaybackThread::DIRECT) {
4477 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004478 srcThread->invalidateTracks(stream);
Eric Laurenta553c252009-07-17 12:17:14 -07004479 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004480 }
Eric Laurentd069f322009-09-01 05:56:26 -07004481
Eric Laurenta553c252009-07-17 12:17:14 -07004482 return NO_ERROR;
4483}
4484
Eric Laurent65b65452010-06-01 23:49:17 -07004485
4486int AudioFlinger::newAudioSessionId()
4487{
4488 return nextUniqueId();
4489}
4490
Eric Laurenta553c252009-07-17 12:17:14 -07004491// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07004492AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
Eric Laurenta553c252009-07-17 12:17:14 -07004493{
4494 PlaybackThread *thread = NULL;
Eric Laurentddb78e72009-07-28 08:44:33 -07004495 if (mPlaybackThreads.indexOfKey(output) >= 0) {
4496 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
Eric Laurenta553c252009-07-17 12:17:14 -07004497 }
Eric Laurenta553c252009-07-17 12:17:14 -07004498 return thread;
4499}
4500
4501// checkMixerThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07004502AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
Eric Laurenta553c252009-07-17 12:17:14 -07004503{
4504 PlaybackThread *thread = checkPlaybackThread_l(output);
4505 if (thread != NULL) {
4506 if (thread->type() == PlaybackThread::DIRECT) {
4507 thread = NULL;
4508 }
4509 }
4510 return (MixerThread *)thread;
4511}
4512
4513// checkRecordThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07004514AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
Eric Laurenta553c252009-07-17 12:17:14 -07004515{
4516 RecordThread *thread = NULL;
Eric Laurentddb78e72009-07-28 08:44:33 -07004517 if (mRecordThreads.indexOfKey(input) >= 0) {
4518 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
Eric Laurenta553c252009-07-17 12:17:14 -07004519 }
Eric Laurenta553c252009-07-17 12:17:14 -07004520 return thread;
4521}
4522
Eric Laurent65b65452010-06-01 23:49:17 -07004523int AudioFlinger::nextUniqueId()
4524{
4525 return android_atomic_inc(&mNextUniqueId);
4526}
4527
4528// ----------------------------------------------------------------------------
4529// Effect management
4530// ----------------------------------------------------------------------------
4531
4532
4533status_t AudioFlinger::loadEffectLibrary(const char *libPath, int *handle)
4534{
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004535 // check calling permissions
4536 if (!settingsAllowed()) {
4537 return PERMISSION_DENIED;
4538 }
4539 // only allow libraries loaded from /system/lib/soundfx for now
4540 if (strncmp(gEffectLibPath, libPath, strlen(gEffectLibPath)) != 0) {
4541 return PERMISSION_DENIED;
4542 }
4543
Eric Laurent65b65452010-06-01 23:49:17 -07004544 Mutex::Autolock _l(mLock);
4545 return EffectLoadLibrary(libPath, handle);
4546}
4547
4548status_t AudioFlinger::unloadEffectLibrary(int handle)
4549{
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004550 // check calling permissions
4551 if (!settingsAllowed()) {
4552 return PERMISSION_DENIED;
4553 }
4554
Eric Laurent65b65452010-06-01 23:49:17 -07004555 Mutex::Autolock _l(mLock);
4556 return EffectUnloadLibrary(handle);
4557}
4558
4559status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects)
4560{
4561 Mutex::Autolock _l(mLock);
4562 return EffectQueryNumberEffects(numEffects);
4563}
4564
Eric Laurent53334cd2010-06-23 17:38:20 -07004565status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor)
Eric Laurent65b65452010-06-01 23:49:17 -07004566{
4567 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07004568 return EffectQueryEffect(index, descriptor);
Eric Laurent65b65452010-06-01 23:49:17 -07004569}
4570
4571status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid, effect_descriptor_t *descriptor)
4572{
4573 Mutex::Autolock _l(mLock);
4574 return EffectGetDescriptor(pUuid, descriptor);
4575}
4576
Eric Laurentdf9b81c2010-07-02 08:12:41 -07004577
4578// this UUID must match the one defined in media/libeffects/EffectVisualizer.cpp
4579static const effect_uuid_t VISUALIZATION_UUID_ =
4580 {0xd069d9e0, 0x8329, 0x11df, 0x9168, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}};
4581
Eric Laurent65b65452010-06-01 23:49:17 -07004582sp<IEffect> AudioFlinger::createEffect(pid_t pid,
4583 effect_descriptor_t *pDesc,
4584 const sp<IEffectClient>& effectClient,
4585 int32_t priority,
4586 int output,
4587 int sessionId,
4588 status_t *status,
4589 int *id,
4590 int *enabled)
4591{
4592 status_t lStatus = NO_ERROR;
4593 sp<EffectHandle> handle;
4594 effect_interface_t itfe;
4595 effect_descriptor_t desc;
4596 sp<Client> client;
4597 wp<Client> wclient;
4598
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004599 LOGV("createEffect pid %d, client %p, priority %d, sessionId %d, output %d",
4600 pid, effectClient.get(), priority, sessionId, output);
Eric Laurent65b65452010-06-01 23:49:17 -07004601
4602 if (pDesc == NULL) {
4603 lStatus = BAD_VALUE;
4604 goto Exit;
4605 }
4606
4607 {
4608 Mutex::Autolock _l(mLock);
4609
Eric Laurentdf9b81c2010-07-02 08:12:41 -07004610 // check recording permission for visualizer
4611 if (memcmp(&pDesc->type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0 ||
4612 memcmp(&pDesc->uuid, &VISUALIZATION_UUID_, sizeof(effect_uuid_t)) == 0) {
4613 if (!recordingAllowed()) {
4614 lStatus = PERMISSION_DENIED;
4615 goto Exit;
4616 }
4617 }
4618
Eric Laurent65b65452010-06-01 23:49:17 -07004619 if (!EffectIsNullUuid(&pDesc->uuid)) {
4620 // if uuid is specified, request effect descriptor
4621 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
4622 if (lStatus < 0) {
4623 LOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
4624 goto Exit;
4625 }
4626 } else {
4627 // if uuid is not specified, look for an available implementation
4628 // of the required type in effect factory
4629 if (EffectIsNullUuid(&pDesc->type)) {
4630 LOGW("createEffect() no effect type");
4631 lStatus = BAD_VALUE;
4632 goto Exit;
4633 }
4634 uint32_t numEffects = 0;
4635 effect_descriptor_t d;
4636 bool found = false;
4637
4638 lStatus = EffectQueryNumberEffects(&numEffects);
4639 if (lStatus < 0) {
4640 LOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
4641 goto Exit;
4642 }
Eric Laurent53334cd2010-06-23 17:38:20 -07004643 for (uint32_t i = 0; i < numEffects; i++) {
4644 lStatus = EffectQueryEffect(i, &desc);
Eric Laurent65b65452010-06-01 23:49:17 -07004645 if (lStatus < 0) {
Eric Laurent53334cd2010-06-23 17:38:20 -07004646 LOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07004647 continue;
4648 }
4649 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
4650 // If matching type found save effect descriptor. If the session is
4651 // 0 and the effect is not auxiliary, continue enumeration in case
4652 // an auxiliary version of this effect type is available
4653 found = true;
4654 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004655 if (sessionId != AudioSystem::SESSION_OUTPUT_MIX ||
Eric Laurent65b65452010-06-01 23:49:17 -07004656 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
4657 break;
4658 }
4659 }
4660 }
4661 if (!found) {
4662 lStatus = BAD_VALUE;
4663 LOGW("createEffect() effect not found");
4664 goto Exit;
4665 }
4666 // For same effect type, chose auxiliary version over insert version if
4667 // connect to output mix (Compliance to OpenSL ES)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004668 if (sessionId == AudioSystem::SESSION_OUTPUT_MIX &&
Eric Laurent65b65452010-06-01 23:49:17 -07004669 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
4670 memcpy(&desc, &d, sizeof(effect_descriptor_t));
4671 }
4672 }
4673
4674 // Do not allow auxiliary effects on a session different from 0 (output mix)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004675 if (sessionId != AudioSystem::SESSION_OUTPUT_MIX &&
Eric Laurent65b65452010-06-01 23:49:17 -07004676 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
4677 lStatus = INVALID_OPERATION;
4678 goto Exit;
4679 }
4680
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004681 // Session AudioSystem::SESSION_OUTPUT_STAGE is reserved for output stage effects
4682 // that can only be created by audio policy manager (running in same process)
4683 if (sessionId == AudioSystem::SESSION_OUTPUT_STAGE &&
4684 getpid() != IPCThreadState::self()->getCallingPid()) {
Eric Laurent53334cd2010-06-23 17:38:20 -07004685 lStatus = INVALID_OPERATION;
4686 goto Exit;
4687 }
4688
Eric Laurent65b65452010-06-01 23:49:17 -07004689 // return effect descriptor
4690 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
4691
4692 // If output is not specified try to find a matching audio session ID in one of the
4693 // output threads.
4694 // TODO: allow attachment of effect to inputs
4695 if (output == 0) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004696 if (sessionId == AudioSystem::SESSION_OUTPUT_STAGE) {
4697 // output must be specified by AudioPolicyManager when using session
4698 // AudioSystem::SESSION_OUTPUT_STAGE
4699 lStatus = BAD_VALUE;
4700 goto Exit;
4701 } else if (sessionId == AudioSystem::SESSION_OUTPUT_MIX) {
4702 output = AudioSystem::getOutputForEffect(&desc);
4703 LOGV("createEffect() got output %d for effect %s", output, desc.name);
Eric Laurent65b65452010-06-01 23:49:17 -07004704 } else {
4705 // look for the thread where the specified audio session is present
4706 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
4707 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId)) {
4708 output = mPlaybackThreads.keyAt(i);
4709 break;
4710 }
4711 }
4712 }
4713 }
4714 PlaybackThread *thread = checkPlaybackThread_l(output);
4715 if (thread == NULL) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004716 LOGE("createEffect() unknown output thread");
Eric Laurent65b65452010-06-01 23:49:17 -07004717 lStatus = BAD_VALUE;
4718 goto Exit;
4719 }
4720
4721 wclient = mClients.valueFor(pid);
4722
4723 if (wclient != NULL) {
4724 client = wclient.promote();
4725 } else {
4726 client = new Client(this, pid);
4727 mClients.add(pid, client);
4728 }
4729
4730 // create effect on selected output trhead
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004731 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
4732 &desc, enabled, &lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07004733 if (handle != 0 && id != NULL) {
4734 *id = handle->id();
4735 }
4736 }
4737
4738Exit:
4739 if(status) {
4740 *status = lStatus;
4741 }
4742 return handle;
4743}
4744
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004745status_t AudioFlinger::moveEffects(int session, int srcOutput, int dstOutput)
4746{
4747 LOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
4748 session, srcOutput, dstOutput);
4749 Mutex::Autolock _l(mLock);
4750 if (srcOutput == dstOutput) {
4751 LOGW("moveEffects() same dst and src outputs %d", dstOutput);
4752 return NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07004753 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004754 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
4755 if (srcThread == NULL) {
4756 LOGW("moveEffects() bad srcOutput %d", srcOutput);
4757 return BAD_VALUE;
Eric Laurent53334cd2010-06-23 17:38:20 -07004758 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004759 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
4760 if (dstThread == NULL) {
4761 LOGW("moveEffects() bad dstOutput %d", dstOutput);
4762 return BAD_VALUE;
4763 }
4764
4765 Mutex::Autolock _dl(dstThread->mLock);
4766 Mutex::Autolock _sl(srcThread->mLock);
4767 moveEffectChain_l(session, srcThread, dstThread);
4768
Eric Laurent53334cd2010-06-23 17:38:20 -07004769 return NO_ERROR;
4770}
4771
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004772// moveEffectChain_l mustbe called with both srcThread and dstThread mLocks held
4773status_t AudioFlinger::moveEffectChain_l(int session,
4774 AudioFlinger::PlaybackThread *srcThread,
4775 AudioFlinger::PlaybackThread *dstThread)
4776{
4777 LOGV("moveEffectChain_l() session %d from thread %p to thread %p",
4778 session, srcThread, dstThread);
4779
4780 sp<EffectChain> chain = srcThread->getEffectChain_l(session);
4781 if (chain == 0) {
4782 LOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
4783 session, srcThread);
4784 return INVALID_OPERATION;
4785 }
4786
4787 // remove chain first. This is usefull only if reconfiguring effect chain on same output thread,
4788 // so that a new chain is created with correct parameters when first effect is added. This is
4789 // otherwise unecessary as removeEffect_l() will remove the chain when last effect is
4790 // removed.
4791 srcThread->removeEffectChain_l(chain);
4792
4793 // transfer all effects one by one so that new effect chain is created on new thread with
4794 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
4795 sp<EffectModule> effect = chain->getEffectFromId_l(0);
4796 while (effect != 0) {
4797 srcThread->removeEffect_l(effect);
4798 dstThread->addEffect_l(effect);
4799 effect = chain->getEffectFromId_l(0);
4800 }
4801
4802 return NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07004803}
4804
Eric Laurent65b65452010-06-01 23:49:17 -07004805// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
4806sp<AudioFlinger::EffectHandle> AudioFlinger::PlaybackThread::createEffect_l(
4807 const sp<AudioFlinger::Client>& client,
4808 const sp<IEffectClient>& effectClient,
4809 int32_t priority,
4810 int sessionId,
4811 effect_descriptor_t *desc,
4812 int *enabled,
4813 status_t *status
4814 )
4815{
4816 sp<EffectModule> effect;
4817 sp<EffectHandle> handle;
4818 status_t lStatus;
4819 sp<Track> track;
4820 sp<EffectChain> chain;
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004821 bool chainCreated = false;
Eric Laurent65b65452010-06-01 23:49:17 -07004822 bool effectCreated = false;
Eric Laurent53334cd2010-06-23 17:38:20 -07004823 bool effectRegistered = false;
Eric Laurent65b65452010-06-01 23:49:17 -07004824
4825 if (mOutput == 0) {
4826 LOGW("createEffect_l() Audio driver not initialized.");
4827 lStatus = NO_INIT;
4828 goto Exit;
4829 }
4830
4831 // Do not allow auxiliary effect on session other than 0
4832 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY &&
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004833 sessionId != AudioSystem::SESSION_OUTPUT_MIX) {
4834 LOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
4835 desc->name, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07004836 lStatus = BAD_VALUE;
4837 goto Exit;
4838 }
4839
4840 // Do not allow effects with session ID 0 on direct output or duplicating threads
4841 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004842 if (sessionId == AudioSystem::SESSION_OUTPUT_MIX && mType != MIXER) {
4843 LOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
4844 desc->name, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07004845 lStatus = BAD_VALUE;
4846 goto Exit;
4847 }
4848
4849 LOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
4850
4851 { // scope for mLock
4852 Mutex::Autolock _l(mLock);
4853
4854 // check for existing effect chain with the requested audio session
4855 chain = getEffectChain_l(sessionId);
4856 if (chain == 0) {
4857 // create a new chain for this session
4858 LOGV("createEffect_l() new effect chain for session %d", sessionId);
4859 chain = new EffectChain(this, sessionId);
4860 addEffectChain_l(chain);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004861 chain->setStrategy(getStrategyForSession_l(sessionId));
4862 chainCreated = true;
Eric Laurent65b65452010-06-01 23:49:17 -07004863 } else {
Eric Laurent76c40f72010-07-15 12:50:15 -07004864 effect = chain->getEffectFromDesc_l(desc);
Eric Laurent65b65452010-06-01 23:49:17 -07004865 }
4866
4867 LOGV("createEffect_l() got effect %p on chain %p", effect == 0 ? 0 : effect.get(), chain.get());
4868
4869 if (effect == 0) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004870 int id = mAudioFlinger->nextUniqueId();
Eric Laurent53334cd2010-06-23 17:38:20 -07004871 // Check CPU and memory usage
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004872 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Eric Laurent53334cd2010-06-23 17:38:20 -07004873 if (lStatus != NO_ERROR) {
4874 goto Exit;
4875 }
4876 effectRegistered = true;
Eric Laurent65b65452010-06-01 23:49:17 -07004877 // create a new effect module if none present in the chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004878 effect = new EffectModule(this, chain, desc, id, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07004879 lStatus = effect->status();
4880 if (lStatus != NO_ERROR) {
4881 goto Exit;
4882 }
Eric Laurent76c40f72010-07-15 12:50:15 -07004883 lStatus = chain->addEffect_l(effect);
Eric Laurent65b65452010-06-01 23:49:17 -07004884 if (lStatus != NO_ERROR) {
4885 goto Exit;
4886 }
Eric Laurent53334cd2010-06-23 17:38:20 -07004887 effectCreated = true;
Eric Laurent65b65452010-06-01 23:49:17 -07004888
4889 effect->setDevice(mDevice);
Eric Laurent53334cd2010-06-23 17:38:20 -07004890 effect->setMode(mAudioFlinger->getMode());
Eric Laurent65b65452010-06-01 23:49:17 -07004891 }
4892 // create effect handle and connect it to effect module
4893 handle = new EffectHandle(effect, client, effectClient, priority);
4894 lStatus = effect->addHandle(handle);
4895 if (enabled) {
4896 *enabled = (int)effect->isEnabled();
4897 }
4898 }
4899
4900Exit:
4901 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004902 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07004903 if (effectCreated) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004904 chain->removeEffect_l(effect);
Eric Laurent65b65452010-06-01 23:49:17 -07004905 }
Eric Laurent53334cd2010-06-23 17:38:20 -07004906 if (effectRegistered) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004907 AudioSystem::unregisterEffect(effect->id());
4908 }
4909 if (chainCreated) {
4910 removeEffectChain_l(chain);
Eric Laurent53334cd2010-06-23 17:38:20 -07004911 }
Eric Laurent65b65452010-06-01 23:49:17 -07004912 handle.clear();
4913 }
4914
4915 if(status) {
4916 *status = lStatus;
4917 }
4918 return handle;
4919}
4920
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004921// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
4922// PlaybackThread::mLock held
4923status_t AudioFlinger::PlaybackThread::addEffect_l(const sp<EffectModule>& effect)
4924{
4925 // check for existing effect chain with the requested audio session
4926 int sessionId = effect->sessionId();
4927 sp<EffectChain> chain = getEffectChain_l(sessionId);
4928 bool chainCreated = false;
4929
4930 if (chain == 0) {
4931 // create a new chain for this session
4932 LOGV("addEffect_l() new effect chain for session %d", sessionId);
4933 chain = new EffectChain(this, sessionId);
4934 addEffectChain_l(chain);
4935 chain->setStrategy(getStrategyForSession_l(sessionId));
4936 chainCreated = true;
4937 }
4938 LOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
4939
4940 if (chain->getEffectFromId_l(effect->id()) != 0) {
4941 LOGW("addEffect_l() %p effect %s already present in chain %p",
4942 this, effect->desc().name, chain.get());
4943 return BAD_VALUE;
4944 }
4945
4946 status_t status = chain->addEffect_l(effect);
4947 if (status != NO_ERROR) {
4948 if (chainCreated) {
4949 removeEffectChain_l(chain);
4950 }
4951 return status;
4952 }
4953
4954 effect->setDevice(mDevice);
4955 effect->setMode(mAudioFlinger->getMode());
4956 return NO_ERROR;
4957}
4958
4959void AudioFlinger::PlaybackThread::removeEffect_l(const sp<EffectModule>& effect) {
4960
4961 LOGV("removeEffect_l() %p effect %p", this, effect.get());
Eric Laurent53334cd2010-06-23 17:38:20 -07004962 effect_descriptor_t desc = effect->desc();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004963 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
4964 detachAuxEffect_l(effect->id());
4965 }
4966
4967 sp<EffectChain> chain = effect->chain().promote();
4968 if (chain != 0) {
4969 // remove effect chain if removing last effect
4970 if (chain->removeEffect_l(effect) == 0) {
4971 removeEffectChain_l(chain);
4972 }
4973 } else {
4974 LOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
4975 }
4976}
4977
4978void AudioFlinger::PlaybackThread::disconnectEffect(const sp<EffectModule>& effect,
4979 const wp<EffectHandle>& handle) {
Eric Laurent53334cd2010-06-23 17:38:20 -07004980 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004981 LOGV("disconnectEffect() %p effect %p", this, effect.get());
Eric Laurent53334cd2010-06-23 17:38:20 -07004982 // delete the effect module if removing last handle on it
4983 if (effect->removeHandle(handle) == 0) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004984 removeEffect_l(effect);
4985 AudioSystem::unregisterEffect(effect->id());
Eric Laurent53334cd2010-06-23 17:38:20 -07004986 }
4987}
4988
Eric Laurent65b65452010-06-01 23:49:17 -07004989status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
4990{
4991 int session = chain->sessionId();
4992 int16_t *buffer = mMixBuffer;
Eric Laurent53334cd2010-06-23 17:38:20 -07004993 bool ownsBuffer = false;
Eric Laurent65b65452010-06-01 23:49:17 -07004994
4995 LOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Eric Laurent53334cd2010-06-23 17:38:20 -07004996 if (session > 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07004997 // Only one effect chain can be present in direct output thread and it uses
4998 // the mix buffer as input
4999 if (mType != DIRECT) {
5000 size_t numSamples = mFrameCount * mChannelCount;
5001 buffer = new int16_t[numSamples];
5002 memset(buffer, 0, numSamples * sizeof(int16_t));
5003 LOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
5004 ownsBuffer = true;
5005 }
Eric Laurent65b65452010-06-01 23:49:17 -07005006
Eric Laurent53334cd2010-06-23 17:38:20 -07005007 // Attach all tracks with same session ID to this chain.
5008 for (size_t i = 0; i < mTracks.size(); ++i) {
5009 sp<Track> track = mTracks[i];
5010 if (session == track->sessionId()) {
5011 LOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
5012 track->setMainBuffer(buffer);
5013 }
5014 }
5015
5016 // indicate all active tracks in the chain
5017 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5018 sp<Track> track = mActiveTracks[i].promote();
5019 if (track == 0) continue;
5020 if (session == track->sessionId()) {
5021 LOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
5022 chain->startTrack();
5023 }
Eric Laurent65b65452010-06-01 23:49:17 -07005024 }
5025 }
5026
Eric Laurent53334cd2010-06-23 17:38:20 -07005027 chain->setInBuffer(buffer, ownsBuffer);
5028 chain->setOutBuffer(mMixBuffer);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005029 // Effect chain for session AudioSystem::SESSION_OUTPUT_STAGE is inserted at end of effect
5030 // chains list in order to be processed last as it contains output stage effects
5031 // Effect chain for session AudioSystem::SESSION_OUTPUT_MIX is inserted before
5032 // session AudioSystem::SESSION_OUTPUT_STAGE to be processed
Eric Laurent53334cd2010-06-23 17:38:20 -07005033 // after track specific effects and before output stage
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005034 // It is therefore mandatory that AudioSystem::SESSION_OUTPUT_MIX == 0 and
5035 // that AudioSystem::SESSION_OUTPUT_STAGE < AudioSystem::SESSION_OUTPUT_MIX
5036 // Effect chain for other sessions are inserted at beginning of effect
5037 // chains list to be processed before output mix effects. Relative order between other
5038 // sessions is not important
Eric Laurent53334cd2010-06-23 17:38:20 -07005039 size_t size = mEffectChains.size();
5040 size_t i = 0;
5041 for (i = 0; i < size; i++) {
5042 if (mEffectChains[i]->sessionId() < session) break;
Eric Laurent65b65452010-06-01 23:49:17 -07005043 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005044 mEffectChains.insertAt(chain, i);
Eric Laurent65b65452010-06-01 23:49:17 -07005045
5046 return NO_ERROR;
5047}
5048
5049size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
5050{
5051 int session = chain->sessionId();
5052
5053 LOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
5054
5055 for (size_t i = 0; i < mEffectChains.size(); i++) {
5056 if (chain == mEffectChains[i]) {
5057 mEffectChains.removeAt(i);
5058 // detach all tracks with same session ID from this chain
5059 for (size_t i = 0; i < mTracks.size(); ++i) {
5060 sp<Track> track = mTracks[i];
5061 if (session == track->sessionId()) {
5062 track->setMainBuffer(mMixBuffer);
5063 }
5064 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005065 break;
Eric Laurent65b65452010-06-01 23:49:17 -07005066 }
5067 }
5068 return mEffectChains.size();
5069}
5070
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005071void AudioFlinger::PlaybackThread::lockEffectChains_l(
5072 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
Eric Laurent65b65452010-06-01 23:49:17 -07005073{
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005074 effectChains = mEffectChains;
Eric Laurent65b65452010-06-01 23:49:17 -07005075 for (size_t i = 0; i < mEffectChains.size(); i++) {
5076 mEffectChains[i]->lock();
5077 }
5078}
5079
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005080void AudioFlinger::PlaybackThread::unlockEffectChains(
5081 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
Eric Laurent65b65452010-06-01 23:49:17 -07005082{
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005083 for (size_t i = 0; i < effectChains.size(); i++) {
5084 effectChains[i]->unlock();
Eric Laurent65b65452010-06-01 23:49:17 -07005085 }
5086}
5087
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005088
Eric Laurent65b65452010-06-01 23:49:17 -07005089sp<AudioFlinger::EffectModule> AudioFlinger::PlaybackThread::getEffect_l(int sessionId, int effectId)
5090{
5091 sp<EffectModule> effect;
5092
5093 sp<EffectChain> chain = getEffectChain_l(sessionId);
5094 if (chain != 0) {
Eric Laurent76c40f72010-07-15 12:50:15 -07005095 effect = chain->getEffectFromId_l(effectId);
Eric Laurent65b65452010-06-01 23:49:17 -07005096 }
5097 return effect;
5098}
5099
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005100status_t AudioFlinger::PlaybackThread::attachAuxEffect(
5101 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Eric Laurent65b65452010-06-01 23:49:17 -07005102{
5103 Mutex::Autolock _l(mLock);
5104 return attachAuxEffect_l(track, EffectId);
5105}
5106
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005107status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
5108 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Eric Laurent65b65452010-06-01 23:49:17 -07005109{
5110 status_t status = NO_ERROR;
5111
5112 if (EffectId == 0) {
5113 track->setAuxBuffer(0, NULL);
5114 } else {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005115 // Auxiliary effects are always in audio session AudioSystem::SESSION_OUTPUT_MIX
5116 sp<EffectModule> effect = getEffect_l(AudioSystem::SESSION_OUTPUT_MIX, EffectId);
Eric Laurent65b65452010-06-01 23:49:17 -07005117 if (effect != 0) {
5118 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5119 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
5120 } else {
5121 status = INVALID_OPERATION;
5122 }
5123 } else {
5124 status = BAD_VALUE;
5125 }
5126 }
5127 return status;
5128}
5129
5130void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
5131{
5132 for (size_t i = 0; i < mTracks.size(); ++i) {
5133 sp<Track> track = mTracks[i];
5134 if (track->auxEffectId() == effectId) {
5135 attachAuxEffect_l(track, 0);
5136 }
5137 }
5138}
5139
5140// ----------------------------------------------------------------------------
5141// EffectModule implementation
5142// ----------------------------------------------------------------------------
5143
5144#undef LOG_TAG
5145#define LOG_TAG "AudioFlinger::EffectModule"
5146
5147AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
5148 const wp<AudioFlinger::EffectChain>& chain,
5149 effect_descriptor_t *desc,
5150 int id,
5151 int sessionId)
5152 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
5153 mStatus(NO_INIT), mState(IDLE)
5154{
5155 LOGV("Constructor %p", this);
5156 int lStatus;
5157 sp<ThreadBase> thread = mThread.promote();
5158 if (thread == 0) {
5159 return;
5160 }
5161 PlaybackThread *p = (PlaybackThread *)thread.get();
5162
5163 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
5164
5165 // create effect engine from effect factory
Eric Laurent53334cd2010-06-23 17:38:20 -07005166 mStatus = EffectCreate(&desc->uuid, sessionId, p->id(), &mEffectInterface);
5167
Eric Laurent65b65452010-06-01 23:49:17 -07005168 if (mStatus != NO_ERROR) {
5169 return;
5170 }
5171 lStatus = init();
5172 if (lStatus < 0) {
5173 mStatus = lStatus;
5174 goto Error;
5175 }
5176
5177 LOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
5178 return;
5179Error:
5180 EffectRelease(mEffectInterface);
5181 mEffectInterface = NULL;
5182 LOGV("Constructor Error %d", mStatus);
5183}
5184
5185AudioFlinger::EffectModule::~EffectModule()
5186{
5187 LOGV("Destructor %p", this);
5188 if (mEffectInterface != NULL) {
5189 // release effect engine
5190 EffectRelease(mEffectInterface);
5191 }
5192}
5193
5194status_t AudioFlinger::EffectModule::addHandle(sp<EffectHandle>& handle)
5195{
5196 status_t status;
5197
5198 Mutex::Autolock _l(mLock);
5199 // First handle in mHandles has highest priority and controls the effect module
5200 int priority = handle->priority();
5201 size_t size = mHandles.size();
5202 sp<EffectHandle> h;
5203 size_t i;
5204 for (i = 0; i < size; i++) {
5205 h = mHandles[i].promote();
5206 if (h == 0) continue;
5207 if (h->priority() <= priority) break;
5208 }
5209 // if inserted in first place, move effect control from previous owner to this handle
5210 if (i == 0) {
5211 if (h != 0) {
5212 h->setControl(false, true);
5213 }
5214 handle->setControl(true, false);
5215 status = NO_ERROR;
5216 } else {
5217 status = ALREADY_EXISTS;
5218 }
5219 mHandles.insertAt(handle, i);
5220 return status;
5221}
5222
5223size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
5224{
5225 Mutex::Autolock _l(mLock);
5226 size_t size = mHandles.size();
5227 size_t i;
5228 for (i = 0; i < size; i++) {
5229 if (mHandles[i] == handle) break;
5230 }
5231 if (i == size) {
5232 return size;
5233 }
5234 mHandles.removeAt(i);
5235 size = mHandles.size();
5236 // if removed from first place, move effect control from this handle to next in line
5237 if (i == 0 && size != 0) {
5238 sp<EffectHandle> h = mHandles[0].promote();
5239 if (h != 0) {
5240 h->setControl(true, true);
5241 }
5242 }
5243
5244 return size;
5245}
5246
5247void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle)
5248{
5249 // keep a strong reference on this EffectModule to avoid calling the
5250 // destructor before we exit
5251 sp<EffectModule> keep(this);
Eric Laurent53334cd2010-06-23 17:38:20 -07005252 {
5253 sp<ThreadBase> thread = mThread.promote();
5254 if (thread != 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07005255 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurent53334cd2010-06-23 17:38:20 -07005256 playbackThread->disconnectEffect(keep, handle);
Eric Laurent65b65452010-06-01 23:49:17 -07005257 }
5258 }
5259}
5260
Eric Laurent7d850f22010-07-09 13:34:17 -07005261void AudioFlinger::EffectModule::updateState() {
5262 Mutex::Autolock _l(mLock);
5263
5264 switch (mState) {
5265 case RESTART:
5266 reset_l();
5267 // FALL THROUGH
5268
5269 case STARTING:
5270 // clear auxiliary effect input buffer for next accumulation
5271 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5272 memset(mConfig.inputCfg.buffer.raw,
5273 0,
5274 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
5275 }
5276 start_l();
5277 mState = ACTIVE;
5278 break;
5279 case STOPPING:
5280 stop_l();
5281 mDisableWaitCnt = mMaxDisableWaitCnt;
5282 mState = STOPPED;
5283 break;
5284 case STOPPED:
5285 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
5286 // turn off sequence.
5287 if (--mDisableWaitCnt == 0) {
5288 reset_l();
5289 mState = IDLE;
5290 }
5291 break;
5292 default: //IDLE , ACTIVE
5293 break;
5294 }
5295}
5296
Eric Laurent65b65452010-06-01 23:49:17 -07005297void AudioFlinger::EffectModule::process()
5298{
5299 Mutex::Autolock _l(mLock);
5300
Eric Laurent7d850f22010-07-09 13:34:17 -07005301 if (mEffectInterface == NULL ||
5302 mConfig.inputCfg.buffer.raw == NULL ||
5303 mConfig.outputCfg.buffer.raw == NULL) {
Eric Laurent65b65452010-06-01 23:49:17 -07005304 return;
5305 }
5306
Eric Laurent7d850f22010-07-09 13:34:17 -07005307 if (mState == ACTIVE || mState == STOPPING || mState == STOPPED) {
Eric Laurent65b65452010-06-01 23:49:17 -07005308 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
5309 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5310 AudioMixer::ditherAndClamp(mConfig.inputCfg.buffer.s32,
5311 mConfig.inputCfg.buffer.s32,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005312 mConfig.inputCfg.buffer.frameCount/2);
Eric Laurent65b65452010-06-01 23:49:17 -07005313 }
5314
Eric Laurent65b65452010-06-01 23:49:17 -07005315 // do the actual processing in the effect engine
Eric Laurent7d850f22010-07-09 13:34:17 -07005316 int ret = (*mEffectInterface)->process(mEffectInterface,
5317 &mConfig.inputCfg.buffer,
5318 &mConfig.outputCfg.buffer);
5319
5320 // force transition to IDLE state when engine is ready
5321 if (mState == STOPPED && ret == -ENODATA) {
5322 mDisableWaitCnt = 1;
5323 }
Eric Laurent65b65452010-06-01 23:49:17 -07005324
5325 // clear auxiliary effect input buffer for next accumulation
5326 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5327 memset(mConfig.inputCfg.buffer.raw, 0, mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
5328 }
5329 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
5330 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw){
5331 // If an insert effect is idle and input buffer is different from output buffer, copy input to
5332 // output
5333 sp<EffectChain> chain = mChain.promote();
5334 if (chain != 0 && chain->activeTracks() != 0) {
5335 size_t size = mConfig.inputCfg.buffer.frameCount * sizeof(int16_t);
5336 if (mConfig.inputCfg.channels == CHANNEL_STEREO) {
5337 size *= 2;
5338 }
5339 memcpy(mConfig.outputCfg.buffer.raw, mConfig.inputCfg.buffer.raw, size);
5340 }
5341 }
5342}
5343
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005344void AudioFlinger::EffectModule::reset_l()
Eric Laurent65b65452010-06-01 23:49:17 -07005345{
5346 if (mEffectInterface == NULL) {
5347 return;
5348 }
5349 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
5350}
5351
5352status_t AudioFlinger::EffectModule::configure()
5353{
5354 uint32_t channels;
5355 if (mEffectInterface == NULL) {
5356 return NO_INIT;
5357 }
5358
5359 sp<ThreadBase> thread = mThread.promote();
5360 if (thread == 0) {
5361 return DEAD_OBJECT;
5362 }
5363
5364 // TODO: handle configuration of effects replacing track process
5365 if (thread->channelCount() == 1) {
5366 channels = CHANNEL_MONO;
5367 } else {
5368 channels = CHANNEL_STEREO;
5369 }
5370
5371 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5372 mConfig.inputCfg.channels = CHANNEL_MONO;
5373 } else {
5374 mConfig.inputCfg.channels = channels;
5375 }
5376 mConfig.outputCfg.channels = channels;
Eric Laurent53334cd2010-06-23 17:38:20 -07005377 mConfig.inputCfg.format = SAMPLE_FORMAT_PCM_S15;
5378 mConfig.outputCfg.format = SAMPLE_FORMAT_PCM_S15;
Eric Laurent65b65452010-06-01 23:49:17 -07005379 mConfig.inputCfg.samplingRate = thread->sampleRate();
5380 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
5381 mConfig.inputCfg.bufferProvider.cookie = NULL;
5382 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
5383 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
5384 mConfig.outputCfg.bufferProvider.cookie = NULL;
5385 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
5386 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
5387 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
5388 // Insert effect:
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005389 // - in session AudioSystem::SESSION_OUTPUT_MIX or AudioSystem::SESSION_OUTPUT_STAGE,
5390 // always overwrites output buffer: input buffer == output buffer
Eric Laurent65b65452010-06-01 23:49:17 -07005391 // - in other sessions:
5392 // last effect in the chain accumulates in output buffer: input buffer != output buffer
5393 // other effect: overwrites output buffer: input buffer == output buffer
5394 // Auxiliary effect:
5395 // accumulates in output buffer: input buffer != output buffer
5396 // Therefore: accumulate <=> input buffer != output buffer
5397 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
5398 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
5399 } else {
5400 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
5401 }
5402 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
5403 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
5404 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
5405 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
5406
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005407 LOGV("configure() %p thread %p buffer %p framecount %d",
5408 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
5409
Eric Laurent65b65452010-06-01 23:49:17 -07005410 status_t cmdStatus;
5411 int size = sizeof(int);
5412 status_t status = (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_CONFIGURE, sizeof(effect_config_t), &mConfig, &size, &cmdStatus);
5413 if (status == 0) {
5414 status = cmdStatus;
5415 }
Eric Laurent7d850f22010-07-09 13:34:17 -07005416
5417 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
5418 (1000 * mConfig.outputCfg.buffer.frameCount);
5419
Eric Laurent65b65452010-06-01 23:49:17 -07005420 return status;
5421}
5422
5423status_t AudioFlinger::EffectModule::init()
5424{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005425 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07005426 if (mEffectInterface == NULL) {
5427 return NO_INIT;
5428 }
5429 status_t cmdStatus;
5430 int size = sizeof(status_t);
5431 status_t status = (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_INIT, 0, NULL, &size, &cmdStatus);
5432 if (status == 0) {
5433 status = cmdStatus;
5434 }
5435 return status;
5436}
5437
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005438status_t AudioFlinger::EffectModule::start_l()
Eric Laurent65b65452010-06-01 23:49:17 -07005439{
5440 if (mEffectInterface == NULL) {
5441 return NO_INIT;
5442 }
5443 status_t cmdStatus;
5444 int size = sizeof(status_t);
5445 status_t status = (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_ENABLE, 0, NULL, &size, &cmdStatus);
5446 if (status == 0) {
5447 status = cmdStatus;
5448 }
5449 return status;
5450}
5451
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005452status_t AudioFlinger::EffectModule::stop_l()
Eric Laurent65b65452010-06-01 23:49:17 -07005453{
5454 if (mEffectInterface == NULL) {
5455 return NO_INIT;
5456 }
5457 status_t cmdStatus;
5458 int size = sizeof(status_t);
5459 status_t status = (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_DISABLE, 0, NULL, &size, &cmdStatus);
5460 if (status == 0) {
5461 status = cmdStatus;
5462 }
5463 return status;
5464}
5465
5466status_t AudioFlinger::EffectModule::command(int cmdCode, int cmdSize, void *pCmdData, int *replySize, void *pReplyData)
5467{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005468 Mutex::Autolock _l(mLock);
5469// LOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Eric Laurent65b65452010-06-01 23:49:17 -07005470
5471 if (mEffectInterface == NULL) {
5472 return NO_INIT;
5473 }
5474 status_t status = (*mEffectInterface)->command(mEffectInterface, cmdCode, cmdSize, pCmdData, replySize, pReplyData);
5475 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
5476 int size = (replySize == NULL) ? 0 : *replySize;
Eric Laurent65b65452010-06-01 23:49:17 -07005477 for (size_t i = 1; i < mHandles.size(); i++) {
5478 sp<EffectHandle> h = mHandles[i].promote();
5479 if (h != 0) {
5480 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
5481 }
5482 }
5483 }
5484 return status;
5485}
5486
5487status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
5488{
5489 Mutex::Autolock _l(mLock);
5490 LOGV("setEnabled %p enabled %d", this, enabled);
5491
5492 if (enabled != isEnabled()) {
5493 switch (mState) {
5494 // going from disabled to enabled
5495 case IDLE:
Eric Laurent7d850f22010-07-09 13:34:17 -07005496 mState = STARTING;
5497 break;
5498 case STOPPED:
5499 mState = RESTART;
Eric Laurent65b65452010-06-01 23:49:17 -07005500 break;
5501 case STOPPING:
5502 mState = ACTIVE;
5503 break;
Eric Laurent65b65452010-06-01 23:49:17 -07005504
5505 // going from enabled to disabled
Eric Laurent7d850f22010-07-09 13:34:17 -07005506 case RESTART:
Eric Laurent65b65452010-06-01 23:49:17 -07005507 case STARTING:
Eric Laurent7d850f22010-07-09 13:34:17 -07005508 mState = IDLE;
Eric Laurent65b65452010-06-01 23:49:17 -07005509 break;
5510 case ACTIVE:
5511 mState = STOPPING;
5512 break;
5513 }
5514 for (size_t i = 1; i < mHandles.size(); i++) {
5515 sp<EffectHandle> h = mHandles[i].promote();
5516 if (h != 0) {
5517 h->setEnabled(enabled);
5518 }
5519 }
5520 }
5521 return NO_ERROR;
5522}
5523
5524bool AudioFlinger::EffectModule::isEnabled()
5525{
5526 switch (mState) {
Eric Laurent7d850f22010-07-09 13:34:17 -07005527 case RESTART:
Eric Laurent65b65452010-06-01 23:49:17 -07005528 case STARTING:
5529 case ACTIVE:
5530 return true;
5531 case IDLE:
5532 case STOPPING:
5533 case STOPPED:
5534 default:
5535 return false;
5536 }
5537}
5538
5539status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
5540{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005541 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07005542 status_t status = NO_ERROR;
5543
5544 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
5545 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent0d7e0482010-07-19 06:24:46 -07005546 if ((mState >= ACTIVE) &&
5547 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
5548 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Eric Laurent65b65452010-06-01 23:49:17 -07005549 status_t cmdStatus;
5550 uint32_t volume[2];
5551 uint32_t *pVolume = NULL;
5552 int size = sizeof(volume);
5553 volume[0] = *left;
5554 volume[1] = *right;
5555 if (controller) {
5556 pVolume = volume;
5557 }
5558 status = (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_SET_VOLUME, size, volume, &size, pVolume);
5559 if (controller && status == NO_ERROR && size == sizeof(volume)) {
5560 *left = volume[0];
5561 *right = volume[1];
5562 }
5563 }
5564 return status;
5565}
5566
5567status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
5568{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005569 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07005570 status_t status = NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07005571 if ((mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
5572 // convert device bit field from AudioSystem to EffectApi format.
5573 device = deviceAudioSystemToEffectApi(device);
5574 if (device == 0) {
5575 return BAD_VALUE;
5576 }
Eric Laurent65b65452010-06-01 23:49:17 -07005577 status_t cmdStatus;
5578 int size = sizeof(status_t);
5579 status = (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_SET_DEVICE, sizeof(uint32_t), &device, &size, &cmdStatus);
5580 if (status == NO_ERROR) {
5581 status = cmdStatus;
5582 }
5583 }
5584 return status;
5585}
5586
Eric Laurent53334cd2010-06-23 17:38:20 -07005587status_t AudioFlinger::EffectModule::setMode(uint32_t mode)
5588{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005589 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07005590 status_t status = NO_ERROR;
5591 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
5592 // convert audio mode from AudioSystem to EffectApi format.
5593 int effectMode = modeAudioSystemToEffectApi(mode);
5594 if (effectMode < 0) {
5595 return BAD_VALUE;
5596 }
5597 status_t cmdStatus;
5598 int size = sizeof(status_t);
5599 status = (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_SET_AUDIO_MODE, sizeof(int), &effectMode, &size, &cmdStatus);
5600 if (status == NO_ERROR) {
5601 status = cmdStatus;
5602 }
5603 }
5604 return status;
5605}
5606
5607// update this table when AudioSystem::audio_devices or audio_device_e (in EffectApi.h) are modified
5608const uint32_t AudioFlinger::EffectModule::sDeviceConvTable[] = {
5609 DEVICE_EARPIECE, // AudioSystem::DEVICE_OUT_EARPIECE
5610 DEVICE_SPEAKER, // AudioSystem::DEVICE_OUT_SPEAKER
5611 DEVICE_WIRED_HEADSET, // case AudioSystem::DEVICE_OUT_WIRED_HEADSET
5612 DEVICE_WIRED_HEADPHONE, // AudioSystem::DEVICE_OUT_WIRED_HEADPHONE
5613 DEVICE_BLUETOOTH_SCO, // AudioSystem::DEVICE_OUT_BLUETOOTH_SCO
5614 DEVICE_BLUETOOTH_SCO_HEADSET, // AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_HEADSET
5615 DEVICE_BLUETOOTH_SCO_CARKIT, // AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_CARKIT
5616 DEVICE_BLUETOOTH_A2DP, // AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP
5617 DEVICE_BLUETOOTH_A2DP_HEADPHONES, // AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES
5618 DEVICE_BLUETOOTH_A2DP_SPEAKER, // AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER
5619 DEVICE_AUX_DIGITAL // AudioSystem::DEVICE_OUT_AUX_DIGITAL
5620};
5621
5622uint32_t AudioFlinger::EffectModule::deviceAudioSystemToEffectApi(uint32_t device)
5623{
5624 uint32_t deviceOut = 0;
5625 while (device) {
5626 const uint32_t i = 31 - __builtin_clz(device);
5627 device &= ~(1 << i);
5628 if (i >= sizeof(sDeviceConvTable)/sizeof(uint32_t)) {
5629 LOGE("device convertion error for AudioSystem device 0x%08x", device);
5630 return 0;
5631 }
5632 deviceOut |= (uint32_t)sDeviceConvTable[i];
5633 }
5634 return deviceOut;
5635}
5636
5637// update this table when AudioSystem::audio_mode or audio_mode_e (in EffectApi.h) are modified
5638const uint32_t AudioFlinger::EffectModule::sModeConvTable[] = {
5639 AUDIO_MODE_NORMAL, // AudioSystem::MODE_NORMAL
5640 AUDIO_MODE_RINGTONE, // AudioSystem::MODE_RINGTONE
5641 AUDIO_MODE_IN_CALL // AudioSystem::MODE_IN_CALL
5642};
5643
5644int AudioFlinger::EffectModule::modeAudioSystemToEffectApi(uint32_t mode)
5645{
5646 int modeOut = -1;
5647 if (mode < sizeof(sModeConvTable) / sizeof(uint32_t)) {
5648 modeOut = (int)sModeConvTable[mode];
5649 }
5650 return modeOut;
5651}
Eric Laurent65b65452010-06-01 23:49:17 -07005652
5653status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
5654{
5655 const size_t SIZE = 256;
5656 char buffer[SIZE];
5657 String8 result;
5658
5659 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
5660 result.append(buffer);
5661
5662 bool locked = tryLock(mLock);
5663 // failed to lock - AudioFlinger is probably deadlocked
5664 if (!locked) {
5665 result.append("\t\tCould not lock Fx mutex:\n");
5666 }
5667
5668 result.append("\t\tSession Status State Engine:\n");
5669 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
5670 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
5671 result.append(buffer);
5672
5673 result.append("\t\tDescriptor:\n");
5674 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
5675 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
5676 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
5677 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
5678 result.append(buffer);
5679 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
5680 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
5681 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
5682 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
5683 result.append(buffer);
5684 snprintf(buffer, SIZE, "\t\t- apiVersion: %04X\n\t\t- flags: %08X\n",
5685 mDescriptor.apiVersion,
5686 mDescriptor.flags);
5687 result.append(buffer);
5688 snprintf(buffer, SIZE, "\t\t- name: %s\n",
5689 mDescriptor.name);
5690 result.append(buffer);
5691 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
5692 mDescriptor.implementor);
5693 result.append(buffer);
5694
5695 result.append("\t\t- Input configuration:\n");
5696 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
5697 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
5698 (uint32_t)mConfig.inputCfg.buffer.raw,
5699 mConfig.inputCfg.buffer.frameCount,
5700 mConfig.inputCfg.samplingRate,
5701 mConfig.inputCfg.channels,
5702 mConfig.inputCfg.format);
5703 result.append(buffer);
5704
5705 result.append("\t\t- Output configuration:\n");
5706 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
5707 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
5708 (uint32_t)mConfig.outputCfg.buffer.raw,
5709 mConfig.outputCfg.buffer.frameCount,
5710 mConfig.outputCfg.samplingRate,
5711 mConfig.outputCfg.channels,
5712 mConfig.outputCfg.format);
5713 result.append(buffer);
5714
5715 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
5716 result.append(buffer);
5717 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
5718 for (size_t i = 0; i < mHandles.size(); ++i) {
5719 sp<EffectHandle> handle = mHandles[i].promote();
5720 if (handle != 0) {
5721 handle->dump(buffer, SIZE);
5722 result.append(buffer);
5723 }
5724 }
5725
5726 result.append("\n");
5727
5728 write(fd, result.string(), result.length());
5729
5730 if (locked) {
5731 mLock.unlock();
5732 }
5733
5734 return NO_ERROR;
5735}
5736
5737// ----------------------------------------------------------------------------
5738// EffectHandle implementation
5739// ----------------------------------------------------------------------------
5740
5741#undef LOG_TAG
5742#define LOG_TAG "AudioFlinger::EffectHandle"
5743
5744AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
5745 const sp<AudioFlinger::Client>& client,
5746 const sp<IEffectClient>& effectClient,
5747 int32_t priority)
5748 : BnEffect(),
5749 mEffect(effect), mEffectClient(effectClient), mClient(client), mPriority(priority), mHasControl(false)
5750{
5751 LOGV("constructor %p", this);
5752
5753 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
5754 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
5755 if (mCblkMemory != 0) {
5756 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
5757
5758 if (mCblk) {
5759 new(mCblk) effect_param_cblk_t();
5760 mBuffer = (uint8_t *)mCblk + bufOffset;
5761 }
5762 } else {
5763 LOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
5764 return;
5765 }
5766}
5767
5768AudioFlinger::EffectHandle::~EffectHandle()
5769{
5770 LOGV("Destructor %p", this);
5771 disconnect();
5772}
5773
5774status_t AudioFlinger::EffectHandle::enable()
5775{
5776 if (!mHasControl) return INVALID_OPERATION;
5777 if (mEffect == 0) return DEAD_OBJECT;
5778
5779 return mEffect->setEnabled(true);
5780}
5781
5782status_t AudioFlinger::EffectHandle::disable()
5783{
5784 if (!mHasControl) return INVALID_OPERATION;
5785 if (mEffect == NULL) return DEAD_OBJECT;
5786
5787 return mEffect->setEnabled(false);
5788}
5789
5790void AudioFlinger::EffectHandle::disconnect()
5791{
5792 if (mEffect == 0) {
5793 return;
5794 }
5795 mEffect->disconnect(this);
5796 // release sp on module => module destructor can be called now
5797 mEffect.clear();
5798 if (mCblk) {
5799 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
5800 }
5801 mCblkMemory.clear(); // and free the shared memory
5802 if (mClient != 0) {
5803 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
5804 mClient.clear();
5805 }
5806}
5807
5808status_t AudioFlinger::EffectHandle::command(int cmdCode, int cmdSize, void *pCmdData, int *replySize, void *pReplyData)
5809{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005810// LOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p", cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Eric Laurent65b65452010-06-01 23:49:17 -07005811
5812 // only get parameter command is permitted for applications not controlling the effect
5813 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
5814 return INVALID_OPERATION;
5815 }
5816 if (mEffect == 0) return DEAD_OBJECT;
5817
5818 // handle commands that are not forwarded transparently to effect engine
5819 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
5820 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
5821 // no risk to block the whole media server process or mixer threads is we are stuck here
5822 Mutex::Autolock _l(mCblk->lock);
5823 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
5824 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
5825 mCblk->serverIndex = 0;
5826 mCblk->clientIndex = 0;
5827 return BAD_VALUE;
5828 }
5829 status_t status = NO_ERROR;
5830 while (mCblk->serverIndex < mCblk->clientIndex) {
5831 int reply;
5832 int rsize = sizeof(int);
5833 int *p = (int *)(mBuffer + mCblk->serverIndex);
5834 int size = *p++;
Eric Laurent53334cd2010-06-23 17:38:20 -07005835 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
5836 LOGW("command(): invalid parameter block size");
5837 break;
5838 }
Eric Laurent65b65452010-06-01 23:49:17 -07005839 effect_param_t *param = (effect_param_t *)p;
Eric Laurent53334cd2010-06-23 17:38:20 -07005840 if (param->psize == 0 || param->vsize == 0) {
5841 LOGW("command(): null parameter or value size");
5842 mCblk->serverIndex += size;
5843 continue;
5844 }
Eric Laurent65b65452010-06-01 23:49:17 -07005845 int psize = sizeof(effect_param_t) + ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) + param->vsize;
5846 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM, psize, p, &rsize, &reply);
5847 if (ret == NO_ERROR) {
5848 if (reply != NO_ERROR) {
5849 status = reply;
5850 }
5851 } else {
5852 status = ret;
5853 }
5854 mCblk->serverIndex += size;
5855 }
5856 mCblk->serverIndex = 0;
5857 mCblk->clientIndex = 0;
5858 return status;
5859 } else if (cmdCode == EFFECT_CMD_ENABLE) {
5860 return enable();
5861 } else if (cmdCode == EFFECT_CMD_DISABLE) {
5862 return disable();
5863 }
5864
5865 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
5866}
5867
5868sp<IMemory> AudioFlinger::EffectHandle::getCblk() const {
5869 return mCblkMemory;
5870}
5871
5872void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal)
5873{
5874 LOGV("setControl %p control %d", this, hasControl);
5875
5876 mHasControl = hasControl;
5877 if (signal && mEffectClient != 0) {
5878 mEffectClient->controlStatusChanged(hasControl);
5879 }
5880}
5881
5882void AudioFlinger::EffectHandle::commandExecuted(int cmdCode, int cmdSize, void *pCmdData, int replySize, void *pReplyData)
5883{
5884 if (mEffectClient != 0) {
5885 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
5886 }
5887}
5888
5889
5890
5891void AudioFlinger::EffectHandle::setEnabled(bool enabled)
5892{
5893 if (mEffectClient != 0) {
5894 mEffectClient->enableStatusChanged(enabled);
5895 }
5896}
5897
5898status_t AudioFlinger::EffectHandle::onTransact(
5899 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5900{
5901 return BnEffect::onTransact(code, data, reply, flags);
5902}
5903
5904
5905void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
5906{
5907 bool locked = tryLock(mCblk->lock);
5908
5909 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
5910 (mClient == NULL) ? getpid() : mClient->pid(),
5911 mPriority,
5912 mHasControl,
5913 !locked,
5914 mCblk->clientIndex,
5915 mCblk->serverIndex
5916 );
5917
5918 if (locked) {
5919 mCblk->lock.unlock();
5920 }
5921}
5922
5923#undef LOG_TAG
5924#define LOG_TAG "AudioFlinger::EffectChain"
5925
5926AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
5927 int sessionId)
Eric Laurent76c40f72010-07-15 12:50:15 -07005928 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mOwnInBuffer(false),
Eric Laurent0d7e0482010-07-19 06:24:46 -07005929 mVolumeCtrlIdx(-1), mLeftVolume(0), mRightVolume(0),
5930 mNewLeftVolume(0), mNewRightVolume(0)
Eric Laurent65b65452010-06-01 23:49:17 -07005931{
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005932 mStrategy = AudioSystem::getStrategyForStream(AudioSystem::MUSIC);
Eric Laurent65b65452010-06-01 23:49:17 -07005933}
5934
5935AudioFlinger::EffectChain::~EffectChain()
5936{
5937 if (mOwnInBuffer) {
5938 delete mInBuffer;
5939 }
5940
5941}
5942
Eric Laurent76c40f72010-07-15 12:50:15 -07005943// getEffectFromDesc_l() must be called with PlaybackThread::mLock held
5944sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Eric Laurent65b65452010-06-01 23:49:17 -07005945{
5946 sp<EffectModule> effect;
5947 size_t size = mEffects.size();
5948
5949 for (size_t i = 0; i < size; i++) {
5950 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
5951 effect = mEffects[i];
5952 break;
5953 }
5954 }
5955 return effect;
5956}
5957
Eric Laurent76c40f72010-07-15 12:50:15 -07005958// getEffectFromId_l() must be called with PlaybackThread::mLock held
5959sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Eric Laurent65b65452010-06-01 23:49:17 -07005960{
5961 sp<EffectModule> effect;
5962 size_t size = mEffects.size();
5963
5964 for (size_t i = 0; i < size; i++) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005965 // by convention, return first effect if id provided is 0 (0 is never a valid id)
5966 if (id == 0 || mEffects[i]->id() == id) {
Eric Laurent65b65452010-06-01 23:49:17 -07005967 effect = mEffects[i];
5968 break;
5969 }
5970 }
5971 return effect;
5972}
5973
5974// Must be called with EffectChain::mLock locked
5975void AudioFlinger::EffectChain::process_l()
5976{
5977 size_t size = mEffects.size();
5978 for (size_t i = 0; i < size; i++) {
5979 mEffects[i]->process();
5980 }
Eric Laurent7d850f22010-07-09 13:34:17 -07005981 for (size_t i = 0; i < size; i++) {
5982 mEffects[i]->updateState();
5983 }
Eric Laurent65b65452010-06-01 23:49:17 -07005984 // if no track is active, input buffer must be cleared here as the mixer process
5985 // will not do it
Eric Laurent53334cd2010-06-23 17:38:20 -07005986 if (mSessionId > 0 && activeTracks() == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07005987 sp<ThreadBase> thread = mThread.promote();
5988 if (thread != 0) {
5989 size_t numSamples = thread->frameCount() * thread->channelCount();
5990 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
5991 }
5992 }
5993}
5994
Eric Laurent76c40f72010-07-15 12:50:15 -07005995// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005996status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Eric Laurent65b65452010-06-01 23:49:17 -07005997{
5998 effect_descriptor_t desc = effect->desc();
5999 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
6000
6001 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006002 effect->setChain(this);
6003 sp<ThreadBase> thread = mThread.promote();
6004 if (thread == 0) {
6005 return NO_INIT;
6006 }
6007 effect->setThread(thread);
Eric Laurent65b65452010-06-01 23:49:17 -07006008
6009 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6010 // Auxiliary effects are inserted at the beginning of mEffects vector as
6011 // they are processed first and accumulated in chain input buffer
6012 mEffects.insertAt(effect, 0);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006013
Eric Laurent65b65452010-06-01 23:49:17 -07006014 // the input buffer for auxiliary effect contains mono samples in
6015 // 32 bit format. This is to avoid saturation in AudoMixer
6016 // accumulation stage. Saturation is done in EffectModule::process() before
6017 // calling the process in effect engine
6018 size_t numSamples = thread->frameCount();
6019 int32_t *buffer = new int32_t[numSamples];
6020 memset(buffer, 0, numSamples * sizeof(int32_t));
6021 effect->setInBuffer((int16_t *)buffer);
6022 // auxiliary effects output samples to chain input buffer for further processing
6023 // by insert effects
6024 effect->setOutBuffer(mInBuffer);
6025 } else {
6026 // Insert effects are inserted at the end of mEffects vector as they are processed
6027 // after track and auxiliary effects.
Eric Laurent53334cd2010-06-23 17:38:20 -07006028 // Insert effect order as a function of indicated preference:
6029 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
6030 // another effect is present
6031 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
6032 // last effect claiming first position
6033 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
6034 // first effect claiming last position
Eric Laurent65b65452010-06-01 23:49:17 -07006035 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
Eric Laurent53334cd2010-06-23 17:38:20 -07006036 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
6037 // already present
Eric Laurent65b65452010-06-01 23:49:17 -07006038
6039 int size = (int)mEffects.size();
6040 int idx_insert = size;
6041 int idx_insert_first = -1;
6042 int idx_insert_last = -1;
6043
6044 for (int i = 0; i < size; i++) {
6045 effect_descriptor_t d = mEffects[i]->desc();
6046 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
6047 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
6048 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
6049 // check invalid effect chaining combinations
6050 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
Eric Laurent53334cd2010-06-23 17:38:20 -07006051 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Eric Laurent76c40f72010-07-15 12:50:15 -07006052 LOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Eric Laurent65b65452010-06-01 23:49:17 -07006053 return INVALID_OPERATION;
6054 }
Eric Laurent53334cd2010-06-23 17:38:20 -07006055 // remember position of first insert effect and by default
6056 // select this as insert position for new effect
Eric Laurent65b65452010-06-01 23:49:17 -07006057 if (idx_insert == size) {
6058 idx_insert = i;
6059 }
Eric Laurent53334cd2010-06-23 17:38:20 -07006060 // remember position of last insert effect claiming
6061 // first position
Eric Laurent65b65452010-06-01 23:49:17 -07006062 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
6063 idx_insert_first = i;
6064 }
Eric Laurent53334cd2010-06-23 17:38:20 -07006065 // remember position of first insert effect claiming
6066 // last position
6067 if (iPref == EFFECT_FLAG_INSERT_LAST &&
6068 idx_insert_last == -1) {
Eric Laurent65b65452010-06-01 23:49:17 -07006069 idx_insert_last = i;
6070 }
6071 }
6072 }
6073
Eric Laurent53334cd2010-06-23 17:38:20 -07006074 // modify idx_insert from first position if needed
6075 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
6076 if (idx_insert_last != -1) {
6077 idx_insert = idx_insert_last;
6078 } else {
6079 idx_insert = size;
6080 }
6081 } else {
6082 if (idx_insert_first != -1) {
6083 idx_insert = idx_insert_first + 1;
6084 }
Eric Laurent65b65452010-06-01 23:49:17 -07006085 }
6086
6087 // always read samples from chain input buffer
6088 effect->setInBuffer(mInBuffer);
6089
6090 // if last effect in the chain, output samples to chain
6091 // output buffer, otherwise to chain input buffer
6092 if (idx_insert == size) {
6093 if (idx_insert != 0) {
6094 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
6095 mEffects[idx_insert-1]->configure();
6096 }
6097 effect->setOutBuffer(mOutBuffer);
6098 } else {
6099 effect->setOutBuffer(mInBuffer);
6100 }
Eric Laurent53334cd2010-06-23 17:38:20 -07006101 mEffects.insertAt(effect, idx_insert);
Eric Laurent65b65452010-06-01 23:49:17 -07006102
Eric Laurent76c40f72010-07-15 12:50:15 -07006103 LOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Eric Laurent65b65452010-06-01 23:49:17 -07006104 }
6105 effect->configure();
6106 return NO_ERROR;
6107}
6108
Eric Laurent76c40f72010-07-15 12:50:15 -07006109// removeEffect_l() must be called with PlaybackThread::mLock held
6110size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Eric Laurent65b65452010-06-01 23:49:17 -07006111{
6112 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07006113 int size = (int)mEffects.size();
6114 int i;
6115 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
6116
6117 for (i = 0; i < size; i++) {
6118 if (effect == mEffects[i]) {
6119 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
6120 delete[] effect->inBuffer();
6121 } else {
6122 if (i == size - 1 && i != 0) {
6123 mEffects[i - 1]->setOutBuffer(mOutBuffer);
6124 mEffects[i - 1]->configure();
6125 }
6126 }
6127 mEffects.removeAt(i);
Eric Laurent76c40f72010-07-15 12:50:15 -07006128 LOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Eric Laurent65b65452010-06-01 23:49:17 -07006129 break;
6130 }
6131 }
Eric Laurent65b65452010-06-01 23:49:17 -07006132
6133 return mEffects.size();
6134}
6135
Eric Laurent76c40f72010-07-15 12:50:15 -07006136// setDevice_l() must be called with PlaybackThread::mLock held
6137void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Eric Laurent65b65452010-06-01 23:49:17 -07006138{
6139 size_t size = mEffects.size();
6140 for (size_t i = 0; i < size; i++) {
6141 mEffects[i]->setDevice(device);
6142 }
6143}
6144
Eric Laurent76c40f72010-07-15 12:50:15 -07006145// setMode_l() must be called with PlaybackThread::mLock held
6146void AudioFlinger::EffectChain::setMode_l(uint32_t mode)
Eric Laurent53334cd2010-06-23 17:38:20 -07006147{
6148 size_t size = mEffects.size();
6149 for (size_t i = 0; i < size; i++) {
6150 mEffects[i]->setMode(mode);
6151 }
6152}
6153
Eric Laurent76c40f72010-07-15 12:50:15 -07006154// setVolume_l() must be called with PlaybackThread::mLock held
6155bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Eric Laurent65b65452010-06-01 23:49:17 -07006156{
6157 uint32_t newLeft = *left;
6158 uint32_t newRight = *right;
6159 bool hasControl = false;
Eric Laurent76c40f72010-07-15 12:50:15 -07006160 int ctrlIdx = -1;
6161 size_t size = mEffects.size();
Eric Laurent65b65452010-06-01 23:49:17 -07006162
Eric Laurent76c40f72010-07-15 12:50:15 -07006163 // first update volume controller
6164 for (size_t i = size; i > 0; i--) {
Eric Laurent0d7e0482010-07-19 06:24:46 -07006165 if ((mEffects[i - 1]->state() >= EffectModule::ACTIVE) &&
Eric Laurent76c40f72010-07-15 12:50:15 -07006166 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
6167 ctrlIdx = i - 1;
Eric Laurent0d7e0482010-07-19 06:24:46 -07006168 hasControl = true;
Eric Laurent76c40f72010-07-15 12:50:15 -07006169 break;
6170 }
6171 }
6172
6173 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurent0d7e0482010-07-19 06:24:46 -07006174 if (hasControl) {
6175 *left = mNewLeftVolume;
6176 *right = mNewRightVolume;
6177 }
6178 return hasControl;
Eric Laurent76c40f72010-07-15 12:50:15 -07006179 }
6180
Eric Laurent0d7e0482010-07-19 06:24:46 -07006181 if (mVolumeCtrlIdx != -1) {
6182 hasControl = true;
6183 }
Eric Laurent76c40f72010-07-15 12:50:15 -07006184 mVolumeCtrlIdx = ctrlIdx;
Eric Laurent0d7e0482010-07-19 06:24:46 -07006185 mLeftVolume = newLeft;
6186 mRightVolume = newRight;
Eric Laurent76c40f72010-07-15 12:50:15 -07006187
6188 // second get volume update from volume controller
6189 if (ctrlIdx >= 0) {
6190 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurent0d7e0482010-07-19 06:24:46 -07006191 mNewLeftVolume = newLeft;
6192 mNewRightVolume = newRight;
Eric Laurent65b65452010-06-01 23:49:17 -07006193 }
6194 // then indicate volume to all other effects in chain.
6195 // Pass altered volume to effects before volume controller
6196 // and requested volume to effects after controller
6197 uint32_t lVol = newLeft;
6198 uint32_t rVol = newRight;
Eric Laurent76c40f72010-07-15 12:50:15 -07006199
Eric Laurent65b65452010-06-01 23:49:17 -07006200 for (size_t i = 0; i < size; i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07006201 if ((int)i == ctrlIdx) continue;
6202 // this also works for ctrlIdx == -1 when there is no volume controller
6203 if ((int)i > ctrlIdx) {
Eric Laurent65b65452010-06-01 23:49:17 -07006204 lVol = *left;
6205 rVol = *right;
6206 }
6207 mEffects[i]->setVolume(&lVol, &rVol, false);
6208 }
6209 *left = newLeft;
6210 *right = newRight;
6211
6212 return hasControl;
6213}
6214
Eric Laurent65b65452010-06-01 23:49:17 -07006215status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
6216{
6217 const size_t SIZE = 256;
6218 char buffer[SIZE];
6219 String8 result;
6220
6221 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
6222 result.append(buffer);
6223
6224 bool locked = tryLock(mLock);
6225 // failed to lock - AudioFlinger is probably deadlocked
6226 if (!locked) {
6227 result.append("\tCould not lock mutex:\n");
6228 }
6229
Eric Laurent76c40f72010-07-15 12:50:15 -07006230 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
6231 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Eric Laurent65b65452010-06-01 23:49:17 -07006232 mEffects.size(),
6233 (uint32_t)mInBuffer,
6234 (uint32_t)mOutBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -07006235 mActiveTrackCnt);
6236 result.append(buffer);
6237 write(fd, result.string(), result.size());
6238
6239 for (size_t i = 0; i < mEffects.size(); ++i) {
6240 sp<EffectModule> effect = mEffects[i];
6241 if (effect != 0) {
6242 effect->dump(fd, args);
6243 }
6244 }
6245
6246 if (locked) {
6247 mLock.unlock();
6248 }
6249
6250 return NO_ERROR;
6251}
6252
6253#undef LOG_TAG
6254#define LOG_TAG "AudioFlinger"
6255
Eric Laurenta553c252009-07-17 12:17:14 -07006256// ----------------------------------------------------------------------------
6257
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07006258status_t AudioFlinger::onTransact(
6259 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6260{
6261 return BnAudioFlinger::onTransact(code, data, reply, flags);
6262}
6263
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07006264}; // namespace android