blob: e6f46ce9ecc036a56e571885eb804b2e8d48bb31 [file] [log] [blame]
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001/* //device/include/server/AudioFlinger/AudioFlinger.cpp
2**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
Eric Laurentdf9b81c2010-07-02 08:12:41 -070020//
21#define LOG_NDEBUG 0
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070022
23#include <math.h>
24#include <signal.h>
25#include <sys/time.h>
26#include <sys/resource.h>
27
Mathias Agopian07952722009-05-19 19:08:10 -070028#include <binder/IServiceManager.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070029#include <utils/Log.h>
Mathias Agopian07952722009-05-19 19:08:10 -070030#include <binder/Parcel.h>
31#include <binder/IPCThreadState.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070032#include <utils/String16.h>
33#include <utils/threads.h>
34
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080035#include <cutils/properties.h>
36
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070037#include <media/AudioTrack.h>
38#include <media/AudioRecord.h>
39
40#include <private/media/AudioTrackShared.h>
Eric Laurent65b65452010-06-01 23:49:17 -070041#include <private/media/AudioEffectShared.h>
The Android Open Source Project9266c552009-01-15 16:12:10 -080042#include <hardware_legacy/AudioHardwareInterface.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070043
44#include "AudioMixer.h"
45#include "AudioFlinger.h"
46
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080047#ifdef WITH_A2DP
48#include "A2dpAudioInterface.h"
49#endif
50
Glenn Kasten871c16c2010-03-05 12:18:01 -080051#ifdef LVMX
52#include "lifevibes.h"
53#endif
54
Eric Laurent53334cd2010-06-23 17:38:20 -070055#include <media/EffectsFactoryApi.h>
Eric Laurentdf9b81c2010-07-02 08:12:41 -070056#include <media/EffectVisualizerApi.h>
Eric Laurent65b65452010-06-01 23:49:17 -070057
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058// ----------------------------------------------------------------------------
59// the sim build doesn't have gettid
60
61#ifndef HAVE_GETTID
62# define gettid getpid
63#endif
64
65// ----------------------------------------------------------------------------
66
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070067namespace android {
68
The Android Open Source Project10592532009-03-18 17:39:46 -070069static const char* kDeadlockedString = "AudioFlinger may be deadlocked\n";
70static const char* kHardwareLockedString = "Hardware lock is taken\n";
71
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080072//static const nsecs_t kStandbyTimeInNsecs = seconds(3);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070073static const float MAX_GAIN = 4096.0f;
Eric Laurent65b65452010-06-01 23:49:17 -070074static const float MAX_GAIN_INT = 0x1000;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070075
76// retry counts for buffer fill timeout
77// 50 * ~20msecs = 1 second
78static const int8_t kMaxTrackRetries = 50;
79static const int8_t kMaxTrackStartupRetries = 50;
Eric Laurentef9500f2010-03-11 14:47:00 -080080// allow less retry attempts on direct output thread.
81// direct outputs can be a scarce resource in audio hardware and should
82// be released as quickly as possible.
83static const int8_t kMaxTrackRetriesDirect = 2;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070084
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -070085static const int kDumpLockRetries = 50;
86static const int kDumpLockSleep = 20000;
87
Dave Sparksd0ac8c02009-09-30 03:09:03 -070088static const nsecs_t kWarningThrottle = seconds(5);
89
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070091#define AUDIOFLINGER_SECURITY_ENABLED 1
92
93// ----------------------------------------------------------------------------
94
95static bool recordingAllowed() {
96#ifndef HAVE_ANDROID_OS
97 return true;
98#endif
99#if AUDIOFLINGER_SECURITY_ENABLED
100 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
101 bool ok = checkCallingPermission(String16("android.permission.RECORD_AUDIO"));
102 if (!ok) LOGE("Request requires android.permission.RECORD_AUDIO");
103 return ok;
104#else
105 if (!checkCallingPermission(String16("android.permission.RECORD_AUDIO")))
106 LOGW("WARNING: Need to add android.permission.RECORD_AUDIO to manifest");
107 return true;
108#endif
109}
110
111static bool settingsAllowed() {
112#ifndef HAVE_ANDROID_OS
113 return true;
114#endif
115#if AUDIOFLINGER_SECURITY_ENABLED
116 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
117 bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
118 if (!ok) LOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
119 return ok;
120#else
121 if (!checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS")))
122 LOGW("WARNING: Need to add android.permission.MODIFY_AUDIO_SETTINGS to manifest");
123 return true;
124#endif
125}
126
127// ----------------------------------------------------------------------------
128
129AudioFlinger::AudioFlinger()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800130 : BnAudioFlinger(),
Eric Laurent53334cd2010-06-23 17:38:20 -0700131 mAudioHardware(0), mMasterVolume(1.0f), mMasterMute(false), mNextUniqueId(1),
132 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700133{
134 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -0700135
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700136 mAudioHardware = AudioHardwareInterface::create();
Eric Laurenta553c252009-07-17 12:17:14 -0700137
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700138 mHardwareStatus = AUDIO_HW_INIT;
139 if (mAudioHardware->initCheck() == NO_ERROR) {
140 // open 16-bit output stream for s/w mixer
Eric Laurent53334cd2010-06-23 17:38:20 -0700141 mMode = AudioSystem::MODE_NORMAL;
142 setMode(mMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143
144 setMasterVolume(1.0f);
145 setMasterMute(false);
Eric Laurenta553c252009-07-17 12:17:14 -0700146 } else {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700147 LOGE("Couldn't even initialize the stubbed audio hardware!");
148 }
Glenn Kasten871c16c2010-03-05 12:18:01 -0800149#ifdef LVMX
150 LifeVibes::init();
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700151 mLifeVibesClientPid = -1;
Glenn Kasten871c16c2010-03-05 12:18:01 -0800152#endif
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700153}
154
155AudioFlinger::~AudioFlinger()
156{
Eric Laurent7954c462009-08-28 10:39:03 -0700157 while (!mRecordThreads.isEmpty()) {
158 // closeInput() will remove first entry from mRecordThreads
159 closeInput(mRecordThreads.keyAt(0));
160 }
161 while (!mPlaybackThreads.isEmpty()) {
162 // closeOutput() will remove first entry from mPlaybackThreads
163 closeOutput(mPlaybackThreads.keyAt(0));
164 }
165 if (mAudioHardware) {
166 delete mAudioHardware;
167 }
The Android Open Source Projectb7986892009-01-09 17:51:23 -0800168}
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800169
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700170
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700171
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700172status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
173{
174 const size_t SIZE = 256;
175 char buffer[SIZE];
176 String8 result;
177
178 result.append("Clients:\n");
179 for (size_t i = 0; i < mClients.size(); ++i) {
180 wp<Client> wClient = mClients.valueAt(i);
181 if (wClient != 0) {
182 sp<Client> client = wClient.promote();
183 if (client != 0) {
184 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
185 result.append(buffer);
186 }
187 }
188 }
189 write(fd, result.string(), result.size());
190 return NO_ERROR;
191}
192
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700193
194status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
195{
196 const size_t SIZE = 256;
197 char buffer[SIZE];
198 String8 result;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700199 int hardwareStatus = mHardwareStatus;
Eric Laurenta553c252009-07-17 12:17:14 -0700200
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700201 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700202 result.append(buffer);
203 write(fd, result.string(), result.size());
204 return NO_ERROR;
205}
206
207status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
208{
209 const size_t SIZE = 256;
210 char buffer[SIZE];
211 String8 result;
212 snprintf(buffer, SIZE, "Permission Denial: "
213 "can't dump AudioFlinger from pid=%d, uid=%d\n",
214 IPCThreadState::self()->getCallingPid(),
215 IPCThreadState::self()->getCallingUid());
216 result.append(buffer);
217 write(fd, result.string(), result.size());
218 return NO_ERROR;
219}
220
The Android Open Source Project10592532009-03-18 17:39:46 -0700221static bool tryLock(Mutex& mutex)
222{
223 bool locked = false;
224 for (int i = 0; i < kDumpLockRetries; ++i) {
225 if (mutex.tryLock() == NO_ERROR) {
226 locked = true;
227 break;
228 }
229 usleep(kDumpLockSleep);
230 }
231 return locked;
232}
233
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700234status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
235{
236 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
237 dumpPermissionDenial(fd, args);
238 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -0700239 // get state of hardware lock
240 bool hardwareLocked = tryLock(mHardwareLock);
241 if (!hardwareLocked) {
242 String8 result(kHardwareLockedString);
243 write(fd, result.string(), result.size());
244 } else {
245 mHardwareLock.unlock();
246 }
247
248 bool locked = tryLock(mLock);
249
250 // failed to lock - AudioFlinger is probably deadlocked
251 if (!locked) {
252 String8 result(kDeadlockedString);
253 write(fd, result.string(), result.size());
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700254 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700255
256 dumpClients(fd, args);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700257 dumpInternals(fd, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800258
Eric Laurenta553c252009-07-17 12:17:14 -0700259 // dump playback threads
260 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700261 mPlaybackThreads.valueAt(i)->dump(fd, args);
Eric Laurenta553c252009-07-17 12:17:14 -0700262 }
263
264 // dump record threads
Eric Laurent102313a2009-07-23 13:35:01 -0700265 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700266 mRecordThreads.valueAt(i)->dump(fd, args);
Eric Laurenta553c252009-07-17 12:17:14 -0700267 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800268
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700269 if (mAudioHardware) {
270 mAudioHardware->dumpState(fd, args);
271 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700272 if (locked) mLock.unlock();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700273 }
274 return NO_ERROR;
275}
276
Eric Laurenta553c252009-07-17 12:17:14 -0700277
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700278// IAudioFlinger interface
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800279
280
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700281sp<IAudioTrack> AudioFlinger::createTrack(
282 pid_t pid,
283 int streamType,
284 uint32_t sampleRate,
285 int format,
286 int channelCount,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800287 int frameCount,
288 uint32_t flags,
289 const sp<IMemory>& sharedBuffer,
Eric Laurentddb78e72009-07-28 08:44:33 -0700290 int output,
Eric Laurent65b65452010-06-01 23:49:17 -0700291 int *sessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800292 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700293{
Eric Laurenta553c252009-07-17 12:17:14 -0700294 sp<PlaybackThread::Track> track;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700295 sp<TrackHandle> trackHandle;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700296 sp<Client> client;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800297 wp<Client> wclient;
298 status_t lStatus;
Eric Laurent65b65452010-06-01 23:49:17 -0700299 int lSessionId;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700300
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800301 if (streamType >= AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800302 LOGE("invalid stream type");
303 lStatus = BAD_VALUE;
304 goto Exit;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700305 }
306
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800307 {
308 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700309 PlaybackThread *thread = checkPlaybackThread_l(output);
310 if (thread == NULL) {
311 LOGE("unknown output thread");
312 lStatus = BAD_VALUE;
313 goto Exit;
314 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800315
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800316 wclient = mClients.valueFor(pid);
317
318 if (wclient != NULL) {
319 client = wclient.promote();
320 } else {
321 client = new Client(this, pid);
322 mClients.add(pid, client);
323 }
Eric Laurent65b65452010-06-01 23:49:17 -0700324
325 // If no audio session id is provided, create one here
326 // TODO: enforce same stream type for all tracks in same audio session?
327 // TODO: prevent same audio session on different output threads
328 LOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
329 if (sessionId != NULL && *sessionId != 0) {
330 lSessionId = *sessionId;
331 } else {
332 lSessionId = nextUniqueId();
333 if (sessionId != NULL) {
334 *sessionId = lSessionId;
335 }
336 }
337 LOGV("createTrack() lSessionId: %d", lSessionId);
338
Eric Laurenta553c252009-07-17 12:17:14 -0700339 track = thread->createTrack_l(client, streamType, sampleRate, format,
Eric Laurent65b65452010-06-01 23:49:17 -0700340 channelCount, frameCount, sharedBuffer, lSessionId, &lStatus);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700341 }
342 if (lStatus == NO_ERROR) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800343 trackHandle = new TrackHandle(track);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700344 } else {
Eric Laurentb9481d82009-09-17 05:12:56 -0700345 // remove local strong reference to Client before deleting the Track so that the Client
346 // destructor is called by the TrackBase destructor with mLock held
347 client.clear();
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700348 track.clear();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800349 }
350
351Exit:
352 if(status) {
353 *status = lStatus;
354 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700355 return trackHandle;
356}
357
Eric Laurentddb78e72009-07-28 08:44:33 -0700358uint32_t AudioFlinger::sampleRate(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700359{
Eric Laurenta553c252009-07-17 12:17:14 -0700360 Mutex::Autolock _l(mLock);
361 PlaybackThread *thread = checkPlaybackThread_l(output);
362 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700363 LOGW("sampleRate() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700364 return 0;
365 }
366 return thread->sampleRate();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700367}
368
Eric Laurentddb78e72009-07-28 08:44:33 -0700369int AudioFlinger::channelCount(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700370{
Eric Laurenta553c252009-07-17 12:17:14 -0700371 Mutex::Autolock _l(mLock);
372 PlaybackThread *thread = checkPlaybackThread_l(output);
373 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700374 LOGW("channelCount() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700375 return 0;
376 }
377 return thread->channelCount();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700378}
379
Eric Laurentddb78e72009-07-28 08:44:33 -0700380int AudioFlinger::format(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700381{
Eric Laurenta553c252009-07-17 12:17:14 -0700382 Mutex::Autolock _l(mLock);
383 PlaybackThread *thread = checkPlaybackThread_l(output);
384 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700385 LOGW("format() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700386 return 0;
387 }
388 return thread->format();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700389}
390
Eric Laurentddb78e72009-07-28 08:44:33 -0700391size_t AudioFlinger::frameCount(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700392{
Eric Laurenta553c252009-07-17 12:17:14 -0700393 Mutex::Autolock _l(mLock);
394 PlaybackThread *thread = checkPlaybackThread_l(output);
395 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700396 LOGW("frameCount() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700397 return 0;
398 }
399 return thread->frameCount();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700400}
401
Eric Laurentddb78e72009-07-28 08:44:33 -0700402uint32_t AudioFlinger::latency(int output) const
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800403{
Eric Laurenta553c252009-07-17 12:17:14 -0700404 Mutex::Autolock _l(mLock);
405 PlaybackThread *thread = checkPlaybackThread_l(output);
406 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700407 LOGW("latency() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700408 return 0;
409 }
410 return thread->latency();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800411}
412
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700413status_t AudioFlinger::setMasterVolume(float value)
414{
415 // check calling permissions
416 if (!settingsAllowed()) {
417 return PERMISSION_DENIED;
418 }
419
420 // when hw supports master volume, don't scale in sw mixer
421 AutoMutex lock(mHardwareLock);
422 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
423 if (mAudioHardware->setMasterVolume(value) == NO_ERROR) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800424 value = 1.0f;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700425 }
426 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -0700427
428 mMasterVolume = value;
429 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700430 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700431
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700432 return NO_ERROR;
433}
434
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700435status_t AudioFlinger::setMode(int mode)
436{
Eric Laurent53334cd2010-06-23 17:38:20 -0700437 status_t ret;
438
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700439 // check calling permissions
440 if (!settingsAllowed()) {
441 return PERMISSION_DENIED;
442 }
443 if ((mode < 0) || (mode >= AudioSystem::NUM_MODES)) {
444 LOGW("Illegal value: setMode(%d)", mode);
445 return BAD_VALUE;
446 }
447
Eric Laurent53334cd2010-06-23 17:38:20 -0700448 { // scope for the lock
449 AutoMutex lock(mHardwareLock);
450 mHardwareStatus = AUDIO_HW_SET_MODE;
451 ret = mAudioHardware->setMode(mode);
452 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten871c16c2010-03-05 12:18:01 -0800453 }
Eric Laurent53334cd2010-06-23 17:38:20 -0700454
455 if (NO_ERROR == ret) {
456 Mutex::Autolock _l(mLock);
457 mMode = mode;
458 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
459 mPlaybackThreads.valueAt(i)->setMode(mode);
460#ifdef LVMX
461 LifeVibes::setMode(mode);
Glenn Kasten871c16c2010-03-05 12:18:01 -0800462#endif
Eric Laurent53334cd2010-06-23 17:38:20 -0700463 }
464
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700465 return ret;
466}
467
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700468status_t AudioFlinger::setMicMute(bool state)
469{
470 // check calling permissions
471 if (!settingsAllowed()) {
472 return PERMISSION_DENIED;
473 }
474
475 AutoMutex lock(mHardwareLock);
476 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
477 status_t ret = mAudioHardware->setMicMute(state);
478 mHardwareStatus = AUDIO_HW_IDLE;
479 return ret;
480}
481
482bool AudioFlinger::getMicMute() const
483{
484 bool state = AudioSystem::MODE_INVALID;
485 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
486 mAudioHardware->getMicMute(&state);
487 mHardwareStatus = AUDIO_HW_IDLE;
488 return state;
489}
490
491status_t AudioFlinger::setMasterMute(bool muted)
492{
493 // check calling permissions
494 if (!settingsAllowed()) {
495 return PERMISSION_DENIED;
496 }
Eric Laurenta553c252009-07-17 12:17:14 -0700497
498 mMasterMute = muted;
499 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700500 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Eric Laurenta553c252009-07-17 12:17:14 -0700501
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700502 return NO_ERROR;
503}
504
505float AudioFlinger::masterVolume() const
506{
Eric Laurenta553c252009-07-17 12:17:14 -0700507 return mMasterVolume;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700508}
509
510bool AudioFlinger::masterMute() const
511{
Eric Laurenta553c252009-07-17 12:17:14 -0700512 return mMasterMute;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700513}
514
Eric Laurentddb78e72009-07-28 08:44:33 -0700515status_t AudioFlinger::setStreamVolume(int stream, float value, int output)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700516{
517 // check calling permissions
518 if (!settingsAllowed()) {
519 return PERMISSION_DENIED;
520 }
521
Eric Laurenta553c252009-07-17 12:17:14 -0700522 if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700523 return BAD_VALUE;
524 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800525
Eric Laurenta553c252009-07-17 12:17:14 -0700526 AutoMutex lock(mLock);
527 PlaybackThread *thread = NULL;
528 if (output) {
529 thread = checkPlaybackThread_l(output);
530 if (thread == NULL) {
531 return BAD_VALUE;
532 }
533 }
534
Eric Laurenta553c252009-07-17 12:17:14 -0700535 mStreamTypes[stream].volume = value;
536
537 if (thread == NULL) {
Eric Laurent415f3e22009-10-21 08:14:22 -0700538 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700539 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Eric Laurent415f3e22009-10-21 08:14:22 -0700540 }
Eric Laurenta553c252009-07-17 12:17:14 -0700541 } else {
542 thread->setStreamVolume(stream, value);
543 }
Eric Laurentef028272009-04-21 07:56:33 -0700544
Eric Laurent415f3e22009-10-21 08:14:22 -0700545 return NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700546}
547
548status_t AudioFlinger::setStreamMute(int stream, bool muted)
549{
550 // check calling permissions
551 if (!settingsAllowed()) {
552 return PERMISSION_DENIED;
553 }
554
Eric Laurenta553c252009-07-17 12:17:14 -0700555 if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES ||
Eric Laurenteeea9222009-03-26 01:57:59 -0700556 uint32_t(stream) == AudioSystem::ENFORCED_AUDIBLE) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700557 return BAD_VALUE;
558 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700559
Eric Laurenta553c252009-07-17 12:17:14 -0700560 mStreamTypes[stream].mute = muted;
561 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700562 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800563
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700564 return NO_ERROR;
565}
566
Eric Laurentddb78e72009-07-28 08:44:33 -0700567float AudioFlinger::streamVolume(int stream, int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700568{
Eric Laurenta553c252009-07-17 12:17:14 -0700569 if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700570 return 0.0f;
571 }
Eric Laurenta553c252009-07-17 12:17:14 -0700572
573 AutoMutex lock(mLock);
574 float volume;
575 if (output) {
576 PlaybackThread *thread = checkPlaybackThread_l(output);
577 if (thread == NULL) {
578 return 0.0f;
579 }
580 volume = thread->streamVolume(stream);
581 } else {
582 volume = mStreamTypes[stream].volume;
583 }
584
Eric Laurentef028272009-04-21 07:56:33 -0700585 return volume;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700586}
587
588bool AudioFlinger::streamMute(int stream) const
589{
Eric Laurenta553c252009-07-17 12:17:14 -0700590 if (stream < 0 || stream >= (int)AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700591 return true;
592 }
Eric Laurenta553c252009-07-17 12:17:14 -0700593
594 return mStreamTypes[stream].mute;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700595}
596
Eric Laurent23f25cd2010-01-25 08:49:09 -0800597bool AudioFlinger::isStreamActive(int stream) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700598{
Eric Laurent4e646332009-07-09 03:20:57 -0700599 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700600 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent23f25cd2010-01-25 08:49:09 -0800601 if (mPlaybackThreads.valueAt(i)->isStreamActive(stream)) {
Eric Laurenta553c252009-07-17 12:17:14 -0700602 return true;
603 }
604 }
605 return false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700606}
607
Eric Laurentddb78e72009-07-28 08:44:33 -0700608status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700609{
Eric Laurenta553c252009-07-17 12:17:14 -0700610 status_t result;
611
Eric Laurentddb78e72009-07-28 08:44:33 -0700612 LOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
Eric Laurenta553c252009-07-17 12:17:14 -0700613 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
614 // check calling permissions
615 if (!settingsAllowed()) {
616 return PERMISSION_DENIED;
The Android Open Source Project9266c552009-01-15 16:12:10 -0800617 }
Eric Laurenta553c252009-07-17 12:17:14 -0700618
Glenn Kasten871c16c2010-03-05 12:18:01 -0800619#ifdef LVMX
620 AudioParameter param = AudioParameter(keyValuePairs);
621 LifeVibes::setParameters(ioHandle,keyValuePairs);
622 String8 key = String8(AudioParameter::keyRouting);
623 int device;
624 if (NO_ERROR != param.getInt(key, device)) {
625 device = -1;
626 }
627
628 key = String8(LifevibesTag);
629 String8 value;
630 int musicEnabled = -1;
631 if (NO_ERROR == param.get(key, value)) {
632 if (value == LifevibesEnable) {
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700633 mLifeVibesClientPid = IPCThreadState::self()->getCallingPid();
Glenn Kasten871c16c2010-03-05 12:18:01 -0800634 musicEnabled = 1;
635 } else if (value == LifevibesDisable) {
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700636 mLifeVibesClientPid = -1;
Glenn Kasten871c16c2010-03-05 12:18:01 -0800637 musicEnabled = 0;
638 }
639 }
640#endif
641
Eric Laurenta553c252009-07-17 12:17:14 -0700642 // ioHandle == 0 means the parameters are global to the audio hardware interface
643 if (ioHandle == 0) {
644 AutoMutex lock(mHardwareLock);
645 mHardwareStatus = AUDIO_SET_PARAMETER;
646 result = mAudioHardware->setParameters(keyValuePairs);
Glenn Kasten871c16c2010-03-05 12:18:01 -0800647#ifdef LVMX
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700648 if (musicEnabled != -1) {
Glenn Kasten871c16c2010-03-05 12:18:01 -0800649 LifeVibes::enableMusic((bool) musicEnabled);
650 }
651#endif
Eric Laurenta553c252009-07-17 12:17:14 -0700652 mHardwareStatus = AUDIO_HW_IDLE;
653 return result;
654 }
655
Eric Laurentb7d94602009-09-29 11:12:57 -0700656 // hold a strong ref on thread in case closeOutput() or closeInput() is called
657 // and the thread is exited once the lock is released
658 sp<ThreadBase> thread;
659 {
660 Mutex::Autolock _l(mLock);
661 thread = checkPlaybackThread_l(ioHandle);
662 if (thread == NULL) {
663 thread = checkRecordThread_l(ioHandle);
664 }
Eric Laurenta553c252009-07-17 12:17:14 -0700665 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700666 if (thread != NULL) {
Glenn Kasten871c16c2010-03-05 12:18:01 -0800667 result = thread->setParameters(keyValuePairs);
668#ifdef LVMX
669 if ((NO_ERROR == result) && (device != -1)) {
670 LifeVibes::setDevice(LifeVibes::threadIdToAudioOutputType(thread->id()), device);
671 }
672#endif
673 return result;
Eric Laurenta553c252009-07-17 12:17:14 -0700674 }
Eric Laurenta553c252009-07-17 12:17:14 -0700675 return BAD_VALUE;
676}
677
Eric Laurentddb78e72009-07-28 08:44:33 -0700678String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
Eric Laurenta553c252009-07-17 12:17:14 -0700679{
Eric Laurentddb78e72009-07-28 08:44:33 -0700680// LOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
Eric Laurenta553c252009-07-17 12:17:14 -0700681// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
682
683 if (ioHandle == 0) {
684 return mAudioHardware->getParameters(keys);
685 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700686
687 Mutex::Autolock _l(mLock);
688
Eric Laurenta553c252009-07-17 12:17:14 -0700689 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
690 if (playbackThread != NULL) {
691 return playbackThread->getParameters(keys);
692 }
693 RecordThread *recordThread = checkRecordThread_l(ioHandle);
694 if (recordThread != NULL) {
695 return recordThread->getParameters(keys);
696 }
697 return String8("");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700698}
699
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800700size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
701{
702 return mAudioHardware->getInputBufferSize(sampleRate, format, channelCount);
703}
704
Eric Laurent47d0a922010-02-26 02:47:27 -0800705unsigned int AudioFlinger::getInputFramesLost(int ioHandle)
706{
707 if (ioHandle == 0) {
708 return 0;
709 }
710
711 Mutex::Autolock _l(mLock);
712
713 RecordThread *recordThread = checkRecordThread_l(ioHandle);
714 if (recordThread != NULL) {
715 return recordThread->getInputFramesLost();
716 }
717 return 0;
718}
719
Eric Laurent415f3e22009-10-21 08:14:22 -0700720status_t AudioFlinger::setVoiceVolume(float value)
721{
722 // check calling permissions
723 if (!settingsAllowed()) {
724 return PERMISSION_DENIED;
725 }
726
727 AutoMutex lock(mHardwareLock);
728 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
729 status_t ret = mAudioHardware->setVoiceVolume(value);
730 mHardwareStatus = AUDIO_HW_IDLE;
731
732 return ret;
733}
734
Eric Laurent0986e792010-01-19 17:37:09 -0800735status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int output)
736{
737 status_t status;
738
739 Mutex::Autolock _l(mLock);
740
741 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
742 if (playbackThread != NULL) {
743 return playbackThread->getRenderPosition(halFrames, dspFrames);
744 }
745
746 return BAD_VALUE;
747}
748
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800749void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
750{
Eric Laurenta553c252009-07-17 12:17:14 -0700751
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800752 Mutex::Autolock _l(mLock);
753
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700754 int pid = IPCThreadState::self()->getCallingPid();
755 if (mNotificationClients.indexOfKey(pid) < 0) {
756 sp<NotificationClient> notificationClient = new NotificationClient(this,
757 client,
758 pid);
759 LOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Eric Laurenta553c252009-07-17 12:17:14 -0700760
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700761 mNotificationClients.add(pid, notificationClient);
Eric Laurenta553c252009-07-17 12:17:14 -0700762
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700763 sp<IBinder> binder = client->asBinder();
764 binder->linkToDeath(notificationClient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800765
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700766 // the config change is always sent from playback or record threads to avoid deadlock
767 // with AudioSystem::gLock
768 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
769 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
770 }
Eric Laurenta553c252009-07-17 12:17:14 -0700771
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700772 for (size_t i = 0; i < mRecordThreads.size(); i++) {
773 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800774 }
775 }
776}
777
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700778void AudioFlinger::removeNotificationClient(pid_t pid)
779{
780 Mutex::Autolock _l(mLock);
781
782 int index = mNotificationClients.indexOfKey(pid);
783 if (index >= 0) {
784 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
785 LOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
786#ifdef LVMX
787 if (pid == mLifeVibesClientPid) {
788 LOGV("Disabling lifevibes");
789 LifeVibes::enableMusic(false);
790 mLifeVibesClientPid = -1;
791 }
792#endif
793 mNotificationClients.removeItem(pid);
794 }
795}
796
Eric Laurent296a0ec2009-09-15 07:10:12 -0700797// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700798void AudioFlinger::audioConfigChanged_l(int event, int ioHandle, void *param2)
799{
Eric Laurent49f02be2009-11-19 09:00:56 -0800800 size_t size = mNotificationClients.size();
801 for (size_t i = 0; i < size; i++) {
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700802 mNotificationClients.valueAt(i)->client()->ioConfigChanged(event, ioHandle, param2);
Eric Laurenta553c252009-07-17 12:17:14 -0700803 }
804}
805
Eric Laurentb9481d82009-09-17 05:12:56 -0700806// removeClient_l() must be called with AudioFlinger::mLock held
807void AudioFlinger::removeClient_l(pid_t pid)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700808{
Eric Laurentb9481d82009-09-17 05:12:56 -0700809 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 -0700810 mClients.removeItem(pid);
811}
812
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700813
Eric Laurenta553c252009-07-17 12:17:14 -0700814// ----------------------------------------------------------------------------
815
Eric Laurent49f02be2009-11-19 09:00:56 -0800816AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, int id)
Eric Laurenta553c252009-07-17 12:17:14 -0700817 : Thread(false),
818 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
Eric Laurentb0a01472010-05-14 05:45:46 -0700819 mFrameSize(1), mFormat(0), mStandby(false), mId(id), mExiting(false)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700820{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800821}
822
Eric Laurenta553c252009-07-17 12:17:14 -0700823AudioFlinger::ThreadBase::~ThreadBase()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800824{
Eric Laurent8fce46a2009-08-04 09:45:33 -0700825 mParamCond.broadcast();
826 mNewParameters.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800827}
828
Eric Laurenta553c252009-07-17 12:17:14 -0700829void AudioFlinger::ThreadBase::exit()
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700830{
Eric Laurentb7d94602009-09-29 11:12:57 -0700831 // keep a strong ref on ourself so that we wont get
Eric Laurenta553c252009-07-17 12:17:14 -0700832 // destroyed in the middle of requestExitAndWait()
833 sp <ThreadBase> strongMe = this;
834
835 LOGV("ThreadBase::exit");
836 {
837 AutoMutex lock(&mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -0800838 mExiting = true;
Eric Laurenta553c252009-07-17 12:17:14 -0700839 requestExit();
840 mWaitWorkCV.signal();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700841 }
Eric Laurenta553c252009-07-17 12:17:14 -0700842 requestExitAndWait();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700843}
Eric Laurenta553c252009-07-17 12:17:14 -0700844
845uint32_t AudioFlinger::ThreadBase::sampleRate() const
846{
847 return mSampleRate;
848}
849
850int AudioFlinger::ThreadBase::channelCount() const
851{
Eric Laurentb0a01472010-05-14 05:45:46 -0700852 return (int)mChannelCount;
Eric Laurenta553c252009-07-17 12:17:14 -0700853}
854
855int AudioFlinger::ThreadBase::format() const
856{
857 return mFormat;
858}
859
860size_t AudioFlinger::ThreadBase::frameCount() const
861{
862 return mFrameCount;
863}
864
865status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
866{
Eric Laurent8fce46a2009-08-04 09:45:33 -0700867 status_t status;
Eric Laurenta553c252009-07-17 12:17:14 -0700868
Eric Laurent8fce46a2009-08-04 09:45:33 -0700869 LOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Eric Laurenta553c252009-07-17 12:17:14 -0700870 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700871
Eric Laurent8fce46a2009-08-04 09:45:33 -0700872 mNewParameters.add(keyValuePairs);
Eric Laurenta553c252009-07-17 12:17:14 -0700873 mWaitWorkCV.signal();
Eric Laurentb7d94602009-09-29 11:12:57 -0700874 // wait condition with timeout in case the thread loop has exited
875 // before the request could be processed
876 if (mParamCond.waitRelative(mLock, seconds(2)) == NO_ERROR) {
877 status = mParamStatus;
878 mWaitWorkCV.signal();
879 } else {
880 status = TIMED_OUT;
881 }
Eric Laurent8fce46a2009-08-04 09:45:33 -0700882 return status;
Eric Laurenta553c252009-07-17 12:17:14 -0700883}
884
885void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
886{
887 Mutex::Autolock _l(mLock);
Eric Laurent8fce46a2009-08-04 09:45:33 -0700888 sendConfigEvent_l(event, param);
889}
890
891// sendConfigEvent_l() must be called with ThreadBase::mLock held
892void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
893{
Eric Laurenta553c252009-07-17 12:17:14 -0700894 ConfigEvent *configEvent = new ConfigEvent();
895 configEvent->mEvent = event;
896 configEvent->mParam = param;
897 mConfigEvents.add(configEvent);
898 LOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
899 mWaitWorkCV.signal();
900}
901
902void AudioFlinger::ThreadBase::processConfigEvents()
903{
904 mLock.lock();
905 while(!mConfigEvents.isEmpty()) {
906 LOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
907 ConfigEvent *configEvent = mConfigEvents[0];
908 mConfigEvents.removeAt(0);
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700909 // release mLock before locking AudioFlinger mLock: lock order is always
910 // AudioFlinger then ThreadBase to avoid cross deadlock
Eric Laurenta553c252009-07-17 12:17:14 -0700911 mLock.unlock();
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700912 mAudioFlinger->mLock.lock();
913 audioConfigChanged_l(configEvent->mEvent, configEvent->mParam);
914 mAudioFlinger->mLock.unlock();
Eric Laurenta553c252009-07-17 12:17:14 -0700915 delete configEvent;
916 mLock.lock();
917 }
918 mLock.unlock();
919}
920
Eric Laurent3fdb1262009-11-07 00:01:32 -0800921status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
922{
923 const size_t SIZE = 256;
924 char buffer[SIZE];
925 String8 result;
926
927 bool locked = tryLock(mLock);
928 if (!locked) {
929 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
930 write(fd, buffer, strlen(buffer));
931 }
932
933 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
934 result.append(buffer);
935 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
936 result.append(buffer);
937 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
938 result.append(buffer);
939 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
940 result.append(buffer);
941 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
942 result.append(buffer);
943 snprintf(buffer, SIZE, "Frame size: %d\n", mFrameSize);
944 result.append(buffer);
945
946 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
947 result.append(buffer);
948 result.append(" Index Command");
949 for (size_t i = 0; i < mNewParameters.size(); ++i) {
950 snprintf(buffer, SIZE, "\n %02d ", i);
951 result.append(buffer);
952 result.append(mNewParameters[i]);
953 }
954
955 snprintf(buffer, SIZE, "\n\nPending config events: \n");
956 result.append(buffer);
957 snprintf(buffer, SIZE, " Index event param\n");
958 result.append(buffer);
959 for (size_t i = 0; i < mConfigEvents.size(); i++) {
960 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i]->mEvent, mConfigEvents[i]->mParam);
961 result.append(buffer);
962 }
963 result.append("\n");
964
965 write(fd, result.string(), result.size());
966
967 if (locked) {
968 mLock.unlock();
969 }
970 return NO_ERROR;
971}
972
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800973
974// ----------------------------------------------------------------------------
975
Eric Laurent65b65452010-06-01 23:49:17 -0700976AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Eric Laurent49f02be2009-11-19 09:00:56 -0800977 : ThreadBase(audioFlinger, id),
Eric Laurentd5603c12009-08-06 08:49:39 -0700978 mMixBuffer(0), mSuspended(0), mBytesWritten(0), mOutput(output),
Eric Laurent65b65452010-06-01 23:49:17 -0700979 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
980 mDevice(device)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800981{
Eric Laurenta553c252009-07-17 12:17:14 -0700982 readOutputParameters();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800983
Eric Laurenta553c252009-07-17 12:17:14 -0700984 mMasterVolume = mAudioFlinger->masterVolume();
985 mMasterMute = mAudioFlinger->masterMute();
986
987 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
988 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
989 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800990 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800991}
992
Eric Laurenta553c252009-07-17 12:17:14 -0700993AudioFlinger::PlaybackThread::~PlaybackThread()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800994{
995 delete [] mMixBuffer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800996}
997
Eric Laurenta553c252009-07-17 12:17:14 -0700998status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800999{
1000 dumpInternals(fd, args);
1001 dumpTracks(fd, args);
Eric Laurent65b65452010-06-01 23:49:17 -07001002 dumpEffectChains(fd, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001003 return NO_ERROR;
1004}
1005
Eric Laurenta553c252009-07-17 12:17:14 -07001006status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001007{
1008 const size_t SIZE = 256;
1009 char buffer[SIZE];
1010 String8 result;
1011
Eric Laurenta553c252009-07-17 12:17:14 -07001012 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001013 result.append(buffer);
Eric Laurent65b65452010-06-01 23:49:17 -07001014 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 -08001015 for (size_t i = 0; i < mTracks.size(); ++i) {
Eric Laurentd3b4d0c2009-03-31 14:34:35 -07001016 sp<Track> track = mTracks[i];
1017 if (track != 0) {
1018 track->dump(buffer, SIZE);
1019 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001020 }
1021 }
1022
Eric Laurenta553c252009-07-17 12:17:14 -07001023 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001024 result.append(buffer);
Eric Laurent65b65452010-06-01 23:49:17 -07001025 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 -08001026 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Eric Laurentd3b4d0c2009-03-31 14:34:35 -07001027 wp<Track> wTrack = mActiveTracks[i];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001028 if (wTrack != 0) {
1029 sp<Track> track = wTrack.promote();
1030 if (track != 0) {
1031 track->dump(buffer, SIZE);
1032 result.append(buffer);
1033 }
1034 }
1035 }
1036 write(fd, result.string(), result.size());
1037 return NO_ERROR;
1038}
1039
Eric Laurent65b65452010-06-01 23:49:17 -07001040status_t AudioFlinger::PlaybackThread::dumpEffectChains(int fd, const Vector<String16>& args)
1041{
1042 const size_t SIZE = 256;
1043 char buffer[SIZE];
1044 String8 result;
1045
1046 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1047 write(fd, buffer, strlen(buffer));
1048
1049 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1050 sp<EffectChain> chain = mEffectChains[i];
1051 if (chain != 0) {
1052 chain->dump(fd, args);
1053 }
1054 }
1055 return NO_ERROR;
1056}
1057
Eric Laurenta553c252009-07-17 12:17:14 -07001058status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001059{
1060 const size_t SIZE = 256;
1061 char buffer[SIZE];
1062 String8 result;
1063
Eric Laurent3fdb1262009-11-07 00:01:32 -08001064 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001065 result.append(buffer);
1066 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1067 result.append(buffer);
1068 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1069 result.append(buffer);
1070 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1071 result.append(buffer);
1072 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1073 result.append(buffer);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08001074 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1075 result.append(buffer);
Eric Laurent65b65452010-06-01 23:49:17 -07001076 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1077 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001078 write(fd, result.string(), result.size());
Eric Laurent3fdb1262009-11-07 00:01:32 -08001079
1080 dumpBase(fd, args);
1081
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001082 return NO_ERROR;
1083}
1084
1085// Thread virtuals
Eric Laurenta553c252009-07-17 12:17:14 -07001086status_t AudioFlinger::PlaybackThread::readyToRun()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001087{
1088 if (mSampleRate == 0) {
1089 LOGE("No working audio driver found.");
1090 return NO_INIT;
1091 }
Eric Laurenta553c252009-07-17 12:17:14 -07001092 LOGI("AudioFlinger's thread %p ready to run", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001093 return NO_ERROR;
1094}
1095
Eric Laurenta553c252009-07-17 12:17:14 -07001096void AudioFlinger::PlaybackThread::onFirstRef()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001097{
1098 const size_t SIZE = 256;
1099 char buffer[SIZE];
1100
Eric Laurenta553c252009-07-17 12:17:14 -07001101 snprintf(buffer, SIZE, "Playback Thread %p", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001102
1103 run(buffer, ANDROID_PRIORITY_URGENT_AUDIO);
1104}
1105
Eric Laurenta553c252009-07-17 12:17:14 -07001106// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1107sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001108 const sp<AudioFlinger::Client>& client,
1109 int streamType,
1110 uint32_t sampleRate,
1111 int format,
1112 int channelCount,
1113 int frameCount,
1114 const sp<IMemory>& sharedBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -07001115 int sessionId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001116 status_t *status)
1117{
1118 sp<Track> track;
1119 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07001120
1121 if (mType == DIRECT) {
Eric Laurentb0a01472010-05-14 05:45:46 -07001122 if (sampleRate != mSampleRate || format != mFormat || channelCount != (int)mChannelCount) {
Eric Laurenta553c252009-07-17 12:17:14 -07001123 LOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelCount %d for output %p",
1124 sampleRate, format, channelCount, mOutput);
1125 lStatus = BAD_VALUE;
1126 goto Exit;
1127 }
1128 } else {
1129 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1130 if (sampleRate > mSampleRate*2) {
1131 LOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
1132 lStatus = BAD_VALUE;
1133 goto Exit;
1134 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001135 }
1136
Eric Laurenta553c252009-07-17 12:17:14 -07001137 if (mOutput == 0) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001138 LOGE("Audio driver not initialized.");
1139 lStatus = NO_INIT;
1140 goto Exit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001141 }
1142
Eric Laurenta553c252009-07-17 12:17:14 -07001143 { // scope for mLock
1144 Mutex::Autolock _l(mLock);
1145 track = new Track(this, client, streamType, sampleRate, format,
Eric Laurent65b65452010-06-01 23:49:17 -07001146 channelCount, frameCount, sharedBuffer, sessionId);
Eric Laurent73b60352009-11-09 04:45:39 -08001147 if (track->getCblk() == NULL || track->name() < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07001148 lStatus = NO_MEMORY;
1149 goto Exit;
1150 }
1151 mTracks.add(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001152
1153 sp<EffectChain> chain = getEffectChain_l(sessionId);
1154 if (chain != 0) {
1155 LOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1156 track->setMainBuffer(chain->inBuffer());
1157 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001158 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001159 lStatus = NO_ERROR;
1160
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001161Exit:
1162 if(status) {
1163 *status = lStatus;
1164 }
1165 return track;
1166}
1167
Eric Laurenta553c252009-07-17 12:17:14 -07001168uint32_t AudioFlinger::PlaybackThread::latency() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001169{
1170 if (mOutput) {
1171 return mOutput->latency();
1172 }
1173 else {
1174 return 0;
1175 }
1176}
1177
Eric Laurenta553c252009-07-17 12:17:14 -07001178status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001179{
Glenn Kasten871c16c2010-03-05 12:18:01 -08001180#ifdef LVMX
1181 int audioOutputType = LifeVibes::getMixerType(mId, mType);
1182 if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType)) {
1183 LifeVibes::setMasterVolume(audioOutputType, value);
1184 }
1185#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001186 mMasterVolume = value;
1187 return NO_ERROR;
1188}
1189
Eric Laurenta553c252009-07-17 12:17:14 -07001190status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001191{
Glenn Kasten871c16c2010-03-05 12:18:01 -08001192#ifdef LVMX
1193 int audioOutputType = LifeVibes::getMixerType(mId, mType);
1194 if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType)) {
1195 LifeVibes::setMasterMute(audioOutputType, muted);
1196 }
1197#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001198 mMasterMute = muted;
1199 return NO_ERROR;
1200}
1201
Eric Laurenta553c252009-07-17 12:17:14 -07001202float AudioFlinger::PlaybackThread::masterVolume() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001203{
1204 return mMasterVolume;
1205}
1206
Eric Laurenta553c252009-07-17 12:17:14 -07001207bool AudioFlinger::PlaybackThread::masterMute() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001208{
1209 return mMasterMute;
1210}
1211
Eric Laurenta553c252009-07-17 12:17:14 -07001212status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001213{
Glenn Kasten871c16c2010-03-05 12:18:01 -08001214#ifdef LVMX
1215 int audioOutputType = LifeVibes::getMixerType(mId, mType);
1216 if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType)) {
1217 LifeVibes::setStreamVolume(audioOutputType, stream, value);
1218 }
1219#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001220 mStreamTypes[stream].volume = value;
1221 return NO_ERROR;
1222}
1223
Eric Laurenta553c252009-07-17 12:17:14 -07001224status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001225{
Glenn Kasten871c16c2010-03-05 12:18:01 -08001226#ifdef LVMX
1227 int audioOutputType = LifeVibes::getMixerType(mId, mType);
1228 if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType)) {
1229 LifeVibes::setStreamMute(audioOutputType, stream, muted);
1230 }
1231#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001232 mStreamTypes[stream].mute = muted;
1233 return NO_ERROR;
1234}
1235
Eric Laurenta553c252009-07-17 12:17:14 -07001236float AudioFlinger::PlaybackThread::streamVolume(int stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001237{
1238 return mStreamTypes[stream].volume;
1239}
1240
Eric Laurenta553c252009-07-17 12:17:14 -07001241bool AudioFlinger::PlaybackThread::streamMute(int stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001242{
1243 return mStreamTypes[stream].mute;
1244}
1245
Eric Laurent23f25cd2010-01-25 08:49:09 -08001246bool AudioFlinger::PlaybackThread::isStreamActive(int stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001247{
Eric Laurenta553c252009-07-17 12:17:14 -07001248 Mutex::Autolock _l(mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001249 size_t count = mActiveTracks.size();
1250 for (size_t i = 0 ; i < count ; ++i) {
1251 sp<Track> t = mActiveTracks[i].promote();
1252 if (t == 0) continue;
1253 Track* const track = t.get();
Eric Laurent23f25cd2010-01-25 08:49:09 -08001254 if (t->type() == stream)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001255 return true;
1256 }
1257 return false;
1258}
1259
Eric Laurenta553c252009-07-17 12:17:14 -07001260// addTrack_l() must be called with ThreadBase::mLock held
1261status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001262{
1263 status_t status = ALREADY_EXISTS;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001264
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001265 // set retry count for buffer fill
1266 track->mRetryCount = kMaxTrackStartupRetries;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001267 if (mActiveTracks.indexOf(track) < 0) {
1268 // the track is newly added, make sure it fills up all its
1269 // buffers before playing. This is to ensure the client will
1270 // effectively get the latency it requested.
1271 track->mFillingUpStatus = Track::FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001272 track->mResetDone = false;
Eric Laurenta553c252009-07-17 12:17:14 -07001273 mActiveTracks.add(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001274 if (track->mainBuffer() != mMixBuffer) {
1275 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1276 if (chain != 0) {
1277 LOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
1278 chain->startTrack();
1279 }
1280 }
1281
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001282 status = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001283 }
Eric Laurenta553c252009-07-17 12:17:14 -07001284
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001285 LOGV("mWaitWorkCV.broadcast");
Eric Laurenta553c252009-07-17 12:17:14 -07001286 mWaitWorkCV.broadcast();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001287
1288 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001289}
1290
Eric Laurenta553c252009-07-17 12:17:14 -07001291// destroyTrack_l() must be called with ThreadBase::mLock held
1292void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001293{
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001294 track->mState = TrackBase::TERMINATED;
1295 if (mActiveTracks.indexOf(track) < 0) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001296 mTracks.remove(track);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001297 deleteTrackName_l(track->name());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001298 }
1299}
1300
Eric Laurenta553c252009-07-17 12:17:14 -07001301String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001302{
Eric Laurenta553c252009-07-17 12:17:14 -07001303 return mOutput->getParameters(keys);
1304}
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001305
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001306// destroyTrack_l() must be called with AudioFlinger::mLock held
1307void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
Eric Laurenta553c252009-07-17 12:17:14 -07001308 AudioSystem::OutputDescriptor desc;
1309 void *param2 = 0;
1310
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001311 LOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Eric Laurenta553c252009-07-17 12:17:14 -07001312
1313 switch (event) {
1314 case AudioSystem::OUTPUT_OPENED:
1315 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Eric Laurentb0a01472010-05-14 05:45:46 -07001316 desc.channels = mChannels;
Eric Laurenta553c252009-07-17 12:17:14 -07001317 desc.samplingRate = mSampleRate;
1318 desc.format = mFormat;
1319 desc.frameCount = mFrameCount;
1320 desc.latency = latency();
1321 param2 = &desc;
1322 break;
1323
1324 case AudioSystem::STREAM_CONFIG_CHANGED:
1325 param2 = &param;
1326 case AudioSystem::OUTPUT_CLOSED:
1327 default:
1328 break;
1329 }
Eric Laurent49f02be2009-11-19 09:00:56 -08001330 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurenta553c252009-07-17 12:17:14 -07001331}
1332
1333void AudioFlinger::PlaybackThread::readOutputParameters()
1334{
1335 mSampleRate = mOutput->sampleRate();
Eric Laurentb0a01472010-05-14 05:45:46 -07001336 mChannels = mOutput->channels();
1337 mChannelCount = (uint16_t)AudioSystem::popCount(mChannels);
Eric Laurenta553c252009-07-17 12:17:14 -07001338 mFormat = mOutput->format();
Eric Laurentb0a01472010-05-14 05:45:46 -07001339 mFrameSize = (uint16_t)mOutput->frameSize();
Eric Laurenta553c252009-07-17 12:17:14 -07001340 mFrameCount = mOutput->bufferSize() / mFrameSize;
1341
Eric Laurenta553c252009-07-17 12:17:14 -07001342 // FIXME - Current mixer implementation only supports stereo output: Always
1343 // Allocate a stereo buffer even if HW output is mono.
Eric Laurent65b65452010-06-01 23:49:17 -07001344 if (mMixBuffer != NULL) delete[] mMixBuffer;
Eric Laurenta553c252009-07-17 12:17:14 -07001345 mMixBuffer = new int16_t[mFrameCount * 2];
1346 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
Eric Laurent65b65452010-06-01 23:49:17 -07001347
1348 //TODO handle effects reconfig
Eric Laurenta553c252009-07-17 12:17:14 -07001349}
1350
Eric Laurent0986e792010-01-19 17:37:09 -08001351status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1352{
1353 if (halFrames == 0 || dspFrames == 0) {
1354 return BAD_VALUE;
1355 }
1356 if (mOutput == 0) {
1357 return INVALID_OPERATION;
1358 }
1359 *halFrames = mBytesWritten/mOutput->frameSize();
1360
1361 return mOutput->getRenderPosition(dspFrames);
1362}
1363
Eric Laurent65b65452010-06-01 23:49:17 -07001364bool AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
1365{
1366 Mutex::Autolock _l(mLock);
1367 if (getEffectChain_l(sessionId) != 0) {
1368 return true;
1369 }
1370
1371 for (size_t i = 0; i < mTracks.size(); ++i) {
1372 sp<Track> track = mTracks[i];
1373 if (sessionId == track->sessionId()) {
1374 return true;
1375 }
1376 }
1377
1378 return false;
1379}
1380
1381sp<AudioFlinger::EffectChain> AudioFlinger::PlaybackThread::getEffectChain(int sessionId)
1382{
1383 Mutex::Autolock _l(mLock);
1384 return getEffectChain_l(sessionId);
1385}
1386
1387sp<AudioFlinger::EffectChain> AudioFlinger::PlaybackThread::getEffectChain_l(int sessionId)
1388{
1389 sp<EffectChain> chain;
1390
1391 size_t size = mEffectChains.size();
1392 for (size_t i = 0; i < size; i++) {
1393 if (mEffectChains[i]->sessionId() == sessionId) {
1394 chain = mEffectChains[i];
1395 break;
1396 }
1397 }
1398 return chain;
1399}
1400
Eric Laurent53334cd2010-06-23 17:38:20 -07001401void AudioFlinger::PlaybackThread::setMode(uint32_t mode)
1402{
1403 Mutex::Autolock _l(mLock);
1404 size_t size = mEffectChains.size();
1405 for (size_t i = 0; i < size; i++) {
1406 mEffectChains[i]->setMode(mode);
1407 }
1408}
1409
Eric Laurenta553c252009-07-17 12:17:14 -07001410// ----------------------------------------------------------------------------
1411
Eric Laurent65b65452010-06-01 23:49:17 -07001412AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
1413 : PlaybackThread(audioFlinger, output, id, device),
Eric Laurenta553c252009-07-17 12:17:14 -07001414 mAudioMixer(0)
1415{
1416 mType = PlaybackThread::MIXER;
1417 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1418
1419 // FIXME - Current mixer implementation only supports stereo output
1420 if (mChannelCount == 1) {
1421 LOGE("Invalid audio hardware channel count");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001422 }
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001423}
1424
Eric Laurenta553c252009-07-17 12:17:14 -07001425AudioFlinger::MixerThread::~MixerThread()
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001426{
Eric Laurenta553c252009-07-17 12:17:14 -07001427 delete mAudioMixer;
1428}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001429
Eric Laurenta553c252009-07-17 12:17:14 -07001430bool AudioFlinger::MixerThread::threadLoop()
1431{
Eric Laurenta553c252009-07-17 12:17:14 -07001432 Vector< sp<Track> > tracksToRemove;
Eric Laurent059b4be2009-11-09 23:32:22 -08001433 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001434 nsecs_t standbyTime = systemTime();
1435 size_t mixBufferSize = mFrameCount * mFrameSize;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001436 // FIXME: Relaxed timing because of a certain device that can't meet latency
1437 // Should be reduced to 2x after the vendor fixes the driver issue
1438 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
1439 nsecs_t lastWarning = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08001440 bool longStandbyExit = false;
1441 uint32_t activeSleepTime = activeSleepTimeUs();
1442 uint32_t idleSleepTime = idleSleepTimeUs();
1443 uint32_t sleepTime = idleSleepTime;
Eric Laurent65b65452010-06-01 23:49:17 -07001444 Vector< sp<EffectChain> > effectChains;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001445
Eric Laurenta553c252009-07-17 12:17:14 -07001446 while (!exitPending())
1447 {
1448 processConfigEvents();
1449
Eric Laurent059b4be2009-11-09 23:32:22 -08001450 mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001451 { // scope for mLock
1452
1453 Mutex::Autolock _l(mLock);
1454
1455 if (checkForNewParameters_l()) {
1456 mixBufferSize = mFrameCount * mFrameSize;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001457 // FIXME: Relaxed timing because of a certain device that can't meet latency
1458 // Should be reduced to 2x after the vendor fixes the driver issue
1459 maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
Eric Laurent059b4be2009-11-09 23:32:22 -08001460 activeSleepTime = activeSleepTimeUs();
1461 idleSleepTime = idleSleepTimeUs();
Eric Laurenta553c252009-07-17 12:17:14 -07001462 }
1463
1464 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1465
1466 // put audio hardware into standby after short delay
1467 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1468 mSuspended) {
1469 if (!mStandby) {
1470 LOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
1471 mOutput->standby();
1472 mStandby = true;
1473 mBytesWritten = 0;
1474 }
1475
1476 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1477 // we're about to wait, flush the binder command buffer
1478 IPCThreadState::self()->flushCommands();
1479
1480 if (exitPending()) break;
1481
1482 // wait until we have something to do...
1483 LOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
1484 mWaitWorkCV.wait(mLock);
1485 LOGV("MixerThread %p TID %d waking up\n", this, gettid());
1486
1487 if (mMasterMute == false) {
1488 char value[PROPERTY_VALUE_MAX];
1489 property_get("ro.audio.silent", value, "0");
1490 if (atoi(value)) {
1491 LOGD("Silence is golden");
1492 setMasterMute(true);
1493 }
1494 }
1495
1496 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent059b4be2009-11-09 23:32:22 -08001497 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07001498 continue;
1499 }
1500 }
1501
Eric Laurent059b4be2009-11-09 23:32:22 -08001502 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07001503
1504 // prevent any changes in effect chain list and in each effect chain
1505 // during mixing and effect process as the audio buffers could be deleted
1506 // or modified if an effect is created or deleted
1507 effectChains = mEffectChains;
1508 lockEffectChains_l();
Eric Laurenta553c252009-07-17 12:17:14 -07001509 }
1510
Eric Laurent059b4be2009-11-09 23:32:22 -08001511 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07001512 // mix buffers...
Eric Laurent65b65452010-06-01 23:49:17 -07001513 mAudioMixer->process();
Eric Laurentf69a3f82009-09-22 00:35:48 -07001514 sleepTime = 0;
1515 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent65b65452010-06-01 23:49:17 -07001516 //TODO: delay standby when effects have a tail
Eric Laurent96c08a62009-09-07 08:38:38 -07001517 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07001518 // If no tracks are ready, sleep once for the duration of an output
1519 // buffer size, then write 0s to the output
1520 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08001521 if (mixerStatus == MIXER_TRACKS_ENABLED) {
1522 sleepTime = activeSleepTime;
1523 } else {
1524 sleepTime = idleSleepTime;
1525 }
1526 } else if (mBytesWritten != 0 ||
1527 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Eric Laurent65b65452010-06-01 23:49:17 -07001528 memset (mMixBuffer, 0, mixBufferSize);
Eric Laurent96c08a62009-09-07 08:38:38 -07001529 sleepTime = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08001530 LOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Eric Laurent96c08a62009-09-07 08:38:38 -07001531 }
Eric Laurent65b65452010-06-01 23:49:17 -07001532 // TODO add standby time extension fct of effect tail
Eric Laurentf69a3f82009-09-22 00:35:48 -07001533 }
1534
1535 if (mSuspended) {
Eric Laurent059b4be2009-11-09 23:32:22 -08001536 sleepTime = idleSleepTime;
Eric Laurentf69a3f82009-09-22 00:35:48 -07001537 }
1538 // sleepTime == 0 means we must write to audio hardware
1539 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07001540 for (size_t i = 0; i < effectChains.size(); i ++) {
1541 effectChains[i]->process_l();
1542 }
1543 // enable changes in effect chain
1544 unlockEffectChains();
Glenn Kasten871c16c2010-03-05 12:18:01 -08001545#ifdef LVMX
1546 int audioOutputType = LifeVibes::getMixerType(mId, mType);
1547 if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType)) {
Eric Laurent65b65452010-06-01 23:49:17 -07001548 LifeVibes::process(audioOutputType, mMixBuffer, mixBufferSize);
Glenn Kasten871c16c2010-03-05 12:18:01 -08001549 }
1550#endif
Eric Laurent65b65452010-06-01 23:49:17 -07001551 mLastWriteTime = systemTime();
1552 mInWrite = true;
1553 mBytesWritten += mixBufferSize;
1554
1555 int bytesWritten = (int)mOutput->write(mMixBuffer, mixBufferSize);
Eric Laurent0986e792010-01-19 17:37:09 -08001556 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07001557 mNumWrites++;
1558 mInWrite = false;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001559 nsecs_t now = systemTime();
1560 nsecs_t delta = now - mLastWriteTime;
Eric Laurentf69a3f82009-09-22 00:35:48 -07001561 if (delta > maxPeriod) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07001562 mNumDelayedWrites++;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001563 if ((now - lastWarning) > kWarningThrottle) {
1564 LOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
1565 ns2ms(delta), mNumDelayedWrites, this);
1566 lastWarning = now;
1567 }
Eric Laurent059b4be2009-11-09 23:32:22 -08001568 if (mStandby) {
1569 longStandbyExit = true;
1570 }
Eric Laurenta553c252009-07-17 12:17:14 -07001571 }
Eric Laurent059b4be2009-11-09 23:32:22 -08001572 mStandby = false;
Eric Laurentf69a3f82009-09-22 00:35:48 -07001573 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07001574 // enable changes in effect chain
1575 unlockEffectChains();
Eric Laurentf69a3f82009-09-22 00:35:48 -07001576 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07001577 }
1578
1579 // finally let go of all our tracks, without the lock held
1580 // since we can't guarantee the destructors won't acquire that
1581 // same lock.
1582 tracksToRemove.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07001583
1584 // Effect chains will be actually deleted here if they were removed from
1585 // mEffectChains list during mixing or effects processing
1586 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07001587 }
1588
1589 if (!mStandby) {
1590 mOutput->standby();
1591 }
Eric Laurenta553c252009-07-17 12:17:14 -07001592
1593 LOGV("MixerThread %p exiting", this);
1594 return false;
1595}
1596
1597// prepareTracks_l() must be called with ThreadBase::mLock held
Eric Laurent059b4be2009-11-09 23:32:22 -08001598uint32_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
Eric Laurenta553c252009-07-17 12:17:14 -07001599{
1600
Eric Laurent059b4be2009-11-09 23:32:22 -08001601 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001602 // find out which tracks need to be processed
1603 size_t count = activeTracks.size();
Eric Laurent65b65452010-06-01 23:49:17 -07001604 size_t mixedTracks = 0;
1605 size_t tracksWithEffect = 0;
Glenn Kasten871c16c2010-03-05 12:18:01 -08001606
1607 float masterVolume = mMasterVolume;
1608 bool masterMute = mMasterMute;
1609
1610#ifdef LVMX
1611 bool tracksConnectedChanged = false;
1612 bool stateChanged = false;
1613
1614 int audioOutputType = LifeVibes::getMixerType(mId, mType);
1615 if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType))
1616 {
1617 int activeTypes = 0;
1618 for (size_t i=0 ; i<count ; i++) {
1619 sp<Track> t = activeTracks[i].promote();
1620 if (t == 0) continue;
1621 Track* const track = t.get();
1622 int iTracktype=track->type();
1623 activeTypes |= 1<<track->type();
1624 }
1625 LifeVibes::computeVolumes(audioOutputType, activeTypes, tracksConnectedChanged, stateChanged, masterVolume, masterMute);
1626 }
1627#endif
Eric Laurent65b65452010-06-01 23:49:17 -07001628 // Delegate master volume control to effect in output mix effect chain if needed
1629 sp<EffectChain> chain = getEffectChain_l(0);
1630 if (chain != 0) {
1631 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
1632 chain->setVolume(&v, &v);
1633 masterVolume = (float)((v + (1 << 23)) >> 24);
1634 chain.clear();
1635 }
Glenn Kasten871c16c2010-03-05 12:18:01 -08001636
Eric Laurenta553c252009-07-17 12:17:14 -07001637 for (size_t i=0 ; i<count ; i++) {
1638 sp<Track> t = activeTracks[i].promote();
1639 if (t == 0) continue;
1640
1641 Track* const track = t.get();
1642 audio_track_cblk_t* cblk = track->cblk();
1643
1644 // The first time a track is added we wait
1645 // for all its buffers to be filled before processing it
1646 mAudioMixer->setActiveTrack(track->name());
1647 if (cblk->framesReady() && (track->isReady() || track->isStopped()) &&
Eric Laurent71f37cd2010-03-31 12:21:17 -07001648 !track->isPaused() && !track->isTerminated())
Eric Laurenta553c252009-07-17 12:17:14 -07001649 {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08001650 //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 -07001651
Eric Laurent65b65452010-06-01 23:49:17 -07001652 mixedTracks++;
1653
1654 // track->mainBuffer() != mMixBuffer means there is an effect chain
1655 // connected to the track
1656 chain.clear();
1657 if (track->mainBuffer() != mMixBuffer) {
1658 chain = getEffectChain_l(track->sessionId());
1659 // Delegate volume control to effect in track effect chain if needed
1660 if (chain != 0) {
1661 tracksWithEffect++;
1662 } else {
1663 LOGW("prepareTracks_l(): track %08x attached to effect but no chain found on session %d",
1664 track->name(), track->sessionId());
1665 }
1666 }
1667
1668
1669 int param = AudioMixer::VOLUME;
1670 if (track->mFillingUpStatus == Track::FS_FILLED) {
1671 // no ramp for the first volume setting
1672 track->mFillingUpStatus = Track::FS_ACTIVE;
1673 if (track->mState == TrackBase::RESUMING) {
1674 track->mState = TrackBase::ACTIVE;
1675 param = AudioMixer::RAMP_VOLUME;
1676 }
1677 } else if (cblk->server != 0) {
1678 // If the track is stopped before the first frame was mixed,
1679 // do not apply ramp
1680 param = AudioMixer::RAMP_VOLUME;
1681 }
1682
Eric Laurenta553c252009-07-17 12:17:14 -07001683 // compute volume for this track
Eric Laurent65b65452010-06-01 23:49:17 -07001684 int16_t left, right, aux;
Glenn Kasten871c16c2010-03-05 12:18:01 -08001685 if (track->isMuted() || masterMute || track->isPausing() ||
Eric Laurenta553c252009-07-17 12:17:14 -07001686 mStreamTypes[track->type()].mute) {
Eric Laurent65b65452010-06-01 23:49:17 -07001687 left = right = aux = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07001688 if (track->isPausing()) {
1689 track->setPaused();
1690 }
1691 } else {
Glenn Kasten871c16c2010-03-05 12:18:01 -08001692 // read original volumes with volume control
Eric Laurenta553c252009-07-17 12:17:14 -07001693 float typeVolume = mStreamTypes[track->type()].volume;
Glenn Kasten871c16c2010-03-05 12:18:01 -08001694#ifdef LVMX
1695 bool streamMute=false;
1696 // read the volume from the LivesVibes audio engine.
1697 if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType))
1698 {
1699 LifeVibes::getStreamVolumes(audioOutputType, track->type(), &typeVolume, &streamMute);
1700 if (streamMute) {
1701 typeVolume = 0;
1702 }
1703 }
1704#endif
1705 float v = masterVolume * typeVolume;
Eric Laurent65b65452010-06-01 23:49:17 -07001706 uint32_t vl = (uint32_t)(v * cblk->volume[0]) << 12;
1707 uint32_t vr = (uint32_t)(v * cblk->volume[1]) << 12;
Eric Laurenta553c252009-07-17 12:17:14 -07001708
Eric Laurent65b65452010-06-01 23:49:17 -07001709 // Delegate volume control to effect in track effect chain if needed
1710 if (chain != 0 && chain->setVolume(&vl, &vr)) {
1711 // Do not ramp volume is volume is controlled by effect
1712 param = AudioMixer::VOLUME;
Eric Laurenta553c252009-07-17 12:17:14 -07001713 }
Eric Laurent65b65452010-06-01 23:49:17 -07001714
1715 // Convert volumes from 8.24 to 4.12 format
1716 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
1717 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
1718 left = int16_t(v_clamped);
1719 v_clamped = (vr + (1 << 11)) >> 12;
1720 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
1721 right = int16_t(v_clamped);
1722
1723 v_clamped = (uint32_t)(v * cblk->sendLevel);
1724 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
1725 aux = int16_t(v_clamped);
Eric Laurenta553c252009-07-17 12:17:14 -07001726 }
Eric Laurent65b65452010-06-01 23:49:17 -07001727
Glenn Kasten871c16c2010-03-05 12:18:01 -08001728#ifdef LVMX
1729 if ( tracksConnectedChanged || stateChanged )
1730 {
1731 // only do the ramp when the volume is changed by the user / application
1732 param = AudioMixer::VOLUME;
1733 }
1734#endif
Eric Laurent65b65452010-06-01 23:49:17 -07001735
1736 // XXX: these things DON'T need to be done each time
1737 mAudioMixer->setBufferProvider(track);
1738 mAudioMixer->enable(AudioMixer::MIXING);
1739
1740 mAudioMixer->setParameter(param, AudioMixer::VOLUME0, (void *)left);
1741 mAudioMixer->setParameter(param, AudioMixer::VOLUME1, (void *)right);
1742 mAudioMixer->setParameter(param, AudioMixer::AUXLEVEL, (void *)aux);
Eric Laurenta553c252009-07-17 12:17:14 -07001743 mAudioMixer->setParameter(
1744 AudioMixer::TRACK,
Eric Laurent65b65452010-06-01 23:49:17 -07001745 AudioMixer::FORMAT, (void *)track->format());
Eric Laurenta553c252009-07-17 12:17:14 -07001746 mAudioMixer->setParameter(
1747 AudioMixer::TRACK,
Eric Laurent65b65452010-06-01 23:49:17 -07001748 AudioMixer::CHANNEL_COUNT, (void *)track->channelCount());
Eric Laurenta553c252009-07-17 12:17:14 -07001749 mAudioMixer->setParameter(
1750 AudioMixer::RESAMPLE,
1751 AudioMixer::SAMPLE_RATE,
Eric Laurent65b65452010-06-01 23:49:17 -07001752 (void *)(cblk->sampleRate));
1753 mAudioMixer->setParameter(
1754 AudioMixer::TRACK,
1755 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
1756 mAudioMixer->setParameter(
1757 AudioMixer::TRACK,
1758 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
Eric Laurenta553c252009-07-17 12:17:14 -07001759
1760 // reset retry count
1761 track->mRetryCount = kMaxTrackRetries;
Eric Laurent059b4be2009-11-09 23:32:22 -08001762 mixerStatus = MIXER_TRACKS_READY;
Eric Laurenta553c252009-07-17 12:17:14 -07001763 } else {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08001764 //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 -07001765 if (track->isStopped()) {
1766 track->reset();
1767 }
1768 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
1769 // We have consumed all the buffers of this track.
1770 // Remove it from the list of active tracks.
1771 tracksToRemove->add(track);
Eric Laurenta553c252009-07-17 12:17:14 -07001772 } else {
1773 // No buffers for this track. Give it a few chances to
1774 // fill a buffer, then remove it from active list.
1775 if (--(track->mRetryCount) <= 0) {
Eric Laurent62443f52009-10-05 20:29:18 -07001776 LOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", track->name(), this);
Eric Laurenta553c252009-07-17 12:17:14 -07001777 tracksToRemove->add(track);
Eric Laurent059b4be2009-11-09 23:32:22 -08001778 } else if (mixerStatus != MIXER_TRACKS_READY) {
1779 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07001780 }
Eric Laurenta553c252009-07-17 12:17:14 -07001781 }
Eric Laurent65b65452010-06-01 23:49:17 -07001782 mAudioMixer->disable(AudioMixer::MIXING);
Eric Laurenta553c252009-07-17 12:17:14 -07001783 }
1784 }
1785
1786 // remove all the tracks that need to be...
1787 count = tracksToRemove->size();
1788 if (UNLIKELY(count)) {
1789 for (size_t i=0 ; i<count ; i++) {
1790 const sp<Track>& track = tracksToRemove->itemAt(i);
1791 mActiveTracks.remove(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001792 if (track->mainBuffer() != mMixBuffer) {
1793 chain = getEffectChain_l(track->sessionId());
1794 if (chain != 0) {
1795 LOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
1796 chain->stopTrack();
1797 }
1798 }
Eric Laurenta553c252009-07-17 12:17:14 -07001799 if (track->isTerminated()) {
1800 mTracks.remove(track);
1801 deleteTrackName_l(track->mName);
1802 }
1803 }
1804 }
1805
Eric Laurent65b65452010-06-01 23:49:17 -07001806 // mix buffer must be cleared if all tracks are connected to an
1807 // effect chain as in this case the mixer will not write to
1808 // mix buffer and track effects will accumulate into it
1809 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
1810 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
1811 }
1812
Eric Laurent059b4be2009-11-09 23:32:22 -08001813 return mixerStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07001814}
1815
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001816void AudioFlinger::MixerThread::invalidateTracks(int streamType)
Eric Laurenta553c252009-07-17 12:17:14 -07001817{
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001818 LOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d", this, streamType, mTracks.size());
Eric Laurenta553c252009-07-17 12:17:14 -07001819 Mutex::Autolock _l(mLock);
1820 size_t size = mTracks.size();
1821 for (size_t i = 0; i < size; i++) {
1822 sp<Track> t = mTracks[i];
1823 if (t->type() == streamType) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001824 t->mCblk->lock.lock();
1825 t->mCblk->flags |= CBLK_INVALID_ON;
1826 t->mCblk->cv.signal();
1827 t->mCblk->lock.unlock();
Eric Laurenta553c252009-07-17 12:17:14 -07001828 }
Eric Laurent53334cd2010-06-23 17:38:20 -07001829 }
1830}
Eric Laurenta553c252009-07-17 12:17:14 -07001831
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001832
Eric Laurenta553c252009-07-17 12:17:14 -07001833// getTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001834int AudioFlinger::MixerThread::getTrackName_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001835{
1836 return mAudioMixer->getTrackName();
1837}
1838
Eric Laurenta553c252009-07-17 12:17:14 -07001839// deleteTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001840void AudioFlinger::MixerThread::deleteTrackName_l(int name)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001841{
Eric Laurent0a080292009-12-07 10:53:10 -08001842 LOGV("remove track (%d) and delete from mixer", name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001843 mAudioMixer->deleteTrackName(name);
1844}
1845
Eric Laurenta553c252009-07-17 12:17:14 -07001846// checkForNewParameters_l() must be called with ThreadBase::mLock held
1847bool AudioFlinger::MixerThread::checkForNewParameters_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001848{
Eric Laurenta553c252009-07-17 12:17:14 -07001849 bool reconfig = false;
1850
Eric Laurent8fce46a2009-08-04 09:45:33 -07001851 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07001852 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07001853 String8 keyValuePair = mNewParameters[0];
1854 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07001855 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07001856
Eric Laurenta553c252009-07-17 12:17:14 -07001857 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
1858 reconfig = true;
1859 }
1860 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
1861 if (value != AudioSystem::PCM_16_BIT) {
1862 status = BAD_VALUE;
1863 } else {
1864 reconfig = true;
1865 }
1866 }
1867 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
1868 if (value != AudioSystem::CHANNEL_OUT_STEREO) {
1869 status = BAD_VALUE;
1870 } else {
1871 reconfig = true;
1872 }
1873 }
1874 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
1875 // do not accept frame count changes if tracks are open as the track buffer
1876 // size depends on frame count and correct behavior would not be garantied
1877 // if frame count is changed after track creation
1878 if (!mTracks.isEmpty()) {
1879 status = INVALID_OPERATION;
1880 } else {
1881 reconfig = true;
1882 }
1883 }
Eric Laurent65b65452010-06-01 23:49:17 -07001884 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
1885 // forward device change to effects that have requested to be
1886 // aware of attached audio device.
1887 mDevice = (uint32_t)value;
1888 for (size_t i = 0; i < mEffectChains.size(); i++) {
1889 mEffectChains[i]->setDevice(mDevice);
1890 }
1891 }
1892
Eric Laurenta553c252009-07-17 12:17:14 -07001893 if (status == NO_ERROR) {
Eric Laurent8fce46a2009-08-04 09:45:33 -07001894 status = mOutput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07001895 if (!mStandby && status == INVALID_OPERATION) {
1896 mOutput->standby();
1897 mStandby = true;
1898 mBytesWritten = 0;
Eric Laurent8fce46a2009-08-04 09:45:33 -07001899 status = mOutput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07001900 }
1901 if (status == NO_ERROR && reconfig) {
1902 delete mAudioMixer;
1903 readOutputParameters();
1904 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1905 for (size_t i = 0; i < mTracks.size() ; i++) {
1906 int name = getTrackName_l();
1907 if (name < 0) break;
1908 mTracks[i]->mName = name;
Eric Laurent6f7e0972009-08-10 08:15:12 -07001909 // limit track sample rate to 2 x new output sample rate
1910 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
1911 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
1912 }
Eric Laurenta553c252009-07-17 12:17:14 -07001913 }
Eric Laurent8fce46a2009-08-04 09:45:33 -07001914 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07001915 }
1916 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08001917
1918 mNewParameters.removeAt(0);
1919
Eric Laurenta553c252009-07-17 12:17:14 -07001920 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07001921 mParamCond.signal();
Eric Laurent8fce46a2009-08-04 09:45:33 -07001922 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07001923 }
1924 return reconfig;
1925}
1926
1927status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
1928{
1929 const size_t SIZE = 256;
1930 char buffer[SIZE];
1931 String8 result;
1932
1933 PlaybackThread::dumpInternals(fd, args);
1934
1935 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
1936 result.append(buffer);
1937 write(fd, result.string(), result.size());
1938 return NO_ERROR;
1939}
1940
Eric Laurent059b4be2009-11-09 23:32:22 -08001941uint32_t AudioFlinger::MixerThread::activeSleepTimeUs()
Eric Laurent62443f52009-10-05 20:29:18 -07001942{
Eric Laurent059b4be2009-11-09 23:32:22 -08001943 return (uint32_t)(mOutput->latency() * 1000) / 2;
1944}
1945
1946uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
1947{
1948 return (uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000;
Eric Laurent62443f52009-10-05 20:29:18 -07001949}
1950
Eric Laurenta553c252009-07-17 12:17:14 -07001951// ----------------------------------------------------------------------------
Eric Laurent65b65452010-06-01 23:49:17 -07001952AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
1953 : PlaybackThread(audioFlinger, output, id, device)
Eric Laurenta553c252009-07-17 12:17:14 -07001954{
1955 mType = PlaybackThread::DIRECT;
1956}
1957
1958AudioFlinger::DirectOutputThread::~DirectOutputThread()
1959{
1960}
1961
1962
Eric Laurent65b65452010-06-01 23:49:17 -07001963static inline int16_t clamp16(int32_t sample)
1964{
1965 if ((sample>>15) ^ (sample>>31))
1966 sample = 0x7FFF ^ (sample>>31);
1967 return sample;
1968}
1969
1970static inline
1971int32_t mul(int16_t in, int16_t v)
1972{
1973#if defined(__arm__) && !defined(__thumb__)
1974 int32_t out;
1975 asm( "smulbb %[out], %[in], %[v] \n"
1976 : [out]"=r"(out)
1977 : [in]"%r"(in), [v]"r"(v)
1978 : );
1979 return out;
1980#else
1981 return in * int32_t(v);
1982#endif
1983}
1984
1985void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
1986{
1987 // Do not apply volume on compressed audio
1988 if (!AudioSystem::isLinearPCM(mFormat)) {
1989 return;
1990 }
1991
1992 // convert to signed 16 bit before volume calculation
1993 if (mFormat == AudioSystem::PCM_8_BIT) {
1994 size_t count = mFrameCount * mChannelCount;
1995 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
1996 int16_t *dst = mMixBuffer + count-1;
1997 while(count--) {
1998 *dst-- = (int16_t)(*src--^0x80) << 8;
1999 }
2000 }
2001
2002 size_t frameCount = mFrameCount;
2003 int16_t *out = mMixBuffer;
2004 if (ramp) {
2005 if (mChannelCount == 1) {
2006 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2007 int32_t vlInc = d / (int32_t)frameCount;
2008 int32_t vl = ((int32_t)mLeftVolShort << 16);
2009 do {
2010 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2011 out++;
2012 vl += vlInc;
2013 } while (--frameCount);
2014
2015 } else {
2016 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2017 int32_t vlInc = d / (int32_t)frameCount;
2018 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2019 int32_t vrInc = d / (int32_t)frameCount;
2020 int32_t vl = ((int32_t)mLeftVolShort << 16);
2021 int32_t vr = ((int32_t)mRightVolShort << 16);
2022 do {
2023 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2024 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2025 out += 2;
2026 vl += vlInc;
2027 vr += vrInc;
2028 } while (--frameCount);
2029 }
2030 } else {
2031 if (mChannelCount == 1) {
2032 do {
2033 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2034 out++;
2035 } while (--frameCount);
2036 } else {
2037 do {
2038 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2039 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2040 out += 2;
2041 } while (--frameCount);
2042 }
2043 }
2044
2045 // convert back to unsigned 8 bit after volume calculation
2046 if (mFormat == AudioSystem::PCM_8_BIT) {
2047 size_t count = mFrameCount * mChannelCount;
2048 int16_t *src = mMixBuffer;
2049 uint8_t *dst = (uint8_t *)mMixBuffer;
2050 while(count--) {
2051 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2052 }
2053 }
2054
2055 mLeftVolShort = leftVol;
2056 mRightVolShort = rightVol;
2057}
2058
Eric Laurenta553c252009-07-17 12:17:14 -07002059bool AudioFlinger::DirectOutputThread::threadLoop()
2060{
Eric Laurent059b4be2009-11-09 23:32:22 -08002061 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002062 sp<Track> trackToRemove;
2063 sp<Track> activeTrack;
2064 nsecs_t standbyTime = systemTime();
2065 int8_t *curBuf;
2066 size_t mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent059b4be2009-11-09 23:32:22 -08002067 uint32_t activeSleepTime = activeSleepTimeUs();
2068 uint32_t idleSleepTime = idleSleepTimeUs();
2069 uint32_t sleepTime = idleSleepTime;
Eric Laurentef9500f2010-03-11 14:47:00 -08002070 // use shorter standby delay as on normal output to release
2071 // hardware resources as soon as possible
2072 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
Eric Laurent059b4be2009-11-09 23:32:22 -08002073
Eric Laurenta553c252009-07-17 12:17:14 -07002074
2075 while (!exitPending())
2076 {
Eric Laurent65b65452010-06-01 23:49:17 -07002077 bool rampVolume;
2078 uint16_t leftVol;
2079 uint16_t rightVol;
2080 Vector< sp<EffectChain> > effectChains;
2081
Eric Laurenta553c252009-07-17 12:17:14 -07002082 processConfigEvents();
2083
Eric Laurent059b4be2009-11-09 23:32:22 -08002084 mixerStatus = MIXER_IDLE;
2085
Eric Laurenta553c252009-07-17 12:17:14 -07002086 { // scope for the mLock
2087
2088 Mutex::Autolock _l(mLock);
2089
2090 if (checkForNewParameters_l()) {
2091 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent059b4be2009-11-09 23:32:22 -08002092 activeSleepTime = activeSleepTimeUs();
2093 idleSleepTime = idleSleepTimeUs();
Eric Laurentef9500f2010-03-11 14:47:00 -08002094 standbyDelay = microseconds(activeSleepTime*2);
Eric Laurenta553c252009-07-17 12:17:14 -07002095 }
2096
2097 // put audio hardware into standby after short delay
2098 if UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2099 mSuspended) {
2100 // wait until we have something to do...
2101 if (!mStandby) {
2102 LOGV("Audio hardware entering standby, mixer %p\n", this);
2103 mOutput->standby();
2104 mStandby = true;
2105 mBytesWritten = 0;
2106 }
2107
2108 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2109 // we're about to wait, flush the binder command buffer
2110 IPCThreadState::self()->flushCommands();
2111
2112 if (exitPending()) break;
2113
2114 LOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
2115 mWaitWorkCV.wait(mLock);
2116 LOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
2117
2118 if (mMasterMute == false) {
2119 char value[PROPERTY_VALUE_MAX];
2120 property_get("ro.audio.silent", value, "0");
2121 if (atoi(value)) {
2122 LOGD("Silence is golden");
2123 setMasterMute(true);
2124 }
2125 }
2126
Eric Laurentef9500f2010-03-11 14:47:00 -08002127 standbyTime = systemTime() + standbyDelay;
Eric Laurent059b4be2009-11-09 23:32:22 -08002128 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07002129 continue;
2130 }
2131 }
2132
Eric Laurent65b65452010-06-01 23:49:17 -07002133 effectChains = mEffectChains;
2134
Eric Laurenta553c252009-07-17 12:17:14 -07002135 // find out which tracks need to be processed
2136 if (mActiveTracks.size() != 0) {
2137 sp<Track> t = mActiveTracks[0].promote();
2138 if (t == 0) continue;
2139
2140 Track* const track = t.get();
2141 audio_track_cblk_t* cblk = track->cblk();
2142
2143 // The first time a track is added we wait
2144 // for all its buffers to be filled before processing it
2145 if (cblk->framesReady() && (track->isReady() || track->isStopped()) &&
Eric Laurent380558b2010-04-09 06:11:48 -07002146 !track->isPaused() && !track->isTerminated())
Eric Laurenta553c252009-07-17 12:17:14 -07002147 {
2148 //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
2149
Eric Laurent65b65452010-06-01 23:49:17 -07002150 if (track->mFillingUpStatus == Track::FS_FILLED) {
2151 track->mFillingUpStatus = Track::FS_ACTIVE;
2152 mLeftVolFloat = mRightVolFloat = 0;
2153 mLeftVolShort = mRightVolShort = 0;
2154 if (track->mState == TrackBase::RESUMING) {
2155 track->mState = TrackBase::ACTIVE;
2156 rampVolume = true;
2157 }
2158 } else if (cblk->server != 0) {
2159 // If the track is stopped before the first frame was mixed,
2160 // do not apply ramp
2161 rampVolume = true;
2162 }
Eric Laurenta553c252009-07-17 12:17:14 -07002163 // compute volume for this track
2164 float left, right;
2165 if (track->isMuted() || mMasterMute || track->isPausing() ||
2166 mStreamTypes[track->type()].mute) {
2167 left = right = 0;
2168 if (track->isPausing()) {
2169 track->setPaused();
2170 }
2171 } else {
2172 float typeVolume = mStreamTypes[track->type()].volume;
2173 float v = mMasterVolume * typeVolume;
2174 float v_clamped = v * cblk->volume[0];
2175 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2176 left = v_clamped/MAX_GAIN;
2177 v_clamped = v * cblk->volume[1];
2178 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2179 right = v_clamped/MAX_GAIN;
2180 }
2181
Eric Laurent65b65452010-06-01 23:49:17 -07002182 if (left != mLeftVolFloat || right != mRightVolFloat) {
2183 mLeftVolFloat = left;
2184 mRightVolFloat = right;
Eric Laurenta553c252009-07-17 12:17:14 -07002185
Eric Laurent65b65452010-06-01 23:49:17 -07002186 // If audio HAL implements volume control,
2187 // force software volume to nominal value
2188 if (mOutput->setVolume(left, right) == NO_ERROR) {
2189 left = 1.0f;
2190 right = 1.0f;
Eric Laurenta553c252009-07-17 12:17:14 -07002191 }
Eric Laurent65b65452010-06-01 23:49:17 -07002192
2193 // Convert volumes from float to 8.24
2194 uint32_t vl = (uint32_t)(left * (1 << 24));
2195 uint32_t vr = (uint32_t)(right * (1 << 24));
2196
2197 // Delegate volume control to effect in track effect chain if needed
2198 // only one effect chain can be present on DirectOutputThread, so if
2199 // there is one, the track is connected to it
2200 if (!effectChains.isEmpty()) {
2201 // Do not ramp volume is volume is controlled by effect
2202 if(effectChains[0]->setVolume(&vl, &vr)) {
2203 rampVolume = false;
2204 }
2205 }
2206
2207 // Convert volumes from 8.24 to 4.12 format
2208 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2209 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2210 leftVol = (uint16_t)v_clamped;
2211 v_clamped = (vr + (1 << 11)) >> 12;
2212 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2213 rightVol = (uint16_t)v_clamped;
2214 } else {
2215 leftVol = mLeftVolShort;
2216 rightVol = mRightVolShort;
2217 rampVolume = false;
Eric Laurenta553c252009-07-17 12:17:14 -07002218 }
2219
2220 // reset retry count
Eric Laurentef9500f2010-03-11 14:47:00 -08002221 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurenta553c252009-07-17 12:17:14 -07002222 activeTrack = t;
Eric Laurent059b4be2009-11-09 23:32:22 -08002223 mixerStatus = MIXER_TRACKS_READY;
Eric Laurenta553c252009-07-17 12:17:14 -07002224 } else {
2225 //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
2226 if (track->isStopped()) {
2227 track->reset();
2228 }
2229 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2230 // We have consumed all the buffers of this track.
2231 // Remove it from the list of active tracks.
2232 trackToRemove = track;
2233 } else {
2234 // No buffers for this track. Give it a few chances to
2235 // fill a buffer, then remove it from active list.
2236 if (--(track->mRetryCount) <= 0) {
2237 LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
2238 trackToRemove = track;
Eric Laurent059b4be2009-11-09 23:32:22 -08002239 } else {
2240 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07002241 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002242 }
Eric Laurenta553c252009-07-17 12:17:14 -07002243 }
2244 }
2245
2246 // remove all the tracks that need to be...
2247 if (UNLIKELY(trackToRemove != 0)) {
2248 mActiveTracks.remove(trackToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07002249 if (!effectChains.isEmpty()) {
2250 LOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(), trackToRemove->sessionId());
2251 effectChains[0]->stopTrack();
2252 }
Eric Laurenta553c252009-07-17 12:17:14 -07002253 if (trackToRemove->isTerminated()) {
2254 mTracks.remove(trackToRemove);
2255 deleteTrackName_l(trackToRemove->mName);
2256 }
2257 }
Eric Laurent65b65452010-06-01 23:49:17 -07002258
2259 lockEffectChains_l();
Eric Laurenta553c252009-07-17 12:17:14 -07002260 }
2261
Eric Laurent059b4be2009-11-09 23:32:22 -08002262 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002263 AudioBufferProvider::Buffer buffer;
2264 size_t frameCount = mFrameCount;
2265 curBuf = (int8_t *)mMixBuffer;
2266 // output audio to hardware
Eric Laurent65b65452010-06-01 23:49:17 -07002267 while (frameCount) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002268 buffer.frameCount = frameCount;
2269 activeTrack->getNextBuffer(&buffer);
2270 if (UNLIKELY(buffer.raw == 0)) {
2271 memset(curBuf, 0, frameCount * mFrameSize);
2272 break;
2273 }
2274 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2275 frameCount -= buffer.frameCount;
2276 curBuf += buffer.frameCount * mFrameSize;
2277 activeTrack->releaseBuffer(&buffer);
2278 }
2279 sleepTime = 0;
Eric Laurentef9500f2010-03-11 14:47:00 -08002280 standbyTime = systemTime() + standbyDelay;
Eric Laurent96c08a62009-09-07 08:38:38 -07002281 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07002282 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002283 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2284 sleepTime = activeSleepTime;
2285 } else {
2286 sleepTime = idleSleepTime;
2287 }
Eric Laurent62443f52009-10-05 20:29:18 -07002288 } else if (mBytesWritten != 0 && AudioSystem::isLinearPCM(mFormat)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002289 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent96c08a62009-09-07 08:38:38 -07002290 sleepTime = 0;
Eric Laurent96c08a62009-09-07 08:38:38 -07002291 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002292 }
Eric Laurent96c08a62009-09-07 08:38:38 -07002293
Eric Laurentf69a3f82009-09-22 00:35:48 -07002294 if (mSuspended) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002295 sleepTime = idleSleepTime;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002296 }
2297 // sleepTime == 0 means we must write to audio hardware
2298 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07002299 if (mixerStatus == MIXER_TRACKS_READY) {
2300 applyVolume(leftVol, rightVol, rampVolume);
2301 }
2302 for (size_t i = 0; i < effectChains.size(); i ++) {
2303 effectChains[i]->process_l();
2304 }
2305 unlockEffectChains();
2306
Eric Laurentf69a3f82009-09-22 00:35:48 -07002307 mLastWriteTime = systemTime();
2308 mInWrite = true;
Eric Laurent0986e792010-01-19 17:37:09 -08002309 mBytesWritten += mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002310 int bytesWritten = (int)mOutput->write(mMixBuffer, mixBufferSize);
Eric Laurent0986e792010-01-19 17:37:09 -08002311 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002312 mNumWrites++;
2313 mInWrite = false;
2314 mStandby = false;
2315 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07002316 unlockEffectChains();
Eric Laurentf69a3f82009-09-22 00:35:48 -07002317 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07002318 }
2319
2320 // finally let go of removed track, without the lock held
2321 // since we can't guarantee the destructors won't acquire that
2322 // same lock.
2323 trackToRemove.clear();
2324 activeTrack.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07002325
2326 // Effect chains will be actually deleted here if they were removed from
2327 // mEffectChains list during mixing or effects processing
2328 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07002329 }
2330
2331 if (!mStandby) {
2332 mOutput->standby();
2333 }
Eric Laurenta553c252009-07-17 12:17:14 -07002334
2335 LOGV("DirectOutputThread %p exiting", this);
2336 return false;
2337}
2338
2339// getTrackName_l() must be called with ThreadBase::mLock held
2340int AudioFlinger::DirectOutputThread::getTrackName_l()
2341{
2342 return 0;
2343}
2344
2345// deleteTrackName_l() must be called with ThreadBase::mLock held
2346void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2347{
2348}
2349
2350// checkForNewParameters_l() must be called with ThreadBase::mLock held
2351bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2352{
2353 bool reconfig = false;
2354
Eric Laurent8fce46a2009-08-04 09:45:33 -07002355 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07002356 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002357 String8 keyValuePair = mNewParameters[0];
2358 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002359 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002360
Eric Laurenta553c252009-07-17 12:17:14 -07002361 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2362 // do not accept frame count changes if tracks are open as the track buffer
2363 // size depends on frame count and correct behavior would not be garantied
2364 // if frame count is changed after track creation
2365 if (!mTracks.isEmpty()) {
2366 status = INVALID_OPERATION;
2367 } else {
2368 reconfig = true;
2369 }
2370 }
2371 if (status == NO_ERROR) {
Eric Laurent8fce46a2009-08-04 09:45:33 -07002372 status = mOutput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002373 if (!mStandby && status == INVALID_OPERATION) {
2374 mOutput->standby();
2375 mStandby = true;
2376 mBytesWritten = 0;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002377 status = mOutput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002378 }
2379 if (status == NO_ERROR && reconfig) {
2380 readOutputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07002381 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07002382 }
2383 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08002384
2385 mNewParameters.removeAt(0);
2386
Eric Laurenta553c252009-07-17 12:17:14 -07002387 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07002388 mParamCond.signal();
Eric Laurent8fce46a2009-08-04 09:45:33 -07002389 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07002390 }
2391 return reconfig;
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08002392}
2393
Eric Laurent059b4be2009-11-09 23:32:22 -08002394uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
Eric Laurent62443f52009-10-05 20:29:18 -07002395{
2396 uint32_t time;
2397 if (AudioSystem::isLinearPCM(mFormat)) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002398 time = (uint32_t)(mOutput->latency() * 1000) / 2;
2399 } else {
2400 time = 10000;
2401 }
2402 return time;
2403}
2404
2405uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2406{
2407 uint32_t time;
2408 if (AudioSystem::isLinearPCM(mFormat)) {
2409 time = (uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000;
Eric Laurent62443f52009-10-05 20:29:18 -07002410 } else {
2411 time = 10000;
2412 }
2413 return time;
2414}
2415
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002416// ----------------------------------------------------------------------------
2417
Eric Laurent49f02be2009-11-19 09:00:56 -08002418AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread, int id)
Eric Laurent65b65452010-06-01 23:49:17 -07002419 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device()), mWaitTimeMs(UINT_MAX)
Eric Laurenta553c252009-07-17 12:17:14 -07002420{
2421 mType = PlaybackThread::DUPLICATING;
2422 addOutputTrack(mainThread);
2423}
2424
2425AudioFlinger::DuplicatingThread::~DuplicatingThread()
2426{
Eric Laurent0a080292009-12-07 10:53:10 -08002427 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2428 mOutputTracks[i]->destroy();
2429 }
Eric Laurenta553c252009-07-17 12:17:14 -07002430 mOutputTracks.clear();
2431}
2432
2433bool AudioFlinger::DuplicatingThread::threadLoop()
2434{
Eric Laurenta553c252009-07-17 12:17:14 -07002435 Vector< sp<Track> > tracksToRemove;
Eric Laurent059b4be2009-11-09 23:32:22 -08002436 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002437 nsecs_t standbyTime = systemTime();
2438 size_t mixBufferSize = mFrameCount*mFrameSize;
2439 SortedVector< sp<OutputTrack> > outputTracks;
Eric Laurent62443f52009-10-05 20:29:18 -07002440 uint32_t writeFrames = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08002441 uint32_t activeSleepTime = activeSleepTimeUs();
2442 uint32_t idleSleepTime = idleSleepTimeUs();
2443 uint32_t sleepTime = idleSleepTime;
Eric Laurent65b65452010-06-01 23:49:17 -07002444 Vector< sp<EffectChain> > effectChains;
Eric Laurenta553c252009-07-17 12:17:14 -07002445
2446 while (!exitPending())
2447 {
2448 processConfigEvents();
2449
Eric Laurent059b4be2009-11-09 23:32:22 -08002450 mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002451 { // scope for the mLock
2452
2453 Mutex::Autolock _l(mLock);
2454
2455 if (checkForNewParameters_l()) {
2456 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002457 updateWaitTime();
Eric Laurent059b4be2009-11-09 23:32:22 -08002458 activeSleepTime = activeSleepTimeUs();
2459 idleSleepTime = idleSleepTimeUs();
Eric Laurenta553c252009-07-17 12:17:14 -07002460 }
2461
2462 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
2463
2464 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2465 outputTracks.add(mOutputTracks[i]);
2466 }
2467
2468 // put audio hardware into standby after short delay
2469 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
2470 mSuspended) {
2471 if (!mStandby) {
2472 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurenta553c252009-07-17 12:17:14 -07002473 outputTracks[i]->stop();
Eric Laurenta553c252009-07-17 12:17:14 -07002474 }
2475 mStandby = true;
2476 mBytesWritten = 0;
2477 }
2478
2479 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
2480 // we're about to wait, flush the binder command buffer
2481 IPCThreadState::self()->flushCommands();
2482 outputTracks.clear();
2483
2484 if (exitPending()) break;
2485
2486 LOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
2487 mWaitWorkCV.wait(mLock);
2488 LOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
2489 if (mMasterMute == false) {
2490 char value[PROPERTY_VALUE_MAX];
2491 property_get("ro.audio.silent", value, "0");
2492 if (atoi(value)) {
2493 LOGD("Silence is golden");
2494 setMasterMute(true);
2495 }
2496 }
2497
2498 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent059b4be2009-11-09 23:32:22 -08002499 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07002500 continue;
2501 }
2502 }
2503
Eric Laurent059b4be2009-11-09 23:32:22 -08002504 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07002505
2506 // prevent any changes in effect chain list and in each effect chain
2507 // during mixing and effect process as the audio buffers could be deleted
2508 // or modified if an effect is created or deleted
2509 effectChains = mEffectChains;
2510 lockEffectChains_l();
Eric Laurentf69a3f82009-09-22 00:35:48 -07002511 }
Eric Laurenta553c252009-07-17 12:17:14 -07002512
Eric Laurent059b4be2009-11-09 23:32:22 -08002513 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurenta553c252009-07-17 12:17:14 -07002514 // mix buffers...
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002515 if (outputsReady(outputTracks)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002516 mAudioMixer->process();
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002517 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07002518 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002519 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002520 sleepTime = 0;
Eric Laurent62443f52009-10-05 20:29:18 -07002521 writeFrames = mFrameCount;
Eric Laurenta553c252009-07-17 12:17:14 -07002522 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07002523 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002524 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2525 sleepTime = activeSleepTime;
2526 } else {
2527 sleepTime = idleSleepTime;
2528 }
Eric Laurent62443f52009-10-05 20:29:18 -07002529 } else if (mBytesWritten != 0) {
2530 // flush remaining overflow buffers in output tracks
2531 for (size_t i = 0; i < outputTracks.size(); i++) {
2532 if (outputTracks[i]->isActive()) {
2533 sleepTime = 0;
2534 writeFrames = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07002535 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent62443f52009-10-05 20:29:18 -07002536 break;
2537 }
2538 }
Eric Laurenta553c252009-07-17 12:17:14 -07002539 }
2540 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002541
2542 if (mSuspended) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002543 sleepTime = idleSleepTime;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002544 }
2545 // sleepTime == 0 means we must write to audio hardware
2546 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07002547 for (size_t i = 0; i < effectChains.size(); i ++) {
2548 effectChains[i]->process_l();
2549 }
2550 // enable changes in effect chain
2551 unlockEffectChains();
2552
Eric Laurent62443f52009-10-05 20:29:18 -07002553 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002554 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurent65b65452010-06-01 23:49:17 -07002555 outputTracks[i]->write(mMixBuffer, writeFrames);
Eric Laurenta553c252009-07-17 12:17:14 -07002556 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002557 mStandby = false;
2558 mBytesWritten += mixBufferSize;
Eric Laurenta553c252009-07-17 12:17:14 -07002559 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07002560 // enable changes in effect chain
2561 unlockEffectChains();
Eric Laurentf69a3f82009-09-22 00:35:48 -07002562 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07002563 }
2564
2565 // finally let go of all our tracks, without the lock held
2566 // since we can't guarantee the destructors won't acquire that
2567 // same lock.
2568 tracksToRemove.clear();
2569 outputTracks.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07002570
2571 // Effect chains will be actually deleted here if they were removed from
2572 // mEffectChains list during mixing or effects processing
2573 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07002574 }
2575
Eric Laurenta553c252009-07-17 12:17:14 -07002576 return false;
2577}
2578
2579void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
2580{
2581 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
2582 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002583 this,
Eric Laurenta553c252009-07-17 12:17:14 -07002584 mSampleRate,
2585 mFormat,
2586 mChannelCount,
2587 frameCount);
Eric Laurent6c30a712009-08-10 23:22:32 -07002588 if (outputTrack->cblk() != NULL) {
2589 thread->setStreamVolume(AudioSystem::NUM_STREAM_TYPES, 1.0f);
2590 mOutputTracks.add(outputTrack);
2591 LOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002592 updateWaitTime();
Eric Laurent6c30a712009-08-10 23:22:32 -07002593 }
Eric Laurenta553c252009-07-17 12:17:14 -07002594}
2595
2596void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
2597{
2598 Mutex::Autolock _l(mLock);
2599 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2600 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
Eric Laurent6c30a712009-08-10 23:22:32 -07002601 mOutputTracks[i]->destroy();
Eric Laurenta553c252009-07-17 12:17:14 -07002602 mOutputTracks.removeAt(i);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002603 updateWaitTime();
Eric Laurenta553c252009-07-17 12:17:14 -07002604 return;
2605 }
2606 }
2607 LOGV("removeOutputTrack(): unkonwn thread: %p", thread);
2608}
2609
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002610void AudioFlinger::DuplicatingThread::updateWaitTime()
2611{
2612 mWaitTimeMs = UINT_MAX;
2613 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2614 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
2615 if (strong != NULL) {
2616 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
2617 if (waitTimeMs < mWaitTimeMs) {
2618 mWaitTimeMs = waitTimeMs;
2619 }
2620 }
2621 }
2622}
2623
2624
2625bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
2626{
2627 for (size_t i = 0; i < outputTracks.size(); i++) {
2628 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
2629 if (thread == 0) {
2630 LOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
2631 return false;
2632 }
2633 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2634 if (playbackThread->standby() && !playbackThread->isSuspended()) {
2635 LOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
2636 return false;
2637 }
2638 }
2639 return true;
2640}
2641
2642uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
2643{
2644 return (mWaitTimeMs * 1000) / 2;
2645}
2646
Eric Laurenta553c252009-07-17 12:17:14 -07002647// ----------------------------------------------------------------------------
2648
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002649// TrackBase constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07002650AudioFlinger::ThreadBase::TrackBase::TrackBase(
2651 const wp<ThreadBase>& thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002652 const sp<Client>& client,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002653 uint32_t sampleRate,
2654 int format,
2655 int channelCount,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002656 int frameCount,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002657 uint32_t flags,
Eric Laurent65b65452010-06-01 23:49:17 -07002658 const sp<IMemory>& sharedBuffer,
2659 int sessionId)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002660 : RefBase(),
Eric Laurenta553c252009-07-17 12:17:14 -07002661 mThread(thread),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002662 mClient(client),
Eric Laurent8a77a992009-09-09 05:16:08 -07002663 mCblk(0),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002664 mFrameCount(0),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002665 mState(IDLE),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002666 mClientTid(-1),
2667 mFormat(format),
Eric Laurent65b65452010-06-01 23:49:17 -07002668 mFlags(flags & ~SYSTEM_FLAGS_MASK),
2669 mSessionId(sessionId)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002670{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002671 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
2672
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002673 // LOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002674 size_t size = sizeof(audio_track_cblk_t);
2675 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
2676 if (sharedBuffer == 0) {
2677 size += bufferSize;
2678 }
2679
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002680 if (client != NULL) {
2681 mCblkMemory = client->heap()->allocate(size);
2682 if (mCblkMemory != 0) {
2683 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
2684 if (mCblk) { // construct the shared structure in-place.
2685 new(mCblk) audio_track_cblk_t();
2686 // clear all buffers
2687 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07002688 mCblk->sampleRate = sampleRate;
Eric Laurentb0a01472010-05-14 05:45:46 -07002689 mCblk->channelCount = (uint8_t)channelCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002690 if (sharedBuffer == 0) {
2691 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2692 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2693 // Force underrun condition to avoid false underrun callback until first data is
2694 // written to buffer
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002695 mCblk->flags = CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002696 } else {
2697 mBuffer = sharedBuffer->pointer();
2698 }
2699 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002700 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002701 } else {
2702 LOGE("not enough memory for AudioTrack size=%u", size);
2703 client->heap()->dump("AudioTrack");
2704 return;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002705 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002706 } else {
2707 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
2708 if (mCblk) { // construct the shared structure in-place.
2709 new(mCblk) audio_track_cblk_t();
2710 // clear all buffers
2711 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07002712 mCblk->sampleRate = sampleRate;
Eric Laurentb0a01472010-05-14 05:45:46 -07002713 mCblk->channelCount = (uint8_t)channelCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002714 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2715 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2716 // Force underrun condition to avoid false underrun callback until first data is
2717 // written to buffer
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002718 mCblk->flags = CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002719 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
2720 }
2721 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002722}
2723
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002724AudioFlinger::ThreadBase::TrackBase::~TrackBase()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002725{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002726 if (mCblk) {
Eric Laurenta553c252009-07-17 12:17:14 -07002727 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
2728 if (mClient == NULL) {
2729 delete mCblk;
2730 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002731 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002732 mCblkMemory.clear(); // and free the shared memory
Eric Laurentb9481d82009-09-17 05:12:56 -07002733 if (mClient != NULL) {
2734 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
2735 mClient.clear();
2736 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002737}
2738
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002739void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002740{
2741 buffer->raw = 0;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002742 mFrameCount = buffer->frameCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002743 step();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002744 buffer->frameCount = 0;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002745}
2746
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002747bool AudioFlinger::ThreadBase::TrackBase::step() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002748 bool result;
2749 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002750
2751 result = cblk->stepServer(mFrameCount);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002752 if (!result) {
2753 LOGV("stepServer failed acquiring cblk mutex");
2754 mFlags |= STEPSERVER_FAILED;
2755 }
2756 return result;
2757}
2758
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002759void AudioFlinger::ThreadBase::TrackBase::reset() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002760 audio_track_cblk_t* cblk = this->cblk();
2761
2762 cblk->user = 0;
2763 cblk->server = 0;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002764 cblk->userBase = 0;
2765 cblk->serverBase = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002766 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002767 LOGV("TrackBase::reset");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002768}
2769
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002770sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002771{
2772 return mCblkMemory;
2773}
2774
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002775int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
The Android Open Source Project10592532009-03-18 17:39:46 -07002776 return (int)mCblk->sampleRate;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002777}
2778
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002779int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
Eric Laurentb0a01472010-05-14 05:45:46 -07002780 return (int)mCblk->channelCount;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002781}
2782
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002783void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002784 audio_track_cblk_t* cblk = this->cblk();
Eric Laurenta553c252009-07-17 12:17:14 -07002785 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
2786 int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002787
2788 // Check validity of returned pointer in case the track control block would have been corrupted.
Eric Laurenta553c252009-07-17 12:17:14 -07002789 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
2790 ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
The Android Open Source Project10592532009-03-18 17:39:46 -07002791 LOGE("TrackBase::getBuffer buffer out of range:\n start: %p, end %p , mBuffer %p mBufferEnd %p\n \
Eric Laurentb0a01472010-05-14 05:45:46 -07002792 server %d, serverBase %d, user %d, userBase %d, channelCount %d",
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002793 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Eric Laurentb0a01472010-05-14 05:45:46 -07002794 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, cblk->channelCount);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002795 return 0;
2796 }
2797
2798 return bufferStart;
2799}
2800
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002801// ----------------------------------------------------------------------------
2802
Eric Laurenta553c252009-07-17 12:17:14 -07002803// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
2804AudioFlinger::PlaybackThread::Track::Track(
2805 const wp<ThreadBase>& thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002806 const sp<Client>& client,
2807 int streamType,
2808 uint32_t sampleRate,
2809 int format,
2810 int channelCount,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002811 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07002812 const sp<IMemory>& sharedBuffer,
2813 int sessionId)
2814 : TrackBase(thread, client, sampleRate, format, channelCount, frameCount, 0, sharedBuffer, sessionId),
2815 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL), mAuxEffectId(0)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002816{
Eric Laurent8a77a992009-09-09 05:16:08 -07002817 if (mCblk != NULL) {
2818 sp<ThreadBase> baseThread = thread.promote();
2819 if (baseThread != 0) {
2820 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
2821 mName = playbackThread->getTrackName_l();
Eric Laurent65b65452010-06-01 23:49:17 -07002822 mMainBuffer = playbackThread->mixBuffer();
Eric Laurent8a77a992009-09-09 05:16:08 -07002823 }
2824 LOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2825 if (mName < 0) {
2826 LOGE("no more track names available");
2827 }
2828 mVolume[0] = 1.0f;
2829 mVolume[1] = 1.0f;
2830 mStreamType = streamType;
2831 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
2832 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
2833 mCblk->frameSize = AudioSystem::isLinearPCM(format) ? channelCount * sizeof(int16_t) : sizeof(int8_t);
Eric Laurenta553c252009-07-17 12:17:14 -07002834 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002835}
2836
Eric Laurenta553c252009-07-17 12:17:14 -07002837AudioFlinger::PlaybackThread::Track::~Track()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002838{
Eric Laurenta553c252009-07-17 12:17:14 -07002839 LOGV("PlaybackThread::Track destructor");
2840 sp<ThreadBase> thread = mThread.promote();
2841 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08002842 Mutex::Autolock _l(thread->mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07002843 mState = TERMINATED;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002844 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002845}
2846
Eric Laurenta553c252009-07-17 12:17:14 -07002847void AudioFlinger::PlaybackThread::Track::destroy()
2848{
2849 // NOTE: destroyTrack_l() can remove a strong reference to this Track
2850 // by removing it from mTracks vector, so there is a risk that this Tracks's
2851 // desctructor is called. As the destructor needs to lock mLock,
2852 // we must acquire a strong reference on this Track before locking mLock
2853 // here so that the destructor is called only when exiting this function.
2854 // On the other hand, as long as Track::destroy() is only called by
2855 // TrackHandle destructor, the TrackHandle still holds a strong ref on
2856 // this Track with its member mTrack.
2857 sp<Track> keep(this);
2858 { // scope for mLock
2859 sp<ThreadBase> thread = mThread.promote();
2860 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08002861 if (!isOutputTrack()) {
2862 if (mState == ACTIVE || mState == RESUMING) {
2863 AudioSystem::stopOutput(thread->id(), (AudioSystem::stream_type)mStreamType);
2864 }
2865 AudioSystem::releaseOutput(thread->id());
Eric Laurent49f02be2009-11-19 09:00:56 -08002866 }
Eric Laurenta553c252009-07-17 12:17:14 -07002867 Mutex::Autolock _l(thread->mLock);
2868 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2869 playbackThread->destroyTrack_l(this);
2870 }
2871 }
2872}
2873
2874void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002875{
Eric Laurent65b65452010-06-01 23:49:17 -07002876 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 -07002877 mName - AudioMixer::TRACK0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002878 (mClient == NULL) ? getpid() : mClient->pid(),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002879 mStreamType,
2880 mFormat,
Eric Laurentb0a01472010-05-14 05:45:46 -07002881 mCblk->channelCount,
Eric Laurent65b65452010-06-01 23:49:17 -07002882 mSessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002883 mFrameCount,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002884 mState,
2885 mMute,
2886 mFillingUpStatus,
2887 mCblk->sampleRate,
2888 mCblk->volume[0],
2889 mCblk->volume[1],
2890 mCblk->server,
Eric Laurent65b65452010-06-01 23:49:17 -07002891 mCblk->user,
2892 (int)mMainBuffer,
2893 (int)mAuxBuffer);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002894}
2895
Eric Laurenta553c252009-07-17 12:17:14 -07002896status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002897{
2898 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002899 uint32_t framesReady;
2900 uint32_t framesReq = buffer->frameCount;
2901
2902 // Check if last stepServer failed, try to step now
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002903 if (mFlags & TrackBase::STEPSERVER_FAILED) {
2904 if (!step()) goto getNextBuffer_exit;
2905 LOGV("stepServer recovered");
2906 mFlags &= ~TrackBase::STEPSERVER_FAILED;
2907 }
2908
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002909 framesReady = cblk->framesReady();
2910
2911 if (LIKELY(framesReady)) {
2912 uint32_t s = cblk->server;
2913 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
2914
2915 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
2916 if (framesReq > framesReady) {
2917 framesReq = framesReady;
2918 }
2919 if (s + framesReq > bufferEnd) {
2920 framesReq = bufferEnd - s;
2921 }
2922
2923 buffer->raw = getBuffer(s, framesReq);
2924 if (buffer->raw == 0) goto getNextBuffer_exit;
2925
2926 buffer->frameCount = framesReq;
2927 return NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002928 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002929
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002930getNextBuffer_exit:
2931 buffer->raw = 0;
2932 buffer->frameCount = 0;
Eric Laurent62443f52009-10-05 20:29:18 -07002933 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 -07002934 return NOT_ENOUGH_DATA;
2935}
2936
Eric Laurenta553c252009-07-17 12:17:14 -07002937bool AudioFlinger::PlaybackThread::Track::isReady() const {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002938 if (mFillingUpStatus != FS_FILLING) return true;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002939
2940 if (mCblk->framesReady() >= mCblk->frameCount ||
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002941 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002942 mFillingUpStatus = FS_FILLED;
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002943 mCblk->flags &= ~CBLK_FORCEREADY_MSK;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002944 return true;
2945 }
2946 return false;
2947}
2948
Eric Laurenta553c252009-07-17 12:17:14 -07002949status_t AudioFlinger::PlaybackThread::Track::start()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002950{
Eric Laurent49f02be2009-11-19 09:00:56 -08002951 status_t status = NO_ERROR;
Eric Laurenta553c252009-07-17 12:17:14 -07002952 LOGV("start(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2953 sp<ThreadBase> thread = mThread.promote();
2954 if (thread != 0) {
2955 Mutex::Autolock _l(thread->mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08002956 int state = mState;
2957 // here the track could be either new, or restarted
2958 // in both cases "unstop" the track
2959 if (mState == PAUSED) {
2960 mState = TrackBase::RESUMING;
2961 LOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
2962 } else {
2963 mState = TrackBase::ACTIVE;
2964 LOGV("? => ACTIVE (%d) on thread %p", mName, this);
2965 }
2966
2967 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
2968 thread->mLock.unlock();
2969 status = AudioSystem::startOutput(thread->id(), (AudioSystem::stream_type)mStreamType);
2970 thread->mLock.lock();
2971 }
2972 if (status == NO_ERROR) {
2973 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2974 playbackThread->addTrack_l(this);
2975 } else {
2976 mState = state;
2977 }
2978 } else {
2979 status = BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -07002980 }
Eric Laurent49f02be2009-11-19 09:00:56 -08002981 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002982}
2983
Eric Laurenta553c252009-07-17 12:17:14 -07002984void AudioFlinger::PlaybackThread::Track::stop()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002985{
Eric Laurenta553c252009-07-17 12:17:14 -07002986 LOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2987 sp<ThreadBase> thread = mThread.promote();
2988 if (thread != 0) {
2989 Mutex::Autolock _l(thread->mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08002990 int state = mState;
Eric Laurenta553c252009-07-17 12:17:14 -07002991 if (mState > STOPPED) {
2992 mState = STOPPED;
2993 // If the track is not active (PAUSED and buffers full), flush buffers
2994 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2995 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
2996 reset();
2997 }
Eric Laurent62443f52009-10-05 20:29:18 -07002998 LOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002999 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003000 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3001 thread->mLock.unlock();
3002 AudioSystem::stopOutput(thread->id(), (AudioSystem::stream_type)mStreamType);
3003 thread->mLock.lock();
3004 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003005 }
3006}
3007
Eric Laurenta553c252009-07-17 12:17:14 -07003008void AudioFlinger::PlaybackThread::Track::pause()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003009{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003010 LOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurenta553c252009-07-17 12:17:14 -07003011 sp<ThreadBase> thread = mThread.promote();
3012 if (thread != 0) {
3013 Mutex::Autolock _l(thread->mLock);
3014 if (mState == ACTIVE || mState == RESUMING) {
3015 mState = PAUSING;
Eric Laurent62443f52009-10-05 20:29:18 -07003016 LOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurent49f02be2009-11-19 09:00:56 -08003017 if (!isOutputTrack()) {
3018 thread->mLock.unlock();
3019 AudioSystem::stopOutput(thread->id(), (AudioSystem::stream_type)mStreamType);
3020 thread->mLock.lock();
3021 }
Eric Laurenta553c252009-07-17 12:17:14 -07003022 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003023 }
3024}
3025
Eric Laurenta553c252009-07-17 12:17:14 -07003026void AudioFlinger::PlaybackThread::Track::flush()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003027{
3028 LOGV("flush(%d)", mName);
Eric Laurenta553c252009-07-17 12:17:14 -07003029 sp<ThreadBase> thread = mThread.promote();
3030 if (thread != 0) {
3031 Mutex::Autolock _l(thread->mLock);
3032 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3033 return;
3034 }
3035 // No point remaining in PAUSED state after a flush => go to
3036 // STOPPED state
3037 mState = STOPPED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003038
Eric Laurenta553c252009-07-17 12:17:14 -07003039 mCblk->lock.lock();
3040 // NOTE: reset() will reset cblk->user and cblk->server with
3041 // the risk that at the same time, the AudioMixer is trying to read
3042 // data. In this case, getNextBuffer() would return a NULL pointer
3043 // as audio buffer => the AudioMixer code MUST always test that pointer
3044 // returned by getNextBuffer() is not NULL!
3045 reset();
3046 mCblk->lock.unlock();
3047 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003048}
3049
Eric Laurenta553c252009-07-17 12:17:14 -07003050void AudioFlinger::PlaybackThread::Track::reset()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003051{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003052 // Do not reset twice to avoid discarding data written just after a flush and before
3053 // the audioflinger thread detects the track is stopped.
3054 if (!mResetDone) {
3055 TrackBase::reset();
3056 // Force underrun condition to avoid false underrun callback until first data is
3057 // written to buffer
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003058 mCblk->flags |= CBLK_UNDERRUN_ON;
3059 mCblk->flags &= ~CBLK_FORCEREADY_MSK;
Eric Laurenta553c252009-07-17 12:17:14 -07003060 mFillingUpStatus = FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003061 mResetDone = true;
3062 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003063}
3064
Eric Laurenta553c252009-07-17 12:17:14 -07003065void AudioFlinger::PlaybackThread::Track::mute(bool muted)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003066{
3067 mMute = muted;
3068}
3069
Eric Laurenta553c252009-07-17 12:17:14 -07003070void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003071{
3072 mVolume[0] = left;
3073 mVolume[1] = right;
3074}
3075
Eric Laurent65b65452010-06-01 23:49:17 -07003076status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3077{
3078 status_t status = DEAD_OBJECT;
3079 sp<ThreadBase> thread = mThread.promote();
3080 if (thread != 0) {
3081 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3082 status = playbackThread->attachAuxEffect(this, EffectId);
3083 }
3084 return status;
3085}
3086
3087void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3088{
3089 mAuxEffectId = EffectId;
3090 mAuxBuffer = buffer;
3091}
3092
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003093// ----------------------------------------------------------------------------
3094
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003095// RecordTrack constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07003096AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3097 const wp<ThreadBase>& thread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003098 const sp<Client>& client,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003099 uint32_t sampleRate,
3100 int format,
3101 int channelCount,
3102 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07003103 uint32_t flags,
3104 int sessionId)
Eric Laurenta553c252009-07-17 12:17:14 -07003105 : TrackBase(thread, client, sampleRate, format,
Eric Laurent65b65452010-06-01 23:49:17 -07003106 channelCount, frameCount, flags, 0, sessionId),
Eric Laurenta553c252009-07-17 12:17:14 -07003107 mOverflow(false)
3108{
Eric Laurent8a77a992009-09-09 05:16:08 -07003109 if (mCblk != NULL) {
3110 LOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
3111 if (format == AudioSystem::PCM_16_BIT) {
3112 mCblk->frameSize = channelCount * sizeof(int16_t);
3113 } else if (format == AudioSystem::PCM_8_BIT) {
3114 mCblk->frameSize = channelCount * sizeof(int8_t);
3115 } else {
3116 mCblk->frameSize = sizeof(int8_t);
3117 }
3118 }
Eric Laurenta553c252009-07-17 12:17:14 -07003119}
3120
3121AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003122{
Eric Laurent49f02be2009-11-19 09:00:56 -08003123 sp<ThreadBase> thread = mThread.promote();
3124 if (thread != 0) {
3125 AudioSystem::releaseInput(thread->id());
3126 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003127}
3128
Eric Laurenta553c252009-07-17 12:17:14 -07003129status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003130{
3131 audio_track_cblk_t* cblk = this->cblk();
3132 uint32_t framesAvail;
3133 uint32_t framesReq = buffer->frameCount;
3134
3135 // Check if last stepServer failed, try to step now
3136 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3137 if (!step()) goto getNextBuffer_exit;
3138 LOGV("stepServer recovered");
3139 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3140 }
3141
3142 framesAvail = cblk->framesAvailable_l();
3143
3144 if (LIKELY(framesAvail)) {
3145 uint32_t s = cblk->server;
3146 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3147
3148 if (framesReq > framesAvail) {
3149 framesReq = framesAvail;
3150 }
3151 if (s + framesReq > bufferEnd) {
3152 framesReq = bufferEnd - s;
3153 }
3154
3155 buffer->raw = getBuffer(s, framesReq);
3156 if (buffer->raw == 0) goto getNextBuffer_exit;
3157
3158 buffer->frameCount = framesReq;
3159 return NO_ERROR;
3160 }
3161
3162getNextBuffer_exit:
3163 buffer->raw = 0;
3164 buffer->frameCount = 0;
3165 return NOT_ENOUGH_DATA;
3166}
3167
Eric Laurenta553c252009-07-17 12:17:14 -07003168status_t AudioFlinger::RecordThread::RecordTrack::start()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003169{
Eric Laurenta553c252009-07-17 12:17:14 -07003170 sp<ThreadBase> thread = mThread.promote();
3171 if (thread != 0) {
3172 RecordThread *recordThread = (RecordThread *)thread.get();
3173 return recordThread->start(this);
Eric Laurent49f02be2009-11-19 09:00:56 -08003174 } else {
3175 return BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -07003176 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003177}
3178
Eric Laurenta553c252009-07-17 12:17:14 -07003179void AudioFlinger::RecordThread::RecordTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003180{
Eric Laurenta553c252009-07-17 12:17:14 -07003181 sp<ThreadBase> thread = mThread.promote();
3182 if (thread != 0) {
3183 RecordThread *recordThread = (RecordThread *)thread.get();
3184 recordThread->stop(this);
3185 TrackBase::reset();
3186 // Force overerrun condition to avoid false overrun callback until first data is
3187 // read from buffer
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003188 mCblk->flags |= CBLK_UNDERRUN_ON;
Eric Laurenta553c252009-07-17 12:17:14 -07003189 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003190}
3191
Eric Laurent3fdb1262009-11-07 00:01:32 -08003192void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3193{
Eric Laurent65b65452010-06-01 23:49:17 -07003194 snprintf(buffer, size, " %05d %03u %03u %05d %04u %01d %05u %08x %08x\n",
Eric Laurent3fdb1262009-11-07 00:01:32 -08003195 (mClient == NULL) ? getpid() : mClient->pid(),
3196 mFormat,
Eric Laurentb0a01472010-05-14 05:45:46 -07003197 mCblk->channelCount,
Eric Laurent65b65452010-06-01 23:49:17 -07003198 mSessionId,
Eric Laurent3fdb1262009-11-07 00:01:32 -08003199 mFrameCount,
3200 mState,
3201 mCblk->sampleRate,
3202 mCblk->server,
3203 mCblk->user);
3204}
3205
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003206
3207// ----------------------------------------------------------------------------
3208
Eric Laurenta553c252009-07-17 12:17:14 -07003209AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3210 const wp<ThreadBase>& thread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003211 DuplicatingThread *sourceThread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003212 uint32_t sampleRate,
3213 int format,
3214 int channelCount,
3215 int frameCount)
Eric Laurent65b65452010-06-01 23:49:17 -07003216 : Track(thread, NULL, AudioSystem::NUM_STREAM_TYPES, sampleRate, format, channelCount, frameCount, NULL, 0),
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003217 mActive(false), mSourceThread(sourceThread)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003218{
Eric Laurenta553c252009-07-17 12:17:14 -07003219
3220 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
Eric Laurent6c30a712009-08-10 23:22:32 -07003221 if (mCblk != NULL) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003222 mCblk->flags |= CBLK_DIRECTION_OUT;
Eric Laurent6c30a712009-08-10 23:22:32 -07003223 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
3224 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
3225 mOutBuffer.frameCount = 0;
Eric Laurent6c30a712009-08-10 23:22:32 -07003226 playbackThread->mTracks.add(this);
Eric Laurentb0a01472010-05-14 05:45:46 -07003227 LOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, mCblk->frameCount %d, mCblk->sampleRate %d, mCblk->channelCount %d mBufferEnd %p",
3228 mCblk, mBuffer, mCblk->buffers, mCblk->frameCount, mCblk->sampleRate, mCblk->channelCount, mBufferEnd);
Eric Laurent6c30a712009-08-10 23:22:32 -07003229 } else {
3230 LOGW("Error creating output track on thread %p", playbackThread);
3231 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003232}
3233
Eric Laurenta553c252009-07-17 12:17:14 -07003234AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003235{
Eric Laurent6c30a712009-08-10 23:22:32 -07003236 clearBufferQueue();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003237}
3238
Eric Laurenta553c252009-07-17 12:17:14 -07003239status_t AudioFlinger::PlaybackThread::OutputTrack::start()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003240{
3241 status_t status = Track::start();
Eric Laurenta553c252009-07-17 12:17:14 -07003242 if (status != NO_ERROR) {
3243 return status;
3244 }
3245
3246 mActive = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003247 mRetryCount = 127;
3248 return status;
3249}
3250
Eric Laurenta553c252009-07-17 12:17:14 -07003251void AudioFlinger::PlaybackThread::OutputTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003252{
3253 Track::stop();
3254 clearBufferQueue();
3255 mOutBuffer.frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003256 mActive = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003257}
3258
Eric Laurenta553c252009-07-17 12:17:14 -07003259bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003260{
3261 Buffer *pInBuffer;
3262 Buffer inBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003263 uint32_t channelCount = mCblk->channelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003264 bool outputBufferFull = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003265 inBuffer.frameCount = frames;
3266 inBuffer.i16 = data;
Eric Laurenta553c252009-07-17 12:17:14 -07003267
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003268 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
Eric Laurenta553c252009-07-17 12:17:14 -07003269
Eric Laurent62443f52009-10-05 20:29:18 -07003270 if (!mActive && frames != 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003271 start();
3272 sp<ThreadBase> thread = mThread.promote();
3273 if (thread != 0) {
3274 MixerThread *mixerThread = (MixerThread *)thread.get();
3275 if (mCblk->frameCount > frames){
3276 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3277 uint32_t startFrames = (mCblk->frameCount - frames);
3278 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003279 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
Eric Laurenta553c252009-07-17 12:17:14 -07003280 pInBuffer->frameCount = startFrames;
3281 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003282 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
Eric Laurenta553c252009-07-17 12:17:14 -07003283 mBufferQueue.add(pInBuffer);
3284 } else {
3285 LOGW ("OutputTrack::write() %p no more buffers in queue", this);
3286 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003287 }
Eric Laurenta553c252009-07-17 12:17:14 -07003288 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003289 }
3290
Eric Laurenta553c252009-07-17 12:17:14 -07003291 while (waitTimeLeftMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003292 // First write pending buffers, then new data
3293 if (mBufferQueue.size()) {
3294 pInBuffer = mBufferQueue.itemAt(0);
3295 } else {
3296 pInBuffer = &inBuffer;
3297 }
Eric Laurenta553c252009-07-17 12:17:14 -07003298
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003299 if (pInBuffer->frameCount == 0) {
3300 break;
3301 }
Eric Laurenta553c252009-07-17 12:17:14 -07003302
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003303 if (mOutBuffer.frameCount == 0) {
3304 mOutBuffer.frameCount = pInBuffer->frameCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003305 nsecs_t startTime = systemTime();
3306 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003307 LOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Eric Laurenta553c252009-07-17 12:17:14 -07003308 outputBufferFull = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003309 break;
3310 }
Eric Laurenta553c252009-07-17 12:17:14 -07003311 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
Eric Laurenta553c252009-07-17 12:17:14 -07003312 if (waitTimeLeftMs >= waitTimeMs) {
3313 waitTimeLeftMs -= waitTimeMs;
3314 } else {
3315 waitTimeLeftMs = 0;
3316 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003317 }
Eric Laurenta553c252009-07-17 12:17:14 -07003318
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003319 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
Eric Laurentb0a01472010-05-14 05:45:46 -07003320 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003321 mCblk->stepUser(outFrames);
3322 pInBuffer->frameCount -= outFrames;
Eric Laurentb0a01472010-05-14 05:45:46 -07003323 pInBuffer->i16 += outFrames * channelCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003324 mOutBuffer.frameCount -= outFrames;
Eric Laurentb0a01472010-05-14 05:45:46 -07003325 mOutBuffer.i16 += outFrames * channelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003326
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003327 if (pInBuffer->frameCount == 0) {
3328 if (mBufferQueue.size()) {
3329 mBufferQueue.removeAt(0);
3330 delete [] pInBuffer->mBuffer;
3331 delete pInBuffer;
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003332 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 -08003333 } else {
3334 break;
3335 }
3336 }
3337 }
Eric Laurenta553c252009-07-17 12:17:14 -07003338
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003339 // If we could not write all frames, allocate a buffer and queue it for next time.
3340 if (inBuffer.frameCount) {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003341 sp<ThreadBase> thread = mThread.promote();
3342 if (thread != 0 && !thread->standby()) {
3343 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3344 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003345 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003346 pInBuffer->frameCount = inBuffer.frameCount;
3347 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003348 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003349 mBufferQueue.add(pInBuffer);
3350 LOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
3351 } else {
3352 LOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
3353 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003354 }
3355 }
Eric Laurenta553c252009-07-17 12:17:14 -07003356
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003357 // Calling write() with a 0 length buffer, means that no more data will be written:
Eric Laurenta553c252009-07-17 12:17:14 -07003358 // 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 -08003359 // by output mixer.
Eric Laurenta553c252009-07-17 12:17:14 -07003360 if (frames == 0 && mBufferQueue.size() == 0) {
3361 if (mCblk->user < mCblk->frameCount) {
3362 frames = mCblk->frameCount - mCblk->user;
3363 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003364 pInBuffer->mBuffer = new int16_t[frames * channelCount];
Eric Laurenta553c252009-07-17 12:17:14 -07003365 pInBuffer->frameCount = frames;
3366 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003367 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
Eric Laurenta553c252009-07-17 12:17:14 -07003368 mBufferQueue.add(pInBuffer);
Eric Laurent62443f52009-10-05 20:29:18 -07003369 } else if (mActive) {
Eric Laurenta553c252009-07-17 12:17:14 -07003370 stop();
3371 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003372 }
3373
Eric Laurenta553c252009-07-17 12:17:14 -07003374 return outputBufferFull;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003375}
3376
Eric Laurenta553c252009-07-17 12:17:14 -07003377status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003378{
3379 int active;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003380 status_t result;
3381 audio_track_cblk_t* cblk = mCblk;
3382 uint32_t framesReq = buffer->frameCount;
3383
Eric Laurenta553c252009-07-17 12:17:14 -07003384// LOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003385 buffer->frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003386
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003387 uint32_t framesAvail = cblk->framesAvailable();
3388
Eric Laurenta553c252009-07-17 12:17:14 -07003389
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003390 if (framesAvail == 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003391 Mutex::Autolock _l(cblk->lock);
3392 goto start_loop_here;
3393 while (framesAvail == 0) {
3394 active = mActive;
3395 if (UNLIKELY(!active)) {
3396 LOGV("Not active and NO_MORE_BUFFERS");
3397 return AudioTrack::NO_MORE_BUFFERS;
3398 }
3399 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3400 if (result != NO_ERROR) {
3401 return AudioTrack::NO_MORE_BUFFERS;
3402 }
3403 // read the server count again
3404 start_loop_here:
3405 framesAvail = cblk->framesAvailable_l();
3406 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003407 }
3408
Eric Laurenta553c252009-07-17 12:17:14 -07003409// if (framesAvail < framesReq) {
3410// return AudioTrack::NO_MORE_BUFFERS;
3411// }
3412
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003413 if (framesReq > framesAvail) {
3414 framesReq = framesAvail;
3415 }
3416
3417 uint32_t u = cblk->user;
3418 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
3419
3420 if (u + framesReq > bufferEnd) {
3421 framesReq = bufferEnd - u;
3422 }
3423
3424 buffer->frameCount = framesReq;
3425 buffer->raw = (void *)cblk->buffer(u);
3426 return NO_ERROR;
3427}
3428
3429
Eric Laurenta553c252009-07-17 12:17:14 -07003430void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003431{
3432 size_t size = mBufferQueue.size();
3433 Buffer *pBuffer;
Eric Laurenta553c252009-07-17 12:17:14 -07003434
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003435 for (size_t i = 0; i < size; i++) {
3436 pBuffer = mBufferQueue.itemAt(i);
3437 delete [] pBuffer->mBuffer;
3438 delete pBuffer;
3439 }
3440 mBufferQueue.clear();
3441}
3442
3443// ----------------------------------------------------------------------------
3444
3445AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
3446 : RefBase(),
3447 mAudioFlinger(audioFlinger),
Mathias Agopian6faf7892010-01-25 19:00:00 -08003448 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003449 mPid(pid)
3450{
3451 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
3452}
3453
Eric Laurentb9481d82009-09-17 05:12:56 -07003454// Client destructor must be called with AudioFlinger::mLock held
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003455AudioFlinger::Client::~Client()
3456{
Eric Laurentb9481d82009-09-17 05:12:56 -07003457 mAudioFlinger->removeClient_l(mPid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003458}
3459
3460const sp<MemoryDealer>& AudioFlinger::Client::heap() const
3461{
3462 return mMemoryDealer;
3463}
3464
3465// ----------------------------------------------------------------------------
3466
Eric Laurent4f0f17d2010-05-12 02:05:53 -07003467AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
3468 const sp<IAudioFlingerClient>& client,
3469 pid_t pid)
3470 : mAudioFlinger(audioFlinger), mPid(pid), mClient(client)
3471{
3472}
3473
3474AudioFlinger::NotificationClient::~NotificationClient()
3475{
3476 mClient.clear();
3477}
3478
3479void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
3480{
3481 sp<NotificationClient> keep(this);
3482 {
3483 mAudioFlinger->removeNotificationClient(mPid);
3484 }
3485}
3486
3487// ----------------------------------------------------------------------------
3488
Eric Laurenta553c252009-07-17 12:17:14 -07003489AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003490 : BnAudioTrack(),
3491 mTrack(track)
3492{
3493}
3494
3495AudioFlinger::TrackHandle::~TrackHandle() {
3496 // just stop the track on deletion, associated resources
3497 // will be freed from the main thread once all pending buffers have
3498 // been played. Unless it's not in the active track list, in which
3499 // case we free everything now...
3500 mTrack->destroy();
3501}
3502
3503status_t AudioFlinger::TrackHandle::start() {
3504 return mTrack->start();
3505}
3506
3507void AudioFlinger::TrackHandle::stop() {
3508 mTrack->stop();
3509}
3510
3511void AudioFlinger::TrackHandle::flush() {
3512 mTrack->flush();
3513}
3514
3515void AudioFlinger::TrackHandle::mute(bool e) {
3516 mTrack->mute(e);
3517}
3518
3519void AudioFlinger::TrackHandle::pause() {
3520 mTrack->pause();
3521}
3522
3523void AudioFlinger::TrackHandle::setVolume(float left, float right) {
3524 mTrack->setVolume(left, right);
3525}
3526
3527sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
3528 return mTrack->getCblk();
3529}
3530
Eric Laurent65b65452010-06-01 23:49:17 -07003531status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
3532{
3533 return mTrack->attachAuxEffect(EffectId);
3534}
3535
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003536status_t AudioFlinger::TrackHandle::onTransact(
3537 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3538{
3539 return BnAudioTrack::onTransact(code, data, reply, flags);
3540}
3541
3542// ----------------------------------------------------------------------------
3543
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003544sp<IAudioRecord> AudioFlinger::openRecord(
3545 pid_t pid,
Eric Laurentddb78e72009-07-28 08:44:33 -07003546 int input,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003547 uint32_t sampleRate,
3548 int format,
3549 int channelCount,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003550 int frameCount,
3551 uint32_t flags,
Eric Laurent65b65452010-06-01 23:49:17 -07003552 int *sessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003553 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003554{
Eric Laurenta553c252009-07-17 12:17:14 -07003555 sp<RecordThread::RecordTrack> recordTrack;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003556 sp<RecordHandle> recordHandle;
3557 sp<Client> client;
3558 wp<Client> wclient;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003559 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07003560 RecordThread *thread;
3561 size_t inFrameCount;
Eric Laurent65b65452010-06-01 23:49:17 -07003562 int lSessionId;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003563
3564 // check calling permissions
3565 if (!recordingAllowed()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003566 lStatus = PERMISSION_DENIED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003567 goto Exit;
3568 }
3569
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003570 // add client to list
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003571 { // scope for mLock
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003572 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07003573 thread = checkRecordThread_l(input);
3574 if (thread == NULL) {
3575 lStatus = BAD_VALUE;
3576 goto Exit;
3577 }
3578
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003579 wclient = mClients.valueFor(pid);
3580 if (wclient != NULL) {
3581 client = wclient.promote();
3582 } else {
3583 client = new Client(this, pid);
3584 mClients.add(pid, client);
3585 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003586
Eric Laurent65b65452010-06-01 23:49:17 -07003587 // If no audio session id is provided, create one here
3588 if (sessionId != NULL && *sessionId != 0) {
3589 lSessionId = *sessionId;
3590 } else {
3591 lSessionId = nextUniqueId();
3592 if (sessionId != NULL) {
3593 *sessionId = lSessionId;
3594 }
3595 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003596 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurenta553c252009-07-17 12:17:14 -07003597 recordTrack = new RecordThread::RecordTrack(thread, client, sampleRate,
Eric Laurent65b65452010-06-01 23:49:17 -07003598 format, channelCount, frameCount, flags, lSessionId);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003599 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003600 if (recordTrack->getCblk() == NULL) {
Eric Laurentb9481d82009-09-17 05:12:56 -07003601 // remove local strong reference to Client before deleting the RecordTrack so that the Client
3602 // destructor is called by the TrackBase destructor with mLock held
3603 client.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003604 recordTrack.clear();
3605 lStatus = NO_MEMORY;
3606 goto Exit;
3607 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003608
3609 // return to handle to client
3610 recordHandle = new RecordHandle(recordTrack);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003611 lStatus = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003612
3613Exit:
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003614 if (status) {
3615 *status = lStatus;
3616 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003617 return recordHandle;
3618}
3619
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003620// ----------------------------------------------------------------------------
3621
Eric Laurenta553c252009-07-17 12:17:14 -07003622AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003623 : BnAudioRecord(),
3624 mRecordTrack(recordTrack)
3625{
3626}
3627
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003628AudioFlinger::RecordHandle::~RecordHandle() {
3629 stop();
3630}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003631
3632status_t AudioFlinger::RecordHandle::start() {
3633 LOGV("RecordHandle::start()");
3634 return mRecordTrack->start();
3635}
3636
3637void AudioFlinger::RecordHandle::stop() {
3638 LOGV("RecordHandle::stop()");
3639 mRecordTrack->stop();
3640}
3641
3642sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
3643 return mRecordTrack->getCblk();
3644}
3645
3646status_t AudioFlinger::RecordHandle::onTransact(
3647 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3648{
3649 return BnAudioRecord::onTransact(code, data, reply, flags);
3650}
3651
3652// ----------------------------------------------------------------------------
3653
Eric Laurent49f02be2009-11-19 09:00:56 -08003654AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger, AudioStreamIn *input, uint32_t sampleRate, uint32_t channels, int id) :
3655 ThreadBase(audioFlinger, id),
Eric Laurenta553c252009-07-17 12:17:14 -07003656 mInput(input), mResampler(0), mRsmpOutBuffer(0), mRsmpInBuffer(0)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003657{
Eric Laurenta553c252009-07-17 12:17:14 -07003658 mReqChannelCount = AudioSystem::popCount(channels);
3659 mReqSampleRate = sampleRate;
3660 readInputParameters();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003661}
3662
Eric Laurenta553c252009-07-17 12:17:14 -07003663
3664AudioFlinger::RecordThread::~RecordThread()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003665{
Eric Laurenta553c252009-07-17 12:17:14 -07003666 delete[] mRsmpInBuffer;
3667 if (mResampler != 0) {
3668 delete mResampler;
3669 delete[] mRsmpOutBuffer;
3670 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003671}
3672
Eric Laurenta553c252009-07-17 12:17:14 -07003673void AudioFlinger::RecordThread::onFirstRef()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003674{
Eric Laurenta553c252009-07-17 12:17:14 -07003675 const size_t SIZE = 256;
3676 char buffer[SIZE];
3677
3678 snprintf(buffer, SIZE, "Record Thread %p", this);
3679
3680 run(buffer, PRIORITY_URGENT_AUDIO);
3681}
Eric Laurent49f02be2009-11-19 09:00:56 -08003682
Eric Laurenta553c252009-07-17 12:17:14 -07003683bool AudioFlinger::RecordThread::threadLoop()
3684{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003685 AudioBufferProvider::Buffer buffer;
Eric Laurenta553c252009-07-17 12:17:14 -07003686 sp<RecordTrack> activeTrack;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003687
3688 // start recording
3689 while (!exitPending()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003690
Eric Laurenta553c252009-07-17 12:17:14 -07003691 processConfigEvents();
3692
3693 { // scope for mLock
3694 Mutex::Autolock _l(mLock);
3695 checkForNewParameters_l();
3696 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
3697 if (!mStandby) {
3698 mInput->standby();
3699 mStandby = true;
3700 }
3701
3702 if (exitPending()) break;
3703
3704 LOGV("RecordThread: loop stopping");
3705 // go to sleep
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003706 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07003707 LOGV("RecordThread: loop starting");
3708 continue;
3709 }
3710 if (mActiveTrack != 0) {
3711 if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08003712 if (!mStandby) {
3713 mInput->standby();
3714 mStandby = true;
3715 }
Eric Laurenta553c252009-07-17 12:17:14 -07003716 mActiveTrack.clear();
3717 mStartStopCond.broadcast();
3718 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
Eric Laurenta553c252009-07-17 12:17:14 -07003719 if (mReqChannelCount != mActiveTrack->channelCount()) {
3720 mActiveTrack.clear();
Eric Laurent9cc489a22009-12-05 05:20:01 -08003721 mStartStopCond.broadcast();
3722 } else if (mBytesRead != 0) {
3723 // record start succeeds only if first read from audio input
3724 // succeeds
3725 if (mBytesRead > 0) {
3726 mActiveTrack->mState = TrackBase::ACTIVE;
3727 } else {
3728 mActiveTrack.clear();
3729 }
3730 mStartStopCond.broadcast();
Eric Laurenta553c252009-07-17 12:17:14 -07003731 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08003732 mStandby = false;
Eric Laurenta553c252009-07-17 12:17:14 -07003733 }
Eric Laurenta553c252009-07-17 12:17:14 -07003734 }
3735 }
3736
3737 if (mActiveTrack != 0) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08003738 if (mActiveTrack->mState != TrackBase::ACTIVE &&
3739 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent49f02be2009-11-19 09:00:56 -08003740 usleep(5000);
3741 continue;
3742 }
Eric Laurenta553c252009-07-17 12:17:14 -07003743 buffer.frameCount = mFrameCount;
3744 if (LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
3745 size_t framesOut = buffer.frameCount;
3746 if (mResampler == 0) {
3747 // no resampling
3748 while (framesOut) {
3749 size_t framesIn = mFrameCount - mRsmpInIndex;
3750 if (framesIn) {
3751 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
3752 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
3753 if (framesIn > framesOut)
3754 framesIn = framesOut;
3755 mRsmpInIndex += framesIn;
3756 framesOut -= framesIn;
Eric Laurentb0a01472010-05-14 05:45:46 -07003757 if ((int)mChannelCount == mReqChannelCount ||
Eric Laurenta553c252009-07-17 12:17:14 -07003758 mFormat != AudioSystem::PCM_16_BIT) {
3759 memcpy(dst, src, framesIn * mFrameSize);
3760 } else {
3761 int16_t *src16 = (int16_t *)src;
3762 int16_t *dst16 = (int16_t *)dst;
3763 if (mChannelCount == 1) {
3764 while (framesIn--) {
3765 *dst16++ = *src16;
3766 *dst16++ = *src16++;
3767 }
3768 } else {
3769 while (framesIn--) {
3770 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
3771 src16 += 2;
3772 }
3773 }
3774 }
3775 }
3776 if (framesOut && mFrameCount == mRsmpInIndex) {
Eric Laurenta553c252009-07-17 12:17:14 -07003777 if (framesOut == mFrameCount &&
Eric Laurentb0a01472010-05-14 05:45:46 -07003778 ((int)mChannelCount == mReqChannelCount || mFormat != AudioSystem::PCM_16_BIT)) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08003779 mBytesRead = mInput->read(buffer.raw, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07003780 framesOut = 0;
3781 } else {
Eric Laurent9cc489a22009-12-05 05:20:01 -08003782 mBytesRead = mInput->read(mRsmpInBuffer, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07003783 mRsmpInIndex = 0;
3784 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08003785 if (mBytesRead < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003786 LOGE("Error reading audio input");
Eric Laurent9cc489a22009-12-05 05:20:01 -08003787 if (mActiveTrack->mState == TrackBase::ACTIVE) {
Eric Laurentba8811f2010-03-02 18:38:06 -08003788 // Force input into standby so that it tries to
3789 // recover at next read attempt
3790 mInput->standby();
3791 usleep(5000);
Eric Laurent9cc489a22009-12-05 05:20:01 -08003792 }
Eric Laurenta553c252009-07-17 12:17:14 -07003793 mRsmpInIndex = mFrameCount;
3794 framesOut = 0;
3795 buffer.frameCount = 0;
3796 }
3797 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003798 }
3799 } else {
Eric Laurenta553c252009-07-17 12:17:14 -07003800 // resampling
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003801
Eric Laurenta553c252009-07-17 12:17:14 -07003802 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
3803 // alter output frame count as if we were expecting stereo samples
3804 if (mChannelCount == 1 && mReqChannelCount == 1) {
3805 framesOut >>= 1;
3806 }
3807 mResampler->resample(mRsmpOutBuffer, framesOut, this);
3808 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
3809 // are 32 bit aligned which should be always true.
3810 if (mChannelCount == 2 && mReqChannelCount == 1) {
3811 AudioMixer::ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
3812 // the resampler always outputs stereo samples: do post stereo to mono conversion
3813 int16_t *src = (int16_t *)mRsmpOutBuffer;
3814 int16_t *dst = buffer.i16;
3815 while (framesOut--) {
3816 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
3817 src += 2;
3818 }
3819 } else {
3820 AudioMixer::ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
3821 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003822
Eric Laurenta553c252009-07-17 12:17:14 -07003823 }
3824 mActiveTrack->releaseBuffer(&buffer);
3825 mActiveTrack->overflow();
3826 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003827 // client isn't retrieving buffers fast enough
3828 else {
Eric Laurenta553c252009-07-17 12:17:14 -07003829 if (!mActiveTrack->setOverflow())
3830 LOGW("RecordThread: buffer overflow");
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003831 // Release the processor for a while before asking for a new buffer.
3832 // This will give the application more chance to read from the buffer and
3833 // clear the overflow.
3834 usleep(5000);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003835 }
3836 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003837 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003838
Eric Laurenta553c252009-07-17 12:17:14 -07003839 if (!mStandby) {
3840 mInput->standby();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003841 }
Eric Laurenta553c252009-07-17 12:17:14 -07003842 mActiveTrack.clear();
3843
Eric Laurent49f02be2009-11-19 09:00:56 -08003844 mStartStopCond.broadcast();
3845
Eric Laurenta553c252009-07-17 12:17:14 -07003846 LOGV("RecordThread %p exiting", this);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003847 return false;
3848}
3849
Eric Laurenta553c252009-07-17 12:17:14 -07003850status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003851{
Eric Laurenta553c252009-07-17 12:17:14 -07003852 LOGV("RecordThread::start");
Eric Laurent49f02be2009-11-19 09:00:56 -08003853 sp <ThreadBase> strongMe = this;
3854 status_t status = NO_ERROR;
3855 {
3856 AutoMutex lock(&mLock);
3857 if (mActiveTrack != 0) {
3858 if (recordTrack != mActiveTrack.get()) {
3859 status = -EBUSY;
3860 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08003861 mActiveTrack->mState = TrackBase::ACTIVE;
Eric Laurent49f02be2009-11-19 09:00:56 -08003862 }
3863 return status;
3864 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003865
Eric Laurent49f02be2009-11-19 09:00:56 -08003866 recordTrack->mState = TrackBase::IDLE;
3867 mActiveTrack = recordTrack;
3868 mLock.unlock();
3869 status_t status = AudioSystem::startInput(mId);
3870 mLock.lock();
3871 if (status != NO_ERROR) {
3872 mActiveTrack.clear();
3873 return status;
3874 }
3875 mActiveTrack->mState = TrackBase::RESUMING;
Eric Laurent9cc489a22009-12-05 05:20:01 -08003876 mRsmpInIndex = mFrameCount;
3877 mBytesRead = 0;
Eric Laurent49f02be2009-11-19 09:00:56 -08003878 // signal thread to start
3879 LOGV("Signal record thread");
3880 mWaitWorkCV.signal();
3881 // do not wait for mStartStopCond if exiting
3882 if (mExiting) {
3883 mActiveTrack.clear();
3884 status = INVALID_OPERATION;
3885 goto startError;
3886 }
3887 mStartStopCond.wait(mLock);
3888 if (mActiveTrack == 0) {
3889 LOGV("Record failed to start");
3890 status = BAD_VALUE;
3891 goto startError;
3892 }
Eric Laurenta553c252009-07-17 12:17:14 -07003893 LOGV("Record started OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08003894 return status;
Eric Laurenta553c252009-07-17 12:17:14 -07003895 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003896startError:
3897 AudioSystem::stopInput(mId);
3898 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003899}
3900
Eric Laurenta553c252009-07-17 12:17:14 -07003901void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
3902 LOGV("RecordThread::stop");
Eric Laurent49f02be2009-11-19 09:00:56 -08003903 sp <ThreadBase> strongMe = this;
3904 {
3905 AutoMutex lock(&mLock);
3906 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
3907 mActiveTrack->mState = TrackBase::PAUSING;
3908 // do not wait for mStartStopCond if exiting
3909 if (mExiting) {
3910 return;
3911 }
3912 mStartStopCond.wait(mLock);
3913 // if we have been restarted, recordTrack == mActiveTrack.get() here
3914 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
3915 mLock.unlock();
3916 AudioSystem::stopInput(mId);
3917 mLock.lock();
Eric Laurent9cc489a22009-12-05 05:20:01 -08003918 LOGV("Record stopped OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08003919 }
3920 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003921 }
3922}
3923
Eric Laurenta553c252009-07-17 12:17:14 -07003924status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003925{
3926 const size_t SIZE = 256;
3927 char buffer[SIZE];
3928 String8 result;
3929 pid_t pid = 0;
3930
Eric Laurent3fdb1262009-11-07 00:01:32 -08003931 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
3932 result.append(buffer);
3933
3934 if (mActiveTrack != 0) {
3935 result.append("Active Track:\n");
Eric Laurent65b65452010-06-01 23:49:17 -07003936 result.append(" Clien Fmt Chn Session Buf S SRate Serv User\n");
Eric Laurent3fdb1262009-11-07 00:01:32 -08003937 mActiveTrack->dump(buffer, SIZE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003938 result.append(buffer);
Eric Laurent3fdb1262009-11-07 00:01:32 -08003939
3940 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
3941 result.append(buffer);
3942 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
3943 result.append(buffer);
3944 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != 0));
3945 result.append(buffer);
3946 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
3947 result.append(buffer);
3948 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
3949 result.append(buffer);
3950
3951
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003952 } else {
3953 result.append("No record client\n");
3954 }
3955 write(fd, result.string(), result.size());
Eric Laurent3fdb1262009-11-07 00:01:32 -08003956
3957 dumpBase(fd, args);
3958
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003959 return NO_ERROR;
3960}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003961
Eric Laurenta553c252009-07-17 12:17:14 -07003962status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3963{
3964 size_t framesReq = buffer->frameCount;
3965 size_t framesReady = mFrameCount - mRsmpInIndex;
3966 int channelCount;
3967
3968 if (framesReady == 0) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08003969 mBytesRead = mInput->read(mRsmpInBuffer, mInputBytes);
3970 if (mBytesRead < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003971 LOGE("RecordThread::getNextBuffer() Error reading audio input");
Eric Laurent9cc489a22009-12-05 05:20:01 -08003972 if (mActiveTrack->mState == TrackBase::ACTIVE) {
Eric Laurentba8811f2010-03-02 18:38:06 -08003973 // Force input into standby so that it tries to
3974 // recover at next read attempt
3975 mInput->standby();
3976 usleep(5000);
Eric Laurent9cc489a22009-12-05 05:20:01 -08003977 }
Eric Laurenta553c252009-07-17 12:17:14 -07003978 buffer->raw = 0;
3979 buffer->frameCount = 0;
3980 return NOT_ENOUGH_DATA;
3981 }
3982 mRsmpInIndex = 0;
3983 framesReady = mFrameCount;
3984 }
3985
3986 if (framesReq > framesReady) {
3987 framesReq = framesReady;
3988 }
3989
3990 if (mChannelCount == 1 && mReqChannelCount == 2) {
3991 channelCount = 1;
3992 } else {
3993 channelCount = 2;
3994 }
3995 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
3996 buffer->frameCount = framesReq;
3997 return NO_ERROR;
3998}
3999
4000void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4001{
4002 mRsmpInIndex += buffer->frameCount;
4003 buffer->frameCount = 0;
4004}
4005
4006bool AudioFlinger::RecordThread::checkForNewParameters_l()
4007{
4008 bool reconfig = false;
4009
Eric Laurent8fce46a2009-08-04 09:45:33 -07004010 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07004011 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07004012 String8 keyValuePair = mNewParameters[0];
4013 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07004014 int value;
4015 int reqFormat = mFormat;
4016 int reqSamplingRate = mReqSampleRate;
4017 int reqChannelCount = mReqChannelCount;
Eric Laurent8fce46a2009-08-04 09:45:33 -07004018
Eric Laurenta553c252009-07-17 12:17:14 -07004019 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4020 reqSamplingRate = value;
4021 reconfig = true;
4022 }
4023 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
4024 reqFormat = value;
4025 reconfig = true;
4026 }
4027 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
4028 reqChannelCount = AudioSystem::popCount(value);
4029 reconfig = true;
4030 }
4031 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4032 // do not accept frame count changes if tracks are open as the track buffer
4033 // size depends on frame count and correct behavior would not be garantied
4034 // if frame count is changed after track creation
4035 if (mActiveTrack != 0) {
4036 status = INVALID_OPERATION;
4037 } else {
4038 reconfig = true;
4039 }
4040 }
4041 if (status == NO_ERROR) {
Eric Laurent8fce46a2009-08-04 09:45:33 -07004042 status = mInput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07004043 if (status == INVALID_OPERATION) {
4044 mInput->standby();
Eric Laurent8fce46a2009-08-04 09:45:33 -07004045 status = mInput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07004046 }
4047 if (reconfig) {
4048 if (status == BAD_VALUE &&
4049 reqFormat == mInput->format() && reqFormat == AudioSystem::PCM_16_BIT &&
4050 ((int)mInput->sampleRate() <= 2 * reqSamplingRate) &&
4051 (AudioSystem::popCount(mInput->channels()) < 3) && (reqChannelCount < 3)) {
4052 status = NO_ERROR;
4053 }
4054 if (status == NO_ERROR) {
4055 readInputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07004056 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07004057 }
4058 }
4059 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08004060
4061 mNewParameters.removeAt(0);
4062
Eric Laurenta553c252009-07-17 12:17:14 -07004063 mParamStatus = status;
4064 mParamCond.signal();
Eric Laurent8fce46a2009-08-04 09:45:33 -07004065 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07004066 }
4067 return reconfig;
4068}
4069
4070String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4071{
4072 return mInput->getParameters(keys);
4073}
4074
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004075void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
Eric Laurenta553c252009-07-17 12:17:14 -07004076 AudioSystem::OutputDescriptor desc;
4077 void *param2 = 0;
4078
4079 switch (event) {
4080 case AudioSystem::INPUT_OPENED:
4081 case AudioSystem::INPUT_CONFIG_CHANGED:
Eric Laurentb0a01472010-05-14 05:45:46 -07004082 desc.channels = mChannels;
Eric Laurenta553c252009-07-17 12:17:14 -07004083 desc.samplingRate = mSampleRate;
4084 desc.format = mFormat;
4085 desc.frameCount = mFrameCount;
4086 desc.latency = 0;
4087 param2 = &desc;
4088 break;
4089
4090 case AudioSystem::INPUT_CLOSED:
4091 default:
4092 break;
4093 }
Eric Laurent49f02be2009-11-19 09:00:56 -08004094 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurenta553c252009-07-17 12:17:14 -07004095}
4096
4097void AudioFlinger::RecordThread::readInputParameters()
4098{
4099 if (mRsmpInBuffer) delete mRsmpInBuffer;
4100 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
4101 if (mResampler) delete mResampler;
4102 mResampler = 0;
4103
4104 mSampleRate = mInput->sampleRate();
Eric Laurentb0a01472010-05-14 05:45:46 -07004105 mChannels = mInput->channels();
4106 mChannelCount = (uint16_t)AudioSystem::popCount(mChannels);
Eric Laurenta553c252009-07-17 12:17:14 -07004107 mFormat = mInput->format();
Eric Laurentb0a01472010-05-14 05:45:46 -07004108 mFrameSize = (uint16_t)mInput->frameSize();
Eric Laurenta553c252009-07-17 12:17:14 -07004109 mInputBytes = mInput->bufferSize();
4110 mFrameCount = mInputBytes / mFrameSize;
4111 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4112
4113 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4114 {
4115 int channelCount;
4116 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4117 // stereo to mono post process as the resampler always outputs stereo.
4118 if (mChannelCount == 1 && mReqChannelCount == 2) {
4119 channelCount = 1;
4120 } else {
4121 channelCount = 2;
4122 }
4123 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4124 mResampler->setSampleRate(mSampleRate);
4125 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4126 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4127
4128 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4129 if (mChannelCount == 1 && mReqChannelCount == 1) {
4130 mFrameCount >>= 1;
4131 }
4132
4133 }
4134 mRsmpInIndex = mFrameCount;
4135}
4136
Eric Laurent47d0a922010-02-26 02:47:27 -08004137unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4138{
4139 return mInput->getInputFramesLost();
4140}
4141
Eric Laurenta553c252009-07-17 12:17:14 -07004142// ----------------------------------------------------------------------------
4143
Eric Laurentddb78e72009-07-28 08:44:33 -07004144int AudioFlinger::openOutput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07004145 uint32_t *pSamplingRate,
4146 uint32_t *pFormat,
4147 uint32_t *pChannels,
4148 uint32_t *pLatencyMs,
4149 uint32_t flags)
4150{
4151 status_t status;
4152 PlaybackThread *thread = NULL;
4153 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4154 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4155 uint32_t format = pFormat ? *pFormat : 0;
4156 uint32_t channels = pChannels ? *pChannels : 0;
4157 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
4158
4159 LOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
4160 pDevices ? *pDevices : 0,
4161 samplingRate,
4162 format,
4163 channels,
4164 flags);
4165
4166 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004167 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004168 }
4169 Mutex::Autolock _l(mLock);
4170
4171 AudioStreamOut *output = mAudioHardware->openOutputStream(*pDevices,
4172 (int *)&format,
4173 &channels,
4174 &samplingRate,
4175 &status);
4176 LOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
4177 output,
4178 samplingRate,
4179 format,
4180 channels,
4181 status);
4182
4183 mHardwareStatus = AUDIO_HW_IDLE;
4184 if (output != 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07004185 int id = nextUniqueId();
Eric Laurenta553c252009-07-17 12:17:14 -07004186 if ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) ||
4187 (format != AudioSystem::PCM_16_BIT) ||
4188 (channels != AudioSystem::CHANNEL_OUT_STEREO)) {
Eric Laurent65b65452010-06-01 23:49:17 -07004189 thread = new DirectOutputThread(this, output, id, *pDevices);
4190 LOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004191 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07004192 thread = new MixerThread(this, output, id, *pDevices);
4193 LOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Glenn Kasten871c16c2010-03-05 12:18:01 -08004194
4195#ifdef LVMX
4196 unsigned bitsPerSample =
4197 (format == AudioSystem::PCM_16_BIT) ? 16 :
4198 ((format == AudioSystem::PCM_8_BIT) ? 8 : 0);
4199 unsigned channelCount = (channels == AudioSystem::CHANNEL_OUT_STEREO) ? 2 : 1;
4200 int audioOutputType = LifeVibes::threadIdToAudioOutputType(thread->id());
4201
4202 LifeVibes::init_aot(audioOutputType, samplingRate, bitsPerSample, channelCount);
4203 LifeVibes::setDevice(audioOutputType, *pDevices);
4204#endif
4205
Eric Laurenta553c252009-07-17 12:17:14 -07004206 }
Eric Laurent65b65452010-06-01 23:49:17 -07004207 mPlaybackThreads.add(id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004208
4209 if (pSamplingRate) *pSamplingRate = samplingRate;
4210 if (pFormat) *pFormat = format;
4211 if (pChannels) *pChannels = channels;
4212 if (pLatencyMs) *pLatencyMs = thread->latency();
Eric Laurent9cc489a22009-12-05 05:20:01 -08004213
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004214 // notify client processes of the new output creation
4215 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004216 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004217 }
4218
Eric Laurent9cc489a22009-12-05 05:20:01 -08004219 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004220}
4221
Eric Laurentddb78e72009-07-28 08:44:33 -07004222int AudioFlinger::openDuplicateOutput(int output1, int output2)
Eric Laurenta553c252009-07-17 12:17:14 -07004223{
4224 Mutex::Autolock _l(mLock);
Eric Laurentddb78e72009-07-28 08:44:33 -07004225 MixerThread *thread1 = checkMixerThread_l(output1);
4226 MixerThread *thread2 = checkMixerThread_l(output2);
Eric Laurenta553c252009-07-17 12:17:14 -07004227
Eric Laurentddb78e72009-07-28 08:44:33 -07004228 if (thread1 == NULL || thread2 == NULL) {
4229 LOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
4230 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004231 }
4232
Eric Laurent65b65452010-06-01 23:49:17 -07004233 int id = nextUniqueId();
4234 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
Eric Laurentddb78e72009-07-28 08:44:33 -07004235 thread->addOutputTrack(thread2);
Eric Laurent65b65452010-06-01 23:49:17 -07004236 mPlaybackThreads.add(id, thread);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004237 // notify client processes of the new output creation
4238 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004239 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004240}
4241
Eric Laurentddb78e72009-07-28 08:44:33 -07004242status_t AudioFlinger::closeOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004243{
Eric Laurent49018a52009-08-04 08:37:05 -07004244 // keep strong reference on the playback thread so that
4245 // it is not destroyed while exit() is executed
4246 sp <PlaybackThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07004247 {
4248 Mutex::Autolock _l(mLock);
4249 thread = checkPlaybackThread_l(output);
4250 if (thread == NULL) {
4251 return BAD_VALUE;
4252 }
4253
Eric Laurentddb78e72009-07-28 08:44:33 -07004254 LOGV("closeOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004255
4256 if (thread->type() == PlaybackThread::MIXER) {
4257 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004258 if (mPlaybackThreads.valueAt(i)->type() == PlaybackThread::DUPLICATING) {
4259 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Eric Laurent49018a52009-08-04 08:37:05 -07004260 dupThread->removeOutputTrack((MixerThread *)thread.get());
Eric Laurenta553c252009-07-17 12:17:14 -07004261 }
4262 }
4263 }
Eric Laurent296a0ec2009-09-15 07:10:12 -07004264 void *param2 = 0;
Eric Laurent49f02be2009-11-19 09:00:56 -08004265 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
Eric Laurentddb78e72009-07-28 08:44:33 -07004266 mPlaybackThreads.removeItem(output);
Eric Laurenta553c252009-07-17 12:17:14 -07004267 }
4268 thread->exit();
4269
Eric Laurent49018a52009-08-04 08:37:05 -07004270 if (thread->type() != PlaybackThread::DUPLICATING) {
4271 mAudioHardware->closeOutputStream(thread->getOutput());
4272 }
Eric Laurenta553c252009-07-17 12:17:14 -07004273 return NO_ERROR;
4274}
4275
Eric Laurentddb78e72009-07-28 08:44:33 -07004276status_t AudioFlinger::suspendOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004277{
4278 Mutex::Autolock _l(mLock);
4279 PlaybackThread *thread = checkPlaybackThread_l(output);
4280
4281 if (thread == NULL) {
4282 return BAD_VALUE;
4283 }
4284
Eric Laurentddb78e72009-07-28 08:44:33 -07004285 LOGV("suspendOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004286 thread->suspend();
4287
4288 return NO_ERROR;
4289}
4290
Eric Laurentddb78e72009-07-28 08:44:33 -07004291status_t AudioFlinger::restoreOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004292{
4293 Mutex::Autolock _l(mLock);
4294 PlaybackThread *thread = checkPlaybackThread_l(output);
4295
4296 if (thread == NULL) {
4297 return BAD_VALUE;
4298 }
4299
Eric Laurentddb78e72009-07-28 08:44:33 -07004300 LOGV("restoreOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004301
4302 thread->restore();
4303
4304 return NO_ERROR;
4305}
4306
Eric Laurentddb78e72009-07-28 08:44:33 -07004307int AudioFlinger::openInput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07004308 uint32_t *pSamplingRate,
4309 uint32_t *pFormat,
4310 uint32_t *pChannels,
4311 uint32_t acoustics)
4312{
4313 status_t status;
4314 RecordThread *thread = NULL;
4315 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4316 uint32_t format = pFormat ? *pFormat : 0;
4317 uint32_t channels = pChannels ? *pChannels : 0;
4318 uint32_t reqSamplingRate = samplingRate;
4319 uint32_t reqFormat = format;
4320 uint32_t reqChannels = channels;
4321
4322 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004323 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004324 }
4325 Mutex::Autolock _l(mLock);
4326
4327 AudioStreamIn *input = mAudioHardware->openInputStream(*pDevices,
4328 (int *)&format,
4329 &channels,
4330 &samplingRate,
4331 &status,
4332 (AudioSystem::audio_in_acoustics)acoustics);
4333 LOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
4334 input,
4335 samplingRate,
4336 format,
4337 channels,
4338 acoustics,
4339 status);
4340
4341 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
4342 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
4343 // or stereo to mono conversions on 16 bit PCM inputs.
4344 if (input == 0 && status == BAD_VALUE &&
4345 reqFormat == format && format == AudioSystem::PCM_16_BIT &&
4346 (samplingRate <= 2 * reqSamplingRate) &&
4347 (AudioSystem::popCount(channels) < 3) && (AudioSystem::popCount(reqChannels) < 3)) {
4348 LOGV("openInput() reopening with proposed sampling rate and channels");
4349 input = mAudioHardware->openInputStream(*pDevices,
4350 (int *)&format,
4351 &channels,
4352 &samplingRate,
4353 &status,
4354 (AudioSystem::audio_in_acoustics)acoustics);
4355 }
4356
4357 if (input != 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07004358 int id = nextUniqueId();
Eric Laurenta553c252009-07-17 12:17:14 -07004359 // Start record thread
Eric Laurent65b65452010-06-01 23:49:17 -07004360 thread = new RecordThread(this, input, reqSamplingRate, reqChannels, id);
4361 mRecordThreads.add(id, thread);
4362 LOGV("openInput() created record thread: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004363 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
4364 if (pFormat) *pFormat = format;
4365 if (pChannels) *pChannels = reqChannels;
4366
4367 input->standby();
Eric Laurent9cc489a22009-12-05 05:20:01 -08004368
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004369 // notify client processes of the new input creation
4370 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004371 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004372 }
4373
Eric Laurent9cc489a22009-12-05 05:20:01 -08004374 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004375}
4376
Eric Laurentddb78e72009-07-28 08:44:33 -07004377status_t AudioFlinger::closeInput(int input)
Eric Laurenta553c252009-07-17 12:17:14 -07004378{
Eric Laurent49018a52009-08-04 08:37:05 -07004379 // keep strong reference on the record thread so that
4380 // it is not destroyed while exit() is executed
4381 sp <RecordThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07004382 {
4383 Mutex::Autolock _l(mLock);
4384 thread = checkRecordThread_l(input);
4385 if (thread == NULL) {
4386 return BAD_VALUE;
4387 }
4388
Eric Laurentddb78e72009-07-28 08:44:33 -07004389 LOGV("closeInput() %d", input);
Eric Laurent296a0ec2009-09-15 07:10:12 -07004390 void *param2 = 0;
Eric Laurent49f02be2009-11-19 09:00:56 -08004391 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
Eric Laurentddb78e72009-07-28 08:44:33 -07004392 mRecordThreads.removeItem(input);
Eric Laurenta553c252009-07-17 12:17:14 -07004393 }
4394 thread->exit();
4395
Eric Laurent49018a52009-08-04 08:37:05 -07004396 mAudioHardware->closeInputStream(thread->getInput());
4397
Eric Laurenta553c252009-07-17 12:17:14 -07004398 return NO_ERROR;
4399}
4400
Eric Laurentddb78e72009-07-28 08:44:33 -07004401status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004402{
4403 Mutex::Autolock _l(mLock);
4404 MixerThread *dstThread = checkMixerThread_l(output);
4405 if (dstThread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004406 LOGW("setStreamOutput() bad output id %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004407 return BAD_VALUE;
4408 }
4409
Eric Laurentddb78e72009-07-28 08:44:33 -07004410 LOGV("setStreamOutput() stream %d to output %d", stream, output);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004411 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
Eric Laurenta553c252009-07-17 12:17:14 -07004412
4413 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004414 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurenta553c252009-07-17 12:17:14 -07004415 if (thread != dstThread &&
4416 thread->type() != PlaybackThread::DIRECT) {
4417 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004418 srcThread->invalidateTracks(stream);
Eric Laurenta553c252009-07-17 12:17:14 -07004419 }
4420 }
Eric Laurentd069f322009-09-01 05:56:26 -07004421
Eric Laurenta553c252009-07-17 12:17:14 -07004422 return NO_ERROR;
4423}
4424
Eric Laurent65b65452010-06-01 23:49:17 -07004425
4426int AudioFlinger::newAudioSessionId()
4427{
4428 return nextUniqueId();
4429}
4430
Eric Laurenta553c252009-07-17 12:17:14 -07004431// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07004432AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
Eric Laurenta553c252009-07-17 12:17:14 -07004433{
4434 PlaybackThread *thread = NULL;
Eric Laurentddb78e72009-07-28 08:44:33 -07004435 if (mPlaybackThreads.indexOfKey(output) >= 0) {
4436 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
Eric Laurenta553c252009-07-17 12:17:14 -07004437 }
Eric Laurenta553c252009-07-17 12:17:14 -07004438 return thread;
4439}
4440
4441// checkMixerThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07004442AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
Eric Laurenta553c252009-07-17 12:17:14 -07004443{
4444 PlaybackThread *thread = checkPlaybackThread_l(output);
4445 if (thread != NULL) {
4446 if (thread->type() == PlaybackThread::DIRECT) {
4447 thread = NULL;
4448 }
4449 }
4450 return (MixerThread *)thread;
4451}
4452
4453// checkRecordThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07004454AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
Eric Laurenta553c252009-07-17 12:17:14 -07004455{
4456 RecordThread *thread = NULL;
Eric Laurentddb78e72009-07-28 08:44:33 -07004457 if (mRecordThreads.indexOfKey(input) >= 0) {
4458 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
Eric Laurenta553c252009-07-17 12:17:14 -07004459 }
Eric Laurenta553c252009-07-17 12:17:14 -07004460 return thread;
4461}
4462
Eric Laurent65b65452010-06-01 23:49:17 -07004463int AudioFlinger::nextUniqueId()
4464{
4465 return android_atomic_inc(&mNextUniqueId);
4466}
4467
4468// ----------------------------------------------------------------------------
4469// Effect management
4470// ----------------------------------------------------------------------------
4471
4472
4473status_t AudioFlinger::loadEffectLibrary(const char *libPath, int *handle)
4474{
4475 Mutex::Autolock _l(mLock);
4476 return EffectLoadLibrary(libPath, handle);
4477}
4478
4479status_t AudioFlinger::unloadEffectLibrary(int handle)
4480{
4481 Mutex::Autolock _l(mLock);
4482 return EffectUnloadLibrary(handle);
4483}
4484
4485status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects)
4486{
4487 Mutex::Autolock _l(mLock);
4488 return EffectQueryNumberEffects(numEffects);
4489}
4490
Eric Laurent53334cd2010-06-23 17:38:20 -07004491status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor)
Eric Laurent65b65452010-06-01 23:49:17 -07004492{
4493 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07004494 return EffectQueryEffect(index, descriptor);
Eric Laurent65b65452010-06-01 23:49:17 -07004495}
4496
4497status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid, effect_descriptor_t *descriptor)
4498{
4499 Mutex::Autolock _l(mLock);
4500 return EffectGetDescriptor(pUuid, descriptor);
4501}
4502
Eric Laurentdf9b81c2010-07-02 08:12:41 -07004503
4504// this UUID must match the one defined in media/libeffects/EffectVisualizer.cpp
4505static const effect_uuid_t VISUALIZATION_UUID_ =
4506 {0xd069d9e0, 0x8329, 0x11df, 0x9168, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}};
4507
Eric Laurent65b65452010-06-01 23:49:17 -07004508sp<IEffect> AudioFlinger::createEffect(pid_t pid,
4509 effect_descriptor_t *pDesc,
4510 const sp<IEffectClient>& effectClient,
4511 int32_t priority,
4512 int output,
4513 int sessionId,
4514 status_t *status,
4515 int *id,
4516 int *enabled)
4517{
4518 status_t lStatus = NO_ERROR;
4519 sp<EffectHandle> handle;
4520 effect_interface_t itfe;
4521 effect_descriptor_t desc;
4522 sp<Client> client;
4523 wp<Client> wclient;
4524
4525 LOGV("createEffect pid %d, client %p, priority %d, sessionId %d, output %d", pid, effectClient.get(), priority, sessionId, output);
4526
4527 if (pDesc == NULL) {
4528 lStatus = BAD_VALUE;
4529 goto Exit;
4530 }
4531
4532 {
4533 Mutex::Autolock _l(mLock);
4534
Eric Laurentdf9b81c2010-07-02 08:12:41 -07004535 // check recording permission for visualizer
4536 if (memcmp(&pDesc->type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0 ||
4537 memcmp(&pDesc->uuid, &VISUALIZATION_UUID_, sizeof(effect_uuid_t)) == 0) {
4538 if (!recordingAllowed()) {
4539 lStatus = PERMISSION_DENIED;
4540 goto Exit;
4541 }
4542 }
4543
Eric Laurent65b65452010-06-01 23:49:17 -07004544 if (!EffectIsNullUuid(&pDesc->uuid)) {
4545 // if uuid is specified, request effect descriptor
4546 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
4547 if (lStatus < 0) {
4548 LOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
4549 goto Exit;
4550 }
4551 } else {
4552 // if uuid is not specified, look for an available implementation
4553 // of the required type in effect factory
4554 if (EffectIsNullUuid(&pDesc->type)) {
4555 LOGW("createEffect() no effect type");
4556 lStatus = BAD_VALUE;
4557 goto Exit;
4558 }
4559 uint32_t numEffects = 0;
4560 effect_descriptor_t d;
4561 bool found = false;
4562
4563 lStatus = EffectQueryNumberEffects(&numEffects);
4564 if (lStatus < 0) {
4565 LOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
4566 goto Exit;
4567 }
Eric Laurent53334cd2010-06-23 17:38:20 -07004568 for (uint32_t i = 0; i < numEffects; i++) {
4569 lStatus = EffectQueryEffect(i, &desc);
Eric Laurent65b65452010-06-01 23:49:17 -07004570 if (lStatus < 0) {
Eric Laurent53334cd2010-06-23 17:38:20 -07004571 LOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07004572 continue;
4573 }
4574 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
4575 // If matching type found save effect descriptor. If the session is
4576 // 0 and the effect is not auxiliary, continue enumeration in case
4577 // an auxiliary version of this effect type is available
4578 found = true;
4579 memcpy(&d, &desc, sizeof(effect_descriptor_t));
4580 if (sessionId != 0 ||
4581 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
4582 break;
4583 }
4584 }
4585 }
4586 if (!found) {
4587 lStatus = BAD_VALUE;
4588 LOGW("createEffect() effect not found");
4589 goto Exit;
4590 }
4591 // For same effect type, chose auxiliary version over insert version if
4592 // connect to output mix (Compliance to OpenSL ES)
4593 if (sessionId == 0 &&
4594 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
4595 memcpy(&desc, &d, sizeof(effect_descriptor_t));
4596 }
4597 }
4598
4599 // Do not allow auxiliary effects on a session different from 0 (output mix)
4600 if (sessionId != 0 &&
4601 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
4602 lStatus = INVALID_OPERATION;
4603 goto Exit;
4604 }
4605
Eric Laurent53334cd2010-06-23 17:38:20 -07004606 // Session -1 is reserved for output stage effects that can only be created
4607 // by audio policy manager (running in same process)
4608 if (sessionId == -1 && getpid() != IPCThreadState::self()->getCallingPid()) {
4609 lStatus = INVALID_OPERATION;
4610 goto Exit;
4611 }
4612
Eric Laurent65b65452010-06-01 23:49:17 -07004613 // return effect descriptor
4614 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
4615
4616 // If output is not specified try to find a matching audio session ID in one of the
4617 // output threads.
4618 // TODO: allow attachment of effect to inputs
4619 if (output == 0) {
Eric Laurent53334cd2010-06-23 17:38:20 -07004620 if (sessionId <= 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07004621 // default to first output
4622 // TODO: define criteria to choose output when not specified. Or
4623 // receive output from audio policy manager
4624 if (mPlaybackThreads.size() != 0) {
4625 output = mPlaybackThreads.keyAt(0);
4626 }
4627 } else {
4628 // look for the thread where the specified audio session is present
4629 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
4630 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId)) {
4631 output = mPlaybackThreads.keyAt(i);
4632 break;
4633 }
4634 }
4635 }
4636 }
4637 PlaybackThread *thread = checkPlaybackThread_l(output);
4638 if (thread == NULL) {
4639 LOGE("unknown output thread");
4640 lStatus = BAD_VALUE;
4641 goto Exit;
4642 }
4643
4644 wclient = mClients.valueFor(pid);
4645
4646 if (wclient != NULL) {
4647 client = wclient.promote();
4648 } else {
4649 client = new Client(this, pid);
4650 mClients.add(pid, client);
4651 }
4652
4653 // create effect on selected output trhead
4654 handle = thread->createEffect_l(client, effectClient, priority, sessionId, &desc, enabled, &lStatus);
4655 if (handle != 0 && id != NULL) {
4656 *id = handle->id();
4657 }
4658 }
4659
4660Exit:
4661 if(status) {
4662 *status = lStatus;
4663 }
4664 return handle;
4665}
4666
Eric Laurent53334cd2010-06-23 17:38:20 -07004667status_t AudioFlinger::registerEffectResource_l(effect_descriptor_t *desc) {
4668 if (mTotalEffectsCpuLoad + desc->cpuLoad > MAX_EFFECTS_CPU_LOAD) {
4669 LOGW("registerEffectResource() CPU Load limit exceeded for Fx %s, CPU %f MIPS",
4670 desc->name, (float)desc->cpuLoad/10);
4671 return INVALID_OPERATION;
4672 }
4673 if (mTotalEffectsMemory + desc->memoryUsage > MAX_EFFECTS_MEMORY) {
4674 LOGW("registerEffectResource() memory limit exceeded for Fx %s, Memory %d KB",
4675 desc->name, desc->memoryUsage);
4676 return INVALID_OPERATION;
4677 }
4678 mTotalEffectsCpuLoad += desc->cpuLoad;
4679 mTotalEffectsMemory += desc->memoryUsage;
4680 LOGV("registerEffectResource_l() effect %s, CPU %d, memory %d",
4681 desc->name, desc->cpuLoad, desc->memoryUsage);
4682 LOGV(" total CPU %d, total memory %d", mTotalEffectsCpuLoad, mTotalEffectsMemory);
4683 return NO_ERROR;
4684}
4685
4686void AudioFlinger::unregisterEffectResource_l(effect_descriptor_t *desc) {
4687 mTotalEffectsCpuLoad -= desc->cpuLoad;
4688 mTotalEffectsMemory -= desc->memoryUsage;
4689 LOGV("unregisterEffectResource_l() effect %s, CPU %d, memory %d",
4690 desc->name, desc->cpuLoad, desc->memoryUsage);
4691 LOGV(" total CPU %d, total memory %d", mTotalEffectsCpuLoad, mTotalEffectsMemory);
4692}
4693
Eric Laurent65b65452010-06-01 23:49:17 -07004694// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
4695sp<AudioFlinger::EffectHandle> AudioFlinger::PlaybackThread::createEffect_l(
4696 const sp<AudioFlinger::Client>& client,
4697 const sp<IEffectClient>& effectClient,
4698 int32_t priority,
4699 int sessionId,
4700 effect_descriptor_t *desc,
4701 int *enabled,
4702 status_t *status
4703 )
4704{
4705 sp<EffectModule> effect;
4706 sp<EffectHandle> handle;
4707 status_t lStatus;
4708 sp<Track> track;
4709 sp<EffectChain> chain;
4710 bool effectCreated = false;
Eric Laurent53334cd2010-06-23 17:38:20 -07004711 bool effectRegistered = false;
Eric Laurent65b65452010-06-01 23:49:17 -07004712
4713 if (mOutput == 0) {
4714 LOGW("createEffect_l() Audio driver not initialized.");
4715 lStatus = NO_INIT;
4716 goto Exit;
4717 }
4718
4719 // Do not allow auxiliary effect on session other than 0
4720 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY &&
4721 sessionId != 0) {
4722 LOGW("createEffect_l() Cannot add auxiliary effect %s to session %d", desc->name, sessionId);
4723 lStatus = BAD_VALUE;
4724 goto Exit;
4725 }
4726
4727 // Do not allow effects with session ID 0 on direct output or duplicating threads
4728 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
4729 if (sessionId == 0 && mType != MIXER) {
4730 LOGW("createEffect_l() Cannot add auxiliary effect %s to session %d", desc->name, sessionId);
4731 lStatus = BAD_VALUE;
4732 goto Exit;
4733 }
4734
4735 LOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
4736
4737 { // scope for mLock
4738 Mutex::Autolock _l(mLock);
4739
4740 // check for existing effect chain with the requested audio session
4741 chain = getEffectChain_l(sessionId);
4742 if (chain == 0) {
4743 // create a new chain for this session
4744 LOGV("createEffect_l() new effect chain for session %d", sessionId);
4745 chain = new EffectChain(this, sessionId);
4746 addEffectChain_l(chain);
4747 } else {
4748 effect = chain->getEffectFromDesc(desc);
4749 }
4750
4751 LOGV("createEffect_l() got effect %p on chain %p", effect == 0 ? 0 : effect.get(), chain.get());
4752
4753 if (effect == 0) {
Eric Laurent53334cd2010-06-23 17:38:20 -07004754 // Check CPU and memory usage
4755 lStatus = mAudioFlinger->registerEffectResource_l(desc);
4756 if (lStatus != NO_ERROR) {
4757 goto Exit;
4758 }
4759 effectRegistered = true;
Eric Laurent65b65452010-06-01 23:49:17 -07004760 // create a new effect module if none present in the chain
Eric Laurent65b65452010-06-01 23:49:17 -07004761 effect = new EffectModule(this, chain, desc, mAudioFlinger->nextUniqueId(), sessionId);
4762 lStatus = effect->status();
4763 if (lStatus != NO_ERROR) {
4764 goto Exit;
4765 }
Eric Laurent65b65452010-06-01 23:49:17 -07004766 lStatus = chain->addEffect(effect);
4767 if (lStatus != NO_ERROR) {
4768 goto Exit;
4769 }
Eric Laurent53334cd2010-06-23 17:38:20 -07004770 effectCreated = true;
Eric Laurent65b65452010-06-01 23:49:17 -07004771
4772 effect->setDevice(mDevice);
Eric Laurent53334cd2010-06-23 17:38:20 -07004773 effect->setMode(mAudioFlinger->getMode());
Eric Laurent65b65452010-06-01 23:49:17 -07004774 }
4775 // create effect handle and connect it to effect module
4776 handle = new EffectHandle(effect, client, effectClient, priority);
4777 lStatus = effect->addHandle(handle);
4778 if (enabled) {
4779 *enabled = (int)effect->isEnabled();
4780 }
4781 }
4782
4783Exit:
4784 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent53334cd2010-06-23 17:38:20 -07004785 if (effectCreated) {
Eric Laurent65b65452010-06-01 23:49:17 -07004786 if (chain->removeEffect(effect) == 0) {
4787 removeEffectChain_l(chain);
4788 }
4789 }
Eric Laurent53334cd2010-06-23 17:38:20 -07004790 if (effectRegistered) {
4791 mAudioFlinger->unregisterEffectResource_l(desc);
4792 }
Eric Laurent65b65452010-06-01 23:49:17 -07004793 handle.clear();
4794 }
4795
4796 if(status) {
4797 *status = lStatus;
4798 }
4799 return handle;
4800}
4801
Eric Laurent53334cd2010-06-23 17:38:20 -07004802void AudioFlinger::PlaybackThread::disconnectEffect(const sp< EffectModule>& effect,
4803 const wp<EffectHandle>& handle) {
4804 effect_descriptor_t desc = effect->desc();
4805 Mutex::Autolock _l(mLock);
4806 // delete the effect module if removing last handle on it
4807 if (effect->removeHandle(handle) == 0) {
4808 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
4809 detachAuxEffect_l(effect->id());
4810 }
4811 sp<EffectChain> chain = effect->chain().promote();
4812 if (chain != 0) {
4813 // remove effect chain if remove last effect
4814 if (chain->removeEffect(effect) == 0) {
4815 removeEffectChain_l(chain);
4816 }
4817 }
4818 mLock.unlock();
4819 mAudioFlinger->mLock.lock();
4820 mAudioFlinger->unregisterEffectResource_l(&desc);
4821 mAudioFlinger->mLock.unlock();
4822 }
4823}
4824
Eric Laurent65b65452010-06-01 23:49:17 -07004825status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
4826{
4827 int session = chain->sessionId();
4828 int16_t *buffer = mMixBuffer;
Eric Laurent53334cd2010-06-23 17:38:20 -07004829 bool ownsBuffer = false;
Eric Laurent65b65452010-06-01 23:49:17 -07004830
4831 LOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Eric Laurent53334cd2010-06-23 17:38:20 -07004832 if (session > 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07004833 // Only one effect chain can be present in direct output thread and it uses
4834 // the mix buffer as input
4835 if (mType != DIRECT) {
4836 size_t numSamples = mFrameCount * mChannelCount;
4837 buffer = new int16_t[numSamples];
4838 memset(buffer, 0, numSamples * sizeof(int16_t));
4839 LOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
4840 ownsBuffer = true;
4841 }
Eric Laurent65b65452010-06-01 23:49:17 -07004842
Eric Laurent53334cd2010-06-23 17:38:20 -07004843 // Attach all tracks with same session ID to this chain.
4844 for (size_t i = 0; i < mTracks.size(); ++i) {
4845 sp<Track> track = mTracks[i];
4846 if (session == track->sessionId()) {
4847 LOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
4848 track->setMainBuffer(buffer);
4849 }
4850 }
4851
4852 // indicate all active tracks in the chain
4853 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
4854 sp<Track> track = mActiveTracks[i].promote();
4855 if (track == 0) continue;
4856 if (session == track->sessionId()) {
4857 LOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
4858 chain->startTrack();
4859 }
Eric Laurent65b65452010-06-01 23:49:17 -07004860 }
4861 }
4862
Eric Laurent53334cd2010-06-23 17:38:20 -07004863 chain->setInBuffer(buffer, ownsBuffer);
4864 chain->setOutBuffer(mMixBuffer);
4865 // Effect chain for session -1 is inserted at end of effect chains list
4866 // in order to be processed last as it contains output stage effects
4867 // Effect chain for session 0 is inserted before session -1 to be processed
4868 // after track specific effects and before output stage
4869 // Effect chain for session other than 0 is inserted at beginning of effect
4870 // chains list to be processed before output mix effects. Relative order between
4871 // sessions other than 0 is not important
4872 size_t size = mEffectChains.size();
4873 size_t i = 0;
4874 for (i = 0; i < size; i++) {
4875 if (mEffectChains[i]->sessionId() < session) break;
Eric Laurent65b65452010-06-01 23:49:17 -07004876 }
Eric Laurent53334cd2010-06-23 17:38:20 -07004877 mEffectChains.insertAt(chain, i);
Eric Laurent65b65452010-06-01 23:49:17 -07004878
4879 return NO_ERROR;
4880}
4881
4882size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
4883{
4884 int session = chain->sessionId();
4885
4886 LOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
4887
4888 for (size_t i = 0; i < mEffectChains.size(); i++) {
4889 if (chain == mEffectChains[i]) {
4890 mEffectChains.removeAt(i);
4891 // detach all tracks with same session ID from this chain
4892 for (size_t i = 0; i < mTracks.size(); ++i) {
4893 sp<Track> track = mTracks[i];
4894 if (session == track->sessionId()) {
4895 track->setMainBuffer(mMixBuffer);
4896 }
4897 }
4898 }
4899 }
4900 return mEffectChains.size();
4901}
4902
4903void AudioFlinger::PlaybackThread::lockEffectChains_l()
4904{
4905 for (size_t i = 0; i < mEffectChains.size(); i++) {
4906 mEffectChains[i]->lock();
4907 }
4908}
4909
4910void AudioFlinger::PlaybackThread::unlockEffectChains()
4911{
4912 Mutex::Autolock _l(mLock);
4913 for (size_t i = 0; i < mEffectChains.size(); i++) {
4914 mEffectChains[i]->unlock();
4915 }
4916}
4917
4918sp<AudioFlinger::EffectModule> AudioFlinger::PlaybackThread::getEffect_l(int sessionId, int effectId)
4919{
4920 sp<EffectModule> effect;
4921
4922 sp<EffectChain> chain = getEffectChain_l(sessionId);
4923 if (chain != 0) {
4924 effect = chain->getEffectFromId(effectId);
4925 }
4926 return effect;
4927}
4928
4929status_t AudioFlinger::PlaybackThread::attachAuxEffect(const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
4930{
4931 Mutex::Autolock _l(mLock);
4932 return attachAuxEffect_l(track, EffectId);
4933}
4934
4935status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
4936{
4937 status_t status = NO_ERROR;
4938
4939 if (EffectId == 0) {
4940 track->setAuxBuffer(0, NULL);
4941 } else {
4942 // Auxiliary effects are always in audio session 0
4943 sp<EffectModule> effect = getEffect_l(0, EffectId);
4944 if (effect != 0) {
4945 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
4946 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
4947 } else {
4948 status = INVALID_OPERATION;
4949 }
4950 } else {
4951 status = BAD_VALUE;
4952 }
4953 }
4954 return status;
4955}
4956
4957void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
4958{
4959 for (size_t i = 0; i < mTracks.size(); ++i) {
4960 sp<Track> track = mTracks[i];
4961 if (track->auxEffectId() == effectId) {
4962 attachAuxEffect_l(track, 0);
4963 }
4964 }
4965}
4966
4967// ----------------------------------------------------------------------------
4968// EffectModule implementation
4969// ----------------------------------------------------------------------------
4970
4971#undef LOG_TAG
4972#define LOG_TAG "AudioFlinger::EffectModule"
4973
4974AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
4975 const wp<AudioFlinger::EffectChain>& chain,
4976 effect_descriptor_t *desc,
4977 int id,
4978 int sessionId)
4979 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
4980 mStatus(NO_INIT), mState(IDLE)
4981{
4982 LOGV("Constructor %p", this);
4983 int lStatus;
4984 sp<ThreadBase> thread = mThread.promote();
4985 if (thread == 0) {
4986 return;
4987 }
4988 PlaybackThread *p = (PlaybackThread *)thread.get();
4989
4990 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
4991
4992 // create effect engine from effect factory
Eric Laurent53334cd2010-06-23 17:38:20 -07004993 mStatus = EffectCreate(&desc->uuid, sessionId, p->id(), &mEffectInterface);
4994
Eric Laurent65b65452010-06-01 23:49:17 -07004995 if (mStatus != NO_ERROR) {
4996 return;
4997 }
4998 lStatus = init();
4999 if (lStatus < 0) {
5000 mStatus = lStatus;
5001 goto Error;
5002 }
5003
5004 LOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
5005 return;
5006Error:
5007 EffectRelease(mEffectInterface);
5008 mEffectInterface = NULL;
5009 LOGV("Constructor Error %d", mStatus);
5010}
5011
5012AudioFlinger::EffectModule::~EffectModule()
5013{
5014 LOGV("Destructor %p", this);
5015 if (mEffectInterface != NULL) {
5016 // release effect engine
5017 EffectRelease(mEffectInterface);
5018 }
5019}
5020
5021status_t AudioFlinger::EffectModule::addHandle(sp<EffectHandle>& handle)
5022{
5023 status_t status;
5024
5025 Mutex::Autolock _l(mLock);
5026 // First handle in mHandles has highest priority and controls the effect module
5027 int priority = handle->priority();
5028 size_t size = mHandles.size();
5029 sp<EffectHandle> h;
5030 size_t i;
5031 for (i = 0; i < size; i++) {
5032 h = mHandles[i].promote();
5033 if (h == 0) continue;
5034 if (h->priority() <= priority) break;
5035 }
5036 // if inserted in first place, move effect control from previous owner to this handle
5037 if (i == 0) {
5038 if (h != 0) {
5039 h->setControl(false, true);
5040 }
5041 handle->setControl(true, false);
5042 status = NO_ERROR;
5043 } else {
5044 status = ALREADY_EXISTS;
5045 }
5046 mHandles.insertAt(handle, i);
5047 return status;
5048}
5049
5050size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
5051{
5052 Mutex::Autolock _l(mLock);
5053 size_t size = mHandles.size();
5054 size_t i;
5055 for (i = 0; i < size; i++) {
5056 if (mHandles[i] == handle) break;
5057 }
5058 if (i == size) {
5059 return size;
5060 }
5061 mHandles.removeAt(i);
5062 size = mHandles.size();
5063 // if removed from first place, move effect control from this handle to next in line
5064 if (i == 0 && size != 0) {
5065 sp<EffectHandle> h = mHandles[0].promote();
5066 if (h != 0) {
5067 h->setControl(true, true);
5068 }
5069 }
5070
5071 return size;
5072}
5073
5074void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle)
5075{
5076 // keep a strong reference on this EffectModule to avoid calling the
5077 // destructor before we exit
5078 sp<EffectModule> keep(this);
Eric Laurent53334cd2010-06-23 17:38:20 -07005079 {
5080 sp<ThreadBase> thread = mThread.promote();
5081 if (thread != 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07005082 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurent53334cd2010-06-23 17:38:20 -07005083 playbackThread->disconnectEffect(keep, handle);
Eric Laurent65b65452010-06-01 23:49:17 -07005084 }
5085 }
5086}
5087
5088void AudioFlinger::EffectModule::process()
5089{
5090 Mutex::Autolock _l(mLock);
5091
5092 if (mEffectInterface == NULL || mConfig.inputCfg.buffer.raw == NULL || mConfig.outputCfg.buffer.raw == NULL) {
5093 return;
5094 }
5095
5096 if (mState != IDLE) {
5097 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
5098 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5099 AudioMixer::ditherAndClamp(mConfig.inputCfg.buffer.s32,
5100 mConfig.inputCfg.buffer.s32,
5101 mConfig.inputCfg.buffer.frameCount);
5102 }
5103
5104 // TODO: handle effects with buffer provider
5105 if (mState != ACTIVE) {
Eric Laurent65b65452010-06-01 23:49:17 -07005106 switch (mState) {
5107 case RESET:
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005108 reset_l();
Eric Laurent53334cd2010-06-23 17:38:20 -07005109 mState = STARTING;
Eric Laurent65b65452010-06-01 23:49:17 -07005110 // clear auxiliary effect input buffer for next accumulation
5111 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5112 memset(mConfig.inputCfg.buffer.raw, 0, mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
5113 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005114 return;
Eric Laurent65b65452010-06-01 23:49:17 -07005115 case STARTING:
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005116 start_l();
Eric Laurent65b65452010-06-01 23:49:17 -07005117 mState = ACTIVE;
5118 break;
5119 case STOPPING:
Eric Laurent65b65452010-06-01 23:49:17 -07005120 mState = STOPPED;
5121 break;
5122 case STOPPED:
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005123 stop_l();
Eric Laurent65b65452010-06-01 23:49:17 -07005124 mState = IDLE;
Eric Laurent65b65452010-06-01 23:49:17 -07005125 return;
5126 }
5127 }
5128
5129 // do the actual processing in the effect engine
5130 (*mEffectInterface)->process(mEffectInterface, &mConfig.inputCfg.buffer, &mConfig.outputCfg.buffer);
5131
5132 // clear auxiliary effect input buffer for next accumulation
5133 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5134 memset(mConfig.inputCfg.buffer.raw, 0, mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
5135 }
5136 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
5137 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw){
5138 // If an insert effect is idle and input buffer is different from output buffer, copy input to
5139 // output
5140 sp<EffectChain> chain = mChain.promote();
5141 if (chain != 0 && chain->activeTracks() != 0) {
5142 size_t size = mConfig.inputCfg.buffer.frameCount * sizeof(int16_t);
5143 if (mConfig.inputCfg.channels == CHANNEL_STEREO) {
5144 size *= 2;
5145 }
5146 memcpy(mConfig.outputCfg.buffer.raw, mConfig.inputCfg.buffer.raw, size);
5147 }
5148 }
5149}
5150
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005151void AudioFlinger::EffectModule::reset_l()
Eric Laurent65b65452010-06-01 23:49:17 -07005152{
5153 if (mEffectInterface == NULL) {
5154 return;
5155 }
5156 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
5157}
5158
5159status_t AudioFlinger::EffectModule::configure()
5160{
5161 uint32_t channels;
5162 if (mEffectInterface == NULL) {
5163 return NO_INIT;
5164 }
5165
5166 sp<ThreadBase> thread = mThread.promote();
5167 if (thread == 0) {
5168 return DEAD_OBJECT;
5169 }
5170
5171 // TODO: handle configuration of effects replacing track process
5172 if (thread->channelCount() == 1) {
5173 channels = CHANNEL_MONO;
5174 } else {
5175 channels = CHANNEL_STEREO;
5176 }
5177
5178 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5179 mConfig.inputCfg.channels = CHANNEL_MONO;
5180 } else {
5181 mConfig.inputCfg.channels = channels;
5182 }
5183 mConfig.outputCfg.channels = channels;
Eric Laurent53334cd2010-06-23 17:38:20 -07005184 mConfig.inputCfg.format = SAMPLE_FORMAT_PCM_S15;
5185 mConfig.outputCfg.format = SAMPLE_FORMAT_PCM_S15;
Eric Laurent65b65452010-06-01 23:49:17 -07005186 mConfig.inputCfg.samplingRate = thread->sampleRate();
5187 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
5188 mConfig.inputCfg.bufferProvider.cookie = NULL;
5189 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
5190 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
5191 mConfig.outputCfg.bufferProvider.cookie = NULL;
5192 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
5193 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
5194 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
5195 // Insert effect:
Eric Laurent53334cd2010-06-23 17:38:20 -07005196 // - in session 0 or -1, always overwrites output buffer: input buffer == output buffer
Eric Laurent65b65452010-06-01 23:49:17 -07005197 // - in other sessions:
5198 // last effect in the chain accumulates in output buffer: input buffer != output buffer
5199 // other effect: overwrites output buffer: input buffer == output buffer
5200 // Auxiliary effect:
5201 // accumulates in output buffer: input buffer != output buffer
5202 // Therefore: accumulate <=> input buffer != output buffer
5203 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
5204 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
5205 } else {
5206 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
5207 }
5208 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
5209 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
5210 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
5211 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
5212
5213 status_t cmdStatus;
5214 int size = sizeof(int);
5215 status_t status = (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_CONFIGURE, sizeof(effect_config_t), &mConfig, &size, &cmdStatus);
5216 if (status == 0) {
5217 status = cmdStatus;
5218 }
5219 return status;
5220}
5221
5222status_t AudioFlinger::EffectModule::init()
5223{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005224 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07005225 if (mEffectInterface == NULL) {
5226 return NO_INIT;
5227 }
5228 status_t cmdStatus;
5229 int size = sizeof(status_t);
5230 status_t status = (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_INIT, 0, NULL, &size, &cmdStatus);
5231 if (status == 0) {
5232 status = cmdStatus;
5233 }
5234 return status;
5235}
5236
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005237status_t AudioFlinger::EffectModule::start_l()
Eric Laurent65b65452010-06-01 23:49:17 -07005238{
5239 if (mEffectInterface == NULL) {
5240 return NO_INIT;
5241 }
5242 status_t cmdStatus;
5243 int size = sizeof(status_t);
5244 status_t status = (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_ENABLE, 0, NULL, &size, &cmdStatus);
5245 if (status == 0) {
5246 status = cmdStatus;
5247 }
5248 return status;
5249}
5250
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005251status_t AudioFlinger::EffectModule::stop_l()
Eric Laurent65b65452010-06-01 23:49:17 -07005252{
5253 if (mEffectInterface == NULL) {
5254 return NO_INIT;
5255 }
5256 status_t cmdStatus;
5257 int size = sizeof(status_t);
5258 status_t status = (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_DISABLE, 0, NULL, &size, &cmdStatus);
5259 if (status == 0) {
5260 status = cmdStatus;
5261 }
5262 return status;
5263}
5264
5265status_t AudioFlinger::EffectModule::command(int cmdCode, int cmdSize, void *pCmdData, int *replySize, void *pReplyData)
5266{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005267 Mutex::Autolock _l(mLock);
5268// LOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Eric Laurent65b65452010-06-01 23:49:17 -07005269
5270 if (mEffectInterface == NULL) {
5271 return NO_INIT;
5272 }
5273 status_t status = (*mEffectInterface)->command(mEffectInterface, cmdCode, cmdSize, pCmdData, replySize, pReplyData);
5274 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
5275 int size = (replySize == NULL) ? 0 : *replySize;
Eric Laurent65b65452010-06-01 23:49:17 -07005276 for (size_t i = 1; i < mHandles.size(); i++) {
5277 sp<EffectHandle> h = mHandles[i].promote();
5278 if (h != 0) {
5279 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
5280 }
5281 }
5282 }
5283 return status;
5284}
5285
5286status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
5287{
5288 Mutex::Autolock _l(mLock);
5289 LOGV("setEnabled %p enabled %d", this, enabled);
5290
5291 if (enabled != isEnabled()) {
5292 switch (mState) {
5293 // going from disabled to enabled
5294 case IDLE:
5295 mState = RESET;
5296 break;
5297 case STOPPING:
5298 mState = ACTIVE;
5299 break;
5300 case STOPPED:
5301 mState = STARTING;
5302 break;
5303
5304 // going from enabled to disabled
5305 case RESET:
5306 mState = IDLE;
5307 break;
5308 case STARTING:
5309 mState = STOPPED;
5310 break;
5311 case ACTIVE:
5312 mState = STOPPING;
5313 break;
5314 }
5315 for (size_t i = 1; i < mHandles.size(); i++) {
5316 sp<EffectHandle> h = mHandles[i].promote();
5317 if (h != 0) {
5318 h->setEnabled(enabled);
5319 }
5320 }
5321 }
5322 return NO_ERROR;
5323}
5324
5325bool AudioFlinger::EffectModule::isEnabled()
5326{
5327 switch (mState) {
5328 case RESET:
5329 case STARTING:
5330 case ACTIVE:
5331 return true;
5332 case IDLE:
5333 case STOPPING:
5334 case STOPPED:
5335 default:
5336 return false;
5337 }
5338}
5339
5340status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
5341{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005342 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07005343 status_t status = NO_ERROR;
5344
5345 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
5346 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
5347 if ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) & (EFFECT_FLAG_VOLUME_CTRL|EFFECT_FLAG_VOLUME_IND)) {
5348 status_t cmdStatus;
5349 uint32_t volume[2];
5350 uint32_t *pVolume = NULL;
5351 int size = sizeof(volume);
5352 volume[0] = *left;
5353 volume[1] = *right;
5354 if (controller) {
5355 pVolume = volume;
5356 }
5357 status = (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_SET_VOLUME, size, volume, &size, pVolume);
5358 if (controller && status == NO_ERROR && size == sizeof(volume)) {
5359 *left = volume[0];
5360 *right = volume[1];
5361 }
5362 }
5363 return status;
5364}
5365
5366status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
5367{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005368 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07005369 status_t status = NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07005370 if ((mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
5371 // convert device bit field from AudioSystem to EffectApi format.
5372 device = deviceAudioSystemToEffectApi(device);
5373 if (device == 0) {
5374 return BAD_VALUE;
5375 }
Eric Laurent65b65452010-06-01 23:49:17 -07005376 status_t cmdStatus;
5377 int size = sizeof(status_t);
5378 status = (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_SET_DEVICE, sizeof(uint32_t), &device, &size, &cmdStatus);
5379 if (status == NO_ERROR) {
5380 status = cmdStatus;
5381 }
5382 }
5383 return status;
5384}
5385
Eric Laurent53334cd2010-06-23 17:38:20 -07005386status_t AudioFlinger::EffectModule::setMode(uint32_t mode)
5387{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005388 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07005389 status_t status = NO_ERROR;
5390 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
5391 // convert audio mode from AudioSystem to EffectApi format.
5392 int effectMode = modeAudioSystemToEffectApi(mode);
5393 if (effectMode < 0) {
5394 return BAD_VALUE;
5395 }
5396 status_t cmdStatus;
5397 int size = sizeof(status_t);
5398 status = (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_SET_AUDIO_MODE, sizeof(int), &effectMode, &size, &cmdStatus);
5399 if (status == NO_ERROR) {
5400 status = cmdStatus;
5401 }
5402 }
5403 return status;
5404}
5405
5406// update this table when AudioSystem::audio_devices or audio_device_e (in EffectApi.h) are modified
5407const uint32_t AudioFlinger::EffectModule::sDeviceConvTable[] = {
5408 DEVICE_EARPIECE, // AudioSystem::DEVICE_OUT_EARPIECE
5409 DEVICE_SPEAKER, // AudioSystem::DEVICE_OUT_SPEAKER
5410 DEVICE_WIRED_HEADSET, // case AudioSystem::DEVICE_OUT_WIRED_HEADSET
5411 DEVICE_WIRED_HEADPHONE, // AudioSystem::DEVICE_OUT_WIRED_HEADPHONE
5412 DEVICE_BLUETOOTH_SCO, // AudioSystem::DEVICE_OUT_BLUETOOTH_SCO
5413 DEVICE_BLUETOOTH_SCO_HEADSET, // AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_HEADSET
5414 DEVICE_BLUETOOTH_SCO_CARKIT, // AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_CARKIT
5415 DEVICE_BLUETOOTH_A2DP, // AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP
5416 DEVICE_BLUETOOTH_A2DP_HEADPHONES, // AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES
5417 DEVICE_BLUETOOTH_A2DP_SPEAKER, // AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER
5418 DEVICE_AUX_DIGITAL // AudioSystem::DEVICE_OUT_AUX_DIGITAL
5419};
5420
5421uint32_t AudioFlinger::EffectModule::deviceAudioSystemToEffectApi(uint32_t device)
5422{
5423 uint32_t deviceOut = 0;
5424 while (device) {
5425 const uint32_t i = 31 - __builtin_clz(device);
5426 device &= ~(1 << i);
5427 if (i >= sizeof(sDeviceConvTable)/sizeof(uint32_t)) {
5428 LOGE("device convertion error for AudioSystem device 0x%08x", device);
5429 return 0;
5430 }
5431 deviceOut |= (uint32_t)sDeviceConvTable[i];
5432 }
5433 return deviceOut;
5434}
5435
5436// update this table when AudioSystem::audio_mode or audio_mode_e (in EffectApi.h) are modified
5437const uint32_t AudioFlinger::EffectModule::sModeConvTable[] = {
5438 AUDIO_MODE_NORMAL, // AudioSystem::MODE_NORMAL
5439 AUDIO_MODE_RINGTONE, // AudioSystem::MODE_RINGTONE
5440 AUDIO_MODE_IN_CALL // AudioSystem::MODE_IN_CALL
5441};
5442
5443int AudioFlinger::EffectModule::modeAudioSystemToEffectApi(uint32_t mode)
5444{
5445 int modeOut = -1;
5446 if (mode < sizeof(sModeConvTable) / sizeof(uint32_t)) {
5447 modeOut = (int)sModeConvTable[mode];
5448 }
5449 return modeOut;
5450}
Eric Laurent65b65452010-06-01 23:49:17 -07005451
5452status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
5453{
5454 const size_t SIZE = 256;
5455 char buffer[SIZE];
5456 String8 result;
5457
5458 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
5459 result.append(buffer);
5460
5461 bool locked = tryLock(mLock);
5462 // failed to lock - AudioFlinger is probably deadlocked
5463 if (!locked) {
5464 result.append("\t\tCould not lock Fx mutex:\n");
5465 }
5466
5467 result.append("\t\tSession Status State Engine:\n");
5468 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
5469 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
5470 result.append(buffer);
5471
5472 result.append("\t\tDescriptor:\n");
5473 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
5474 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
5475 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
5476 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
5477 result.append(buffer);
5478 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
5479 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
5480 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
5481 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
5482 result.append(buffer);
5483 snprintf(buffer, SIZE, "\t\t- apiVersion: %04X\n\t\t- flags: %08X\n",
5484 mDescriptor.apiVersion,
5485 mDescriptor.flags);
5486 result.append(buffer);
5487 snprintf(buffer, SIZE, "\t\t- name: %s\n",
5488 mDescriptor.name);
5489 result.append(buffer);
5490 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
5491 mDescriptor.implementor);
5492 result.append(buffer);
5493
5494 result.append("\t\t- Input configuration:\n");
5495 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
5496 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
5497 (uint32_t)mConfig.inputCfg.buffer.raw,
5498 mConfig.inputCfg.buffer.frameCount,
5499 mConfig.inputCfg.samplingRate,
5500 mConfig.inputCfg.channels,
5501 mConfig.inputCfg.format);
5502 result.append(buffer);
5503
5504 result.append("\t\t- Output configuration:\n");
5505 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
5506 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
5507 (uint32_t)mConfig.outputCfg.buffer.raw,
5508 mConfig.outputCfg.buffer.frameCount,
5509 mConfig.outputCfg.samplingRate,
5510 mConfig.outputCfg.channels,
5511 mConfig.outputCfg.format);
5512 result.append(buffer);
5513
5514 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
5515 result.append(buffer);
5516 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
5517 for (size_t i = 0; i < mHandles.size(); ++i) {
5518 sp<EffectHandle> handle = mHandles[i].promote();
5519 if (handle != 0) {
5520 handle->dump(buffer, SIZE);
5521 result.append(buffer);
5522 }
5523 }
5524
5525 result.append("\n");
5526
5527 write(fd, result.string(), result.length());
5528
5529 if (locked) {
5530 mLock.unlock();
5531 }
5532
5533 return NO_ERROR;
5534}
5535
5536// ----------------------------------------------------------------------------
5537// EffectHandle implementation
5538// ----------------------------------------------------------------------------
5539
5540#undef LOG_TAG
5541#define LOG_TAG "AudioFlinger::EffectHandle"
5542
5543AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
5544 const sp<AudioFlinger::Client>& client,
5545 const sp<IEffectClient>& effectClient,
5546 int32_t priority)
5547 : BnEffect(),
5548 mEffect(effect), mEffectClient(effectClient), mClient(client), mPriority(priority), mHasControl(false)
5549{
5550 LOGV("constructor %p", this);
5551
5552 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
5553 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
5554 if (mCblkMemory != 0) {
5555 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
5556
5557 if (mCblk) {
5558 new(mCblk) effect_param_cblk_t();
5559 mBuffer = (uint8_t *)mCblk + bufOffset;
5560 }
5561 } else {
5562 LOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
5563 return;
5564 }
5565}
5566
5567AudioFlinger::EffectHandle::~EffectHandle()
5568{
5569 LOGV("Destructor %p", this);
5570 disconnect();
5571}
5572
5573status_t AudioFlinger::EffectHandle::enable()
5574{
5575 if (!mHasControl) return INVALID_OPERATION;
5576 if (mEffect == 0) return DEAD_OBJECT;
5577
5578 return mEffect->setEnabled(true);
5579}
5580
5581status_t AudioFlinger::EffectHandle::disable()
5582{
5583 if (!mHasControl) return INVALID_OPERATION;
5584 if (mEffect == NULL) return DEAD_OBJECT;
5585
5586 return mEffect->setEnabled(false);
5587}
5588
5589void AudioFlinger::EffectHandle::disconnect()
5590{
5591 if (mEffect == 0) {
5592 return;
5593 }
5594 mEffect->disconnect(this);
5595 // release sp on module => module destructor can be called now
5596 mEffect.clear();
5597 if (mCblk) {
5598 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
5599 }
5600 mCblkMemory.clear(); // and free the shared memory
5601 if (mClient != 0) {
5602 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
5603 mClient.clear();
5604 }
5605}
5606
5607status_t AudioFlinger::EffectHandle::command(int cmdCode, int cmdSize, void *pCmdData, int *replySize, void *pReplyData)
5608{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005609// LOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p", cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Eric Laurent65b65452010-06-01 23:49:17 -07005610
5611 // only get parameter command is permitted for applications not controlling the effect
5612 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
5613 return INVALID_OPERATION;
5614 }
5615 if (mEffect == 0) return DEAD_OBJECT;
5616
5617 // handle commands that are not forwarded transparently to effect engine
5618 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
5619 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
5620 // no risk to block the whole media server process or mixer threads is we are stuck here
5621 Mutex::Autolock _l(mCblk->lock);
5622 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
5623 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
5624 mCblk->serverIndex = 0;
5625 mCblk->clientIndex = 0;
5626 return BAD_VALUE;
5627 }
5628 status_t status = NO_ERROR;
5629 while (mCblk->serverIndex < mCblk->clientIndex) {
5630 int reply;
5631 int rsize = sizeof(int);
5632 int *p = (int *)(mBuffer + mCblk->serverIndex);
5633 int size = *p++;
Eric Laurent53334cd2010-06-23 17:38:20 -07005634 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
5635 LOGW("command(): invalid parameter block size");
5636 break;
5637 }
Eric Laurent65b65452010-06-01 23:49:17 -07005638 effect_param_t *param = (effect_param_t *)p;
Eric Laurent53334cd2010-06-23 17:38:20 -07005639 if (param->psize == 0 || param->vsize == 0) {
5640 LOGW("command(): null parameter or value size");
5641 mCblk->serverIndex += size;
5642 continue;
5643 }
Eric Laurent65b65452010-06-01 23:49:17 -07005644 int psize = sizeof(effect_param_t) + ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) + param->vsize;
5645 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM, psize, p, &rsize, &reply);
5646 if (ret == NO_ERROR) {
5647 if (reply != NO_ERROR) {
5648 status = reply;
5649 }
5650 } else {
5651 status = ret;
5652 }
5653 mCblk->serverIndex += size;
5654 }
5655 mCblk->serverIndex = 0;
5656 mCblk->clientIndex = 0;
5657 return status;
5658 } else if (cmdCode == EFFECT_CMD_ENABLE) {
5659 return enable();
5660 } else if (cmdCode == EFFECT_CMD_DISABLE) {
5661 return disable();
5662 }
5663
5664 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
5665}
5666
5667sp<IMemory> AudioFlinger::EffectHandle::getCblk() const {
5668 return mCblkMemory;
5669}
5670
5671void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal)
5672{
5673 LOGV("setControl %p control %d", this, hasControl);
5674
5675 mHasControl = hasControl;
5676 if (signal && mEffectClient != 0) {
5677 mEffectClient->controlStatusChanged(hasControl);
5678 }
5679}
5680
5681void AudioFlinger::EffectHandle::commandExecuted(int cmdCode, int cmdSize, void *pCmdData, int replySize, void *pReplyData)
5682{
5683 if (mEffectClient != 0) {
5684 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
5685 }
5686}
5687
5688
5689
5690void AudioFlinger::EffectHandle::setEnabled(bool enabled)
5691{
5692 if (mEffectClient != 0) {
5693 mEffectClient->enableStatusChanged(enabled);
5694 }
5695}
5696
5697status_t AudioFlinger::EffectHandle::onTransact(
5698 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5699{
5700 return BnEffect::onTransact(code, data, reply, flags);
5701}
5702
5703
5704void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
5705{
5706 bool locked = tryLock(mCblk->lock);
5707
5708 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
5709 (mClient == NULL) ? getpid() : mClient->pid(),
5710 mPriority,
5711 mHasControl,
5712 !locked,
5713 mCblk->clientIndex,
5714 mCblk->serverIndex
5715 );
5716
5717 if (locked) {
5718 mCblk->lock.unlock();
5719 }
5720}
5721
5722#undef LOG_TAG
5723#define LOG_TAG "AudioFlinger::EffectChain"
5724
5725AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
5726 int sessionId)
5727 : mThread(wThread), mSessionId(sessionId), mVolumeCtrlIdx(-1), mActiveTrackCnt(0), mOwnInBuffer(false)
5728{
5729
5730}
5731
5732AudioFlinger::EffectChain::~EffectChain()
5733{
5734 if (mOwnInBuffer) {
5735 delete mInBuffer;
5736 }
5737
5738}
5739
5740sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc(effect_descriptor_t *descriptor)
5741{
5742 sp<EffectModule> effect;
5743 size_t size = mEffects.size();
5744
5745 for (size_t i = 0; i < size; i++) {
5746 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
5747 effect = mEffects[i];
5748 break;
5749 }
5750 }
5751 return effect;
5752}
5753
5754sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId(int id)
5755{
5756 sp<EffectModule> effect;
5757 size_t size = mEffects.size();
5758
5759 for (size_t i = 0; i < size; i++) {
5760 if (mEffects[i]->id() == id) {
5761 effect = mEffects[i];
5762 break;
5763 }
5764 }
5765 return effect;
5766}
5767
5768// Must be called with EffectChain::mLock locked
5769void AudioFlinger::EffectChain::process_l()
5770{
5771 size_t size = mEffects.size();
5772 for (size_t i = 0; i < size; i++) {
5773 mEffects[i]->process();
5774 }
5775 // if no track is active, input buffer must be cleared here as the mixer process
5776 // will not do it
Eric Laurent53334cd2010-06-23 17:38:20 -07005777 if (mSessionId > 0 && activeTracks() == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07005778 sp<ThreadBase> thread = mThread.promote();
5779 if (thread != 0) {
5780 size_t numSamples = thread->frameCount() * thread->channelCount();
5781 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
5782 }
5783 }
5784}
5785
5786status_t AudioFlinger::EffectChain::addEffect(sp<EffectModule>& effect)
5787{
5788 effect_descriptor_t desc = effect->desc();
5789 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
5790
5791 Mutex::Autolock _l(mLock);
5792
5793 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5794 // Auxiliary effects are inserted at the beginning of mEffects vector as
5795 // they are processed first and accumulated in chain input buffer
5796 mEffects.insertAt(effect, 0);
5797 sp<ThreadBase> thread = mThread.promote();
5798 if (thread == 0) {
5799 return NO_INIT;
5800 }
5801 // the input buffer for auxiliary effect contains mono samples in
5802 // 32 bit format. This is to avoid saturation in AudoMixer
5803 // accumulation stage. Saturation is done in EffectModule::process() before
5804 // calling the process in effect engine
5805 size_t numSamples = thread->frameCount();
5806 int32_t *buffer = new int32_t[numSamples];
5807 memset(buffer, 0, numSamples * sizeof(int32_t));
5808 effect->setInBuffer((int16_t *)buffer);
5809 // auxiliary effects output samples to chain input buffer for further processing
5810 // by insert effects
5811 effect->setOutBuffer(mInBuffer);
5812 } else {
5813 // Insert effects are inserted at the end of mEffects vector as they are processed
5814 // after track and auxiliary effects.
Eric Laurent53334cd2010-06-23 17:38:20 -07005815 // Insert effect order as a function of indicated preference:
5816 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
5817 // another effect is present
5818 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
5819 // last effect claiming first position
5820 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
5821 // first effect claiming last position
Eric Laurent65b65452010-06-01 23:49:17 -07005822 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
Eric Laurent53334cd2010-06-23 17:38:20 -07005823 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
5824 // already present
Eric Laurent65b65452010-06-01 23:49:17 -07005825
5826 int size = (int)mEffects.size();
5827 int idx_insert = size;
5828 int idx_insert_first = -1;
5829 int idx_insert_last = -1;
5830
5831 for (int i = 0; i < size; i++) {
5832 effect_descriptor_t d = mEffects[i]->desc();
5833 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
5834 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
5835 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
5836 // check invalid effect chaining combinations
5837 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
Eric Laurent53334cd2010-06-23 17:38:20 -07005838 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
5839 LOGW("addEffect() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Eric Laurent65b65452010-06-01 23:49:17 -07005840 return INVALID_OPERATION;
5841 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005842 // remember position of first insert effect and by default
5843 // select this as insert position for new effect
Eric Laurent65b65452010-06-01 23:49:17 -07005844 if (idx_insert == size) {
5845 idx_insert = i;
5846 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005847 // remember position of last insert effect claiming
5848 // first position
Eric Laurent65b65452010-06-01 23:49:17 -07005849 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
5850 idx_insert_first = i;
5851 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005852 // remember position of first insert effect claiming
5853 // last position
5854 if (iPref == EFFECT_FLAG_INSERT_LAST &&
5855 idx_insert_last == -1) {
Eric Laurent65b65452010-06-01 23:49:17 -07005856 idx_insert_last = i;
5857 }
5858 }
5859 }
5860
Eric Laurent53334cd2010-06-23 17:38:20 -07005861 // modify idx_insert from first position if needed
5862 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
5863 if (idx_insert_last != -1) {
5864 idx_insert = idx_insert_last;
5865 } else {
5866 idx_insert = size;
5867 }
5868 } else {
5869 if (idx_insert_first != -1) {
5870 idx_insert = idx_insert_first + 1;
5871 }
Eric Laurent65b65452010-06-01 23:49:17 -07005872 }
5873
5874 // always read samples from chain input buffer
5875 effect->setInBuffer(mInBuffer);
5876
5877 // if last effect in the chain, output samples to chain
5878 // output buffer, otherwise to chain input buffer
5879 if (idx_insert == size) {
5880 if (idx_insert != 0) {
5881 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
5882 mEffects[idx_insert-1]->configure();
5883 }
5884 effect->setOutBuffer(mOutBuffer);
5885 } else {
5886 effect->setOutBuffer(mInBuffer);
5887 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005888 mEffects.insertAt(effect, idx_insert);
Eric Laurent65b65452010-06-01 23:49:17 -07005889 // Always give volume control to last effect in chain with volume control capability
5890 if (((desc.flags & EFFECT_FLAG_VOLUME_MASK) & EFFECT_FLAG_VOLUME_CTRL) &&
5891 mVolumeCtrlIdx < idx_insert) {
5892 mVolumeCtrlIdx = idx_insert;
5893 }
5894
Eric Laurent53334cd2010-06-23 17:38:20 -07005895 LOGV("addEffect() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Eric Laurent65b65452010-06-01 23:49:17 -07005896 }
5897 effect->configure();
5898 return NO_ERROR;
5899}
5900
5901size_t AudioFlinger::EffectChain::removeEffect(const sp<EffectModule>& effect)
5902{
5903 Mutex::Autolock _l(mLock);
5904
5905 int size = (int)mEffects.size();
5906 int i;
5907 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
5908
5909 for (i = 0; i < size; i++) {
5910 if (effect == mEffects[i]) {
5911 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
5912 delete[] effect->inBuffer();
5913 } else {
5914 if (i == size - 1 && i != 0) {
5915 mEffects[i - 1]->setOutBuffer(mOutBuffer);
5916 mEffects[i - 1]->configure();
5917 }
5918 }
5919 mEffects.removeAt(i);
5920 LOGV("removeEffect() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
5921 break;
5922 }
5923 }
5924 // Return volume control to last effect in chain with volume control capability
5925 if (mVolumeCtrlIdx == i) {
5926 size = (int)mEffects.size();
5927 for (i = size; i > 0; i--) {
5928 if ((mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) & EFFECT_FLAG_VOLUME_CTRL) {
5929 break;
5930 }
5931 }
5932 // mVolumeCtrlIdx reset to -1 if no effect found with volume control flag set
5933 mVolumeCtrlIdx = i - 1;
5934 }
5935
5936 return mEffects.size();
5937}
5938
5939void AudioFlinger::EffectChain::setDevice(uint32_t device)
5940{
5941 size_t size = mEffects.size();
5942 for (size_t i = 0; i < size; i++) {
5943 mEffects[i]->setDevice(device);
5944 }
5945}
5946
Eric Laurent53334cd2010-06-23 17:38:20 -07005947void AudioFlinger::EffectChain::setMode(uint32_t mode)
5948{
5949 size_t size = mEffects.size();
5950 for (size_t i = 0; i < size; i++) {
5951 mEffects[i]->setMode(mode);
5952 }
5953}
5954
Eric Laurent65b65452010-06-01 23:49:17 -07005955bool AudioFlinger::EffectChain::setVolume(uint32_t *left, uint32_t *right)
5956{
5957 uint32_t newLeft = *left;
5958 uint32_t newRight = *right;
5959 bool hasControl = false;
5960
5961 // first get volume update from volume controller
5962 if (mVolumeCtrlIdx >= 0) {
5963 mEffects[mVolumeCtrlIdx]->setVolume(&newLeft, &newRight, true);
5964 hasControl = true;
5965 }
5966 // then indicate volume to all other effects in chain.
5967 // Pass altered volume to effects before volume controller
5968 // and requested volume to effects after controller
5969 uint32_t lVol = newLeft;
5970 uint32_t rVol = newRight;
5971 size_t size = mEffects.size();
5972 for (size_t i = 0; i < size; i++) {
5973 if ((int)i == mVolumeCtrlIdx) continue;
5974 // this also works for mVolumeCtrlIdx == -1 when there is no volume controller
5975 if ((int)i > mVolumeCtrlIdx) {
5976 lVol = *left;
5977 rVol = *right;
5978 }
5979 mEffects[i]->setVolume(&lVol, &rVol, false);
5980 }
5981 *left = newLeft;
5982 *right = newRight;
5983
5984 return hasControl;
5985}
5986
5987sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getVolumeController()
5988{
5989 sp<EffectModule> effect;
5990 if (mVolumeCtrlIdx >= 0) {
5991 effect = mEffects[mVolumeCtrlIdx];
5992 }
5993 return effect;
5994}
5995
5996
5997status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
5998{
5999 const size_t SIZE = 256;
6000 char buffer[SIZE];
6001 String8 result;
6002
6003 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
6004 result.append(buffer);
6005
6006 bool locked = tryLock(mLock);
6007 // failed to lock - AudioFlinger is probably deadlocked
6008 if (!locked) {
6009 result.append("\tCould not lock mutex:\n");
6010 }
6011
6012 result.append("\tNum fx In buffer Out buffer Vol ctrl Active tracks:\n");
6013 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %02d %d\n",
6014 mEffects.size(),
6015 (uint32_t)mInBuffer,
6016 (uint32_t)mOutBuffer,
6017 (mVolumeCtrlIdx == -1) ? 0 : mEffects[mVolumeCtrlIdx]->id(),
6018 mActiveTrackCnt);
6019 result.append(buffer);
6020 write(fd, result.string(), result.size());
6021
6022 for (size_t i = 0; i < mEffects.size(); ++i) {
6023 sp<EffectModule> effect = mEffects[i];
6024 if (effect != 0) {
6025 effect->dump(fd, args);
6026 }
6027 }
6028
6029 if (locked) {
6030 mLock.unlock();
6031 }
6032
6033 return NO_ERROR;
6034}
6035
6036#undef LOG_TAG
6037#define LOG_TAG "AudioFlinger"
6038
Eric Laurenta553c252009-07-17 12:17:14 -07006039// ----------------------------------------------------------------------------
6040
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07006041status_t AudioFlinger::onTransact(
6042 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6043{
6044 return BnAudioFlinger::onTransact(code, data, reply, flags);
6045}
6046
6047// ----------------------------------------------------------------------------
Eric Laurenta553c252009-07-17 12:17:14 -07006048
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07006049void AudioFlinger::instantiate() {
6050 defaultServiceManager()->addService(
6051 String16("media.audio_flinger"), new AudioFlinger());
6052}
6053
6054}; // namespace android