blob: 48c04a6680c18b68d937e9e49fd4c86762b0557f [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"
20//#define LOG_NDEBUG 0
21
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 Laurent65b65452010-06-01 23:49:17 -070055
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056// ----------------------------------------------------------------------------
57// the sim build doesn't have gettid
58
59#ifndef HAVE_GETTID
60# define gettid getpid
61#endif
62
63// ----------------------------------------------------------------------------
64
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070065namespace android {
66
The Android Open Source Project10592532009-03-18 17:39:46 -070067static const char* kDeadlockedString = "AudioFlinger may be deadlocked\n";
68static const char* kHardwareLockedString = "Hardware lock is taken\n";
69
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080070//static const nsecs_t kStandbyTimeInNsecs = seconds(3);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070071static const float MAX_GAIN = 4096.0f;
Eric Laurent65b65452010-06-01 23:49:17 -070072static const float MAX_GAIN_INT = 0x1000;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070073
74// retry counts for buffer fill timeout
75// 50 * ~20msecs = 1 second
76static const int8_t kMaxTrackRetries = 50;
77static const int8_t kMaxTrackStartupRetries = 50;
Eric Laurentef9500f2010-03-11 14:47:00 -080078// allow less retry attempts on direct output thread.
79// direct outputs can be a scarce resource in audio hardware and should
80// be released as quickly as possible.
81static const int8_t kMaxTrackRetriesDirect = 2;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070082
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -070083static const int kDumpLockRetries = 50;
84static const int kDumpLockSleep = 20000;
85
Dave Sparksd0ac8c02009-09-30 03:09:03 -070086static const nsecs_t kWarningThrottle = seconds(5);
87
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070089#define AUDIOFLINGER_SECURITY_ENABLED 1
90
91// ----------------------------------------------------------------------------
92
93static bool recordingAllowed() {
94#ifndef HAVE_ANDROID_OS
95 return true;
96#endif
97#if AUDIOFLINGER_SECURITY_ENABLED
98 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
99 bool ok = checkCallingPermission(String16("android.permission.RECORD_AUDIO"));
100 if (!ok) LOGE("Request requires android.permission.RECORD_AUDIO");
101 return ok;
102#else
103 if (!checkCallingPermission(String16("android.permission.RECORD_AUDIO")))
104 LOGW("WARNING: Need to add android.permission.RECORD_AUDIO to manifest");
105 return true;
106#endif
107}
108
109static bool settingsAllowed() {
110#ifndef HAVE_ANDROID_OS
111 return true;
112#endif
113#if AUDIOFLINGER_SECURITY_ENABLED
114 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
115 bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
116 if (!ok) LOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
117 return ok;
118#else
119 if (!checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS")))
120 LOGW("WARNING: Need to add android.permission.MODIFY_AUDIO_SETTINGS to manifest");
121 return true;
122#endif
123}
124
125// ----------------------------------------------------------------------------
126
127AudioFlinger::AudioFlinger()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128 : BnAudioFlinger(),
Eric Laurent53334cd2010-06-23 17:38:20 -0700129 mAudioHardware(0), mMasterVolume(1.0f), mMasterMute(false), mNextUniqueId(1),
130 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700131{
132 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -0700133
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700134 mAudioHardware = AudioHardwareInterface::create();
Eric Laurenta553c252009-07-17 12:17:14 -0700135
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700136 mHardwareStatus = AUDIO_HW_INIT;
137 if (mAudioHardware->initCheck() == NO_ERROR) {
138 // open 16-bit output stream for s/w mixer
Eric Laurent53334cd2010-06-23 17:38:20 -0700139 mMode = AudioSystem::MODE_NORMAL;
140 setMode(mMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800141
142 setMasterVolume(1.0f);
143 setMasterMute(false);
Eric Laurenta553c252009-07-17 12:17:14 -0700144 } else {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700145 LOGE("Couldn't even initialize the stubbed audio hardware!");
146 }
Glenn Kasten871c16c2010-03-05 12:18:01 -0800147#ifdef LVMX
148 LifeVibes::init();
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700149 mLifeVibesClientPid = -1;
Glenn Kasten871c16c2010-03-05 12:18:01 -0800150#endif
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700151}
152
153AudioFlinger::~AudioFlinger()
154{
Eric Laurent7954c462009-08-28 10:39:03 -0700155 while (!mRecordThreads.isEmpty()) {
156 // closeInput() will remove first entry from mRecordThreads
157 closeInput(mRecordThreads.keyAt(0));
158 }
159 while (!mPlaybackThreads.isEmpty()) {
160 // closeOutput() will remove first entry from mPlaybackThreads
161 closeOutput(mPlaybackThreads.keyAt(0));
162 }
163 if (mAudioHardware) {
164 delete mAudioHardware;
165 }
The Android Open Source Projectb7986892009-01-09 17:51:23 -0800166}
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800167
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700168
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700169
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700170status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
171{
172 const size_t SIZE = 256;
173 char buffer[SIZE];
174 String8 result;
175
176 result.append("Clients:\n");
177 for (size_t i = 0; i < mClients.size(); ++i) {
178 wp<Client> wClient = mClients.valueAt(i);
179 if (wClient != 0) {
180 sp<Client> client = wClient.promote();
181 if (client != 0) {
182 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
183 result.append(buffer);
184 }
185 }
186 }
187 write(fd, result.string(), result.size());
188 return NO_ERROR;
189}
190
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700191
192status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
193{
194 const size_t SIZE = 256;
195 char buffer[SIZE];
196 String8 result;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700197 int hardwareStatus = mHardwareStatus;
Eric Laurenta553c252009-07-17 12:17:14 -0700198
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700199 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700200 result.append(buffer);
201 write(fd, result.string(), result.size());
202 return NO_ERROR;
203}
204
205status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
206{
207 const size_t SIZE = 256;
208 char buffer[SIZE];
209 String8 result;
210 snprintf(buffer, SIZE, "Permission Denial: "
211 "can't dump AudioFlinger from pid=%d, uid=%d\n",
212 IPCThreadState::self()->getCallingPid(),
213 IPCThreadState::self()->getCallingUid());
214 result.append(buffer);
215 write(fd, result.string(), result.size());
216 return NO_ERROR;
217}
218
The Android Open Source Project10592532009-03-18 17:39:46 -0700219static bool tryLock(Mutex& mutex)
220{
221 bool locked = false;
222 for (int i = 0; i < kDumpLockRetries; ++i) {
223 if (mutex.tryLock() == NO_ERROR) {
224 locked = true;
225 break;
226 }
227 usleep(kDumpLockSleep);
228 }
229 return locked;
230}
231
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700232status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
233{
234 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
235 dumpPermissionDenial(fd, args);
236 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -0700237 // get state of hardware lock
238 bool hardwareLocked = tryLock(mHardwareLock);
239 if (!hardwareLocked) {
240 String8 result(kHardwareLockedString);
241 write(fd, result.string(), result.size());
242 } else {
243 mHardwareLock.unlock();
244 }
245
246 bool locked = tryLock(mLock);
247
248 // failed to lock - AudioFlinger is probably deadlocked
249 if (!locked) {
250 String8 result(kDeadlockedString);
251 write(fd, result.string(), result.size());
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700252 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700253
254 dumpClients(fd, args);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700255 dumpInternals(fd, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800256
Eric Laurenta553c252009-07-17 12:17:14 -0700257 // dump playback threads
258 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700259 mPlaybackThreads.valueAt(i)->dump(fd, args);
Eric Laurenta553c252009-07-17 12:17:14 -0700260 }
261
262 // dump record threads
Eric Laurent102313a2009-07-23 13:35:01 -0700263 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700264 mRecordThreads.valueAt(i)->dump(fd, args);
Eric Laurenta553c252009-07-17 12:17:14 -0700265 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800266
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700267 if (mAudioHardware) {
268 mAudioHardware->dumpState(fd, args);
269 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700270 if (locked) mLock.unlock();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700271 }
272 return NO_ERROR;
273}
274
Eric Laurenta553c252009-07-17 12:17:14 -0700275
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700276// IAudioFlinger interface
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800277
278
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700279sp<IAudioTrack> AudioFlinger::createTrack(
280 pid_t pid,
281 int streamType,
282 uint32_t sampleRate,
283 int format,
284 int channelCount,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800285 int frameCount,
286 uint32_t flags,
287 const sp<IMemory>& sharedBuffer,
Eric Laurentddb78e72009-07-28 08:44:33 -0700288 int output,
Eric Laurent65b65452010-06-01 23:49:17 -0700289 int *sessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800290 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700291{
Eric Laurenta553c252009-07-17 12:17:14 -0700292 sp<PlaybackThread::Track> track;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700293 sp<TrackHandle> trackHandle;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700294 sp<Client> client;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800295 wp<Client> wclient;
296 status_t lStatus;
Eric Laurent65b65452010-06-01 23:49:17 -0700297 int lSessionId;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700298
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800299 if (streamType >= AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800300 LOGE("invalid stream type");
301 lStatus = BAD_VALUE;
302 goto Exit;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700303 }
304
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800305 {
306 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700307 PlaybackThread *thread = checkPlaybackThread_l(output);
308 if (thread == NULL) {
309 LOGE("unknown output thread");
310 lStatus = BAD_VALUE;
311 goto Exit;
312 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800313
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800314 wclient = mClients.valueFor(pid);
315
316 if (wclient != NULL) {
317 client = wclient.promote();
318 } else {
319 client = new Client(this, pid);
320 mClients.add(pid, client);
321 }
Eric Laurent65b65452010-06-01 23:49:17 -0700322
323 // If no audio session id is provided, create one here
324 // TODO: enforce same stream type for all tracks in same audio session?
325 // TODO: prevent same audio session on different output threads
326 LOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
327 if (sessionId != NULL && *sessionId != 0) {
328 lSessionId = *sessionId;
329 } else {
330 lSessionId = nextUniqueId();
331 if (sessionId != NULL) {
332 *sessionId = lSessionId;
333 }
334 }
335 LOGV("createTrack() lSessionId: %d", lSessionId);
336
Eric Laurenta553c252009-07-17 12:17:14 -0700337 track = thread->createTrack_l(client, streamType, sampleRate, format,
Eric Laurent65b65452010-06-01 23:49:17 -0700338 channelCount, frameCount, sharedBuffer, lSessionId, &lStatus);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700339 }
340 if (lStatus == NO_ERROR) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800341 trackHandle = new TrackHandle(track);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700342 } else {
Eric Laurentb9481d82009-09-17 05:12:56 -0700343 // remove local strong reference to Client before deleting the Track so that the Client
344 // destructor is called by the TrackBase destructor with mLock held
345 client.clear();
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700346 track.clear();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800347 }
348
349Exit:
350 if(status) {
351 *status = lStatus;
352 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700353 return trackHandle;
354}
355
Eric Laurentddb78e72009-07-28 08:44:33 -0700356uint32_t AudioFlinger::sampleRate(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700357{
Eric Laurenta553c252009-07-17 12:17:14 -0700358 Mutex::Autolock _l(mLock);
359 PlaybackThread *thread = checkPlaybackThread_l(output);
360 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700361 LOGW("sampleRate() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700362 return 0;
363 }
364 return thread->sampleRate();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700365}
366
Eric Laurentddb78e72009-07-28 08:44:33 -0700367int AudioFlinger::channelCount(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700368{
Eric Laurenta553c252009-07-17 12:17:14 -0700369 Mutex::Autolock _l(mLock);
370 PlaybackThread *thread = checkPlaybackThread_l(output);
371 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700372 LOGW("channelCount() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700373 return 0;
374 }
375 return thread->channelCount();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700376}
377
Eric Laurentddb78e72009-07-28 08:44:33 -0700378int AudioFlinger::format(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700379{
Eric Laurenta553c252009-07-17 12:17:14 -0700380 Mutex::Autolock _l(mLock);
381 PlaybackThread *thread = checkPlaybackThread_l(output);
382 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700383 LOGW("format() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700384 return 0;
385 }
386 return thread->format();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700387}
388
Eric Laurentddb78e72009-07-28 08:44:33 -0700389size_t AudioFlinger::frameCount(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700390{
Eric Laurenta553c252009-07-17 12:17:14 -0700391 Mutex::Autolock _l(mLock);
392 PlaybackThread *thread = checkPlaybackThread_l(output);
393 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700394 LOGW("frameCount() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700395 return 0;
396 }
397 return thread->frameCount();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700398}
399
Eric Laurentddb78e72009-07-28 08:44:33 -0700400uint32_t AudioFlinger::latency(int output) const
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800401{
Eric Laurenta553c252009-07-17 12:17:14 -0700402 Mutex::Autolock _l(mLock);
403 PlaybackThread *thread = checkPlaybackThread_l(output);
404 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700405 LOGW("latency() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700406 return 0;
407 }
408 return thread->latency();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800409}
410
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700411status_t AudioFlinger::setMasterVolume(float value)
412{
413 // check calling permissions
414 if (!settingsAllowed()) {
415 return PERMISSION_DENIED;
416 }
417
418 // when hw supports master volume, don't scale in sw mixer
419 AutoMutex lock(mHardwareLock);
420 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
421 if (mAudioHardware->setMasterVolume(value) == NO_ERROR) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800422 value = 1.0f;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700423 }
424 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -0700425
426 mMasterVolume = value;
427 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700428 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700429
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700430 return NO_ERROR;
431}
432
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700433status_t AudioFlinger::setMode(int mode)
434{
Eric Laurent53334cd2010-06-23 17:38:20 -0700435 status_t ret;
436
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700437 // check calling permissions
438 if (!settingsAllowed()) {
439 return PERMISSION_DENIED;
440 }
441 if ((mode < 0) || (mode >= AudioSystem::NUM_MODES)) {
442 LOGW("Illegal value: setMode(%d)", mode);
443 return BAD_VALUE;
444 }
445
Eric Laurent53334cd2010-06-23 17:38:20 -0700446 { // scope for the lock
447 AutoMutex lock(mHardwareLock);
448 mHardwareStatus = AUDIO_HW_SET_MODE;
449 ret = mAudioHardware->setMode(mode);
450 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten871c16c2010-03-05 12:18:01 -0800451 }
Eric Laurent53334cd2010-06-23 17:38:20 -0700452
453 if (NO_ERROR == ret) {
454 Mutex::Autolock _l(mLock);
455 mMode = mode;
456 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
457 mPlaybackThreads.valueAt(i)->setMode(mode);
458#ifdef LVMX
459 LifeVibes::setMode(mode);
Glenn Kasten871c16c2010-03-05 12:18:01 -0800460#endif
Eric Laurent53334cd2010-06-23 17:38:20 -0700461 }
462
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700463 return ret;
464}
465
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700466status_t AudioFlinger::setMicMute(bool state)
467{
468 // check calling permissions
469 if (!settingsAllowed()) {
470 return PERMISSION_DENIED;
471 }
472
473 AutoMutex lock(mHardwareLock);
474 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
475 status_t ret = mAudioHardware->setMicMute(state);
476 mHardwareStatus = AUDIO_HW_IDLE;
477 return ret;
478}
479
480bool AudioFlinger::getMicMute() const
481{
482 bool state = AudioSystem::MODE_INVALID;
483 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
484 mAudioHardware->getMicMute(&state);
485 mHardwareStatus = AUDIO_HW_IDLE;
486 return state;
487}
488
489status_t AudioFlinger::setMasterMute(bool muted)
490{
491 // check calling permissions
492 if (!settingsAllowed()) {
493 return PERMISSION_DENIED;
494 }
Eric Laurenta553c252009-07-17 12:17:14 -0700495
496 mMasterMute = muted;
497 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700498 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Eric Laurenta553c252009-07-17 12:17:14 -0700499
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700500 return NO_ERROR;
501}
502
503float AudioFlinger::masterVolume() const
504{
Eric Laurenta553c252009-07-17 12:17:14 -0700505 return mMasterVolume;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700506}
507
508bool AudioFlinger::masterMute() const
509{
Eric Laurenta553c252009-07-17 12:17:14 -0700510 return mMasterMute;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700511}
512
Eric Laurentddb78e72009-07-28 08:44:33 -0700513status_t AudioFlinger::setStreamVolume(int stream, float value, int output)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700514{
515 // check calling permissions
516 if (!settingsAllowed()) {
517 return PERMISSION_DENIED;
518 }
519
Eric Laurenta553c252009-07-17 12:17:14 -0700520 if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700521 return BAD_VALUE;
522 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800523
Eric Laurenta553c252009-07-17 12:17:14 -0700524 AutoMutex lock(mLock);
525 PlaybackThread *thread = NULL;
526 if (output) {
527 thread = checkPlaybackThread_l(output);
528 if (thread == NULL) {
529 return BAD_VALUE;
530 }
531 }
532
Eric Laurenta553c252009-07-17 12:17:14 -0700533 mStreamTypes[stream].volume = value;
534
535 if (thread == NULL) {
Eric Laurent415f3e22009-10-21 08:14:22 -0700536 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700537 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Eric Laurent415f3e22009-10-21 08:14:22 -0700538 }
Eric Laurenta553c252009-07-17 12:17:14 -0700539 } else {
540 thread->setStreamVolume(stream, value);
541 }
Eric Laurentef028272009-04-21 07:56:33 -0700542
Eric Laurent415f3e22009-10-21 08:14:22 -0700543 return NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700544}
545
546status_t AudioFlinger::setStreamMute(int stream, bool muted)
547{
548 // check calling permissions
549 if (!settingsAllowed()) {
550 return PERMISSION_DENIED;
551 }
552
Eric Laurenta553c252009-07-17 12:17:14 -0700553 if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES ||
Eric Laurenteeea9222009-03-26 01:57:59 -0700554 uint32_t(stream) == AudioSystem::ENFORCED_AUDIBLE) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700555 return BAD_VALUE;
556 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700557
Eric Laurenta553c252009-07-17 12:17:14 -0700558 mStreamTypes[stream].mute = muted;
559 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700560 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800561
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700562 return NO_ERROR;
563}
564
Eric Laurentddb78e72009-07-28 08:44:33 -0700565float AudioFlinger::streamVolume(int stream, int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700566{
Eric Laurenta553c252009-07-17 12:17:14 -0700567 if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700568 return 0.0f;
569 }
Eric Laurenta553c252009-07-17 12:17:14 -0700570
571 AutoMutex lock(mLock);
572 float volume;
573 if (output) {
574 PlaybackThread *thread = checkPlaybackThread_l(output);
575 if (thread == NULL) {
576 return 0.0f;
577 }
578 volume = thread->streamVolume(stream);
579 } else {
580 volume = mStreamTypes[stream].volume;
581 }
582
Eric Laurentef028272009-04-21 07:56:33 -0700583 return volume;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700584}
585
586bool AudioFlinger::streamMute(int stream) const
587{
Eric Laurenta553c252009-07-17 12:17:14 -0700588 if (stream < 0 || stream >= (int)AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700589 return true;
590 }
Eric Laurenta553c252009-07-17 12:17:14 -0700591
592 return mStreamTypes[stream].mute;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700593}
594
Eric Laurent23f25cd2010-01-25 08:49:09 -0800595bool AudioFlinger::isStreamActive(int stream) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700596{
Eric Laurent4e646332009-07-09 03:20:57 -0700597 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700598 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent23f25cd2010-01-25 08:49:09 -0800599 if (mPlaybackThreads.valueAt(i)->isStreamActive(stream)) {
Eric Laurenta553c252009-07-17 12:17:14 -0700600 return true;
601 }
602 }
603 return false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700604}
605
Eric Laurentddb78e72009-07-28 08:44:33 -0700606status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700607{
Eric Laurenta553c252009-07-17 12:17:14 -0700608 status_t result;
609
Eric Laurentddb78e72009-07-28 08:44:33 -0700610 LOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
Eric Laurenta553c252009-07-17 12:17:14 -0700611 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
612 // check calling permissions
613 if (!settingsAllowed()) {
614 return PERMISSION_DENIED;
The Android Open Source Project9266c552009-01-15 16:12:10 -0800615 }
Eric Laurenta553c252009-07-17 12:17:14 -0700616
Glenn Kasten871c16c2010-03-05 12:18:01 -0800617#ifdef LVMX
618 AudioParameter param = AudioParameter(keyValuePairs);
619 LifeVibes::setParameters(ioHandle,keyValuePairs);
620 String8 key = String8(AudioParameter::keyRouting);
621 int device;
622 if (NO_ERROR != param.getInt(key, device)) {
623 device = -1;
624 }
625
626 key = String8(LifevibesTag);
627 String8 value;
628 int musicEnabled = -1;
629 if (NO_ERROR == param.get(key, value)) {
630 if (value == LifevibesEnable) {
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700631 mLifeVibesClientPid = IPCThreadState::self()->getCallingPid();
Glenn Kasten871c16c2010-03-05 12:18:01 -0800632 musicEnabled = 1;
633 } else if (value == LifevibesDisable) {
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700634 mLifeVibesClientPid = -1;
Glenn Kasten871c16c2010-03-05 12:18:01 -0800635 musicEnabled = 0;
636 }
637 }
638#endif
639
Eric Laurenta553c252009-07-17 12:17:14 -0700640 // ioHandle == 0 means the parameters are global to the audio hardware interface
641 if (ioHandle == 0) {
642 AutoMutex lock(mHardwareLock);
643 mHardwareStatus = AUDIO_SET_PARAMETER;
644 result = mAudioHardware->setParameters(keyValuePairs);
Glenn Kasten871c16c2010-03-05 12:18:01 -0800645#ifdef LVMX
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700646 if (musicEnabled != -1) {
Glenn Kasten871c16c2010-03-05 12:18:01 -0800647 LifeVibes::enableMusic((bool) musicEnabled);
648 }
649#endif
Eric Laurenta553c252009-07-17 12:17:14 -0700650 mHardwareStatus = AUDIO_HW_IDLE;
651 return result;
652 }
653
Eric Laurentb7d94602009-09-29 11:12:57 -0700654 // hold a strong ref on thread in case closeOutput() or closeInput() is called
655 // and the thread is exited once the lock is released
656 sp<ThreadBase> thread;
657 {
658 Mutex::Autolock _l(mLock);
659 thread = checkPlaybackThread_l(ioHandle);
660 if (thread == NULL) {
661 thread = checkRecordThread_l(ioHandle);
662 }
Eric Laurenta553c252009-07-17 12:17:14 -0700663 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700664 if (thread != NULL) {
Glenn Kasten871c16c2010-03-05 12:18:01 -0800665 result = thread->setParameters(keyValuePairs);
666#ifdef LVMX
667 if ((NO_ERROR == result) && (device != -1)) {
668 LifeVibes::setDevice(LifeVibes::threadIdToAudioOutputType(thread->id()), device);
669 }
670#endif
671 return result;
Eric Laurenta553c252009-07-17 12:17:14 -0700672 }
Eric Laurenta553c252009-07-17 12:17:14 -0700673 return BAD_VALUE;
674}
675
Eric Laurentddb78e72009-07-28 08:44:33 -0700676String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
Eric Laurenta553c252009-07-17 12:17:14 -0700677{
Eric Laurentddb78e72009-07-28 08:44:33 -0700678// LOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
Eric Laurenta553c252009-07-17 12:17:14 -0700679// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
680
681 if (ioHandle == 0) {
682 return mAudioHardware->getParameters(keys);
683 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700684
685 Mutex::Autolock _l(mLock);
686
Eric Laurenta553c252009-07-17 12:17:14 -0700687 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
688 if (playbackThread != NULL) {
689 return playbackThread->getParameters(keys);
690 }
691 RecordThread *recordThread = checkRecordThread_l(ioHandle);
692 if (recordThread != NULL) {
693 return recordThread->getParameters(keys);
694 }
695 return String8("");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700696}
697
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800698size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
699{
700 return mAudioHardware->getInputBufferSize(sampleRate, format, channelCount);
701}
702
Eric Laurent47d0a922010-02-26 02:47:27 -0800703unsigned int AudioFlinger::getInputFramesLost(int ioHandle)
704{
705 if (ioHandle == 0) {
706 return 0;
707 }
708
709 Mutex::Autolock _l(mLock);
710
711 RecordThread *recordThread = checkRecordThread_l(ioHandle);
712 if (recordThread != NULL) {
713 return recordThread->getInputFramesLost();
714 }
715 return 0;
716}
717
Eric Laurent415f3e22009-10-21 08:14:22 -0700718status_t AudioFlinger::setVoiceVolume(float value)
719{
720 // check calling permissions
721 if (!settingsAllowed()) {
722 return PERMISSION_DENIED;
723 }
724
725 AutoMutex lock(mHardwareLock);
726 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
727 status_t ret = mAudioHardware->setVoiceVolume(value);
728 mHardwareStatus = AUDIO_HW_IDLE;
729
730 return ret;
731}
732
Eric Laurent0986e792010-01-19 17:37:09 -0800733status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int output)
734{
735 status_t status;
736
737 Mutex::Autolock _l(mLock);
738
739 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
740 if (playbackThread != NULL) {
741 return playbackThread->getRenderPosition(halFrames, dspFrames);
742 }
743
744 return BAD_VALUE;
745}
746
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800747void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
748{
Eric Laurenta553c252009-07-17 12:17:14 -0700749
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800750 Mutex::Autolock _l(mLock);
751
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700752 int pid = IPCThreadState::self()->getCallingPid();
753 if (mNotificationClients.indexOfKey(pid) < 0) {
754 sp<NotificationClient> notificationClient = new NotificationClient(this,
755 client,
756 pid);
757 LOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Eric Laurenta553c252009-07-17 12:17:14 -0700758
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700759 mNotificationClients.add(pid, notificationClient);
Eric Laurenta553c252009-07-17 12:17:14 -0700760
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700761 sp<IBinder> binder = client->asBinder();
762 binder->linkToDeath(notificationClient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800763
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700764 // the config change is always sent from playback or record threads to avoid deadlock
765 // with AudioSystem::gLock
766 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
767 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
768 }
Eric Laurenta553c252009-07-17 12:17:14 -0700769
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700770 for (size_t i = 0; i < mRecordThreads.size(); i++) {
771 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800772 }
773 }
774}
775
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700776void AudioFlinger::removeNotificationClient(pid_t pid)
777{
778 Mutex::Autolock _l(mLock);
779
780 int index = mNotificationClients.indexOfKey(pid);
781 if (index >= 0) {
782 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
783 LOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
784#ifdef LVMX
785 if (pid == mLifeVibesClientPid) {
786 LOGV("Disabling lifevibes");
787 LifeVibes::enableMusic(false);
788 mLifeVibesClientPid = -1;
789 }
790#endif
791 mNotificationClients.removeItem(pid);
792 }
793}
794
Eric Laurent296a0ec2009-09-15 07:10:12 -0700795// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700796void AudioFlinger::audioConfigChanged_l(int event, int ioHandle, void *param2)
797{
Eric Laurent49f02be2009-11-19 09:00:56 -0800798 size_t size = mNotificationClients.size();
799 for (size_t i = 0; i < size; i++) {
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700800 mNotificationClients.valueAt(i)->client()->ioConfigChanged(event, ioHandle, param2);
Eric Laurenta553c252009-07-17 12:17:14 -0700801 }
802}
803
Eric Laurentb9481d82009-09-17 05:12:56 -0700804// removeClient_l() must be called with AudioFlinger::mLock held
805void AudioFlinger::removeClient_l(pid_t pid)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700806{
Eric Laurentb9481d82009-09-17 05:12:56 -0700807 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 -0700808 mClients.removeItem(pid);
809}
810
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700811
Eric Laurenta553c252009-07-17 12:17:14 -0700812// ----------------------------------------------------------------------------
813
Eric Laurent49f02be2009-11-19 09:00:56 -0800814AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, int id)
Eric Laurenta553c252009-07-17 12:17:14 -0700815 : Thread(false),
816 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
Eric Laurentb0a01472010-05-14 05:45:46 -0700817 mFrameSize(1), mFormat(0), mStandby(false), mId(id), mExiting(false)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700818{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800819}
820
Eric Laurenta553c252009-07-17 12:17:14 -0700821AudioFlinger::ThreadBase::~ThreadBase()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800822{
Eric Laurent8fce46a2009-08-04 09:45:33 -0700823 mParamCond.broadcast();
824 mNewParameters.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800825}
826
Eric Laurenta553c252009-07-17 12:17:14 -0700827void AudioFlinger::ThreadBase::exit()
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700828{
Eric Laurentb7d94602009-09-29 11:12:57 -0700829 // keep a strong ref on ourself so that we wont get
Eric Laurenta553c252009-07-17 12:17:14 -0700830 // destroyed in the middle of requestExitAndWait()
831 sp <ThreadBase> strongMe = this;
832
833 LOGV("ThreadBase::exit");
834 {
835 AutoMutex lock(&mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -0800836 mExiting = true;
Eric Laurenta553c252009-07-17 12:17:14 -0700837 requestExit();
838 mWaitWorkCV.signal();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700839 }
Eric Laurenta553c252009-07-17 12:17:14 -0700840 requestExitAndWait();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700841}
Eric Laurenta553c252009-07-17 12:17:14 -0700842
843uint32_t AudioFlinger::ThreadBase::sampleRate() const
844{
845 return mSampleRate;
846}
847
848int AudioFlinger::ThreadBase::channelCount() const
849{
Eric Laurentb0a01472010-05-14 05:45:46 -0700850 return (int)mChannelCount;
Eric Laurenta553c252009-07-17 12:17:14 -0700851}
852
853int AudioFlinger::ThreadBase::format() const
854{
855 return mFormat;
856}
857
858size_t AudioFlinger::ThreadBase::frameCount() const
859{
860 return mFrameCount;
861}
862
863status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
864{
Eric Laurent8fce46a2009-08-04 09:45:33 -0700865 status_t status;
Eric Laurenta553c252009-07-17 12:17:14 -0700866
Eric Laurent8fce46a2009-08-04 09:45:33 -0700867 LOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Eric Laurenta553c252009-07-17 12:17:14 -0700868 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700869
Eric Laurent8fce46a2009-08-04 09:45:33 -0700870 mNewParameters.add(keyValuePairs);
Eric Laurenta553c252009-07-17 12:17:14 -0700871 mWaitWorkCV.signal();
Eric Laurentb7d94602009-09-29 11:12:57 -0700872 // wait condition with timeout in case the thread loop has exited
873 // before the request could be processed
874 if (mParamCond.waitRelative(mLock, seconds(2)) == NO_ERROR) {
875 status = mParamStatus;
876 mWaitWorkCV.signal();
877 } else {
878 status = TIMED_OUT;
879 }
Eric Laurent8fce46a2009-08-04 09:45:33 -0700880 return status;
Eric Laurenta553c252009-07-17 12:17:14 -0700881}
882
883void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
884{
885 Mutex::Autolock _l(mLock);
Eric Laurent8fce46a2009-08-04 09:45:33 -0700886 sendConfigEvent_l(event, param);
887}
888
889// sendConfigEvent_l() must be called with ThreadBase::mLock held
890void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
891{
Eric Laurenta553c252009-07-17 12:17:14 -0700892 ConfigEvent *configEvent = new ConfigEvent();
893 configEvent->mEvent = event;
894 configEvent->mParam = param;
895 mConfigEvents.add(configEvent);
896 LOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
897 mWaitWorkCV.signal();
898}
899
900void AudioFlinger::ThreadBase::processConfigEvents()
901{
902 mLock.lock();
903 while(!mConfigEvents.isEmpty()) {
904 LOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
905 ConfigEvent *configEvent = mConfigEvents[0];
906 mConfigEvents.removeAt(0);
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700907 // release mLock before locking AudioFlinger mLock: lock order is always
908 // AudioFlinger then ThreadBase to avoid cross deadlock
Eric Laurenta553c252009-07-17 12:17:14 -0700909 mLock.unlock();
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700910 mAudioFlinger->mLock.lock();
911 audioConfigChanged_l(configEvent->mEvent, configEvent->mParam);
912 mAudioFlinger->mLock.unlock();
Eric Laurenta553c252009-07-17 12:17:14 -0700913 delete configEvent;
914 mLock.lock();
915 }
916 mLock.unlock();
917}
918
Eric Laurent3fdb1262009-11-07 00:01:32 -0800919status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
920{
921 const size_t SIZE = 256;
922 char buffer[SIZE];
923 String8 result;
924
925 bool locked = tryLock(mLock);
926 if (!locked) {
927 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
928 write(fd, buffer, strlen(buffer));
929 }
930
931 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
932 result.append(buffer);
933 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
934 result.append(buffer);
935 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
936 result.append(buffer);
937 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
938 result.append(buffer);
939 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
940 result.append(buffer);
941 snprintf(buffer, SIZE, "Frame size: %d\n", mFrameSize);
942 result.append(buffer);
943
944 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
945 result.append(buffer);
946 result.append(" Index Command");
947 for (size_t i = 0; i < mNewParameters.size(); ++i) {
948 snprintf(buffer, SIZE, "\n %02d ", i);
949 result.append(buffer);
950 result.append(mNewParameters[i]);
951 }
952
953 snprintf(buffer, SIZE, "\n\nPending config events: \n");
954 result.append(buffer);
955 snprintf(buffer, SIZE, " Index event param\n");
956 result.append(buffer);
957 for (size_t i = 0; i < mConfigEvents.size(); i++) {
958 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i]->mEvent, mConfigEvents[i]->mParam);
959 result.append(buffer);
960 }
961 result.append("\n");
962
963 write(fd, result.string(), result.size());
964
965 if (locked) {
966 mLock.unlock();
967 }
968 return NO_ERROR;
969}
970
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800971
972// ----------------------------------------------------------------------------
973
Eric Laurent65b65452010-06-01 23:49:17 -0700974AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Eric Laurent49f02be2009-11-19 09:00:56 -0800975 : ThreadBase(audioFlinger, id),
Eric Laurentd5603c12009-08-06 08:49:39 -0700976 mMixBuffer(0), mSuspended(0), mBytesWritten(0), mOutput(output),
Eric Laurent65b65452010-06-01 23:49:17 -0700977 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
978 mDevice(device)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800979{
Eric Laurenta553c252009-07-17 12:17:14 -0700980 readOutputParameters();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800981
Eric Laurenta553c252009-07-17 12:17:14 -0700982 mMasterVolume = mAudioFlinger->masterVolume();
983 mMasterMute = mAudioFlinger->masterMute();
984
985 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
986 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
987 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800988 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800989}
990
Eric Laurenta553c252009-07-17 12:17:14 -0700991AudioFlinger::PlaybackThread::~PlaybackThread()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800992{
993 delete [] mMixBuffer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800994}
995
Eric Laurenta553c252009-07-17 12:17:14 -0700996status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800997{
998 dumpInternals(fd, args);
999 dumpTracks(fd, args);
Eric Laurent65b65452010-06-01 23:49:17 -07001000 dumpEffectChains(fd, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001001 return NO_ERROR;
1002}
1003
Eric Laurenta553c252009-07-17 12:17:14 -07001004status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001005{
1006 const size_t SIZE = 256;
1007 char buffer[SIZE];
1008 String8 result;
1009
Eric Laurenta553c252009-07-17 12:17:14 -07001010 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001011 result.append(buffer);
Eric Laurent65b65452010-06-01 23:49:17 -07001012 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 -08001013 for (size_t i = 0; i < mTracks.size(); ++i) {
Eric Laurentd3b4d0c2009-03-31 14:34:35 -07001014 sp<Track> track = mTracks[i];
1015 if (track != 0) {
1016 track->dump(buffer, SIZE);
1017 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001018 }
1019 }
1020
Eric Laurenta553c252009-07-17 12:17:14 -07001021 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001022 result.append(buffer);
Eric Laurent65b65452010-06-01 23:49:17 -07001023 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 -08001024 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Eric Laurentd3b4d0c2009-03-31 14:34:35 -07001025 wp<Track> wTrack = mActiveTracks[i];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001026 if (wTrack != 0) {
1027 sp<Track> track = wTrack.promote();
1028 if (track != 0) {
1029 track->dump(buffer, SIZE);
1030 result.append(buffer);
1031 }
1032 }
1033 }
1034 write(fd, result.string(), result.size());
1035 return NO_ERROR;
1036}
1037
Eric Laurent65b65452010-06-01 23:49:17 -07001038status_t AudioFlinger::PlaybackThread::dumpEffectChains(int fd, const Vector<String16>& args)
1039{
1040 const size_t SIZE = 256;
1041 char buffer[SIZE];
1042 String8 result;
1043
1044 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1045 write(fd, buffer, strlen(buffer));
1046
1047 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1048 sp<EffectChain> chain = mEffectChains[i];
1049 if (chain != 0) {
1050 chain->dump(fd, args);
1051 }
1052 }
1053 return NO_ERROR;
1054}
1055
Eric Laurenta553c252009-07-17 12:17:14 -07001056status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001057{
1058 const size_t SIZE = 256;
1059 char buffer[SIZE];
1060 String8 result;
1061
Eric Laurent3fdb1262009-11-07 00:01:32 -08001062 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001063 result.append(buffer);
1064 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1065 result.append(buffer);
1066 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1067 result.append(buffer);
1068 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1069 result.append(buffer);
1070 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1071 result.append(buffer);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08001072 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1073 result.append(buffer);
Eric Laurent65b65452010-06-01 23:49:17 -07001074 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1075 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001076 write(fd, result.string(), result.size());
Eric Laurent3fdb1262009-11-07 00:01:32 -08001077
1078 dumpBase(fd, args);
1079
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001080 return NO_ERROR;
1081}
1082
1083// Thread virtuals
Eric Laurenta553c252009-07-17 12:17:14 -07001084status_t AudioFlinger::PlaybackThread::readyToRun()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001085{
1086 if (mSampleRate == 0) {
1087 LOGE("No working audio driver found.");
1088 return NO_INIT;
1089 }
Eric Laurenta553c252009-07-17 12:17:14 -07001090 LOGI("AudioFlinger's thread %p ready to run", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001091 return NO_ERROR;
1092}
1093
Eric Laurenta553c252009-07-17 12:17:14 -07001094void AudioFlinger::PlaybackThread::onFirstRef()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001095{
1096 const size_t SIZE = 256;
1097 char buffer[SIZE];
1098
Eric Laurenta553c252009-07-17 12:17:14 -07001099 snprintf(buffer, SIZE, "Playback Thread %p", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001100
1101 run(buffer, ANDROID_PRIORITY_URGENT_AUDIO);
1102}
1103
Eric Laurenta553c252009-07-17 12:17:14 -07001104// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1105sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001106 const sp<AudioFlinger::Client>& client,
1107 int streamType,
1108 uint32_t sampleRate,
1109 int format,
1110 int channelCount,
1111 int frameCount,
1112 const sp<IMemory>& sharedBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -07001113 int sessionId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001114 status_t *status)
1115{
1116 sp<Track> track;
1117 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07001118
1119 if (mType == DIRECT) {
Eric Laurentb0a01472010-05-14 05:45:46 -07001120 if (sampleRate != mSampleRate || format != mFormat || channelCount != (int)mChannelCount) {
Eric Laurenta553c252009-07-17 12:17:14 -07001121 LOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelCount %d for output %p",
1122 sampleRate, format, channelCount, mOutput);
1123 lStatus = BAD_VALUE;
1124 goto Exit;
1125 }
1126 } else {
1127 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1128 if (sampleRate > mSampleRate*2) {
1129 LOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
1130 lStatus = BAD_VALUE;
1131 goto Exit;
1132 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001133 }
1134
Eric Laurenta553c252009-07-17 12:17:14 -07001135 if (mOutput == 0) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001136 LOGE("Audio driver not initialized.");
1137 lStatus = NO_INIT;
1138 goto Exit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001139 }
1140
Eric Laurenta553c252009-07-17 12:17:14 -07001141 { // scope for mLock
1142 Mutex::Autolock _l(mLock);
1143 track = new Track(this, client, streamType, sampleRate, format,
Eric Laurent65b65452010-06-01 23:49:17 -07001144 channelCount, frameCount, sharedBuffer, sessionId);
Eric Laurent73b60352009-11-09 04:45:39 -08001145 if (track->getCblk() == NULL || track->name() < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07001146 lStatus = NO_MEMORY;
1147 goto Exit;
1148 }
1149 mTracks.add(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001150
1151 sp<EffectChain> chain = getEffectChain_l(sessionId);
1152 if (chain != 0) {
1153 LOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1154 track->setMainBuffer(chain->inBuffer());
1155 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001156 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001157 lStatus = NO_ERROR;
1158
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001159Exit:
1160 if(status) {
1161 *status = lStatus;
1162 }
1163 return track;
1164}
1165
Eric Laurenta553c252009-07-17 12:17:14 -07001166uint32_t AudioFlinger::PlaybackThread::latency() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001167{
1168 if (mOutput) {
1169 return mOutput->latency();
1170 }
1171 else {
1172 return 0;
1173 }
1174}
1175
Eric Laurenta553c252009-07-17 12:17:14 -07001176status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001177{
Glenn Kasten871c16c2010-03-05 12:18:01 -08001178#ifdef LVMX
1179 int audioOutputType = LifeVibes::getMixerType(mId, mType);
1180 if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType)) {
1181 LifeVibes::setMasterVolume(audioOutputType, value);
1182 }
1183#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001184 mMasterVolume = value;
1185 return NO_ERROR;
1186}
1187
Eric Laurenta553c252009-07-17 12:17:14 -07001188status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001189{
Glenn Kasten871c16c2010-03-05 12:18:01 -08001190#ifdef LVMX
1191 int audioOutputType = LifeVibes::getMixerType(mId, mType);
1192 if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType)) {
1193 LifeVibes::setMasterMute(audioOutputType, muted);
1194 }
1195#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001196 mMasterMute = muted;
1197 return NO_ERROR;
1198}
1199
Eric Laurenta553c252009-07-17 12:17:14 -07001200float AudioFlinger::PlaybackThread::masterVolume() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001201{
1202 return mMasterVolume;
1203}
1204
Eric Laurenta553c252009-07-17 12:17:14 -07001205bool AudioFlinger::PlaybackThread::masterMute() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001206{
1207 return mMasterMute;
1208}
1209
Eric Laurenta553c252009-07-17 12:17:14 -07001210status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001211{
Glenn Kasten871c16c2010-03-05 12:18:01 -08001212#ifdef LVMX
1213 int audioOutputType = LifeVibes::getMixerType(mId, mType);
1214 if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType)) {
1215 LifeVibes::setStreamVolume(audioOutputType, stream, value);
1216 }
1217#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001218 mStreamTypes[stream].volume = value;
1219 return NO_ERROR;
1220}
1221
Eric Laurenta553c252009-07-17 12:17:14 -07001222status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001223{
Glenn Kasten871c16c2010-03-05 12:18:01 -08001224#ifdef LVMX
1225 int audioOutputType = LifeVibes::getMixerType(mId, mType);
1226 if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType)) {
1227 LifeVibes::setStreamMute(audioOutputType, stream, muted);
1228 }
1229#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001230 mStreamTypes[stream].mute = muted;
1231 return NO_ERROR;
1232}
1233
Eric Laurenta553c252009-07-17 12:17:14 -07001234float AudioFlinger::PlaybackThread::streamVolume(int stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001235{
1236 return mStreamTypes[stream].volume;
1237}
1238
Eric Laurenta553c252009-07-17 12:17:14 -07001239bool AudioFlinger::PlaybackThread::streamMute(int stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001240{
1241 return mStreamTypes[stream].mute;
1242}
1243
Eric Laurent23f25cd2010-01-25 08:49:09 -08001244bool AudioFlinger::PlaybackThread::isStreamActive(int stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001245{
Eric Laurenta553c252009-07-17 12:17:14 -07001246 Mutex::Autolock _l(mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001247 size_t count = mActiveTracks.size();
1248 for (size_t i = 0 ; i < count ; ++i) {
1249 sp<Track> t = mActiveTracks[i].promote();
1250 if (t == 0) continue;
1251 Track* const track = t.get();
Eric Laurent23f25cd2010-01-25 08:49:09 -08001252 if (t->type() == stream)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001253 return true;
1254 }
1255 return false;
1256}
1257
Eric Laurenta553c252009-07-17 12:17:14 -07001258// addTrack_l() must be called with ThreadBase::mLock held
1259status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001260{
1261 status_t status = ALREADY_EXISTS;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001262
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001263 // set retry count for buffer fill
1264 track->mRetryCount = kMaxTrackStartupRetries;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001265 if (mActiveTracks.indexOf(track) < 0) {
1266 // the track is newly added, make sure it fills up all its
1267 // buffers before playing. This is to ensure the client will
1268 // effectively get the latency it requested.
1269 track->mFillingUpStatus = Track::FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001270 track->mResetDone = false;
Eric Laurenta553c252009-07-17 12:17:14 -07001271 mActiveTracks.add(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001272 if (track->mainBuffer() != mMixBuffer) {
1273 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1274 if (chain != 0) {
1275 LOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
1276 chain->startTrack();
1277 }
1278 }
1279
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001280 status = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001281 }
Eric Laurenta553c252009-07-17 12:17:14 -07001282
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001283 LOGV("mWaitWorkCV.broadcast");
Eric Laurenta553c252009-07-17 12:17:14 -07001284 mWaitWorkCV.broadcast();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001285
1286 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001287}
1288
Eric Laurenta553c252009-07-17 12:17:14 -07001289// destroyTrack_l() must be called with ThreadBase::mLock held
1290void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001291{
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001292 track->mState = TrackBase::TERMINATED;
1293 if (mActiveTracks.indexOf(track) < 0) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001294 mTracks.remove(track);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001295 deleteTrackName_l(track->name());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001296 }
1297}
1298
Eric Laurenta553c252009-07-17 12:17:14 -07001299String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001300{
Eric Laurenta553c252009-07-17 12:17:14 -07001301 return mOutput->getParameters(keys);
1302}
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001303
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001304// destroyTrack_l() must be called with AudioFlinger::mLock held
1305void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
Eric Laurenta553c252009-07-17 12:17:14 -07001306 AudioSystem::OutputDescriptor desc;
1307 void *param2 = 0;
1308
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001309 LOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Eric Laurenta553c252009-07-17 12:17:14 -07001310
1311 switch (event) {
1312 case AudioSystem::OUTPUT_OPENED:
1313 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Eric Laurentb0a01472010-05-14 05:45:46 -07001314 desc.channels = mChannels;
Eric Laurenta553c252009-07-17 12:17:14 -07001315 desc.samplingRate = mSampleRate;
1316 desc.format = mFormat;
1317 desc.frameCount = mFrameCount;
1318 desc.latency = latency();
1319 param2 = &desc;
1320 break;
1321
1322 case AudioSystem::STREAM_CONFIG_CHANGED:
1323 param2 = &param;
1324 case AudioSystem::OUTPUT_CLOSED:
1325 default:
1326 break;
1327 }
Eric Laurent49f02be2009-11-19 09:00:56 -08001328 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurenta553c252009-07-17 12:17:14 -07001329}
1330
1331void AudioFlinger::PlaybackThread::readOutputParameters()
1332{
1333 mSampleRate = mOutput->sampleRate();
Eric Laurentb0a01472010-05-14 05:45:46 -07001334 mChannels = mOutput->channels();
1335 mChannelCount = (uint16_t)AudioSystem::popCount(mChannels);
Eric Laurenta553c252009-07-17 12:17:14 -07001336 mFormat = mOutput->format();
Eric Laurentb0a01472010-05-14 05:45:46 -07001337 mFrameSize = (uint16_t)mOutput->frameSize();
Eric Laurenta553c252009-07-17 12:17:14 -07001338 mFrameCount = mOutput->bufferSize() / mFrameSize;
1339
Eric Laurenta553c252009-07-17 12:17:14 -07001340 // FIXME - Current mixer implementation only supports stereo output: Always
1341 // Allocate a stereo buffer even if HW output is mono.
Eric Laurent65b65452010-06-01 23:49:17 -07001342 if (mMixBuffer != NULL) delete[] mMixBuffer;
Eric Laurenta553c252009-07-17 12:17:14 -07001343 mMixBuffer = new int16_t[mFrameCount * 2];
1344 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
Eric Laurent65b65452010-06-01 23:49:17 -07001345
1346 //TODO handle effects reconfig
Eric Laurenta553c252009-07-17 12:17:14 -07001347}
1348
Eric Laurent0986e792010-01-19 17:37:09 -08001349status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1350{
1351 if (halFrames == 0 || dspFrames == 0) {
1352 return BAD_VALUE;
1353 }
1354 if (mOutput == 0) {
1355 return INVALID_OPERATION;
1356 }
1357 *halFrames = mBytesWritten/mOutput->frameSize();
1358
1359 return mOutput->getRenderPosition(dspFrames);
1360}
1361
Eric Laurent65b65452010-06-01 23:49:17 -07001362bool AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
1363{
1364 Mutex::Autolock _l(mLock);
1365 if (getEffectChain_l(sessionId) != 0) {
1366 return true;
1367 }
1368
1369 for (size_t i = 0; i < mTracks.size(); ++i) {
1370 sp<Track> track = mTracks[i];
1371 if (sessionId == track->sessionId()) {
1372 return true;
1373 }
1374 }
1375
1376 return false;
1377}
1378
1379sp<AudioFlinger::EffectChain> AudioFlinger::PlaybackThread::getEffectChain(int sessionId)
1380{
1381 Mutex::Autolock _l(mLock);
1382 return getEffectChain_l(sessionId);
1383}
1384
1385sp<AudioFlinger::EffectChain> AudioFlinger::PlaybackThread::getEffectChain_l(int sessionId)
1386{
1387 sp<EffectChain> chain;
1388
1389 size_t size = mEffectChains.size();
1390 for (size_t i = 0; i < size; i++) {
1391 if (mEffectChains[i]->sessionId() == sessionId) {
1392 chain = mEffectChains[i];
1393 break;
1394 }
1395 }
1396 return chain;
1397}
1398
Eric Laurent53334cd2010-06-23 17:38:20 -07001399void AudioFlinger::PlaybackThread::setMode(uint32_t mode)
1400{
1401 Mutex::Autolock _l(mLock);
1402 size_t size = mEffectChains.size();
1403 for (size_t i = 0; i < size; i++) {
1404 mEffectChains[i]->setMode(mode);
1405 }
1406}
1407
Eric Laurenta553c252009-07-17 12:17:14 -07001408// ----------------------------------------------------------------------------
1409
Eric Laurent65b65452010-06-01 23:49:17 -07001410AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
1411 : PlaybackThread(audioFlinger, output, id, device),
Eric Laurenta553c252009-07-17 12:17:14 -07001412 mAudioMixer(0)
1413{
1414 mType = PlaybackThread::MIXER;
1415 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1416
1417 // FIXME - Current mixer implementation only supports stereo output
1418 if (mChannelCount == 1) {
1419 LOGE("Invalid audio hardware channel count");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001420 }
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001421}
1422
Eric Laurenta553c252009-07-17 12:17:14 -07001423AudioFlinger::MixerThread::~MixerThread()
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001424{
Eric Laurenta553c252009-07-17 12:17:14 -07001425 delete mAudioMixer;
1426}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001427
Eric Laurenta553c252009-07-17 12:17:14 -07001428bool AudioFlinger::MixerThread::threadLoop()
1429{
Eric Laurenta553c252009-07-17 12:17:14 -07001430 Vector< sp<Track> > tracksToRemove;
Eric Laurent059b4be2009-11-09 23:32:22 -08001431 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001432 nsecs_t standbyTime = systemTime();
1433 size_t mixBufferSize = mFrameCount * mFrameSize;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001434 // FIXME: Relaxed timing because of a certain device that can't meet latency
1435 // Should be reduced to 2x after the vendor fixes the driver issue
1436 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
1437 nsecs_t lastWarning = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08001438 bool longStandbyExit = false;
1439 uint32_t activeSleepTime = activeSleepTimeUs();
1440 uint32_t idleSleepTime = idleSleepTimeUs();
1441 uint32_t sleepTime = idleSleepTime;
Eric Laurent65b65452010-06-01 23:49:17 -07001442 Vector< sp<EffectChain> > effectChains;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001443
Eric Laurenta553c252009-07-17 12:17:14 -07001444 while (!exitPending())
1445 {
1446 processConfigEvents();
1447
Eric Laurent059b4be2009-11-09 23:32:22 -08001448 mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001449 { // scope for mLock
1450
1451 Mutex::Autolock _l(mLock);
1452
1453 if (checkForNewParameters_l()) {
1454 mixBufferSize = mFrameCount * mFrameSize;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001455 // FIXME: Relaxed timing because of a certain device that can't meet latency
1456 // Should be reduced to 2x after the vendor fixes the driver issue
1457 maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
Eric Laurent059b4be2009-11-09 23:32:22 -08001458 activeSleepTime = activeSleepTimeUs();
1459 idleSleepTime = idleSleepTimeUs();
Eric Laurenta553c252009-07-17 12:17:14 -07001460 }
1461
1462 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1463
1464 // put audio hardware into standby after short delay
1465 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1466 mSuspended) {
1467 if (!mStandby) {
1468 LOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
1469 mOutput->standby();
1470 mStandby = true;
1471 mBytesWritten = 0;
1472 }
1473
1474 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1475 // we're about to wait, flush the binder command buffer
1476 IPCThreadState::self()->flushCommands();
1477
1478 if (exitPending()) break;
1479
1480 // wait until we have something to do...
1481 LOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
1482 mWaitWorkCV.wait(mLock);
1483 LOGV("MixerThread %p TID %d waking up\n", this, gettid());
1484
1485 if (mMasterMute == false) {
1486 char value[PROPERTY_VALUE_MAX];
1487 property_get("ro.audio.silent", value, "0");
1488 if (atoi(value)) {
1489 LOGD("Silence is golden");
1490 setMasterMute(true);
1491 }
1492 }
1493
1494 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent059b4be2009-11-09 23:32:22 -08001495 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07001496 continue;
1497 }
1498 }
1499
Eric Laurent059b4be2009-11-09 23:32:22 -08001500 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07001501
1502 // prevent any changes in effect chain list and in each effect chain
1503 // during mixing and effect process as the audio buffers could be deleted
1504 // or modified if an effect is created or deleted
1505 effectChains = mEffectChains;
1506 lockEffectChains_l();
Eric Laurenta553c252009-07-17 12:17:14 -07001507 }
1508
Eric Laurent059b4be2009-11-09 23:32:22 -08001509 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07001510 // mix buffers...
Eric Laurent65b65452010-06-01 23:49:17 -07001511 mAudioMixer->process();
Eric Laurentf69a3f82009-09-22 00:35:48 -07001512 sleepTime = 0;
1513 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent65b65452010-06-01 23:49:17 -07001514 //TODO: delay standby when effects have a tail
Eric Laurent96c08a62009-09-07 08:38:38 -07001515 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07001516 // If no tracks are ready, sleep once for the duration of an output
1517 // buffer size, then write 0s to the output
1518 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08001519 if (mixerStatus == MIXER_TRACKS_ENABLED) {
1520 sleepTime = activeSleepTime;
1521 } else {
1522 sleepTime = idleSleepTime;
1523 }
1524 } else if (mBytesWritten != 0 ||
1525 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Eric Laurent65b65452010-06-01 23:49:17 -07001526 memset (mMixBuffer, 0, mixBufferSize);
Eric Laurent96c08a62009-09-07 08:38:38 -07001527 sleepTime = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08001528 LOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Eric Laurent96c08a62009-09-07 08:38:38 -07001529 }
Eric Laurent65b65452010-06-01 23:49:17 -07001530 // TODO add standby time extension fct of effect tail
Eric Laurentf69a3f82009-09-22 00:35:48 -07001531 }
1532
1533 if (mSuspended) {
Eric Laurent059b4be2009-11-09 23:32:22 -08001534 sleepTime = idleSleepTime;
Eric Laurentf69a3f82009-09-22 00:35:48 -07001535 }
1536 // sleepTime == 0 means we must write to audio hardware
1537 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07001538 for (size_t i = 0; i < effectChains.size(); i ++) {
1539 effectChains[i]->process_l();
1540 }
1541 // enable changes in effect chain
1542 unlockEffectChains();
Glenn Kasten871c16c2010-03-05 12:18:01 -08001543#ifdef LVMX
1544 int audioOutputType = LifeVibes::getMixerType(mId, mType);
1545 if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType)) {
Eric Laurent65b65452010-06-01 23:49:17 -07001546 LifeVibes::process(audioOutputType, mMixBuffer, mixBufferSize);
Glenn Kasten871c16c2010-03-05 12:18:01 -08001547 }
1548#endif
Eric Laurent65b65452010-06-01 23:49:17 -07001549 mLastWriteTime = systemTime();
1550 mInWrite = true;
1551 mBytesWritten += mixBufferSize;
1552
1553 int bytesWritten = (int)mOutput->write(mMixBuffer, mixBufferSize);
Eric Laurent0986e792010-01-19 17:37:09 -08001554 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07001555 mNumWrites++;
1556 mInWrite = false;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001557 nsecs_t now = systemTime();
1558 nsecs_t delta = now - mLastWriteTime;
Eric Laurentf69a3f82009-09-22 00:35:48 -07001559 if (delta > maxPeriod) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07001560 mNumDelayedWrites++;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001561 if ((now - lastWarning) > kWarningThrottle) {
1562 LOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
1563 ns2ms(delta), mNumDelayedWrites, this);
1564 lastWarning = now;
1565 }
Eric Laurent059b4be2009-11-09 23:32:22 -08001566 if (mStandby) {
1567 longStandbyExit = true;
1568 }
Eric Laurenta553c252009-07-17 12:17:14 -07001569 }
Eric Laurent059b4be2009-11-09 23:32:22 -08001570 mStandby = false;
Eric Laurentf69a3f82009-09-22 00:35:48 -07001571 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07001572 // enable changes in effect chain
1573 unlockEffectChains();
Eric Laurentf69a3f82009-09-22 00:35:48 -07001574 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07001575 }
1576
1577 // finally let go of all our tracks, without the lock held
1578 // since we can't guarantee the destructors won't acquire that
1579 // same lock.
1580 tracksToRemove.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07001581
1582 // Effect chains will be actually deleted here if they were removed from
1583 // mEffectChains list during mixing or effects processing
1584 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07001585 }
1586
1587 if (!mStandby) {
1588 mOutput->standby();
1589 }
Eric Laurenta553c252009-07-17 12:17:14 -07001590
1591 LOGV("MixerThread %p exiting", this);
1592 return false;
1593}
1594
1595// prepareTracks_l() must be called with ThreadBase::mLock held
Eric Laurent059b4be2009-11-09 23:32:22 -08001596uint32_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
Eric Laurenta553c252009-07-17 12:17:14 -07001597{
1598
Eric Laurent059b4be2009-11-09 23:32:22 -08001599 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001600 // find out which tracks need to be processed
1601 size_t count = activeTracks.size();
Eric Laurent65b65452010-06-01 23:49:17 -07001602 size_t mixedTracks = 0;
1603 size_t tracksWithEffect = 0;
Glenn Kasten871c16c2010-03-05 12:18:01 -08001604
1605 float masterVolume = mMasterVolume;
1606 bool masterMute = mMasterMute;
1607
1608#ifdef LVMX
1609 bool tracksConnectedChanged = false;
1610 bool stateChanged = false;
1611
1612 int audioOutputType = LifeVibes::getMixerType(mId, mType);
1613 if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType))
1614 {
1615 int activeTypes = 0;
1616 for (size_t i=0 ; i<count ; i++) {
1617 sp<Track> t = activeTracks[i].promote();
1618 if (t == 0) continue;
1619 Track* const track = t.get();
1620 int iTracktype=track->type();
1621 activeTypes |= 1<<track->type();
1622 }
1623 LifeVibes::computeVolumes(audioOutputType, activeTypes, tracksConnectedChanged, stateChanged, masterVolume, masterMute);
1624 }
1625#endif
Eric Laurent65b65452010-06-01 23:49:17 -07001626 // Delegate master volume control to effect in output mix effect chain if needed
1627 sp<EffectChain> chain = getEffectChain_l(0);
1628 if (chain != 0) {
1629 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
1630 chain->setVolume(&v, &v);
1631 masterVolume = (float)((v + (1 << 23)) >> 24);
1632 chain.clear();
1633 }
Glenn Kasten871c16c2010-03-05 12:18:01 -08001634
Eric Laurenta553c252009-07-17 12:17:14 -07001635 for (size_t i=0 ; i<count ; i++) {
1636 sp<Track> t = activeTracks[i].promote();
1637 if (t == 0) continue;
1638
1639 Track* const track = t.get();
1640 audio_track_cblk_t* cblk = track->cblk();
1641
1642 // The first time a track is added we wait
1643 // for all its buffers to be filled before processing it
1644 mAudioMixer->setActiveTrack(track->name());
1645 if (cblk->framesReady() && (track->isReady() || track->isStopped()) &&
Eric Laurent71f37cd2010-03-31 12:21:17 -07001646 !track->isPaused() && !track->isTerminated())
Eric Laurenta553c252009-07-17 12:17:14 -07001647 {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08001648 //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 -07001649
Eric Laurent65b65452010-06-01 23:49:17 -07001650 mixedTracks++;
1651
1652 // track->mainBuffer() != mMixBuffer means there is an effect chain
1653 // connected to the track
1654 chain.clear();
1655 if (track->mainBuffer() != mMixBuffer) {
1656 chain = getEffectChain_l(track->sessionId());
1657 // Delegate volume control to effect in track effect chain if needed
1658 if (chain != 0) {
1659 tracksWithEffect++;
1660 } else {
1661 LOGW("prepareTracks_l(): track %08x attached to effect but no chain found on session %d",
1662 track->name(), track->sessionId());
1663 }
1664 }
1665
1666
1667 int param = AudioMixer::VOLUME;
1668 if (track->mFillingUpStatus == Track::FS_FILLED) {
1669 // no ramp for the first volume setting
1670 track->mFillingUpStatus = Track::FS_ACTIVE;
1671 if (track->mState == TrackBase::RESUMING) {
1672 track->mState = TrackBase::ACTIVE;
1673 param = AudioMixer::RAMP_VOLUME;
1674 }
1675 } else if (cblk->server != 0) {
1676 // If the track is stopped before the first frame was mixed,
1677 // do not apply ramp
1678 param = AudioMixer::RAMP_VOLUME;
1679 }
1680
Eric Laurenta553c252009-07-17 12:17:14 -07001681 // compute volume for this track
Eric Laurent65b65452010-06-01 23:49:17 -07001682 int16_t left, right, aux;
Glenn Kasten871c16c2010-03-05 12:18:01 -08001683 if (track->isMuted() || masterMute || track->isPausing() ||
Eric Laurenta553c252009-07-17 12:17:14 -07001684 mStreamTypes[track->type()].mute) {
Eric Laurent65b65452010-06-01 23:49:17 -07001685 left = right = aux = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07001686 if (track->isPausing()) {
1687 track->setPaused();
1688 }
1689 } else {
Glenn Kasten871c16c2010-03-05 12:18:01 -08001690 // read original volumes with volume control
Eric Laurenta553c252009-07-17 12:17:14 -07001691 float typeVolume = mStreamTypes[track->type()].volume;
Glenn Kasten871c16c2010-03-05 12:18:01 -08001692#ifdef LVMX
1693 bool streamMute=false;
1694 // read the volume from the LivesVibes audio engine.
1695 if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType))
1696 {
1697 LifeVibes::getStreamVolumes(audioOutputType, track->type(), &typeVolume, &streamMute);
1698 if (streamMute) {
1699 typeVolume = 0;
1700 }
1701 }
1702#endif
1703 float v = masterVolume * typeVolume;
Eric Laurent65b65452010-06-01 23:49:17 -07001704 uint32_t vl = (uint32_t)(v * cblk->volume[0]) << 12;
1705 uint32_t vr = (uint32_t)(v * cblk->volume[1]) << 12;
Eric Laurenta553c252009-07-17 12:17:14 -07001706
Eric Laurent65b65452010-06-01 23:49:17 -07001707 // Delegate volume control to effect in track effect chain if needed
1708 if (chain != 0 && chain->setVolume(&vl, &vr)) {
1709 // Do not ramp volume is volume is controlled by effect
1710 param = AudioMixer::VOLUME;
Eric Laurenta553c252009-07-17 12:17:14 -07001711 }
Eric Laurent65b65452010-06-01 23:49:17 -07001712
1713 // Convert volumes from 8.24 to 4.12 format
1714 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
1715 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
1716 left = int16_t(v_clamped);
1717 v_clamped = (vr + (1 << 11)) >> 12;
1718 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
1719 right = int16_t(v_clamped);
1720
1721 v_clamped = (uint32_t)(v * cblk->sendLevel);
1722 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
1723 aux = int16_t(v_clamped);
Eric Laurenta553c252009-07-17 12:17:14 -07001724 }
Eric Laurent65b65452010-06-01 23:49:17 -07001725
Glenn Kasten871c16c2010-03-05 12:18:01 -08001726#ifdef LVMX
1727 if ( tracksConnectedChanged || stateChanged )
1728 {
1729 // only do the ramp when the volume is changed by the user / application
1730 param = AudioMixer::VOLUME;
1731 }
1732#endif
Eric Laurent65b65452010-06-01 23:49:17 -07001733
1734 // XXX: these things DON'T need to be done each time
1735 mAudioMixer->setBufferProvider(track);
1736 mAudioMixer->enable(AudioMixer::MIXING);
1737
1738 mAudioMixer->setParameter(param, AudioMixer::VOLUME0, (void *)left);
1739 mAudioMixer->setParameter(param, AudioMixer::VOLUME1, (void *)right);
1740 mAudioMixer->setParameter(param, AudioMixer::AUXLEVEL, (void *)aux);
Eric Laurenta553c252009-07-17 12:17:14 -07001741 mAudioMixer->setParameter(
1742 AudioMixer::TRACK,
Eric Laurent65b65452010-06-01 23:49:17 -07001743 AudioMixer::FORMAT, (void *)track->format());
Eric Laurenta553c252009-07-17 12:17:14 -07001744 mAudioMixer->setParameter(
1745 AudioMixer::TRACK,
Eric Laurent65b65452010-06-01 23:49:17 -07001746 AudioMixer::CHANNEL_COUNT, (void *)track->channelCount());
Eric Laurenta553c252009-07-17 12:17:14 -07001747 mAudioMixer->setParameter(
1748 AudioMixer::RESAMPLE,
1749 AudioMixer::SAMPLE_RATE,
Eric Laurent65b65452010-06-01 23:49:17 -07001750 (void *)(cblk->sampleRate));
1751 mAudioMixer->setParameter(
1752 AudioMixer::TRACK,
1753 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
1754 mAudioMixer->setParameter(
1755 AudioMixer::TRACK,
1756 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
Eric Laurenta553c252009-07-17 12:17:14 -07001757
1758 // reset retry count
1759 track->mRetryCount = kMaxTrackRetries;
Eric Laurent059b4be2009-11-09 23:32:22 -08001760 mixerStatus = MIXER_TRACKS_READY;
Eric Laurenta553c252009-07-17 12:17:14 -07001761 } else {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08001762 //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 -07001763 if (track->isStopped()) {
1764 track->reset();
1765 }
1766 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
1767 // We have consumed all the buffers of this track.
1768 // Remove it from the list of active tracks.
1769 tracksToRemove->add(track);
Eric Laurenta553c252009-07-17 12:17:14 -07001770 } else {
1771 // No buffers for this track. Give it a few chances to
1772 // fill a buffer, then remove it from active list.
1773 if (--(track->mRetryCount) <= 0) {
Eric Laurent62443f52009-10-05 20:29:18 -07001774 LOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", track->name(), this);
Eric Laurenta553c252009-07-17 12:17:14 -07001775 tracksToRemove->add(track);
Eric Laurent059b4be2009-11-09 23:32:22 -08001776 } else if (mixerStatus != MIXER_TRACKS_READY) {
1777 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07001778 }
Eric Laurenta553c252009-07-17 12:17:14 -07001779 }
Eric Laurent65b65452010-06-01 23:49:17 -07001780 mAudioMixer->disable(AudioMixer::MIXING);
Eric Laurenta553c252009-07-17 12:17:14 -07001781 }
1782 }
1783
1784 // remove all the tracks that need to be...
1785 count = tracksToRemove->size();
1786 if (UNLIKELY(count)) {
1787 for (size_t i=0 ; i<count ; i++) {
1788 const sp<Track>& track = tracksToRemove->itemAt(i);
1789 mActiveTracks.remove(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001790 if (track->mainBuffer() != mMixBuffer) {
1791 chain = getEffectChain_l(track->sessionId());
1792 if (chain != 0) {
1793 LOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
1794 chain->stopTrack();
1795 }
1796 }
Eric Laurenta553c252009-07-17 12:17:14 -07001797 if (track->isTerminated()) {
1798 mTracks.remove(track);
1799 deleteTrackName_l(track->mName);
1800 }
1801 }
1802 }
1803
Eric Laurent65b65452010-06-01 23:49:17 -07001804 // mix buffer must be cleared if all tracks are connected to an
1805 // effect chain as in this case the mixer will not write to
1806 // mix buffer and track effects will accumulate into it
1807 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
1808 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
1809 }
1810
Eric Laurent059b4be2009-11-09 23:32:22 -08001811 return mixerStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07001812}
1813
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001814void AudioFlinger::MixerThread::invalidateTracks(int streamType)
Eric Laurenta553c252009-07-17 12:17:14 -07001815{
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001816 LOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d", this, streamType, mTracks.size());
Eric Laurenta553c252009-07-17 12:17:14 -07001817 Mutex::Autolock _l(mLock);
1818 size_t size = mTracks.size();
1819 for (size_t i = 0; i < size; i++) {
1820 sp<Track> t = mTracks[i];
1821 if (t->type() == streamType) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001822 t->mCblk->lock.lock();
1823 t->mCblk->flags |= CBLK_INVALID_ON;
1824 t->mCblk->cv.signal();
1825 t->mCblk->lock.unlock();
Eric Laurenta553c252009-07-17 12:17:14 -07001826 }
Eric Laurent53334cd2010-06-23 17:38:20 -07001827 }
1828}
Eric Laurenta553c252009-07-17 12:17:14 -07001829
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001830
Eric Laurenta553c252009-07-17 12:17:14 -07001831// getTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001832int AudioFlinger::MixerThread::getTrackName_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001833{
1834 return mAudioMixer->getTrackName();
1835}
1836
Eric Laurenta553c252009-07-17 12:17:14 -07001837// deleteTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001838void AudioFlinger::MixerThread::deleteTrackName_l(int name)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001839{
Eric Laurent0a080292009-12-07 10:53:10 -08001840 LOGV("remove track (%d) and delete from mixer", name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001841 mAudioMixer->deleteTrackName(name);
1842}
1843
Eric Laurenta553c252009-07-17 12:17:14 -07001844// checkForNewParameters_l() must be called with ThreadBase::mLock held
1845bool AudioFlinger::MixerThread::checkForNewParameters_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001846{
Eric Laurenta553c252009-07-17 12:17:14 -07001847 bool reconfig = false;
1848
Eric Laurent8fce46a2009-08-04 09:45:33 -07001849 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07001850 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07001851 String8 keyValuePair = mNewParameters[0];
1852 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07001853 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07001854
Eric Laurenta553c252009-07-17 12:17:14 -07001855 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
1856 reconfig = true;
1857 }
1858 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
1859 if (value != AudioSystem::PCM_16_BIT) {
1860 status = BAD_VALUE;
1861 } else {
1862 reconfig = true;
1863 }
1864 }
1865 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
1866 if (value != AudioSystem::CHANNEL_OUT_STEREO) {
1867 status = BAD_VALUE;
1868 } else {
1869 reconfig = true;
1870 }
1871 }
1872 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
1873 // do not accept frame count changes if tracks are open as the track buffer
1874 // size depends on frame count and correct behavior would not be garantied
1875 // if frame count is changed after track creation
1876 if (!mTracks.isEmpty()) {
1877 status = INVALID_OPERATION;
1878 } else {
1879 reconfig = true;
1880 }
1881 }
Eric Laurent65b65452010-06-01 23:49:17 -07001882 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
1883 // forward device change to effects that have requested to be
1884 // aware of attached audio device.
1885 mDevice = (uint32_t)value;
1886 for (size_t i = 0; i < mEffectChains.size(); i++) {
1887 mEffectChains[i]->setDevice(mDevice);
1888 }
1889 }
1890
Eric Laurenta553c252009-07-17 12:17:14 -07001891 if (status == NO_ERROR) {
Eric Laurent8fce46a2009-08-04 09:45:33 -07001892 status = mOutput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07001893 if (!mStandby && status == INVALID_OPERATION) {
1894 mOutput->standby();
1895 mStandby = true;
1896 mBytesWritten = 0;
Eric Laurent8fce46a2009-08-04 09:45:33 -07001897 status = mOutput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07001898 }
1899 if (status == NO_ERROR && reconfig) {
1900 delete mAudioMixer;
1901 readOutputParameters();
1902 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1903 for (size_t i = 0; i < mTracks.size() ; i++) {
1904 int name = getTrackName_l();
1905 if (name < 0) break;
1906 mTracks[i]->mName = name;
Eric Laurent6f7e0972009-08-10 08:15:12 -07001907 // limit track sample rate to 2 x new output sample rate
1908 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
1909 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
1910 }
Eric Laurenta553c252009-07-17 12:17:14 -07001911 }
Eric Laurent8fce46a2009-08-04 09:45:33 -07001912 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07001913 }
1914 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08001915
1916 mNewParameters.removeAt(0);
1917
Eric Laurenta553c252009-07-17 12:17:14 -07001918 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07001919 mParamCond.signal();
Eric Laurent8fce46a2009-08-04 09:45:33 -07001920 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07001921 }
1922 return reconfig;
1923}
1924
1925status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
1926{
1927 const size_t SIZE = 256;
1928 char buffer[SIZE];
1929 String8 result;
1930
1931 PlaybackThread::dumpInternals(fd, args);
1932
1933 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
1934 result.append(buffer);
1935 write(fd, result.string(), result.size());
1936 return NO_ERROR;
1937}
1938
Eric Laurent059b4be2009-11-09 23:32:22 -08001939uint32_t AudioFlinger::MixerThread::activeSleepTimeUs()
Eric Laurent62443f52009-10-05 20:29:18 -07001940{
Eric Laurent059b4be2009-11-09 23:32:22 -08001941 return (uint32_t)(mOutput->latency() * 1000) / 2;
1942}
1943
1944uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
1945{
1946 return (uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000;
Eric Laurent62443f52009-10-05 20:29:18 -07001947}
1948
Eric Laurenta553c252009-07-17 12:17:14 -07001949// ----------------------------------------------------------------------------
Eric Laurent65b65452010-06-01 23:49:17 -07001950AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
1951 : PlaybackThread(audioFlinger, output, id, device)
Eric Laurenta553c252009-07-17 12:17:14 -07001952{
1953 mType = PlaybackThread::DIRECT;
1954}
1955
1956AudioFlinger::DirectOutputThread::~DirectOutputThread()
1957{
1958}
1959
1960
Eric Laurent65b65452010-06-01 23:49:17 -07001961static inline int16_t clamp16(int32_t sample)
1962{
1963 if ((sample>>15) ^ (sample>>31))
1964 sample = 0x7FFF ^ (sample>>31);
1965 return sample;
1966}
1967
1968static inline
1969int32_t mul(int16_t in, int16_t v)
1970{
1971#if defined(__arm__) && !defined(__thumb__)
1972 int32_t out;
1973 asm( "smulbb %[out], %[in], %[v] \n"
1974 : [out]"=r"(out)
1975 : [in]"%r"(in), [v]"r"(v)
1976 : );
1977 return out;
1978#else
1979 return in * int32_t(v);
1980#endif
1981}
1982
1983void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
1984{
1985 // Do not apply volume on compressed audio
1986 if (!AudioSystem::isLinearPCM(mFormat)) {
1987 return;
1988 }
1989
1990 // convert to signed 16 bit before volume calculation
1991 if (mFormat == AudioSystem::PCM_8_BIT) {
1992 size_t count = mFrameCount * mChannelCount;
1993 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
1994 int16_t *dst = mMixBuffer + count-1;
1995 while(count--) {
1996 *dst-- = (int16_t)(*src--^0x80) << 8;
1997 }
1998 }
1999
2000 size_t frameCount = mFrameCount;
2001 int16_t *out = mMixBuffer;
2002 if (ramp) {
2003 if (mChannelCount == 1) {
2004 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2005 int32_t vlInc = d / (int32_t)frameCount;
2006 int32_t vl = ((int32_t)mLeftVolShort << 16);
2007 do {
2008 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2009 out++;
2010 vl += vlInc;
2011 } while (--frameCount);
2012
2013 } else {
2014 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2015 int32_t vlInc = d / (int32_t)frameCount;
2016 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2017 int32_t vrInc = d / (int32_t)frameCount;
2018 int32_t vl = ((int32_t)mLeftVolShort << 16);
2019 int32_t vr = ((int32_t)mRightVolShort << 16);
2020 do {
2021 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2022 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2023 out += 2;
2024 vl += vlInc;
2025 vr += vrInc;
2026 } while (--frameCount);
2027 }
2028 } else {
2029 if (mChannelCount == 1) {
2030 do {
2031 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2032 out++;
2033 } while (--frameCount);
2034 } else {
2035 do {
2036 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2037 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2038 out += 2;
2039 } while (--frameCount);
2040 }
2041 }
2042
2043 // convert back to unsigned 8 bit after volume calculation
2044 if (mFormat == AudioSystem::PCM_8_BIT) {
2045 size_t count = mFrameCount * mChannelCount;
2046 int16_t *src = mMixBuffer;
2047 uint8_t *dst = (uint8_t *)mMixBuffer;
2048 while(count--) {
2049 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2050 }
2051 }
2052
2053 mLeftVolShort = leftVol;
2054 mRightVolShort = rightVol;
2055}
2056
Eric Laurenta553c252009-07-17 12:17:14 -07002057bool AudioFlinger::DirectOutputThread::threadLoop()
2058{
Eric Laurent059b4be2009-11-09 23:32:22 -08002059 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002060 sp<Track> trackToRemove;
2061 sp<Track> activeTrack;
2062 nsecs_t standbyTime = systemTime();
2063 int8_t *curBuf;
2064 size_t mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent059b4be2009-11-09 23:32:22 -08002065 uint32_t activeSleepTime = activeSleepTimeUs();
2066 uint32_t idleSleepTime = idleSleepTimeUs();
2067 uint32_t sleepTime = idleSleepTime;
Eric Laurentef9500f2010-03-11 14:47:00 -08002068 // use shorter standby delay as on normal output to release
2069 // hardware resources as soon as possible
2070 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
Eric Laurent059b4be2009-11-09 23:32:22 -08002071
Eric Laurenta553c252009-07-17 12:17:14 -07002072
2073 while (!exitPending())
2074 {
Eric Laurent65b65452010-06-01 23:49:17 -07002075 bool rampVolume;
2076 uint16_t leftVol;
2077 uint16_t rightVol;
2078 Vector< sp<EffectChain> > effectChains;
2079
Eric Laurenta553c252009-07-17 12:17:14 -07002080 processConfigEvents();
2081
Eric Laurent059b4be2009-11-09 23:32:22 -08002082 mixerStatus = MIXER_IDLE;
2083
Eric Laurenta553c252009-07-17 12:17:14 -07002084 { // scope for the mLock
2085
2086 Mutex::Autolock _l(mLock);
2087
2088 if (checkForNewParameters_l()) {
2089 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent059b4be2009-11-09 23:32:22 -08002090 activeSleepTime = activeSleepTimeUs();
2091 idleSleepTime = idleSleepTimeUs();
Eric Laurentef9500f2010-03-11 14:47:00 -08002092 standbyDelay = microseconds(activeSleepTime*2);
Eric Laurenta553c252009-07-17 12:17:14 -07002093 }
2094
2095 // put audio hardware into standby after short delay
2096 if UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2097 mSuspended) {
2098 // wait until we have something to do...
2099 if (!mStandby) {
2100 LOGV("Audio hardware entering standby, mixer %p\n", this);
2101 mOutput->standby();
2102 mStandby = true;
2103 mBytesWritten = 0;
2104 }
2105
2106 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2107 // we're about to wait, flush the binder command buffer
2108 IPCThreadState::self()->flushCommands();
2109
2110 if (exitPending()) break;
2111
2112 LOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
2113 mWaitWorkCV.wait(mLock);
2114 LOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
2115
2116 if (mMasterMute == false) {
2117 char value[PROPERTY_VALUE_MAX];
2118 property_get("ro.audio.silent", value, "0");
2119 if (atoi(value)) {
2120 LOGD("Silence is golden");
2121 setMasterMute(true);
2122 }
2123 }
2124
Eric Laurentef9500f2010-03-11 14:47:00 -08002125 standbyTime = systemTime() + standbyDelay;
Eric Laurent059b4be2009-11-09 23:32:22 -08002126 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07002127 continue;
2128 }
2129 }
2130
Eric Laurent65b65452010-06-01 23:49:17 -07002131 effectChains = mEffectChains;
2132
Eric Laurenta553c252009-07-17 12:17:14 -07002133 // find out which tracks need to be processed
2134 if (mActiveTracks.size() != 0) {
2135 sp<Track> t = mActiveTracks[0].promote();
2136 if (t == 0) continue;
2137
2138 Track* const track = t.get();
2139 audio_track_cblk_t* cblk = track->cblk();
2140
2141 // The first time a track is added we wait
2142 // for all its buffers to be filled before processing it
2143 if (cblk->framesReady() && (track->isReady() || track->isStopped()) &&
Eric Laurent380558b2010-04-09 06:11:48 -07002144 !track->isPaused() && !track->isTerminated())
Eric Laurenta553c252009-07-17 12:17:14 -07002145 {
2146 //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
2147
Eric Laurent65b65452010-06-01 23:49:17 -07002148 if (track->mFillingUpStatus == Track::FS_FILLED) {
2149 track->mFillingUpStatus = Track::FS_ACTIVE;
2150 mLeftVolFloat = mRightVolFloat = 0;
2151 mLeftVolShort = mRightVolShort = 0;
2152 if (track->mState == TrackBase::RESUMING) {
2153 track->mState = TrackBase::ACTIVE;
2154 rampVolume = true;
2155 }
2156 } else if (cblk->server != 0) {
2157 // If the track is stopped before the first frame was mixed,
2158 // do not apply ramp
2159 rampVolume = true;
2160 }
Eric Laurenta553c252009-07-17 12:17:14 -07002161 // compute volume for this track
2162 float left, right;
2163 if (track->isMuted() || mMasterMute || track->isPausing() ||
2164 mStreamTypes[track->type()].mute) {
2165 left = right = 0;
2166 if (track->isPausing()) {
2167 track->setPaused();
2168 }
2169 } else {
2170 float typeVolume = mStreamTypes[track->type()].volume;
2171 float v = mMasterVolume * typeVolume;
2172 float v_clamped = v * cblk->volume[0];
2173 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2174 left = v_clamped/MAX_GAIN;
2175 v_clamped = v * cblk->volume[1];
2176 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2177 right = v_clamped/MAX_GAIN;
2178 }
2179
Eric Laurent65b65452010-06-01 23:49:17 -07002180 if (left != mLeftVolFloat || right != mRightVolFloat) {
2181 mLeftVolFloat = left;
2182 mRightVolFloat = right;
Eric Laurenta553c252009-07-17 12:17:14 -07002183
Eric Laurent65b65452010-06-01 23:49:17 -07002184 // If audio HAL implements volume control,
2185 // force software volume to nominal value
2186 if (mOutput->setVolume(left, right) == NO_ERROR) {
2187 left = 1.0f;
2188 right = 1.0f;
Eric Laurenta553c252009-07-17 12:17:14 -07002189 }
Eric Laurent65b65452010-06-01 23:49:17 -07002190
2191 // Convert volumes from float to 8.24
2192 uint32_t vl = (uint32_t)(left * (1 << 24));
2193 uint32_t vr = (uint32_t)(right * (1 << 24));
2194
2195 // Delegate volume control to effect in track effect chain if needed
2196 // only one effect chain can be present on DirectOutputThread, so if
2197 // there is one, the track is connected to it
2198 if (!effectChains.isEmpty()) {
2199 // Do not ramp volume is volume is controlled by effect
2200 if(effectChains[0]->setVolume(&vl, &vr)) {
2201 rampVolume = false;
2202 }
2203 }
2204
2205 // Convert volumes from 8.24 to 4.12 format
2206 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2207 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2208 leftVol = (uint16_t)v_clamped;
2209 v_clamped = (vr + (1 << 11)) >> 12;
2210 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2211 rightVol = (uint16_t)v_clamped;
2212 } else {
2213 leftVol = mLeftVolShort;
2214 rightVol = mRightVolShort;
2215 rampVolume = false;
Eric Laurenta553c252009-07-17 12:17:14 -07002216 }
2217
2218 // reset retry count
Eric Laurentef9500f2010-03-11 14:47:00 -08002219 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurenta553c252009-07-17 12:17:14 -07002220 activeTrack = t;
Eric Laurent059b4be2009-11-09 23:32:22 -08002221 mixerStatus = MIXER_TRACKS_READY;
Eric Laurenta553c252009-07-17 12:17:14 -07002222 } else {
2223 //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
2224 if (track->isStopped()) {
2225 track->reset();
2226 }
2227 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2228 // We have consumed all the buffers of this track.
2229 // Remove it from the list of active tracks.
2230 trackToRemove = track;
2231 } else {
2232 // No buffers for this track. Give it a few chances to
2233 // fill a buffer, then remove it from active list.
2234 if (--(track->mRetryCount) <= 0) {
2235 LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
2236 trackToRemove = track;
Eric Laurent059b4be2009-11-09 23:32:22 -08002237 } else {
2238 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07002239 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002240 }
Eric Laurenta553c252009-07-17 12:17:14 -07002241 }
2242 }
2243
2244 // remove all the tracks that need to be...
2245 if (UNLIKELY(trackToRemove != 0)) {
2246 mActiveTracks.remove(trackToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07002247 if (!effectChains.isEmpty()) {
2248 LOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(), trackToRemove->sessionId());
2249 effectChains[0]->stopTrack();
2250 }
Eric Laurenta553c252009-07-17 12:17:14 -07002251 if (trackToRemove->isTerminated()) {
2252 mTracks.remove(trackToRemove);
2253 deleteTrackName_l(trackToRemove->mName);
2254 }
2255 }
Eric Laurent65b65452010-06-01 23:49:17 -07002256
2257 lockEffectChains_l();
Eric Laurenta553c252009-07-17 12:17:14 -07002258 }
2259
Eric Laurent059b4be2009-11-09 23:32:22 -08002260 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002261 AudioBufferProvider::Buffer buffer;
2262 size_t frameCount = mFrameCount;
2263 curBuf = (int8_t *)mMixBuffer;
2264 // output audio to hardware
Eric Laurent65b65452010-06-01 23:49:17 -07002265 while (frameCount) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002266 buffer.frameCount = frameCount;
2267 activeTrack->getNextBuffer(&buffer);
2268 if (UNLIKELY(buffer.raw == 0)) {
2269 memset(curBuf, 0, frameCount * mFrameSize);
2270 break;
2271 }
2272 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2273 frameCount -= buffer.frameCount;
2274 curBuf += buffer.frameCount * mFrameSize;
2275 activeTrack->releaseBuffer(&buffer);
2276 }
2277 sleepTime = 0;
Eric Laurentef9500f2010-03-11 14:47:00 -08002278 standbyTime = systemTime() + standbyDelay;
Eric Laurent96c08a62009-09-07 08:38:38 -07002279 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07002280 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002281 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2282 sleepTime = activeSleepTime;
2283 } else {
2284 sleepTime = idleSleepTime;
2285 }
Eric Laurent62443f52009-10-05 20:29:18 -07002286 } else if (mBytesWritten != 0 && AudioSystem::isLinearPCM(mFormat)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002287 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent96c08a62009-09-07 08:38:38 -07002288 sleepTime = 0;
Eric Laurent96c08a62009-09-07 08:38:38 -07002289 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002290 }
Eric Laurent96c08a62009-09-07 08:38:38 -07002291
Eric Laurentf69a3f82009-09-22 00:35:48 -07002292 if (mSuspended) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002293 sleepTime = idleSleepTime;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002294 }
2295 // sleepTime == 0 means we must write to audio hardware
2296 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07002297 if (mixerStatus == MIXER_TRACKS_READY) {
2298 applyVolume(leftVol, rightVol, rampVolume);
2299 }
2300 for (size_t i = 0; i < effectChains.size(); i ++) {
2301 effectChains[i]->process_l();
2302 }
2303 unlockEffectChains();
2304
Eric Laurentf69a3f82009-09-22 00:35:48 -07002305 mLastWriteTime = systemTime();
2306 mInWrite = true;
Eric Laurent0986e792010-01-19 17:37:09 -08002307 mBytesWritten += mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002308 int bytesWritten = (int)mOutput->write(mMixBuffer, mixBufferSize);
Eric Laurent0986e792010-01-19 17:37:09 -08002309 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002310 mNumWrites++;
2311 mInWrite = false;
2312 mStandby = false;
2313 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07002314 unlockEffectChains();
Eric Laurentf69a3f82009-09-22 00:35:48 -07002315 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07002316 }
2317
2318 // finally let go of removed track, without the lock held
2319 // since we can't guarantee the destructors won't acquire that
2320 // same lock.
2321 trackToRemove.clear();
2322 activeTrack.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07002323
2324 // Effect chains will be actually deleted here if they were removed from
2325 // mEffectChains list during mixing or effects processing
2326 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07002327 }
2328
2329 if (!mStandby) {
2330 mOutput->standby();
2331 }
Eric Laurenta553c252009-07-17 12:17:14 -07002332
2333 LOGV("DirectOutputThread %p exiting", this);
2334 return false;
2335}
2336
2337// getTrackName_l() must be called with ThreadBase::mLock held
2338int AudioFlinger::DirectOutputThread::getTrackName_l()
2339{
2340 return 0;
2341}
2342
2343// deleteTrackName_l() must be called with ThreadBase::mLock held
2344void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2345{
2346}
2347
2348// checkForNewParameters_l() must be called with ThreadBase::mLock held
2349bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2350{
2351 bool reconfig = false;
2352
Eric Laurent8fce46a2009-08-04 09:45:33 -07002353 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07002354 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002355 String8 keyValuePair = mNewParameters[0];
2356 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002357 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002358
Eric Laurenta553c252009-07-17 12:17:14 -07002359 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2360 // do not accept frame count changes if tracks are open as the track buffer
2361 // size depends on frame count and correct behavior would not be garantied
2362 // if frame count is changed after track creation
2363 if (!mTracks.isEmpty()) {
2364 status = INVALID_OPERATION;
2365 } else {
2366 reconfig = true;
2367 }
2368 }
2369 if (status == NO_ERROR) {
Eric Laurent8fce46a2009-08-04 09:45:33 -07002370 status = mOutput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002371 if (!mStandby && status == INVALID_OPERATION) {
2372 mOutput->standby();
2373 mStandby = true;
2374 mBytesWritten = 0;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002375 status = mOutput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002376 }
2377 if (status == NO_ERROR && reconfig) {
2378 readOutputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07002379 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07002380 }
2381 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08002382
2383 mNewParameters.removeAt(0);
2384
Eric Laurenta553c252009-07-17 12:17:14 -07002385 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07002386 mParamCond.signal();
Eric Laurent8fce46a2009-08-04 09:45:33 -07002387 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07002388 }
2389 return reconfig;
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08002390}
2391
Eric Laurent059b4be2009-11-09 23:32:22 -08002392uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
Eric Laurent62443f52009-10-05 20:29:18 -07002393{
2394 uint32_t time;
2395 if (AudioSystem::isLinearPCM(mFormat)) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002396 time = (uint32_t)(mOutput->latency() * 1000) / 2;
2397 } else {
2398 time = 10000;
2399 }
2400 return time;
2401}
2402
2403uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2404{
2405 uint32_t time;
2406 if (AudioSystem::isLinearPCM(mFormat)) {
2407 time = (uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000;
Eric Laurent62443f52009-10-05 20:29:18 -07002408 } else {
2409 time = 10000;
2410 }
2411 return time;
2412}
2413
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002414// ----------------------------------------------------------------------------
2415
Eric Laurent49f02be2009-11-19 09:00:56 -08002416AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread, int id)
Eric Laurent65b65452010-06-01 23:49:17 -07002417 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device()), mWaitTimeMs(UINT_MAX)
Eric Laurenta553c252009-07-17 12:17:14 -07002418{
2419 mType = PlaybackThread::DUPLICATING;
2420 addOutputTrack(mainThread);
2421}
2422
2423AudioFlinger::DuplicatingThread::~DuplicatingThread()
2424{
Eric Laurent0a080292009-12-07 10:53:10 -08002425 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2426 mOutputTracks[i]->destroy();
2427 }
Eric Laurenta553c252009-07-17 12:17:14 -07002428 mOutputTracks.clear();
2429}
2430
2431bool AudioFlinger::DuplicatingThread::threadLoop()
2432{
Eric Laurenta553c252009-07-17 12:17:14 -07002433 Vector< sp<Track> > tracksToRemove;
Eric Laurent059b4be2009-11-09 23:32:22 -08002434 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002435 nsecs_t standbyTime = systemTime();
2436 size_t mixBufferSize = mFrameCount*mFrameSize;
2437 SortedVector< sp<OutputTrack> > outputTracks;
Eric Laurent62443f52009-10-05 20:29:18 -07002438 uint32_t writeFrames = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08002439 uint32_t activeSleepTime = activeSleepTimeUs();
2440 uint32_t idleSleepTime = idleSleepTimeUs();
2441 uint32_t sleepTime = idleSleepTime;
Eric Laurent65b65452010-06-01 23:49:17 -07002442 Vector< sp<EffectChain> > effectChains;
Eric Laurenta553c252009-07-17 12:17:14 -07002443
2444 while (!exitPending())
2445 {
2446 processConfigEvents();
2447
Eric Laurent059b4be2009-11-09 23:32:22 -08002448 mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002449 { // scope for the mLock
2450
2451 Mutex::Autolock _l(mLock);
2452
2453 if (checkForNewParameters_l()) {
2454 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002455 updateWaitTime();
Eric Laurent059b4be2009-11-09 23:32:22 -08002456 activeSleepTime = activeSleepTimeUs();
2457 idleSleepTime = idleSleepTimeUs();
Eric Laurenta553c252009-07-17 12:17:14 -07002458 }
2459
2460 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
2461
2462 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2463 outputTracks.add(mOutputTracks[i]);
2464 }
2465
2466 // put audio hardware into standby after short delay
2467 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
2468 mSuspended) {
2469 if (!mStandby) {
2470 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurenta553c252009-07-17 12:17:14 -07002471 outputTracks[i]->stop();
Eric Laurenta553c252009-07-17 12:17:14 -07002472 }
2473 mStandby = true;
2474 mBytesWritten = 0;
2475 }
2476
2477 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
2478 // we're about to wait, flush the binder command buffer
2479 IPCThreadState::self()->flushCommands();
2480 outputTracks.clear();
2481
2482 if (exitPending()) break;
2483
2484 LOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
2485 mWaitWorkCV.wait(mLock);
2486 LOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
2487 if (mMasterMute == false) {
2488 char value[PROPERTY_VALUE_MAX];
2489 property_get("ro.audio.silent", value, "0");
2490 if (atoi(value)) {
2491 LOGD("Silence is golden");
2492 setMasterMute(true);
2493 }
2494 }
2495
2496 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent059b4be2009-11-09 23:32:22 -08002497 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07002498 continue;
2499 }
2500 }
2501
Eric Laurent059b4be2009-11-09 23:32:22 -08002502 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07002503
2504 // prevent any changes in effect chain list and in each effect chain
2505 // during mixing and effect process as the audio buffers could be deleted
2506 // or modified if an effect is created or deleted
2507 effectChains = mEffectChains;
2508 lockEffectChains_l();
Eric Laurentf69a3f82009-09-22 00:35:48 -07002509 }
Eric Laurenta553c252009-07-17 12:17:14 -07002510
Eric Laurent059b4be2009-11-09 23:32:22 -08002511 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurenta553c252009-07-17 12:17:14 -07002512 // mix buffers...
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002513 if (outputsReady(outputTracks)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002514 mAudioMixer->process();
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002515 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07002516 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002517 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002518 sleepTime = 0;
Eric Laurent62443f52009-10-05 20:29:18 -07002519 writeFrames = mFrameCount;
Eric Laurenta553c252009-07-17 12:17:14 -07002520 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07002521 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002522 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2523 sleepTime = activeSleepTime;
2524 } else {
2525 sleepTime = idleSleepTime;
2526 }
Eric Laurent62443f52009-10-05 20:29:18 -07002527 } else if (mBytesWritten != 0) {
2528 // flush remaining overflow buffers in output tracks
2529 for (size_t i = 0; i < outputTracks.size(); i++) {
2530 if (outputTracks[i]->isActive()) {
2531 sleepTime = 0;
2532 writeFrames = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07002533 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent62443f52009-10-05 20:29:18 -07002534 break;
2535 }
2536 }
Eric Laurenta553c252009-07-17 12:17:14 -07002537 }
2538 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002539
2540 if (mSuspended) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002541 sleepTime = idleSleepTime;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002542 }
2543 // sleepTime == 0 means we must write to audio hardware
2544 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07002545 for (size_t i = 0; i < effectChains.size(); i ++) {
2546 effectChains[i]->process_l();
2547 }
2548 // enable changes in effect chain
2549 unlockEffectChains();
2550
Eric Laurent62443f52009-10-05 20:29:18 -07002551 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002552 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurent65b65452010-06-01 23:49:17 -07002553 outputTracks[i]->write(mMixBuffer, writeFrames);
Eric Laurenta553c252009-07-17 12:17:14 -07002554 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002555 mStandby = false;
2556 mBytesWritten += mixBufferSize;
Eric Laurenta553c252009-07-17 12:17:14 -07002557 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07002558 // enable changes in effect chain
2559 unlockEffectChains();
Eric Laurentf69a3f82009-09-22 00:35:48 -07002560 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07002561 }
2562
2563 // finally let go of all our tracks, without the lock held
2564 // since we can't guarantee the destructors won't acquire that
2565 // same lock.
2566 tracksToRemove.clear();
2567 outputTracks.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07002568
2569 // Effect chains will be actually deleted here if they were removed from
2570 // mEffectChains list during mixing or effects processing
2571 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07002572 }
2573
Eric Laurenta553c252009-07-17 12:17:14 -07002574 return false;
2575}
2576
2577void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
2578{
2579 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
2580 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002581 this,
Eric Laurenta553c252009-07-17 12:17:14 -07002582 mSampleRate,
2583 mFormat,
2584 mChannelCount,
2585 frameCount);
Eric Laurent6c30a712009-08-10 23:22:32 -07002586 if (outputTrack->cblk() != NULL) {
2587 thread->setStreamVolume(AudioSystem::NUM_STREAM_TYPES, 1.0f);
2588 mOutputTracks.add(outputTrack);
2589 LOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002590 updateWaitTime();
Eric Laurent6c30a712009-08-10 23:22:32 -07002591 }
Eric Laurenta553c252009-07-17 12:17:14 -07002592}
2593
2594void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
2595{
2596 Mutex::Autolock _l(mLock);
2597 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2598 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
Eric Laurent6c30a712009-08-10 23:22:32 -07002599 mOutputTracks[i]->destroy();
Eric Laurenta553c252009-07-17 12:17:14 -07002600 mOutputTracks.removeAt(i);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002601 updateWaitTime();
Eric Laurenta553c252009-07-17 12:17:14 -07002602 return;
2603 }
2604 }
2605 LOGV("removeOutputTrack(): unkonwn thread: %p", thread);
2606}
2607
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002608void AudioFlinger::DuplicatingThread::updateWaitTime()
2609{
2610 mWaitTimeMs = UINT_MAX;
2611 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2612 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
2613 if (strong != NULL) {
2614 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
2615 if (waitTimeMs < mWaitTimeMs) {
2616 mWaitTimeMs = waitTimeMs;
2617 }
2618 }
2619 }
2620}
2621
2622
2623bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
2624{
2625 for (size_t i = 0; i < outputTracks.size(); i++) {
2626 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
2627 if (thread == 0) {
2628 LOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
2629 return false;
2630 }
2631 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2632 if (playbackThread->standby() && !playbackThread->isSuspended()) {
2633 LOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
2634 return false;
2635 }
2636 }
2637 return true;
2638}
2639
2640uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
2641{
2642 return (mWaitTimeMs * 1000) / 2;
2643}
2644
Eric Laurenta553c252009-07-17 12:17:14 -07002645// ----------------------------------------------------------------------------
2646
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002647// TrackBase constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07002648AudioFlinger::ThreadBase::TrackBase::TrackBase(
2649 const wp<ThreadBase>& thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002650 const sp<Client>& client,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002651 uint32_t sampleRate,
2652 int format,
2653 int channelCount,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002654 int frameCount,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002655 uint32_t flags,
Eric Laurent65b65452010-06-01 23:49:17 -07002656 const sp<IMemory>& sharedBuffer,
2657 int sessionId)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002658 : RefBase(),
Eric Laurenta553c252009-07-17 12:17:14 -07002659 mThread(thread),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002660 mClient(client),
Eric Laurent8a77a992009-09-09 05:16:08 -07002661 mCblk(0),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002662 mFrameCount(0),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002663 mState(IDLE),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002664 mClientTid(-1),
2665 mFormat(format),
Eric Laurent65b65452010-06-01 23:49:17 -07002666 mFlags(flags & ~SYSTEM_FLAGS_MASK),
2667 mSessionId(sessionId)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002668{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002669 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
2670
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002671 // LOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002672 size_t size = sizeof(audio_track_cblk_t);
2673 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
2674 if (sharedBuffer == 0) {
2675 size += bufferSize;
2676 }
2677
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002678 if (client != NULL) {
2679 mCblkMemory = client->heap()->allocate(size);
2680 if (mCblkMemory != 0) {
2681 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
2682 if (mCblk) { // construct the shared structure in-place.
2683 new(mCblk) audio_track_cblk_t();
2684 // clear all buffers
2685 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07002686 mCblk->sampleRate = sampleRate;
Eric Laurentb0a01472010-05-14 05:45:46 -07002687 mCblk->channelCount = (uint8_t)channelCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002688 if (sharedBuffer == 0) {
2689 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2690 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2691 // Force underrun condition to avoid false underrun callback until first data is
2692 // written to buffer
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002693 mCblk->flags = CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002694 } else {
2695 mBuffer = sharedBuffer->pointer();
2696 }
2697 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002698 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002699 } else {
2700 LOGE("not enough memory for AudioTrack size=%u", size);
2701 client->heap()->dump("AudioTrack");
2702 return;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002703 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002704 } else {
2705 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
2706 if (mCblk) { // construct the shared structure in-place.
2707 new(mCblk) audio_track_cblk_t();
2708 // clear all buffers
2709 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07002710 mCblk->sampleRate = sampleRate;
Eric Laurentb0a01472010-05-14 05:45:46 -07002711 mCblk->channelCount = (uint8_t)channelCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002712 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2713 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2714 // Force underrun condition to avoid false underrun callback until first data is
2715 // written to buffer
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002716 mCblk->flags = CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002717 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
2718 }
2719 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002720}
2721
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002722AudioFlinger::ThreadBase::TrackBase::~TrackBase()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002723{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002724 if (mCblk) {
Eric Laurenta553c252009-07-17 12:17:14 -07002725 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
2726 if (mClient == NULL) {
2727 delete mCblk;
2728 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002729 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002730 mCblkMemory.clear(); // and free the shared memory
Eric Laurentb9481d82009-09-17 05:12:56 -07002731 if (mClient != NULL) {
2732 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
2733 mClient.clear();
2734 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002735}
2736
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002737void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002738{
2739 buffer->raw = 0;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002740 mFrameCount = buffer->frameCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002741 step();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002742 buffer->frameCount = 0;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002743}
2744
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002745bool AudioFlinger::ThreadBase::TrackBase::step() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002746 bool result;
2747 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002748
2749 result = cblk->stepServer(mFrameCount);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002750 if (!result) {
2751 LOGV("stepServer failed acquiring cblk mutex");
2752 mFlags |= STEPSERVER_FAILED;
2753 }
2754 return result;
2755}
2756
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002757void AudioFlinger::ThreadBase::TrackBase::reset() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002758 audio_track_cblk_t* cblk = this->cblk();
2759
2760 cblk->user = 0;
2761 cblk->server = 0;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002762 cblk->userBase = 0;
2763 cblk->serverBase = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002764 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002765 LOGV("TrackBase::reset");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002766}
2767
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002768sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002769{
2770 return mCblkMemory;
2771}
2772
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002773int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
The Android Open Source Project10592532009-03-18 17:39:46 -07002774 return (int)mCblk->sampleRate;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002775}
2776
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002777int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
Eric Laurentb0a01472010-05-14 05:45:46 -07002778 return (int)mCblk->channelCount;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002779}
2780
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002781void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002782 audio_track_cblk_t* cblk = this->cblk();
Eric Laurenta553c252009-07-17 12:17:14 -07002783 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
2784 int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002785
2786 // Check validity of returned pointer in case the track control block would have been corrupted.
Eric Laurenta553c252009-07-17 12:17:14 -07002787 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
2788 ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
The Android Open Source Project10592532009-03-18 17:39:46 -07002789 LOGE("TrackBase::getBuffer buffer out of range:\n start: %p, end %p , mBuffer %p mBufferEnd %p\n \
Eric Laurentb0a01472010-05-14 05:45:46 -07002790 server %d, serverBase %d, user %d, userBase %d, channelCount %d",
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002791 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Eric Laurentb0a01472010-05-14 05:45:46 -07002792 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, cblk->channelCount);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002793 return 0;
2794 }
2795
2796 return bufferStart;
2797}
2798
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002799// ----------------------------------------------------------------------------
2800
Eric Laurenta553c252009-07-17 12:17:14 -07002801// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
2802AudioFlinger::PlaybackThread::Track::Track(
2803 const wp<ThreadBase>& thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002804 const sp<Client>& client,
2805 int streamType,
2806 uint32_t sampleRate,
2807 int format,
2808 int channelCount,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002809 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07002810 const sp<IMemory>& sharedBuffer,
2811 int sessionId)
2812 : TrackBase(thread, client, sampleRate, format, channelCount, frameCount, 0, sharedBuffer, sessionId),
2813 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL), mAuxEffectId(0)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002814{
Eric Laurent8a77a992009-09-09 05:16:08 -07002815 if (mCblk != NULL) {
2816 sp<ThreadBase> baseThread = thread.promote();
2817 if (baseThread != 0) {
2818 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
2819 mName = playbackThread->getTrackName_l();
Eric Laurent65b65452010-06-01 23:49:17 -07002820 mMainBuffer = playbackThread->mixBuffer();
Eric Laurent8a77a992009-09-09 05:16:08 -07002821 }
2822 LOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2823 if (mName < 0) {
2824 LOGE("no more track names available");
2825 }
2826 mVolume[0] = 1.0f;
2827 mVolume[1] = 1.0f;
2828 mStreamType = streamType;
2829 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
2830 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
2831 mCblk->frameSize = AudioSystem::isLinearPCM(format) ? channelCount * sizeof(int16_t) : sizeof(int8_t);
Eric Laurenta553c252009-07-17 12:17:14 -07002832 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002833}
2834
Eric Laurenta553c252009-07-17 12:17:14 -07002835AudioFlinger::PlaybackThread::Track::~Track()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002836{
Eric Laurenta553c252009-07-17 12:17:14 -07002837 LOGV("PlaybackThread::Track destructor");
2838 sp<ThreadBase> thread = mThread.promote();
2839 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08002840 Mutex::Autolock _l(thread->mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07002841 mState = TERMINATED;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002842 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002843}
2844
Eric Laurenta553c252009-07-17 12:17:14 -07002845void AudioFlinger::PlaybackThread::Track::destroy()
2846{
2847 // NOTE: destroyTrack_l() can remove a strong reference to this Track
2848 // by removing it from mTracks vector, so there is a risk that this Tracks's
2849 // desctructor is called. As the destructor needs to lock mLock,
2850 // we must acquire a strong reference on this Track before locking mLock
2851 // here so that the destructor is called only when exiting this function.
2852 // On the other hand, as long as Track::destroy() is only called by
2853 // TrackHandle destructor, the TrackHandle still holds a strong ref on
2854 // this Track with its member mTrack.
2855 sp<Track> keep(this);
2856 { // scope for mLock
2857 sp<ThreadBase> thread = mThread.promote();
2858 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08002859 if (!isOutputTrack()) {
2860 if (mState == ACTIVE || mState == RESUMING) {
2861 AudioSystem::stopOutput(thread->id(), (AudioSystem::stream_type)mStreamType);
2862 }
2863 AudioSystem::releaseOutput(thread->id());
Eric Laurent49f02be2009-11-19 09:00:56 -08002864 }
Eric Laurenta553c252009-07-17 12:17:14 -07002865 Mutex::Autolock _l(thread->mLock);
2866 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2867 playbackThread->destroyTrack_l(this);
2868 }
2869 }
2870}
2871
2872void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002873{
Eric Laurent65b65452010-06-01 23:49:17 -07002874 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 -07002875 mName - AudioMixer::TRACK0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002876 (mClient == NULL) ? getpid() : mClient->pid(),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002877 mStreamType,
2878 mFormat,
Eric Laurentb0a01472010-05-14 05:45:46 -07002879 mCblk->channelCount,
Eric Laurent65b65452010-06-01 23:49:17 -07002880 mSessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002881 mFrameCount,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002882 mState,
2883 mMute,
2884 mFillingUpStatus,
2885 mCblk->sampleRate,
2886 mCblk->volume[0],
2887 mCblk->volume[1],
2888 mCblk->server,
Eric Laurent65b65452010-06-01 23:49:17 -07002889 mCblk->user,
2890 (int)mMainBuffer,
2891 (int)mAuxBuffer);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002892}
2893
Eric Laurenta553c252009-07-17 12:17:14 -07002894status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002895{
2896 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002897 uint32_t framesReady;
2898 uint32_t framesReq = buffer->frameCount;
2899
2900 // Check if last stepServer failed, try to step now
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002901 if (mFlags & TrackBase::STEPSERVER_FAILED) {
2902 if (!step()) goto getNextBuffer_exit;
2903 LOGV("stepServer recovered");
2904 mFlags &= ~TrackBase::STEPSERVER_FAILED;
2905 }
2906
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002907 framesReady = cblk->framesReady();
2908
2909 if (LIKELY(framesReady)) {
2910 uint32_t s = cblk->server;
2911 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
2912
2913 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
2914 if (framesReq > framesReady) {
2915 framesReq = framesReady;
2916 }
2917 if (s + framesReq > bufferEnd) {
2918 framesReq = bufferEnd - s;
2919 }
2920
2921 buffer->raw = getBuffer(s, framesReq);
2922 if (buffer->raw == 0) goto getNextBuffer_exit;
2923
2924 buffer->frameCount = framesReq;
2925 return NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002926 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002927
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002928getNextBuffer_exit:
2929 buffer->raw = 0;
2930 buffer->frameCount = 0;
Eric Laurent62443f52009-10-05 20:29:18 -07002931 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 -07002932 return NOT_ENOUGH_DATA;
2933}
2934
Eric Laurenta553c252009-07-17 12:17:14 -07002935bool AudioFlinger::PlaybackThread::Track::isReady() const {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002936 if (mFillingUpStatus != FS_FILLING) return true;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002937
2938 if (mCblk->framesReady() >= mCblk->frameCount ||
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002939 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002940 mFillingUpStatus = FS_FILLED;
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002941 mCblk->flags &= ~CBLK_FORCEREADY_MSK;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002942 return true;
2943 }
2944 return false;
2945}
2946
Eric Laurenta553c252009-07-17 12:17:14 -07002947status_t AudioFlinger::PlaybackThread::Track::start()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002948{
Eric Laurent49f02be2009-11-19 09:00:56 -08002949 status_t status = NO_ERROR;
Eric Laurenta553c252009-07-17 12:17:14 -07002950 LOGV("start(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2951 sp<ThreadBase> thread = mThread.promote();
2952 if (thread != 0) {
2953 Mutex::Autolock _l(thread->mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08002954 int state = mState;
2955 // here the track could be either new, or restarted
2956 // in both cases "unstop" the track
2957 if (mState == PAUSED) {
2958 mState = TrackBase::RESUMING;
2959 LOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
2960 } else {
2961 mState = TrackBase::ACTIVE;
2962 LOGV("? => ACTIVE (%d) on thread %p", mName, this);
2963 }
2964
2965 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
2966 thread->mLock.unlock();
2967 status = AudioSystem::startOutput(thread->id(), (AudioSystem::stream_type)mStreamType);
2968 thread->mLock.lock();
2969 }
2970 if (status == NO_ERROR) {
2971 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2972 playbackThread->addTrack_l(this);
2973 } else {
2974 mState = state;
2975 }
2976 } else {
2977 status = BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -07002978 }
Eric Laurent49f02be2009-11-19 09:00:56 -08002979 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002980}
2981
Eric Laurenta553c252009-07-17 12:17:14 -07002982void AudioFlinger::PlaybackThread::Track::stop()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002983{
Eric Laurenta553c252009-07-17 12:17:14 -07002984 LOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2985 sp<ThreadBase> thread = mThread.promote();
2986 if (thread != 0) {
2987 Mutex::Autolock _l(thread->mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08002988 int state = mState;
Eric Laurenta553c252009-07-17 12:17:14 -07002989 if (mState > STOPPED) {
2990 mState = STOPPED;
2991 // If the track is not active (PAUSED and buffers full), flush buffers
2992 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2993 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
2994 reset();
2995 }
Eric Laurent62443f52009-10-05 20:29:18 -07002996 LOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002997 }
Eric Laurent49f02be2009-11-19 09:00:56 -08002998 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
2999 thread->mLock.unlock();
3000 AudioSystem::stopOutput(thread->id(), (AudioSystem::stream_type)mStreamType);
3001 thread->mLock.lock();
3002 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003003 }
3004}
3005
Eric Laurenta553c252009-07-17 12:17:14 -07003006void AudioFlinger::PlaybackThread::Track::pause()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003007{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003008 LOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurenta553c252009-07-17 12:17:14 -07003009 sp<ThreadBase> thread = mThread.promote();
3010 if (thread != 0) {
3011 Mutex::Autolock _l(thread->mLock);
3012 if (mState == ACTIVE || mState == RESUMING) {
3013 mState = PAUSING;
Eric Laurent62443f52009-10-05 20:29:18 -07003014 LOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurent49f02be2009-11-19 09:00:56 -08003015 if (!isOutputTrack()) {
3016 thread->mLock.unlock();
3017 AudioSystem::stopOutput(thread->id(), (AudioSystem::stream_type)mStreamType);
3018 thread->mLock.lock();
3019 }
Eric Laurenta553c252009-07-17 12:17:14 -07003020 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003021 }
3022}
3023
Eric Laurenta553c252009-07-17 12:17:14 -07003024void AudioFlinger::PlaybackThread::Track::flush()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003025{
3026 LOGV("flush(%d)", mName);
Eric Laurenta553c252009-07-17 12:17:14 -07003027 sp<ThreadBase> thread = mThread.promote();
3028 if (thread != 0) {
3029 Mutex::Autolock _l(thread->mLock);
3030 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3031 return;
3032 }
3033 // No point remaining in PAUSED state after a flush => go to
3034 // STOPPED state
3035 mState = STOPPED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003036
Eric Laurenta553c252009-07-17 12:17:14 -07003037 mCblk->lock.lock();
3038 // NOTE: reset() will reset cblk->user and cblk->server with
3039 // the risk that at the same time, the AudioMixer is trying to read
3040 // data. In this case, getNextBuffer() would return a NULL pointer
3041 // as audio buffer => the AudioMixer code MUST always test that pointer
3042 // returned by getNextBuffer() is not NULL!
3043 reset();
3044 mCblk->lock.unlock();
3045 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003046}
3047
Eric Laurenta553c252009-07-17 12:17:14 -07003048void AudioFlinger::PlaybackThread::Track::reset()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003049{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003050 // Do not reset twice to avoid discarding data written just after a flush and before
3051 // the audioflinger thread detects the track is stopped.
3052 if (!mResetDone) {
3053 TrackBase::reset();
3054 // Force underrun condition to avoid false underrun callback until first data is
3055 // written to buffer
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003056 mCblk->flags |= CBLK_UNDERRUN_ON;
3057 mCblk->flags &= ~CBLK_FORCEREADY_MSK;
Eric Laurenta553c252009-07-17 12:17:14 -07003058 mFillingUpStatus = FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003059 mResetDone = true;
3060 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003061}
3062
Eric Laurenta553c252009-07-17 12:17:14 -07003063void AudioFlinger::PlaybackThread::Track::mute(bool muted)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003064{
3065 mMute = muted;
3066}
3067
Eric Laurenta553c252009-07-17 12:17:14 -07003068void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003069{
3070 mVolume[0] = left;
3071 mVolume[1] = right;
3072}
3073
Eric Laurent65b65452010-06-01 23:49:17 -07003074status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3075{
3076 status_t status = DEAD_OBJECT;
3077 sp<ThreadBase> thread = mThread.promote();
3078 if (thread != 0) {
3079 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3080 status = playbackThread->attachAuxEffect(this, EffectId);
3081 }
3082 return status;
3083}
3084
3085void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3086{
3087 mAuxEffectId = EffectId;
3088 mAuxBuffer = buffer;
3089}
3090
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003091// ----------------------------------------------------------------------------
3092
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003093// RecordTrack constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07003094AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3095 const wp<ThreadBase>& thread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003096 const sp<Client>& client,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003097 uint32_t sampleRate,
3098 int format,
3099 int channelCount,
3100 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07003101 uint32_t flags,
3102 int sessionId)
Eric Laurenta553c252009-07-17 12:17:14 -07003103 : TrackBase(thread, client, sampleRate, format,
Eric Laurent65b65452010-06-01 23:49:17 -07003104 channelCount, frameCount, flags, 0, sessionId),
Eric Laurenta553c252009-07-17 12:17:14 -07003105 mOverflow(false)
3106{
Eric Laurent8a77a992009-09-09 05:16:08 -07003107 if (mCblk != NULL) {
3108 LOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
3109 if (format == AudioSystem::PCM_16_BIT) {
3110 mCblk->frameSize = channelCount * sizeof(int16_t);
3111 } else if (format == AudioSystem::PCM_8_BIT) {
3112 mCblk->frameSize = channelCount * sizeof(int8_t);
3113 } else {
3114 mCblk->frameSize = sizeof(int8_t);
3115 }
3116 }
Eric Laurenta553c252009-07-17 12:17:14 -07003117}
3118
3119AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003120{
Eric Laurent49f02be2009-11-19 09:00:56 -08003121 sp<ThreadBase> thread = mThread.promote();
3122 if (thread != 0) {
3123 AudioSystem::releaseInput(thread->id());
3124 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003125}
3126
Eric Laurenta553c252009-07-17 12:17:14 -07003127status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003128{
3129 audio_track_cblk_t* cblk = this->cblk();
3130 uint32_t framesAvail;
3131 uint32_t framesReq = buffer->frameCount;
3132
3133 // Check if last stepServer failed, try to step now
3134 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3135 if (!step()) goto getNextBuffer_exit;
3136 LOGV("stepServer recovered");
3137 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3138 }
3139
3140 framesAvail = cblk->framesAvailable_l();
3141
3142 if (LIKELY(framesAvail)) {
3143 uint32_t s = cblk->server;
3144 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3145
3146 if (framesReq > framesAvail) {
3147 framesReq = framesAvail;
3148 }
3149 if (s + framesReq > bufferEnd) {
3150 framesReq = bufferEnd - s;
3151 }
3152
3153 buffer->raw = getBuffer(s, framesReq);
3154 if (buffer->raw == 0) goto getNextBuffer_exit;
3155
3156 buffer->frameCount = framesReq;
3157 return NO_ERROR;
3158 }
3159
3160getNextBuffer_exit:
3161 buffer->raw = 0;
3162 buffer->frameCount = 0;
3163 return NOT_ENOUGH_DATA;
3164}
3165
Eric Laurenta553c252009-07-17 12:17:14 -07003166status_t AudioFlinger::RecordThread::RecordTrack::start()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003167{
Eric Laurenta553c252009-07-17 12:17:14 -07003168 sp<ThreadBase> thread = mThread.promote();
3169 if (thread != 0) {
3170 RecordThread *recordThread = (RecordThread *)thread.get();
3171 return recordThread->start(this);
Eric Laurent49f02be2009-11-19 09:00:56 -08003172 } else {
3173 return BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -07003174 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003175}
3176
Eric Laurenta553c252009-07-17 12:17:14 -07003177void AudioFlinger::RecordThread::RecordTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003178{
Eric Laurenta553c252009-07-17 12:17:14 -07003179 sp<ThreadBase> thread = mThread.promote();
3180 if (thread != 0) {
3181 RecordThread *recordThread = (RecordThread *)thread.get();
3182 recordThread->stop(this);
3183 TrackBase::reset();
3184 // Force overerrun condition to avoid false overrun callback until first data is
3185 // read from buffer
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003186 mCblk->flags |= CBLK_UNDERRUN_ON;
Eric Laurenta553c252009-07-17 12:17:14 -07003187 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003188}
3189
Eric Laurent3fdb1262009-11-07 00:01:32 -08003190void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3191{
Eric Laurent65b65452010-06-01 23:49:17 -07003192 snprintf(buffer, size, " %05d %03u %03u %05d %04u %01d %05u %08x %08x\n",
Eric Laurent3fdb1262009-11-07 00:01:32 -08003193 (mClient == NULL) ? getpid() : mClient->pid(),
3194 mFormat,
Eric Laurentb0a01472010-05-14 05:45:46 -07003195 mCblk->channelCount,
Eric Laurent65b65452010-06-01 23:49:17 -07003196 mSessionId,
Eric Laurent3fdb1262009-11-07 00:01:32 -08003197 mFrameCount,
3198 mState,
3199 mCblk->sampleRate,
3200 mCblk->server,
3201 mCblk->user);
3202}
3203
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003204
3205// ----------------------------------------------------------------------------
3206
Eric Laurenta553c252009-07-17 12:17:14 -07003207AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3208 const wp<ThreadBase>& thread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003209 DuplicatingThread *sourceThread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003210 uint32_t sampleRate,
3211 int format,
3212 int channelCount,
3213 int frameCount)
Eric Laurent65b65452010-06-01 23:49:17 -07003214 : Track(thread, NULL, AudioSystem::NUM_STREAM_TYPES, sampleRate, format, channelCount, frameCount, NULL, 0),
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003215 mActive(false), mSourceThread(sourceThread)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003216{
Eric Laurenta553c252009-07-17 12:17:14 -07003217
3218 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
Eric Laurent6c30a712009-08-10 23:22:32 -07003219 if (mCblk != NULL) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003220 mCblk->flags |= CBLK_DIRECTION_OUT;
Eric Laurent6c30a712009-08-10 23:22:32 -07003221 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
3222 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
3223 mOutBuffer.frameCount = 0;
Eric Laurent6c30a712009-08-10 23:22:32 -07003224 playbackThread->mTracks.add(this);
Eric Laurentb0a01472010-05-14 05:45:46 -07003225 LOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, mCblk->frameCount %d, mCblk->sampleRate %d, mCblk->channelCount %d mBufferEnd %p",
3226 mCblk, mBuffer, mCblk->buffers, mCblk->frameCount, mCblk->sampleRate, mCblk->channelCount, mBufferEnd);
Eric Laurent6c30a712009-08-10 23:22:32 -07003227 } else {
3228 LOGW("Error creating output track on thread %p", playbackThread);
3229 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003230}
3231
Eric Laurenta553c252009-07-17 12:17:14 -07003232AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003233{
Eric Laurent6c30a712009-08-10 23:22:32 -07003234 clearBufferQueue();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003235}
3236
Eric Laurenta553c252009-07-17 12:17:14 -07003237status_t AudioFlinger::PlaybackThread::OutputTrack::start()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003238{
3239 status_t status = Track::start();
Eric Laurenta553c252009-07-17 12:17:14 -07003240 if (status != NO_ERROR) {
3241 return status;
3242 }
3243
3244 mActive = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003245 mRetryCount = 127;
3246 return status;
3247}
3248
Eric Laurenta553c252009-07-17 12:17:14 -07003249void AudioFlinger::PlaybackThread::OutputTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003250{
3251 Track::stop();
3252 clearBufferQueue();
3253 mOutBuffer.frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003254 mActive = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003255}
3256
Eric Laurenta553c252009-07-17 12:17:14 -07003257bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003258{
3259 Buffer *pInBuffer;
3260 Buffer inBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003261 uint32_t channelCount = mCblk->channelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003262 bool outputBufferFull = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003263 inBuffer.frameCount = frames;
3264 inBuffer.i16 = data;
Eric Laurenta553c252009-07-17 12:17:14 -07003265
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003266 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
Eric Laurenta553c252009-07-17 12:17:14 -07003267
Eric Laurent62443f52009-10-05 20:29:18 -07003268 if (!mActive && frames != 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003269 start();
3270 sp<ThreadBase> thread = mThread.promote();
3271 if (thread != 0) {
3272 MixerThread *mixerThread = (MixerThread *)thread.get();
3273 if (mCblk->frameCount > frames){
3274 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3275 uint32_t startFrames = (mCblk->frameCount - frames);
3276 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003277 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
Eric Laurenta553c252009-07-17 12:17:14 -07003278 pInBuffer->frameCount = startFrames;
3279 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003280 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
Eric Laurenta553c252009-07-17 12:17:14 -07003281 mBufferQueue.add(pInBuffer);
3282 } else {
3283 LOGW ("OutputTrack::write() %p no more buffers in queue", this);
3284 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003285 }
Eric Laurenta553c252009-07-17 12:17:14 -07003286 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003287 }
3288
Eric Laurenta553c252009-07-17 12:17:14 -07003289 while (waitTimeLeftMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003290 // First write pending buffers, then new data
3291 if (mBufferQueue.size()) {
3292 pInBuffer = mBufferQueue.itemAt(0);
3293 } else {
3294 pInBuffer = &inBuffer;
3295 }
Eric Laurenta553c252009-07-17 12:17:14 -07003296
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003297 if (pInBuffer->frameCount == 0) {
3298 break;
3299 }
Eric Laurenta553c252009-07-17 12:17:14 -07003300
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003301 if (mOutBuffer.frameCount == 0) {
3302 mOutBuffer.frameCount = pInBuffer->frameCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003303 nsecs_t startTime = systemTime();
3304 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003305 LOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Eric Laurenta553c252009-07-17 12:17:14 -07003306 outputBufferFull = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003307 break;
3308 }
Eric Laurenta553c252009-07-17 12:17:14 -07003309 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
Eric Laurenta553c252009-07-17 12:17:14 -07003310 if (waitTimeLeftMs >= waitTimeMs) {
3311 waitTimeLeftMs -= waitTimeMs;
3312 } else {
3313 waitTimeLeftMs = 0;
3314 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003315 }
Eric Laurenta553c252009-07-17 12:17:14 -07003316
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003317 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
Eric Laurentb0a01472010-05-14 05:45:46 -07003318 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003319 mCblk->stepUser(outFrames);
3320 pInBuffer->frameCount -= outFrames;
Eric Laurentb0a01472010-05-14 05:45:46 -07003321 pInBuffer->i16 += outFrames * channelCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003322 mOutBuffer.frameCount -= outFrames;
Eric Laurentb0a01472010-05-14 05:45:46 -07003323 mOutBuffer.i16 += outFrames * channelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003324
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003325 if (pInBuffer->frameCount == 0) {
3326 if (mBufferQueue.size()) {
3327 mBufferQueue.removeAt(0);
3328 delete [] pInBuffer->mBuffer;
3329 delete pInBuffer;
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003330 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 -08003331 } else {
3332 break;
3333 }
3334 }
3335 }
Eric Laurenta553c252009-07-17 12:17:14 -07003336
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003337 // If we could not write all frames, allocate a buffer and queue it for next time.
3338 if (inBuffer.frameCount) {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003339 sp<ThreadBase> thread = mThread.promote();
3340 if (thread != 0 && !thread->standby()) {
3341 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3342 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003343 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003344 pInBuffer->frameCount = inBuffer.frameCount;
3345 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003346 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003347 mBufferQueue.add(pInBuffer);
3348 LOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
3349 } else {
3350 LOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
3351 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003352 }
3353 }
Eric Laurenta553c252009-07-17 12:17:14 -07003354
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003355 // Calling write() with a 0 length buffer, means that no more data will be written:
Eric Laurenta553c252009-07-17 12:17:14 -07003356 // 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 -08003357 // by output mixer.
Eric Laurenta553c252009-07-17 12:17:14 -07003358 if (frames == 0 && mBufferQueue.size() == 0) {
3359 if (mCblk->user < mCblk->frameCount) {
3360 frames = mCblk->frameCount - mCblk->user;
3361 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003362 pInBuffer->mBuffer = new int16_t[frames * channelCount];
Eric Laurenta553c252009-07-17 12:17:14 -07003363 pInBuffer->frameCount = frames;
3364 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003365 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
Eric Laurenta553c252009-07-17 12:17:14 -07003366 mBufferQueue.add(pInBuffer);
Eric Laurent62443f52009-10-05 20:29:18 -07003367 } else if (mActive) {
Eric Laurenta553c252009-07-17 12:17:14 -07003368 stop();
3369 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003370 }
3371
Eric Laurenta553c252009-07-17 12:17:14 -07003372 return outputBufferFull;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003373}
3374
Eric Laurenta553c252009-07-17 12:17:14 -07003375status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003376{
3377 int active;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003378 status_t result;
3379 audio_track_cblk_t* cblk = mCblk;
3380 uint32_t framesReq = buffer->frameCount;
3381
Eric Laurenta553c252009-07-17 12:17:14 -07003382// LOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003383 buffer->frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003384
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003385 uint32_t framesAvail = cblk->framesAvailable();
3386
Eric Laurenta553c252009-07-17 12:17:14 -07003387
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003388 if (framesAvail == 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003389 Mutex::Autolock _l(cblk->lock);
3390 goto start_loop_here;
3391 while (framesAvail == 0) {
3392 active = mActive;
3393 if (UNLIKELY(!active)) {
3394 LOGV("Not active and NO_MORE_BUFFERS");
3395 return AudioTrack::NO_MORE_BUFFERS;
3396 }
3397 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3398 if (result != NO_ERROR) {
3399 return AudioTrack::NO_MORE_BUFFERS;
3400 }
3401 // read the server count again
3402 start_loop_here:
3403 framesAvail = cblk->framesAvailable_l();
3404 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003405 }
3406
Eric Laurenta553c252009-07-17 12:17:14 -07003407// if (framesAvail < framesReq) {
3408// return AudioTrack::NO_MORE_BUFFERS;
3409// }
3410
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003411 if (framesReq > framesAvail) {
3412 framesReq = framesAvail;
3413 }
3414
3415 uint32_t u = cblk->user;
3416 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
3417
3418 if (u + framesReq > bufferEnd) {
3419 framesReq = bufferEnd - u;
3420 }
3421
3422 buffer->frameCount = framesReq;
3423 buffer->raw = (void *)cblk->buffer(u);
3424 return NO_ERROR;
3425}
3426
3427
Eric Laurenta553c252009-07-17 12:17:14 -07003428void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003429{
3430 size_t size = mBufferQueue.size();
3431 Buffer *pBuffer;
Eric Laurenta553c252009-07-17 12:17:14 -07003432
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003433 for (size_t i = 0; i < size; i++) {
3434 pBuffer = mBufferQueue.itemAt(i);
3435 delete [] pBuffer->mBuffer;
3436 delete pBuffer;
3437 }
3438 mBufferQueue.clear();
3439}
3440
3441// ----------------------------------------------------------------------------
3442
3443AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
3444 : RefBase(),
3445 mAudioFlinger(audioFlinger),
Mathias Agopian6faf7892010-01-25 19:00:00 -08003446 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003447 mPid(pid)
3448{
3449 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
3450}
3451
Eric Laurentb9481d82009-09-17 05:12:56 -07003452// Client destructor must be called with AudioFlinger::mLock held
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003453AudioFlinger::Client::~Client()
3454{
Eric Laurentb9481d82009-09-17 05:12:56 -07003455 mAudioFlinger->removeClient_l(mPid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003456}
3457
3458const sp<MemoryDealer>& AudioFlinger::Client::heap() const
3459{
3460 return mMemoryDealer;
3461}
3462
3463// ----------------------------------------------------------------------------
3464
Eric Laurent4f0f17d2010-05-12 02:05:53 -07003465AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
3466 const sp<IAudioFlingerClient>& client,
3467 pid_t pid)
3468 : mAudioFlinger(audioFlinger), mPid(pid), mClient(client)
3469{
3470}
3471
3472AudioFlinger::NotificationClient::~NotificationClient()
3473{
3474 mClient.clear();
3475}
3476
3477void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
3478{
3479 sp<NotificationClient> keep(this);
3480 {
3481 mAudioFlinger->removeNotificationClient(mPid);
3482 }
3483}
3484
3485// ----------------------------------------------------------------------------
3486
Eric Laurenta553c252009-07-17 12:17:14 -07003487AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003488 : BnAudioTrack(),
3489 mTrack(track)
3490{
3491}
3492
3493AudioFlinger::TrackHandle::~TrackHandle() {
3494 // just stop the track on deletion, associated resources
3495 // will be freed from the main thread once all pending buffers have
3496 // been played. Unless it's not in the active track list, in which
3497 // case we free everything now...
3498 mTrack->destroy();
3499}
3500
3501status_t AudioFlinger::TrackHandle::start() {
3502 return mTrack->start();
3503}
3504
3505void AudioFlinger::TrackHandle::stop() {
3506 mTrack->stop();
3507}
3508
3509void AudioFlinger::TrackHandle::flush() {
3510 mTrack->flush();
3511}
3512
3513void AudioFlinger::TrackHandle::mute(bool e) {
3514 mTrack->mute(e);
3515}
3516
3517void AudioFlinger::TrackHandle::pause() {
3518 mTrack->pause();
3519}
3520
3521void AudioFlinger::TrackHandle::setVolume(float left, float right) {
3522 mTrack->setVolume(left, right);
3523}
3524
3525sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
3526 return mTrack->getCblk();
3527}
3528
Eric Laurent65b65452010-06-01 23:49:17 -07003529status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
3530{
3531 return mTrack->attachAuxEffect(EffectId);
3532}
3533
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003534status_t AudioFlinger::TrackHandle::onTransact(
3535 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3536{
3537 return BnAudioTrack::onTransact(code, data, reply, flags);
3538}
3539
3540// ----------------------------------------------------------------------------
3541
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003542sp<IAudioRecord> AudioFlinger::openRecord(
3543 pid_t pid,
Eric Laurentddb78e72009-07-28 08:44:33 -07003544 int input,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003545 uint32_t sampleRate,
3546 int format,
3547 int channelCount,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003548 int frameCount,
3549 uint32_t flags,
Eric Laurent65b65452010-06-01 23:49:17 -07003550 int *sessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003551 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003552{
Eric Laurenta553c252009-07-17 12:17:14 -07003553 sp<RecordThread::RecordTrack> recordTrack;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003554 sp<RecordHandle> recordHandle;
3555 sp<Client> client;
3556 wp<Client> wclient;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003557 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07003558 RecordThread *thread;
3559 size_t inFrameCount;
Eric Laurent65b65452010-06-01 23:49:17 -07003560 int lSessionId;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003561
3562 // check calling permissions
3563 if (!recordingAllowed()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003564 lStatus = PERMISSION_DENIED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003565 goto Exit;
3566 }
3567
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003568 // add client to list
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003569 { // scope for mLock
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003570 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07003571 thread = checkRecordThread_l(input);
3572 if (thread == NULL) {
3573 lStatus = BAD_VALUE;
3574 goto Exit;
3575 }
3576
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003577 wclient = mClients.valueFor(pid);
3578 if (wclient != NULL) {
3579 client = wclient.promote();
3580 } else {
3581 client = new Client(this, pid);
3582 mClients.add(pid, client);
3583 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003584
Eric Laurent65b65452010-06-01 23:49:17 -07003585 // If no audio session id is provided, create one here
3586 if (sessionId != NULL && *sessionId != 0) {
3587 lSessionId = *sessionId;
3588 } else {
3589 lSessionId = nextUniqueId();
3590 if (sessionId != NULL) {
3591 *sessionId = lSessionId;
3592 }
3593 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003594 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurenta553c252009-07-17 12:17:14 -07003595 recordTrack = new RecordThread::RecordTrack(thread, client, sampleRate,
Eric Laurent65b65452010-06-01 23:49:17 -07003596 format, channelCount, frameCount, flags, lSessionId);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003597 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003598 if (recordTrack->getCblk() == NULL) {
Eric Laurentb9481d82009-09-17 05:12:56 -07003599 // remove local strong reference to Client before deleting the RecordTrack so that the Client
3600 // destructor is called by the TrackBase destructor with mLock held
3601 client.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003602 recordTrack.clear();
3603 lStatus = NO_MEMORY;
3604 goto Exit;
3605 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003606
3607 // return to handle to client
3608 recordHandle = new RecordHandle(recordTrack);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003609 lStatus = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003610
3611Exit:
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003612 if (status) {
3613 *status = lStatus;
3614 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003615 return recordHandle;
3616}
3617
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003618// ----------------------------------------------------------------------------
3619
Eric Laurenta553c252009-07-17 12:17:14 -07003620AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003621 : BnAudioRecord(),
3622 mRecordTrack(recordTrack)
3623{
3624}
3625
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003626AudioFlinger::RecordHandle::~RecordHandle() {
3627 stop();
3628}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003629
3630status_t AudioFlinger::RecordHandle::start() {
3631 LOGV("RecordHandle::start()");
3632 return mRecordTrack->start();
3633}
3634
3635void AudioFlinger::RecordHandle::stop() {
3636 LOGV("RecordHandle::stop()");
3637 mRecordTrack->stop();
3638}
3639
3640sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
3641 return mRecordTrack->getCblk();
3642}
3643
3644status_t AudioFlinger::RecordHandle::onTransact(
3645 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3646{
3647 return BnAudioRecord::onTransact(code, data, reply, flags);
3648}
3649
3650// ----------------------------------------------------------------------------
3651
Eric Laurent49f02be2009-11-19 09:00:56 -08003652AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger, AudioStreamIn *input, uint32_t sampleRate, uint32_t channels, int id) :
3653 ThreadBase(audioFlinger, id),
Eric Laurenta553c252009-07-17 12:17:14 -07003654 mInput(input), mResampler(0), mRsmpOutBuffer(0), mRsmpInBuffer(0)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003655{
Eric Laurenta553c252009-07-17 12:17:14 -07003656 mReqChannelCount = AudioSystem::popCount(channels);
3657 mReqSampleRate = sampleRate;
3658 readInputParameters();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003659}
3660
Eric Laurenta553c252009-07-17 12:17:14 -07003661
3662AudioFlinger::RecordThread::~RecordThread()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003663{
Eric Laurenta553c252009-07-17 12:17:14 -07003664 delete[] mRsmpInBuffer;
3665 if (mResampler != 0) {
3666 delete mResampler;
3667 delete[] mRsmpOutBuffer;
3668 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003669}
3670
Eric Laurenta553c252009-07-17 12:17:14 -07003671void AudioFlinger::RecordThread::onFirstRef()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003672{
Eric Laurenta553c252009-07-17 12:17:14 -07003673 const size_t SIZE = 256;
3674 char buffer[SIZE];
3675
3676 snprintf(buffer, SIZE, "Record Thread %p", this);
3677
3678 run(buffer, PRIORITY_URGENT_AUDIO);
3679}
Eric Laurent49f02be2009-11-19 09:00:56 -08003680
Eric Laurenta553c252009-07-17 12:17:14 -07003681bool AudioFlinger::RecordThread::threadLoop()
3682{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003683 AudioBufferProvider::Buffer buffer;
Eric Laurenta553c252009-07-17 12:17:14 -07003684 sp<RecordTrack> activeTrack;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003685
3686 // start recording
3687 while (!exitPending()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003688
Eric Laurenta553c252009-07-17 12:17:14 -07003689 processConfigEvents();
3690
3691 { // scope for mLock
3692 Mutex::Autolock _l(mLock);
3693 checkForNewParameters_l();
3694 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
3695 if (!mStandby) {
3696 mInput->standby();
3697 mStandby = true;
3698 }
3699
3700 if (exitPending()) break;
3701
3702 LOGV("RecordThread: loop stopping");
3703 // go to sleep
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003704 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07003705 LOGV("RecordThread: loop starting");
3706 continue;
3707 }
3708 if (mActiveTrack != 0) {
3709 if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08003710 if (!mStandby) {
3711 mInput->standby();
3712 mStandby = true;
3713 }
Eric Laurenta553c252009-07-17 12:17:14 -07003714 mActiveTrack.clear();
3715 mStartStopCond.broadcast();
3716 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
Eric Laurenta553c252009-07-17 12:17:14 -07003717 if (mReqChannelCount != mActiveTrack->channelCount()) {
3718 mActiveTrack.clear();
Eric Laurent9cc489a22009-12-05 05:20:01 -08003719 mStartStopCond.broadcast();
3720 } else if (mBytesRead != 0) {
3721 // record start succeeds only if first read from audio input
3722 // succeeds
3723 if (mBytesRead > 0) {
3724 mActiveTrack->mState = TrackBase::ACTIVE;
3725 } else {
3726 mActiveTrack.clear();
3727 }
3728 mStartStopCond.broadcast();
Eric Laurenta553c252009-07-17 12:17:14 -07003729 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08003730 mStandby = false;
Eric Laurenta553c252009-07-17 12:17:14 -07003731 }
Eric Laurenta553c252009-07-17 12:17:14 -07003732 }
3733 }
3734
3735 if (mActiveTrack != 0) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08003736 if (mActiveTrack->mState != TrackBase::ACTIVE &&
3737 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent49f02be2009-11-19 09:00:56 -08003738 usleep(5000);
3739 continue;
3740 }
Eric Laurenta553c252009-07-17 12:17:14 -07003741 buffer.frameCount = mFrameCount;
3742 if (LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
3743 size_t framesOut = buffer.frameCount;
3744 if (mResampler == 0) {
3745 // no resampling
3746 while (framesOut) {
3747 size_t framesIn = mFrameCount - mRsmpInIndex;
3748 if (framesIn) {
3749 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
3750 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
3751 if (framesIn > framesOut)
3752 framesIn = framesOut;
3753 mRsmpInIndex += framesIn;
3754 framesOut -= framesIn;
Eric Laurentb0a01472010-05-14 05:45:46 -07003755 if ((int)mChannelCount == mReqChannelCount ||
Eric Laurenta553c252009-07-17 12:17:14 -07003756 mFormat != AudioSystem::PCM_16_BIT) {
3757 memcpy(dst, src, framesIn * mFrameSize);
3758 } else {
3759 int16_t *src16 = (int16_t *)src;
3760 int16_t *dst16 = (int16_t *)dst;
3761 if (mChannelCount == 1) {
3762 while (framesIn--) {
3763 *dst16++ = *src16;
3764 *dst16++ = *src16++;
3765 }
3766 } else {
3767 while (framesIn--) {
3768 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
3769 src16 += 2;
3770 }
3771 }
3772 }
3773 }
3774 if (framesOut && mFrameCount == mRsmpInIndex) {
Eric Laurenta553c252009-07-17 12:17:14 -07003775 if (framesOut == mFrameCount &&
Eric Laurentb0a01472010-05-14 05:45:46 -07003776 ((int)mChannelCount == mReqChannelCount || mFormat != AudioSystem::PCM_16_BIT)) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08003777 mBytesRead = mInput->read(buffer.raw, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07003778 framesOut = 0;
3779 } else {
Eric Laurent9cc489a22009-12-05 05:20:01 -08003780 mBytesRead = mInput->read(mRsmpInBuffer, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07003781 mRsmpInIndex = 0;
3782 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08003783 if (mBytesRead < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003784 LOGE("Error reading audio input");
Eric Laurent9cc489a22009-12-05 05:20:01 -08003785 if (mActiveTrack->mState == TrackBase::ACTIVE) {
Eric Laurentba8811f2010-03-02 18:38:06 -08003786 // Force input into standby so that it tries to
3787 // recover at next read attempt
3788 mInput->standby();
3789 usleep(5000);
Eric Laurent9cc489a22009-12-05 05:20:01 -08003790 }
Eric Laurenta553c252009-07-17 12:17:14 -07003791 mRsmpInIndex = mFrameCount;
3792 framesOut = 0;
3793 buffer.frameCount = 0;
3794 }
3795 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003796 }
3797 } else {
Eric Laurenta553c252009-07-17 12:17:14 -07003798 // resampling
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003799
Eric Laurenta553c252009-07-17 12:17:14 -07003800 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
3801 // alter output frame count as if we were expecting stereo samples
3802 if (mChannelCount == 1 && mReqChannelCount == 1) {
3803 framesOut >>= 1;
3804 }
3805 mResampler->resample(mRsmpOutBuffer, framesOut, this);
3806 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
3807 // are 32 bit aligned which should be always true.
3808 if (mChannelCount == 2 && mReqChannelCount == 1) {
3809 AudioMixer::ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
3810 // the resampler always outputs stereo samples: do post stereo to mono conversion
3811 int16_t *src = (int16_t *)mRsmpOutBuffer;
3812 int16_t *dst = buffer.i16;
3813 while (framesOut--) {
3814 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
3815 src += 2;
3816 }
3817 } else {
3818 AudioMixer::ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
3819 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003820
Eric Laurenta553c252009-07-17 12:17:14 -07003821 }
3822 mActiveTrack->releaseBuffer(&buffer);
3823 mActiveTrack->overflow();
3824 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003825 // client isn't retrieving buffers fast enough
3826 else {
Eric Laurenta553c252009-07-17 12:17:14 -07003827 if (!mActiveTrack->setOverflow())
3828 LOGW("RecordThread: buffer overflow");
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003829 // Release the processor for a while before asking for a new buffer.
3830 // This will give the application more chance to read from the buffer and
3831 // clear the overflow.
3832 usleep(5000);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003833 }
3834 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003835 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003836
Eric Laurenta553c252009-07-17 12:17:14 -07003837 if (!mStandby) {
3838 mInput->standby();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003839 }
Eric Laurenta553c252009-07-17 12:17:14 -07003840 mActiveTrack.clear();
3841
Eric Laurent49f02be2009-11-19 09:00:56 -08003842 mStartStopCond.broadcast();
3843
Eric Laurenta553c252009-07-17 12:17:14 -07003844 LOGV("RecordThread %p exiting", this);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003845 return false;
3846}
3847
Eric Laurenta553c252009-07-17 12:17:14 -07003848status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003849{
Eric Laurenta553c252009-07-17 12:17:14 -07003850 LOGV("RecordThread::start");
Eric Laurent49f02be2009-11-19 09:00:56 -08003851 sp <ThreadBase> strongMe = this;
3852 status_t status = NO_ERROR;
3853 {
3854 AutoMutex lock(&mLock);
3855 if (mActiveTrack != 0) {
3856 if (recordTrack != mActiveTrack.get()) {
3857 status = -EBUSY;
3858 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08003859 mActiveTrack->mState = TrackBase::ACTIVE;
Eric Laurent49f02be2009-11-19 09:00:56 -08003860 }
3861 return status;
3862 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003863
Eric Laurent49f02be2009-11-19 09:00:56 -08003864 recordTrack->mState = TrackBase::IDLE;
3865 mActiveTrack = recordTrack;
3866 mLock.unlock();
3867 status_t status = AudioSystem::startInput(mId);
3868 mLock.lock();
3869 if (status != NO_ERROR) {
3870 mActiveTrack.clear();
3871 return status;
3872 }
3873 mActiveTrack->mState = TrackBase::RESUMING;
Eric Laurent9cc489a22009-12-05 05:20:01 -08003874 mRsmpInIndex = mFrameCount;
3875 mBytesRead = 0;
Eric Laurent49f02be2009-11-19 09:00:56 -08003876 // signal thread to start
3877 LOGV("Signal record thread");
3878 mWaitWorkCV.signal();
3879 // do not wait for mStartStopCond if exiting
3880 if (mExiting) {
3881 mActiveTrack.clear();
3882 status = INVALID_OPERATION;
3883 goto startError;
3884 }
3885 mStartStopCond.wait(mLock);
3886 if (mActiveTrack == 0) {
3887 LOGV("Record failed to start");
3888 status = BAD_VALUE;
3889 goto startError;
3890 }
Eric Laurenta553c252009-07-17 12:17:14 -07003891 LOGV("Record started OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08003892 return status;
Eric Laurenta553c252009-07-17 12:17:14 -07003893 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003894startError:
3895 AudioSystem::stopInput(mId);
3896 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003897}
3898
Eric Laurenta553c252009-07-17 12:17:14 -07003899void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
3900 LOGV("RecordThread::stop");
Eric Laurent49f02be2009-11-19 09:00:56 -08003901 sp <ThreadBase> strongMe = this;
3902 {
3903 AutoMutex lock(&mLock);
3904 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
3905 mActiveTrack->mState = TrackBase::PAUSING;
3906 // do not wait for mStartStopCond if exiting
3907 if (mExiting) {
3908 return;
3909 }
3910 mStartStopCond.wait(mLock);
3911 // if we have been restarted, recordTrack == mActiveTrack.get() here
3912 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
3913 mLock.unlock();
3914 AudioSystem::stopInput(mId);
3915 mLock.lock();
Eric Laurent9cc489a22009-12-05 05:20:01 -08003916 LOGV("Record stopped OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08003917 }
3918 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003919 }
3920}
3921
Eric Laurenta553c252009-07-17 12:17:14 -07003922status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003923{
3924 const size_t SIZE = 256;
3925 char buffer[SIZE];
3926 String8 result;
3927 pid_t pid = 0;
3928
Eric Laurent3fdb1262009-11-07 00:01:32 -08003929 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
3930 result.append(buffer);
3931
3932 if (mActiveTrack != 0) {
3933 result.append("Active Track:\n");
Eric Laurent65b65452010-06-01 23:49:17 -07003934 result.append(" Clien Fmt Chn Session Buf S SRate Serv User\n");
Eric Laurent3fdb1262009-11-07 00:01:32 -08003935 mActiveTrack->dump(buffer, SIZE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003936 result.append(buffer);
Eric Laurent3fdb1262009-11-07 00:01:32 -08003937
3938 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
3939 result.append(buffer);
3940 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
3941 result.append(buffer);
3942 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != 0));
3943 result.append(buffer);
3944 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
3945 result.append(buffer);
3946 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
3947 result.append(buffer);
3948
3949
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003950 } else {
3951 result.append("No record client\n");
3952 }
3953 write(fd, result.string(), result.size());
Eric Laurent3fdb1262009-11-07 00:01:32 -08003954
3955 dumpBase(fd, args);
3956
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003957 return NO_ERROR;
3958}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003959
Eric Laurenta553c252009-07-17 12:17:14 -07003960status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3961{
3962 size_t framesReq = buffer->frameCount;
3963 size_t framesReady = mFrameCount - mRsmpInIndex;
3964 int channelCount;
3965
3966 if (framesReady == 0) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08003967 mBytesRead = mInput->read(mRsmpInBuffer, mInputBytes);
3968 if (mBytesRead < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003969 LOGE("RecordThread::getNextBuffer() Error reading audio input");
Eric Laurent9cc489a22009-12-05 05:20:01 -08003970 if (mActiveTrack->mState == TrackBase::ACTIVE) {
Eric Laurentba8811f2010-03-02 18:38:06 -08003971 // Force input into standby so that it tries to
3972 // recover at next read attempt
3973 mInput->standby();
3974 usleep(5000);
Eric Laurent9cc489a22009-12-05 05:20:01 -08003975 }
Eric Laurenta553c252009-07-17 12:17:14 -07003976 buffer->raw = 0;
3977 buffer->frameCount = 0;
3978 return NOT_ENOUGH_DATA;
3979 }
3980 mRsmpInIndex = 0;
3981 framesReady = mFrameCount;
3982 }
3983
3984 if (framesReq > framesReady) {
3985 framesReq = framesReady;
3986 }
3987
3988 if (mChannelCount == 1 && mReqChannelCount == 2) {
3989 channelCount = 1;
3990 } else {
3991 channelCount = 2;
3992 }
3993 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
3994 buffer->frameCount = framesReq;
3995 return NO_ERROR;
3996}
3997
3998void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3999{
4000 mRsmpInIndex += buffer->frameCount;
4001 buffer->frameCount = 0;
4002}
4003
4004bool AudioFlinger::RecordThread::checkForNewParameters_l()
4005{
4006 bool reconfig = false;
4007
Eric Laurent8fce46a2009-08-04 09:45:33 -07004008 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07004009 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07004010 String8 keyValuePair = mNewParameters[0];
4011 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07004012 int value;
4013 int reqFormat = mFormat;
4014 int reqSamplingRate = mReqSampleRate;
4015 int reqChannelCount = mReqChannelCount;
Eric Laurent8fce46a2009-08-04 09:45:33 -07004016
Eric Laurenta553c252009-07-17 12:17:14 -07004017 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4018 reqSamplingRate = value;
4019 reconfig = true;
4020 }
4021 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
4022 reqFormat = value;
4023 reconfig = true;
4024 }
4025 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
4026 reqChannelCount = AudioSystem::popCount(value);
4027 reconfig = true;
4028 }
4029 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4030 // do not accept frame count changes if tracks are open as the track buffer
4031 // size depends on frame count and correct behavior would not be garantied
4032 // if frame count is changed after track creation
4033 if (mActiveTrack != 0) {
4034 status = INVALID_OPERATION;
4035 } else {
4036 reconfig = true;
4037 }
4038 }
4039 if (status == NO_ERROR) {
Eric Laurent8fce46a2009-08-04 09:45:33 -07004040 status = mInput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07004041 if (status == INVALID_OPERATION) {
4042 mInput->standby();
Eric Laurent8fce46a2009-08-04 09:45:33 -07004043 status = mInput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07004044 }
4045 if (reconfig) {
4046 if (status == BAD_VALUE &&
4047 reqFormat == mInput->format() && reqFormat == AudioSystem::PCM_16_BIT &&
4048 ((int)mInput->sampleRate() <= 2 * reqSamplingRate) &&
4049 (AudioSystem::popCount(mInput->channels()) < 3) && (reqChannelCount < 3)) {
4050 status = NO_ERROR;
4051 }
4052 if (status == NO_ERROR) {
4053 readInputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07004054 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07004055 }
4056 }
4057 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08004058
4059 mNewParameters.removeAt(0);
4060
Eric Laurenta553c252009-07-17 12:17:14 -07004061 mParamStatus = status;
4062 mParamCond.signal();
Eric Laurent8fce46a2009-08-04 09:45:33 -07004063 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07004064 }
4065 return reconfig;
4066}
4067
4068String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4069{
4070 return mInput->getParameters(keys);
4071}
4072
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004073void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
Eric Laurenta553c252009-07-17 12:17:14 -07004074 AudioSystem::OutputDescriptor desc;
4075 void *param2 = 0;
4076
4077 switch (event) {
4078 case AudioSystem::INPUT_OPENED:
4079 case AudioSystem::INPUT_CONFIG_CHANGED:
Eric Laurentb0a01472010-05-14 05:45:46 -07004080 desc.channels = mChannels;
Eric Laurenta553c252009-07-17 12:17:14 -07004081 desc.samplingRate = mSampleRate;
4082 desc.format = mFormat;
4083 desc.frameCount = mFrameCount;
4084 desc.latency = 0;
4085 param2 = &desc;
4086 break;
4087
4088 case AudioSystem::INPUT_CLOSED:
4089 default:
4090 break;
4091 }
Eric Laurent49f02be2009-11-19 09:00:56 -08004092 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurenta553c252009-07-17 12:17:14 -07004093}
4094
4095void AudioFlinger::RecordThread::readInputParameters()
4096{
4097 if (mRsmpInBuffer) delete mRsmpInBuffer;
4098 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
4099 if (mResampler) delete mResampler;
4100 mResampler = 0;
4101
4102 mSampleRate = mInput->sampleRate();
Eric Laurentb0a01472010-05-14 05:45:46 -07004103 mChannels = mInput->channels();
4104 mChannelCount = (uint16_t)AudioSystem::popCount(mChannels);
Eric Laurenta553c252009-07-17 12:17:14 -07004105 mFormat = mInput->format();
Eric Laurentb0a01472010-05-14 05:45:46 -07004106 mFrameSize = (uint16_t)mInput->frameSize();
Eric Laurenta553c252009-07-17 12:17:14 -07004107 mInputBytes = mInput->bufferSize();
4108 mFrameCount = mInputBytes / mFrameSize;
4109 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4110
4111 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4112 {
4113 int channelCount;
4114 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4115 // stereo to mono post process as the resampler always outputs stereo.
4116 if (mChannelCount == 1 && mReqChannelCount == 2) {
4117 channelCount = 1;
4118 } else {
4119 channelCount = 2;
4120 }
4121 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4122 mResampler->setSampleRate(mSampleRate);
4123 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4124 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4125
4126 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4127 if (mChannelCount == 1 && mReqChannelCount == 1) {
4128 mFrameCount >>= 1;
4129 }
4130
4131 }
4132 mRsmpInIndex = mFrameCount;
4133}
4134
Eric Laurent47d0a922010-02-26 02:47:27 -08004135unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4136{
4137 return mInput->getInputFramesLost();
4138}
4139
Eric Laurenta553c252009-07-17 12:17:14 -07004140// ----------------------------------------------------------------------------
4141
Eric Laurentddb78e72009-07-28 08:44:33 -07004142int AudioFlinger::openOutput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07004143 uint32_t *pSamplingRate,
4144 uint32_t *pFormat,
4145 uint32_t *pChannels,
4146 uint32_t *pLatencyMs,
4147 uint32_t flags)
4148{
4149 status_t status;
4150 PlaybackThread *thread = NULL;
4151 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4152 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4153 uint32_t format = pFormat ? *pFormat : 0;
4154 uint32_t channels = pChannels ? *pChannels : 0;
4155 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
4156
4157 LOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
4158 pDevices ? *pDevices : 0,
4159 samplingRate,
4160 format,
4161 channels,
4162 flags);
4163
4164 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004165 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004166 }
4167 Mutex::Autolock _l(mLock);
4168
4169 AudioStreamOut *output = mAudioHardware->openOutputStream(*pDevices,
4170 (int *)&format,
4171 &channels,
4172 &samplingRate,
4173 &status);
4174 LOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
4175 output,
4176 samplingRate,
4177 format,
4178 channels,
4179 status);
4180
4181 mHardwareStatus = AUDIO_HW_IDLE;
4182 if (output != 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07004183 int id = nextUniqueId();
Eric Laurenta553c252009-07-17 12:17:14 -07004184 if ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) ||
4185 (format != AudioSystem::PCM_16_BIT) ||
4186 (channels != AudioSystem::CHANNEL_OUT_STEREO)) {
Eric Laurent65b65452010-06-01 23:49:17 -07004187 thread = new DirectOutputThread(this, output, id, *pDevices);
4188 LOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004189 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07004190 thread = new MixerThread(this, output, id, *pDevices);
4191 LOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Glenn Kasten871c16c2010-03-05 12:18:01 -08004192
4193#ifdef LVMX
4194 unsigned bitsPerSample =
4195 (format == AudioSystem::PCM_16_BIT) ? 16 :
4196 ((format == AudioSystem::PCM_8_BIT) ? 8 : 0);
4197 unsigned channelCount = (channels == AudioSystem::CHANNEL_OUT_STEREO) ? 2 : 1;
4198 int audioOutputType = LifeVibes::threadIdToAudioOutputType(thread->id());
4199
4200 LifeVibes::init_aot(audioOutputType, samplingRate, bitsPerSample, channelCount);
4201 LifeVibes::setDevice(audioOutputType, *pDevices);
4202#endif
4203
Eric Laurenta553c252009-07-17 12:17:14 -07004204 }
Eric Laurent65b65452010-06-01 23:49:17 -07004205 mPlaybackThreads.add(id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004206
4207 if (pSamplingRate) *pSamplingRate = samplingRate;
4208 if (pFormat) *pFormat = format;
4209 if (pChannels) *pChannels = channels;
4210 if (pLatencyMs) *pLatencyMs = thread->latency();
Eric Laurent9cc489a22009-12-05 05:20:01 -08004211
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004212 // notify client processes of the new output creation
4213 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004214 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004215 }
4216
Eric Laurent9cc489a22009-12-05 05:20:01 -08004217 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004218}
4219
Eric Laurentddb78e72009-07-28 08:44:33 -07004220int AudioFlinger::openDuplicateOutput(int output1, int output2)
Eric Laurenta553c252009-07-17 12:17:14 -07004221{
4222 Mutex::Autolock _l(mLock);
Eric Laurentddb78e72009-07-28 08:44:33 -07004223 MixerThread *thread1 = checkMixerThread_l(output1);
4224 MixerThread *thread2 = checkMixerThread_l(output2);
Eric Laurenta553c252009-07-17 12:17:14 -07004225
Eric Laurentddb78e72009-07-28 08:44:33 -07004226 if (thread1 == NULL || thread2 == NULL) {
4227 LOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
4228 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004229 }
4230
Eric Laurent65b65452010-06-01 23:49:17 -07004231 int id = nextUniqueId();
4232 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
Eric Laurentddb78e72009-07-28 08:44:33 -07004233 thread->addOutputTrack(thread2);
Eric Laurent65b65452010-06-01 23:49:17 -07004234 mPlaybackThreads.add(id, thread);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004235 // notify client processes of the new output creation
4236 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004237 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004238}
4239
Eric Laurentddb78e72009-07-28 08:44:33 -07004240status_t AudioFlinger::closeOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004241{
Eric Laurent49018a52009-08-04 08:37:05 -07004242 // keep strong reference on the playback thread so that
4243 // it is not destroyed while exit() is executed
4244 sp <PlaybackThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07004245 {
4246 Mutex::Autolock _l(mLock);
4247 thread = checkPlaybackThread_l(output);
4248 if (thread == NULL) {
4249 return BAD_VALUE;
4250 }
4251
Eric Laurentddb78e72009-07-28 08:44:33 -07004252 LOGV("closeOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004253
4254 if (thread->type() == PlaybackThread::MIXER) {
4255 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004256 if (mPlaybackThreads.valueAt(i)->type() == PlaybackThread::DUPLICATING) {
4257 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Eric Laurent49018a52009-08-04 08:37:05 -07004258 dupThread->removeOutputTrack((MixerThread *)thread.get());
Eric Laurenta553c252009-07-17 12:17:14 -07004259 }
4260 }
4261 }
Eric Laurent296a0ec2009-09-15 07:10:12 -07004262 void *param2 = 0;
Eric Laurent49f02be2009-11-19 09:00:56 -08004263 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
Eric Laurentddb78e72009-07-28 08:44:33 -07004264 mPlaybackThreads.removeItem(output);
Eric Laurenta553c252009-07-17 12:17:14 -07004265 }
4266 thread->exit();
4267
Eric Laurent49018a52009-08-04 08:37:05 -07004268 if (thread->type() != PlaybackThread::DUPLICATING) {
4269 mAudioHardware->closeOutputStream(thread->getOutput());
4270 }
Eric Laurenta553c252009-07-17 12:17:14 -07004271 return NO_ERROR;
4272}
4273
Eric Laurentddb78e72009-07-28 08:44:33 -07004274status_t AudioFlinger::suspendOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004275{
4276 Mutex::Autolock _l(mLock);
4277 PlaybackThread *thread = checkPlaybackThread_l(output);
4278
4279 if (thread == NULL) {
4280 return BAD_VALUE;
4281 }
4282
Eric Laurentddb78e72009-07-28 08:44:33 -07004283 LOGV("suspendOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004284 thread->suspend();
4285
4286 return NO_ERROR;
4287}
4288
Eric Laurentddb78e72009-07-28 08:44:33 -07004289status_t AudioFlinger::restoreOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004290{
4291 Mutex::Autolock _l(mLock);
4292 PlaybackThread *thread = checkPlaybackThread_l(output);
4293
4294 if (thread == NULL) {
4295 return BAD_VALUE;
4296 }
4297
Eric Laurentddb78e72009-07-28 08:44:33 -07004298 LOGV("restoreOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004299
4300 thread->restore();
4301
4302 return NO_ERROR;
4303}
4304
Eric Laurentddb78e72009-07-28 08:44:33 -07004305int AudioFlinger::openInput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07004306 uint32_t *pSamplingRate,
4307 uint32_t *pFormat,
4308 uint32_t *pChannels,
4309 uint32_t acoustics)
4310{
4311 status_t status;
4312 RecordThread *thread = NULL;
4313 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4314 uint32_t format = pFormat ? *pFormat : 0;
4315 uint32_t channels = pChannels ? *pChannels : 0;
4316 uint32_t reqSamplingRate = samplingRate;
4317 uint32_t reqFormat = format;
4318 uint32_t reqChannels = channels;
4319
4320 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004321 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004322 }
4323 Mutex::Autolock _l(mLock);
4324
4325 AudioStreamIn *input = mAudioHardware->openInputStream(*pDevices,
4326 (int *)&format,
4327 &channels,
4328 &samplingRate,
4329 &status,
4330 (AudioSystem::audio_in_acoustics)acoustics);
4331 LOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
4332 input,
4333 samplingRate,
4334 format,
4335 channels,
4336 acoustics,
4337 status);
4338
4339 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
4340 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
4341 // or stereo to mono conversions on 16 bit PCM inputs.
4342 if (input == 0 && status == BAD_VALUE &&
4343 reqFormat == format && format == AudioSystem::PCM_16_BIT &&
4344 (samplingRate <= 2 * reqSamplingRate) &&
4345 (AudioSystem::popCount(channels) < 3) && (AudioSystem::popCount(reqChannels) < 3)) {
4346 LOGV("openInput() reopening with proposed sampling rate and channels");
4347 input = mAudioHardware->openInputStream(*pDevices,
4348 (int *)&format,
4349 &channels,
4350 &samplingRate,
4351 &status,
4352 (AudioSystem::audio_in_acoustics)acoustics);
4353 }
4354
4355 if (input != 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07004356 int id = nextUniqueId();
Eric Laurenta553c252009-07-17 12:17:14 -07004357 // Start record thread
Eric Laurent65b65452010-06-01 23:49:17 -07004358 thread = new RecordThread(this, input, reqSamplingRate, reqChannels, id);
4359 mRecordThreads.add(id, thread);
4360 LOGV("openInput() created record thread: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004361 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
4362 if (pFormat) *pFormat = format;
4363 if (pChannels) *pChannels = reqChannels;
4364
4365 input->standby();
Eric Laurent9cc489a22009-12-05 05:20:01 -08004366
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004367 // notify client processes of the new input creation
4368 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004369 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004370 }
4371
Eric Laurent9cc489a22009-12-05 05:20:01 -08004372 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004373}
4374
Eric Laurentddb78e72009-07-28 08:44:33 -07004375status_t AudioFlinger::closeInput(int input)
Eric Laurenta553c252009-07-17 12:17:14 -07004376{
Eric Laurent49018a52009-08-04 08:37:05 -07004377 // keep strong reference on the record thread so that
4378 // it is not destroyed while exit() is executed
4379 sp <RecordThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07004380 {
4381 Mutex::Autolock _l(mLock);
4382 thread = checkRecordThread_l(input);
4383 if (thread == NULL) {
4384 return BAD_VALUE;
4385 }
4386
Eric Laurentddb78e72009-07-28 08:44:33 -07004387 LOGV("closeInput() %d", input);
Eric Laurent296a0ec2009-09-15 07:10:12 -07004388 void *param2 = 0;
Eric Laurent49f02be2009-11-19 09:00:56 -08004389 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
Eric Laurentddb78e72009-07-28 08:44:33 -07004390 mRecordThreads.removeItem(input);
Eric Laurenta553c252009-07-17 12:17:14 -07004391 }
4392 thread->exit();
4393
Eric Laurent49018a52009-08-04 08:37:05 -07004394 mAudioHardware->closeInputStream(thread->getInput());
4395
Eric Laurenta553c252009-07-17 12:17:14 -07004396 return NO_ERROR;
4397}
4398
Eric Laurentddb78e72009-07-28 08:44:33 -07004399status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004400{
4401 Mutex::Autolock _l(mLock);
4402 MixerThread *dstThread = checkMixerThread_l(output);
4403 if (dstThread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004404 LOGW("setStreamOutput() bad output id %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004405 return BAD_VALUE;
4406 }
4407
Eric Laurentddb78e72009-07-28 08:44:33 -07004408 LOGV("setStreamOutput() stream %d to output %d", stream, output);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004409 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
Eric Laurenta553c252009-07-17 12:17:14 -07004410
4411 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004412 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurenta553c252009-07-17 12:17:14 -07004413 if (thread != dstThread &&
4414 thread->type() != PlaybackThread::DIRECT) {
4415 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004416 srcThread->invalidateTracks(stream);
Eric Laurenta553c252009-07-17 12:17:14 -07004417 }
4418 }
Eric Laurentd069f322009-09-01 05:56:26 -07004419
Eric Laurenta553c252009-07-17 12:17:14 -07004420 return NO_ERROR;
4421}
4422
Eric Laurent65b65452010-06-01 23:49:17 -07004423
4424int AudioFlinger::newAudioSessionId()
4425{
4426 return nextUniqueId();
4427}
4428
Eric Laurenta553c252009-07-17 12:17:14 -07004429// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07004430AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
Eric Laurenta553c252009-07-17 12:17:14 -07004431{
4432 PlaybackThread *thread = NULL;
Eric Laurentddb78e72009-07-28 08:44:33 -07004433 if (mPlaybackThreads.indexOfKey(output) >= 0) {
4434 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
Eric Laurenta553c252009-07-17 12:17:14 -07004435 }
Eric Laurenta553c252009-07-17 12:17:14 -07004436 return thread;
4437}
4438
4439// checkMixerThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07004440AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
Eric Laurenta553c252009-07-17 12:17:14 -07004441{
4442 PlaybackThread *thread = checkPlaybackThread_l(output);
4443 if (thread != NULL) {
4444 if (thread->type() == PlaybackThread::DIRECT) {
4445 thread = NULL;
4446 }
4447 }
4448 return (MixerThread *)thread;
4449}
4450
4451// checkRecordThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07004452AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
Eric Laurenta553c252009-07-17 12:17:14 -07004453{
4454 RecordThread *thread = NULL;
Eric Laurentddb78e72009-07-28 08:44:33 -07004455 if (mRecordThreads.indexOfKey(input) >= 0) {
4456 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
Eric Laurenta553c252009-07-17 12:17:14 -07004457 }
Eric Laurenta553c252009-07-17 12:17:14 -07004458 return thread;
4459}
4460
Eric Laurent65b65452010-06-01 23:49:17 -07004461int AudioFlinger::nextUniqueId()
4462{
4463 return android_atomic_inc(&mNextUniqueId);
4464}
4465
4466// ----------------------------------------------------------------------------
4467// Effect management
4468// ----------------------------------------------------------------------------
4469
4470
4471status_t AudioFlinger::loadEffectLibrary(const char *libPath, int *handle)
4472{
4473 Mutex::Autolock _l(mLock);
4474 return EffectLoadLibrary(libPath, handle);
4475}
4476
4477status_t AudioFlinger::unloadEffectLibrary(int handle)
4478{
4479 Mutex::Autolock _l(mLock);
4480 return EffectUnloadLibrary(handle);
4481}
4482
4483status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects)
4484{
4485 Mutex::Autolock _l(mLock);
4486 return EffectQueryNumberEffects(numEffects);
4487}
4488
Eric Laurent53334cd2010-06-23 17:38:20 -07004489status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor)
Eric Laurent65b65452010-06-01 23:49:17 -07004490{
4491 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07004492 return EffectQueryEffect(index, descriptor);
Eric Laurent65b65452010-06-01 23:49:17 -07004493}
4494
4495status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid, effect_descriptor_t *descriptor)
4496{
4497 Mutex::Autolock _l(mLock);
4498 return EffectGetDescriptor(pUuid, descriptor);
4499}
4500
4501sp<IEffect> AudioFlinger::createEffect(pid_t pid,
4502 effect_descriptor_t *pDesc,
4503 const sp<IEffectClient>& effectClient,
4504 int32_t priority,
4505 int output,
4506 int sessionId,
4507 status_t *status,
4508 int *id,
4509 int *enabled)
4510{
4511 status_t lStatus = NO_ERROR;
4512 sp<EffectHandle> handle;
4513 effect_interface_t itfe;
4514 effect_descriptor_t desc;
4515 sp<Client> client;
4516 wp<Client> wclient;
4517
4518 LOGV("createEffect pid %d, client %p, priority %d, sessionId %d, output %d", pid, effectClient.get(), priority, sessionId, output);
4519
4520 if (pDesc == NULL) {
4521 lStatus = BAD_VALUE;
4522 goto Exit;
4523 }
4524
4525 {
4526 Mutex::Autolock _l(mLock);
4527
4528 if (!EffectIsNullUuid(&pDesc->uuid)) {
4529 // if uuid is specified, request effect descriptor
4530 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
4531 if (lStatus < 0) {
4532 LOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
4533 goto Exit;
4534 }
4535 } else {
4536 // if uuid is not specified, look for an available implementation
4537 // of the required type in effect factory
4538 if (EffectIsNullUuid(&pDesc->type)) {
4539 LOGW("createEffect() no effect type");
4540 lStatus = BAD_VALUE;
4541 goto Exit;
4542 }
4543 uint32_t numEffects = 0;
4544 effect_descriptor_t d;
4545 bool found = false;
4546
4547 lStatus = EffectQueryNumberEffects(&numEffects);
4548 if (lStatus < 0) {
4549 LOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
4550 goto Exit;
4551 }
Eric Laurent53334cd2010-06-23 17:38:20 -07004552 for (uint32_t i = 0; i < numEffects; i++) {
4553 lStatus = EffectQueryEffect(i, &desc);
Eric Laurent65b65452010-06-01 23:49:17 -07004554 if (lStatus < 0) {
Eric Laurent53334cd2010-06-23 17:38:20 -07004555 LOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07004556 continue;
4557 }
4558 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
4559 // If matching type found save effect descriptor. If the session is
4560 // 0 and the effect is not auxiliary, continue enumeration in case
4561 // an auxiliary version of this effect type is available
4562 found = true;
4563 memcpy(&d, &desc, sizeof(effect_descriptor_t));
4564 if (sessionId != 0 ||
4565 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
4566 break;
4567 }
4568 }
4569 }
4570 if (!found) {
4571 lStatus = BAD_VALUE;
4572 LOGW("createEffect() effect not found");
4573 goto Exit;
4574 }
4575 // For same effect type, chose auxiliary version over insert version if
4576 // connect to output mix (Compliance to OpenSL ES)
4577 if (sessionId == 0 &&
4578 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
4579 memcpy(&desc, &d, sizeof(effect_descriptor_t));
4580 }
4581 }
4582
4583 // Do not allow auxiliary effects on a session different from 0 (output mix)
4584 if (sessionId != 0 &&
4585 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
4586 lStatus = INVALID_OPERATION;
4587 goto Exit;
4588 }
4589
Eric Laurent53334cd2010-06-23 17:38:20 -07004590 // Session -1 is reserved for output stage effects that can only be created
4591 // by audio policy manager (running in same process)
4592 if (sessionId == -1 && getpid() != IPCThreadState::self()->getCallingPid()) {
4593 lStatus = INVALID_OPERATION;
4594 goto Exit;
4595 }
4596
Eric Laurent65b65452010-06-01 23:49:17 -07004597 // return effect descriptor
4598 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
4599
4600 // If output is not specified try to find a matching audio session ID in one of the
4601 // output threads.
4602 // TODO: allow attachment of effect to inputs
4603 if (output == 0) {
Eric Laurent53334cd2010-06-23 17:38:20 -07004604 if (sessionId <= 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07004605 // default to first output
4606 // TODO: define criteria to choose output when not specified. Or
4607 // receive output from audio policy manager
4608 if (mPlaybackThreads.size() != 0) {
4609 output = mPlaybackThreads.keyAt(0);
4610 }
4611 } else {
4612 // look for the thread where the specified audio session is present
4613 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
4614 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId)) {
4615 output = mPlaybackThreads.keyAt(i);
4616 break;
4617 }
4618 }
4619 }
4620 }
4621 PlaybackThread *thread = checkPlaybackThread_l(output);
4622 if (thread == NULL) {
4623 LOGE("unknown output thread");
4624 lStatus = BAD_VALUE;
4625 goto Exit;
4626 }
4627
4628 wclient = mClients.valueFor(pid);
4629
4630 if (wclient != NULL) {
4631 client = wclient.promote();
4632 } else {
4633 client = new Client(this, pid);
4634 mClients.add(pid, client);
4635 }
4636
4637 // create effect on selected output trhead
4638 handle = thread->createEffect_l(client, effectClient, priority, sessionId, &desc, enabled, &lStatus);
4639 if (handle != 0 && id != NULL) {
4640 *id = handle->id();
4641 }
4642 }
4643
4644Exit:
4645 if(status) {
4646 *status = lStatus;
4647 }
4648 return handle;
4649}
4650
Eric Laurent53334cd2010-06-23 17:38:20 -07004651status_t AudioFlinger::registerEffectResource_l(effect_descriptor_t *desc) {
4652 if (mTotalEffectsCpuLoad + desc->cpuLoad > MAX_EFFECTS_CPU_LOAD) {
4653 LOGW("registerEffectResource() CPU Load limit exceeded for Fx %s, CPU %f MIPS",
4654 desc->name, (float)desc->cpuLoad/10);
4655 return INVALID_OPERATION;
4656 }
4657 if (mTotalEffectsMemory + desc->memoryUsage > MAX_EFFECTS_MEMORY) {
4658 LOGW("registerEffectResource() memory limit exceeded for Fx %s, Memory %d KB",
4659 desc->name, desc->memoryUsage);
4660 return INVALID_OPERATION;
4661 }
4662 mTotalEffectsCpuLoad += desc->cpuLoad;
4663 mTotalEffectsMemory += desc->memoryUsage;
4664 LOGV("registerEffectResource_l() effect %s, CPU %d, memory %d",
4665 desc->name, desc->cpuLoad, desc->memoryUsage);
4666 LOGV(" total CPU %d, total memory %d", mTotalEffectsCpuLoad, mTotalEffectsMemory);
4667 return NO_ERROR;
4668}
4669
4670void AudioFlinger::unregisterEffectResource_l(effect_descriptor_t *desc) {
4671 mTotalEffectsCpuLoad -= desc->cpuLoad;
4672 mTotalEffectsMemory -= desc->memoryUsage;
4673 LOGV("unregisterEffectResource_l() effect %s, CPU %d, memory %d",
4674 desc->name, desc->cpuLoad, desc->memoryUsage);
4675 LOGV(" total CPU %d, total memory %d", mTotalEffectsCpuLoad, mTotalEffectsMemory);
4676}
4677
Eric Laurent65b65452010-06-01 23:49:17 -07004678// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
4679sp<AudioFlinger::EffectHandle> AudioFlinger::PlaybackThread::createEffect_l(
4680 const sp<AudioFlinger::Client>& client,
4681 const sp<IEffectClient>& effectClient,
4682 int32_t priority,
4683 int sessionId,
4684 effect_descriptor_t *desc,
4685 int *enabled,
4686 status_t *status
4687 )
4688{
4689 sp<EffectModule> effect;
4690 sp<EffectHandle> handle;
4691 status_t lStatus;
4692 sp<Track> track;
4693 sp<EffectChain> chain;
4694 bool effectCreated = false;
Eric Laurent53334cd2010-06-23 17:38:20 -07004695 bool effectRegistered = false;
Eric Laurent65b65452010-06-01 23:49:17 -07004696
4697 if (mOutput == 0) {
4698 LOGW("createEffect_l() Audio driver not initialized.");
4699 lStatus = NO_INIT;
4700 goto Exit;
4701 }
4702
4703 // Do not allow auxiliary effect on session other than 0
4704 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY &&
4705 sessionId != 0) {
4706 LOGW("createEffect_l() Cannot add auxiliary effect %s to session %d", desc->name, sessionId);
4707 lStatus = BAD_VALUE;
4708 goto Exit;
4709 }
4710
4711 // Do not allow effects with session ID 0 on direct output or duplicating threads
4712 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
4713 if (sessionId == 0 && mType != MIXER) {
4714 LOGW("createEffect_l() Cannot add auxiliary effect %s to session %d", desc->name, sessionId);
4715 lStatus = BAD_VALUE;
4716 goto Exit;
4717 }
4718
4719 LOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
4720
4721 { // scope for mLock
4722 Mutex::Autolock _l(mLock);
4723
4724 // check for existing effect chain with the requested audio session
4725 chain = getEffectChain_l(sessionId);
4726 if (chain == 0) {
4727 // create a new chain for this session
4728 LOGV("createEffect_l() new effect chain for session %d", sessionId);
4729 chain = new EffectChain(this, sessionId);
4730 addEffectChain_l(chain);
4731 } else {
4732 effect = chain->getEffectFromDesc(desc);
4733 }
4734
4735 LOGV("createEffect_l() got effect %p on chain %p", effect == 0 ? 0 : effect.get(), chain.get());
4736
4737 if (effect == 0) {
Eric Laurent53334cd2010-06-23 17:38:20 -07004738 // Check CPU and memory usage
4739 lStatus = mAudioFlinger->registerEffectResource_l(desc);
4740 if (lStatus != NO_ERROR) {
4741 goto Exit;
4742 }
4743 effectRegistered = true;
Eric Laurent65b65452010-06-01 23:49:17 -07004744 // create a new effect module if none present in the chain
Eric Laurent65b65452010-06-01 23:49:17 -07004745 effect = new EffectModule(this, chain, desc, mAudioFlinger->nextUniqueId(), sessionId);
4746 lStatus = effect->status();
4747 if (lStatus != NO_ERROR) {
4748 goto Exit;
4749 }
Eric Laurent65b65452010-06-01 23:49:17 -07004750 lStatus = chain->addEffect(effect);
4751 if (lStatus != NO_ERROR) {
4752 goto Exit;
4753 }
Eric Laurent53334cd2010-06-23 17:38:20 -07004754 effectCreated = true;
Eric Laurent65b65452010-06-01 23:49:17 -07004755
4756 effect->setDevice(mDevice);
Eric Laurent53334cd2010-06-23 17:38:20 -07004757 effect->setMode(mAudioFlinger->getMode());
Eric Laurent65b65452010-06-01 23:49:17 -07004758 }
4759 // create effect handle and connect it to effect module
4760 handle = new EffectHandle(effect, client, effectClient, priority);
4761 lStatus = effect->addHandle(handle);
4762 if (enabled) {
4763 *enabled = (int)effect->isEnabled();
4764 }
4765 }
4766
4767Exit:
4768 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent53334cd2010-06-23 17:38:20 -07004769 if (effectCreated) {
Eric Laurent65b65452010-06-01 23:49:17 -07004770 if (chain->removeEffect(effect) == 0) {
4771 removeEffectChain_l(chain);
4772 }
4773 }
Eric Laurent53334cd2010-06-23 17:38:20 -07004774 if (effectRegistered) {
4775 mAudioFlinger->unregisterEffectResource_l(desc);
4776 }
Eric Laurent65b65452010-06-01 23:49:17 -07004777 handle.clear();
4778 }
4779
4780 if(status) {
4781 *status = lStatus;
4782 }
4783 return handle;
4784}
4785
Eric Laurent53334cd2010-06-23 17:38:20 -07004786void AudioFlinger::PlaybackThread::disconnectEffect(const sp< EffectModule>& effect,
4787 const wp<EffectHandle>& handle) {
4788 effect_descriptor_t desc = effect->desc();
4789 Mutex::Autolock _l(mLock);
4790 // delete the effect module if removing last handle on it
4791 if (effect->removeHandle(handle) == 0) {
4792 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
4793 detachAuxEffect_l(effect->id());
4794 }
4795 sp<EffectChain> chain = effect->chain().promote();
4796 if (chain != 0) {
4797 // remove effect chain if remove last effect
4798 if (chain->removeEffect(effect) == 0) {
4799 removeEffectChain_l(chain);
4800 }
4801 }
4802 mLock.unlock();
4803 mAudioFlinger->mLock.lock();
4804 mAudioFlinger->unregisterEffectResource_l(&desc);
4805 mAudioFlinger->mLock.unlock();
4806 }
4807}
4808
Eric Laurent65b65452010-06-01 23:49:17 -07004809status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
4810{
4811 int session = chain->sessionId();
4812 int16_t *buffer = mMixBuffer;
Eric Laurent53334cd2010-06-23 17:38:20 -07004813 bool ownsBuffer = false;
Eric Laurent65b65452010-06-01 23:49:17 -07004814
4815 LOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Eric Laurent53334cd2010-06-23 17:38:20 -07004816 if (session > 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07004817 // Only one effect chain can be present in direct output thread and it uses
4818 // the mix buffer as input
4819 if (mType != DIRECT) {
4820 size_t numSamples = mFrameCount * mChannelCount;
4821 buffer = new int16_t[numSamples];
4822 memset(buffer, 0, numSamples * sizeof(int16_t));
4823 LOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
4824 ownsBuffer = true;
4825 }
Eric Laurent65b65452010-06-01 23:49:17 -07004826
Eric Laurent53334cd2010-06-23 17:38:20 -07004827 // Attach all tracks with same session ID to this chain.
4828 for (size_t i = 0; i < mTracks.size(); ++i) {
4829 sp<Track> track = mTracks[i];
4830 if (session == track->sessionId()) {
4831 LOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
4832 track->setMainBuffer(buffer);
4833 }
4834 }
4835
4836 // indicate all active tracks in the chain
4837 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
4838 sp<Track> track = mActiveTracks[i].promote();
4839 if (track == 0) continue;
4840 if (session == track->sessionId()) {
4841 LOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
4842 chain->startTrack();
4843 }
Eric Laurent65b65452010-06-01 23:49:17 -07004844 }
4845 }
4846
Eric Laurent53334cd2010-06-23 17:38:20 -07004847 chain->setInBuffer(buffer, ownsBuffer);
4848 chain->setOutBuffer(mMixBuffer);
4849 // Effect chain for session -1 is inserted at end of effect chains list
4850 // in order to be processed last as it contains output stage effects
4851 // Effect chain for session 0 is inserted before session -1 to be processed
4852 // after track specific effects and before output stage
4853 // Effect chain for session other than 0 is inserted at beginning of effect
4854 // chains list to be processed before output mix effects. Relative order between
4855 // sessions other than 0 is not important
4856 size_t size = mEffectChains.size();
4857 size_t i = 0;
4858 for (i = 0; i < size; i++) {
4859 if (mEffectChains[i]->sessionId() < session) break;
Eric Laurent65b65452010-06-01 23:49:17 -07004860 }
Eric Laurent53334cd2010-06-23 17:38:20 -07004861 mEffectChains.insertAt(chain, i);
Eric Laurent65b65452010-06-01 23:49:17 -07004862
4863 return NO_ERROR;
4864}
4865
4866size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
4867{
4868 int session = chain->sessionId();
4869
4870 LOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
4871
4872 for (size_t i = 0; i < mEffectChains.size(); i++) {
4873 if (chain == mEffectChains[i]) {
4874 mEffectChains.removeAt(i);
4875 // detach all tracks with same session ID from this chain
4876 for (size_t i = 0; i < mTracks.size(); ++i) {
4877 sp<Track> track = mTracks[i];
4878 if (session == track->sessionId()) {
4879 track->setMainBuffer(mMixBuffer);
4880 }
4881 }
4882 }
4883 }
4884 return mEffectChains.size();
4885}
4886
4887void AudioFlinger::PlaybackThread::lockEffectChains_l()
4888{
4889 for (size_t i = 0; i < mEffectChains.size(); i++) {
4890 mEffectChains[i]->lock();
4891 }
4892}
4893
4894void AudioFlinger::PlaybackThread::unlockEffectChains()
4895{
4896 Mutex::Autolock _l(mLock);
4897 for (size_t i = 0; i < mEffectChains.size(); i++) {
4898 mEffectChains[i]->unlock();
4899 }
4900}
4901
4902sp<AudioFlinger::EffectModule> AudioFlinger::PlaybackThread::getEffect_l(int sessionId, int effectId)
4903{
4904 sp<EffectModule> effect;
4905
4906 sp<EffectChain> chain = getEffectChain_l(sessionId);
4907 if (chain != 0) {
4908 effect = chain->getEffectFromId(effectId);
4909 }
4910 return effect;
4911}
4912
4913status_t AudioFlinger::PlaybackThread::attachAuxEffect(const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
4914{
4915 Mutex::Autolock _l(mLock);
4916 return attachAuxEffect_l(track, EffectId);
4917}
4918
4919status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
4920{
4921 status_t status = NO_ERROR;
4922
4923 if (EffectId == 0) {
4924 track->setAuxBuffer(0, NULL);
4925 } else {
4926 // Auxiliary effects are always in audio session 0
4927 sp<EffectModule> effect = getEffect_l(0, EffectId);
4928 if (effect != 0) {
4929 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
4930 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
4931 } else {
4932 status = INVALID_OPERATION;
4933 }
4934 } else {
4935 status = BAD_VALUE;
4936 }
4937 }
4938 return status;
4939}
4940
4941void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
4942{
4943 for (size_t i = 0; i < mTracks.size(); ++i) {
4944 sp<Track> track = mTracks[i];
4945 if (track->auxEffectId() == effectId) {
4946 attachAuxEffect_l(track, 0);
4947 }
4948 }
4949}
4950
4951// ----------------------------------------------------------------------------
4952// EffectModule implementation
4953// ----------------------------------------------------------------------------
4954
4955#undef LOG_TAG
4956#define LOG_TAG "AudioFlinger::EffectModule"
4957
4958AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
4959 const wp<AudioFlinger::EffectChain>& chain,
4960 effect_descriptor_t *desc,
4961 int id,
4962 int sessionId)
4963 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
4964 mStatus(NO_INIT), mState(IDLE)
4965{
4966 LOGV("Constructor %p", this);
4967 int lStatus;
4968 sp<ThreadBase> thread = mThread.promote();
4969 if (thread == 0) {
4970 return;
4971 }
4972 PlaybackThread *p = (PlaybackThread *)thread.get();
4973
4974 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
4975
4976 // create effect engine from effect factory
Eric Laurent53334cd2010-06-23 17:38:20 -07004977 mStatus = EffectCreate(&desc->uuid, sessionId, p->id(), &mEffectInterface);
4978
Eric Laurent65b65452010-06-01 23:49:17 -07004979 if (mStatus != NO_ERROR) {
4980 return;
4981 }
4982 lStatus = init();
4983 if (lStatus < 0) {
4984 mStatus = lStatus;
4985 goto Error;
4986 }
4987
4988 LOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
4989 return;
4990Error:
4991 EffectRelease(mEffectInterface);
4992 mEffectInterface = NULL;
4993 LOGV("Constructor Error %d", mStatus);
4994}
4995
4996AudioFlinger::EffectModule::~EffectModule()
4997{
4998 LOGV("Destructor %p", this);
4999 if (mEffectInterface != NULL) {
5000 // release effect engine
5001 EffectRelease(mEffectInterface);
5002 }
5003}
5004
5005status_t AudioFlinger::EffectModule::addHandle(sp<EffectHandle>& handle)
5006{
5007 status_t status;
5008
5009 Mutex::Autolock _l(mLock);
5010 // First handle in mHandles has highest priority and controls the effect module
5011 int priority = handle->priority();
5012 size_t size = mHandles.size();
5013 sp<EffectHandle> h;
5014 size_t i;
5015 for (i = 0; i < size; i++) {
5016 h = mHandles[i].promote();
5017 if (h == 0) continue;
5018 if (h->priority() <= priority) break;
5019 }
5020 // if inserted in first place, move effect control from previous owner to this handle
5021 if (i == 0) {
5022 if (h != 0) {
5023 h->setControl(false, true);
5024 }
5025 handle->setControl(true, false);
5026 status = NO_ERROR;
5027 } else {
5028 status = ALREADY_EXISTS;
5029 }
5030 mHandles.insertAt(handle, i);
5031 return status;
5032}
5033
5034size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
5035{
5036 Mutex::Autolock _l(mLock);
5037 size_t size = mHandles.size();
5038 size_t i;
5039 for (i = 0; i < size; i++) {
5040 if (mHandles[i] == handle) break;
5041 }
5042 if (i == size) {
5043 return size;
5044 }
5045 mHandles.removeAt(i);
5046 size = mHandles.size();
5047 // if removed from first place, move effect control from this handle to next in line
5048 if (i == 0 && size != 0) {
5049 sp<EffectHandle> h = mHandles[0].promote();
5050 if (h != 0) {
5051 h->setControl(true, true);
5052 }
5053 }
5054
5055 return size;
5056}
5057
5058void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle)
5059{
5060 // keep a strong reference on this EffectModule to avoid calling the
5061 // destructor before we exit
5062 sp<EffectModule> keep(this);
Eric Laurent53334cd2010-06-23 17:38:20 -07005063 {
5064 sp<ThreadBase> thread = mThread.promote();
5065 if (thread != 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07005066 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurent53334cd2010-06-23 17:38:20 -07005067 playbackThread->disconnectEffect(keep, handle);
Eric Laurent65b65452010-06-01 23:49:17 -07005068 }
5069 }
5070}
5071
5072void AudioFlinger::EffectModule::process()
5073{
5074 Mutex::Autolock _l(mLock);
5075
5076 if (mEffectInterface == NULL || mConfig.inputCfg.buffer.raw == NULL || mConfig.outputCfg.buffer.raw == NULL) {
5077 return;
5078 }
5079
5080 if (mState != IDLE) {
5081 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
5082 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5083 AudioMixer::ditherAndClamp(mConfig.inputCfg.buffer.s32,
5084 mConfig.inputCfg.buffer.s32,
5085 mConfig.inputCfg.buffer.frameCount);
5086 }
5087
5088 // TODO: handle effects with buffer provider
5089 if (mState != ACTIVE) {
Eric Laurent65b65452010-06-01 23:49:17 -07005090 switch (mState) {
5091 case RESET:
5092 reset();
Eric Laurent53334cd2010-06-23 17:38:20 -07005093 mState = STARTING;
Eric Laurent65b65452010-06-01 23:49:17 -07005094 // clear auxiliary effect input buffer for next accumulation
5095 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5096 memset(mConfig.inputCfg.buffer.raw, 0, mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
5097 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005098 return;
Eric Laurent65b65452010-06-01 23:49:17 -07005099 case STARTING:
5100 start();
Eric Laurent65b65452010-06-01 23:49:17 -07005101 mState = ACTIVE;
5102 break;
5103 case STOPPING:
Eric Laurent65b65452010-06-01 23:49:17 -07005104 mState = STOPPED;
5105 break;
5106 case STOPPED:
5107 stop();
Eric Laurent65b65452010-06-01 23:49:17 -07005108 mState = IDLE;
Eric Laurent65b65452010-06-01 23:49:17 -07005109 return;
5110 }
5111 }
5112
5113 // do the actual processing in the effect engine
5114 (*mEffectInterface)->process(mEffectInterface, &mConfig.inputCfg.buffer, &mConfig.outputCfg.buffer);
5115
5116 // clear auxiliary effect input buffer for next accumulation
5117 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5118 memset(mConfig.inputCfg.buffer.raw, 0, mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
5119 }
5120 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
5121 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw){
5122 // If an insert effect is idle and input buffer is different from output buffer, copy input to
5123 // output
5124 sp<EffectChain> chain = mChain.promote();
5125 if (chain != 0 && chain->activeTracks() != 0) {
5126 size_t size = mConfig.inputCfg.buffer.frameCount * sizeof(int16_t);
5127 if (mConfig.inputCfg.channels == CHANNEL_STEREO) {
5128 size *= 2;
5129 }
5130 memcpy(mConfig.outputCfg.buffer.raw, mConfig.inputCfg.buffer.raw, size);
5131 }
5132 }
5133}
5134
5135void AudioFlinger::EffectModule::reset()
5136{
5137 if (mEffectInterface == NULL) {
5138 return;
5139 }
5140 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
5141}
5142
5143status_t AudioFlinger::EffectModule::configure()
5144{
5145 uint32_t channels;
5146 if (mEffectInterface == NULL) {
5147 return NO_INIT;
5148 }
5149
5150 sp<ThreadBase> thread = mThread.promote();
5151 if (thread == 0) {
5152 return DEAD_OBJECT;
5153 }
5154
5155 // TODO: handle configuration of effects replacing track process
5156 if (thread->channelCount() == 1) {
5157 channels = CHANNEL_MONO;
5158 } else {
5159 channels = CHANNEL_STEREO;
5160 }
5161
5162 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5163 mConfig.inputCfg.channels = CHANNEL_MONO;
5164 } else {
5165 mConfig.inputCfg.channels = channels;
5166 }
5167 mConfig.outputCfg.channels = channels;
Eric Laurent53334cd2010-06-23 17:38:20 -07005168 mConfig.inputCfg.format = SAMPLE_FORMAT_PCM_S15;
5169 mConfig.outputCfg.format = SAMPLE_FORMAT_PCM_S15;
Eric Laurent65b65452010-06-01 23:49:17 -07005170 mConfig.inputCfg.samplingRate = thread->sampleRate();
5171 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
5172 mConfig.inputCfg.bufferProvider.cookie = NULL;
5173 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
5174 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
5175 mConfig.outputCfg.bufferProvider.cookie = NULL;
5176 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
5177 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
5178 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
5179 // Insert effect:
Eric Laurent53334cd2010-06-23 17:38:20 -07005180 // - in session 0 or -1, always overwrites output buffer: input buffer == output buffer
Eric Laurent65b65452010-06-01 23:49:17 -07005181 // - in other sessions:
5182 // last effect in the chain accumulates in output buffer: input buffer != output buffer
5183 // other effect: overwrites output buffer: input buffer == output buffer
5184 // Auxiliary effect:
5185 // accumulates in output buffer: input buffer != output buffer
5186 // Therefore: accumulate <=> input buffer != output buffer
5187 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
5188 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
5189 } else {
5190 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
5191 }
5192 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
5193 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
5194 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
5195 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
5196
5197 status_t cmdStatus;
5198 int size = sizeof(int);
5199 status_t status = (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_CONFIGURE, sizeof(effect_config_t), &mConfig, &size, &cmdStatus);
5200 if (status == 0) {
5201 status = cmdStatus;
5202 }
5203 return status;
5204}
5205
5206status_t AudioFlinger::EffectModule::init()
5207{
5208 if (mEffectInterface == NULL) {
5209 return NO_INIT;
5210 }
5211 status_t cmdStatus;
5212 int size = sizeof(status_t);
5213 status_t status = (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_INIT, 0, NULL, &size, &cmdStatus);
5214 if (status == 0) {
5215 status = cmdStatus;
5216 }
5217 return status;
5218}
5219
5220status_t AudioFlinger::EffectModule::start()
5221{
5222 if (mEffectInterface == NULL) {
5223 return NO_INIT;
5224 }
5225 status_t cmdStatus;
5226 int size = sizeof(status_t);
5227 status_t status = (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_ENABLE, 0, NULL, &size, &cmdStatus);
5228 if (status == 0) {
5229 status = cmdStatus;
5230 }
5231 return status;
5232}
5233
5234status_t AudioFlinger::EffectModule::stop()
5235{
5236 if (mEffectInterface == NULL) {
5237 return NO_INIT;
5238 }
5239 status_t cmdStatus;
5240 int size = sizeof(status_t);
5241 status_t status = (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_DISABLE, 0, NULL, &size, &cmdStatus);
5242 if (status == 0) {
5243 status = cmdStatus;
5244 }
5245 return status;
5246}
5247
5248status_t AudioFlinger::EffectModule::command(int cmdCode, int cmdSize, void *pCmdData, int *replySize, void *pReplyData)
5249{
5250 LOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
5251
5252 if (mEffectInterface == NULL) {
5253 return NO_INIT;
5254 }
5255 status_t status = (*mEffectInterface)->command(mEffectInterface, cmdCode, cmdSize, pCmdData, replySize, pReplyData);
5256 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
5257 int size = (replySize == NULL) ? 0 : *replySize;
5258 Mutex::Autolock _l(mLock);
5259 for (size_t i = 1; i < mHandles.size(); i++) {
5260 sp<EffectHandle> h = mHandles[i].promote();
5261 if (h != 0) {
5262 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
5263 }
5264 }
5265 }
5266 return status;
5267}
5268
5269status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
5270{
5271 Mutex::Autolock _l(mLock);
5272 LOGV("setEnabled %p enabled %d", this, enabled);
5273
5274 if (enabled != isEnabled()) {
5275 switch (mState) {
5276 // going from disabled to enabled
5277 case IDLE:
5278 mState = RESET;
5279 break;
5280 case STOPPING:
5281 mState = ACTIVE;
5282 break;
5283 case STOPPED:
5284 mState = STARTING;
5285 break;
5286
5287 // going from enabled to disabled
5288 case RESET:
5289 mState = IDLE;
5290 break;
5291 case STARTING:
5292 mState = STOPPED;
5293 break;
5294 case ACTIVE:
5295 mState = STOPPING;
5296 break;
5297 }
5298 for (size_t i = 1; i < mHandles.size(); i++) {
5299 sp<EffectHandle> h = mHandles[i].promote();
5300 if (h != 0) {
5301 h->setEnabled(enabled);
5302 }
5303 }
5304 }
5305 return NO_ERROR;
5306}
5307
5308bool AudioFlinger::EffectModule::isEnabled()
5309{
5310 switch (mState) {
5311 case RESET:
5312 case STARTING:
5313 case ACTIVE:
5314 return true;
5315 case IDLE:
5316 case STOPPING:
5317 case STOPPED:
5318 default:
5319 return false;
5320 }
5321}
5322
5323status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
5324{
5325 status_t status = NO_ERROR;
5326
5327 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
5328 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
5329 if ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) & (EFFECT_FLAG_VOLUME_CTRL|EFFECT_FLAG_VOLUME_IND)) {
5330 status_t cmdStatus;
5331 uint32_t volume[2];
5332 uint32_t *pVolume = NULL;
5333 int size = sizeof(volume);
5334 volume[0] = *left;
5335 volume[1] = *right;
5336 if (controller) {
5337 pVolume = volume;
5338 }
5339 status = (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_SET_VOLUME, size, volume, &size, pVolume);
5340 if (controller && status == NO_ERROR && size == sizeof(volume)) {
5341 *left = volume[0];
5342 *right = volume[1];
5343 }
5344 }
5345 return status;
5346}
5347
5348status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
5349{
5350 status_t status = NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07005351 if ((mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
5352 // convert device bit field from AudioSystem to EffectApi format.
5353 device = deviceAudioSystemToEffectApi(device);
5354 if (device == 0) {
5355 return BAD_VALUE;
5356 }
Eric Laurent65b65452010-06-01 23:49:17 -07005357 status_t cmdStatus;
5358 int size = sizeof(status_t);
5359 status = (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_SET_DEVICE, sizeof(uint32_t), &device, &size, &cmdStatus);
5360 if (status == NO_ERROR) {
5361 status = cmdStatus;
5362 }
5363 }
5364 return status;
5365}
5366
Eric Laurent53334cd2010-06-23 17:38:20 -07005367status_t AudioFlinger::EffectModule::setMode(uint32_t mode)
5368{
5369 status_t status = NO_ERROR;
5370 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
5371 // convert audio mode from AudioSystem to EffectApi format.
5372 int effectMode = modeAudioSystemToEffectApi(mode);
5373 if (effectMode < 0) {
5374 return BAD_VALUE;
5375 }
5376 status_t cmdStatus;
5377 int size = sizeof(status_t);
5378 status = (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_SET_AUDIO_MODE, sizeof(int), &effectMode, &size, &cmdStatus);
5379 if (status == NO_ERROR) {
5380 status = cmdStatus;
5381 }
5382 }
5383 return status;
5384}
5385
5386// update this table when AudioSystem::audio_devices or audio_device_e (in EffectApi.h) are modified
5387const uint32_t AudioFlinger::EffectModule::sDeviceConvTable[] = {
5388 DEVICE_EARPIECE, // AudioSystem::DEVICE_OUT_EARPIECE
5389 DEVICE_SPEAKER, // AudioSystem::DEVICE_OUT_SPEAKER
5390 DEVICE_WIRED_HEADSET, // case AudioSystem::DEVICE_OUT_WIRED_HEADSET
5391 DEVICE_WIRED_HEADPHONE, // AudioSystem::DEVICE_OUT_WIRED_HEADPHONE
5392 DEVICE_BLUETOOTH_SCO, // AudioSystem::DEVICE_OUT_BLUETOOTH_SCO
5393 DEVICE_BLUETOOTH_SCO_HEADSET, // AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_HEADSET
5394 DEVICE_BLUETOOTH_SCO_CARKIT, // AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_CARKIT
5395 DEVICE_BLUETOOTH_A2DP, // AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP
5396 DEVICE_BLUETOOTH_A2DP_HEADPHONES, // AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES
5397 DEVICE_BLUETOOTH_A2DP_SPEAKER, // AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER
5398 DEVICE_AUX_DIGITAL // AudioSystem::DEVICE_OUT_AUX_DIGITAL
5399};
5400
5401uint32_t AudioFlinger::EffectModule::deviceAudioSystemToEffectApi(uint32_t device)
5402{
5403 uint32_t deviceOut = 0;
5404 while (device) {
5405 const uint32_t i = 31 - __builtin_clz(device);
5406 device &= ~(1 << i);
5407 if (i >= sizeof(sDeviceConvTable)/sizeof(uint32_t)) {
5408 LOGE("device convertion error for AudioSystem device 0x%08x", device);
5409 return 0;
5410 }
5411 deviceOut |= (uint32_t)sDeviceConvTable[i];
5412 }
5413 return deviceOut;
5414}
5415
5416// update this table when AudioSystem::audio_mode or audio_mode_e (in EffectApi.h) are modified
5417const uint32_t AudioFlinger::EffectModule::sModeConvTable[] = {
5418 AUDIO_MODE_NORMAL, // AudioSystem::MODE_NORMAL
5419 AUDIO_MODE_RINGTONE, // AudioSystem::MODE_RINGTONE
5420 AUDIO_MODE_IN_CALL // AudioSystem::MODE_IN_CALL
5421};
5422
5423int AudioFlinger::EffectModule::modeAudioSystemToEffectApi(uint32_t mode)
5424{
5425 int modeOut = -1;
5426 if (mode < sizeof(sModeConvTable) / sizeof(uint32_t)) {
5427 modeOut = (int)sModeConvTable[mode];
5428 }
5429 return modeOut;
5430}
Eric Laurent65b65452010-06-01 23:49:17 -07005431
5432status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
5433{
5434 const size_t SIZE = 256;
5435 char buffer[SIZE];
5436 String8 result;
5437
5438 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
5439 result.append(buffer);
5440
5441 bool locked = tryLock(mLock);
5442 // failed to lock - AudioFlinger is probably deadlocked
5443 if (!locked) {
5444 result.append("\t\tCould not lock Fx mutex:\n");
5445 }
5446
5447 result.append("\t\tSession Status State Engine:\n");
5448 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
5449 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
5450 result.append(buffer);
5451
5452 result.append("\t\tDescriptor:\n");
5453 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
5454 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
5455 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
5456 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
5457 result.append(buffer);
5458 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
5459 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
5460 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
5461 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
5462 result.append(buffer);
5463 snprintf(buffer, SIZE, "\t\t- apiVersion: %04X\n\t\t- flags: %08X\n",
5464 mDescriptor.apiVersion,
5465 mDescriptor.flags);
5466 result.append(buffer);
5467 snprintf(buffer, SIZE, "\t\t- name: %s\n",
5468 mDescriptor.name);
5469 result.append(buffer);
5470 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
5471 mDescriptor.implementor);
5472 result.append(buffer);
5473
5474 result.append("\t\t- Input configuration:\n");
5475 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
5476 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
5477 (uint32_t)mConfig.inputCfg.buffer.raw,
5478 mConfig.inputCfg.buffer.frameCount,
5479 mConfig.inputCfg.samplingRate,
5480 mConfig.inputCfg.channels,
5481 mConfig.inputCfg.format);
5482 result.append(buffer);
5483
5484 result.append("\t\t- Output configuration:\n");
5485 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
5486 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
5487 (uint32_t)mConfig.outputCfg.buffer.raw,
5488 mConfig.outputCfg.buffer.frameCount,
5489 mConfig.outputCfg.samplingRate,
5490 mConfig.outputCfg.channels,
5491 mConfig.outputCfg.format);
5492 result.append(buffer);
5493
5494 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
5495 result.append(buffer);
5496 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
5497 for (size_t i = 0; i < mHandles.size(); ++i) {
5498 sp<EffectHandle> handle = mHandles[i].promote();
5499 if (handle != 0) {
5500 handle->dump(buffer, SIZE);
5501 result.append(buffer);
5502 }
5503 }
5504
5505 result.append("\n");
5506
5507 write(fd, result.string(), result.length());
5508
5509 if (locked) {
5510 mLock.unlock();
5511 }
5512
5513 return NO_ERROR;
5514}
5515
5516// ----------------------------------------------------------------------------
5517// EffectHandle implementation
5518// ----------------------------------------------------------------------------
5519
5520#undef LOG_TAG
5521#define LOG_TAG "AudioFlinger::EffectHandle"
5522
5523AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
5524 const sp<AudioFlinger::Client>& client,
5525 const sp<IEffectClient>& effectClient,
5526 int32_t priority)
5527 : BnEffect(),
5528 mEffect(effect), mEffectClient(effectClient), mClient(client), mPriority(priority), mHasControl(false)
5529{
5530 LOGV("constructor %p", this);
5531
5532 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
5533 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
5534 if (mCblkMemory != 0) {
5535 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
5536
5537 if (mCblk) {
5538 new(mCblk) effect_param_cblk_t();
5539 mBuffer = (uint8_t *)mCblk + bufOffset;
5540 }
5541 } else {
5542 LOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
5543 return;
5544 }
5545}
5546
5547AudioFlinger::EffectHandle::~EffectHandle()
5548{
5549 LOGV("Destructor %p", this);
5550 disconnect();
5551}
5552
5553status_t AudioFlinger::EffectHandle::enable()
5554{
5555 if (!mHasControl) return INVALID_OPERATION;
5556 if (mEffect == 0) return DEAD_OBJECT;
5557
5558 return mEffect->setEnabled(true);
5559}
5560
5561status_t AudioFlinger::EffectHandle::disable()
5562{
5563 if (!mHasControl) return INVALID_OPERATION;
5564 if (mEffect == NULL) return DEAD_OBJECT;
5565
5566 return mEffect->setEnabled(false);
5567}
5568
5569void AudioFlinger::EffectHandle::disconnect()
5570{
5571 if (mEffect == 0) {
5572 return;
5573 }
5574 mEffect->disconnect(this);
5575 // release sp on module => module destructor can be called now
5576 mEffect.clear();
5577 if (mCblk) {
5578 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
5579 }
5580 mCblkMemory.clear(); // and free the shared memory
5581 if (mClient != 0) {
5582 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
5583 mClient.clear();
5584 }
5585}
5586
5587status_t AudioFlinger::EffectHandle::command(int cmdCode, int cmdSize, void *pCmdData, int *replySize, void *pReplyData)
5588{
5589 LOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p", cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
5590
5591 // only get parameter command is permitted for applications not controlling the effect
5592 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
5593 return INVALID_OPERATION;
5594 }
5595 if (mEffect == 0) return DEAD_OBJECT;
5596
5597 // handle commands that are not forwarded transparently to effect engine
5598 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
5599 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
5600 // no risk to block the whole media server process or mixer threads is we are stuck here
5601 Mutex::Autolock _l(mCblk->lock);
5602 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
5603 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
5604 mCblk->serverIndex = 0;
5605 mCblk->clientIndex = 0;
5606 return BAD_VALUE;
5607 }
5608 status_t status = NO_ERROR;
5609 while (mCblk->serverIndex < mCblk->clientIndex) {
5610 int reply;
5611 int rsize = sizeof(int);
5612 int *p = (int *)(mBuffer + mCblk->serverIndex);
5613 int size = *p++;
Eric Laurent53334cd2010-06-23 17:38:20 -07005614 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
5615 LOGW("command(): invalid parameter block size");
5616 break;
5617 }
Eric Laurent65b65452010-06-01 23:49:17 -07005618 effect_param_t *param = (effect_param_t *)p;
Eric Laurent53334cd2010-06-23 17:38:20 -07005619 if (param->psize == 0 || param->vsize == 0) {
5620 LOGW("command(): null parameter or value size");
5621 mCblk->serverIndex += size;
5622 continue;
5623 }
Eric Laurent65b65452010-06-01 23:49:17 -07005624 int psize = sizeof(effect_param_t) + ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) + param->vsize;
5625 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM, psize, p, &rsize, &reply);
5626 if (ret == NO_ERROR) {
5627 if (reply != NO_ERROR) {
5628 status = reply;
5629 }
5630 } else {
5631 status = ret;
5632 }
5633 mCblk->serverIndex += size;
5634 }
5635 mCblk->serverIndex = 0;
5636 mCblk->clientIndex = 0;
5637 return status;
5638 } else if (cmdCode == EFFECT_CMD_ENABLE) {
5639 return enable();
5640 } else if (cmdCode == EFFECT_CMD_DISABLE) {
5641 return disable();
5642 }
5643
5644 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
5645}
5646
5647sp<IMemory> AudioFlinger::EffectHandle::getCblk() const {
5648 return mCblkMemory;
5649}
5650
5651void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal)
5652{
5653 LOGV("setControl %p control %d", this, hasControl);
5654
5655 mHasControl = hasControl;
5656 if (signal && mEffectClient != 0) {
5657 mEffectClient->controlStatusChanged(hasControl);
5658 }
5659}
5660
5661void AudioFlinger::EffectHandle::commandExecuted(int cmdCode, int cmdSize, void *pCmdData, int replySize, void *pReplyData)
5662{
5663 if (mEffectClient != 0) {
5664 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
5665 }
5666}
5667
5668
5669
5670void AudioFlinger::EffectHandle::setEnabled(bool enabled)
5671{
5672 if (mEffectClient != 0) {
5673 mEffectClient->enableStatusChanged(enabled);
5674 }
5675}
5676
5677status_t AudioFlinger::EffectHandle::onTransact(
5678 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5679{
5680 return BnEffect::onTransact(code, data, reply, flags);
5681}
5682
5683
5684void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
5685{
5686 bool locked = tryLock(mCblk->lock);
5687
5688 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
5689 (mClient == NULL) ? getpid() : mClient->pid(),
5690 mPriority,
5691 mHasControl,
5692 !locked,
5693 mCblk->clientIndex,
5694 mCblk->serverIndex
5695 );
5696
5697 if (locked) {
5698 mCblk->lock.unlock();
5699 }
5700}
5701
5702#undef LOG_TAG
5703#define LOG_TAG "AudioFlinger::EffectChain"
5704
5705AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
5706 int sessionId)
5707 : mThread(wThread), mSessionId(sessionId), mVolumeCtrlIdx(-1), mActiveTrackCnt(0), mOwnInBuffer(false)
5708{
5709
5710}
5711
5712AudioFlinger::EffectChain::~EffectChain()
5713{
5714 if (mOwnInBuffer) {
5715 delete mInBuffer;
5716 }
5717
5718}
5719
5720sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc(effect_descriptor_t *descriptor)
5721{
5722 sp<EffectModule> effect;
5723 size_t size = mEffects.size();
5724
5725 for (size_t i = 0; i < size; i++) {
5726 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
5727 effect = mEffects[i];
5728 break;
5729 }
5730 }
5731 return effect;
5732}
5733
5734sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId(int id)
5735{
5736 sp<EffectModule> effect;
5737 size_t size = mEffects.size();
5738
5739 for (size_t i = 0; i < size; i++) {
5740 if (mEffects[i]->id() == id) {
5741 effect = mEffects[i];
5742 break;
5743 }
5744 }
5745 return effect;
5746}
5747
5748// Must be called with EffectChain::mLock locked
5749void AudioFlinger::EffectChain::process_l()
5750{
5751 size_t size = mEffects.size();
5752 for (size_t i = 0; i < size; i++) {
5753 mEffects[i]->process();
5754 }
5755 // if no track is active, input buffer must be cleared here as the mixer process
5756 // will not do it
Eric Laurent53334cd2010-06-23 17:38:20 -07005757 if (mSessionId > 0 && activeTracks() == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07005758 sp<ThreadBase> thread = mThread.promote();
5759 if (thread != 0) {
5760 size_t numSamples = thread->frameCount() * thread->channelCount();
5761 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
5762 }
5763 }
5764}
5765
5766status_t AudioFlinger::EffectChain::addEffect(sp<EffectModule>& effect)
5767{
5768 effect_descriptor_t desc = effect->desc();
5769 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
5770
5771 Mutex::Autolock _l(mLock);
5772
5773 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5774 // Auxiliary effects are inserted at the beginning of mEffects vector as
5775 // they are processed first and accumulated in chain input buffer
5776 mEffects.insertAt(effect, 0);
5777 sp<ThreadBase> thread = mThread.promote();
5778 if (thread == 0) {
5779 return NO_INIT;
5780 }
5781 // the input buffer for auxiliary effect contains mono samples in
5782 // 32 bit format. This is to avoid saturation in AudoMixer
5783 // accumulation stage. Saturation is done in EffectModule::process() before
5784 // calling the process in effect engine
5785 size_t numSamples = thread->frameCount();
5786 int32_t *buffer = new int32_t[numSamples];
5787 memset(buffer, 0, numSamples * sizeof(int32_t));
5788 effect->setInBuffer((int16_t *)buffer);
5789 // auxiliary effects output samples to chain input buffer for further processing
5790 // by insert effects
5791 effect->setOutBuffer(mInBuffer);
5792 } else {
5793 // Insert effects are inserted at the end of mEffects vector as they are processed
5794 // after track and auxiliary effects.
Eric Laurent53334cd2010-06-23 17:38:20 -07005795 // Insert effect order as a function of indicated preference:
5796 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
5797 // another effect is present
5798 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
5799 // last effect claiming first position
5800 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
5801 // first effect claiming last position
Eric Laurent65b65452010-06-01 23:49:17 -07005802 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
Eric Laurent53334cd2010-06-23 17:38:20 -07005803 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
5804 // already present
Eric Laurent65b65452010-06-01 23:49:17 -07005805
5806 int size = (int)mEffects.size();
5807 int idx_insert = size;
5808 int idx_insert_first = -1;
5809 int idx_insert_last = -1;
5810
5811 for (int i = 0; i < size; i++) {
5812 effect_descriptor_t d = mEffects[i]->desc();
5813 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
5814 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
5815 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
5816 // check invalid effect chaining combinations
5817 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
Eric Laurent53334cd2010-06-23 17:38:20 -07005818 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
5819 LOGW("addEffect() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Eric Laurent65b65452010-06-01 23:49:17 -07005820 return INVALID_OPERATION;
5821 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005822 // remember position of first insert effect and by default
5823 // select this as insert position for new effect
Eric Laurent65b65452010-06-01 23:49:17 -07005824 if (idx_insert == size) {
5825 idx_insert = i;
5826 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005827 // remember position of last insert effect claiming
5828 // first position
Eric Laurent65b65452010-06-01 23:49:17 -07005829 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
5830 idx_insert_first = i;
5831 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005832 // remember position of first insert effect claiming
5833 // last position
5834 if (iPref == EFFECT_FLAG_INSERT_LAST &&
5835 idx_insert_last == -1) {
Eric Laurent65b65452010-06-01 23:49:17 -07005836 idx_insert_last = i;
5837 }
5838 }
5839 }
5840
Eric Laurent53334cd2010-06-23 17:38:20 -07005841 // modify idx_insert from first position if needed
5842 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
5843 if (idx_insert_last != -1) {
5844 idx_insert = idx_insert_last;
5845 } else {
5846 idx_insert = size;
5847 }
5848 } else {
5849 if (idx_insert_first != -1) {
5850 idx_insert = idx_insert_first + 1;
5851 }
Eric Laurent65b65452010-06-01 23:49:17 -07005852 }
5853
5854 // always read samples from chain input buffer
5855 effect->setInBuffer(mInBuffer);
5856
5857 // if last effect in the chain, output samples to chain
5858 // output buffer, otherwise to chain input buffer
5859 if (idx_insert == size) {
5860 if (idx_insert != 0) {
5861 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
5862 mEffects[idx_insert-1]->configure();
5863 }
5864 effect->setOutBuffer(mOutBuffer);
5865 } else {
5866 effect->setOutBuffer(mInBuffer);
5867 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005868 mEffects.insertAt(effect, idx_insert);
Eric Laurent65b65452010-06-01 23:49:17 -07005869 // Always give volume control to last effect in chain with volume control capability
5870 if (((desc.flags & EFFECT_FLAG_VOLUME_MASK) & EFFECT_FLAG_VOLUME_CTRL) &&
5871 mVolumeCtrlIdx < idx_insert) {
5872 mVolumeCtrlIdx = idx_insert;
5873 }
5874
Eric Laurent53334cd2010-06-23 17:38:20 -07005875 LOGV("addEffect() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Eric Laurent65b65452010-06-01 23:49:17 -07005876 }
5877 effect->configure();
5878 return NO_ERROR;
5879}
5880
5881size_t AudioFlinger::EffectChain::removeEffect(const sp<EffectModule>& effect)
5882{
5883 Mutex::Autolock _l(mLock);
5884
5885 int size = (int)mEffects.size();
5886 int i;
5887 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
5888
5889 for (i = 0; i < size; i++) {
5890 if (effect == mEffects[i]) {
5891 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
5892 delete[] effect->inBuffer();
5893 } else {
5894 if (i == size - 1 && i != 0) {
5895 mEffects[i - 1]->setOutBuffer(mOutBuffer);
5896 mEffects[i - 1]->configure();
5897 }
5898 }
5899 mEffects.removeAt(i);
5900 LOGV("removeEffect() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
5901 break;
5902 }
5903 }
5904 // Return volume control to last effect in chain with volume control capability
5905 if (mVolumeCtrlIdx == i) {
5906 size = (int)mEffects.size();
5907 for (i = size; i > 0; i--) {
5908 if ((mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) & EFFECT_FLAG_VOLUME_CTRL) {
5909 break;
5910 }
5911 }
5912 // mVolumeCtrlIdx reset to -1 if no effect found with volume control flag set
5913 mVolumeCtrlIdx = i - 1;
5914 }
5915
5916 return mEffects.size();
5917}
5918
5919void AudioFlinger::EffectChain::setDevice(uint32_t device)
5920{
5921 size_t size = mEffects.size();
5922 for (size_t i = 0; i < size; i++) {
5923 mEffects[i]->setDevice(device);
5924 }
5925}
5926
Eric Laurent53334cd2010-06-23 17:38:20 -07005927void AudioFlinger::EffectChain::setMode(uint32_t mode)
5928{
5929 size_t size = mEffects.size();
5930 for (size_t i = 0; i < size; i++) {
5931 mEffects[i]->setMode(mode);
5932 }
5933}
5934
Eric Laurent65b65452010-06-01 23:49:17 -07005935bool AudioFlinger::EffectChain::setVolume(uint32_t *left, uint32_t *right)
5936{
5937 uint32_t newLeft = *left;
5938 uint32_t newRight = *right;
5939 bool hasControl = false;
5940
5941 // first get volume update from volume controller
5942 if (mVolumeCtrlIdx >= 0) {
5943 mEffects[mVolumeCtrlIdx]->setVolume(&newLeft, &newRight, true);
5944 hasControl = true;
5945 }
5946 // then indicate volume to all other effects in chain.
5947 // Pass altered volume to effects before volume controller
5948 // and requested volume to effects after controller
5949 uint32_t lVol = newLeft;
5950 uint32_t rVol = newRight;
5951 size_t size = mEffects.size();
5952 for (size_t i = 0; i < size; i++) {
5953 if ((int)i == mVolumeCtrlIdx) continue;
5954 // this also works for mVolumeCtrlIdx == -1 when there is no volume controller
5955 if ((int)i > mVolumeCtrlIdx) {
5956 lVol = *left;
5957 rVol = *right;
5958 }
5959 mEffects[i]->setVolume(&lVol, &rVol, false);
5960 }
5961 *left = newLeft;
5962 *right = newRight;
5963
5964 return hasControl;
5965}
5966
5967sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getVolumeController()
5968{
5969 sp<EffectModule> effect;
5970 if (mVolumeCtrlIdx >= 0) {
5971 effect = mEffects[mVolumeCtrlIdx];
5972 }
5973 return effect;
5974}
5975
5976
5977status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
5978{
5979 const size_t SIZE = 256;
5980 char buffer[SIZE];
5981 String8 result;
5982
5983 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
5984 result.append(buffer);
5985
5986 bool locked = tryLock(mLock);
5987 // failed to lock - AudioFlinger is probably deadlocked
5988 if (!locked) {
5989 result.append("\tCould not lock mutex:\n");
5990 }
5991
5992 result.append("\tNum fx In buffer Out buffer Vol ctrl Active tracks:\n");
5993 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %02d %d\n",
5994 mEffects.size(),
5995 (uint32_t)mInBuffer,
5996 (uint32_t)mOutBuffer,
5997 (mVolumeCtrlIdx == -1) ? 0 : mEffects[mVolumeCtrlIdx]->id(),
5998 mActiveTrackCnt);
5999 result.append(buffer);
6000 write(fd, result.string(), result.size());
6001
6002 for (size_t i = 0; i < mEffects.size(); ++i) {
6003 sp<EffectModule> effect = mEffects[i];
6004 if (effect != 0) {
6005 effect->dump(fd, args);
6006 }
6007 }
6008
6009 if (locked) {
6010 mLock.unlock();
6011 }
6012
6013 return NO_ERROR;
6014}
6015
6016#undef LOG_TAG
6017#define LOG_TAG "AudioFlinger"
6018
Eric Laurenta553c252009-07-17 12:17:14 -07006019// ----------------------------------------------------------------------------
6020
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07006021status_t AudioFlinger::onTransact(
6022 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6023{
6024 return BnAudioFlinger::onTransact(code, data, reply, flags);
6025}
6026
6027// ----------------------------------------------------------------------------
Eric Laurenta553c252009-07-17 12:17:14 -07006028
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07006029void AudioFlinger::instantiate() {
6030 defaultServiceManager()->addService(
6031 String16("media.audio_flinger"), new AudioFlinger());
6032}
6033
6034}; // namespace android