blob: cd9b07e71b0722bf1a03b68f7f1efc77a2db8166 [file] [log] [blame]
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001/* //device/include/server/AudioFlinger/AudioFlinger.cpp
2**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
Eric Laurent7d850f22010-07-09 13:34:17 -070020//#define LOG_NDEBUG 0
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070021
22#include <math.h>
23#include <signal.h>
24#include <sys/time.h>
25#include <sys/resource.h>
26
Mathias Agopian07952722009-05-19 19:08:10 -070027#include <binder/IServiceManager.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070028#include <utils/Log.h>
Mathias Agopian07952722009-05-19 19:08:10 -070029#include <binder/Parcel.h>
30#include <binder/IPCThreadState.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070031#include <utils/String16.h>
32#include <utils/threads.h>
33
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080034#include <cutils/properties.h>
35
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070036#include <media/AudioTrack.h>
37#include <media/AudioRecord.h>
38
39#include <private/media/AudioTrackShared.h>
Eric Laurent65b65452010-06-01 23:49:17 -070040#include <private/media/AudioEffectShared.h>
The Android Open Source Project9266c552009-01-15 16:12:10 -080041#include <hardware_legacy/AudioHardwareInterface.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070042
43#include "AudioMixer.h"
44#include "AudioFlinger.h"
45
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080046#ifdef WITH_A2DP
47#include "A2dpAudioInterface.h"
48#endif
49
Glenn Kasten871c16c2010-03-05 12:18:01 -080050#ifdef LVMX
51#include "lifevibes.h"
52#endif
53
Eric Laurent53334cd2010-06-23 17:38:20 -070054#include <media/EffectsFactoryApi.h>
Eric Laurentdf9b81c2010-07-02 08:12:41 -070055#include <media/EffectVisualizerApi.h>
Eric Laurent65b65452010-06-01 23:49:17 -070056
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057// ----------------------------------------------------------------------------
58// the sim build doesn't have gettid
59
60#ifndef HAVE_GETTID
61# define gettid getpid
62#endif
63
64// ----------------------------------------------------------------------------
65
Eric Laurent8ed6ed02010-07-13 04:45:46 -070066extern const char * const gEffectLibPath;
67
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070068namespace android {
69
The Android Open Source Project10592532009-03-18 17:39:46 -070070static const char* kDeadlockedString = "AudioFlinger may be deadlocked\n";
71static const char* kHardwareLockedString = "Hardware lock is taken\n";
72
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080073//static const nsecs_t kStandbyTimeInNsecs = seconds(3);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070074static const float MAX_GAIN = 4096.0f;
Eric Laurent65b65452010-06-01 23:49:17 -070075static const float MAX_GAIN_INT = 0x1000;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070076
77// retry counts for buffer fill timeout
78// 50 * ~20msecs = 1 second
79static const int8_t kMaxTrackRetries = 50;
80static const int8_t kMaxTrackStartupRetries = 50;
Eric Laurentef9500f2010-03-11 14:47:00 -080081// allow less retry attempts on direct output thread.
82// direct outputs can be a scarce resource in audio hardware and should
83// be released as quickly as possible.
84static const int8_t kMaxTrackRetriesDirect = 2;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070085
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -070086static const int kDumpLockRetries = 50;
87static const int kDumpLockSleep = 20000;
88
Dave Sparksd0ac8c02009-09-30 03:09:03 -070089static const nsecs_t kWarningThrottle = seconds(5);
90
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070092#define AUDIOFLINGER_SECURITY_ENABLED 1
93
94// ----------------------------------------------------------------------------
95
96static bool recordingAllowed() {
97#ifndef HAVE_ANDROID_OS
98 return true;
99#endif
100#if AUDIOFLINGER_SECURITY_ENABLED
101 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
102 bool ok = checkCallingPermission(String16("android.permission.RECORD_AUDIO"));
103 if (!ok) LOGE("Request requires android.permission.RECORD_AUDIO");
104 return ok;
105#else
106 if (!checkCallingPermission(String16("android.permission.RECORD_AUDIO")))
107 LOGW("WARNING: Need to add android.permission.RECORD_AUDIO to manifest");
108 return true;
109#endif
110}
111
112static bool settingsAllowed() {
113#ifndef HAVE_ANDROID_OS
114 return true;
115#endif
116#if AUDIOFLINGER_SECURITY_ENABLED
117 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
118 bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
119 if (!ok) LOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
120 return ok;
121#else
122 if (!checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS")))
123 LOGW("WARNING: Need to add android.permission.MODIFY_AUDIO_SETTINGS to manifest");
124 return true;
125#endif
126}
127
128// ----------------------------------------------------------------------------
129
130AudioFlinger::AudioFlinger()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800131 : BnAudioFlinger(),
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700132 mAudioHardware(0), mMasterVolume(1.0f), mMasterMute(false), mNextUniqueId(1)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700133{
134 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -0700135
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700136 mAudioHardware = AudioHardwareInterface::create();
Eric Laurenta553c252009-07-17 12:17:14 -0700137
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700138 mHardwareStatus = AUDIO_HW_INIT;
139 if (mAudioHardware->initCheck() == NO_ERROR) {
140 // open 16-bit output stream for s/w mixer
Eric Laurent53334cd2010-06-23 17:38:20 -0700141 mMode = AudioSystem::MODE_NORMAL;
142 setMode(mMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143
144 setMasterVolume(1.0f);
145 setMasterMute(false);
Eric Laurenta553c252009-07-17 12:17:14 -0700146 } else {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700147 LOGE("Couldn't even initialize the stubbed audio hardware!");
148 }
Glenn Kasten871c16c2010-03-05 12:18:01 -0800149#ifdef LVMX
150 LifeVibes::init();
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700151 mLifeVibesClientPid = -1;
Glenn Kasten871c16c2010-03-05 12:18:01 -0800152#endif
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700153}
154
155AudioFlinger::~AudioFlinger()
156{
Eric Laurent7954c462009-08-28 10:39:03 -0700157 while (!mRecordThreads.isEmpty()) {
158 // closeInput() will remove first entry from mRecordThreads
159 closeInput(mRecordThreads.keyAt(0));
160 }
161 while (!mPlaybackThreads.isEmpty()) {
162 // closeOutput() will remove first entry from mPlaybackThreads
163 closeOutput(mPlaybackThreads.keyAt(0));
164 }
165 if (mAudioHardware) {
166 delete mAudioHardware;
167 }
The Android Open Source Projectb7986892009-01-09 17:51:23 -0800168}
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800169
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700170
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700171
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700172status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
173{
174 const size_t SIZE = 256;
175 char buffer[SIZE];
176 String8 result;
177
178 result.append("Clients:\n");
179 for (size_t i = 0; i < mClients.size(); ++i) {
180 wp<Client> wClient = mClients.valueAt(i);
181 if (wClient != 0) {
182 sp<Client> client = wClient.promote();
183 if (client != 0) {
184 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
185 result.append(buffer);
186 }
187 }
188 }
189 write(fd, result.string(), result.size());
190 return NO_ERROR;
191}
192
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700193
194status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
195{
196 const size_t SIZE = 256;
197 char buffer[SIZE];
198 String8 result;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700199 int hardwareStatus = mHardwareStatus;
Eric Laurenta553c252009-07-17 12:17:14 -0700200
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700201 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700202 result.append(buffer);
203 write(fd, result.string(), result.size());
204 return NO_ERROR;
205}
206
207status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
208{
209 const size_t SIZE = 256;
210 char buffer[SIZE];
211 String8 result;
212 snprintf(buffer, SIZE, "Permission Denial: "
213 "can't dump AudioFlinger from pid=%d, uid=%d\n",
214 IPCThreadState::self()->getCallingPid(),
215 IPCThreadState::self()->getCallingUid());
216 result.append(buffer);
217 write(fd, result.string(), result.size());
218 return NO_ERROR;
219}
220
The Android Open Source Project10592532009-03-18 17:39:46 -0700221static bool tryLock(Mutex& mutex)
222{
223 bool locked = false;
224 for (int i = 0; i < kDumpLockRetries; ++i) {
225 if (mutex.tryLock() == NO_ERROR) {
226 locked = true;
227 break;
228 }
229 usleep(kDumpLockSleep);
230 }
231 return locked;
232}
233
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700234status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
235{
236 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
237 dumpPermissionDenial(fd, args);
238 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -0700239 // get state of hardware lock
240 bool hardwareLocked = tryLock(mHardwareLock);
241 if (!hardwareLocked) {
242 String8 result(kHardwareLockedString);
243 write(fd, result.string(), result.size());
244 } else {
245 mHardwareLock.unlock();
246 }
247
248 bool locked = tryLock(mLock);
249
250 // failed to lock - AudioFlinger is probably deadlocked
251 if (!locked) {
252 String8 result(kDeadlockedString);
253 write(fd, result.string(), result.size());
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700254 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700255
256 dumpClients(fd, args);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700257 dumpInternals(fd, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800258
Eric Laurenta553c252009-07-17 12:17:14 -0700259 // dump playback threads
260 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700261 mPlaybackThreads.valueAt(i)->dump(fd, args);
Eric Laurenta553c252009-07-17 12:17:14 -0700262 }
263
264 // dump record threads
Eric Laurent102313a2009-07-23 13:35:01 -0700265 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700266 mRecordThreads.valueAt(i)->dump(fd, args);
Eric Laurenta553c252009-07-17 12:17:14 -0700267 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800268
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700269 if (mAudioHardware) {
270 mAudioHardware->dumpState(fd, args);
271 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700272 if (locked) mLock.unlock();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700273 }
274 return NO_ERROR;
275}
276
Eric Laurenta553c252009-07-17 12:17:14 -0700277
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700278// IAudioFlinger interface
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800279
280
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700281sp<IAudioTrack> AudioFlinger::createTrack(
282 pid_t pid,
283 int streamType,
284 uint32_t sampleRate,
285 int format,
286 int channelCount,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800287 int frameCount,
288 uint32_t flags,
289 const sp<IMemory>& sharedBuffer,
Eric Laurentddb78e72009-07-28 08:44:33 -0700290 int output,
Eric Laurent65b65452010-06-01 23:49:17 -0700291 int *sessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800292 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700293{
Eric Laurenta553c252009-07-17 12:17:14 -0700294 sp<PlaybackThread::Track> track;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700295 sp<TrackHandle> trackHandle;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700296 sp<Client> client;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800297 wp<Client> wclient;
298 status_t lStatus;
Eric Laurent65b65452010-06-01 23:49:17 -0700299 int lSessionId;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700300
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800301 if (streamType >= AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800302 LOGE("invalid stream type");
303 lStatus = BAD_VALUE;
304 goto Exit;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700305 }
306
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800307 {
308 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700309 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent493941b2010-07-28 01:32:47 -0700310 PlaybackThread *effectThread = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -0700311 if (thread == NULL) {
312 LOGE("unknown output thread");
313 lStatus = BAD_VALUE;
314 goto Exit;
315 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800316
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800317 wclient = mClients.valueFor(pid);
318
319 if (wclient != NULL) {
320 client = wclient.promote();
321 } else {
322 client = new Client(this, pid);
323 mClients.add(pid, client);
324 }
Eric Laurent65b65452010-06-01 23:49:17 -0700325
Eric Laurent65b65452010-06-01 23:49:17 -0700326 LOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700327 if (sessionId != NULL && *sessionId != AudioSystem::SESSION_OUTPUT_MIX) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700328 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent493941b2010-07-28 01:32:47 -0700329 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
330 if (mPlaybackThreads.keyAt(i) != output) {
331 // prevent same audio session on different output threads
332 uint32_t sessions = t->hasAudioSession(*sessionId);
333 if (sessions & PlaybackThread::TRACK_SESSION) {
334 lStatus = BAD_VALUE;
335 goto Exit;
336 }
337 // check if an effect with same session ID is waiting for a track to be created
338 if (sessions & PlaybackThread::EFFECT_SESSION) {
339 effectThread = t.get();
340 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700341 }
342 }
Eric Laurent65b65452010-06-01 23:49:17 -0700343 lSessionId = *sessionId;
344 } else {
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700345 // if no audio session id is provided, create one here
Eric Laurent65b65452010-06-01 23:49:17 -0700346 lSessionId = nextUniqueId();
347 if (sessionId != NULL) {
348 *sessionId = lSessionId;
349 }
350 }
351 LOGV("createTrack() lSessionId: %d", lSessionId);
352
Eric Laurenta553c252009-07-17 12:17:14 -0700353 track = thread->createTrack_l(client, streamType, sampleRate, format,
Eric Laurent65b65452010-06-01 23:49:17 -0700354 channelCount, frameCount, sharedBuffer, lSessionId, &lStatus);
Eric Laurent493941b2010-07-28 01:32:47 -0700355
356 // move effect chain to this output thread if an effect on same session was waiting
357 // for a track to be created
358 if (lStatus == NO_ERROR && effectThread != NULL) {
359 Mutex::Autolock _dl(thread->mLock);
360 Mutex::Autolock _sl(effectThread->mLock);
361 moveEffectChain_l(lSessionId, effectThread, thread, true);
362 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700363 }
364 if (lStatus == NO_ERROR) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800365 trackHandle = new TrackHandle(track);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700366 } else {
Eric Laurentb9481d82009-09-17 05:12:56 -0700367 // remove local strong reference to Client before deleting the Track so that the Client
368 // destructor is called by the TrackBase destructor with mLock held
369 client.clear();
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700370 track.clear();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800371 }
372
373Exit:
374 if(status) {
375 *status = lStatus;
376 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700377 return trackHandle;
378}
379
Eric Laurentddb78e72009-07-28 08:44:33 -0700380uint32_t AudioFlinger::sampleRate(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("sampleRate() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700386 return 0;
387 }
388 return thread->sampleRate();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700389}
390
Eric Laurentddb78e72009-07-28 08:44:33 -0700391int AudioFlinger::channelCount(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("channelCount() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700397 return 0;
398 }
399 return thread->channelCount();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700400}
401
Eric Laurentddb78e72009-07-28 08:44:33 -0700402int AudioFlinger::format(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700403{
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("format() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700408 return 0;
409 }
410 return thread->format();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700411}
412
Eric Laurentddb78e72009-07-28 08:44:33 -0700413size_t AudioFlinger::frameCount(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700414{
Eric Laurenta553c252009-07-17 12:17:14 -0700415 Mutex::Autolock _l(mLock);
416 PlaybackThread *thread = checkPlaybackThread_l(output);
417 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700418 LOGW("frameCount() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700419 return 0;
420 }
421 return thread->frameCount();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700422}
423
Eric Laurentddb78e72009-07-28 08:44:33 -0700424uint32_t AudioFlinger::latency(int output) const
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800425{
Eric Laurenta553c252009-07-17 12:17:14 -0700426 Mutex::Autolock _l(mLock);
427 PlaybackThread *thread = checkPlaybackThread_l(output);
428 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700429 LOGW("latency() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700430 return 0;
431 }
432 return thread->latency();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800433}
434
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700435status_t AudioFlinger::setMasterVolume(float value)
436{
437 // check calling permissions
438 if (!settingsAllowed()) {
439 return PERMISSION_DENIED;
440 }
441
442 // when hw supports master volume, don't scale in sw mixer
443 AutoMutex lock(mHardwareLock);
444 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
445 if (mAudioHardware->setMasterVolume(value) == NO_ERROR) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800446 value = 1.0f;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700447 }
448 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -0700449
450 mMasterVolume = value;
451 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700452 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700453
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700454 return NO_ERROR;
455}
456
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700457status_t AudioFlinger::setMode(int mode)
458{
Eric Laurent53334cd2010-06-23 17:38:20 -0700459 status_t ret;
460
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700461 // check calling permissions
462 if (!settingsAllowed()) {
463 return PERMISSION_DENIED;
464 }
465 if ((mode < 0) || (mode >= AudioSystem::NUM_MODES)) {
466 LOGW("Illegal value: setMode(%d)", mode);
467 return BAD_VALUE;
468 }
469
Eric Laurent53334cd2010-06-23 17:38:20 -0700470 { // scope for the lock
471 AutoMutex lock(mHardwareLock);
472 mHardwareStatus = AUDIO_HW_SET_MODE;
473 ret = mAudioHardware->setMode(mode);
474 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten871c16c2010-03-05 12:18:01 -0800475 }
Eric Laurent53334cd2010-06-23 17:38:20 -0700476
477 if (NO_ERROR == ret) {
478 Mutex::Autolock _l(mLock);
479 mMode = mode;
480 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
481 mPlaybackThreads.valueAt(i)->setMode(mode);
482#ifdef LVMX
483 LifeVibes::setMode(mode);
Glenn Kasten871c16c2010-03-05 12:18:01 -0800484#endif
Eric Laurent53334cd2010-06-23 17:38:20 -0700485 }
486
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700487 return ret;
488}
489
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700490status_t AudioFlinger::setMicMute(bool state)
491{
492 // check calling permissions
493 if (!settingsAllowed()) {
494 return PERMISSION_DENIED;
495 }
496
497 AutoMutex lock(mHardwareLock);
498 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
499 status_t ret = mAudioHardware->setMicMute(state);
500 mHardwareStatus = AUDIO_HW_IDLE;
501 return ret;
502}
503
504bool AudioFlinger::getMicMute() const
505{
506 bool state = AudioSystem::MODE_INVALID;
507 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
508 mAudioHardware->getMicMute(&state);
509 mHardwareStatus = AUDIO_HW_IDLE;
510 return state;
511}
512
513status_t AudioFlinger::setMasterMute(bool muted)
514{
515 // check calling permissions
516 if (!settingsAllowed()) {
517 return PERMISSION_DENIED;
518 }
Eric Laurenta553c252009-07-17 12:17:14 -0700519
520 mMasterMute = muted;
521 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700522 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Eric Laurenta553c252009-07-17 12:17:14 -0700523
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700524 return NO_ERROR;
525}
526
527float AudioFlinger::masterVolume() const
528{
Eric Laurenta553c252009-07-17 12:17:14 -0700529 return mMasterVolume;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700530}
531
532bool AudioFlinger::masterMute() const
533{
Eric Laurenta553c252009-07-17 12:17:14 -0700534 return mMasterMute;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700535}
536
Eric Laurentddb78e72009-07-28 08:44:33 -0700537status_t AudioFlinger::setStreamVolume(int stream, float value, int output)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700538{
539 // check calling permissions
540 if (!settingsAllowed()) {
541 return PERMISSION_DENIED;
542 }
543
Eric Laurenta553c252009-07-17 12:17:14 -0700544 if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700545 return BAD_VALUE;
546 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800547
Eric Laurenta553c252009-07-17 12:17:14 -0700548 AutoMutex lock(mLock);
549 PlaybackThread *thread = NULL;
550 if (output) {
551 thread = checkPlaybackThread_l(output);
552 if (thread == NULL) {
553 return BAD_VALUE;
554 }
555 }
556
Eric Laurenta553c252009-07-17 12:17:14 -0700557 mStreamTypes[stream].volume = value;
558
559 if (thread == NULL) {
Eric Laurent415f3e22009-10-21 08:14:22 -0700560 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700561 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Eric Laurent415f3e22009-10-21 08:14:22 -0700562 }
Eric Laurenta553c252009-07-17 12:17:14 -0700563 } else {
564 thread->setStreamVolume(stream, value);
565 }
Eric Laurentef028272009-04-21 07:56:33 -0700566
Eric Laurent415f3e22009-10-21 08:14:22 -0700567 return NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700568}
569
570status_t AudioFlinger::setStreamMute(int stream, bool muted)
571{
572 // check calling permissions
573 if (!settingsAllowed()) {
574 return PERMISSION_DENIED;
575 }
576
Eric Laurenta553c252009-07-17 12:17:14 -0700577 if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES ||
Eric Laurenteeea9222009-03-26 01:57:59 -0700578 uint32_t(stream) == AudioSystem::ENFORCED_AUDIBLE) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700579 return BAD_VALUE;
580 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700581
Eric Laurenta553c252009-07-17 12:17:14 -0700582 mStreamTypes[stream].mute = muted;
583 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700584 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800585
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700586 return NO_ERROR;
587}
588
Eric Laurentddb78e72009-07-28 08:44:33 -0700589float AudioFlinger::streamVolume(int stream, int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700590{
Eric Laurenta553c252009-07-17 12:17:14 -0700591 if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700592 return 0.0f;
593 }
Eric Laurenta553c252009-07-17 12:17:14 -0700594
595 AutoMutex lock(mLock);
596 float volume;
597 if (output) {
598 PlaybackThread *thread = checkPlaybackThread_l(output);
599 if (thread == NULL) {
600 return 0.0f;
601 }
602 volume = thread->streamVolume(stream);
603 } else {
604 volume = mStreamTypes[stream].volume;
605 }
606
Eric Laurentef028272009-04-21 07:56:33 -0700607 return volume;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700608}
609
610bool AudioFlinger::streamMute(int stream) const
611{
Eric Laurenta553c252009-07-17 12:17:14 -0700612 if (stream < 0 || stream >= (int)AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700613 return true;
614 }
Eric Laurenta553c252009-07-17 12:17:14 -0700615
616 return mStreamTypes[stream].mute;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700617}
618
Eric Laurent23f25cd2010-01-25 08:49:09 -0800619bool AudioFlinger::isStreamActive(int stream) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700620{
Eric Laurent4e646332009-07-09 03:20:57 -0700621 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700622 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent23f25cd2010-01-25 08:49:09 -0800623 if (mPlaybackThreads.valueAt(i)->isStreamActive(stream)) {
Eric Laurenta553c252009-07-17 12:17:14 -0700624 return true;
625 }
626 }
627 return false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700628}
629
Eric Laurentddb78e72009-07-28 08:44:33 -0700630status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700631{
Eric Laurenta553c252009-07-17 12:17:14 -0700632 status_t result;
633
Eric Laurentddb78e72009-07-28 08:44:33 -0700634 LOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
Eric Laurenta553c252009-07-17 12:17:14 -0700635 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
636 // check calling permissions
637 if (!settingsAllowed()) {
638 return PERMISSION_DENIED;
The Android Open Source Project9266c552009-01-15 16:12:10 -0800639 }
Eric Laurenta553c252009-07-17 12:17:14 -0700640
Glenn Kasten871c16c2010-03-05 12:18:01 -0800641#ifdef LVMX
642 AudioParameter param = AudioParameter(keyValuePairs);
643 LifeVibes::setParameters(ioHandle,keyValuePairs);
644 String8 key = String8(AudioParameter::keyRouting);
645 int device;
646 if (NO_ERROR != param.getInt(key, device)) {
647 device = -1;
648 }
649
650 key = String8(LifevibesTag);
651 String8 value;
652 int musicEnabled = -1;
653 if (NO_ERROR == param.get(key, value)) {
654 if (value == LifevibesEnable) {
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700655 mLifeVibesClientPid = IPCThreadState::self()->getCallingPid();
Glenn Kasten871c16c2010-03-05 12:18:01 -0800656 musicEnabled = 1;
657 } else if (value == LifevibesDisable) {
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700658 mLifeVibesClientPid = -1;
Glenn Kasten871c16c2010-03-05 12:18:01 -0800659 musicEnabled = 0;
660 }
661 }
662#endif
663
Eric Laurenta553c252009-07-17 12:17:14 -0700664 // ioHandle == 0 means the parameters are global to the audio hardware interface
665 if (ioHandle == 0) {
666 AutoMutex lock(mHardwareLock);
667 mHardwareStatus = AUDIO_SET_PARAMETER;
668 result = mAudioHardware->setParameters(keyValuePairs);
Glenn Kasten871c16c2010-03-05 12:18:01 -0800669#ifdef LVMX
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700670 if (musicEnabled != -1) {
Glenn Kasten871c16c2010-03-05 12:18:01 -0800671 LifeVibes::enableMusic((bool) musicEnabled);
672 }
673#endif
Eric Laurenta553c252009-07-17 12:17:14 -0700674 mHardwareStatus = AUDIO_HW_IDLE;
675 return result;
676 }
677
Eric Laurentb7d94602009-09-29 11:12:57 -0700678 // hold a strong ref on thread in case closeOutput() or closeInput() is called
679 // and the thread is exited once the lock is released
680 sp<ThreadBase> thread;
681 {
682 Mutex::Autolock _l(mLock);
683 thread = checkPlaybackThread_l(ioHandle);
684 if (thread == NULL) {
685 thread = checkRecordThread_l(ioHandle);
686 }
Eric Laurenta553c252009-07-17 12:17:14 -0700687 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700688 if (thread != NULL) {
Glenn Kasten871c16c2010-03-05 12:18:01 -0800689 result = thread->setParameters(keyValuePairs);
690#ifdef LVMX
691 if ((NO_ERROR == result) && (device != -1)) {
692 LifeVibes::setDevice(LifeVibes::threadIdToAudioOutputType(thread->id()), device);
693 }
694#endif
695 return result;
Eric Laurenta553c252009-07-17 12:17:14 -0700696 }
Eric Laurenta553c252009-07-17 12:17:14 -0700697 return BAD_VALUE;
698}
699
Eric Laurentddb78e72009-07-28 08:44:33 -0700700String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
Eric Laurenta553c252009-07-17 12:17:14 -0700701{
Eric Laurentddb78e72009-07-28 08:44:33 -0700702// LOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
Eric Laurenta553c252009-07-17 12:17:14 -0700703// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
704
705 if (ioHandle == 0) {
706 return mAudioHardware->getParameters(keys);
707 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700708
709 Mutex::Autolock _l(mLock);
710
Eric Laurenta553c252009-07-17 12:17:14 -0700711 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
712 if (playbackThread != NULL) {
713 return playbackThread->getParameters(keys);
714 }
715 RecordThread *recordThread = checkRecordThread_l(ioHandle);
716 if (recordThread != NULL) {
717 return recordThread->getParameters(keys);
718 }
719 return String8("");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700720}
721
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800722size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
723{
724 return mAudioHardware->getInputBufferSize(sampleRate, format, channelCount);
725}
726
Eric Laurent47d0a922010-02-26 02:47:27 -0800727unsigned int AudioFlinger::getInputFramesLost(int ioHandle)
728{
729 if (ioHandle == 0) {
730 return 0;
731 }
732
733 Mutex::Autolock _l(mLock);
734
735 RecordThread *recordThread = checkRecordThread_l(ioHandle);
736 if (recordThread != NULL) {
737 return recordThread->getInputFramesLost();
738 }
739 return 0;
740}
741
Eric Laurent415f3e22009-10-21 08:14:22 -0700742status_t AudioFlinger::setVoiceVolume(float value)
743{
744 // check calling permissions
745 if (!settingsAllowed()) {
746 return PERMISSION_DENIED;
747 }
748
749 AutoMutex lock(mHardwareLock);
750 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
751 status_t ret = mAudioHardware->setVoiceVolume(value);
752 mHardwareStatus = AUDIO_HW_IDLE;
753
754 return ret;
755}
756
Eric Laurent0986e792010-01-19 17:37:09 -0800757status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int output)
758{
759 status_t status;
760
761 Mutex::Autolock _l(mLock);
762
763 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
764 if (playbackThread != NULL) {
765 return playbackThread->getRenderPosition(halFrames, dspFrames);
766 }
767
768 return BAD_VALUE;
769}
770
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800771void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
772{
Eric Laurenta553c252009-07-17 12:17:14 -0700773
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800774 Mutex::Autolock _l(mLock);
775
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700776 int pid = IPCThreadState::self()->getCallingPid();
777 if (mNotificationClients.indexOfKey(pid) < 0) {
778 sp<NotificationClient> notificationClient = new NotificationClient(this,
779 client,
780 pid);
781 LOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Eric Laurenta553c252009-07-17 12:17:14 -0700782
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700783 mNotificationClients.add(pid, notificationClient);
Eric Laurenta553c252009-07-17 12:17:14 -0700784
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700785 sp<IBinder> binder = client->asBinder();
786 binder->linkToDeath(notificationClient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800787
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700788 // the config change is always sent from playback or record threads to avoid deadlock
789 // with AudioSystem::gLock
790 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
791 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
792 }
Eric Laurenta553c252009-07-17 12:17:14 -0700793
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700794 for (size_t i = 0; i < mRecordThreads.size(); i++) {
795 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800796 }
797 }
798}
799
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700800void AudioFlinger::removeNotificationClient(pid_t pid)
801{
802 Mutex::Autolock _l(mLock);
803
804 int index = mNotificationClients.indexOfKey(pid);
805 if (index >= 0) {
806 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
807 LOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
808#ifdef LVMX
809 if (pid == mLifeVibesClientPid) {
810 LOGV("Disabling lifevibes");
811 LifeVibes::enableMusic(false);
812 mLifeVibesClientPid = -1;
813 }
814#endif
815 mNotificationClients.removeItem(pid);
816 }
817}
818
Eric Laurent296a0ec2009-09-15 07:10:12 -0700819// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700820void AudioFlinger::audioConfigChanged_l(int event, int ioHandle, void *param2)
821{
Eric Laurent49f02be2009-11-19 09:00:56 -0800822 size_t size = mNotificationClients.size();
823 for (size_t i = 0; i < size; i++) {
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700824 mNotificationClients.valueAt(i)->client()->ioConfigChanged(event, ioHandle, param2);
Eric Laurenta553c252009-07-17 12:17:14 -0700825 }
826}
827
Eric Laurentb9481d82009-09-17 05:12:56 -0700828// removeClient_l() must be called with AudioFlinger::mLock held
829void AudioFlinger::removeClient_l(pid_t pid)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700830{
Eric Laurentb9481d82009-09-17 05:12:56 -0700831 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 -0700832 mClients.removeItem(pid);
833}
834
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700835
Eric Laurenta553c252009-07-17 12:17:14 -0700836// ----------------------------------------------------------------------------
837
Eric Laurent49f02be2009-11-19 09:00:56 -0800838AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, int id)
Eric Laurenta553c252009-07-17 12:17:14 -0700839 : Thread(false),
840 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
Eric Laurentb0a01472010-05-14 05:45:46 -0700841 mFrameSize(1), mFormat(0), mStandby(false), mId(id), mExiting(false)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700842{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800843}
844
Eric Laurenta553c252009-07-17 12:17:14 -0700845AudioFlinger::ThreadBase::~ThreadBase()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800846{
Eric Laurent8fce46a2009-08-04 09:45:33 -0700847 mParamCond.broadcast();
848 mNewParameters.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800849}
850
Eric Laurenta553c252009-07-17 12:17:14 -0700851void AudioFlinger::ThreadBase::exit()
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700852{
Eric Laurentb7d94602009-09-29 11:12:57 -0700853 // keep a strong ref on ourself so that we wont get
Eric Laurenta553c252009-07-17 12:17:14 -0700854 // destroyed in the middle of requestExitAndWait()
855 sp <ThreadBase> strongMe = this;
856
857 LOGV("ThreadBase::exit");
858 {
859 AutoMutex lock(&mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -0800860 mExiting = true;
Eric Laurenta553c252009-07-17 12:17:14 -0700861 requestExit();
862 mWaitWorkCV.signal();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700863 }
Eric Laurenta553c252009-07-17 12:17:14 -0700864 requestExitAndWait();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700865}
Eric Laurenta553c252009-07-17 12:17:14 -0700866
867uint32_t AudioFlinger::ThreadBase::sampleRate() const
868{
869 return mSampleRate;
870}
871
872int AudioFlinger::ThreadBase::channelCount() const
873{
Eric Laurentb0a01472010-05-14 05:45:46 -0700874 return (int)mChannelCount;
Eric Laurenta553c252009-07-17 12:17:14 -0700875}
876
877int AudioFlinger::ThreadBase::format() const
878{
879 return mFormat;
880}
881
882size_t AudioFlinger::ThreadBase::frameCount() const
883{
884 return mFrameCount;
885}
886
887status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
888{
Eric Laurent8fce46a2009-08-04 09:45:33 -0700889 status_t status;
Eric Laurenta553c252009-07-17 12:17:14 -0700890
Eric Laurent8fce46a2009-08-04 09:45:33 -0700891 LOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Eric Laurenta553c252009-07-17 12:17:14 -0700892 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700893
Eric Laurent8fce46a2009-08-04 09:45:33 -0700894 mNewParameters.add(keyValuePairs);
Eric Laurenta553c252009-07-17 12:17:14 -0700895 mWaitWorkCV.signal();
Eric Laurentb7d94602009-09-29 11:12:57 -0700896 // wait condition with timeout in case the thread loop has exited
897 // before the request could be processed
898 if (mParamCond.waitRelative(mLock, seconds(2)) == NO_ERROR) {
899 status = mParamStatus;
900 mWaitWorkCV.signal();
901 } else {
902 status = TIMED_OUT;
903 }
Eric Laurent8fce46a2009-08-04 09:45:33 -0700904 return status;
Eric Laurenta553c252009-07-17 12:17:14 -0700905}
906
907void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
908{
909 Mutex::Autolock _l(mLock);
Eric Laurent8fce46a2009-08-04 09:45:33 -0700910 sendConfigEvent_l(event, param);
911}
912
913// sendConfigEvent_l() must be called with ThreadBase::mLock held
914void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
915{
Eric Laurenta553c252009-07-17 12:17:14 -0700916 ConfigEvent *configEvent = new ConfigEvent();
917 configEvent->mEvent = event;
918 configEvent->mParam = param;
919 mConfigEvents.add(configEvent);
920 LOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
921 mWaitWorkCV.signal();
922}
923
924void AudioFlinger::ThreadBase::processConfigEvents()
925{
926 mLock.lock();
927 while(!mConfigEvents.isEmpty()) {
928 LOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
929 ConfigEvent *configEvent = mConfigEvents[0];
930 mConfigEvents.removeAt(0);
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700931 // release mLock before locking AudioFlinger mLock: lock order is always
932 // AudioFlinger then ThreadBase to avoid cross deadlock
Eric Laurenta553c252009-07-17 12:17:14 -0700933 mLock.unlock();
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700934 mAudioFlinger->mLock.lock();
935 audioConfigChanged_l(configEvent->mEvent, configEvent->mParam);
936 mAudioFlinger->mLock.unlock();
Eric Laurenta553c252009-07-17 12:17:14 -0700937 delete configEvent;
938 mLock.lock();
939 }
940 mLock.unlock();
941}
942
Eric Laurent3fdb1262009-11-07 00:01:32 -0800943status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
944{
945 const size_t SIZE = 256;
946 char buffer[SIZE];
947 String8 result;
948
949 bool locked = tryLock(mLock);
950 if (!locked) {
951 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
952 write(fd, buffer, strlen(buffer));
953 }
954
955 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
956 result.append(buffer);
957 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
958 result.append(buffer);
959 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
960 result.append(buffer);
961 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
962 result.append(buffer);
963 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
964 result.append(buffer);
965 snprintf(buffer, SIZE, "Frame size: %d\n", mFrameSize);
966 result.append(buffer);
967
968 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
969 result.append(buffer);
970 result.append(" Index Command");
971 for (size_t i = 0; i < mNewParameters.size(); ++i) {
972 snprintf(buffer, SIZE, "\n %02d ", i);
973 result.append(buffer);
974 result.append(mNewParameters[i]);
975 }
976
977 snprintf(buffer, SIZE, "\n\nPending config events: \n");
978 result.append(buffer);
979 snprintf(buffer, SIZE, " Index event param\n");
980 result.append(buffer);
981 for (size_t i = 0; i < mConfigEvents.size(); i++) {
982 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i]->mEvent, mConfigEvents[i]->mParam);
983 result.append(buffer);
984 }
985 result.append("\n");
986
987 write(fd, result.string(), result.size());
988
989 if (locked) {
990 mLock.unlock();
991 }
992 return NO_ERROR;
993}
994
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800995
996// ----------------------------------------------------------------------------
997
Eric Laurent65b65452010-06-01 23:49:17 -0700998AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Eric Laurent49f02be2009-11-19 09:00:56 -0800999 : ThreadBase(audioFlinger, id),
Eric Laurentd5603c12009-08-06 08:49:39 -07001000 mMixBuffer(0), mSuspended(0), mBytesWritten(0), mOutput(output),
Eric Laurent65b65452010-06-01 23:49:17 -07001001 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1002 mDevice(device)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001003{
Eric Laurenta553c252009-07-17 12:17:14 -07001004 readOutputParameters();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001005
Eric Laurenta553c252009-07-17 12:17:14 -07001006 mMasterVolume = mAudioFlinger->masterVolume();
1007 mMasterMute = mAudioFlinger->masterMute();
1008
1009 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
1010 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
1011 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001012 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001013}
1014
Eric Laurenta553c252009-07-17 12:17:14 -07001015AudioFlinger::PlaybackThread::~PlaybackThread()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001016{
1017 delete [] mMixBuffer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001018}
1019
Eric Laurenta553c252009-07-17 12:17:14 -07001020status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001021{
1022 dumpInternals(fd, args);
1023 dumpTracks(fd, args);
Eric Laurent65b65452010-06-01 23:49:17 -07001024 dumpEffectChains(fd, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001025 return NO_ERROR;
1026}
1027
Eric Laurenta553c252009-07-17 12:17:14 -07001028status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001029{
1030 const size_t SIZE = 256;
1031 char buffer[SIZE];
1032 String8 result;
1033
Eric Laurenta553c252009-07-17 12:17:14 -07001034 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001035 result.append(buffer);
Eric Laurent65b65452010-06-01 23:49:17 -07001036 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 -08001037 for (size_t i = 0; i < mTracks.size(); ++i) {
Eric Laurentd3b4d0c2009-03-31 14:34:35 -07001038 sp<Track> track = mTracks[i];
1039 if (track != 0) {
1040 track->dump(buffer, SIZE);
1041 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001042 }
1043 }
1044
Eric Laurenta553c252009-07-17 12:17:14 -07001045 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001046 result.append(buffer);
Eric Laurent65b65452010-06-01 23:49:17 -07001047 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 -08001048 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Eric Laurentd3b4d0c2009-03-31 14:34:35 -07001049 wp<Track> wTrack = mActiveTracks[i];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001050 if (wTrack != 0) {
1051 sp<Track> track = wTrack.promote();
1052 if (track != 0) {
1053 track->dump(buffer, SIZE);
1054 result.append(buffer);
1055 }
1056 }
1057 }
1058 write(fd, result.string(), result.size());
1059 return NO_ERROR;
1060}
1061
Eric Laurent65b65452010-06-01 23:49:17 -07001062status_t AudioFlinger::PlaybackThread::dumpEffectChains(int fd, const Vector<String16>& args)
1063{
1064 const size_t SIZE = 256;
1065 char buffer[SIZE];
1066 String8 result;
1067
1068 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1069 write(fd, buffer, strlen(buffer));
1070
1071 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1072 sp<EffectChain> chain = mEffectChains[i];
1073 if (chain != 0) {
1074 chain->dump(fd, args);
1075 }
1076 }
1077 return NO_ERROR;
1078}
1079
Eric Laurenta553c252009-07-17 12:17:14 -07001080status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001081{
1082 const size_t SIZE = 256;
1083 char buffer[SIZE];
1084 String8 result;
1085
Eric Laurent3fdb1262009-11-07 00:01:32 -08001086 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001087 result.append(buffer);
1088 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1089 result.append(buffer);
1090 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1091 result.append(buffer);
1092 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1093 result.append(buffer);
1094 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1095 result.append(buffer);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08001096 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1097 result.append(buffer);
Eric Laurent65b65452010-06-01 23:49:17 -07001098 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1099 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001100 write(fd, result.string(), result.size());
Eric Laurent3fdb1262009-11-07 00:01:32 -08001101
1102 dumpBase(fd, args);
1103
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001104 return NO_ERROR;
1105}
1106
1107// Thread virtuals
Eric Laurenta553c252009-07-17 12:17:14 -07001108status_t AudioFlinger::PlaybackThread::readyToRun()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001109{
1110 if (mSampleRate == 0) {
1111 LOGE("No working audio driver found.");
1112 return NO_INIT;
1113 }
Eric Laurenta553c252009-07-17 12:17:14 -07001114 LOGI("AudioFlinger's thread %p ready to run", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001115 return NO_ERROR;
1116}
1117
Eric Laurenta553c252009-07-17 12:17:14 -07001118void AudioFlinger::PlaybackThread::onFirstRef()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001119{
1120 const size_t SIZE = 256;
1121 char buffer[SIZE];
1122
Eric Laurenta553c252009-07-17 12:17:14 -07001123 snprintf(buffer, SIZE, "Playback Thread %p", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001124
1125 run(buffer, ANDROID_PRIORITY_URGENT_AUDIO);
1126}
1127
Eric Laurenta553c252009-07-17 12:17:14 -07001128// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1129sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001130 const sp<AudioFlinger::Client>& client,
1131 int streamType,
1132 uint32_t sampleRate,
1133 int format,
1134 int channelCount,
1135 int frameCount,
1136 const sp<IMemory>& sharedBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -07001137 int sessionId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001138 status_t *status)
1139{
1140 sp<Track> track;
1141 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07001142
1143 if (mType == DIRECT) {
Eric Laurentb0a01472010-05-14 05:45:46 -07001144 if (sampleRate != mSampleRate || format != mFormat || channelCount != (int)mChannelCount) {
Eric Laurenta553c252009-07-17 12:17:14 -07001145 LOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelCount %d for output %p",
1146 sampleRate, format, channelCount, mOutput);
1147 lStatus = BAD_VALUE;
1148 goto Exit;
1149 }
1150 } else {
1151 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1152 if (sampleRate > mSampleRate*2) {
1153 LOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
1154 lStatus = BAD_VALUE;
1155 goto Exit;
1156 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001157 }
1158
Eric Laurenta553c252009-07-17 12:17:14 -07001159 if (mOutput == 0) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001160 LOGE("Audio driver not initialized.");
1161 lStatus = NO_INIT;
1162 goto Exit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001163 }
1164
Eric Laurenta553c252009-07-17 12:17:14 -07001165 { // scope for mLock
1166 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001167
1168 // all tracks in same audio session must share the same routing strategy otherwise
1169 // conflicts will happen when tracks are moved from one output to another by audio policy
1170 // manager
1171 uint32_t strategy =
1172 AudioSystem::getStrategyForStream((AudioSystem::stream_type)streamType);
1173 for (size_t i = 0; i < mTracks.size(); ++i) {
1174 sp<Track> t = mTracks[i];
1175 if (t != 0) {
1176 if (sessionId == t->sessionId() &&
1177 strategy != AudioSystem::getStrategyForStream((AudioSystem::stream_type)t->type())) {
1178 lStatus = BAD_VALUE;
1179 goto Exit;
1180 }
1181 }
1182 }
1183
Eric Laurenta553c252009-07-17 12:17:14 -07001184 track = new Track(this, client, streamType, sampleRate, format,
Eric Laurent65b65452010-06-01 23:49:17 -07001185 channelCount, frameCount, sharedBuffer, sessionId);
Eric Laurent73b60352009-11-09 04:45:39 -08001186 if (track->getCblk() == NULL || track->name() < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07001187 lStatus = NO_MEMORY;
1188 goto Exit;
1189 }
1190 mTracks.add(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001191
1192 sp<EffectChain> chain = getEffectChain_l(sessionId);
1193 if (chain != 0) {
1194 LOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1195 track->setMainBuffer(chain->inBuffer());
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001196 chain->setStrategy(AudioSystem::getStrategyForStream((AudioSystem::stream_type)track->type()));
Eric Laurent65b65452010-06-01 23:49:17 -07001197 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001198 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001199 lStatus = NO_ERROR;
1200
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001201Exit:
1202 if(status) {
1203 *status = lStatus;
1204 }
1205 return track;
1206}
1207
Eric Laurenta553c252009-07-17 12:17:14 -07001208uint32_t AudioFlinger::PlaybackThread::latency() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001209{
1210 if (mOutput) {
1211 return mOutput->latency();
1212 }
1213 else {
1214 return 0;
1215 }
1216}
1217
Eric Laurenta553c252009-07-17 12:17:14 -07001218status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001219{
Glenn Kasten871c16c2010-03-05 12:18:01 -08001220#ifdef LVMX
1221 int audioOutputType = LifeVibes::getMixerType(mId, mType);
1222 if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType)) {
1223 LifeVibes::setMasterVolume(audioOutputType, value);
1224 }
1225#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001226 mMasterVolume = value;
1227 return NO_ERROR;
1228}
1229
Eric Laurenta553c252009-07-17 12:17:14 -07001230status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001231{
Glenn Kasten871c16c2010-03-05 12:18:01 -08001232#ifdef LVMX
1233 int audioOutputType = LifeVibes::getMixerType(mId, mType);
1234 if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType)) {
1235 LifeVibes::setMasterMute(audioOutputType, muted);
1236 }
1237#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001238 mMasterMute = muted;
1239 return NO_ERROR;
1240}
1241
Eric Laurenta553c252009-07-17 12:17:14 -07001242float AudioFlinger::PlaybackThread::masterVolume() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001243{
1244 return mMasterVolume;
1245}
1246
Eric Laurenta553c252009-07-17 12:17:14 -07001247bool AudioFlinger::PlaybackThread::masterMute() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001248{
1249 return mMasterMute;
1250}
1251
Eric Laurenta553c252009-07-17 12:17:14 -07001252status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001253{
Glenn Kasten871c16c2010-03-05 12:18:01 -08001254#ifdef LVMX
1255 int audioOutputType = LifeVibes::getMixerType(mId, mType);
1256 if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType)) {
1257 LifeVibes::setStreamVolume(audioOutputType, stream, value);
1258 }
1259#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001260 mStreamTypes[stream].volume = value;
1261 return NO_ERROR;
1262}
1263
Eric Laurenta553c252009-07-17 12:17:14 -07001264status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001265{
Glenn Kasten871c16c2010-03-05 12:18:01 -08001266#ifdef LVMX
1267 int audioOutputType = LifeVibes::getMixerType(mId, mType);
1268 if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType)) {
1269 LifeVibes::setStreamMute(audioOutputType, stream, muted);
1270 }
1271#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001272 mStreamTypes[stream].mute = muted;
1273 return NO_ERROR;
1274}
1275
Eric Laurenta553c252009-07-17 12:17:14 -07001276float AudioFlinger::PlaybackThread::streamVolume(int stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001277{
1278 return mStreamTypes[stream].volume;
1279}
1280
Eric Laurenta553c252009-07-17 12:17:14 -07001281bool AudioFlinger::PlaybackThread::streamMute(int stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001282{
1283 return mStreamTypes[stream].mute;
1284}
1285
Eric Laurent23f25cd2010-01-25 08:49:09 -08001286bool AudioFlinger::PlaybackThread::isStreamActive(int stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001287{
Eric Laurenta553c252009-07-17 12:17:14 -07001288 Mutex::Autolock _l(mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001289 size_t count = mActiveTracks.size();
1290 for (size_t i = 0 ; i < count ; ++i) {
1291 sp<Track> t = mActiveTracks[i].promote();
1292 if (t == 0) continue;
1293 Track* const track = t.get();
Eric Laurent23f25cd2010-01-25 08:49:09 -08001294 if (t->type() == stream)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001295 return true;
1296 }
1297 return false;
1298}
1299
Eric Laurenta553c252009-07-17 12:17:14 -07001300// addTrack_l() must be called with ThreadBase::mLock held
1301status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001302{
1303 status_t status = ALREADY_EXISTS;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001304
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001305 // set retry count for buffer fill
1306 track->mRetryCount = kMaxTrackStartupRetries;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001307 if (mActiveTracks.indexOf(track) < 0) {
1308 // the track is newly added, make sure it fills up all its
1309 // buffers before playing. This is to ensure the client will
1310 // effectively get the latency it requested.
1311 track->mFillingUpStatus = Track::FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001312 track->mResetDone = false;
Eric Laurenta553c252009-07-17 12:17:14 -07001313 mActiveTracks.add(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001314 if (track->mainBuffer() != mMixBuffer) {
1315 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1316 if (chain != 0) {
1317 LOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
1318 chain->startTrack();
1319 }
1320 }
1321
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001322 status = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001323 }
Eric Laurenta553c252009-07-17 12:17:14 -07001324
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001325 LOGV("mWaitWorkCV.broadcast");
Eric Laurenta553c252009-07-17 12:17:14 -07001326 mWaitWorkCV.broadcast();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001327
1328 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001329}
1330
Eric Laurenta553c252009-07-17 12:17:14 -07001331// destroyTrack_l() must be called with ThreadBase::mLock held
1332void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001333{
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001334 track->mState = TrackBase::TERMINATED;
1335 if (mActiveTracks.indexOf(track) < 0) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001336 mTracks.remove(track);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001337 deleteTrackName_l(track->name());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001338 }
1339}
1340
Eric Laurenta553c252009-07-17 12:17:14 -07001341String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001342{
Eric Laurenta553c252009-07-17 12:17:14 -07001343 return mOutput->getParameters(keys);
1344}
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001345
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001346// destroyTrack_l() must be called with AudioFlinger::mLock held
1347void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
Eric Laurenta553c252009-07-17 12:17:14 -07001348 AudioSystem::OutputDescriptor desc;
1349 void *param2 = 0;
1350
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001351 LOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Eric Laurenta553c252009-07-17 12:17:14 -07001352
1353 switch (event) {
1354 case AudioSystem::OUTPUT_OPENED:
1355 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Eric Laurentb0a01472010-05-14 05:45:46 -07001356 desc.channels = mChannels;
Eric Laurenta553c252009-07-17 12:17:14 -07001357 desc.samplingRate = mSampleRate;
1358 desc.format = mFormat;
1359 desc.frameCount = mFrameCount;
1360 desc.latency = latency();
1361 param2 = &desc;
1362 break;
1363
1364 case AudioSystem::STREAM_CONFIG_CHANGED:
1365 param2 = &param;
1366 case AudioSystem::OUTPUT_CLOSED:
1367 default:
1368 break;
1369 }
Eric Laurent49f02be2009-11-19 09:00:56 -08001370 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurenta553c252009-07-17 12:17:14 -07001371}
1372
1373void AudioFlinger::PlaybackThread::readOutputParameters()
1374{
1375 mSampleRate = mOutput->sampleRate();
Eric Laurentb0a01472010-05-14 05:45:46 -07001376 mChannels = mOutput->channels();
1377 mChannelCount = (uint16_t)AudioSystem::popCount(mChannels);
Eric Laurenta553c252009-07-17 12:17:14 -07001378 mFormat = mOutput->format();
Eric Laurentb0a01472010-05-14 05:45:46 -07001379 mFrameSize = (uint16_t)mOutput->frameSize();
Eric Laurenta553c252009-07-17 12:17:14 -07001380 mFrameCount = mOutput->bufferSize() / mFrameSize;
1381
Eric Laurenta553c252009-07-17 12:17:14 -07001382 // FIXME - Current mixer implementation only supports stereo output: Always
1383 // Allocate a stereo buffer even if HW output is mono.
Eric Laurent65b65452010-06-01 23:49:17 -07001384 if (mMixBuffer != NULL) delete[] mMixBuffer;
Eric Laurenta553c252009-07-17 12:17:14 -07001385 mMixBuffer = new int16_t[mFrameCount * 2];
1386 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
Eric Laurent65b65452010-06-01 23:49:17 -07001387
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001388 // force reconfiguration of effect chains and engines to take new buffer size and audio
1389 // parameters into account
1390 // Note that mLock is not held when readOutputParameters() is called from the constructor
1391 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1392 // matter.
1393 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1394 Vector< sp<EffectChain> > effectChains = mEffectChains;
1395 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent493941b2010-07-28 01:32:47 -07001396 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001397 }
Eric Laurenta553c252009-07-17 12:17:14 -07001398}
1399
Eric Laurent0986e792010-01-19 17:37:09 -08001400status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1401{
1402 if (halFrames == 0 || dspFrames == 0) {
1403 return BAD_VALUE;
1404 }
1405 if (mOutput == 0) {
1406 return INVALID_OPERATION;
1407 }
1408 *halFrames = mBytesWritten/mOutput->frameSize();
1409
1410 return mOutput->getRenderPosition(dspFrames);
1411}
1412
Eric Laurent493941b2010-07-28 01:32:47 -07001413uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Eric Laurent65b65452010-06-01 23:49:17 -07001414{
1415 Mutex::Autolock _l(mLock);
Eric Laurent493941b2010-07-28 01:32:47 -07001416 uint32_t result = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07001417 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent493941b2010-07-28 01:32:47 -07001418 result = EFFECT_SESSION;
Eric Laurent65b65452010-06-01 23:49:17 -07001419 }
1420
1421 for (size_t i = 0; i < mTracks.size(); ++i) {
1422 sp<Track> track = mTracks[i];
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001423 if (sessionId == track->sessionId() &&
1424 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent493941b2010-07-28 01:32:47 -07001425 result |= TRACK_SESSION;
1426 break;
Eric Laurent65b65452010-06-01 23:49:17 -07001427 }
1428 }
1429
Eric Laurent493941b2010-07-28 01:32:47 -07001430 return result;
Eric Laurent65b65452010-06-01 23:49:17 -07001431}
1432
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001433uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1434{
1435 // session AudioSystem::SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
1436 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
1437 if (sessionId == AudioSystem::SESSION_OUTPUT_MIX) {
1438 return AudioSystem::getStrategyForStream(AudioSystem::MUSIC);
1439 }
1440 for (size_t i = 0; i < mTracks.size(); i++) {
1441 sp<Track> track = mTracks[i];
1442 if (sessionId == track->sessionId() &&
1443 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
1444 return AudioSystem::getStrategyForStream((AudioSystem::stream_type) track->type());
1445 }
1446 }
1447 return AudioSystem::getStrategyForStream(AudioSystem::MUSIC);
1448}
1449
Eric Laurent65b65452010-06-01 23:49:17 -07001450sp<AudioFlinger::EffectChain> AudioFlinger::PlaybackThread::getEffectChain(int sessionId)
1451{
1452 Mutex::Autolock _l(mLock);
1453 return getEffectChain_l(sessionId);
1454}
1455
1456sp<AudioFlinger::EffectChain> AudioFlinger::PlaybackThread::getEffectChain_l(int sessionId)
1457{
1458 sp<EffectChain> chain;
1459
1460 size_t size = mEffectChains.size();
1461 for (size_t i = 0; i < size; i++) {
1462 if (mEffectChains[i]->sessionId() == sessionId) {
1463 chain = mEffectChains[i];
1464 break;
1465 }
1466 }
1467 return chain;
1468}
1469
Eric Laurent53334cd2010-06-23 17:38:20 -07001470void AudioFlinger::PlaybackThread::setMode(uint32_t mode)
1471{
1472 Mutex::Autolock _l(mLock);
1473 size_t size = mEffectChains.size();
1474 for (size_t i = 0; i < size; i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07001475 mEffectChains[i]->setMode_l(mode);
Eric Laurent53334cd2010-06-23 17:38:20 -07001476 }
1477}
1478
Eric Laurenta553c252009-07-17 12:17:14 -07001479// ----------------------------------------------------------------------------
1480
Eric Laurent65b65452010-06-01 23:49:17 -07001481AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
1482 : PlaybackThread(audioFlinger, output, id, device),
Eric Laurenta553c252009-07-17 12:17:14 -07001483 mAudioMixer(0)
1484{
1485 mType = PlaybackThread::MIXER;
1486 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1487
1488 // FIXME - Current mixer implementation only supports stereo output
1489 if (mChannelCount == 1) {
1490 LOGE("Invalid audio hardware channel count");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001491 }
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001492}
1493
Eric Laurenta553c252009-07-17 12:17:14 -07001494AudioFlinger::MixerThread::~MixerThread()
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001495{
Eric Laurenta553c252009-07-17 12:17:14 -07001496 delete mAudioMixer;
1497}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001498
Eric Laurenta553c252009-07-17 12:17:14 -07001499bool AudioFlinger::MixerThread::threadLoop()
1500{
Eric Laurenta553c252009-07-17 12:17:14 -07001501 Vector< sp<Track> > tracksToRemove;
Eric Laurent059b4be2009-11-09 23:32:22 -08001502 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001503 nsecs_t standbyTime = systemTime();
1504 size_t mixBufferSize = mFrameCount * mFrameSize;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001505 // FIXME: Relaxed timing because of a certain device that can't meet latency
1506 // Should be reduced to 2x after the vendor fixes the driver issue
1507 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
1508 nsecs_t lastWarning = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08001509 bool longStandbyExit = false;
1510 uint32_t activeSleepTime = activeSleepTimeUs();
1511 uint32_t idleSleepTime = idleSleepTimeUs();
1512 uint32_t sleepTime = idleSleepTime;
Eric Laurent65b65452010-06-01 23:49:17 -07001513 Vector< sp<EffectChain> > effectChains;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001514
Eric Laurenta553c252009-07-17 12:17:14 -07001515 while (!exitPending())
1516 {
1517 processConfigEvents();
1518
Eric Laurent059b4be2009-11-09 23:32:22 -08001519 mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001520 { // scope for mLock
1521
1522 Mutex::Autolock _l(mLock);
1523
1524 if (checkForNewParameters_l()) {
1525 mixBufferSize = mFrameCount * mFrameSize;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001526 // FIXME: Relaxed timing because of a certain device that can't meet latency
1527 // Should be reduced to 2x after the vendor fixes the driver issue
1528 maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
Eric Laurent059b4be2009-11-09 23:32:22 -08001529 activeSleepTime = activeSleepTimeUs();
1530 idleSleepTime = idleSleepTimeUs();
Eric Laurenta553c252009-07-17 12:17:14 -07001531 }
1532
1533 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1534
1535 // put audio hardware into standby after short delay
1536 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1537 mSuspended) {
1538 if (!mStandby) {
1539 LOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
1540 mOutput->standby();
1541 mStandby = true;
1542 mBytesWritten = 0;
1543 }
1544
1545 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1546 // we're about to wait, flush the binder command buffer
1547 IPCThreadState::self()->flushCommands();
1548
1549 if (exitPending()) break;
1550
1551 // wait until we have something to do...
1552 LOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
1553 mWaitWorkCV.wait(mLock);
1554 LOGV("MixerThread %p TID %d waking up\n", this, gettid());
1555
1556 if (mMasterMute == false) {
1557 char value[PROPERTY_VALUE_MAX];
1558 property_get("ro.audio.silent", value, "0");
1559 if (atoi(value)) {
1560 LOGD("Silence is golden");
1561 setMasterMute(true);
1562 }
1563 }
1564
1565 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent059b4be2009-11-09 23:32:22 -08001566 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07001567 continue;
1568 }
1569 }
1570
Eric Laurent059b4be2009-11-09 23:32:22 -08001571 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07001572
1573 // prevent any changes in effect chain list and in each effect chain
1574 // during mixing and effect process as the audio buffers could be deleted
1575 // or modified if an effect is created or deleted
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001576 lockEffectChains_l(effectChains);
Eric Laurenta553c252009-07-17 12:17:14 -07001577 }
1578
Eric Laurent059b4be2009-11-09 23:32:22 -08001579 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07001580 // mix buffers...
Eric Laurent65b65452010-06-01 23:49:17 -07001581 mAudioMixer->process();
Eric Laurentf69a3f82009-09-22 00:35:48 -07001582 sleepTime = 0;
1583 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent65b65452010-06-01 23:49:17 -07001584 //TODO: delay standby when effects have a tail
Eric Laurent96c08a62009-09-07 08:38:38 -07001585 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07001586 // If no tracks are ready, sleep once for the duration of an output
1587 // buffer size, then write 0s to the output
1588 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08001589 if (mixerStatus == MIXER_TRACKS_ENABLED) {
1590 sleepTime = activeSleepTime;
1591 } else {
1592 sleepTime = idleSleepTime;
1593 }
1594 } else if (mBytesWritten != 0 ||
1595 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Eric Laurent65b65452010-06-01 23:49:17 -07001596 memset (mMixBuffer, 0, mixBufferSize);
Eric Laurent96c08a62009-09-07 08:38:38 -07001597 sleepTime = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08001598 LOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Eric Laurent96c08a62009-09-07 08:38:38 -07001599 }
Eric Laurent65b65452010-06-01 23:49:17 -07001600 // TODO add standby time extension fct of effect tail
Eric Laurentf69a3f82009-09-22 00:35:48 -07001601 }
1602
1603 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07001604 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07001605 }
1606 // sleepTime == 0 means we must write to audio hardware
1607 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07001608 for (size_t i = 0; i < effectChains.size(); i ++) {
1609 effectChains[i]->process_l();
1610 }
1611 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001612 unlockEffectChains(effectChains);
Glenn Kasten871c16c2010-03-05 12:18:01 -08001613#ifdef LVMX
1614 int audioOutputType = LifeVibes::getMixerType(mId, mType);
1615 if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType)) {
Eric Laurent65b65452010-06-01 23:49:17 -07001616 LifeVibes::process(audioOutputType, mMixBuffer, mixBufferSize);
Glenn Kasten871c16c2010-03-05 12:18:01 -08001617 }
1618#endif
Eric Laurent65b65452010-06-01 23:49:17 -07001619 mLastWriteTime = systemTime();
1620 mInWrite = true;
1621 mBytesWritten += mixBufferSize;
1622
1623 int bytesWritten = (int)mOutput->write(mMixBuffer, mixBufferSize);
Eric Laurent0986e792010-01-19 17:37:09 -08001624 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07001625 mNumWrites++;
1626 mInWrite = false;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001627 nsecs_t now = systemTime();
1628 nsecs_t delta = now - mLastWriteTime;
Eric Laurentf69a3f82009-09-22 00:35:48 -07001629 if (delta > maxPeriod) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07001630 mNumDelayedWrites++;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001631 if ((now - lastWarning) > kWarningThrottle) {
1632 LOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
1633 ns2ms(delta), mNumDelayedWrites, this);
1634 lastWarning = now;
1635 }
Eric Laurent059b4be2009-11-09 23:32:22 -08001636 if (mStandby) {
1637 longStandbyExit = true;
1638 }
Eric Laurenta553c252009-07-17 12:17:14 -07001639 }
Eric Laurent059b4be2009-11-09 23:32:22 -08001640 mStandby = false;
Eric Laurentf69a3f82009-09-22 00:35:48 -07001641 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07001642 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001643 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07001644 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07001645 }
1646
1647 // finally let go of all our tracks, without the lock held
1648 // since we can't guarantee the destructors won't acquire that
1649 // same lock.
1650 tracksToRemove.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07001651
1652 // Effect chains will be actually deleted here if they were removed from
1653 // mEffectChains list during mixing or effects processing
1654 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07001655 }
1656
1657 if (!mStandby) {
1658 mOutput->standby();
1659 }
Eric Laurenta553c252009-07-17 12:17:14 -07001660
1661 LOGV("MixerThread %p exiting", this);
1662 return false;
1663}
1664
1665// prepareTracks_l() must be called with ThreadBase::mLock held
Eric Laurent059b4be2009-11-09 23:32:22 -08001666uint32_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
Eric Laurenta553c252009-07-17 12:17:14 -07001667{
1668
Eric Laurent059b4be2009-11-09 23:32:22 -08001669 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001670 // find out which tracks need to be processed
1671 size_t count = activeTracks.size();
Eric Laurent65b65452010-06-01 23:49:17 -07001672 size_t mixedTracks = 0;
1673 size_t tracksWithEffect = 0;
Glenn Kasten871c16c2010-03-05 12:18:01 -08001674
1675 float masterVolume = mMasterVolume;
1676 bool masterMute = mMasterMute;
1677
Eric Laurent8cc93b92010-08-11 05:20:11 -07001678 if (masterMute) {
1679 masterVolume = 0;
1680 }
Glenn Kasten871c16c2010-03-05 12:18:01 -08001681#ifdef LVMX
1682 bool tracksConnectedChanged = false;
1683 bool stateChanged = false;
1684
1685 int audioOutputType = LifeVibes::getMixerType(mId, mType);
1686 if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType))
1687 {
1688 int activeTypes = 0;
1689 for (size_t i=0 ; i<count ; i++) {
1690 sp<Track> t = activeTracks[i].promote();
1691 if (t == 0) continue;
1692 Track* const track = t.get();
1693 int iTracktype=track->type();
1694 activeTypes |= 1<<track->type();
1695 }
1696 LifeVibes::computeVolumes(audioOutputType, activeTypes, tracksConnectedChanged, stateChanged, masterVolume, masterMute);
1697 }
1698#endif
Eric Laurent65b65452010-06-01 23:49:17 -07001699 // Delegate master volume control to effect in output mix effect chain if needed
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001700 sp<EffectChain> chain = getEffectChain_l(AudioSystem::SESSION_OUTPUT_MIX);
Eric Laurent65b65452010-06-01 23:49:17 -07001701 if (chain != 0) {
Eric Laurent8cc93b92010-08-11 05:20:11 -07001702 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurent76c40f72010-07-15 12:50:15 -07001703 chain->setVolume_l(&v, &v);
Eric Laurent65b65452010-06-01 23:49:17 -07001704 masterVolume = (float)((v + (1 << 23)) >> 24);
1705 chain.clear();
1706 }
Glenn Kasten871c16c2010-03-05 12:18:01 -08001707
Eric Laurenta553c252009-07-17 12:17:14 -07001708 for (size_t i=0 ; i<count ; i++) {
1709 sp<Track> t = activeTracks[i].promote();
1710 if (t == 0) continue;
1711
1712 Track* const track = t.get();
1713 audio_track_cblk_t* cblk = track->cblk();
1714
1715 // The first time a track is added we wait
1716 // for all its buffers to be filled before processing it
1717 mAudioMixer->setActiveTrack(track->name());
Eric Laurent9a30fc12010-10-05 14:41:42 -07001718 if (cblk->framesReady() && track->isReady() &&
Eric Laurent71f37cd2010-03-31 12:21:17 -07001719 !track->isPaused() && !track->isTerminated())
Eric Laurenta553c252009-07-17 12:17:14 -07001720 {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08001721 //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 -07001722
Eric Laurent65b65452010-06-01 23:49:17 -07001723 mixedTracks++;
1724
1725 // track->mainBuffer() != mMixBuffer means there is an effect chain
1726 // connected to the track
1727 chain.clear();
1728 if (track->mainBuffer() != mMixBuffer) {
1729 chain = getEffectChain_l(track->sessionId());
1730 // Delegate volume control to effect in track effect chain if needed
1731 if (chain != 0) {
1732 tracksWithEffect++;
1733 } else {
1734 LOGW("prepareTracks_l(): track %08x attached to effect but no chain found on session %d",
1735 track->name(), track->sessionId());
1736 }
1737 }
1738
1739
1740 int param = AudioMixer::VOLUME;
1741 if (track->mFillingUpStatus == Track::FS_FILLED) {
1742 // no ramp for the first volume setting
1743 track->mFillingUpStatus = Track::FS_ACTIVE;
1744 if (track->mState == TrackBase::RESUMING) {
1745 track->mState = TrackBase::ACTIVE;
1746 param = AudioMixer::RAMP_VOLUME;
1747 }
1748 } else if (cblk->server != 0) {
1749 // If the track is stopped before the first frame was mixed,
1750 // do not apply ramp
1751 param = AudioMixer::RAMP_VOLUME;
1752 }
1753
Eric Laurenta553c252009-07-17 12:17:14 -07001754 // compute volume for this track
Eric Laurent27a2fdf2010-09-10 17:44:44 -07001755 uint32_t vl, vr, va;
Eric Laurent2a6b80b2010-07-29 23:43:43 -07001756 if (track->isMuted() || track->isPausing() ||
Eric Laurenta553c252009-07-17 12:17:14 -07001757 mStreamTypes[track->type()].mute) {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07001758 vl = vr = va = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07001759 if (track->isPausing()) {
1760 track->setPaused();
1761 }
1762 } else {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07001763
Glenn Kasten871c16c2010-03-05 12:18:01 -08001764 // read original volumes with volume control
Eric Laurenta553c252009-07-17 12:17:14 -07001765 float typeVolume = mStreamTypes[track->type()].volume;
Glenn Kasten871c16c2010-03-05 12:18:01 -08001766#ifdef LVMX
1767 bool streamMute=false;
1768 // read the volume from the LivesVibes audio engine.
1769 if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType))
1770 {
1771 LifeVibes::getStreamVolumes(audioOutputType, track->type(), &typeVolume, &streamMute);
1772 if (streamMute) {
1773 typeVolume = 0;
1774 }
1775 }
1776#endif
1777 float v = masterVolume * typeVolume;
Eric Laurent27a2fdf2010-09-10 17:44:44 -07001778 vl = (uint32_t)(v * cblk->volume[0]) << 12;
1779 vr = (uint32_t)(v * cblk->volume[1]) << 12;
Eric Laurenta553c252009-07-17 12:17:14 -07001780
Eric Laurent27a2fdf2010-09-10 17:44:44 -07001781 va = (uint32_t)(v * cblk->sendLevel);
Eric Laurenta553c252009-07-17 12:17:14 -07001782 }
Eric Laurent27a2fdf2010-09-10 17:44:44 -07001783 // Delegate volume control to effect in track effect chain if needed
1784 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
1785 // Do not ramp volume if volume is controlled by effect
1786 param = AudioMixer::VOLUME;
1787 track->mHasVolumeController = true;
1788 } else {
1789 // force no volume ramp when volume controller was just disabled or removed
1790 // from effect chain to avoid volume spike
1791 if (track->mHasVolumeController) {
1792 param = AudioMixer::VOLUME;
1793 }
1794 track->mHasVolumeController = false;
1795 }
1796
1797 // Convert volumes from 8.24 to 4.12 format
1798 int16_t left, right, aux;
1799 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
1800 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
1801 left = int16_t(v_clamped);
1802 v_clamped = (vr + (1 << 11)) >> 12;
1803 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
1804 right = int16_t(v_clamped);
1805
1806 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
1807 aux = int16_t(va);
Eric Laurent65b65452010-06-01 23:49:17 -07001808
Glenn Kasten871c16c2010-03-05 12:18:01 -08001809#ifdef LVMX
1810 if ( tracksConnectedChanged || stateChanged )
1811 {
1812 // only do the ramp when the volume is changed by the user / application
1813 param = AudioMixer::VOLUME;
1814 }
1815#endif
Eric Laurent65b65452010-06-01 23:49:17 -07001816
1817 // XXX: these things DON'T need to be done each time
1818 mAudioMixer->setBufferProvider(track);
1819 mAudioMixer->enable(AudioMixer::MIXING);
1820
1821 mAudioMixer->setParameter(param, AudioMixer::VOLUME0, (void *)left);
1822 mAudioMixer->setParameter(param, AudioMixer::VOLUME1, (void *)right);
1823 mAudioMixer->setParameter(param, AudioMixer::AUXLEVEL, (void *)aux);
Eric Laurenta553c252009-07-17 12:17:14 -07001824 mAudioMixer->setParameter(
1825 AudioMixer::TRACK,
Eric Laurent65b65452010-06-01 23:49:17 -07001826 AudioMixer::FORMAT, (void *)track->format());
Eric Laurenta553c252009-07-17 12:17:14 -07001827 mAudioMixer->setParameter(
1828 AudioMixer::TRACK,
Eric Laurent65b65452010-06-01 23:49:17 -07001829 AudioMixer::CHANNEL_COUNT, (void *)track->channelCount());
Eric Laurenta553c252009-07-17 12:17:14 -07001830 mAudioMixer->setParameter(
1831 AudioMixer::RESAMPLE,
1832 AudioMixer::SAMPLE_RATE,
Eric Laurent65b65452010-06-01 23:49:17 -07001833 (void *)(cblk->sampleRate));
1834 mAudioMixer->setParameter(
1835 AudioMixer::TRACK,
1836 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
1837 mAudioMixer->setParameter(
1838 AudioMixer::TRACK,
1839 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
Eric Laurenta553c252009-07-17 12:17:14 -07001840
1841 // reset retry count
1842 track->mRetryCount = kMaxTrackRetries;
Eric Laurent059b4be2009-11-09 23:32:22 -08001843 mixerStatus = MIXER_TRACKS_READY;
Eric Laurenta553c252009-07-17 12:17:14 -07001844 } else {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08001845 //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 -07001846 if (track->isStopped()) {
1847 track->reset();
1848 }
1849 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
1850 // We have consumed all the buffers of this track.
1851 // Remove it from the list of active tracks.
1852 tracksToRemove->add(track);
Eric Laurenta553c252009-07-17 12:17:14 -07001853 } else {
1854 // No buffers for this track. Give it a few chances to
1855 // fill a buffer, then remove it from active list.
1856 if (--(track->mRetryCount) <= 0) {
Eric Laurent62443f52009-10-05 20:29:18 -07001857 LOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", track->name(), this);
Eric Laurenta553c252009-07-17 12:17:14 -07001858 tracksToRemove->add(track);
Eric Laurent4712baa2010-09-30 16:12:31 -07001859 // indicate to client process that the track was disabled because of underrun
1860 cblk->flags |= CBLK_DISABLED_ON;
Eric Laurent059b4be2009-11-09 23:32:22 -08001861 } else if (mixerStatus != MIXER_TRACKS_READY) {
1862 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07001863 }
Eric Laurenta553c252009-07-17 12:17:14 -07001864 }
Eric Laurent65b65452010-06-01 23:49:17 -07001865 mAudioMixer->disable(AudioMixer::MIXING);
Eric Laurenta553c252009-07-17 12:17:14 -07001866 }
1867 }
1868
1869 // remove all the tracks that need to be...
1870 count = tracksToRemove->size();
1871 if (UNLIKELY(count)) {
1872 for (size_t i=0 ; i<count ; i++) {
1873 const sp<Track>& track = tracksToRemove->itemAt(i);
1874 mActiveTracks.remove(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001875 if (track->mainBuffer() != mMixBuffer) {
1876 chain = getEffectChain_l(track->sessionId());
1877 if (chain != 0) {
1878 LOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
1879 chain->stopTrack();
1880 }
1881 }
Eric Laurenta553c252009-07-17 12:17:14 -07001882 if (track->isTerminated()) {
1883 mTracks.remove(track);
1884 deleteTrackName_l(track->mName);
1885 }
1886 }
1887 }
1888
Eric Laurent65b65452010-06-01 23:49:17 -07001889 // mix buffer must be cleared if all tracks are connected to an
1890 // effect chain as in this case the mixer will not write to
1891 // mix buffer and track effects will accumulate into it
1892 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
1893 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
1894 }
1895
Eric Laurent059b4be2009-11-09 23:32:22 -08001896 return mixerStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07001897}
1898
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001899void AudioFlinger::MixerThread::invalidateTracks(int streamType)
Eric Laurenta553c252009-07-17 12:17:14 -07001900{
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001901 LOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
1902 this, streamType, mTracks.size());
Eric Laurenta553c252009-07-17 12:17:14 -07001903 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001904
Eric Laurenta553c252009-07-17 12:17:14 -07001905 size_t size = mTracks.size();
1906 for (size_t i = 0; i < size; i++) {
1907 sp<Track> t = mTracks[i];
1908 if (t->type() == streamType) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001909 t->mCblk->lock.lock();
1910 t->mCblk->flags |= CBLK_INVALID_ON;
1911 t->mCblk->cv.signal();
1912 t->mCblk->lock.unlock();
Eric Laurenta553c252009-07-17 12:17:14 -07001913 }
Eric Laurent53334cd2010-06-23 17:38:20 -07001914 }
1915}
Eric Laurenta553c252009-07-17 12:17:14 -07001916
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001917
Eric Laurenta553c252009-07-17 12:17:14 -07001918// getTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001919int AudioFlinger::MixerThread::getTrackName_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001920{
1921 return mAudioMixer->getTrackName();
1922}
1923
Eric Laurenta553c252009-07-17 12:17:14 -07001924// deleteTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001925void AudioFlinger::MixerThread::deleteTrackName_l(int name)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001926{
Eric Laurent0a080292009-12-07 10:53:10 -08001927 LOGV("remove track (%d) and delete from mixer", name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001928 mAudioMixer->deleteTrackName(name);
1929}
1930
Eric Laurenta553c252009-07-17 12:17:14 -07001931// checkForNewParameters_l() must be called with ThreadBase::mLock held
1932bool AudioFlinger::MixerThread::checkForNewParameters_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001933{
Eric Laurenta553c252009-07-17 12:17:14 -07001934 bool reconfig = false;
1935
Eric Laurent8fce46a2009-08-04 09:45:33 -07001936 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07001937 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07001938 String8 keyValuePair = mNewParameters[0];
1939 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07001940 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07001941
Eric Laurenta553c252009-07-17 12:17:14 -07001942 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
1943 reconfig = true;
1944 }
1945 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
1946 if (value != AudioSystem::PCM_16_BIT) {
1947 status = BAD_VALUE;
1948 } else {
1949 reconfig = true;
1950 }
1951 }
1952 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
1953 if (value != AudioSystem::CHANNEL_OUT_STEREO) {
1954 status = BAD_VALUE;
1955 } else {
1956 reconfig = true;
1957 }
1958 }
1959 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
1960 // do not accept frame count changes if tracks are open as the track buffer
1961 // size depends on frame count and correct behavior would not be garantied
1962 // if frame count is changed after track creation
1963 if (!mTracks.isEmpty()) {
1964 status = INVALID_OPERATION;
1965 } else {
1966 reconfig = true;
1967 }
1968 }
Eric Laurent65b65452010-06-01 23:49:17 -07001969 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
1970 // forward device change to effects that have requested to be
1971 // aware of attached audio device.
1972 mDevice = (uint32_t)value;
1973 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07001974 mEffectChains[i]->setDevice_l(mDevice);
Eric Laurent65b65452010-06-01 23:49:17 -07001975 }
1976 }
1977
Eric Laurenta553c252009-07-17 12:17:14 -07001978 if (status == NO_ERROR) {
Eric Laurent8fce46a2009-08-04 09:45:33 -07001979 status = mOutput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07001980 if (!mStandby && status == INVALID_OPERATION) {
1981 mOutput->standby();
1982 mStandby = true;
1983 mBytesWritten = 0;
Eric Laurent8fce46a2009-08-04 09:45:33 -07001984 status = mOutput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07001985 }
1986 if (status == NO_ERROR && reconfig) {
1987 delete mAudioMixer;
1988 readOutputParameters();
1989 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1990 for (size_t i = 0; i < mTracks.size() ; i++) {
1991 int name = getTrackName_l();
1992 if (name < 0) break;
1993 mTracks[i]->mName = name;
Eric Laurent6f7e0972009-08-10 08:15:12 -07001994 // limit track sample rate to 2 x new output sample rate
1995 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
1996 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
1997 }
Eric Laurenta553c252009-07-17 12:17:14 -07001998 }
Eric Laurent8fce46a2009-08-04 09:45:33 -07001999 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07002000 }
2001 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08002002
2003 mNewParameters.removeAt(0);
2004
Eric Laurenta553c252009-07-17 12:17:14 -07002005 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07002006 mParamCond.signal();
Eric Laurent8fce46a2009-08-04 09:45:33 -07002007 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07002008 }
2009 return reconfig;
2010}
2011
2012status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2013{
2014 const size_t SIZE = 256;
2015 char buffer[SIZE];
2016 String8 result;
2017
2018 PlaybackThread::dumpInternals(fd, args);
2019
2020 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2021 result.append(buffer);
2022 write(fd, result.string(), result.size());
2023 return NO_ERROR;
2024}
2025
Eric Laurent059b4be2009-11-09 23:32:22 -08002026uint32_t AudioFlinger::MixerThread::activeSleepTimeUs()
Eric Laurent62443f52009-10-05 20:29:18 -07002027{
Eric Laurent059b4be2009-11-09 23:32:22 -08002028 return (uint32_t)(mOutput->latency() * 1000) / 2;
2029}
2030
2031uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2032{
Eric Laurenta54d7d32010-07-29 06:50:24 -07002033 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Eric Laurent62443f52009-10-05 20:29:18 -07002034}
2035
Eric Laurent8448a792010-08-18 18:13:17 -07002036uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2037{
2038 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2039}
2040
Eric Laurenta553c252009-07-17 12:17:14 -07002041// ----------------------------------------------------------------------------
Eric Laurent65b65452010-06-01 23:49:17 -07002042AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
2043 : PlaybackThread(audioFlinger, output, id, device)
Eric Laurenta553c252009-07-17 12:17:14 -07002044{
2045 mType = PlaybackThread::DIRECT;
2046}
2047
2048AudioFlinger::DirectOutputThread::~DirectOutputThread()
2049{
2050}
2051
2052
Eric Laurent65b65452010-06-01 23:49:17 -07002053static inline int16_t clamp16(int32_t sample)
2054{
2055 if ((sample>>15) ^ (sample>>31))
2056 sample = 0x7FFF ^ (sample>>31);
2057 return sample;
2058}
2059
2060static inline
2061int32_t mul(int16_t in, int16_t v)
2062{
2063#if defined(__arm__) && !defined(__thumb__)
2064 int32_t out;
2065 asm( "smulbb %[out], %[in], %[v] \n"
2066 : [out]"=r"(out)
2067 : [in]"%r"(in), [v]"r"(v)
2068 : );
2069 return out;
2070#else
2071 return in * int32_t(v);
2072#endif
2073}
2074
2075void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2076{
2077 // Do not apply volume on compressed audio
2078 if (!AudioSystem::isLinearPCM(mFormat)) {
2079 return;
2080 }
2081
2082 // convert to signed 16 bit before volume calculation
2083 if (mFormat == AudioSystem::PCM_8_BIT) {
2084 size_t count = mFrameCount * mChannelCount;
2085 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2086 int16_t *dst = mMixBuffer + count-1;
2087 while(count--) {
2088 *dst-- = (int16_t)(*src--^0x80) << 8;
2089 }
2090 }
2091
2092 size_t frameCount = mFrameCount;
2093 int16_t *out = mMixBuffer;
2094 if (ramp) {
2095 if (mChannelCount == 1) {
2096 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2097 int32_t vlInc = d / (int32_t)frameCount;
2098 int32_t vl = ((int32_t)mLeftVolShort << 16);
2099 do {
2100 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2101 out++;
2102 vl += vlInc;
2103 } while (--frameCount);
2104
2105 } else {
2106 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2107 int32_t vlInc = d / (int32_t)frameCount;
2108 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2109 int32_t vrInc = d / (int32_t)frameCount;
2110 int32_t vl = ((int32_t)mLeftVolShort << 16);
2111 int32_t vr = ((int32_t)mRightVolShort << 16);
2112 do {
2113 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2114 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2115 out += 2;
2116 vl += vlInc;
2117 vr += vrInc;
2118 } while (--frameCount);
2119 }
2120 } else {
2121 if (mChannelCount == 1) {
2122 do {
2123 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2124 out++;
2125 } while (--frameCount);
2126 } else {
2127 do {
2128 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2129 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2130 out += 2;
2131 } while (--frameCount);
2132 }
2133 }
2134
2135 // convert back to unsigned 8 bit after volume calculation
2136 if (mFormat == AudioSystem::PCM_8_BIT) {
2137 size_t count = mFrameCount * mChannelCount;
2138 int16_t *src = mMixBuffer;
2139 uint8_t *dst = (uint8_t *)mMixBuffer;
2140 while(count--) {
2141 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2142 }
2143 }
2144
2145 mLeftVolShort = leftVol;
2146 mRightVolShort = rightVol;
2147}
2148
Eric Laurenta553c252009-07-17 12:17:14 -07002149bool AudioFlinger::DirectOutputThread::threadLoop()
2150{
Eric Laurent059b4be2009-11-09 23:32:22 -08002151 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002152 sp<Track> trackToRemove;
2153 sp<Track> activeTrack;
2154 nsecs_t standbyTime = systemTime();
2155 int8_t *curBuf;
2156 size_t mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent059b4be2009-11-09 23:32:22 -08002157 uint32_t activeSleepTime = activeSleepTimeUs();
2158 uint32_t idleSleepTime = idleSleepTimeUs();
2159 uint32_t sleepTime = idleSleepTime;
Eric Laurentef9500f2010-03-11 14:47:00 -08002160 // use shorter standby delay as on normal output to release
2161 // hardware resources as soon as possible
2162 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
Eric Laurent059b4be2009-11-09 23:32:22 -08002163
Eric Laurenta553c252009-07-17 12:17:14 -07002164 while (!exitPending())
2165 {
Eric Laurent65b65452010-06-01 23:49:17 -07002166 bool rampVolume;
2167 uint16_t leftVol;
2168 uint16_t rightVol;
2169 Vector< sp<EffectChain> > effectChains;
2170
Eric Laurenta553c252009-07-17 12:17:14 -07002171 processConfigEvents();
2172
Eric Laurent059b4be2009-11-09 23:32:22 -08002173 mixerStatus = MIXER_IDLE;
2174
Eric Laurenta553c252009-07-17 12:17:14 -07002175 { // scope for the mLock
2176
2177 Mutex::Autolock _l(mLock);
2178
2179 if (checkForNewParameters_l()) {
2180 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent059b4be2009-11-09 23:32:22 -08002181 activeSleepTime = activeSleepTimeUs();
2182 idleSleepTime = idleSleepTimeUs();
Eric Laurentef9500f2010-03-11 14:47:00 -08002183 standbyDelay = microseconds(activeSleepTime*2);
Eric Laurenta553c252009-07-17 12:17:14 -07002184 }
2185
2186 // put audio hardware into standby after short delay
2187 if UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2188 mSuspended) {
2189 // wait until we have something to do...
2190 if (!mStandby) {
2191 LOGV("Audio hardware entering standby, mixer %p\n", this);
2192 mOutput->standby();
2193 mStandby = true;
2194 mBytesWritten = 0;
2195 }
2196
2197 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2198 // we're about to wait, flush the binder command buffer
2199 IPCThreadState::self()->flushCommands();
2200
2201 if (exitPending()) break;
2202
2203 LOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
2204 mWaitWorkCV.wait(mLock);
2205 LOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
2206
2207 if (mMasterMute == false) {
2208 char value[PROPERTY_VALUE_MAX];
2209 property_get("ro.audio.silent", value, "0");
2210 if (atoi(value)) {
2211 LOGD("Silence is golden");
2212 setMasterMute(true);
2213 }
2214 }
2215
Eric Laurentef9500f2010-03-11 14:47:00 -08002216 standbyTime = systemTime() + standbyDelay;
Eric Laurent059b4be2009-11-09 23:32:22 -08002217 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07002218 continue;
2219 }
2220 }
2221
Eric Laurent65b65452010-06-01 23:49:17 -07002222 effectChains = mEffectChains;
2223
Eric Laurenta553c252009-07-17 12:17:14 -07002224 // find out which tracks need to be processed
2225 if (mActiveTracks.size() != 0) {
2226 sp<Track> t = mActiveTracks[0].promote();
2227 if (t == 0) continue;
2228
2229 Track* const track = t.get();
2230 audio_track_cblk_t* cblk = track->cblk();
2231
2232 // The first time a track is added we wait
2233 // for all its buffers to be filled before processing it
Eric Laurent9a30fc12010-10-05 14:41:42 -07002234 if (cblk->framesReady() && track->isReady() &&
Eric Laurent380558b2010-04-09 06:11:48 -07002235 !track->isPaused() && !track->isTerminated())
Eric Laurenta553c252009-07-17 12:17:14 -07002236 {
2237 //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
2238
Eric Laurent65b65452010-06-01 23:49:17 -07002239 if (track->mFillingUpStatus == Track::FS_FILLED) {
2240 track->mFillingUpStatus = Track::FS_ACTIVE;
2241 mLeftVolFloat = mRightVolFloat = 0;
2242 mLeftVolShort = mRightVolShort = 0;
2243 if (track->mState == TrackBase::RESUMING) {
2244 track->mState = TrackBase::ACTIVE;
2245 rampVolume = true;
2246 }
2247 } else if (cblk->server != 0) {
2248 // If the track is stopped before the first frame was mixed,
2249 // do not apply ramp
2250 rampVolume = true;
2251 }
Eric Laurenta553c252009-07-17 12:17:14 -07002252 // compute volume for this track
2253 float left, right;
2254 if (track->isMuted() || mMasterMute || track->isPausing() ||
2255 mStreamTypes[track->type()].mute) {
2256 left = right = 0;
2257 if (track->isPausing()) {
2258 track->setPaused();
2259 }
2260 } else {
2261 float typeVolume = mStreamTypes[track->type()].volume;
2262 float v = mMasterVolume * typeVolume;
2263 float v_clamped = v * cblk->volume[0];
2264 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2265 left = v_clamped/MAX_GAIN;
2266 v_clamped = v * cblk->volume[1];
2267 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2268 right = v_clamped/MAX_GAIN;
2269 }
2270
Eric Laurent65b65452010-06-01 23:49:17 -07002271 if (left != mLeftVolFloat || right != mRightVolFloat) {
2272 mLeftVolFloat = left;
2273 mRightVolFloat = right;
Eric Laurenta553c252009-07-17 12:17:14 -07002274
Eric Laurent65b65452010-06-01 23:49:17 -07002275 // If audio HAL implements volume control,
2276 // force software volume to nominal value
2277 if (mOutput->setVolume(left, right) == NO_ERROR) {
2278 left = 1.0f;
2279 right = 1.0f;
Eric Laurenta553c252009-07-17 12:17:14 -07002280 }
Eric Laurent65b65452010-06-01 23:49:17 -07002281
2282 // Convert volumes from float to 8.24
2283 uint32_t vl = (uint32_t)(left * (1 << 24));
2284 uint32_t vr = (uint32_t)(right * (1 << 24));
2285
2286 // Delegate volume control to effect in track effect chain if needed
2287 // only one effect chain can be present on DirectOutputThread, so if
2288 // there is one, the track is connected to it
2289 if (!effectChains.isEmpty()) {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002290 // Do not ramp volume if volume is controlled by effect
Eric Laurent76c40f72010-07-15 12:50:15 -07002291 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002292 rampVolume = false;
2293 }
2294 }
2295
2296 // Convert volumes from 8.24 to 4.12 format
2297 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2298 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2299 leftVol = (uint16_t)v_clamped;
2300 v_clamped = (vr + (1 << 11)) >> 12;
2301 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2302 rightVol = (uint16_t)v_clamped;
2303 } else {
2304 leftVol = mLeftVolShort;
2305 rightVol = mRightVolShort;
2306 rampVolume = false;
Eric Laurenta553c252009-07-17 12:17:14 -07002307 }
2308
2309 // reset retry count
Eric Laurentef9500f2010-03-11 14:47:00 -08002310 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurenta553c252009-07-17 12:17:14 -07002311 activeTrack = t;
Eric Laurent059b4be2009-11-09 23:32:22 -08002312 mixerStatus = MIXER_TRACKS_READY;
Eric Laurenta553c252009-07-17 12:17:14 -07002313 } else {
2314 //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
2315 if (track->isStopped()) {
2316 track->reset();
2317 }
2318 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2319 // We have consumed all the buffers of this track.
2320 // Remove it from the list of active tracks.
2321 trackToRemove = track;
2322 } else {
2323 // No buffers for this track. Give it a few chances to
2324 // fill a buffer, then remove it from active list.
2325 if (--(track->mRetryCount) <= 0) {
2326 LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
2327 trackToRemove = track;
Eric Laurent059b4be2009-11-09 23:32:22 -08002328 } else {
2329 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07002330 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002331 }
Eric Laurenta553c252009-07-17 12:17:14 -07002332 }
2333 }
2334
2335 // remove all the tracks that need to be...
2336 if (UNLIKELY(trackToRemove != 0)) {
2337 mActiveTracks.remove(trackToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07002338 if (!effectChains.isEmpty()) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002339 LOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
2340 trackToRemove->sessionId());
Eric Laurent65b65452010-06-01 23:49:17 -07002341 effectChains[0]->stopTrack();
2342 }
Eric Laurenta553c252009-07-17 12:17:14 -07002343 if (trackToRemove->isTerminated()) {
2344 mTracks.remove(trackToRemove);
2345 deleteTrackName_l(trackToRemove->mName);
2346 }
2347 }
Eric Laurent65b65452010-06-01 23:49:17 -07002348
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002349 lockEffectChains_l(effectChains);
Eric Laurenta553c252009-07-17 12:17:14 -07002350 }
2351
Eric Laurent059b4be2009-11-09 23:32:22 -08002352 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002353 AudioBufferProvider::Buffer buffer;
2354 size_t frameCount = mFrameCount;
2355 curBuf = (int8_t *)mMixBuffer;
2356 // output audio to hardware
Eric Laurent65b65452010-06-01 23:49:17 -07002357 while (frameCount) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002358 buffer.frameCount = frameCount;
2359 activeTrack->getNextBuffer(&buffer);
2360 if (UNLIKELY(buffer.raw == 0)) {
2361 memset(curBuf, 0, frameCount * mFrameSize);
2362 break;
2363 }
2364 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2365 frameCount -= buffer.frameCount;
2366 curBuf += buffer.frameCount * mFrameSize;
2367 activeTrack->releaseBuffer(&buffer);
2368 }
2369 sleepTime = 0;
Eric Laurentef9500f2010-03-11 14:47:00 -08002370 standbyTime = systemTime() + standbyDelay;
Eric Laurent96c08a62009-09-07 08:38:38 -07002371 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07002372 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002373 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2374 sleepTime = activeSleepTime;
2375 } else {
2376 sleepTime = idleSleepTime;
2377 }
Eric Laurent62443f52009-10-05 20:29:18 -07002378 } else if (mBytesWritten != 0 && AudioSystem::isLinearPCM(mFormat)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002379 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent96c08a62009-09-07 08:38:38 -07002380 sleepTime = 0;
Eric Laurent96c08a62009-09-07 08:38:38 -07002381 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002382 }
Eric Laurent96c08a62009-09-07 08:38:38 -07002383
Eric Laurentf69a3f82009-09-22 00:35:48 -07002384 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07002385 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07002386 }
2387 // sleepTime == 0 means we must write to audio hardware
2388 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07002389 if (mixerStatus == MIXER_TRACKS_READY) {
2390 applyVolume(leftVol, rightVol, rampVolume);
2391 }
2392 for (size_t i = 0; i < effectChains.size(); i ++) {
2393 effectChains[i]->process_l();
2394 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002395 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07002396
Eric Laurentf69a3f82009-09-22 00:35:48 -07002397 mLastWriteTime = systemTime();
2398 mInWrite = true;
Eric Laurent0986e792010-01-19 17:37:09 -08002399 mBytesWritten += mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002400 int bytesWritten = (int)mOutput->write(mMixBuffer, mixBufferSize);
Eric Laurent0986e792010-01-19 17:37:09 -08002401 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002402 mNumWrites++;
2403 mInWrite = false;
2404 mStandby = false;
2405 } else {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002406 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002407 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07002408 }
2409
2410 // finally let go of removed track, without the lock held
2411 // since we can't guarantee the destructors won't acquire that
2412 // same lock.
2413 trackToRemove.clear();
2414 activeTrack.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07002415
2416 // Effect chains will be actually deleted here if they were removed from
2417 // mEffectChains list during mixing or effects processing
2418 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07002419 }
2420
2421 if (!mStandby) {
2422 mOutput->standby();
2423 }
Eric Laurenta553c252009-07-17 12:17:14 -07002424
2425 LOGV("DirectOutputThread %p exiting", this);
2426 return false;
2427}
2428
2429// getTrackName_l() must be called with ThreadBase::mLock held
2430int AudioFlinger::DirectOutputThread::getTrackName_l()
2431{
2432 return 0;
2433}
2434
2435// deleteTrackName_l() must be called with ThreadBase::mLock held
2436void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2437{
2438}
2439
2440// checkForNewParameters_l() must be called with ThreadBase::mLock held
2441bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2442{
2443 bool reconfig = false;
2444
Eric Laurent8fce46a2009-08-04 09:45:33 -07002445 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07002446 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002447 String8 keyValuePair = mNewParameters[0];
2448 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002449 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002450
Eric Laurenta553c252009-07-17 12:17:14 -07002451 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2452 // do not accept frame count changes if tracks are open as the track buffer
2453 // size depends on frame count and correct behavior would not be garantied
2454 // if frame count is changed after track creation
2455 if (!mTracks.isEmpty()) {
2456 status = INVALID_OPERATION;
2457 } else {
2458 reconfig = true;
2459 }
2460 }
2461 if (status == NO_ERROR) {
Eric Laurent8fce46a2009-08-04 09:45:33 -07002462 status = mOutput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002463 if (!mStandby && status == INVALID_OPERATION) {
2464 mOutput->standby();
2465 mStandby = true;
2466 mBytesWritten = 0;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002467 status = mOutput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002468 }
2469 if (status == NO_ERROR && reconfig) {
2470 readOutputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07002471 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07002472 }
2473 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08002474
2475 mNewParameters.removeAt(0);
2476
Eric Laurenta553c252009-07-17 12:17:14 -07002477 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07002478 mParamCond.signal();
Eric Laurent8fce46a2009-08-04 09:45:33 -07002479 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07002480 }
2481 return reconfig;
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08002482}
2483
Eric Laurent059b4be2009-11-09 23:32:22 -08002484uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
Eric Laurent62443f52009-10-05 20:29:18 -07002485{
2486 uint32_t time;
2487 if (AudioSystem::isLinearPCM(mFormat)) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002488 time = (uint32_t)(mOutput->latency() * 1000) / 2;
2489 } else {
2490 time = 10000;
2491 }
2492 return time;
2493}
2494
2495uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2496{
2497 uint32_t time;
2498 if (AudioSystem::isLinearPCM(mFormat)) {
Eric Laurenta54d7d32010-07-29 06:50:24 -07002499 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Eric Laurent62443f52009-10-05 20:29:18 -07002500 } else {
2501 time = 10000;
2502 }
2503 return time;
2504}
2505
Eric Laurent8448a792010-08-18 18:13:17 -07002506uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2507{
2508 uint32_t time;
2509 if (AudioSystem::isLinearPCM(mFormat)) {
2510 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2511 } else {
2512 time = 10000;
2513 }
2514 return time;
2515}
2516
2517
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002518// ----------------------------------------------------------------------------
2519
Eric Laurent49f02be2009-11-19 09:00:56 -08002520AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread, int id)
Eric Laurent65b65452010-06-01 23:49:17 -07002521 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device()), mWaitTimeMs(UINT_MAX)
Eric Laurenta553c252009-07-17 12:17:14 -07002522{
2523 mType = PlaybackThread::DUPLICATING;
2524 addOutputTrack(mainThread);
2525}
2526
2527AudioFlinger::DuplicatingThread::~DuplicatingThread()
2528{
Eric Laurent0a080292009-12-07 10:53:10 -08002529 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2530 mOutputTracks[i]->destroy();
2531 }
Eric Laurenta553c252009-07-17 12:17:14 -07002532 mOutputTracks.clear();
2533}
2534
2535bool AudioFlinger::DuplicatingThread::threadLoop()
2536{
Eric Laurenta553c252009-07-17 12:17:14 -07002537 Vector< sp<Track> > tracksToRemove;
Eric Laurent059b4be2009-11-09 23:32:22 -08002538 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002539 nsecs_t standbyTime = systemTime();
2540 size_t mixBufferSize = mFrameCount*mFrameSize;
2541 SortedVector< sp<OutputTrack> > outputTracks;
Eric Laurent62443f52009-10-05 20:29:18 -07002542 uint32_t writeFrames = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08002543 uint32_t activeSleepTime = activeSleepTimeUs();
2544 uint32_t idleSleepTime = idleSleepTimeUs();
2545 uint32_t sleepTime = idleSleepTime;
Eric Laurent65b65452010-06-01 23:49:17 -07002546 Vector< sp<EffectChain> > effectChains;
Eric Laurenta553c252009-07-17 12:17:14 -07002547
2548 while (!exitPending())
2549 {
2550 processConfigEvents();
2551
Eric Laurent059b4be2009-11-09 23:32:22 -08002552 mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002553 { // scope for the mLock
2554
2555 Mutex::Autolock _l(mLock);
2556
2557 if (checkForNewParameters_l()) {
2558 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002559 updateWaitTime();
Eric Laurent059b4be2009-11-09 23:32:22 -08002560 activeSleepTime = activeSleepTimeUs();
2561 idleSleepTime = idleSleepTimeUs();
Eric Laurenta553c252009-07-17 12:17:14 -07002562 }
2563
2564 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
2565
2566 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2567 outputTracks.add(mOutputTracks[i]);
2568 }
2569
2570 // put audio hardware into standby after short delay
2571 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
2572 mSuspended) {
2573 if (!mStandby) {
2574 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurenta553c252009-07-17 12:17:14 -07002575 outputTracks[i]->stop();
Eric Laurenta553c252009-07-17 12:17:14 -07002576 }
2577 mStandby = true;
2578 mBytesWritten = 0;
2579 }
2580
2581 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
2582 // we're about to wait, flush the binder command buffer
2583 IPCThreadState::self()->flushCommands();
2584 outputTracks.clear();
2585
2586 if (exitPending()) break;
2587
2588 LOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
2589 mWaitWorkCV.wait(mLock);
2590 LOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
2591 if (mMasterMute == false) {
2592 char value[PROPERTY_VALUE_MAX];
2593 property_get("ro.audio.silent", value, "0");
2594 if (atoi(value)) {
2595 LOGD("Silence is golden");
2596 setMasterMute(true);
2597 }
2598 }
2599
2600 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent059b4be2009-11-09 23:32:22 -08002601 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07002602 continue;
2603 }
2604 }
2605
Eric Laurent059b4be2009-11-09 23:32:22 -08002606 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07002607
2608 // prevent any changes in effect chain list and in each effect chain
2609 // during mixing and effect process as the audio buffers could be deleted
2610 // or modified if an effect is created or deleted
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002611 lockEffectChains_l(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002612 }
Eric Laurenta553c252009-07-17 12:17:14 -07002613
Eric Laurent059b4be2009-11-09 23:32:22 -08002614 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurenta553c252009-07-17 12:17:14 -07002615 // mix buffers...
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002616 if (outputsReady(outputTracks)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002617 mAudioMixer->process();
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002618 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07002619 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002620 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002621 sleepTime = 0;
Eric Laurent62443f52009-10-05 20:29:18 -07002622 writeFrames = mFrameCount;
Eric Laurenta553c252009-07-17 12:17:14 -07002623 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07002624 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002625 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2626 sleepTime = activeSleepTime;
2627 } else {
2628 sleepTime = idleSleepTime;
2629 }
Eric Laurent62443f52009-10-05 20:29:18 -07002630 } else if (mBytesWritten != 0) {
2631 // flush remaining overflow buffers in output tracks
2632 for (size_t i = 0; i < outputTracks.size(); i++) {
2633 if (outputTracks[i]->isActive()) {
2634 sleepTime = 0;
2635 writeFrames = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07002636 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent62443f52009-10-05 20:29:18 -07002637 break;
2638 }
2639 }
Eric Laurenta553c252009-07-17 12:17:14 -07002640 }
2641 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002642
2643 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07002644 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07002645 }
2646 // sleepTime == 0 means we must write to audio hardware
2647 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07002648 for (size_t i = 0; i < effectChains.size(); i ++) {
2649 effectChains[i]->process_l();
2650 }
2651 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002652 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07002653
Eric Laurent62443f52009-10-05 20:29:18 -07002654 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002655 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurent65b65452010-06-01 23:49:17 -07002656 outputTracks[i]->write(mMixBuffer, writeFrames);
Eric Laurenta553c252009-07-17 12:17:14 -07002657 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002658 mStandby = false;
2659 mBytesWritten += mixBufferSize;
Eric Laurenta553c252009-07-17 12:17:14 -07002660 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07002661 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002662 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002663 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07002664 }
2665
2666 // finally let go of all our tracks, without the lock held
2667 // since we can't guarantee the destructors won't acquire that
2668 // same lock.
2669 tracksToRemove.clear();
2670 outputTracks.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07002671
2672 // Effect chains will be actually deleted here if they were removed from
2673 // mEffectChains list during mixing or effects processing
2674 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07002675 }
2676
Eric Laurenta553c252009-07-17 12:17:14 -07002677 return false;
2678}
2679
2680void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
2681{
2682 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
2683 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002684 this,
Eric Laurenta553c252009-07-17 12:17:14 -07002685 mSampleRate,
2686 mFormat,
2687 mChannelCount,
2688 frameCount);
Eric Laurent6c30a712009-08-10 23:22:32 -07002689 if (outputTrack->cblk() != NULL) {
2690 thread->setStreamVolume(AudioSystem::NUM_STREAM_TYPES, 1.0f);
2691 mOutputTracks.add(outputTrack);
2692 LOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002693 updateWaitTime();
Eric Laurent6c30a712009-08-10 23:22:32 -07002694 }
Eric Laurenta553c252009-07-17 12:17:14 -07002695}
2696
2697void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
2698{
2699 Mutex::Autolock _l(mLock);
2700 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2701 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
Eric Laurent6c30a712009-08-10 23:22:32 -07002702 mOutputTracks[i]->destroy();
Eric Laurenta553c252009-07-17 12:17:14 -07002703 mOutputTracks.removeAt(i);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002704 updateWaitTime();
Eric Laurenta553c252009-07-17 12:17:14 -07002705 return;
2706 }
2707 }
2708 LOGV("removeOutputTrack(): unkonwn thread: %p", thread);
2709}
2710
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002711void AudioFlinger::DuplicatingThread::updateWaitTime()
2712{
2713 mWaitTimeMs = UINT_MAX;
2714 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2715 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
2716 if (strong != NULL) {
2717 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
2718 if (waitTimeMs < mWaitTimeMs) {
2719 mWaitTimeMs = waitTimeMs;
2720 }
2721 }
2722 }
2723}
2724
2725
2726bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
2727{
2728 for (size_t i = 0; i < outputTracks.size(); i++) {
2729 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
2730 if (thread == 0) {
2731 LOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
2732 return false;
2733 }
2734 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2735 if (playbackThread->standby() && !playbackThread->isSuspended()) {
2736 LOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
2737 return false;
2738 }
2739 }
2740 return true;
2741}
2742
2743uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
2744{
2745 return (mWaitTimeMs * 1000) / 2;
2746}
2747
Eric Laurenta553c252009-07-17 12:17:14 -07002748// ----------------------------------------------------------------------------
2749
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002750// TrackBase constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07002751AudioFlinger::ThreadBase::TrackBase::TrackBase(
2752 const wp<ThreadBase>& thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002753 const sp<Client>& client,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002754 uint32_t sampleRate,
2755 int format,
2756 int channelCount,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002757 int frameCount,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002758 uint32_t flags,
Eric Laurent65b65452010-06-01 23:49:17 -07002759 const sp<IMemory>& sharedBuffer,
2760 int sessionId)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002761 : RefBase(),
Eric Laurenta553c252009-07-17 12:17:14 -07002762 mThread(thread),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002763 mClient(client),
Eric Laurent8a77a992009-09-09 05:16:08 -07002764 mCblk(0),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002765 mFrameCount(0),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002766 mState(IDLE),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002767 mClientTid(-1),
2768 mFormat(format),
Eric Laurent65b65452010-06-01 23:49:17 -07002769 mFlags(flags & ~SYSTEM_FLAGS_MASK),
2770 mSessionId(sessionId)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002771{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002772 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
2773
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002774 // LOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002775 size_t size = sizeof(audio_track_cblk_t);
2776 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
2777 if (sharedBuffer == 0) {
2778 size += bufferSize;
2779 }
2780
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002781 if (client != NULL) {
2782 mCblkMemory = client->heap()->allocate(size);
2783 if (mCblkMemory != 0) {
2784 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
2785 if (mCblk) { // construct the shared structure in-place.
2786 new(mCblk) audio_track_cblk_t();
2787 // clear all buffers
2788 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07002789 mCblk->sampleRate = sampleRate;
Eric Laurentb0a01472010-05-14 05:45:46 -07002790 mCblk->channelCount = (uint8_t)channelCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002791 if (sharedBuffer == 0) {
2792 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2793 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2794 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent4712baa2010-09-30 16:12:31 -07002795 // written to buffer (other flags are cleared)
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002796 mCblk->flags = CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002797 } else {
2798 mBuffer = sharedBuffer->pointer();
2799 }
2800 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002801 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002802 } else {
2803 LOGE("not enough memory for AudioTrack size=%u", size);
2804 client->heap()->dump("AudioTrack");
2805 return;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002806 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002807 } else {
2808 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
2809 if (mCblk) { // construct the shared structure in-place.
2810 new(mCblk) audio_track_cblk_t();
2811 // clear all buffers
2812 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07002813 mCblk->sampleRate = sampleRate;
Eric Laurentb0a01472010-05-14 05:45:46 -07002814 mCblk->channelCount = (uint8_t)channelCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002815 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2816 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2817 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent4712baa2010-09-30 16:12:31 -07002818 // written to buffer (other flags are cleared)
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002819 mCblk->flags = CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002820 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
2821 }
2822 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002823}
2824
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002825AudioFlinger::ThreadBase::TrackBase::~TrackBase()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002826{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002827 if (mCblk) {
Eric Laurenta553c252009-07-17 12:17:14 -07002828 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
2829 if (mClient == NULL) {
2830 delete mCblk;
2831 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002832 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002833 mCblkMemory.clear(); // and free the shared memory
Eric Laurentb9481d82009-09-17 05:12:56 -07002834 if (mClient != NULL) {
2835 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
2836 mClient.clear();
2837 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002838}
2839
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002840void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002841{
2842 buffer->raw = 0;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002843 mFrameCount = buffer->frameCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002844 step();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002845 buffer->frameCount = 0;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002846}
2847
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002848bool AudioFlinger::ThreadBase::TrackBase::step() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002849 bool result;
2850 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002851
2852 result = cblk->stepServer(mFrameCount);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002853 if (!result) {
2854 LOGV("stepServer failed acquiring cblk mutex");
2855 mFlags |= STEPSERVER_FAILED;
2856 }
2857 return result;
2858}
2859
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002860void AudioFlinger::ThreadBase::TrackBase::reset() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002861 audio_track_cblk_t* cblk = this->cblk();
2862
2863 cblk->user = 0;
2864 cblk->server = 0;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002865 cblk->userBase = 0;
2866 cblk->serverBase = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002867 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002868 LOGV("TrackBase::reset");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002869}
2870
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002871sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002872{
2873 return mCblkMemory;
2874}
2875
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002876int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
The Android Open Source Project10592532009-03-18 17:39:46 -07002877 return (int)mCblk->sampleRate;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002878}
2879
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002880int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
Eric Laurentb0a01472010-05-14 05:45:46 -07002881 return (int)mCblk->channelCount;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002882}
2883
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002884void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002885 audio_track_cblk_t* cblk = this->cblk();
Eric Laurenta553c252009-07-17 12:17:14 -07002886 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
2887 int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002888
2889 // Check validity of returned pointer in case the track control block would have been corrupted.
Eric Laurenta553c252009-07-17 12:17:14 -07002890 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
2891 ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
The Android Open Source Project10592532009-03-18 17:39:46 -07002892 LOGE("TrackBase::getBuffer buffer out of range:\n start: %p, end %p , mBuffer %p mBufferEnd %p\n \
Eric Laurentb0a01472010-05-14 05:45:46 -07002893 server %d, serverBase %d, user %d, userBase %d, channelCount %d",
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002894 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Eric Laurentb0a01472010-05-14 05:45:46 -07002895 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, cblk->channelCount);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002896 return 0;
2897 }
2898
2899 return bufferStart;
2900}
2901
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002902// ----------------------------------------------------------------------------
2903
Eric Laurenta553c252009-07-17 12:17:14 -07002904// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
2905AudioFlinger::PlaybackThread::Track::Track(
2906 const wp<ThreadBase>& thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002907 const sp<Client>& client,
2908 int streamType,
2909 uint32_t sampleRate,
2910 int format,
2911 int channelCount,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002912 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07002913 const sp<IMemory>& sharedBuffer,
2914 int sessionId)
2915 : TrackBase(thread, client, sampleRate, format, channelCount, frameCount, 0, sharedBuffer, sessionId),
Eric Laurenta92ebfa2010-08-31 13:50:07 -07002916 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
2917 mAuxEffectId(0), mHasVolumeController(false)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002918{
Eric Laurent8a77a992009-09-09 05:16:08 -07002919 if (mCblk != NULL) {
2920 sp<ThreadBase> baseThread = thread.promote();
2921 if (baseThread != 0) {
2922 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
2923 mName = playbackThread->getTrackName_l();
Eric Laurent65b65452010-06-01 23:49:17 -07002924 mMainBuffer = playbackThread->mixBuffer();
Eric Laurent8a77a992009-09-09 05:16:08 -07002925 }
2926 LOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2927 if (mName < 0) {
2928 LOGE("no more track names available");
2929 }
2930 mVolume[0] = 1.0f;
2931 mVolume[1] = 1.0f;
2932 mStreamType = streamType;
2933 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
2934 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
2935 mCblk->frameSize = AudioSystem::isLinearPCM(format) ? channelCount * sizeof(int16_t) : sizeof(int8_t);
Eric Laurenta553c252009-07-17 12:17:14 -07002936 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002937}
2938
Eric Laurenta553c252009-07-17 12:17:14 -07002939AudioFlinger::PlaybackThread::Track::~Track()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002940{
Eric Laurenta553c252009-07-17 12:17:14 -07002941 LOGV("PlaybackThread::Track destructor");
2942 sp<ThreadBase> thread = mThread.promote();
2943 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08002944 Mutex::Autolock _l(thread->mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07002945 mState = TERMINATED;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002946 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002947}
2948
Eric Laurenta553c252009-07-17 12:17:14 -07002949void AudioFlinger::PlaybackThread::Track::destroy()
2950{
2951 // NOTE: destroyTrack_l() can remove a strong reference to this Track
2952 // by removing it from mTracks vector, so there is a risk that this Tracks's
2953 // desctructor is called. As the destructor needs to lock mLock,
2954 // we must acquire a strong reference on this Track before locking mLock
2955 // here so that the destructor is called only when exiting this function.
2956 // On the other hand, as long as Track::destroy() is only called by
2957 // TrackHandle destructor, the TrackHandle still holds a strong ref on
2958 // this Track with its member mTrack.
2959 sp<Track> keep(this);
2960 { // scope for mLock
2961 sp<ThreadBase> thread = mThread.promote();
2962 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08002963 if (!isOutputTrack()) {
2964 if (mState == ACTIVE || mState == RESUMING) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002965 AudioSystem::stopOutput(thread->id(),
2966 (AudioSystem::stream_type)mStreamType,
2967 mSessionId);
Eric Laurentac196e12009-12-01 02:17:41 -08002968 }
2969 AudioSystem::releaseOutput(thread->id());
Eric Laurent49f02be2009-11-19 09:00:56 -08002970 }
Eric Laurenta553c252009-07-17 12:17:14 -07002971 Mutex::Autolock _l(thread->mLock);
2972 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2973 playbackThread->destroyTrack_l(this);
2974 }
2975 }
2976}
2977
2978void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002979{
Eric Laurent65b65452010-06-01 23:49:17 -07002980 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 -07002981 mName - AudioMixer::TRACK0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002982 (mClient == NULL) ? getpid() : mClient->pid(),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002983 mStreamType,
2984 mFormat,
Eric Laurentb0a01472010-05-14 05:45:46 -07002985 mCblk->channelCount,
Eric Laurent65b65452010-06-01 23:49:17 -07002986 mSessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002987 mFrameCount,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002988 mState,
2989 mMute,
2990 mFillingUpStatus,
2991 mCblk->sampleRate,
2992 mCblk->volume[0],
2993 mCblk->volume[1],
2994 mCblk->server,
Eric Laurent65b65452010-06-01 23:49:17 -07002995 mCblk->user,
2996 (int)mMainBuffer,
2997 (int)mAuxBuffer);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002998}
2999
Eric Laurenta553c252009-07-17 12:17:14 -07003000status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003001{
3002 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003003 uint32_t framesReady;
3004 uint32_t framesReq = buffer->frameCount;
3005
3006 // Check if last stepServer failed, try to step now
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003007 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3008 if (!step()) goto getNextBuffer_exit;
3009 LOGV("stepServer recovered");
3010 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3011 }
3012
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003013 framesReady = cblk->framesReady();
3014
3015 if (LIKELY(framesReady)) {
3016 uint32_t s = cblk->server;
3017 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3018
3019 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3020 if (framesReq > framesReady) {
3021 framesReq = framesReady;
3022 }
3023 if (s + framesReq > bufferEnd) {
3024 framesReq = bufferEnd - s;
3025 }
3026
3027 buffer->raw = getBuffer(s, framesReq);
3028 if (buffer->raw == 0) goto getNextBuffer_exit;
3029
3030 buffer->frameCount = framesReq;
3031 return NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003032 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003033
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003034getNextBuffer_exit:
3035 buffer->raw = 0;
3036 buffer->frameCount = 0;
Eric Laurent62443f52009-10-05 20:29:18 -07003037 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 -07003038 return NOT_ENOUGH_DATA;
3039}
3040
Eric Laurenta553c252009-07-17 12:17:14 -07003041bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurent9a30fc12010-10-05 14:41:42 -07003042 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003043
3044 if (mCblk->framesReady() >= mCblk->frameCount ||
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003045 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003046 mFillingUpStatus = FS_FILLED;
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003047 mCblk->flags &= ~CBLK_FORCEREADY_MSK;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003048 return true;
3049 }
3050 return false;
3051}
3052
Eric Laurenta553c252009-07-17 12:17:14 -07003053status_t AudioFlinger::PlaybackThread::Track::start()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003054{
Eric Laurent49f02be2009-11-19 09:00:56 -08003055 status_t status = NO_ERROR;
Eric Laurent0d7e0482010-07-19 06:24:46 -07003056 LOGV("start(%d), calling thread %d session %d",
3057 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Eric Laurenta553c252009-07-17 12:17:14 -07003058 sp<ThreadBase> thread = mThread.promote();
3059 if (thread != 0) {
3060 Mutex::Autolock _l(thread->mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08003061 int state = mState;
3062 // here the track could be either new, or restarted
3063 // in both cases "unstop" the track
3064 if (mState == PAUSED) {
3065 mState = TrackBase::RESUMING;
3066 LOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
3067 } else {
3068 mState = TrackBase::ACTIVE;
3069 LOGV("? => ACTIVE (%d) on thread %p", mName, this);
3070 }
3071
3072 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3073 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003074 status = AudioSystem::startOutput(thread->id(),
3075 (AudioSystem::stream_type)mStreamType,
3076 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003077 thread->mLock.lock();
3078 }
3079 if (status == NO_ERROR) {
3080 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3081 playbackThread->addTrack_l(this);
3082 } else {
3083 mState = state;
3084 }
3085 } else {
3086 status = BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -07003087 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003088 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003089}
3090
Eric Laurenta553c252009-07-17 12:17:14 -07003091void AudioFlinger::PlaybackThread::Track::stop()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003092{
Eric Laurenta553c252009-07-17 12:17:14 -07003093 LOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3094 sp<ThreadBase> thread = mThread.promote();
3095 if (thread != 0) {
3096 Mutex::Autolock _l(thread->mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08003097 int state = mState;
Eric Laurenta553c252009-07-17 12:17:14 -07003098 if (mState > STOPPED) {
3099 mState = STOPPED;
3100 // If the track is not active (PAUSED and buffers full), flush buffers
3101 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3102 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3103 reset();
3104 }
Eric Laurent62443f52009-10-05 20:29:18 -07003105 LOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003106 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003107 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3108 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003109 AudioSystem::stopOutput(thread->id(),
3110 (AudioSystem::stream_type)mStreamType,
3111 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003112 thread->mLock.lock();
3113 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003114 }
3115}
3116
Eric Laurenta553c252009-07-17 12:17:14 -07003117void AudioFlinger::PlaybackThread::Track::pause()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003118{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003119 LOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurenta553c252009-07-17 12:17:14 -07003120 sp<ThreadBase> thread = mThread.promote();
3121 if (thread != 0) {
3122 Mutex::Autolock _l(thread->mLock);
3123 if (mState == ACTIVE || mState == RESUMING) {
3124 mState = PAUSING;
Eric Laurent62443f52009-10-05 20:29:18 -07003125 LOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurent49f02be2009-11-19 09:00:56 -08003126 if (!isOutputTrack()) {
3127 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003128 AudioSystem::stopOutput(thread->id(),
3129 (AudioSystem::stream_type)mStreamType,
3130 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003131 thread->mLock.lock();
3132 }
Eric Laurenta553c252009-07-17 12:17:14 -07003133 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003134 }
3135}
3136
Eric Laurenta553c252009-07-17 12:17:14 -07003137void AudioFlinger::PlaybackThread::Track::flush()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003138{
3139 LOGV("flush(%d)", mName);
Eric Laurenta553c252009-07-17 12:17:14 -07003140 sp<ThreadBase> thread = mThread.promote();
3141 if (thread != 0) {
3142 Mutex::Autolock _l(thread->mLock);
3143 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3144 return;
3145 }
3146 // No point remaining in PAUSED state after a flush => go to
3147 // STOPPED state
3148 mState = STOPPED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003149
Eric Laurenta553c252009-07-17 12:17:14 -07003150 mCblk->lock.lock();
3151 // NOTE: reset() will reset cblk->user and cblk->server with
3152 // the risk that at the same time, the AudioMixer is trying to read
3153 // data. In this case, getNextBuffer() would return a NULL pointer
3154 // as audio buffer => the AudioMixer code MUST always test that pointer
3155 // returned by getNextBuffer() is not NULL!
3156 reset();
3157 mCblk->lock.unlock();
3158 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003159}
3160
Eric Laurenta553c252009-07-17 12:17:14 -07003161void AudioFlinger::PlaybackThread::Track::reset()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003162{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003163 // Do not reset twice to avoid discarding data written just after a flush and before
3164 // the audioflinger thread detects the track is stopped.
3165 if (!mResetDone) {
3166 TrackBase::reset();
3167 // Force underrun condition to avoid false underrun callback until first data is
3168 // written to buffer
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003169 mCblk->flags |= CBLK_UNDERRUN_ON;
3170 mCblk->flags &= ~CBLK_FORCEREADY_MSK;
Eric Laurenta553c252009-07-17 12:17:14 -07003171 mFillingUpStatus = FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003172 mResetDone = true;
3173 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003174}
3175
Eric Laurenta553c252009-07-17 12:17:14 -07003176void AudioFlinger::PlaybackThread::Track::mute(bool muted)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003177{
3178 mMute = muted;
3179}
3180
Eric Laurenta553c252009-07-17 12:17:14 -07003181void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003182{
3183 mVolume[0] = left;
3184 mVolume[1] = right;
3185}
3186
Eric Laurent65b65452010-06-01 23:49:17 -07003187status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3188{
3189 status_t status = DEAD_OBJECT;
3190 sp<ThreadBase> thread = mThread.promote();
3191 if (thread != 0) {
3192 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3193 status = playbackThread->attachAuxEffect(this, EffectId);
3194 }
3195 return status;
3196}
3197
3198void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3199{
3200 mAuxEffectId = EffectId;
3201 mAuxBuffer = buffer;
3202}
3203
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003204// ----------------------------------------------------------------------------
3205
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003206// RecordTrack constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07003207AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3208 const wp<ThreadBase>& thread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003209 const sp<Client>& client,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003210 uint32_t sampleRate,
3211 int format,
3212 int channelCount,
3213 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07003214 uint32_t flags,
3215 int sessionId)
Eric Laurenta553c252009-07-17 12:17:14 -07003216 : TrackBase(thread, client, sampleRate, format,
Eric Laurent65b65452010-06-01 23:49:17 -07003217 channelCount, frameCount, flags, 0, sessionId),
Eric Laurenta553c252009-07-17 12:17:14 -07003218 mOverflow(false)
3219{
Eric Laurent8a77a992009-09-09 05:16:08 -07003220 if (mCblk != NULL) {
3221 LOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
3222 if (format == AudioSystem::PCM_16_BIT) {
3223 mCblk->frameSize = channelCount * sizeof(int16_t);
3224 } else if (format == AudioSystem::PCM_8_BIT) {
3225 mCblk->frameSize = channelCount * sizeof(int8_t);
3226 } else {
3227 mCblk->frameSize = sizeof(int8_t);
3228 }
3229 }
Eric Laurenta553c252009-07-17 12:17:14 -07003230}
3231
3232AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003233{
Eric Laurent49f02be2009-11-19 09:00:56 -08003234 sp<ThreadBase> thread = mThread.promote();
3235 if (thread != 0) {
3236 AudioSystem::releaseInput(thread->id());
3237 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003238}
3239
Eric Laurenta553c252009-07-17 12:17:14 -07003240status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003241{
3242 audio_track_cblk_t* cblk = this->cblk();
3243 uint32_t framesAvail;
3244 uint32_t framesReq = buffer->frameCount;
3245
3246 // Check if last stepServer failed, try to step now
3247 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3248 if (!step()) goto getNextBuffer_exit;
3249 LOGV("stepServer recovered");
3250 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3251 }
3252
3253 framesAvail = cblk->framesAvailable_l();
3254
3255 if (LIKELY(framesAvail)) {
3256 uint32_t s = cblk->server;
3257 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3258
3259 if (framesReq > framesAvail) {
3260 framesReq = framesAvail;
3261 }
3262 if (s + framesReq > bufferEnd) {
3263 framesReq = bufferEnd - s;
3264 }
3265
3266 buffer->raw = getBuffer(s, framesReq);
3267 if (buffer->raw == 0) goto getNextBuffer_exit;
3268
3269 buffer->frameCount = framesReq;
3270 return NO_ERROR;
3271 }
3272
3273getNextBuffer_exit:
3274 buffer->raw = 0;
3275 buffer->frameCount = 0;
3276 return NOT_ENOUGH_DATA;
3277}
3278
Eric Laurenta553c252009-07-17 12:17:14 -07003279status_t AudioFlinger::RecordThread::RecordTrack::start()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003280{
Eric Laurenta553c252009-07-17 12:17:14 -07003281 sp<ThreadBase> thread = mThread.promote();
3282 if (thread != 0) {
3283 RecordThread *recordThread = (RecordThread *)thread.get();
3284 return recordThread->start(this);
Eric Laurent49f02be2009-11-19 09:00:56 -08003285 } else {
3286 return BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -07003287 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003288}
3289
Eric Laurenta553c252009-07-17 12:17:14 -07003290void AudioFlinger::RecordThread::RecordTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003291{
Eric Laurenta553c252009-07-17 12:17:14 -07003292 sp<ThreadBase> thread = mThread.promote();
3293 if (thread != 0) {
3294 RecordThread *recordThread = (RecordThread *)thread.get();
3295 recordThread->stop(this);
3296 TrackBase::reset();
3297 // Force overerrun condition to avoid false overrun callback until first data is
3298 // read from buffer
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003299 mCblk->flags |= CBLK_UNDERRUN_ON;
Eric Laurenta553c252009-07-17 12:17:14 -07003300 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003301}
3302
Eric Laurent3fdb1262009-11-07 00:01:32 -08003303void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3304{
Eric Laurent65b65452010-06-01 23:49:17 -07003305 snprintf(buffer, size, " %05d %03u %03u %05d %04u %01d %05u %08x %08x\n",
Eric Laurent3fdb1262009-11-07 00:01:32 -08003306 (mClient == NULL) ? getpid() : mClient->pid(),
3307 mFormat,
Eric Laurentb0a01472010-05-14 05:45:46 -07003308 mCblk->channelCount,
Eric Laurent65b65452010-06-01 23:49:17 -07003309 mSessionId,
Eric Laurent3fdb1262009-11-07 00:01:32 -08003310 mFrameCount,
3311 mState,
3312 mCblk->sampleRate,
3313 mCblk->server,
3314 mCblk->user);
3315}
3316
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003317
3318// ----------------------------------------------------------------------------
3319
Eric Laurenta553c252009-07-17 12:17:14 -07003320AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3321 const wp<ThreadBase>& thread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003322 DuplicatingThread *sourceThread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003323 uint32_t sampleRate,
3324 int format,
3325 int channelCount,
3326 int frameCount)
Eric Laurent65b65452010-06-01 23:49:17 -07003327 : Track(thread, NULL, AudioSystem::NUM_STREAM_TYPES, sampleRate, format, channelCount, frameCount, NULL, 0),
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003328 mActive(false), mSourceThread(sourceThread)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003329{
Eric Laurenta553c252009-07-17 12:17:14 -07003330
3331 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
Eric Laurent6c30a712009-08-10 23:22:32 -07003332 if (mCblk != NULL) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003333 mCblk->flags |= CBLK_DIRECTION_OUT;
Eric Laurent6c30a712009-08-10 23:22:32 -07003334 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
3335 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
3336 mOutBuffer.frameCount = 0;
Eric Laurent6c30a712009-08-10 23:22:32 -07003337 playbackThread->mTracks.add(this);
Eric Laurentb0a01472010-05-14 05:45:46 -07003338 LOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, mCblk->frameCount %d, mCblk->sampleRate %d, mCblk->channelCount %d mBufferEnd %p",
3339 mCblk, mBuffer, mCblk->buffers, mCblk->frameCount, mCblk->sampleRate, mCblk->channelCount, mBufferEnd);
Eric Laurent6c30a712009-08-10 23:22:32 -07003340 } else {
3341 LOGW("Error creating output track on thread %p", playbackThread);
3342 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003343}
3344
Eric Laurenta553c252009-07-17 12:17:14 -07003345AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003346{
Eric Laurent6c30a712009-08-10 23:22:32 -07003347 clearBufferQueue();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003348}
3349
Eric Laurenta553c252009-07-17 12:17:14 -07003350status_t AudioFlinger::PlaybackThread::OutputTrack::start()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003351{
3352 status_t status = Track::start();
Eric Laurenta553c252009-07-17 12:17:14 -07003353 if (status != NO_ERROR) {
3354 return status;
3355 }
3356
3357 mActive = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003358 mRetryCount = 127;
3359 return status;
3360}
3361
Eric Laurenta553c252009-07-17 12:17:14 -07003362void AudioFlinger::PlaybackThread::OutputTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003363{
3364 Track::stop();
3365 clearBufferQueue();
3366 mOutBuffer.frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003367 mActive = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003368}
3369
Eric Laurenta553c252009-07-17 12:17:14 -07003370bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003371{
3372 Buffer *pInBuffer;
3373 Buffer inBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003374 uint32_t channelCount = mCblk->channelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003375 bool outputBufferFull = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003376 inBuffer.frameCount = frames;
3377 inBuffer.i16 = data;
Eric Laurenta553c252009-07-17 12:17:14 -07003378
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003379 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
Eric Laurenta553c252009-07-17 12:17:14 -07003380
Eric Laurent62443f52009-10-05 20:29:18 -07003381 if (!mActive && frames != 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003382 start();
3383 sp<ThreadBase> thread = mThread.promote();
3384 if (thread != 0) {
3385 MixerThread *mixerThread = (MixerThread *)thread.get();
3386 if (mCblk->frameCount > frames){
3387 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3388 uint32_t startFrames = (mCblk->frameCount - frames);
3389 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003390 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
Eric Laurenta553c252009-07-17 12:17:14 -07003391 pInBuffer->frameCount = startFrames;
3392 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003393 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
Eric Laurenta553c252009-07-17 12:17:14 -07003394 mBufferQueue.add(pInBuffer);
3395 } else {
3396 LOGW ("OutputTrack::write() %p no more buffers in queue", this);
3397 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003398 }
Eric Laurenta553c252009-07-17 12:17:14 -07003399 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003400 }
3401
Eric Laurenta553c252009-07-17 12:17:14 -07003402 while (waitTimeLeftMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003403 // First write pending buffers, then new data
3404 if (mBufferQueue.size()) {
3405 pInBuffer = mBufferQueue.itemAt(0);
3406 } else {
3407 pInBuffer = &inBuffer;
3408 }
Eric Laurenta553c252009-07-17 12:17:14 -07003409
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003410 if (pInBuffer->frameCount == 0) {
3411 break;
3412 }
Eric Laurenta553c252009-07-17 12:17:14 -07003413
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003414 if (mOutBuffer.frameCount == 0) {
3415 mOutBuffer.frameCount = pInBuffer->frameCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003416 nsecs_t startTime = systemTime();
3417 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003418 LOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Eric Laurenta553c252009-07-17 12:17:14 -07003419 outputBufferFull = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003420 break;
3421 }
Eric Laurenta553c252009-07-17 12:17:14 -07003422 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
Eric Laurenta553c252009-07-17 12:17:14 -07003423 if (waitTimeLeftMs >= waitTimeMs) {
3424 waitTimeLeftMs -= waitTimeMs;
3425 } else {
3426 waitTimeLeftMs = 0;
3427 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003428 }
Eric Laurenta553c252009-07-17 12:17:14 -07003429
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003430 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
Eric Laurentb0a01472010-05-14 05:45:46 -07003431 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003432 mCblk->stepUser(outFrames);
3433 pInBuffer->frameCount -= outFrames;
Eric Laurentb0a01472010-05-14 05:45:46 -07003434 pInBuffer->i16 += outFrames * channelCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003435 mOutBuffer.frameCount -= outFrames;
Eric Laurentb0a01472010-05-14 05:45:46 -07003436 mOutBuffer.i16 += outFrames * channelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003437
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003438 if (pInBuffer->frameCount == 0) {
3439 if (mBufferQueue.size()) {
3440 mBufferQueue.removeAt(0);
3441 delete [] pInBuffer->mBuffer;
3442 delete pInBuffer;
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003443 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 -08003444 } else {
3445 break;
3446 }
3447 }
3448 }
Eric Laurenta553c252009-07-17 12:17:14 -07003449
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003450 // If we could not write all frames, allocate a buffer and queue it for next time.
3451 if (inBuffer.frameCount) {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003452 sp<ThreadBase> thread = mThread.promote();
3453 if (thread != 0 && !thread->standby()) {
3454 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3455 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003456 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003457 pInBuffer->frameCount = inBuffer.frameCount;
3458 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003459 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003460 mBufferQueue.add(pInBuffer);
3461 LOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
3462 } else {
3463 LOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
3464 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003465 }
3466 }
Eric Laurenta553c252009-07-17 12:17:14 -07003467
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003468 // Calling write() with a 0 length buffer, means that no more data will be written:
Eric Laurenta553c252009-07-17 12:17:14 -07003469 // 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 -08003470 // by output mixer.
Eric Laurenta553c252009-07-17 12:17:14 -07003471 if (frames == 0 && mBufferQueue.size() == 0) {
3472 if (mCblk->user < mCblk->frameCount) {
3473 frames = mCblk->frameCount - mCblk->user;
3474 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003475 pInBuffer->mBuffer = new int16_t[frames * channelCount];
Eric Laurenta553c252009-07-17 12:17:14 -07003476 pInBuffer->frameCount = frames;
3477 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003478 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
Eric Laurenta553c252009-07-17 12:17:14 -07003479 mBufferQueue.add(pInBuffer);
Eric Laurent62443f52009-10-05 20:29:18 -07003480 } else if (mActive) {
Eric Laurenta553c252009-07-17 12:17:14 -07003481 stop();
3482 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003483 }
3484
Eric Laurenta553c252009-07-17 12:17:14 -07003485 return outputBufferFull;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003486}
3487
Eric Laurenta553c252009-07-17 12:17:14 -07003488status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003489{
3490 int active;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003491 status_t result;
3492 audio_track_cblk_t* cblk = mCblk;
3493 uint32_t framesReq = buffer->frameCount;
3494
Eric Laurenta553c252009-07-17 12:17:14 -07003495// LOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003496 buffer->frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003497
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003498 uint32_t framesAvail = cblk->framesAvailable();
3499
Eric Laurenta553c252009-07-17 12:17:14 -07003500
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003501 if (framesAvail == 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003502 Mutex::Autolock _l(cblk->lock);
3503 goto start_loop_here;
3504 while (framesAvail == 0) {
3505 active = mActive;
3506 if (UNLIKELY(!active)) {
3507 LOGV("Not active and NO_MORE_BUFFERS");
3508 return AudioTrack::NO_MORE_BUFFERS;
3509 }
3510 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3511 if (result != NO_ERROR) {
3512 return AudioTrack::NO_MORE_BUFFERS;
3513 }
3514 // read the server count again
3515 start_loop_here:
3516 framesAvail = cblk->framesAvailable_l();
3517 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003518 }
3519
Eric Laurenta553c252009-07-17 12:17:14 -07003520// if (framesAvail < framesReq) {
3521// return AudioTrack::NO_MORE_BUFFERS;
3522// }
3523
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003524 if (framesReq > framesAvail) {
3525 framesReq = framesAvail;
3526 }
3527
3528 uint32_t u = cblk->user;
3529 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
3530
3531 if (u + framesReq > bufferEnd) {
3532 framesReq = bufferEnd - u;
3533 }
3534
3535 buffer->frameCount = framesReq;
3536 buffer->raw = (void *)cblk->buffer(u);
3537 return NO_ERROR;
3538}
3539
3540
Eric Laurenta553c252009-07-17 12:17:14 -07003541void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003542{
3543 size_t size = mBufferQueue.size();
3544 Buffer *pBuffer;
Eric Laurenta553c252009-07-17 12:17:14 -07003545
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003546 for (size_t i = 0; i < size; i++) {
3547 pBuffer = mBufferQueue.itemAt(i);
3548 delete [] pBuffer->mBuffer;
3549 delete pBuffer;
3550 }
3551 mBufferQueue.clear();
3552}
3553
3554// ----------------------------------------------------------------------------
3555
3556AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
3557 : RefBase(),
3558 mAudioFlinger(audioFlinger),
Mathias Agopian6faf7892010-01-25 19:00:00 -08003559 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003560 mPid(pid)
3561{
3562 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
3563}
3564
Eric Laurentb9481d82009-09-17 05:12:56 -07003565// Client destructor must be called with AudioFlinger::mLock held
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003566AudioFlinger::Client::~Client()
3567{
Eric Laurentb9481d82009-09-17 05:12:56 -07003568 mAudioFlinger->removeClient_l(mPid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003569}
3570
3571const sp<MemoryDealer>& AudioFlinger::Client::heap() const
3572{
3573 return mMemoryDealer;
3574}
3575
3576// ----------------------------------------------------------------------------
3577
Eric Laurent4f0f17d2010-05-12 02:05:53 -07003578AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
3579 const sp<IAudioFlingerClient>& client,
3580 pid_t pid)
3581 : mAudioFlinger(audioFlinger), mPid(pid), mClient(client)
3582{
3583}
3584
3585AudioFlinger::NotificationClient::~NotificationClient()
3586{
3587 mClient.clear();
3588}
3589
3590void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
3591{
3592 sp<NotificationClient> keep(this);
3593 {
3594 mAudioFlinger->removeNotificationClient(mPid);
3595 }
3596}
3597
3598// ----------------------------------------------------------------------------
3599
Eric Laurenta553c252009-07-17 12:17:14 -07003600AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003601 : BnAudioTrack(),
3602 mTrack(track)
3603{
3604}
3605
3606AudioFlinger::TrackHandle::~TrackHandle() {
3607 // just stop the track on deletion, associated resources
3608 // will be freed from the main thread once all pending buffers have
3609 // been played. Unless it's not in the active track list, in which
3610 // case we free everything now...
3611 mTrack->destroy();
3612}
3613
3614status_t AudioFlinger::TrackHandle::start() {
3615 return mTrack->start();
3616}
3617
3618void AudioFlinger::TrackHandle::stop() {
3619 mTrack->stop();
3620}
3621
3622void AudioFlinger::TrackHandle::flush() {
3623 mTrack->flush();
3624}
3625
3626void AudioFlinger::TrackHandle::mute(bool e) {
3627 mTrack->mute(e);
3628}
3629
3630void AudioFlinger::TrackHandle::pause() {
3631 mTrack->pause();
3632}
3633
3634void AudioFlinger::TrackHandle::setVolume(float left, float right) {
3635 mTrack->setVolume(left, right);
3636}
3637
3638sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
3639 return mTrack->getCblk();
3640}
3641
Eric Laurent65b65452010-06-01 23:49:17 -07003642status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
3643{
3644 return mTrack->attachAuxEffect(EffectId);
3645}
3646
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003647status_t AudioFlinger::TrackHandle::onTransact(
3648 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3649{
3650 return BnAudioTrack::onTransact(code, data, reply, flags);
3651}
3652
3653// ----------------------------------------------------------------------------
3654
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003655sp<IAudioRecord> AudioFlinger::openRecord(
3656 pid_t pid,
Eric Laurentddb78e72009-07-28 08:44:33 -07003657 int input,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003658 uint32_t sampleRate,
3659 int format,
3660 int channelCount,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003661 int frameCount,
3662 uint32_t flags,
Eric Laurent65b65452010-06-01 23:49:17 -07003663 int *sessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003664 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003665{
Eric Laurenta553c252009-07-17 12:17:14 -07003666 sp<RecordThread::RecordTrack> recordTrack;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003667 sp<RecordHandle> recordHandle;
3668 sp<Client> client;
3669 wp<Client> wclient;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003670 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07003671 RecordThread *thread;
3672 size_t inFrameCount;
Eric Laurent65b65452010-06-01 23:49:17 -07003673 int lSessionId;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003674
3675 // check calling permissions
3676 if (!recordingAllowed()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003677 lStatus = PERMISSION_DENIED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003678 goto Exit;
3679 }
3680
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003681 // add client to list
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003682 { // scope for mLock
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003683 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07003684 thread = checkRecordThread_l(input);
3685 if (thread == NULL) {
3686 lStatus = BAD_VALUE;
3687 goto Exit;
3688 }
3689
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003690 wclient = mClients.valueFor(pid);
3691 if (wclient != NULL) {
3692 client = wclient.promote();
3693 } else {
3694 client = new Client(this, pid);
3695 mClients.add(pid, client);
3696 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003697
Eric Laurent65b65452010-06-01 23:49:17 -07003698 // If no audio session id is provided, create one here
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003699 if (sessionId != NULL && *sessionId != AudioSystem::SESSION_OUTPUT_MIX) {
Eric Laurent65b65452010-06-01 23:49:17 -07003700 lSessionId = *sessionId;
3701 } else {
3702 lSessionId = nextUniqueId();
3703 if (sessionId != NULL) {
3704 *sessionId = lSessionId;
3705 }
3706 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003707 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurenta553c252009-07-17 12:17:14 -07003708 recordTrack = new RecordThread::RecordTrack(thread, client, sampleRate,
Eric Laurent65b65452010-06-01 23:49:17 -07003709 format, channelCount, frameCount, flags, lSessionId);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003710 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003711 if (recordTrack->getCblk() == NULL) {
Eric Laurentb9481d82009-09-17 05:12:56 -07003712 // remove local strong reference to Client before deleting the RecordTrack so that the Client
3713 // destructor is called by the TrackBase destructor with mLock held
3714 client.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003715 recordTrack.clear();
3716 lStatus = NO_MEMORY;
3717 goto Exit;
3718 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003719
3720 // return to handle to client
3721 recordHandle = new RecordHandle(recordTrack);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003722 lStatus = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003723
3724Exit:
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003725 if (status) {
3726 *status = lStatus;
3727 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003728 return recordHandle;
3729}
3730
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003731// ----------------------------------------------------------------------------
3732
Eric Laurenta553c252009-07-17 12:17:14 -07003733AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003734 : BnAudioRecord(),
3735 mRecordTrack(recordTrack)
3736{
3737}
3738
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003739AudioFlinger::RecordHandle::~RecordHandle() {
3740 stop();
3741}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003742
3743status_t AudioFlinger::RecordHandle::start() {
3744 LOGV("RecordHandle::start()");
3745 return mRecordTrack->start();
3746}
3747
3748void AudioFlinger::RecordHandle::stop() {
3749 LOGV("RecordHandle::stop()");
3750 mRecordTrack->stop();
3751}
3752
3753sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
3754 return mRecordTrack->getCblk();
3755}
3756
3757status_t AudioFlinger::RecordHandle::onTransact(
3758 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3759{
3760 return BnAudioRecord::onTransact(code, data, reply, flags);
3761}
3762
3763// ----------------------------------------------------------------------------
3764
Eric Laurent49f02be2009-11-19 09:00:56 -08003765AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger, AudioStreamIn *input, uint32_t sampleRate, uint32_t channels, int id) :
3766 ThreadBase(audioFlinger, id),
Eric Laurenta553c252009-07-17 12:17:14 -07003767 mInput(input), mResampler(0), mRsmpOutBuffer(0), mRsmpInBuffer(0)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003768{
Eric Laurenta553c252009-07-17 12:17:14 -07003769 mReqChannelCount = AudioSystem::popCount(channels);
3770 mReqSampleRate = sampleRate;
3771 readInputParameters();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003772}
3773
Eric Laurenta553c252009-07-17 12:17:14 -07003774
3775AudioFlinger::RecordThread::~RecordThread()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003776{
Eric Laurenta553c252009-07-17 12:17:14 -07003777 delete[] mRsmpInBuffer;
3778 if (mResampler != 0) {
3779 delete mResampler;
3780 delete[] mRsmpOutBuffer;
3781 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003782}
3783
Eric Laurenta553c252009-07-17 12:17:14 -07003784void AudioFlinger::RecordThread::onFirstRef()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003785{
Eric Laurenta553c252009-07-17 12:17:14 -07003786 const size_t SIZE = 256;
3787 char buffer[SIZE];
3788
3789 snprintf(buffer, SIZE, "Record Thread %p", this);
3790
3791 run(buffer, PRIORITY_URGENT_AUDIO);
3792}
Eric Laurent49f02be2009-11-19 09:00:56 -08003793
Eric Laurenta553c252009-07-17 12:17:14 -07003794bool AudioFlinger::RecordThread::threadLoop()
3795{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003796 AudioBufferProvider::Buffer buffer;
Eric Laurenta553c252009-07-17 12:17:14 -07003797 sp<RecordTrack> activeTrack;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003798
Eric Laurent4712baa2010-09-30 16:12:31 -07003799 nsecs_t lastWarning = 0;
3800
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003801 // start recording
3802 while (!exitPending()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003803
Eric Laurenta553c252009-07-17 12:17:14 -07003804 processConfigEvents();
3805
3806 { // scope for mLock
3807 Mutex::Autolock _l(mLock);
3808 checkForNewParameters_l();
3809 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
3810 if (!mStandby) {
3811 mInput->standby();
3812 mStandby = true;
3813 }
3814
3815 if (exitPending()) break;
3816
3817 LOGV("RecordThread: loop stopping");
3818 // go to sleep
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003819 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07003820 LOGV("RecordThread: loop starting");
3821 continue;
3822 }
3823 if (mActiveTrack != 0) {
3824 if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08003825 if (!mStandby) {
3826 mInput->standby();
3827 mStandby = true;
3828 }
Eric Laurenta553c252009-07-17 12:17:14 -07003829 mActiveTrack.clear();
3830 mStartStopCond.broadcast();
3831 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
Eric Laurenta553c252009-07-17 12:17:14 -07003832 if (mReqChannelCount != mActiveTrack->channelCount()) {
3833 mActiveTrack.clear();
Eric Laurent9cc489a22009-12-05 05:20:01 -08003834 mStartStopCond.broadcast();
3835 } else if (mBytesRead != 0) {
3836 // record start succeeds only if first read from audio input
3837 // succeeds
3838 if (mBytesRead > 0) {
3839 mActiveTrack->mState = TrackBase::ACTIVE;
3840 } else {
3841 mActiveTrack.clear();
3842 }
3843 mStartStopCond.broadcast();
Eric Laurenta553c252009-07-17 12:17:14 -07003844 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08003845 mStandby = false;
Eric Laurenta553c252009-07-17 12:17:14 -07003846 }
Eric Laurenta553c252009-07-17 12:17:14 -07003847 }
3848 }
3849
3850 if (mActiveTrack != 0) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08003851 if (mActiveTrack->mState != TrackBase::ACTIVE &&
3852 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent49f02be2009-11-19 09:00:56 -08003853 usleep(5000);
3854 continue;
3855 }
Eric Laurenta553c252009-07-17 12:17:14 -07003856 buffer.frameCount = mFrameCount;
3857 if (LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
3858 size_t framesOut = buffer.frameCount;
3859 if (mResampler == 0) {
3860 // no resampling
3861 while (framesOut) {
3862 size_t framesIn = mFrameCount - mRsmpInIndex;
3863 if (framesIn) {
3864 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
3865 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
3866 if (framesIn > framesOut)
3867 framesIn = framesOut;
3868 mRsmpInIndex += framesIn;
3869 framesOut -= framesIn;
Eric Laurentb0a01472010-05-14 05:45:46 -07003870 if ((int)mChannelCount == mReqChannelCount ||
Eric Laurenta553c252009-07-17 12:17:14 -07003871 mFormat != AudioSystem::PCM_16_BIT) {
3872 memcpy(dst, src, framesIn * mFrameSize);
3873 } else {
3874 int16_t *src16 = (int16_t *)src;
3875 int16_t *dst16 = (int16_t *)dst;
3876 if (mChannelCount == 1) {
3877 while (framesIn--) {
3878 *dst16++ = *src16;
3879 *dst16++ = *src16++;
3880 }
3881 } else {
3882 while (framesIn--) {
3883 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
3884 src16 += 2;
3885 }
3886 }
3887 }
3888 }
3889 if (framesOut && mFrameCount == mRsmpInIndex) {
Eric Laurenta553c252009-07-17 12:17:14 -07003890 if (framesOut == mFrameCount &&
Eric Laurentb0a01472010-05-14 05:45:46 -07003891 ((int)mChannelCount == mReqChannelCount || mFormat != AudioSystem::PCM_16_BIT)) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08003892 mBytesRead = mInput->read(buffer.raw, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07003893 framesOut = 0;
3894 } else {
Eric Laurent9cc489a22009-12-05 05:20:01 -08003895 mBytesRead = mInput->read(mRsmpInBuffer, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07003896 mRsmpInIndex = 0;
3897 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08003898 if (mBytesRead < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003899 LOGE("Error reading audio input");
Eric Laurent9cc489a22009-12-05 05:20:01 -08003900 if (mActiveTrack->mState == TrackBase::ACTIVE) {
Eric Laurentba8811f2010-03-02 18:38:06 -08003901 // Force input into standby so that it tries to
3902 // recover at next read attempt
3903 mInput->standby();
3904 usleep(5000);
Eric Laurent9cc489a22009-12-05 05:20:01 -08003905 }
Eric Laurenta553c252009-07-17 12:17:14 -07003906 mRsmpInIndex = mFrameCount;
3907 framesOut = 0;
3908 buffer.frameCount = 0;
3909 }
3910 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003911 }
3912 } else {
Eric Laurenta553c252009-07-17 12:17:14 -07003913 // resampling
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003914
Eric Laurenta553c252009-07-17 12:17:14 -07003915 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
3916 // alter output frame count as if we were expecting stereo samples
3917 if (mChannelCount == 1 && mReqChannelCount == 1) {
3918 framesOut >>= 1;
3919 }
3920 mResampler->resample(mRsmpOutBuffer, framesOut, this);
3921 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
3922 // are 32 bit aligned which should be always true.
3923 if (mChannelCount == 2 && mReqChannelCount == 1) {
3924 AudioMixer::ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
3925 // the resampler always outputs stereo samples: do post stereo to mono conversion
3926 int16_t *src = (int16_t *)mRsmpOutBuffer;
3927 int16_t *dst = buffer.i16;
3928 while (framesOut--) {
3929 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
3930 src += 2;
3931 }
3932 } else {
3933 AudioMixer::ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
3934 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003935
Eric Laurenta553c252009-07-17 12:17:14 -07003936 }
3937 mActiveTrack->releaseBuffer(&buffer);
3938 mActiveTrack->overflow();
3939 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003940 // client isn't retrieving buffers fast enough
3941 else {
Eric Laurent4712baa2010-09-30 16:12:31 -07003942 if (!mActiveTrack->setOverflow()) {
3943 nsecs_t now = systemTime();
3944 if ((now - lastWarning) > kWarningThrottle) {
3945 LOGW("RecordThread: buffer overflow");
3946 lastWarning = now;
3947 }
3948 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003949 // Release the processor for a while before asking for a new buffer.
3950 // This will give the application more chance to read from the buffer and
3951 // clear the overflow.
3952 usleep(5000);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003953 }
3954 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003955 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003956
Eric Laurenta553c252009-07-17 12:17:14 -07003957 if (!mStandby) {
3958 mInput->standby();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003959 }
Eric Laurenta553c252009-07-17 12:17:14 -07003960 mActiveTrack.clear();
3961
Eric Laurent49f02be2009-11-19 09:00:56 -08003962 mStartStopCond.broadcast();
3963
Eric Laurenta553c252009-07-17 12:17:14 -07003964 LOGV("RecordThread %p exiting", this);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003965 return false;
3966}
3967
Eric Laurenta553c252009-07-17 12:17:14 -07003968status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003969{
Eric Laurenta553c252009-07-17 12:17:14 -07003970 LOGV("RecordThread::start");
Eric Laurent49f02be2009-11-19 09:00:56 -08003971 sp <ThreadBase> strongMe = this;
3972 status_t status = NO_ERROR;
3973 {
3974 AutoMutex lock(&mLock);
3975 if (mActiveTrack != 0) {
3976 if (recordTrack != mActiveTrack.get()) {
3977 status = -EBUSY;
3978 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08003979 mActiveTrack->mState = TrackBase::ACTIVE;
Eric Laurent49f02be2009-11-19 09:00:56 -08003980 }
3981 return status;
3982 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003983
Eric Laurent49f02be2009-11-19 09:00:56 -08003984 recordTrack->mState = TrackBase::IDLE;
3985 mActiveTrack = recordTrack;
3986 mLock.unlock();
3987 status_t status = AudioSystem::startInput(mId);
3988 mLock.lock();
3989 if (status != NO_ERROR) {
3990 mActiveTrack.clear();
3991 return status;
3992 }
3993 mActiveTrack->mState = TrackBase::RESUMING;
Eric Laurent9cc489a22009-12-05 05:20:01 -08003994 mRsmpInIndex = mFrameCount;
3995 mBytesRead = 0;
Eric Laurent49f02be2009-11-19 09:00:56 -08003996 // signal thread to start
3997 LOGV("Signal record thread");
3998 mWaitWorkCV.signal();
3999 // do not wait for mStartStopCond if exiting
4000 if (mExiting) {
4001 mActiveTrack.clear();
4002 status = INVALID_OPERATION;
4003 goto startError;
4004 }
4005 mStartStopCond.wait(mLock);
4006 if (mActiveTrack == 0) {
4007 LOGV("Record failed to start");
4008 status = BAD_VALUE;
4009 goto startError;
4010 }
Eric Laurenta553c252009-07-17 12:17:14 -07004011 LOGV("Record started OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08004012 return status;
Eric Laurenta553c252009-07-17 12:17:14 -07004013 }
Eric Laurent49f02be2009-11-19 09:00:56 -08004014startError:
4015 AudioSystem::stopInput(mId);
4016 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004017}
4018
Eric Laurenta553c252009-07-17 12:17:14 -07004019void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
4020 LOGV("RecordThread::stop");
Eric Laurent49f02be2009-11-19 09:00:56 -08004021 sp <ThreadBase> strongMe = this;
4022 {
4023 AutoMutex lock(&mLock);
4024 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4025 mActiveTrack->mState = TrackBase::PAUSING;
4026 // do not wait for mStartStopCond if exiting
4027 if (mExiting) {
4028 return;
4029 }
4030 mStartStopCond.wait(mLock);
4031 // if we have been restarted, recordTrack == mActiveTrack.get() here
4032 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4033 mLock.unlock();
4034 AudioSystem::stopInput(mId);
4035 mLock.lock();
Eric Laurent9cc489a22009-12-05 05:20:01 -08004036 LOGV("Record stopped OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08004037 }
4038 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004039 }
4040}
4041
Eric Laurenta553c252009-07-17 12:17:14 -07004042status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004043{
4044 const size_t SIZE = 256;
4045 char buffer[SIZE];
4046 String8 result;
4047 pid_t pid = 0;
4048
Eric Laurent3fdb1262009-11-07 00:01:32 -08004049 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4050 result.append(buffer);
4051
4052 if (mActiveTrack != 0) {
4053 result.append("Active Track:\n");
Eric Laurent65b65452010-06-01 23:49:17 -07004054 result.append(" Clien Fmt Chn Session Buf S SRate Serv User\n");
Eric Laurent3fdb1262009-11-07 00:01:32 -08004055 mActiveTrack->dump(buffer, SIZE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004056 result.append(buffer);
Eric Laurent3fdb1262009-11-07 00:01:32 -08004057
4058 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4059 result.append(buffer);
4060 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4061 result.append(buffer);
4062 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != 0));
4063 result.append(buffer);
4064 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4065 result.append(buffer);
4066 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4067 result.append(buffer);
4068
4069
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004070 } else {
4071 result.append("No record client\n");
4072 }
4073 write(fd, result.string(), result.size());
Eric Laurent3fdb1262009-11-07 00:01:32 -08004074
4075 dumpBase(fd, args);
4076
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004077 return NO_ERROR;
4078}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004079
Eric Laurenta553c252009-07-17 12:17:14 -07004080status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4081{
4082 size_t framesReq = buffer->frameCount;
4083 size_t framesReady = mFrameCount - mRsmpInIndex;
4084 int channelCount;
4085
4086 if (framesReady == 0) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08004087 mBytesRead = mInput->read(mRsmpInBuffer, mInputBytes);
4088 if (mBytesRead < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07004089 LOGE("RecordThread::getNextBuffer() Error reading audio input");
Eric Laurent9cc489a22009-12-05 05:20:01 -08004090 if (mActiveTrack->mState == TrackBase::ACTIVE) {
Eric Laurentba8811f2010-03-02 18:38:06 -08004091 // Force input into standby so that it tries to
4092 // recover at next read attempt
4093 mInput->standby();
4094 usleep(5000);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004095 }
Eric Laurenta553c252009-07-17 12:17:14 -07004096 buffer->raw = 0;
4097 buffer->frameCount = 0;
4098 return NOT_ENOUGH_DATA;
4099 }
4100 mRsmpInIndex = 0;
4101 framesReady = mFrameCount;
4102 }
4103
4104 if (framesReq > framesReady) {
4105 framesReq = framesReady;
4106 }
4107
4108 if (mChannelCount == 1 && mReqChannelCount == 2) {
4109 channelCount = 1;
4110 } else {
4111 channelCount = 2;
4112 }
4113 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4114 buffer->frameCount = framesReq;
4115 return NO_ERROR;
4116}
4117
4118void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4119{
4120 mRsmpInIndex += buffer->frameCount;
4121 buffer->frameCount = 0;
4122}
4123
4124bool AudioFlinger::RecordThread::checkForNewParameters_l()
4125{
4126 bool reconfig = false;
4127
Eric Laurent8fce46a2009-08-04 09:45:33 -07004128 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07004129 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07004130 String8 keyValuePair = mNewParameters[0];
4131 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07004132 int value;
4133 int reqFormat = mFormat;
4134 int reqSamplingRate = mReqSampleRate;
4135 int reqChannelCount = mReqChannelCount;
Eric Laurent8fce46a2009-08-04 09:45:33 -07004136
Eric Laurenta553c252009-07-17 12:17:14 -07004137 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4138 reqSamplingRate = value;
4139 reconfig = true;
4140 }
4141 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
4142 reqFormat = value;
4143 reconfig = true;
4144 }
4145 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
4146 reqChannelCount = AudioSystem::popCount(value);
4147 reconfig = true;
4148 }
4149 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4150 // do not accept frame count changes if tracks are open as the track buffer
4151 // size depends on frame count and correct behavior would not be garantied
4152 // if frame count is changed after track creation
4153 if (mActiveTrack != 0) {
4154 status = INVALID_OPERATION;
4155 } else {
4156 reconfig = true;
4157 }
4158 }
4159 if (status == NO_ERROR) {
Eric Laurent8fce46a2009-08-04 09:45:33 -07004160 status = mInput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07004161 if (status == INVALID_OPERATION) {
4162 mInput->standby();
Eric Laurent8fce46a2009-08-04 09:45:33 -07004163 status = mInput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07004164 }
4165 if (reconfig) {
4166 if (status == BAD_VALUE &&
4167 reqFormat == mInput->format() && reqFormat == AudioSystem::PCM_16_BIT &&
4168 ((int)mInput->sampleRate() <= 2 * reqSamplingRate) &&
4169 (AudioSystem::popCount(mInput->channels()) < 3) && (reqChannelCount < 3)) {
4170 status = NO_ERROR;
4171 }
4172 if (status == NO_ERROR) {
4173 readInputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07004174 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07004175 }
4176 }
4177 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08004178
4179 mNewParameters.removeAt(0);
4180
Eric Laurenta553c252009-07-17 12:17:14 -07004181 mParamStatus = status;
4182 mParamCond.signal();
Eric Laurent8fce46a2009-08-04 09:45:33 -07004183 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07004184 }
4185 return reconfig;
4186}
4187
4188String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4189{
4190 return mInput->getParameters(keys);
4191}
4192
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004193void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
Eric Laurenta553c252009-07-17 12:17:14 -07004194 AudioSystem::OutputDescriptor desc;
4195 void *param2 = 0;
4196
4197 switch (event) {
4198 case AudioSystem::INPUT_OPENED:
4199 case AudioSystem::INPUT_CONFIG_CHANGED:
Eric Laurentb0a01472010-05-14 05:45:46 -07004200 desc.channels = mChannels;
Eric Laurenta553c252009-07-17 12:17:14 -07004201 desc.samplingRate = mSampleRate;
4202 desc.format = mFormat;
4203 desc.frameCount = mFrameCount;
4204 desc.latency = 0;
4205 param2 = &desc;
4206 break;
4207
4208 case AudioSystem::INPUT_CLOSED:
4209 default:
4210 break;
4211 }
Eric Laurent49f02be2009-11-19 09:00:56 -08004212 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurenta553c252009-07-17 12:17:14 -07004213}
4214
4215void AudioFlinger::RecordThread::readInputParameters()
4216{
4217 if (mRsmpInBuffer) delete mRsmpInBuffer;
4218 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
4219 if (mResampler) delete mResampler;
4220 mResampler = 0;
4221
4222 mSampleRate = mInput->sampleRate();
Eric Laurentb0a01472010-05-14 05:45:46 -07004223 mChannels = mInput->channels();
4224 mChannelCount = (uint16_t)AudioSystem::popCount(mChannels);
Eric Laurenta553c252009-07-17 12:17:14 -07004225 mFormat = mInput->format();
Eric Laurentb0a01472010-05-14 05:45:46 -07004226 mFrameSize = (uint16_t)mInput->frameSize();
Eric Laurenta553c252009-07-17 12:17:14 -07004227 mInputBytes = mInput->bufferSize();
4228 mFrameCount = mInputBytes / mFrameSize;
4229 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4230
4231 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4232 {
4233 int channelCount;
4234 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4235 // stereo to mono post process as the resampler always outputs stereo.
4236 if (mChannelCount == 1 && mReqChannelCount == 2) {
4237 channelCount = 1;
4238 } else {
4239 channelCount = 2;
4240 }
4241 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4242 mResampler->setSampleRate(mSampleRate);
4243 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4244 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4245
4246 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4247 if (mChannelCount == 1 && mReqChannelCount == 1) {
4248 mFrameCount >>= 1;
4249 }
4250
4251 }
4252 mRsmpInIndex = mFrameCount;
4253}
4254
Eric Laurent47d0a922010-02-26 02:47:27 -08004255unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4256{
4257 return mInput->getInputFramesLost();
4258}
4259
Eric Laurenta553c252009-07-17 12:17:14 -07004260// ----------------------------------------------------------------------------
4261
Eric Laurentddb78e72009-07-28 08:44:33 -07004262int AudioFlinger::openOutput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07004263 uint32_t *pSamplingRate,
4264 uint32_t *pFormat,
4265 uint32_t *pChannels,
4266 uint32_t *pLatencyMs,
4267 uint32_t flags)
4268{
4269 status_t status;
4270 PlaybackThread *thread = NULL;
4271 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4272 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4273 uint32_t format = pFormat ? *pFormat : 0;
4274 uint32_t channels = pChannels ? *pChannels : 0;
4275 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
4276
4277 LOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
4278 pDevices ? *pDevices : 0,
4279 samplingRate,
4280 format,
4281 channels,
4282 flags);
4283
4284 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004285 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004286 }
4287 Mutex::Autolock _l(mLock);
4288
4289 AudioStreamOut *output = mAudioHardware->openOutputStream(*pDevices,
4290 (int *)&format,
4291 &channels,
4292 &samplingRate,
4293 &status);
4294 LOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
4295 output,
4296 samplingRate,
4297 format,
4298 channels,
4299 status);
4300
4301 mHardwareStatus = AUDIO_HW_IDLE;
4302 if (output != 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07004303 int id = nextUniqueId();
Eric Laurenta553c252009-07-17 12:17:14 -07004304 if ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) ||
4305 (format != AudioSystem::PCM_16_BIT) ||
4306 (channels != AudioSystem::CHANNEL_OUT_STEREO)) {
Eric Laurent65b65452010-06-01 23:49:17 -07004307 thread = new DirectOutputThread(this, output, id, *pDevices);
4308 LOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004309 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07004310 thread = new MixerThread(this, output, id, *pDevices);
4311 LOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Glenn Kasten871c16c2010-03-05 12:18:01 -08004312
4313#ifdef LVMX
4314 unsigned bitsPerSample =
4315 (format == AudioSystem::PCM_16_BIT) ? 16 :
4316 ((format == AudioSystem::PCM_8_BIT) ? 8 : 0);
4317 unsigned channelCount = (channels == AudioSystem::CHANNEL_OUT_STEREO) ? 2 : 1;
4318 int audioOutputType = LifeVibes::threadIdToAudioOutputType(thread->id());
4319
4320 LifeVibes::init_aot(audioOutputType, samplingRate, bitsPerSample, channelCount);
4321 LifeVibes::setDevice(audioOutputType, *pDevices);
4322#endif
4323
Eric Laurenta553c252009-07-17 12:17:14 -07004324 }
Eric Laurent65b65452010-06-01 23:49:17 -07004325 mPlaybackThreads.add(id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004326
4327 if (pSamplingRate) *pSamplingRate = samplingRate;
4328 if (pFormat) *pFormat = format;
4329 if (pChannels) *pChannels = channels;
4330 if (pLatencyMs) *pLatencyMs = thread->latency();
Eric Laurent9cc489a22009-12-05 05:20:01 -08004331
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004332 // notify client processes of the new output creation
4333 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004334 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004335 }
4336
Eric Laurent9cc489a22009-12-05 05:20:01 -08004337 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004338}
4339
Eric Laurentddb78e72009-07-28 08:44:33 -07004340int AudioFlinger::openDuplicateOutput(int output1, int output2)
Eric Laurenta553c252009-07-17 12:17:14 -07004341{
4342 Mutex::Autolock _l(mLock);
Eric Laurentddb78e72009-07-28 08:44:33 -07004343 MixerThread *thread1 = checkMixerThread_l(output1);
4344 MixerThread *thread2 = checkMixerThread_l(output2);
Eric Laurenta553c252009-07-17 12:17:14 -07004345
Eric Laurentddb78e72009-07-28 08:44:33 -07004346 if (thread1 == NULL || thread2 == NULL) {
4347 LOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
4348 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004349 }
4350
Eric Laurent65b65452010-06-01 23:49:17 -07004351 int id = nextUniqueId();
4352 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
Eric Laurentddb78e72009-07-28 08:44:33 -07004353 thread->addOutputTrack(thread2);
Eric Laurent65b65452010-06-01 23:49:17 -07004354 mPlaybackThreads.add(id, thread);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004355 // notify client processes of the new output creation
4356 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004357 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004358}
4359
Eric Laurentddb78e72009-07-28 08:44:33 -07004360status_t AudioFlinger::closeOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004361{
Eric Laurent49018a52009-08-04 08:37:05 -07004362 // keep strong reference on the playback thread so that
4363 // it is not destroyed while exit() is executed
4364 sp <PlaybackThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07004365 {
4366 Mutex::Autolock _l(mLock);
4367 thread = checkPlaybackThread_l(output);
4368 if (thread == NULL) {
4369 return BAD_VALUE;
4370 }
4371
Eric Laurentddb78e72009-07-28 08:44:33 -07004372 LOGV("closeOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004373
4374 if (thread->type() == PlaybackThread::MIXER) {
4375 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004376 if (mPlaybackThreads.valueAt(i)->type() == PlaybackThread::DUPLICATING) {
4377 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Eric Laurent49018a52009-08-04 08:37:05 -07004378 dupThread->removeOutputTrack((MixerThread *)thread.get());
Eric Laurenta553c252009-07-17 12:17:14 -07004379 }
4380 }
4381 }
Eric Laurent296a0ec2009-09-15 07:10:12 -07004382 void *param2 = 0;
Eric Laurent49f02be2009-11-19 09:00:56 -08004383 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
Eric Laurentddb78e72009-07-28 08:44:33 -07004384 mPlaybackThreads.removeItem(output);
Eric Laurenta553c252009-07-17 12:17:14 -07004385 }
4386 thread->exit();
4387
Eric Laurent49018a52009-08-04 08:37:05 -07004388 if (thread->type() != PlaybackThread::DUPLICATING) {
4389 mAudioHardware->closeOutputStream(thread->getOutput());
4390 }
Eric Laurenta553c252009-07-17 12:17:14 -07004391 return NO_ERROR;
4392}
4393
Eric Laurentddb78e72009-07-28 08:44:33 -07004394status_t AudioFlinger::suspendOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004395{
4396 Mutex::Autolock _l(mLock);
4397 PlaybackThread *thread = checkPlaybackThread_l(output);
4398
4399 if (thread == NULL) {
4400 return BAD_VALUE;
4401 }
4402
Eric Laurentddb78e72009-07-28 08:44:33 -07004403 LOGV("suspendOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004404 thread->suspend();
4405
4406 return NO_ERROR;
4407}
4408
Eric Laurentddb78e72009-07-28 08:44:33 -07004409status_t AudioFlinger::restoreOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004410{
4411 Mutex::Autolock _l(mLock);
4412 PlaybackThread *thread = checkPlaybackThread_l(output);
4413
4414 if (thread == NULL) {
4415 return BAD_VALUE;
4416 }
4417
Eric Laurentddb78e72009-07-28 08:44:33 -07004418 LOGV("restoreOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004419
4420 thread->restore();
4421
4422 return NO_ERROR;
4423}
4424
Eric Laurentddb78e72009-07-28 08:44:33 -07004425int AudioFlinger::openInput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07004426 uint32_t *pSamplingRate,
4427 uint32_t *pFormat,
4428 uint32_t *pChannels,
4429 uint32_t acoustics)
4430{
4431 status_t status;
4432 RecordThread *thread = NULL;
4433 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4434 uint32_t format = pFormat ? *pFormat : 0;
4435 uint32_t channels = pChannels ? *pChannels : 0;
4436 uint32_t reqSamplingRate = samplingRate;
4437 uint32_t reqFormat = format;
4438 uint32_t reqChannels = channels;
4439
4440 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004441 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004442 }
4443 Mutex::Autolock _l(mLock);
4444
4445 AudioStreamIn *input = mAudioHardware->openInputStream(*pDevices,
4446 (int *)&format,
4447 &channels,
4448 &samplingRate,
4449 &status,
4450 (AudioSystem::audio_in_acoustics)acoustics);
4451 LOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
4452 input,
4453 samplingRate,
4454 format,
4455 channels,
4456 acoustics,
4457 status);
4458
4459 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
4460 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
4461 // or stereo to mono conversions on 16 bit PCM inputs.
4462 if (input == 0 && status == BAD_VALUE &&
4463 reqFormat == format && format == AudioSystem::PCM_16_BIT &&
4464 (samplingRate <= 2 * reqSamplingRate) &&
4465 (AudioSystem::popCount(channels) < 3) && (AudioSystem::popCount(reqChannels) < 3)) {
4466 LOGV("openInput() reopening with proposed sampling rate and channels");
4467 input = mAudioHardware->openInputStream(*pDevices,
4468 (int *)&format,
4469 &channels,
4470 &samplingRate,
4471 &status,
4472 (AudioSystem::audio_in_acoustics)acoustics);
4473 }
4474
4475 if (input != 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07004476 int id = nextUniqueId();
Eric Laurenta553c252009-07-17 12:17:14 -07004477 // Start record thread
Eric Laurent65b65452010-06-01 23:49:17 -07004478 thread = new RecordThread(this, input, reqSamplingRate, reqChannels, id);
4479 mRecordThreads.add(id, thread);
4480 LOGV("openInput() created record thread: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004481 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
4482 if (pFormat) *pFormat = format;
4483 if (pChannels) *pChannels = reqChannels;
4484
4485 input->standby();
Eric Laurent9cc489a22009-12-05 05:20:01 -08004486
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004487 // notify client processes of the new input creation
4488 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004489 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004490 }
4491
Eric Laurent9cc489a22009-12-05 05:20:01 -08004492 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004493}
4494
Eric Laurentddb78e72009-07-28 08:44:33 -07004495status_t AudioFlinger::closeInput(int input)
Eric Laurenta553c252009-07-17 12:17:14 -07004496{
Eric Laurent49018a52009-08-04 08:37:05 -07004497 // keep strong reference on the record thread so that
4498 // it is not destroyed while exit() is executed
4499 sp <RecordThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07004500 {
4501 Mutex::Autolock _l(mLock);
4502 thread = checkRecordThread_l(input);
4503 if (thread == NULL) {
4504 return BAD_VALUE;
4505 }
4506
Eric Laurentddb78e72009-07-28 08:44:33 -07004507 LOGV("closeInput() %d", input);
Eric Laurent296a0ec2009-09-15 07:10:12 -07004508 void *param2 = 0;
Eric Laurent49f02be2009-11-19 09:00:56 -08004509 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
Eric Laurentddb78e72009-07-28 08:44:33 -07004510 mRecordThreads.removeItem(input);
Eric Laurenta553c252009-07-17 12:17:14 -07004511 }
4512 thread->exit();
4513
Eric Laurent49018a52009-08-04 08:37:05 -07004514 mAudioHardware->closeInputStream(thread->getInput());
4515
Eric Laurenta553c252009-07-17 12:17:14 -07004516 return NO_ERROR;
4517}
4518
Eric Laurentddb78e72009-07-28 08:44:33 -07004519status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004520{
4521 Mutex::Autolock _l(mLock);
4522 MixerThread *dstThread = checkMixerThread_l(output);
4523 if (dstThread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004524 LOGW("setStreamOutput() bad output id %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004525 return BAD_VALUE;
4526 }
4527
Eric Laurentddb78e72009-07-28 08:44:33 -07004528 LOGV("setStreamOutput() stream %d to output %d", stream, output);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004529 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
Eric Laurenta553c252009-07-17 12:17:14 -07004530
4531 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004532 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurenta553c252009-07-17 12:17:14 -07004533 if (thread != dstThread &&
4534 thread->type() != PlaybackThread::DIRECT) {
4535 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004536 srcThread->invalidateTracks(stream);
Eric Laurenta553c252009-07-17 12:17:14 -07004537 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004538 }
Eric Laurentd069f322009-09-01 05:56:26 -07004539
Eric Laurenta553c252009-07-17 12:17:14 -07004540 return NO_ERROR;
4541}
4542
Eric Laurent65b65452010-06-01 23:49:17 -07004543
4544int AudioFlinger::newAudioSessionId()
4545{
4546 return nextUniqueId();
4547}
4548
Eric Laurenta553c252009-07-17 12:17:14 -07004549// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07004550AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
Eric Laurenta553c252009-07-17 12:17:14 -07004551{
4552 PlaybackThread *thread = NULL;
Eric Laurentddb78e72009-07-28 08:44:33 -07004553 if (mPlaybackThreads.indexOfKey(output) >= 0) {
4554 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
Eric Laurenta553c252009-07-17 12:17:14 -07004555 }
Eric Laurenta553c252009-07-17 12:17:14 -07004556 return thread;
4557}
4558
4559// checkMixerThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07004560AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
Eric Laurenta553c252009-07-17 12:17:14 -07004561{
4562 PlaybackThread *thread = checkPlaybackThread_l(output);
4563 if (thread != NULL) {
4564 if (thread->type() == PlaybackThread::DIRECT) {
4565 thread = NULL;
4566 }
4567 }
4568 return (MixerThread *)thread;
4569}
4570
4571// checkRecordThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07004572AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
Eric Laurenta553c252009-07-17 12:17:14 -07004573{
4574 RecordThread *thread = NULL;
Eric Laurentddb78e72009-07-28 08:44:33 -07004575 if (mRecordThreads.indexOfKey(input) >= 0) {
4576 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
Eric Laurenta553c252009-07-17 12:17:14 -07004577 }
Eric Laurenta553c252009-07-17 12:17:14 -07004578 return thread;
4579}
4580
Eric Laurent65b65452010-06-01 23:49:17 -07004581int AudioFlinger::nextUniqueId()
4582{
4583 return android_atomic_inc(&mNextUniqueId);
4584}
4585
4586// ----------------------------------------------------------------------------
4587// Effect management
4588// ----------------------------------------------------------------------------
4589
4590
4591status_t AudioFlinger::loadEffectLibrary(const char *libPath, int *handle)
4592{
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004593 // check calling permissions
4594 if (!settingsAllowed()) {
4595 return PERMISSION_DENIED;
4596 }
4597 // only allow libraries loaded from /system/lib/soundfx for now
4598 if (strncmp(gEffectLibPath, libPath, strlen(gEffectLibPath)) != 0) {
4599 return PERMISSION_DENIED;
4600 }
4601
Eric Laurent65b65452010-06-01 23:49:17 -07004602 Mutex::Autolock _l(mLock);
4603 return EffectLoadLibrary(libPath, handle);
4604}
4605
4606status_t AudioFlinger::unloadEffectLibrary(int handle)
4607{
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004608 // check calling permissions
4609 if (!settingsAllowed()) {
4610 return PERMISSION_DENIED;
4611 }
4612
Eric Laurent65b65452010-06-01 23:49:17 -07004613 Mutex::Autolock _l(mLock);
4614 return EffectUnloadLibrary(handle);
4615}
4616
4617status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects)
4618{
4619 Mutex::Autolock _l(mLock);
4620 return EffectQueryNumberEffects(numEffects);
4621}
4622
Eric Laurent53334cd2010-06-23 17:38:20 -07004623status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor)
Eric Laurent65b65452010-06-01 23:49:17 -07004624{
4625 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07004626 return EffectQueryEffect(index, descriptor);
Eric Laurent65b65452010-06-01 23:49:17 -07004627}
4628
4629status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid, effect_descriptor_t *descriptor)
4630{
4631 Mutex::Autolock _l(mLock);
4632 return EffectGetDescriptor(pUuid, descriptor);
4633}
4634
Eric Laurentdf9b81c2010-07-02 08:12:41 -07004635
4636// this UUID must match the one defined in media/libeffects/EffectVisualizer.cpp
4637static const effect_uuid_t VISUALIZATION_UUID_ =
4638 {0xd069d9e0, 0x8329, 0x11df, 0x9168, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}};
4639
Eric Laurent65b65452010-06-01 23:49:17 -07004640sp<IEffect> AudioFlinger::createEffect(pid_t pid,
4641 effect_descriptor_t *pDesc,
4642 const sp<IEffectClient>& effectClient,
4643 int32_t priority,
4644 int output,
4645 int sessionId,
4646 status_t *status,
4647 int *id,
4648 int *enabled)
4649{
4650 status_t lStatus = NO_ERROR;
4651 sp<EffectHandle> handle;
4652 effect_interface_t itfe;
4653 effect_descriptor_t desc;
4654 sp<Client> client;
4655 wp<Client> wclient;
4656
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004657 LOGV("createEffect pid %d, client %p, priority %d, sessionId %d, output %d",
4658 pid, effectClient.get(), priority, sessionId, output);
Eric Laurent65b65452010-06-01 23:49:17 -07004659
4660 if (pDesc == NULL) {
4661 lStatus = BAD_VALUE;
4662 goto Exit;
4663 }
4664
Eric Laurent98c92592010-09-23 16:10:16 -07004665 // check audio settings permission for global effects
4666 if (sessionId == AudioSystem::SESSION_OUTPUT_MIX && !settingsAllowed()) {
4667 lStatus = PERMISSION_DENIED;
4668 goto Exit;
4669 }
4670
4671 // Session AudioSystem::SESSION_OUTPUT_STAGE is reserved for output stage effects
4672 // that can only be created by audio policy manager (running in same process)
4673 if (sessionId == AudioSystem::SESSION_OUTPUT_STAGE && getpid() != pid) {
4674 lStatus = PERMISSION_DENIED;
4675 goto Exit;
4676 }
4677
4678 // check recording permission for visualizer
4679 if ((memcmp(&pDesc->type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0 ||
4680 memcmp(&pDesc->uuid, &VISUALIZATION_UUID_, sizeof(effect_uuid_t)) == 0) &&
4681 !recordingAllowed()) {
4682 lStatus = PERMISSION_DENIED;
4683 goto Exit;
4684 }
4685
4686 if (output == 0) {
4687 if (sessionId == AudioSystem::SESSION_OUTPUT_STAGE) {
4688 // output must be specified by AudioPolicyManager when using session
4689 // AudioSystem::SESSION_OUTPUT_STAGE
4690 lStatus = BAD_VALUE;
4691 goto Exit;
4692 } else if (sessionId == AudioSystem::SESSION_OUTPUT_MIX) {
4693 // if the output returned by getOutputForEffect() is removed before we lock the
4694 // mutex below, the call to checkPlaybackThread_l(output) below will detect it
4695 // and we will exit safely
4696 output = AudioSystem::getOutputForEffect(&desc);
4697 }
4698 }
4699
Eric Laurent65b65452010-06-01 23:49:17 -07004700 {
4701 Mutex::Autolock _l(mLock);
4702
Eric Laurentdf9b81c2010-07-02 08:12:41 -07004703
Eric Laurent65b65452010-06-01 23:49:17 -07004704 if (!EffectIsNullUuid(&pDesc->uuid)) {
4705 // if uuid is specified, request effect descriptor
4706 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
4707 if (lStatus < 0) {
4708 LOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
4709 goto Exit;
4710 }
4711 } else {
4712 // if uuid is not specified, look for an available implementation
4713 // of the required type in effect factory
4714 if (EffectIsNullUuid(&pDesc->type)) {
4715 LOGW("createEffect() no effect type");
4716 lStatus = BAD_VALUE;
4717 goto Exit;
4718 }
4719 uint32_t numEffects = 0;
4720 effect_descriptor_t d;
4721 bool found = false;
4722
4723 lStatus = EffectQueryNumberEffects(&numEffects);
4724 if (lStatus < 0) {
4725 LOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
4726 goto Exit;
4727 }
Eric Laurent53334cd2010-06-23 17:38:20 -07004728 for (uint32_t i = 0; i < numEffects; i++) {
4729 lStatus = EffectQueryEffect(i, &desc);
Eric Laurent65b65452010-06-01 23:49:17 -07004730 if (lStatus < 0) {
Eric Laurent53334cd2010-06-23 17:38:20 -07004731 LOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07004732 continue;
4733 }
4734 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
4735 // If matching type found save effect descriptor. If the session is
4736 // 0 and the effect is not auxiliary, continue enumeration in case
4737 // an auxiliary version of this effect type is available
4738 found = true;
4739 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004740 if (sessionId != AudioSystem::SESSION_OUTPUT_MIX ||
Eric Laurent65b65452010-06-01 23:49:17 -07004741 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
4742 break;
4743 }
4744 }
4745 }
4746 if (!found) {
4747 lStatus = BAD_VALUE;
4748 LOGW("createEffect() effect not found");
4749 goto Exit;
4750 }
4751 // For same effect type, chose auxiliary version over insert version if
4752 // connect to output mix (Compliance to OpenSL ES)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004753 if (sessionId == AudioSystem::SESSION_OUTPUT_MIX &&
Eric Laurent65b65452010-06-01 23:49:17 -07004754 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
4755 memcpy(&desc, &d, sizeof(effect_descriptor_t));
4756 }
4757 }
4758
4759 // Do not allow auxiliary effects on a session different from 0 (output mix)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004760 if (sessionId != AudioSystem::SESSION_OUTPUT_MIX &&
Eric Laurent65b65452010-06-01 23:49:17 -07004761 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
4762 lStatus = INVALID_OPERATION;
4763 goto Exit;
4764 }
4765
4766 // return effect descriptor
4767 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
4768
4769 // If output is not specified try to find a matching audio session ID in one of the
4770 // output threads.
Eric Laurent98c92592010-09-23 16:10:16 -07004771 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
4772 // because of code checking output when entering the function.
Eric Laurent65b65452010-06-01 23:49:17 -07004773 if (output == 0) {
Eric Laurent98c92592010-09-23 16:10:16 -07004774 // look for the thread where the specified audio session is present
4775 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
4776 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
4777 output = mPlaybackThreads.keyAt(i);
4778 break;
Eric Laurent493941b2010-07-28 01:32:47 -07004779 }
Eric Laurent65b65452010-06-01 23:49:17 -07004780 }
Eric Laurent98c92592010-09-23 16:10:16 -07004781 // If no output thread contains the requested session ID, default to
4782 // first output. The effect chain will be moved to the correct output
4783 // thread when a track with the same session ID is created
4784 if (output == 0 && mPlaybackThreads.size()) {
4785 output = mPlaybackThreads.keyAt(0);
4786 }
Eric Laurent65b65452010-06-01 23:49:17 -07004787 }
Eric Laurent98c92592010-09-23 16:10:16 -07004788 LOGV("createEffect() got output %d for effect %s", output, desc.name);
Eric Laurent65b65452010-06-01 23:49:17 -07004789 PlaybackThread *thread = checkPlaybackThread_l(output);
4790 if (thread == NULL) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004791 LOGE("createEffect() unknown output thread");
Eric Laurent65b65452010-06-01 23:49:17 -07004792 lStatus = BAD_VALUE;
4793 goto Exit;
4794 }
4795
Eric Laurent98c92592010-09-23 16:10:16 -07004796 // TODO: allow attachment of effect to inputs
4797
Eric Laurent65b65452010-06-01 23:49:17 -07004798 wclient = mClients.valueFor(pid);
4799
4800 if (wclient != NULL) {
4801 client = wclient.promote();
4802 } else {
4803 client = new Client(this, pid);
4804 mClients.add(pid, client);
4805 }
4806
4807 // create effect on selected output trhead
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004808 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
4809 &desc, enabled, &lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07004810 if (handle != 0 && id != NULL) {
4811 *id = handle->id();
4812 }
4813 }
4814
4815Exit:
4816 if(status) {
4817 *status = lStatus;
4818 }
4819 return handle;
4820}
4821
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004822status_t AudioFlinger::moveEffects(int session, int srcOutput, int dstOutput)
4823{
4824 LOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
4825 session, srcOutput, dstOutput);
4826 Mutex::Autolock _l(mLock);
4827 if (srcOutput == dstOutput) {
4828 LOGW("moveEffects() same dst and src outputs %d", dstOutput);
4829 return NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07004830 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004831 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
4832 if (srcThread == NULL) {
4833 LOGW("moveEffects() bad srcOutput %d", srcOutput);
4834 return BAD_VALUE;
Eric Laurent53334cd2010-06-23 17:38:20 -07004835 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004836 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
4837 if (dstThread == NULL) {
4838 LOGW("moveEffects() bad dstOutput %d", dstOutput);
4839 return BAD_VALUE;
4840 }
4841
4842 Mutex::Autolock _dl(dstThread->mLock);
4843 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent493941b2010-07-28 01:32:47 -07004844 moveEffectChain_l(session, srcThread, dstThread, false);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004845
Eric Laurent53334cd2010-06-23 17:38:20 -07004846 return NO_ERROR;
4847}
4848
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004849// moveEffectChain_l mustbe called with both srcThread and dstThread mLocks held
4850status_t AudioFlinger::moveEffectChain_l(int session,
4851 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent493941b2010-07-28 01:32:47 -07004852 AudioFlinger::PlaybackThread *dstThread,
4853 bool reRegister)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004854{
4855 LOGV("moveEffectChain_l() session %d from thread %p to thread %p",
4856 session, srcThread, dstThread);
4857
4858 sp<EffectChain> chain = srcThread->getEffectChain_l(session);
4859 if (chain == 0) {
4860 LOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
4861 session, srcThread);
4862 return INVALID_OPERATION;
4863 }
4864
Eric Laurent493941b2010-07-28 01:32:47 -07004865 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004866 // so that a new chain is created with correct parameters when first effect is added. This is
4867 // otherwise unecessary as removeEffect_l() will remove the chain when last effect is
4868 // removed.
4869 srcThread->removeEffectChain_l(chain);
4870
4871 // transfer all effects one by one so that new effect chain is created on new thread with
4872 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent493941b2010-07-28 01:32:47 -07004873 int dstOutput = dstThread->id();
4874 sp<EffectChain> dstChain;
4875 uint32_t strategy;
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004876 sp<EffectModule> effect = chain->getEffectFromId_l(0);
4877 while (effect != 0) {
4878 srcThread->removeEffect_l(effect);
4879 dstThread->addEffect_l(effect);
Eric Laurent493941b2010-07-28 01:32:47 -07004880 // if the move request is not received from audio policy manager, the effect must be
4881 // re-registered with the new strategy and output
4882 if (dstChain == 0) {
4883 dstChain = effect->chain().promote();
4884 if (dstChain == 0) {
4885 LOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
4886 srcThread->addEffect_l(effect);
4887 return NO_INIT;
4888 }
4889 strategy = dstChain->strategy();
4890 }
4891 if (reRegister) {
4892 AudioSystem::unregisterEffect(effect->id());
4893 AudioSystem::registerEffect(&effect->desc(),
4894 dstOutput,
4895 strategy,
4896 session,
4897 effect->id());
4898 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004899 effect = chain->getEffectFromId_l(0);
4900 }
4901
4902 return NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07004903}
4904
Eric Laurent65b65452010-06-01 23:49:17 -07004905// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
4906sp<AudioFlinger::EffectHandle> AudioFlinger::PlaybackThread::createEffect_l(
4907 const sp<AudioFlinger::Client>& client,
4908 const sp<IEffectClient>& effectClient,
4909 int32_t priority,
4910 int sessionId,
4911 effect_descriptor_t *desc,
4912 int *enabled,
4913 status_t *status
4914 )
4915{
4916 sp<EffectModule> effect;
4917 sp<EffectHandle> handle;
4918 status_t lStatus;
4919 sp<Track> track;
4920 sp<EffectChain> chain;
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004921 bool chainCreated = false;
Eric Laurent65b65452010-06-01 23:49:17 -07004922 bool effectCreated = false;
Eric Laurent53334cd2010-06-23 17:38:20 -07004923 bool effectRegistered = false;
Eric Laurent65b65452010-06-01 23:49:17 -07004924
4925 if (mOutput == 0) {
4926 LOGW("createEffect_l() Audio driver not initialized.");
4927 lStatus = NO_INIT;
4928 goto Exit;
4929 }
4930
4931 // Do not allow auxiliary effect on session other than 0
4932 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY &&
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004933 sessionId != AudioSystem::SESSION_OUTPUT_MIX) {
4934 LOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
4935 desc->name, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07004936 lStatus = BAD_VALUE;
4937 goto Exit;
4938 }
4939
4940 // Do not allow effects with session ID 0 on direct output or duplicating threads
4941 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004942 if (sessionId == AudioSystem::SESSION_OUTPUT_MIX && mType != MIXER) {
4943 LOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
4944 desc->name, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07004945 lStatus = BAD_VALUE;
4946 goto Exit;
4947 }
4948
4949 LOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
4950
4951 { // scope for mLock
4952 Mutex::Autolock _l(mLock);
4953
4954 // check for existing effect chain with the requested audio session
4955 chain = getEffectChain_l(sessionId);
4956 if (chain == 0) {
4957 // create a new chain for this session
4958 LOGV("createEffect_l() new effect chain for session %d", sessionId);
4959 chain = new EffectChain(this, sessionId);
4960 addEffectChain_l(chain);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004961 chain->setStrategy(getStrategyForSession_l(sessionId));
4962 chainCreated = true;
Eric Laurent65b65452010-06-01 23:49:17 -07004963 } else {
Eric Laurent76c40f72010-07-15 12:50:15 -07004964 effect = chain->getEffectFromDesc_l(desc);
Eric Laurent65b65452010-06-01 23:49:17 -07004965 }
4966
4967 LOGV("createEffect_l() got effect %p on chain %p", effect == 0 ? 0 : effect.get(), chain.get());
4968
4969 if (effect == 0) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004970 int id = mAudioFlinger->nextUniqueId();
Eric Laurent53334cd2010-06-23 17:38:20 -07004971 // Check CPU and memory usage
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004972 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Eric Laurent53334cd2010-06-23 17:38:20 -07004973 if (lStatus != NO_ERROR) {
4974 goto Exit;
4975 }
4976 effectRegistered = true;
Eric Laurent65b65452010-06-01 23:49:17 -07004977 // create a new effect module if none present in the chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004978 effect = new EffectModule(this, chain, desc, id, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07004979 lStatus = effect->status();
4980 if (lStatus != NO_ERROR) {
4981 goto Exit;
4982 }
Eric Laurent76c40f72010-07-15 12:50:15 -07004983 lStatus = chain->addEffect_l(effect);
Eric Laurent65b65452010-06-01 23:49:17 -07004984 if (lStatus != NO_ERROR) {
4985 goto Exit;
4986 }
Eric Laurent53334cd2010-06-23 17:38:20 -07004987 effectCreated = true;
Eric Laurent65b65452010-06-01 23:49:17 -07004988
4989 effect->setDevice(mDevice);
Eric Laurent53334cd2010-06-23 17:38:20 -07004990 effect->setMode(mAudioFlinger->getMode());
Eric Laurent65b65452010-06-01 23:49:17 -07004991 }
4992 // create effect handle and connect it to effect module
4993 handle = new EffectHandle(effect, client, effectClient, priority);
4994 lStatus = effect->addHandle(handle);
4995 if (enabled) {
4996 *enabled = (int)effect->isEnabled();
4997 }
4998 }
4999
5000Exit:
5001 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005002 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07005003 if (effectCreated) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005004 chain->removeEffect_l(effect);
Eric Laurent65b65452010-06-01 23:49:17 -07005005 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005006 if (effectRegistered) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005007 AudioSystem::unregisterEffect(effect->id());
5008 }
5009 if (chainCreated) {
5010 removeEffectChain_l(chain);
Eric Laurent53334cd2010-06-23 17:38:20 -07005011 }
Eric Laurent65b65452010-06-01 23:49:17 -07005012 handle.clear();
5013 }
5014
5015 if(status) {
5016 *status = lStatus;
5017 }
5018 return handle;
5019}
5020
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005021// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5022// PlaybackThread::mLock held
5023status_t AudioFlinger::PlaybackThread::addEffect_l(const sp<EffectModule>& effect)
5024{
5025 // check for existing effect chain with the requested audio session
5026 int sessionId = effect->sessionId();
5027 sp<EffectChain> chain = getEffectChain_l(sessionId);
5028 bool chainCreated = false;
5029
5030 if (chain == 0) {
5031 // create a new chain for this session
5032 LOGV("addEffect_l() new effect chain for session %d", sessionId);
5033 chain = new EffectChain(this, sessionId);
5034 addEffectChain_l(chain);
5035 chain->setStrategy(getStrategyForSession_l(sessionId));
5036 chainCreated = true;
5037 }
5038 LOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
5039
5040 if (chain->getEffectFromId_l(effect->id()) != 0) {
5041 LOGW("addEffect_l() %p effect %s already present in chain %p",
5042 this, effect->desc().name, chain.get());
5043 return BAD_VALUE;
5044 }
5045
5046 status_t status = chain->addEffect_l(effect);
5047 if (status != NO_ERROR) {
5048 if (chainCreated) {
5049 removeEffectChain_l(chain);
5050 }
5051 return status;
5052 }
5053
5054 effect->setDevice(mDevice);
5055 effect->setMode(mAudioFlinger->getMode());
5056 return NO_ERROR;
5057}
5058
5059void AudioFlinger::PlaybackThread::removeEffect_l(const sp<EffectModule>& effect) {
5060
5061 LOGV("removeEffect_l() %p effect %p", this, effect.get());
Eric Laurent53334cd2010-06-23 17:38:20 -07005062 effect_descriptor_t desc = effect->desc();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005063 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5064 detachAuxEffect_l(effect->id());
5065 }
5066
5067 sp<EffectChain> chain = effect->chain().promote();
5068 if (chain != 0) {
5069 // remove effect chain if removing last effect
5070 if (chain->removeEffect_l(effect) == 0) {
5071 removeEffectChain_l(chain);
5072 }
5073 } else {
5074 LOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
5075 }
5076}
5077
5078void AudioFlinger::PlaybackThread::disconnectEffect(const sp<EffectModule>& effect,
5079 const wp<EffectHandle>& handle) {
Eric Laurent53334cd2010-06-23 17:38:20 -07005080 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005081 LOGV("disconnectEffect() %p effect %p", this, effect.get());
Eric Laurent53334cd2010-06-23 17:38:20 -07005082 // delete the effect module if removing last handle on it
5083 if (effect->removeHandle(handle) == 0) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005084 removeEffect_l(effect);
5085 AudioSystem::unregisterEffect(effect->id());
Eric Laurent53334cd2010-06-23 17:38:20 -07005086 }
5087}
5088
Eric Laurent65b65452010-06-01 23:49:17 -07005089status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5090{
5091 int session = chain->sessionId();
5092 int16_t *buffer = mMixBuffer;
Eric Laurent53334cd2010-06-23 17:38:20 -07005093 bool ownsBuffer = false;
Eric Laurent65b65452010-06-01 23:49:17 -07005094
5095 LOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Eric Laurent53334cd2010-06-23 17:38:20 -07005096 if (session > 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07005097 // Only one effect chain can be present in direct output thread and it uses
5098 // the mix buffer as input
5099 if (mType != DIRECT) {
5100 size_t numSamples = mFrameCount * mChannelCount;
5101 buffer = new int16_t[numSamples];
5102 memset(buffer, 0, numSamples * sizeof(int16_t));
5103 LOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
5104 ownsBuffer = true;
5105 }
Eric Laurent65b65452010-06-01 23:49:17 -07005106
Eric Laurent53334cd2010-06-23 17:38:20 -07005107 // Attach all tracks with same session ID to this chain.
5108 for (size_t i = 0; i < mTracks.size(); ++i) {
5109 sp<Track> track = mTracks[i];
5110 if (session == track->sessionId()) {
5111 LOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
5112 track->setMainBuffer(buffer);
5113 }
5114 }
5115
5116 // indicate all active tracks in the chain
5117 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5118 sp<Track> track = mActiveTracks[i].promote();
5119 if (track == 0) continue;
5120 if (session == track->sessionId()) {
5121 LOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
5122 chain->startTrack();
5123 }
Eric Laurent65b65452010-06-01 23:49:17 -07005124 }
5125 }
5126
Eric Laurent53334cd2010-06-23 17:38:20 -07005127 chain->setInBuffer(buffer, ownsBuffer);
5128 chain->setOutBuffer(mMixBuffer);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005129 // Effect chain for session AudioSystem::SESSION_OUTPUT_STAGE is inserted at end of effect
5130 // chains list in order to be processed last as it contains output stage effects
5131 // Effect chain for session AudioSystem::SESSION_OUTPUT_MIX is inserted before
5132 // session AudioSystem::SESSION_OUTPUT_STAGE to be processed
Eric Laurent53334cd2010-06-23 17:38:20 -07005133 // after track specific effects and before output stage
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005134 // It is therefore mandatory that AudioSystem::SESSION_OUTPUT_MIX == 0 and
5135 // that AudioSystem::SESSION_OUTPUT_STAGE < AudioSystem::SESSION_OUTPUT_MIX
5136 // Effect chain for other sessions are inserted at beginning of effect
5137 // chains list to be processed before output mix effects. Relative order between other
5138 // sessions is not important
Eric Laurent53334cd2010-06-23 17:38:20 -07005139 size_t size = mEffectChains.size();
5140 size_t i = 0;
5141 for (i = 0; i < size; i++) {
5142 if (mEffectChains[i]->sessionId() < session) break;
Eric Laurent65b65452010-06-01 23:49:17 -07005143 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005144 mEffectChains.insertAt(chain, i);
Eric Laurent65b65452010-06-01 23:49:17 -07005145
5146 return NO_ERROR;
5147}
5148
5149size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
5150{
5151 int session = chain->sessionId();
5152
5153 LOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
5154
5155 for (size_t i = 0; i < mEffectChains.size(); i++) {
5156 if (chain == mEffectChains[i]) {
5157 mEffectChains.removeAt(i);
5158 // detach all tracks with same session ID from this chain
5159 for (size_t i = 0; i < mTracks.size(); ++i) {
5160 sp<Track> track = mTracks[i];
5161 if (session == track->sessionId()) {
5162 track->setMainBuffer(mMixBuffer);
5163 }
5164 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005165 break;
Eric Laurent65b65452010-06-01 23:49:17 -07005166 }
5167 }
5168 return mEffectChains.size();
5169}
5170
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005171void AudioFlinger::PlaybackThread::lockEffectChains_l(
5172 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
Eric Laurent65b65452010-06-01 23:49:17 -07005173{
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005174 effectChains = mEffectChains;
Eric Laurent65b65452010-06-01 23:49:17 -07005175 for (size_t i = 0; i < mEffectChains.size(); i++) {
5176 mEffectChains[i]->lock();
5177 }
5178}
5179
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005180void AudioFlinger::PlaybackThread::unlockEffectChains(
5181 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
Eric Laurent65b65452010-06-01 23:49:17 -07005182{
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005183 for (size_t i = 0; i < effectChains.size(); i++) {
5184 effectChains[i]->unlock();
Eric Laurent65b65452010-06-01 23:49:17 -07005185 }
5186}
5187
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005188
Eric Laurent65b65452010-06-01 23:49:17 -07005189sp<AudioFlinger::EffectModule> AudioFlinger::PlaybackThread::getEffect_l(int sessionId, int effectId)
5190{
5191 sp<EffectModule> effect;
5192
5193 sp<EffectChain> chain = getEffectChain_l(sessionId);
5194 if (chain != 0) {
Eric Laurent76c40f72010-07-15 12:50:15 -07005195 effect = chain->getEffectFromId_l(effectId);
Eric Laurent65b65452010-06-01 23:49:17 -07005196 }
5197 return effect;
5198}
5199
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005200status_t AudioFlinger::PlaybackThread::attachAuxEffect(
5201 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Eric Laurent65b65452010-06-01 23:49:17 -07005202{
5203 Mutex::Autolock _l(mLock);
5204 return attachAuxEffect_l(track, EffectId);
5205}
5206
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005207status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
5208 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Eric Laurent65b65452010-06-01 23:49:17 -07005209{
5210 status_t status = NO_ERROR;
5211
5212 if (EffectId == 0) {
5213 track->setAuxBuffer(0, NULL);
5214 } else {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005215 // Auxiliary effects are always in audio session AudioSystem::SESSION_OUTPUT_MIX
5216 sp<EffectModule> effect = getEffect_l(AudioSystem::SESSION_OUTPUT_MIX, EffectId);
Eric Laurent65b65452010-06-01 23:49:17 -07005217 if (effect != 0) {
5218 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5219 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
5220 } else {
5221 status = INVALID_OPERATION;
5222 }
5223 } else {
5224 status = BAD_VALUE;
5225 }
5226 }
5227 return status;
5228}
5229
5230void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
5231{
5232 for (size_t i = 0; i < mTracks.size(); ++i) {
5233 sp<Track> track = mTracks[i];
5234 if (track->auxEffectId() == effectId) {
5235 attachAuxEffect_l(track, 0);
5236 }
5237 }
5238}
5239
5240// ----------------------------------------------------------------------------
5241// EffectModule implementation
5242// ----------------------------------------------------------------------------
5243
5244#undef LOG_TAG
5245#define LOG_TAG "AudioFlinger::EffectModule"
5246
5247AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
5248 const wp<AudioFlinger::EffectChain>& chain,
5249 effect_descriptor_t *desc,
5250 int id,
5251 int sessionId)
5252 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
5253 mStatus(NO_INIT), mState(IDLE)
5254{
5255 LOGV("Constructor %p", this);
5256 int lStatus;
5257 sp<ThreadBase> thread = mThread.promote();
5258 if (thread == 0) {
5259 return;
5260 }
5261 PlaybackThread *p = (PlaybackThread *)thread.get();
5262
5263 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
5264
5265 // create effect engine from effect factory
Eric Laurent53334cd2010-06-23 17:38:20 -07005266 mStatus = EffectCreate(&desc->uuid, sessionId, p->id(), &mEffectInterface);
5267
Eric Laurent65b65452010-06-01 23:49:17 -07005268 if (mStatus != NO_ERROR) {
5269 return;
5270 }
5271 lStatus = init();
5272 if (lStatus < 0) {
5273 mStatus = lStatus;
5274 goto Error;
5275 }
5276
5277 LOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
5278 return;
5279Error:
5280 EffectRelease(mEffectInterface);
5281 mEffectInterface = NULL;
5282 LOGV("Constructor Error %d", mStatus);
5283}
5284
5285AudioFlinger::EffectModule::~EffectModule()
5286{
5287 LOGV("Destructor %p", this);
5288 if (mEffectInterface != NULL) {
5289 // release effect engine
5290 EffectRelease(mEffectInterface);
5291 }
5292}
5293
5294status_t AudioFlinger::EffectModule::addHandle(sp<EffectHandle>& handle)
5295{
5296 status_t status;
5297
5298 Mutex::Autolock _l(mLock);
5299 // First handle in mHandles has highest priority and controls the effect module
5300 int priority = handle->priority();
5301 size_t size = mHandles.size();
5302 sp<EffectHandle> h;
5303 size_t i;
5304 for (i = 0; i < size; i++) {
5305 h = mHandles[i].promote();
5306 if (h == 0) continue;
5307 if (h->priority() <= priority) break;
5308 }
5309 // if inserted in first place, move effect control from previous owner to this handle
5310 if (i == 0) {
5311 if (h != 0) {
5312 h->setControl(false, true);
5313 }
5314 handle->setControl(true, false);
5315 status = NO_ERROR;
5316 } else {
5317 status = ALREADY_EXISTS;
5318 }
5319 mHandles.insertAt(handle, i);
5320 return status;
5321}
5322
5323size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
5324{
5325 Mutex::Autolock _l(mLock);
5326 size_t size = mHandles.size();
5327 size_t i;
5328 for (i = 0; i < size; i++) {
5329 if (mHandles[i] == handle) break;
5330 }
5331 if (i == size) {
5332 return size;
5333 }
5334 mHandles.removeAt(i);
5335 size = mHandles.size();
5336 // if removed from first place, move effect control from this handle to next in line
5337 if (i == 0 && size != 0) {
5338 sp<EffectHandle> h = mHandles[0].promote();
5339 if (h != 0) {
5340 h->setControl(true, true);
5341 }
5342 }
5343
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07005344 // Release effect engine here so that it is done immediately. Otherwise it will be released
5345 // by the destructor when the last strong reference on the this object is released which can
5346 // happen after next process is called on this effect.
5347 if (size == 0 && mEffectInterface != NULL) {
5348 // release effect engine
5349 EffectRelease(mEffectInterface);
5350 mEffectInterface = NULL;
5351 }
5352
Eric Laurent65b65452010-06-01 23:49:17 -07005353 return size;
5354}
5355
5356void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle)
5357{
5358 // keep a strong reference on this EffectModule to avoid calling the
5359 // destructor before we exit
5360 sp<EffectModule> keep(this);
Eric Laurent53334cd2010-06-23 17:38:20 -07005361 {
5362 sp<ThreadBase> thread = mThread.promote();
5363 if (thread != 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07005364 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurent53334cd2010-06-23 17:38:20 -07005365 playbackThread->disconnectEffect(keep, handle);
Eric Laurent65b65452010-06-01 23:49:17 -07005366 }
5367 }
5368}
5369
Eric Laurent7d850f22010-07-09 13:34:17 -07005370void AudioFlinger::EffectModule::updateState() {
5371 Mutex::Autolock _l(mLock);
5372
5373 switch (mState) {
5374 case RESTART:
5375 reset_l();
5376 // FALL THROUGH
5377
5378 case STARTING:
5379 // clear auxiliary effect input buffer for next accumulation
5380 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5381 memset(mConfig.inputCfg.buffer.raw,
5382 0,
5383 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
5384 }
5385 start_l();
5386 mState = ACTIVE;
5387 break;
5388 case STOPPING:
5389 stop_l();
5390 mDisableWaitCnt = mMaxDisableWaitCnt;
5391 mState = STOPPED;
5392 break;
5393 case STOPPED:
5394 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
5395 // turn off sequence.
5396 if (--mDisableWaitCnt == 0) {
5397 reset_l();
5398 mState = IDLE;
5399 }
5400 break;
5401 default: //IDLE , ACTIVE
5402 break;
5403 }
5404}
5405
Eric Laurent65b65452010-06-01 23:49:17 -07005406void AudioFlinger::EffectModule::process()
5407{
5408 Mutex::Autolock _l(mLock);
5409
Eric Laurent7d850f22010-07-09 13:34:17 -07005410 if (mEffectInterface == NULL ||
5411 mConfig.inputCfg.buffer.raw == NULL ||
5412 mConfig.outputCfg.buffer.raw == NULL) {
Eric Laurent65b65452010-06-01 23:49:17 -07005413 return;
5414 }
5415
Eric Laurenta92ebfa2010-08-31 13:50:07 -07005416 if (isProcessEnabled()) {
Eric Laurent65b65452010-06-01 23:49:17 -07005417 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
5418 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5419 AudioMixer::ditherAndClamp(mConfig.inputCfg.buffer.s32,
5420 mConfig.inputCfg.buffer.s32,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005421 mConfig.inputCfg.buffer.frameCount/2);
Eric Laurent65b65452010-06-01 23:49:17 -07005422 }
5423
Eric Laurent65b65452010-06-01 23:49:17 -07005424 // do the actual processing in the effect engine
Eric Laurent7d850f22010-07-09 13:34:17 -07005425 int ret = (*mEffectInterface)->process(mEffectInterface,
5426 &mConfig.inputCfg.buffer,
5427 &mConfig.outputCfg.buffer);
5428
5429 // force transition to IDLE state when engine is ready
5430 if (mState == STOPPED && ret == -ENODATA) {
5431 mDisableWaitCnt = 1;
5432 }
Eric Laurent65b65452010-06-01 23:49:17 -07005433
5434 // clear auxiliary effect input buffer for next accumulation
5435 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5436 memset(mConfig.inputCfg.buffer.raw, 0, mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
5437 }
5438 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
5439 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw){
5440 // If an insert effect is idle and input buffer is different from output buffer, copy input to
5441 // output
5442 sp<EffectChain> chain = mChain.promote();
5443 if (chain != 0 && chain->activeTracks() != 0) {
5444 size_t size = mConfig.inputCfg.buffer.frameCount * sizeof(int16_t);
5445 if (mConfig.inputCfg.channels == CHANNEL_STEREO) {
5446 size *= 2;
5447 }
5448 memcpy(mConfig.outputCfg.buffer.raw, mConfig.inputCfg.buffer.raw, size);
5449 }
5450 }
5451}
5452
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005453void AudioFlinger::EffectModule::reset_l()
Eric Laurent65b65452010-06-01 23:49:17 -07005454{
5455 if (mEffectInterface == NULL) {
5456 return;
5457 }
5458 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
5459}
5460
5461status_t AudioFlinger::EffectModule::configure()
5462{
5463 uint32_t channels;
5464 if (mEffectInterface == NULL) {
5465 return NO_INIT;
5466 }
5467
5468 sp<ThreadBase> thread = mThread.promote();
5469 if (thread == 0) {
5470 return DEAD_OBJECT;
5471 }
5472
5473 // TODO: handle configuration of effects replacing track process
5474 if (thread->channelCount() == 1) {
5475 channels = CHANNEL_MONO;
5476 } else {
5477 channels = CHANNEL_STEREO;
5478 }
5479
5480 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5481 mConfig.inputCfg.channels = CHANNEL_MONO;
5482 } else {
5483 mConfig.inputCfg.channels = channels;
5484 }
5485 mConfig.outputCfg.channels = channels;
Eric Laurent53334cd2010-06-23 17:38:20 -07005486 mConfig.inputCfg.format = SAMPLE_FORMAT_PCM_S15;
5487 mConfig.outputCfg.format = SAMPLE_FORMAT_PCM_S15;
Eric Laurent65b65452010-06-01 23:49:17 -07005488 mConfig.inputCfg.samplingRate = thread->sampleRate();
5489 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
5490 mConfig.inputCfg.bufferProvider.cookie = NULL;
5491 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
5492 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
5493 mConfig.outputCfg.bufferProvider.cookie = NULL;
5494 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
5495 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
5496 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
5497 // Insert effect:
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005498 // - in session AudioSystem::SESSION_OUTPUT_MIX or AudioSystem::SESSION_OUTPUT_STAGE,
5499 // always overwrites output buffer: input buffer == output buffer
Eric Laurent65b65452010-06-01 23:49:17 -07005500 // - in other sessions:
5501 // last effect in the chain accumulates in output buffer: input buffer != output buffer
5502 // other effect: overwrites output buffer: input buffer == output buffer
5503 // Auxiliary effect:
5504 // accumulates in output buffer: input buffer != output buffer
5505 // Therefore: accumulate <=> input buffer != output buffer
5506 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
5507 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
5508 } else {
5509 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
5510 }
5511 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
5512 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
5513 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
5514 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
5515
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005516 LOGV("configure() %p thread %p buffer %p framecount %d",
5517 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
5518
Eric Laurent65b65452010-06-01 23:49:17 -07005519 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005520 uint32_t size = sizeof(int);
5521 status_t status = (*mEffectInterface)->command(mEffectInterface,
5522 EFFECT_CMD_CONFIGURE,
5523 sizeof(effect_config_t),
5524 &mConfig,
5525 &size,
5526 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005527 if (status == 0) {
5528 status = cmdStatus;
5529 }
Eric Laurent7d850f22010-07-09 13:34:17 -07005530
5531 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
5532 (1000 * mConfig.outputCfg.buffer.frameCount);
5533
Eric Laurent65b65452010-06-01 23:49:17 -07005534 return status;
5535}
5536
5537status_t AudioFlinger::EffectModule::init()
5538{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005539 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07005540 if (mEffectInterface == NULL) {
5541 return NO_INIT;
5542 }
5543 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005544 uint32_t size = sizeof(status_t);
5545 status_t status = (*mEffectInterface)->command(mEffectInterface,
5546 EFFECT_CMD_INIT,
5547 0,
5548 NULL,
5549 &size,
5550 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005551 if (status == 0) {
5552 status = cmdStatus;
5553 }
5554 return status;
5555}
5556
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005557status_t AudioFlinger::EffectModule::start_l()
Eric Laurent65b65452010-06-01 23:49:17 -07005558{
5559 if (mEffectInterface == NULL) {
5560 return NO_INIT;
5561 }
5562 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005563 uint32_t size = sizeof(status_t);
5564 status_t status = (*mEffectInterface)->command(mEffectInterface,
5565 EFFECT_CMD_ENABLE,
5566 0,
5567 NULL,
5568 &size,
5569 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005570 if (status == 0) {
5571 status = cmdStatus;
5572 }
5573 return status;
5574}
5575
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005576status_t AudioFlinger::EffectModule::stop_l()
Eric Laurent65b65452010-06-01 23:49:17 -07005577{
5578 if (mEffectInterface == NULL) {
5579 return NO_INIT;
5580 }
5581 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005582 uint32_t size = sizeof(status_t);
5583 status_t status = (*mEffectInterface)->command(mEffectInterface,
5584 EFFECT_CMD_DISABLE,
5585 0,
5586 NULL,
5587 &size,
5588 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005589 if (status == 0) {
5590 status = cmdStatus;
5591 }
5592 return status;
5593}
5594
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005595status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
5596 uint32_t cmdSize,
5597 void *pCmdData,
5598 uint32_t *replySize,
5599 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07005600{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005601 Mutex::Autolock _l(mLock);
5602// LOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Eric Laurent65b65452010-06-01 23:49:17 -07005603
5604 if (mEffectInterface == NULL) {
5605 return NO_INIT;
5606 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005607 status_t status = (*mEffectInterface)->command(mEffectInterface,
5608 cmdCode,
5609 cmdSize,
5610 pCmdData,
5611 replySize,
5612 pReplyData);
Eric Laurent65b65452010-06-01 23:49:17 -07005613 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005614 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Eric Laurent65b65452010-06-01 23:49:17 -07005615 for (size_t i = 1; i < mHandles.size(); i++) {
5616 sp<EffectHandle> h = mHandles[i].promote();
5617 if (h != 0) {
5618 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
5619 }
5620 }
5621 }
5622 return status;
5623}
5624
5625status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
5626{
5627 Mutex::Autolock _l(mLock);
5628 LOGV("setEnabled %p enabled %d", this, enabled);
5629
5630 if (enabled != isEnabled()) {
5631 switch (mState) {
5632 // going from disabled to enabled
5633 case IDLE:
Eric Laurent7d850f22010-07-09 13:34:17 -07005634 mState = STARTING;
5635 break;
5636 case STOPPED:
5637 mState = RESTART;
Eric Laurent65b65452010-06-01 23:49:17 -07005638 break;
5639 case STOPPING:
5640 mState = ACTIVE;
5641 break;
Eric Laurent65b65452010-06-01 23:49:17 -07005642
5643 // going from enabled to disabled
Eric Laurent7d850f22010-07-09 13:34:17 -07005644 case RESTART:
Eric Laurenta92ebfa2010-08-31 13:50:07 -07005645 mState = STOPPED;
5646 break;
Eric Laurent65b65452010-06-01 23:49:17 -07005647 case STARTING:
Eric Laurent7d850f22010-07-09 13:34:17 -07005648 mState = IDLE;
Eric Laurent65b65452010-06-01 23:49:17 -07005649 break;
5650 case ACTIVE:
5651 mState = STOPPING;
5652 break;
5653 }
5654 for (size_t i = 1; i < mHandles.size(); i++) {
5655 sp<EffectHandle> h = mHandles[i].promote();
5656 if (h != 0) {
5657 h->setEnabled(enabled);
5658 }
5659 }
5660 }
5661 return NO_ERROR;
5662}
5663
5664bool AudioFlinger::EffectModule::isEnabled()
5665{
5666 switch (mState) {
Eric Laurent7d850f22010-07-09 13:34:17 -07005667 case RESTART:
Eric Laurent65b65452010-06-01 23:49:17 -07005668 case STARTING:
5669 case ACTIVE:
5670 return true;
5671 case IDLE:
5672 case STOPPING:
5673 case STOPPED:
5674 default:
5675 return false;
5676 }
5677}
5678
Eric Laurenta92ebfa2010-08-31 13:50:07 -07005679bool AudioFlinger::EffectModule::isProcessEnabled()
5680{
5681 switch (mState) {
5682 case RESTART:
5683 case ACTIVE:
5684 case STOPPING:
5685 case STOPPED:
5686 return true;
5687 case IDLE:
5688 case STARTING:
5689 default:
5690 return false;
5691 }
5692}
5693
Eric Laurent65b65452010-06-01 23:49:17 -07005694status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
5695{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005696 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07005697 status_t status = NO_ERROR;
5698
5699 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
5700 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurenta92ebfa2010-08-31 13:50:07 -07005701 if (isProcessEnabled() &&
Eric Laurent0d7e0482010-07-19 06:24:46 -07005702 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
5703 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Eric Laurent65b65452010-06-01 23:49:17 -07005704 status_t cmdStatus;
5705 uint32_t volume[2];
5706 uint32_t *pVolume = NULL;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005707 uint32_t size = sizeof(volume);
Eric Laurent65b65452010-06-01 23:49:17 -07005708 volume[0] = *left;
5709 volume[1] = *right;
5710 if (controller) {
5711 pVolume = volume;
5712 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005713 status = (*mEffectInterface)->command(mEffectInterface,
5714 EFFECT_CMD_SET_VOLUME,
5715 size,
5716 volume,
5717 &size,
5718 pVolume);
Eric Laurent65b65452010-06-01 23:49:17 -07005719 if (controller && status == NO_ERROR && size == sizeof(volume)) {
5720 *left = volume[0];
5721 *right = volume[1];
5722 }
5723 }
5724 return status;
5725}
5726
5727status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
5728{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005729 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07005730 status_t status = NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07005731 if ((mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
5732 // convert device bit field from AudioSystem to EffectApi format.
5733 device = deviceAudioSystemToEffectApi(device);
5734 if (device == 0) {
5735 return BAD_VALUE;
5736 }
Eric Laurent65b65452010-06-01 23:49:17 -07005737 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005738 uint32_t size = sizeof(status_t);
5739 status = (*mEffectInterface)->command(mEffectInterface,
5740 EFFECT_CMD_SET_DEVICE,
5741 sizeof(uint32_t),
5742 &device,
5743 &size,
5744 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005745 if (status == NO_ERROR) {
5746 status = cmdStatus;
5747 }
5748 }
5749 return status;
5750}
5751
Eric Laurent53334cd2010-06-23 17:38:20 -07005752status_t AudioFlinger::EffectModule::setMode(uint32_t mode)
5753{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005754 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07005755 status_t status = NO_ERROR;
5756 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
5757 // convert audio mode from AudioSystem to EffectApi format.
5758 int effectMode = modeAudioSystemToEffectApi(mode);
5759 if (effectMode < 0) {
5760 return BAD_VALUE;
5761 }
5762 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005763 uint32_t size = sizeof(status_t);
5764 status = (*mEffectInterface)->command(mEffectInterface,
5765 EFFECT_CMD_SET_AUDIO_MODE,
5766 sizeof(int),
5767 &effectMode,
5768 &size,
5769 &cmdStatus);
Eric Laurent53334cd2010-06-23 17:38:20 -07005770 if (status == NO_ERROR) {
5771 status = cmdStatus;
5772 }
5773 }
5774 return status;
5775}
5776
5777// update this table when AudioSystem::audio_devices or audio_device_e (in EffectApi.h) are modified
5778const uint32_t AudioFlinger::EffectModule::sDeviceConvTable[] = {
5779 DEVICE_EARPIECE, // AudioSystem::DEVICE_OUT_EARPIECE
5780 DEVICE_SPEAKER, // AudioSystem::DEVICE_OUT_SPEAKER
5781 DEVICE_WIRED_HEADSET, // case AudioSystem::DEVICE_OUT_WIRED_HEADSET
5782 DEVICE_WIRED_HEADPHONE, // AudioSystem::DEVICE_OUT_WIRED_HEADPHONE
5783 DEVICE_BLUETOOTH_SCO, // AudioSystem::DEVICE_OUT_BLUETOOTH_SCO
5784 DEVICE_BLUETOOTH_SCO_HEADSET, // AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_HEADSET
5785 DEVICE_BLUETOOTH_SCO_CARKIT, // AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_CARKIT
5786 DEVICE_BLUETOOTH_A2DP, // AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP
5787 DEVICE_BLUETOOTH_A2DP_HEADPHONES, // AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES
5788 DEVICE_BLUETOOTH_A2DP_SPEAKER, // AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER
5789 DEVICE_AUX_DIGITAL // AudioSystem::DEVICE_OUT_AUX_DIGITAL
5790};
5791
5792uint32_t AudioFlinger::EffectModule::deviceAudioSystemToEffectApi(uint32_t device)
5793{
5794 uint32_t deviceOut = 0;
5795 while (device) {
5796 const uint32_t i = 31 - __builtin_clz(device);
5797 device &= ~(1 << i);
5798 if (i >= sizeof(sDeviceConvTable)/sizeof(uint32_t)) {
5799 LOGE("device convertion error for AudioSystem device 0x%08x", device);
5800 return 0;
5801 }
5802 deviceOut |= (uint32_t)sDeviceConvTable[i];
5803 }
5804 return deviceOut;
5805}
5806
5807// update this table when AudioSystem::audio_mode or audio_mode_e (in EffectApi.h) are modified
5808const uint32_t AudioFlinger::EffectModule::sModeConvTable[] = {
5809 AUDIO_MODE_NORMAL, // AudioSystem::MODE_NORMAL
5810 AUDIO_MODE_RINGTONE, // AudioSystem::MODE_RINGTONE
5811 AUDIO_MODE_IN_CALL // AudioSystem::MODE_IN_CALL
5812};
5813
5814int AudioFlinger::EffectModule::modeAudioSystemToEffectApi(uint32_t mode)
5815{
5816 int modeOut = -1;
5817 if (mode < sizeof(sModeConvTable) / sizeof(uint32_t)) {
5818 modeOut = (int)sModeConvTable[mode];
5819 }
5820 return modeOut;
5821}
Eric Laurent65b65452010-06-01 23:49:17 -07005822
5823status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
5824{
5825 const size_t SIZE = 256;
5826 char buffer[SIZE];
5827 String8 result;
5828
5829 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
5830 result.append(buffer);
5831
5832 bool locked = tryLock(mLock);
5833 // failed to lock - AudioFlinger is probably deadlocked
5834 if (!locked) {
5835 result.append("\t\tCould not lock Fx mutex:\n");
5836 }
5837
5838 result.append("\t\tSession Status State Engine:\n");
5839 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
5840 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
5841 result.append(buffer);
5842
5843 result.append("\t\tDescriptor:\n");
5844 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
5845 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
5846 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
5847 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
5848 result.append(buffer);
5849 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
5850 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
5851 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
5852 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
5853 result.append(buffer);
5854 snprintf(buffer, SIZE, "\t\t- apiVersion: %04X\n\t\t- flags: %08X\n",
5855 mDescriptor.apiVersion,
5856 mDescriptor.flags);
5857 result.append(buffer);
5858 snprintf(buffer, SIZE, "\t\t- name: %s\n",
5859 mDescriptor.name);
5860 result.append(buffer);
5861 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
5862 mDescriptor.implementor);
5863 result.append(buffer);
5864
5865 result.append("\t\t- Input configuration:\n");
5866 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
5867 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
5868 (uint32_t)mConfig.inputCfg.buffer.raw,
5869 mConfig.inputCfg.buffer.frameCount,
5870 mConfig.inputCfg.samplingRate,
5871 mConfig.inputCfg.channels,
5872 mConfig.inputCfg.format);
5873 result.append(buffer);
5874
5875 result.append("\t\t- Output configuration:\n");
5876 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
5877 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
5878 (uint32_t)mConfig.outputCfg.buffer.raw,
5879 mConfig.outputCfg.buffer.frameCount,
5880 mConfig.outputCfg.samplingRate,
5881 mConfig.outputCfg.channels,
5882 mConfig.outputCfg.format);
5883 result.append(buffer);
5884
5885 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
5886 result.append(buffer);
5887 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
5888 for (size_t i = 0; i < mHandles.size(); ++i) {
5889 sp<EffectHandle> handle = mHandles[i].promote();
5890 if (handle != 0) {
5891 handle->dump(buffer, SIZE);
5892 result.append(buffer);
5893 }
5894 }
5895
5896 result.append("\n");
5897
5898 write(fd, result.string(), result.length());
5899
5900 if (locked) {
5901 mLock.unlock();
5902 }
5903
5904 return NO_ERROR;
5905}
5906
5907// ----------------------------------------------------------------------------
5908// EffectHandle implementation
5909// ----------------------------------------------------------------------------
5910
5911#undef LOG_TAG
5912#define LOG_TAG "AudioFlinger::EffectHandle"
5913
5914AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
5915 const sp<AudioFlinger::Client>& client,
5916 const sp<IEffectClient>& effectClient,
5917 int32_t priority)
5918 : BnEffect(),
5919 mEffect(effect), mEffectClient(effectClient), mClient(client), mPriority(priority), mHasControl(false)
5920{
5921 LOGV("constructor %p", this);
5922
5923 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
5924 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
5925 if (mCblkMemory != 0) {
5926 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
5927
5928 if (mCblk) {
5929 new(mCblk) effect_param_cblk_t();
5930 mBuffer = (uint8_t *)mCblk + bufOffset;
5931 }
5932 } else {
5933 LOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
5934 return;
5935 }
5936}
5937
5938AudioFlinger::EffectHandle::~EffectHandle()
5939{
5940 LOGV("Destructor %p", this);
5941 disconnect();
5942}
5943
5944status_t AudioFlinger::EffectHandle::enable()
5945{
5946 if (!mHasControl) return INVALID_OPERATION;
5947 if (mEffect == 0) return DEAD_OBJECT;
5948
5949 return mEffect->setEnabled(true);
5950}
5951
5952status_t AudioFlinger::EffectHandle::disable()
5953{
5954 if (!mHasControl) return INVALID_OPERATION;
5955 if (mEffect == NULL) return DEAD_OBJECT;
5956
5957 return mEffect->setEnabled(false);
5958}
5959
5960void AudioFlinger::EffectHandle::disconnect()
5961{
5962 if (mEffect == 0) {
5963 return;
5964 }
5965 mEffect->disconnect(this);
5966 // release sp on module => module destructor can be called now
5967 mEffect.clear();
5968 if (mCblk) {
5969 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
5970 }
5971 mCblkMemory.clear(); // and free the shared memory
5972 if (mClient != 0) {
5973 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
5974 mClient.clear();
5975 }
5976}
5977
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005978status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
5979 uint32_t cmdSize,
5980 void *pCmdData,
5981 uint32_t *replySize,
5982 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07005983{
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005984// LOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
5985// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Eric Laurent65b65452010-06-01 23:49:17 -07005986
5987 // only get parameter command is permitted for applications not controlling the effect
5988 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
5989 return INVALID_OPERATION;
5990 }
5991 if (mEffect == 0) return DEAD_OBJECT;
5992
5993 // handle commands that are not forwarded transparently to effect engine
5994 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
5995 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
5996 // no risk to block the whole media server process or mixer threads is we are stuck here
5997 Mutex::Autolock _l(mCblk->lock);
5998 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
5999 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
6000 mCblk->serverIndex = 0;
6001 mCblk->clientIndex = 0;
6002 return BAD_VALUE;
6003 }
6004 status_t status = NO_ERROR;
6005 while (mCblk->serverIndex < mCblk->clientIndex) {
6006 int reply;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006007 uint32_t rsize = sizeof(int);
Eric Laurent65b65452010-06-01 23:49:17 -07006008 int *p = (int *)(mBuffer + mCblk->serverIndex);
6009 int size = *p++;
Eric Laurent53334cd2010-06-23 17:38:20 -07006010 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
6011 LOGW("command(): invalid parameter block size");
6012 break;
6013 }
Eric Laurent65b65452010-06-01 23:49:17 -07006014 effect_param_t *param = (effect_param_t *)p;
Eric Laurent53334cd2010-06-23 17:38:20 -07006015 if (param->psize == 0 || param->vsize == 0) {
6016 LOGW("command(): null parameter or value size");
6017 mCblk->serverIndex += size;
6018 continue;
6019 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006020 uint32_t psize = sizeof(effect_param_t) +
6021 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
6022 param->vsize;
6023 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
6024 psize,
6025 p,
6026 &rsize,
6027 &reply);
Eric Laurente65280c2010-09-02 11:56:55 -07006028 // stop at first error encountered
6029 if (ret != NO_ERROR) {
Eric Laurent65b65452010-06-01 23:49:17 -07006030 status = ret;
Eric Laurente65280c2010-09-02 11:56:55 -07006031 *(int *)pReplyData = reply;
6032 break;
6033 } else if (reply != NO_ERROR) {
6034 *(int *)pReplyData = reply;
6035 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006036 }
6037 mCblk->serverIndex += size;
6038 }
6039 mCblk->serverIndex = 0;
6040 mCblk->clientIndex = 0;
6041 return status;
6042 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurente65280c2010-09-02 11:56:55 -07006043 *(int *)pReplyData = NO_ERROR;
Eric Laurent65b65452010-06-01 23:49:17 -07006044 return enable();
6045 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurente65280c2010-09-02 11:56:55 -07006046 *(int *)pReplyData = NO_ERROR;
Eric Laurent65b65452010-06-01 23:49:17 -07006047 return disable();
6048 }
6049
6050 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
6051}
6052
6053sp<IMemory> AudioFlinger::EffectHandle::getCblk() const {
6054 return mCblkMemory;
6055}
6056
6057void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal)
6058{
6059 LOGV("setControl %p control %d", this, hasControl);
6060
6061 mHasControl = hasControl;
6062 if (signal && mEffectClient != 0) {
6063 mEffectClient->controlStatusChanged(hasControl);
6064 }
6065}
6066
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006067void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
6068 uint32_t cmdSize,
6069 void *pCmdData,
6070 uint32_t replySize,
6071 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07006072{
6073 if (mEffectClient != 0) {
6074 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
6075 }
6076}
6077
6078
6079
6080void AudioFlinger::EffectHandle::setEnabled(bool enabled)
6081{
6082 if (mEffectClient != 0) {
6083 mEffectClient->enableStatusChanged(enabled);
6084 }
6085}
6086
6087status_t AudioFlinger::EffectHandle::onTransact(
6088 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6089{
6090 return BnEffect::onTransact(code, data, reply, flags);
6091}
6092
6093
6094void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
6095{
6096 bool locked = tryLock(mCblk->lock);
6097
6098 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
6099 (mClient == NULL) ? getpid() : mClient->pid(),
6100 mPriority,
6101 mHasControl,
6102 !locked,
6103 mCblk->clientIndex,
6104 mCblk->serverIndex
6105 );
6106
6107 if (locked) {
6108 mCblk->lock.unlock();
6109 }
6110}
6111
6112#undef LOG_TAG
6113#define LOG_TAG "AudioFlinger::EffectChain"
6114
6115AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
6116 int sessionId)
Eric Laurent76c40f72010-07-15 12:50:15 -07006117 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mOwnInBuffer(false),
Eric Laurent2a6b80b2010-07-29 23:43:43 -07006118 mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
6119 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Eric Laurent65b65452010-06-01 23:49:17 -07006120{
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006121 mStrategy = AudioSystem::getStrategyForStream(AudioSystem::MUSIC);
Eric Laurent65b65452010-06-01 23:49:17 -07006122}
6123
6124AudioFlinger::EffectChain::~EffectChain()
6125{
6126 if (mOwnInBuffer) {
6127 delete mInBuffer;
6128 }
6129
6130}
6131
Eric Laurent76c40f72010-07-15 12:50:15 -07006132// getEffectFromDesc_l() must be called with PlaybackThread::mLock held
6133sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Eric Laurent65b65452010-06-01 23:49:17 -07006134{
6135 sp<EffectModule> effect;
6136 size_t size = mEffects.size();
6137
6138 for (size_t i = 0; i < size; i++) {
6139 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
6140 effect = mEffects[i];
6141 break;
6142 }
6143 }
6144 return effect;
6145}
6146
Eric Laurent76c40f72010-07-15 12:50:15 -07006147// getEffectFromId_l() must be called with PlaybackThread::mLock held
6148sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Eric Laurent65b65452010-06-01 23:49:17 -07006149{
6150 sp<EffectModule> effect;
6151 size_t size = mEffects.size();
6152
6153 for (size_t i = 0; i < size; i++) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006154 // by convention, return first effect if id provided is 0 (0 is never a valid id)
6155 if (id == 0 || mEffects[i]->id() == id) {
Eric Laurent65b65452010-06-01 23:49:17 -07006156 effect = mEffects[i];
6157 break;
6158 }
6159 }
6160 return effect;
6161}
6162
6163// Must be called with EffectChain::mLock locked
6164void AudioFlinger::EffectChain::process_l()
6165{
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07006166 sp<ThreadBase> thread = mThread.promote();
6167 if (thread == 0) {
6168 LOGW("process_l(): cannot promote mixer thread");
6169 return;
6170 }
6171 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
6172 bool isGlobalSession = (mSessionId == AudioSystem::SESSION_OUTPUT_MIX) ||
6173 (mSessionId == AudioSystem::SESSION_OUTPUT_STAGE);
6174 bool tracksOnSession = false;
6175 if (!isGlobalSession) {
6176 tracksOnSession =
6177 playbackThread->hasAudioSession(mSessionId) & PlaybackThread::TRACK_SESSION;
6178 }
6179
Eric Laurent65b65452010-06-01 23:49:17 -07006180 size_t size = mEffects.size();
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07006181 // do not process effect if no track is present in same audio session
6182 if (isGlobalSession || tracksOnSession) {
6183 for (size_t i = 0; i < size; i++) {
6184 mEffects[i]->process();
6185 }
Eric Laurent65b65452010-06-01 23:49:17 -07006186 }
Eric Laurent7d850f22010-07-09 13:34:17 -07006187 for (size_t i = 0; i < size; i++) {
6188 mEffects[i]->updateState();
6189 }
Eric Laurent65b65452010-06-01 23:49:17 -07006190 // if no track is active, input buffer must be cleared here as the mixer process
6191 // will not do it
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07006192 if (tracksOnSession &&
6193 activeTracks() == 0) {
6194 size_t numSamples = playbackThread->frameCount() * playbackThread->channelCount();
6195 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
Eric Laurent65b65452010-06-01 23:49:17 -07006196 }
6197}
6198
Eric Laurent76c40f72010-07-15 12:50:15 -07006199// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006200status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Eric Laurent65b65452010-06-01 23:49:17 -07006201{
6202 effect_descriptor_t desc = effect->desc();
6203 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
6204
6205 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006206 effect->setChain(this);
6207 sp<ThreadBase> thread = mThread.promote();
6208 if (thread == 0) {
6209 return NO_INIT;
6210 }
6211 effect->setThread(thread);
Eric Laurent65b65452010-06-01 23:49:17 -07006212
6213 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6214 // Auxiliary effects are inserted at the beginning of mEffects vector as
6215 // they are processed first and accumulated in chain input buffer
6216 mEffects.insertAt(effect, 0);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006217
Eric Laurent65b65452010-06-01 23:49:17 -07006218 // the input buffer for auxiliary effect contains mono samples in
6219 // 32 bit format. This is to avoid saturation in AudoMixer
6220 // accumulation stage. Saturation is done in EffectModule::process() before
6221 // calling the process in effect engine
6222 size_t numSamples = thread->frameCount();
6223 int32_t *buffer = new int32_t[numSamples];
6224 memset(buffer, 0, numSamples * sizeof(int32_t));
6225 effect->setInBuffer((int16_t *)buffer);
6226 // auxiliary effects output samples to chain input buffer for further processing
6227 // by insert effects
6228 effect->setOutBuffer(mInBuffer);
6229 } else {
6230 // Insert effects are inserted at the end of mEffects vector as they are processed
6231 // after track and auxiliary effects.
Eric Laurent53334cd2010-06-23 17:38:20 -07006232 // Insert effect order as a function of indicated preference:
6233 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
6234 // another effect is present
6235 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
6236 // last effect claiming first position
6237 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
6238 // first effect claiming last position
Eric Laurent65b65452010-06-01 23:49:17 -07006239 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
Eric Laurent53334cd2010-06-23 17:38:20 -07006240 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
6241 // already present
Eric Laurent65b65452010-06-01 23:49:17 -07006242
6243 int size = (int)mEffects.size();
6244 int idx_insert = size;
6245 int idx_insert_first = -1;
6246 int idx_insert_last = -1;
6247
6248 for (int i = 0; i < size; i++) {
6249 effect_descriptor_t d = mEffects[i]->desc();
6250 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
6251 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
6252 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
6253 // check invalid effect chaining combinations
6254 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
Eric Laurent53334cd2010-06-23 17:38:20 -07006255 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Eric Laurent76c40f72010-07-15 12:50:15 -07006256 LOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Eric Laurent65b65452010-06-01 23:49:17 -07006257 return INVALID_OPERATION;
6258 }
Eric Laurent53334cd2010-06-23 17:38:20 -07006259 // remember position of first insert effect and by default
6260 // select this as insert position for new effect
Eric Laurent65b65452010-06-01 23:49:17 -07006261 if (idx_insert == size) {
6262 idx_insert = i;
6263 }
Eric Laurent53334cd2010-06-23 17:38:20 -07006264 // remember position of last insert effect claiming
6265 // first position
Eric Laurent65b65452010-06-01 23:49:17 -07006266 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
6267 idx_insert_first = i;
6268 }
Eric Laurent53334cd2010-06-23 17:38:20 -07006269 // remember position of first insert effect claiming
6270 // last position
6271 if (iPref == EFFECT_FLAG_INSERT_LAST &&
6272 idx_insert_last == -1) {
Eric Laurent65b65452010-06-01 23:49:17 -07006273 idx_insert_last = i;
6274 }
6275 }
6276 }
6277
Eric Laurent53334cd2010-06-23 17:38:20 -07006278 // modify idx_insert from first position if needed
6279 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
6280 if (idx_insert_last != -1) {
6281 idx_insert = idx_insert_last;
6282 } else {
6283 idx_insert = size;
6284 }
6285 } else {
6286 if (idx_insert_first != -1) {
6287 idx_insert = idx_insert_first + 1;
6288 }
Eric Laurent65b65452010-06-01 23:49:17 -07006289 }
6290
6291 // always read samples from chain input buffer
6292 effect->setInBuffer(mInBuffer);
6293
6294 // if last effect in the chain, output samples to chain
6295 // output buffer, otherwise to chain input buffer
6296 if (idx_insert == size) {
6297 if (idx_insert != 0) {
6298 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
6299 mEffects[idx_insert-1]->configure();
6300 }
6301 effect->setOutBuffer(mOutBuffer);
6302 } else {
6303 effect->setOutBuffer(mInBuffer);
6304 }
Eric Laurent53334cd2010-06-23 17:38:20 -07006305 mEffects.insertAt(effect, idx_insert);
Eric Laurent65b65452010-06-01 23:49:17 -07006306
Eric Laurent76c40f72010-07-15 12:50:15 -07006307 LOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Eric Laurent65b65452010-06-01 23:49:17 -07006308 }
6309 effect->configure();
6310 return NO_ERROR;
6311}
6312
Eric Laurent76c40f72010-07-15 12:50:15 -07006313// removeEffect_l() must be called with PlaybackThread::mLock held
6314size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Eric Laurent65b65452010-06-01 23:49:17 -07006315{
6316 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07006317 int size = (int)mEffects.size();
6318 int i;
6319 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
6320
6321 for (i = 0; i < size; i++) {
6322 if (effect == mEffects[i]) {
6323 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
6324 delete[] effect->inBuffer();
6325 } else {
6326 if (i == size - 1 && i != 0) {
6327 mEffects[i - 1]->setOutBuffer(mOutBuffer);
6328 mEffects[i - 1]->configure();
6329 }
6330 }
6331 mEffects.removeAt(i);
Eric Laurent76c40f72010-07-15 12:50:15 -07006332 LOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Eric Laurent65b65452010-06-01 23:49:17 -07006333 break;
6334 }
6335 }
Eric Laurent65b65452010-06-01 23:49:17 -07006336
6337 return mEffects.size();
6338}
6339
Eric Laurent76c40f72010-07-15 12:50:15 -07006340// setDevice_l() must be called with PlaybackThread::mLock held
6341void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Eric Laurent65b65452010-06-01 23:49:17 -07006342{
6343 size_t size = mEffects.size();
6344 for (size_t i = 0; i < size; i++) {
6345 mEffects[i]->setDevice(device);
6346 }
6347}
6348
Eric Laurent76c40f72010-07-15 12:50:15 -07006349// setMode_l() must be called with PlaybackThread::mLock held
6350void AudioFlinger::EffectChain::setMode_l(uint32_t mode)
Eric Laurent53334cd2010-06-23 17:38:20 -07006351{
6352 size_t size = mEffects.size();
6353 for (size_t i = 0; i < size; i++) {
6354 mEffects[i]->setMode(mode);
6355 }
6356}
6357
Eric Laurent76c40f72010-07-15 12:50:15 -07006358// setVolume_l() must be called with PlaybackThread::mLock held
6359bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Eric Laurent65b65452010-06-01 23:49:17 -07006360{
6361 uint32_t newLeft = *left;
6362 uint32_t newRight = *right;
6363 bool hasControl = false;
Eric Laurent76c40f72010-07-15 12:50:15 -07006364 int ctrlIdx = -1;
6365 size_t size = mEffects.size();
Eric Laurent65b65452010-06-01 23:49:17 -07006366
Eric Laurent76c40f72010-07-15 12:50:15 -07006367 // first update volume controller
6368 for (size_t i = size; i > 0; i--) {
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006369 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurent76c40f72010-07-15 12:50:15 -07006370 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
6371 ctrlIdx = i - 1;
Eric Laurent0d7e0482010-07-19 06:24:46 -07006372 hasControl = true;
Eric Laurent76c40f72010-07-15 12:50:15 -07006373 break;
6374 }
6375 }
6376
6377 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurent0d7e0482010-07-19 06:24:46 -07006378 if (hasControl) {
6379 *left = mNewLeftVolume;
6380 *right = mNewRightVolume;
6381 }
6382 return hasControl;
Eric Laurent76c40f72010-07-15 12:50:15 -07006383 }
6384
6385 mVolumeCtrlIdx = ctrlIdx;
Eric Laurent0d7e0482010-07-19 06:24:46 -07006386 mLeftVolume = newLeft;
6387 mRightVolume = newRight;
Eric Laurent76c40f72010-07-15 12:50:15 -07006388
6389 // second get volume update from volume controller
6390 if (ctrlIdx >= 0) {
6391 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurent0d7e0482010-07-19 06:24:46 -07006392 mNewLeftVolume = newLeft;
6393 mNewRightVolume = newRight;
Eric Laurent65b65452010-06-01 23:49:17 -07006394 }
6395 // then indicate volume to all other effects in chain.
6396 // Pass altered volume to effects before volume controller
6397 // and requested volume to effects after controller
6398 uint32_t lVol = newLeft;
6399 uint32_t rVol = newRight;
Eric Laurent76c40f72010-07-15 12:50:15 -07006400
Eric Laurent65b65452010-06-01 23:49:17 -07006401 for (size_t i = 0; i < size; i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07006402 if ((int)i == ctrlIdx) continue;
6403 // this also works for ctrlIdx == -1 when there is no volume controller
6404 if ((int)i > ctrlIdx) {
Eric Laurent65b65452010-06-01 23:49:17 -07006405 lVol = *left;
6406 rVol = *right;
6407 }
6408 mEffects[i]->setVolume(&lVol, &rVol, false);
6409 }
6410 *left = newLeft;
6411 *right = newRight;
6412
6413 return hasControl;
6414}
6415
Eric Laurent65b65452010-06-01 23:49:17 -07006416status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
6417{
6418 const size_t SIZE = 256;
6419 char buffer[SIZE];
6420 String8 result;
6421
6422 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
6423 result.append(buffer);
6424
6425 bool locked = tryLock(mLock);
6426 // failed to lock - AudioFlinger is probably deadlocked
6427 if (!locked) {
6428 result.append("\tCould not lock mutex:\n");
6429 }
6430
Eric Laurent76c40f72010-07-15 12:50:15 -07006431 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
6432 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Eric Laurent65b65452010-06-01 23:49:17 -07006433 mEffects.size(),
6434 (uint32_t)mInBuffer,
6435 (uint32_t)mOutBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -07006436 mActiveTrackCnt);
6437 result.append(buffer);
6438 write(fd, result.string(), result.size());
6439
6440 for (size_t i = 0; i < mEffects.size(); ++i) {
6441 sp<EffectModule> effect = mEffects[i];
6442 if (effect != 0) {
6443 effect->dump(fd, args);
6444 }
6445 }
6446
6447 if (locked) {
6448 mLock.unlock();
6449 }
6450
6451 return NO_ERROR;
6452}
6453
6454#undef LOG_TAG
6455#define LOG_TAG "AudioFlinger"
6456
Eric Laurenta553c252009-07-17 12:17:14 -07006457// ----------------------------------------------------------------------------
6458
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07006459status_t AudioFlinger::onTransact(
6460 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6461{
6462 return BnAudioFlinger::onTransact(code, data, reply, flags);
6463}
6464
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07006465}; // namespace android