blob: 11ad4e468a9acd4a0caa15feaec3b09d71053364 [file] [log] [blame]
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001/* //device/include/server/AudioFlinger/AudioFlinger.cpp
2**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
Eric Laurent7d850f22010-07-09 13:34:17 -070020//#define LOG_NDEBUG 0
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070021
22#include <math.h>
23#include <signal.h>
24#include <sys/time.h>
25#include <sys/resource.h>
26
Mathias Agopian07952722009-05-19 19:08:10 -070027#include <binder/IServiceManager.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070028#include <utils/Log.h>
Mathias Agopian07952722009-05-19 19:08:10 -070029#include <binder/Parcel.h>
30#include <binder/IPCThreadState.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070031#include <utils/String16.h>
32#include <utils/threads.h>
33
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080034#include <cutils/properties.h>
35
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070036#include <media/AudioTrack.h>
37#include <media/AudioRecord.h>
38
39#include <private/media/AudioTrackShared.h>
Eric Laurent65b65452010-06-01 23:49:17 -070040#include <private/media/AudioEffectShared.h>
The Android Open Source Project9266c552009-01-15 16:12:10 -080041#include <hardware_legacy/AudioHardwareInterface.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070042
43#include "AudioMixer.h"
44#include "AudioFlinger.h"
45
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080046#ifdef WITH_A2DP
47#include "A2dpAudioInterface.h"
48#endif
49
Glenn Kasten871c16c2010-03-05 12:18:01 -080050#ifdef LVMX
51#include "lifevibes.h"
52#endif
53
Eric Laurent53334cd2010-06-23 17:38:20 -070054#include <media/EffectsFactoryApi.h>
Eric Laurentdf9b81c2010-07-02 08:12:41 -070055#include <media/EffectVisualizerApi.h>
Eric Laurent65b65452010-06-01 23:49:17 -070056
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057// ----------------------------------------------------------------------------
58// the sim build doesn't have gettid
59
60#ifndef HAVE_GETTID
61# define gettid getpid
62#endif
63
64// ----------------------------------------------------------------------------
65
Eric Laurent8ed6ed02010-07-13 04:45:46 -070066extern const char * const gEffectLibPath;
67
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070068namespace android {
69
The Android Open Source Project10592532009-03-18 17:39:46 -070070static const char* kDeadlockedString = "AudioFlinger may be deadlocked\n";
71static const char* kHardwareLockedString = "Hardware lock is taken\n";
72
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080073//static const nsecs_t kStandbyTimeInNsecs = seconds(3);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070074static const float MAX_GAIN = 4096.0f;
Eric Laurent65b65452010-06-01 23:49:17 -070075static const float MAX_GAIN_INT = 0x1000;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070076
77// retry counts for buffer fill timeout
78// 50 * ~20msecs = 1 second
79static const int8_t kMaxTrackRetries = 50;
80static const int8_t kMaxTrackStartupRetries = 50;
Eric Laurentef9500f2010-03-11 14:47:00 -080081// allow less retry attempts on direct output thread.
82// direct outputs can be a scarce resource in audio hardware and should
83// be released as quickly as possible.
84static const int8_t kMaxTrackRetriesDirect = 2;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070085
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -070086static const int kDumpLockRetries = 50;
87static const int kDumpLockSleep = 20000;
88
Dave Sparksd0ac8c02009-09-30 03:09:03 -070089static const nsecs_t kWarningThrottle = seconds(5);
90
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070092#define AUDIOFLINGER_SECURITY_ENABLED 1
93
94// ----------------------------------------------------------------------------
95
96static bool recordingAllowed() {
97#ifndef HAVE_ANDROID_OS
98 return true;
99#endif
100#if AUDIOFLINGER_SECURITY_ENABLED
101 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
102 bool ok = checkCallingPermission(String16("android.permission.RECORD_AUDIO"));
103 if (!ok) LOGE("Request requires android.permission.RECORD_AUDIO");
104 return ok;
105#else
106 if (!checkCallingPermission(String16("android.permission.RECORD_AUDIO")))
107 LOGW("WARNING: Need to add android.permission.RECORD_AUDIO to manifest");
108 return true;
109#endif
110}
111
112static bool settingsAllowed() {
113#ifndef HAVE_ANDROID_OS
114 return true;
115#endif
116#if AUDIOFLINGER_SECURITY_ENABLED
117 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
118 bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
119 if (!ok) LOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
120 return ok;
121#else
122 if (!checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS")))
123 LOGW("WARNING: Need to add android.permission.MODIFY_AUDIO_SETTINGS to manifest");
124 return true;
125#endif
126}
127
128// ----------------------------------------------------------------------------
129
130AudioFlinger::AudioFlinger()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800131 : BnAudioFlinger(),
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700132 mAudioHardware(0), mMasterVolume(1.0f), mMasterMute(false), mNextUniqueId(1)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700133{
Eric Laurent01635942011-01-18 18:39:02 -0800134 Mutex::Autolock _l(mLock);
135
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700136 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -0700137
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700138 mAudioHardware = AudioHardwareInterface::create();
Eric Laurenta553c252009-07-17 12:17:14 -0700139
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700140 mHardwareStatus = AUDIO_HW_INIT;
141 if (mAudioHardware->initCheck() == NO_ERROR) {
Eric Laurent01635942011-01-18 18:39:02 -0800142 AutoMutex lock(mHardwareLock);
Eric Laurent53334cd2010-06-23 17:38:20 -0700143 mMode = AudioSystem::MODE_NORMAL;
Eric Laurent01635942011-01-18 18:39:02 -0800144 mHardwareStatus = AUDIO_HW_SET_MODE;
145 mAudioHardware->setMode(mMode);
146 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
147 mAudioHardware->setMasterVolume(1.0f);
148 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -0700149 } else {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700150 LOGE("Couldn't even initialize the stubbed audio hardware!");
151 }
Glenn Kasten871c16c2010-03-05 12:18:01 -0800152#ifdef LVMX
153 LifeVibes::init();
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700154 mLifeVibesClientPid = -1;
Glenn Kasten871c16c2010-03-05 12:18:01 -0800155#endif
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700156}
157
158AudioFlinger::~AudioFlinger()
159{
Eric Laurent7954c462009-08-28 10:39:03 -0700160 while (!mRecordThreads.isEmpty()) {
161 // closeInput() will remove first entry from mRecordThreads
162 closeInput(mRecordThreads.keyAt(0));
163 }
164 while (!mPlaybackThreads.isEmpty()) {
165 // closeOutput() will remove first entry from mPlaybackThreads
166 closeOutput(mPlaybackThreads.keyAt(0));
167 }
168 if (mAudioHardware) {
169 delete mAudioHardware;
170 }
The Android Open Source Projectb7986892009-01-09 17:51:23 -0800171}
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800172
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700173
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700174
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700175status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
176{
177 const size_t SIZE = 256;
178 char buffer[SIZE];
179 String8 result;
180
181 result.append("Clients:\n");
182 for (size_t i = 0; i < mClients.size(); ++i) {
183 wp<Client> wClient = mClients.valueAt(i);
184 if (wClient != 0) {
185 sp<Client> client = wClient.promote();
186 if (client != 0) {
187 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
188 result.append(buffer);
189 }
190 }
191 }
192 write(fd, result.string(), result.size());
193 return NO_ERROR;
194}
195
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700196
197status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
198{
199 const size_t SIZE = 256;
200 char buffer[SIZE];
201 String8 result;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700202 int hardwareStatus = mHardwareStatus;
Eric Laurenta553c252009-07-17 12:17:14 -0700203
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700204 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700205 result.append(buffer);
206 write(fd, result.string(), result.size());
207 return NO_ERROR;
208}
209
210status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
211{
212 const size_t SIZE = 256;
213 char buffer[SIZE];
214 String8 result;
215 snprintf(buffer, SIZE, "Permission Denial: "
216 "can't dump AudioFlinger from pid=%d, uid=%d\n",
217 IPCThreadState::self()->getCallingPid(),
218 IPCThreadState::self()->getCallingUid());
219 result.append(buffer);
220 write(fd, result.string(), result.size());
221 return NO_ERROR;
222}
223
The Android Open Source Project10592532009-03-18 17:39:46 -0700224static bool tryLock(Mutex& mutex)
225{
226 bool locked = false;
227 for (int i = 0; i < kDumpLockRetries; ++i) {
228 if (mutex.tryLock() == NO_ERROR) {
229 locked = true;
230 break;
231 }
232 usleep(kDumpLockSleep);
233 }
234 return locked;
235}
236
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700237status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
238{
239 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
240 dumpPermissionDenial(fd, args);
241 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -0700242 // get state of hardware lock
243 bool hardwareLocked = tryLock(mHardwareLock);
244 if (!hardwareLocked) {
245 String8 result(kHardwareLockedString);
246 write(fd, result.string(), result.size());
247 } else {
248 mHardwareLock.unlock();
249 }
250
251 bool locked = tryLock(mLock);
252
253 // failed to lock - AudioFlinger is probably deadlocked
254 if (!locked) {
255 String8 result(kDeadlockedString);
256 write(fd, result.string(), result.size());
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700257 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700258
259 dumpClients(fd, args);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700260 dumpInternals(fd, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800261
Eric Laurenta553c252009-07-17 12:17:14 -0700262 // dump playback threads
263 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700264 mPlaybackThreads.valueAt(i)->dump(fd, args);
Eric Laurenta553c252009-07-17 12:17:14 -0700265 }
266
267 // dump record threads
Eric Laurent102313a2009-07-23 13:35:01 -0700268 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700269 mRecordThreads.valueAt(i)->dump(fd, args);
Eric Laurenta553c252009-07-17 12:17:14 -0700270 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800271
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700272 if (mAudioHardware) {
273 mAudioHardware->dumpState(fd, args);
274 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700275 if (locked) mLock.unlock();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700276 }
277 return NO_ERROR;
278}
279
Eric Laurenta553c252009-07-17 12:17:14 -0700280
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700281// IAudioFlinger interface
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800282
283
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700284sp<IAudioTrack> AudioFlinger::createTrack(
285 pid_t pid,
286 int streamType,
287 uint32_t sampleRate,
288 int format,
289 int channelCount,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800290 int frameCount,
291 uint32_t flags,
292 const sp<IMemory>& sharedBuffer,
Eric Laurentddb78e72009-07-28 08:44:33 -0700293 int output,
Eric Laurent65b65452010-06-01 23:49:17 -0700294 int *sessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800295 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700296{
Eric Laurenta553c252009-07-17 12:17:14 -0700297 sp<PlaybackThread::Track> track;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700298 sp<TrackHandle> trackHandle;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700299 sp<Client> client;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800300 wp<Client> wclient;
301 status_t lStatus;
Eric Laurent65b65452010-06-01 23:49:17 -0700302 int lSessionId;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700303
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800304 if (streamType >= AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800305 LOGE("invalid stream type");
306 lStatus = BAD_VALUE;
307 goto Exit;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700308 }
309
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800310 {
311 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700312 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent493941b2010-07-28 01:32:47 -0700313 PlaybackThread *effectThread = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -0700314 if (thread == NULL) {
315 LOGE("unknown output thread");
316 lStatus = BAD_VALUE;
317 goto Exit;
318 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800319
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800320 wclient = mClients.valueFor(pid);
321
322 if (wclient != NULL) {
323 client = wclient.promote();
324 } else {
325 client = new Client(this, pid);
326 mClients.add(pid, client);
327 }
Eric Laurent65b65452010-06-01 23:49:17 -0700328
Eric Laurent65b65452010-06-01 23:49:17 -0700329 LOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700330 if (sessionId != NULL && *sessionId != AudioSystem::SESSION_OUTPUT_MIX) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700331 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent493941b2010-07-28 01:32:47 -0700332 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
333 if (mPlaybackThreads.keyAt(i) != output) {
334 // prevent same audio session on different output threads
335 uint32_t sessions = t->hasAudioSession(*sessionId);
336 if (sessions & PlaybackThread::TRACK_SESSION) {
337 lStatus = BAD_VALUE;
338 goto Exit;
339 }
340 // check if an effect with same session ID is waiting for a track to be created
341 if (sessions & PlaybackThread::EFFECT_SESSION) {
342 effectThread = t.get();
343 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700344 }
345 }
Eric Laurent65b65452010-06-01 23:49:17 -0700346 lSessionId = *sessionId;
347 } else {
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700348 // if no audio session id is provided, create one here
Eric Laurentf3d6dd02010-11-18 08:40:16 -0800349 lSessionId = nextUniqueId_l();
Eric Laurent65b65452010-06-01 23:49:17 -0700350 if (sessionId != NULL) {
351 *sessionId = lSessionId;
352 }
353 }
354 LOGV("createTrack() lSessionId: %d", lSessionId);
355
Eric Laurenta553c252009-07-17 12:17:14 -0700356 track = thread->createTrack_l(client, streamType, sampleRate, format,
Eric Laurent65b65452010-06-01 23:49:17 -0700357 channelCount, frameCount, sharedBuffer, lSessionId, &lStatus);
Eric Laurent493941b2010-07-28 01:32:47 -0700358
359 // move effect chain to this output thread if an effect on same session was waiting
360 // for a track to be created
361 if (lStatus == NO_ERROR && effectThread != NULL) {
362 Mutex::Autolock _dl(thread->mLock);
363 Mutex::Autolock _sl(effectThread->mLock);
364 moveEffectChain_l(lSessionId, effectThread, thread, true);
365 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700366 }
367 if (lStatus == NO_ERROR) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800368 trackHandle = new TrackHandle(track);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700369 } else {
Eric Laurentb9481d82009-09-17 05:12:56 -0700370 // remove local strong reference to Client before deleting the Track so that the Client
371 // destructor is called by the TrackBase destructor with mLock held
372 client.clear();
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700373 track.clear();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800374 }
375
376Exit:
377 if(status) {
378 *status = lStatus;
379 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700380 return trackHandle;
381}
382
Eric Laurentddb78e72009-07-28 08:44:33 -0700383uint32_t AudioFlinger::sampleRate(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700384{
Eric Laurenta553c252009-07-17 12:17:14 -0700385 Mutex::Autolock _l(mLock);
386 PlaybackThread *thread = checkPlaybackThread_l(output);
387 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700388 LOGW("sampleRate() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700389 return 0;
390 }
391 return thread->sampleRate();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700392}
393
Eric Laurentddb78e72009-07-28 08:44:33 -0700394int AudioFlinger::channelCount(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700395{
Eric Laurenta553c252009-07-17 12:17:14 -0700396 Mutex::Autolock _l(mLock);
397 PlaybackThread *thread = checkPlaybackThread_l(output);
398 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700399 LOGW("channelCount() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700400 return 0;
401 }
402 return thread->channelCount();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700403}
404
Eric Laurentddb78e72009-07-28 08:44:33 -0700405int AudioFlinger::format(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700406{
Eric Laurenta553c252009-07-17 12:17:14 -0700407 Mutex::Autolock _l(mLock);
408 PlaybackThread *thread = checkPlaybackThread_l(output);
409 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700410 LOGW("format() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700411 return 0;
412 }
413 return thread->format();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700414}
415
Eric Laurentddb78e72009-07-28 08:44:33 -0700416size_t AudioFlinger::frameCount(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700417{
Eric Laurenta553c252009-07-17 12:17:14 -0700418 Mutex::Autolock _l(mLock);
419 PlaybackThread *thread = checkPlaybackThread_l(output);
420 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700421 LOGW("frameCount() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700422 return 0;
423 }
424 return thread->frameCount();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700425}
426
Eric Laurentddb78e72009-07-28 08:44:33 -0700427uint32_t AudioFlinger::latency(int output) const
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800428{
Eric Laurenta553c252009-07-17 12:17:14 -0700429 Mutex::Autolock _l(mLock);
430 PlaybackThread *thread = checkPlaybackThread_l(output);
431 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700432 LOGW("latency() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700433 return 0;
434 }
435 return thread->latency();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800436}
437
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700438status_t AudioFlinger::setMasterVolume(float value)
439{
440 // check calling permissions
441 if (!settingsAllowed()) {
442 return PERMISSION_DENIED;
443 }
444
445 // when hw supports master volume, don't scale in sw mixer
Eric Laurent01635942011-01-18 18:39:02 -0800446 { // scope for the lock
447 AutoMutex lock(mHardwareLock);
448 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
449 if (mAudioHardware->setMasterVolume(value) == NO_ERROR) {
450 value = 1.0f;
451 }
452 mHardwareStatus = AUDIO_HW_IDLE;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700453 }
Eric Laurenta553c252009-07-17 12:17:14 -0700454
Eric Laurent01635942011-01-18 18:39:02 -0800455 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700456 mMasterVolume = value;
457 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700458 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700459
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700460 return NO_ERROR;
461}
462
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700463status_t AudioFlinger::setMode(int mode)
464{
Eric Laurent53334cd2010-06-23 17:38:20 -0700465 status_t ret;
466
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700467 // check calling permissions
468 if (!settingsAllowed()) {
469 return PERMISSION_DENIED;
470 }
471 if ((mode < 0) || (mode >= AudioSystem::NUM_MODES)) {
472 LOGW("Illegal value: setMode(%d)", mode);
473 return BAD_VALUE;
474 }
475
Eric Laurent53334cd2010-06-23 17:38:20 -0700476 { // scope for the lock
477 AutoMutex lock(mHardwareLock);
478 mHardwareStatus = AUDIO_HW_SET_MODE;
479 ret = mAudioHardware->setMode(mode);
480 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten871c16c2010-03-05 12:18:01 -0800481 }
Eric Laurent53334cd2010-06-23 17:38:20 -0700482
483 if (NO_ERROR == ret) {
484 Mutex::Autolock _l(mLock);
485 mMode = mode;
486 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
487 mPlaybackThreads.valueAt(i)->setMode(mode);
488#ifdef LVMX
489 LifeVibes::setMode(mode);
Glenn Kasten871c16c2010-03-05 12:18:01 -0800490#endif
Eric Laurent53334cd2010-06-23 17:38:20 -0700491 }
492
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700493 return ret;
494}
495
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700496status_t AudioFlinger::setMicMute(bool state)
497{
498 // check calling permissions
499 if (!settingsAllowed()) {
500 return PERMISSION_DENIED;
501 }
502
503 AutoMutex lock(mHardwareLock);
504 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
505 status_t ret = mAudioHardware->setMicMute(state);
506 mHardwareStatus = AUDIO_HW_IDLE;
507 return ret;
508}
509
510bool AudioFlinger::getMicMute() const
511{
512 bool state = AudioSystem::MODE_INVALID;
513 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
514 mAudioHardware->getMicMute(&state);
515 mHardwareStatus = AUDIO_HW_IDLE;
516 return state;
517}
518
519status_t AudioFlinger::setMasterMute(bool muted)
520{
521 // check calling permissions
522 if (!settingsAllowed()) {
523 return PERMISSION_DENIED;
524 }
Eric Laurenta553c252009-07-17 12:17:14 -0700525
Eric Laurent01635942011-01-18 18:39:02 -0800526 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700527 mMasterMute = muted;
528 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700529 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Eric Laurenta553c252009-07-17 12:17:14 -0700530
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700531 return NO_ERROR;
532}
533
534float AudioFlinger::masterVolume() const
535{
Eric Laurenta553c252009-07-17 12:17:14 -0700536 return mMasterVolume;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700537}
538
539bool AudioFlinger::masterMute() const
540{
Eric Laurenta553c252009-07-17 12:17:14 -0700541 return mMasterMute;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700542}
543
Eric Laurentddb78e72009-07-28 08:44:33 -0700544status_t AudioFlinger::setStreamVolume(int stream, float value, int output)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700545{
546 // check calling permissions
547 if (!settingsAllowed()) {
548 return PERMISSION_DENIED;
549 }
550
Eric Laurenta553c252009-07-17 12:17:14 -0700551 if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700552 return BAD_VALUE;
553 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800554
Eric Laurenta553c252009-07-17 12:17:14 -0700555 AutoMutex lock(mLock);
556 PlaybackThread *thread = NULL;
557 if (output) {
558 thread = checkPlaybackThread_l(output);
559 if (thread == NULL) {
560 return BAD_VALUE;
561 }
562 }
563
Eric Laurenta553c252009-07-17 12:17:14 -0700564 mStreamTypes[stream].volume = value;
565
566 if (thread == NULL) {
Eric Laurent415f3e22009-10-21 08:14:22 -0700567 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700568 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Eric Laurent415f3e22009-10-21 08:14:22 -0700569 }
Eric Laurenta553c252009-07-17 12:17:14 -0700570 } else {
571 thread->setStreamVolume(stream, value);
572 }
Eric Laurentef028272009-04-21 07:56:33 -0700573
Eric Laurent415f3e22009-10-21 08:14:22 -0700574 return NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700575}
576
577status_t AudioFlinger::setStreamMute(int stream, bool muted)
578{
579 // check calling permissions
580 if (!settingsAllowed()) {
581 return PERMISSION_DENIED;
582 }
583
Eric Laurenta553c252009-07-17 12:17:14 -0700584 if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES ||
Eric Laurenteeea9222009-03-26 01:57:59 -0700585 uint32_t(stream) == AudioSystem::ENFORCED_AUDIBLE) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700586 return BAD_VALUE;
587 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700588
Eric Laurent01635942011-01-18 18:39:02 -0800589 AutoMutex lock(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700590 mStreamTypes[stream].mute = muted;
591 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700592 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800593
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700594 return NO_ERROR;
595}
596
Eric Laurentddb78e72009-07-28 08:44:33 -0700597float AudioFlinger::streamVolume(int stream, int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700598{
Eric Laurenta553c252009-07-17 12:17:14 -0700599 if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700600 return 0.0f;
601 }
Eric Laurenta553c252009-07-17 12:17:14 -0700602
603 AutoMutex lock(mLock);
604 float volume;
605 if (output) {
606 PlaybackThread *thread = checkPlaybackThread_l(output);
607 if (thread == NULL) {
608 return 0.0f;
609 }
610 volume = thread->streamVolume(stream);
611 } else {
612 volume = mStreamTypes[stream].volume;
613 }
614
Eric Laurentef028272009-04-21 07:56:33 -0700615 return volume;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700616}
617
618bool AudioFlinger::streamMute(int stream) const
619{
Eric Laurenta553c252009-07-17 12:17:14 -0700620 if (stream < 0 || stream >= (int)AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700621 return true;
622 }
Eric Laurenta553c252009-07-17 12:17:14 -0700623
624 return mStreamTypes[stream].mute;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700625}
626
Eric Laurent23f25cd2010-01-25 08:49:09 -0800627bool AudioFlinger::isStreamActive(int stream) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700628{
Eric Laurent4e646332009-07-09 03:20:57 -0700629 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700630 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent23f25cd2010-01-25 08:49:09 -0800631 if (mPlaybackThreads.valueAt(i)->isStreamActive(stream)) {
Eric Laurenta553c252009-07-17 12:17:14 -0700632 return true;
633 }
634 }
635 return false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700636}
637
Eric Laurentddb78e72009-07-28 08:44:33 -0700638status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700639{
Eric Laurenta553c252009-07-17 12:17:14 -0700640 status_t result;
641
Eric Laurentddb78e72009-07-28 08:44:33 -0700642 LOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
Eric Laurenta553c252009-07-17 12:17:14 -0700643 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
644 // check calling permissions
645 if (!settingsAllowed()) {
646 return PERMISSION_DENIED;
The Android Open Source Project9266c552009-01-15 16:12:10 -0800647 }
Eric Laurenta553c252009-07-17 12:17:14 -0700648
Glenn Kasten871c16c2010-03-05 12:18:01 -0800649#ifdef LVMX
650 AudioParameter param = AudioParameter(keyValuePairs);
651 LifeVibes::setParameters(ioHandle,keyValuePairs);
652 String8 key = String8(AudioParameter::keyRouting);
653 int device;
654 if (NO_ERROR != param.getInt(key, device)) {
655 device = -1;
656 }
657
658 key = String8(LifevibesTag);
659 String8 value;
660 int musicEnabled = -1;
661 if (NO_ERROR == param.get(key, value)) {
662 if (value == LifevibesEnable) {
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700663 mLifeVibesClientPid = IPCThreadState::self()->getCallingPid();
Glenn Kasten871c16c2010-03-05 12:18:01 -0800664 musicEnabled = 1;
665 } else if (value == LifevibesDisable) {
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700666 mLifeVibesClientPid = -1;
Glenn Kasten871c16c2010-03-05 12:18:01 -0800667 musicEnabled = 0;
668 }
669 }
670#endif
671
Eric Laurenta553c252009-07-17 12:17:14 -0700672 // ioHandle == 0 means the parameters are global to the audio hardware interface
673 if (ioHandle == 0) {
674 AutoMutex lock(mHardwareLock);
675 mHardwareStatus = AUDIO_SET_PARAMETER;
676 result = mAudioHardware->setParameters(keyValuePairs);
Glenn Kasten871c16c2010-03-05 12:18:01 -0800677#ifdef LVMX
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700678 if (musicEnabled != -1) {
Glenn Kasten871c16c2010-03-05 12:18:01 -0800679 LifeVibes::enableMusic((bool) musicEnabled);
680 }
681#endif
Eric Laurenta553c252009-07-17 12:17:14 -0700682 mHardwareStatus = AUDIO_HW_IDLE;
683 return result;
684 }
685
Eric Laurentb7d94602009-09-29 11:12:57 -0700686 // hold a strong ref on thread in case closeOutput() or closeInput() is called
687 // and the thread is exited once the lock is released
688 sp<ThreadBase> thread;
689 {
690 Mutex::Autolock _l(mLock);
691 thread = checkPlaybackThread_l(ioHandle);
692 if (thread == NULL) {
693 thread = checkRecordThread_l(ioHandle);
694 }
Eric Laurenta553c252009-07-17 12:17:14 -0700695 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700696 if (thread != NULL) {
Glenn Kasten871c16c2010-03-05 12:18:01 -0800697 result = thread->setParameters(keyValuePairs);
698#ifdef LVMX
699 if ((NO_ERROR == result) && (device != -1)) {
700 LifeVibes::setDevice(LifeVibes::threadIdToAudioOutputType(thread->id()), device);
701 }
702#endif
703 return result;
Eric Laurenta553c252009-07-17 12:17:14 -0700704 }
Eric Laurenta553c252009-07-17 12:17:14 -0700705 return BAD_VALUE;
706}
707
Eric Laurentddb78e72009-07-28 08:44:33 -0700708String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
Eric Laurenta553c252009-07-17 12:17:14 -0700709{
Eric Laurentddb78e72009-07-28 08:44:33 -0700710// LOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
Eric Laurenta553c252009-07-17 12:17:14 -0700711// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
712
713 if (ioHandle == 0) {
714 return mAudioHardware->getParameters(keys);
715 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700716
717 Mutex::Autolock _l(mLock);
718
Eric Laurenta553c252009-07-17 12:17:14 -0700719 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
720 if (playbackThread != NULL) {
721 return playbackThread->getParameters(keys);
722 }
723 RecordThread *recordThread = checkRecordThread_l(ioHandle);
724 if (recordThread != NULL) {
725 return recordThread->getParameters(keys);
726 }
727 return String8("");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700728}
729
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800730size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
731{
732 return mAudioHardware->getInputBufferSize(sampleRate, format, channelCount);
733}
734
Eric Laurent47d0a922010-02-26 02:47:27 -0800735unsigned int AudioFlinger::getInputFramesLost(int ioHandle)
736{
737 if (ioHandle == 0) {
738 return 0;
739 }
740
741 Mutex::Autolock _l(mLock);
742
743 RecordThread *recordThread = checkRecordThread_l(ioHandle);
744 if (recordThread != NULL) {
745 return recordThread->getInputFramesLost();
746 }
747 return 0;
748}
749
Eric Laurent415f3e22009-10-21 08:14:22 -0700750status_t AudioFlinger::setVoiceVolume(float value)
751{
752 // check calling permissions
753 if (!settingsAllowed()) {
754 return PERMISSION_DENIED;
755 }
756
757 AutoMutex lock(mHardwareLock);
758 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
759 status_t ret = mAudioHardware->setVoiceVolume(value);
760 mHardwareStatus = AUDIO_HW_IDLE;
761
762 return ret;
763}
764
Eric Laurent0986e792010-01-19 17:37:09 -0800765status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int output)
766{
767 status_t status;
768
769 Mutex::Autolock _l(mLock);
770
771 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
772 if (playbackThread != NULL) {
773 return playbackThread->getRenderPosition(halFrames, dspFrames);
774 }
775
776 return BAD_VALUE;
777}
778
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800779void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
780{
Eric Laurenta553c252009-07-17 12:17:14 -0700781
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800782 Mutex::Autolock _l(mLock);
783
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700784 int pid = IPCThreadState::self()->getCallingPid();
785 if (mNotificationClients.indexOfKey(pid) < 0) {
786 sp<NotificationClient> notificationClient = new NotificationClient(this,
787 client,
788 pid);
789 LOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Eric Laurenta553c252009-07-17 12:17:14 -0700790
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700791 mNotificationClients.add(pid, notificationClient);
Eric Laurenta553c252009-07-17 12:17:14 -0700792
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700793 sp<IBinder> binder = client->asBinder();
794 binder->linkToDeath(notificationClient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800795
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700796 // the config change is always sent from playback or record threads to avoid deadlock
797 // with AudioSystem::gLock
798 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
799 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
800 }
Eric Laurenta553c252009-07-17 12:17:14 -0700801
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700802 for (size_t i = 0; i < mRecordThreads.size(); i++) {
803 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800804 }
805 }
806}
807
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700808void AudioFlinger::removeNotificationClient(pid_t pid)
809{
810 Mutex::Autolock _l(mLock);
811
812 int index = mNotificationClients.indexOfKey(pid);
813 if (index >= 0) {
814 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
815 LOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
816#ifdef LVMX
817 if (pid == mLifeVibesClientPid) {
818 LOGV("Disabling lifevibes");
819 LifeVibes::enableMusic(false);
820 mLifeVibesClientPid = -1;
821 }
822#endif
823 mNotificationClients.removeItem(pid);
824 }
825}
826
Eric Laurent296a0ec2009-09-15 07:10:12 -0700827// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700828void AudioFlinger::audioConfigChanged_l(int event, int ioHandle, void *param2)
829{
Eric Laurent49f02be2009-11-19 09:00:56 -0800830 size_t size = mNotificationClients.size();
831 for (size_t i = 0; i < size; i++) {
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700832 mNotificationClients.valueAt(i)->client()->ioConfigChanged(event, ioHandle, param2);
Eric Laurenta553c252009-07-17 12:17:14 -0700833 }
834}
835
Eric Laurentb9481d82009-09-17 05:12:56 -0700836// removeClient_l() must be called with AudioFlinger::mLock held
837void AudioFlinger::removeClient_l(pid_t pid)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700838{
Eric Laurentb9481d82009-09-17 05:12:56 -0700839 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 -0700840 mClients.removeItem(pid);
841}
842
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700843
Eric Laurenta553c252009-07-17 12:17:14 -0700844// ----------------------------------------------------------------------------
845
Eric Laurent49f02be2009-11-19 09:00:56 -0800846AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, int id)
Eric Laurenta553c252009-07-17 12:17:14 -0700847 : Thread(false),
848 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
Eric Laurentb0a01472010-05-14 05:45:46 -0700849 mFrameSize(1), mFormat(0), mStandby(false), mId(id), mExiting(false)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700850{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800851}
852
Eric Laurenta553c252009-07-17 12:17:14 -0700853AudioFlinger::ThreadBase::~ThreadBase()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800854{
Eric Laurent8fce46a2009-08-04 09:45:33 -0700855 mParamCond.broadcast();
856 mNewParameters.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800857}
858
Eric Laurenta553c252009-07-17 12:17:14 -0700859void AudioFlinger::ThreadBase::exit()
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700860{
Eric Laurentb7d94602009-09-29 11:12:57 -0700861 // keep a strong ref on ourself so that we wont get
Eric Laurenta553c252009-07-17 12:17:14 -0700862 // destroyed in the middle of requestExitAndWait()
863 sp <ThreadBase> strongMe = this;
864
865 LOGV("ThreadBase::exit");
866 {
867 AutoMutex lock(&mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -0800868 mExiting = true;
Eric Laurenta553c252009-07-17 12:17:14 -0700869 requestExit();
870 mWaitWorkCV.signal();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700871 }
Eric Laurenta553c252009-07-17 12:17:14 -0700872 requestExitAndWait();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700873}
Eric Laurenta553c252009-07-17 12:17:14 -0700874
875uint32_t AudioFlinger::ThreadBase::sampleRate() const
876{
877 return mSampleRate;
878}
879
880int AudioFlinger::ThreadBase::channelCount() const
881{
Eric Laurentb0a01472010-05-14 05:45:46 -0700882 return (int)mChannelCount;
Eric Laurenta553c252009-07-17 12:17:14 -0700883}
884
885int AudioFlinger::ThreadBase::format() const
886{
887 return mFormat;
888}
889
890size_t AudioFlinger::ThreadBase::frameCount() const
891{
892 return mFrameCount;
893}
894
895status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
896{
Eric Laurent8fce46a2009-08-04 09:45:33 -0700897 status_t status;
Eric Laurenta553c252009-07-17 12:17:14 -0700898
Eric Laurent8fce46a2009-08-04 09:45:33 -0700899 LOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Eric Laurenta553c252009-07-17 12:17:14 -0700900 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700901
Eric Laurent8fce46a2009-08-04 09:45:33 -0700902 mNewParameters.add(keyValuePairs);
Eric Laurenta553c252009-07-17 12:17:14 -0700903 mWaitWorkCV.signal();
Eric Laurentb7d94602009-09-29 11:12:57 -0700904 // wait condition with timeout in case the thread loop has exited
905 // before the request could be processed
906 if (mParamCond.waitRelative(mLock, seconds(2)) == NO_ERROR) {
907 status = mParamStatus;
908 mWaitWorkCV.signal();
909 } else {
910 status = TIMED_OUT;
911 }
Eric Laurent8fce46a2009-08-04 09:45:33 -0700912 return status;
Eric Laurenta553c252009-07-17 12:17:14 -0700913}
914
915void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
916{
917 Mutex::Autolock _l(mLock);
Eric Laurent8fce46a2009-08-04 09:45:33 -0700918 sendConfigEvent_l(event, param);
919}
920
921// sendConfigEvent_l() must be called with ThreadBase::mLock held
922void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
923{
Eric Laurenta553c252009-07-17 12:17:14 -0700924 ConfigEvent *configEvent = new ConfigEvent();
925 configEvent->mEvent = event;
926 configEvent->mParam = param;
927 mConfigEvents.add(configEvent);
928 LOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
929 mWaitWorkCV.signal();
930}
931
932void AudioFlinger::ThreadBase::processConfigEvents()
933{
934 mLock.lock();
935 while(!mConfigEvents.isEmpty()) {
936 LOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
937 ConfigEvent *configEvent = mConfigEvents[0];
938 mConfigEvents.removeAt(0);
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700939 // release mLock before locking AudioFlinger mLock: lock order is always
940 // AudioFlinger then ThreadBase to avoid cross deadlock
Eric Laurenta553c252009-07-17 12:17:14 -0700941 mLock.unlock();
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700942 mAudioFlinger->mLock.lock();
943 audioConfigChanged_l(configEvent->mEvent, configEvent->mParam);
944 mAudioFlinger->mLock.unlock();
Eric Laurenta553c252009-07-17 12:17:14 -0700945 delete configEvent;
946 mLock.lock();
947 }
948 mLock.unlock();
949}
950
Eric Laurent3fdb1262009-11-07 00:01:32 -0800951status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
952{
953 const size_t SIZE = 256;
954 char buffer[SIZE];
955 String8 result;
956
957 bool locked = tryLock(mLock);
958 if (!locked) {
959 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
960 write(fd, buffer, strlen(buffer));
961 }
962
963 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
964 result.append(buffer);
965 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
966 result.append(buffer);
967 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
968 result.append(buffer);
969 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
970 result.append(buffer);
971 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
972 result.append(buffer);
973 snprintf(buffer, SIZE, "Frame size: %d\n", mFrameSize);
974 result.append(buffer);
975
976 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
977 result.append(buffer);
978 result.append(" Index Command");
979 for (size_t i = 0; i < mNewParameters.size(); ++i) {
980 snprintf(buffer, SIZE, "\n %02d ", i);
981 result.append(buffer);
982 result.append(mNewParameters[i]);
983 }
984
985 snprintf(buffer, SIZE, "\n\nPending config events: \n");
986 result.append(buffer);
987 snprintf(buffer, SIZE, " Index event param\n");
988 result.append(buffer);
989 for (size_t i = 0; i < mConfigEvents.size(); i++) {
990 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i]->mEvent, mConfigEvents[i]->mParam);
991 result.append(buffer);
992 }
993 result.append("\n");
994
995 write(fd, result.string(), result.size());
996
997 if (locked) {
998 mLock.unlock();
999 }
1000 return NO_ERROR;
1001}
1002
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001003
1004// ----------------------------------------------------------------------------
1005
Eric Laurent65b65452010-06-01 23:49:17 -07001006AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Eric Laurent49f02be2009-11-19 09:00:56 -08001007 : ThreadBase(audioFlinger, id),
Eric Laurentd5603c12009-08-06 08:49:39 -07001008 mMixBuffer(0), mSuspended(0), mBytesWritten(0), mOutput(output),
Eric Laurent65b65452010-06-01 23:49:17 -07001009 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1010 mDevice(device)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001011{
Eric Laurenta553c252009-07-17 12:17:14 -07001012 readOutputParameters();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001013
Eric Laurenta553c252009-07-17 12:17:14 -07001014 mMasterVolume = mAudioFlinger->masterVolume();
1015 mMasterMute = mAudioFlinger->masterMute();
1016
1017 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
1018 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
1019 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001020 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001021}
1022
Eric Laurenta553c252009-07-17 12:17:14 -07001023AudioFlinger::PlaybackThread::~PlaybackThread()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001024{
1025 delete [] mMixBuffer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001026}
1027
Eric Laurenta553c252009-07-17 12:17:14 -07001028status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001029{
1030 dumpInternals(fd, args);
1031 dumpTracks(fd, args);
Eric Laurent65b65452010-06-01 23:49:17 -07001032 dumpEffectChains(fd, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001033 return NO_ERROR;
1034}
1035
Eric Laurenta553c252009-07-17 12:17:14 -07001036status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001037{
1038 const size_t SIZE = 256;
1039 char buffer[SIZE];
1040 String8 result;
1041
Eric Laurenta553c252009-07-17 12:17:14 -07001042 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001043 result.append(buffer);
Eric Laurent65b65452010-06-01 23:49:17 -07001044 result.append(" Name Clien Typ Fmt Chn Session Buf S M F SRate LeftV RighV Serv User Main buf Aux Buf\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001045 for (size_t i = 0; i < mTracks.size(); ++i) {
Eric Laurentd3b4d0c2009-03-31 14:34:35 -07001046 sp<Track> track = mTracks[i];
1047 if (track != 0) {
1048 track->dump(buffer, SIZE);
1049 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001050 }
1051 }
1052
Eric Laurenta553c252009-07-17 12:17:14 -07001053 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054 result.append(buffer);
Eric Laurent65b65452010-06-01 23:49:17 -07001055 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 -08001056 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Eric Laurentd3b4d0c2009-03-31 14:34:35 -07001057 wp<Track> wTrack = mActiveTracks[i];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001058 if (wTrack != 0) {
1059 sp<Track> track = wTrack.promote();
1060 if (track != 0) {
1061 track->dump(buffer, SIZE);
1062 result.append(buffer);
1063 }
1064 }
1065 }
1066 write(fd, result.string(), result.size());
1067 return NO_ERROR;
1068}
1069
Eric Laurent65b65452010-06-01 23:49:17 -07001070status_t AudioFlinger::PlaybackThread::dumpEffectChains(int fd, const Vector<String16>& args)
1071{
1072 const size_t SIZE = 256;
1073 char buffer[SIZE];
1074 String8 result;
1075
1076 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1077 write(fd, buffer, strlen(buffer));
1078
1079 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1080 sp<EffectChain> chain = mEffectChains[i];
1081 if (chain != 0) {
1082 chain->dump(fd, args);
1083 }
1084 }
1085 return NO_ERROR;
1086}
1087
Eric Laurenta553c252009-07-17 12:17:14 -07001088status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001089{
1090 const size_t SIZE = 256;
1091 char buffer[SIZE];
1092 String8 result;
1093
Eric Laurent3fdb1262009-11-07 00:01:32 -08001094 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001095 result.append(buffer);
1096 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1097 result.append(buffer);
1098 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1099 result.append(buffer);
1100 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1101 result.append(buffer);
1102 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1103 result.append(buffer);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08001104 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1105 result.append(buffer);
Eric Laurent65b65452010-06-01 23:49:17 -07001106 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1107 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001108 write(fd, result.string(), result.size());
Eric Laurent3fdb1262009-11-07 00:01:32 -08001109
1110 dumpBase(fd, args);
1111
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001112 return NO_ERROR;
1113}
1114
1115// Thread virtuals
Eric Laurenta553c252009-07-17 12:17:14 -07001116status_t AudioFlinger::PlaybackThread::readyToRun()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001117{
1118 if (mSampleRate == 0) {
1119 LOGE("No working audio driver found.");
1120 return NO_INIT;
1121 }
Eric Laurenta553c252009-07-17 12:17:14 -07001122 LOGI("AudioFlinger's thread %p ready to run", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001123 return NO_ERROR;
1124}
1125
Eric Laurenta553c252009-07-17 12:17:14 -07001126void AudioFlinger::PlaybackThread::onFirstRef()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001127{
1128 const size_t SIZE = 256;
1129 char buffer[SIZE];
1130
Eric Laurenta553c252009-07-17 12:17:14 -07001131 snprintf(buffer, SIZE, "Playback Thread %p", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001132
1133 run(buffer, ANDROID_PRIORITY_URGENT_AUDIO);
1134}
1135
Eric Laurenta553c252009-07-17 12:17:14 -07001136// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1137sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001138 const sp<AudioFlinger::Client>& client,
1139 int streamType,
1140 uint32_t sampleRate,
1141 int format,
1142 int channelCount,
1143 int frameCount,
1144 const sp<IMemory>& sharedBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -07001145 int sessionId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001146 status_t *status)
1147{
1148 sp<Track> track;
1149 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07001150
1151 if (mType == DIRECT) {
Eric Laurentb0a01472010-05-14 05:45:46 -07001152 if (sampleRate != mSampleRate || format != mFormat || channelCount != (int)mChannelCount) {
Eric Laurenta553c252009-07-17 12:17:14 -07001153 LOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelCount %d for output %p",
1154 sampleRate, format, channelCount, mOutput);
1155 lStatus = BAD_VALUE;
1156 goto Exit;
1157 }
1158 } else {
1159 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1160 if (sampleRate > mSampleRate*2) {
1161 LOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
1162 lStatus = BAD_VALUE;
1163 goto Exit;
1164 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001165 }
1166
Eric Laurenta553c252009-07-17 12:17:14 -07001167 if (mOutput == 0) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001168 LOGE("Audio driver not initialized.");
1169 lStatus = NO_INIT;
1170 goto Exit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001171 }
1172
Eric Laurenta553c252009-07-17 12:17:14 -07001173 { // scope for mLock
1174 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001175
1176 // all tracks in same audio session must share the same routing strategy otherwise
1177 // conflicts will happen when tracks are moved from one output to another by audio policy
1178 // manager
1179 uint32_t strategy =
1180 AudioSystem::getStrategyForStream((AudioSystem::stream_type)streamType);
1181 for (size_t i = 0; i < mTracks.size(); ++i) {
1182 sp<Track> t = mTracks[i];
1183 if (t != 0) {
1184 if (sessionId == t->sessionId() &&
1185 strategy != AudioSystem::getStrategyForStream((AudioSystem::stream_type)t->type())) {
1186 lStatus = BAD_VALUE;
1187 goto Exit;
1188 }
1189 }
1190 }
1191
Eric Laurenta553c252009-07-17 12:17:14 -07001192 track = new Track(this, client, streamType, sampleRate, format,
Eric Laurent65b65452010-06-01 23:49:17 -07001193 channelCount, frameCount, sharedBuffer, sessionId);
Eric Laurent73b60352009-11-09 04:45:39 -08001194 if (track->getCblk() == NULL || track->name() < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07001195 lStatus = NO_MEMORY;
1196 goto Exit;
1197 }
1198 mTracks.add(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001199
1200 sp<EffectChain> chain = getEffectChain_l(sessionId);
1201 if (chain != 0) {
1202 LOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1203 track->setMainBuffer(chain->inBuffer());
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001204 chain->setStrategy(AudioSystem::getStrategyForStream((AudioSystem::stream_type)track->type()));
Eric Laurent65b65452010-06-01 23:49:17 -07001205 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001206 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001207 lStatus = NO_ERROR;
1208
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001209Exit:
1210 if(status) {
1211 *status = lStatus;
1212 }
1213 return track;
1214}
1215
Eric Laurenta553c252009-07-17 12:17:14 -07001216uint32_t AudioFlinger::PlaybackThread::latency() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001217{
1218 if (mOutput) {
1219 return mOutput->latency();
1220 }
1221 else {
1222 return 0;
1223 }
1224}
1225
Eric Laurenta553c252009-07-17 12:17:14 -07001226status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001227{
Glenn Kasten871c16c2010-03-05 12:18:01 -08001228#ifdef LVMX
1229 int audioOutputType = LifeVibes::getMixerType(mId, mType);
1230 if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType)) {
1231 LifeVibes::setMasterVolume(audioOutputType, value);
1232 }
1233#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001234 mMasterVolume = value;
1235 return NO_ERROR;
1236}
1237
Eric Laurenta553c252009-07-17 12:17:14 -07001238status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001239{
Glenn Kasten871c16c2010-03-05 12:18:01 -08001240#ifdef LVMX
1241 int audioOutputType = LifeVibes::getMixerType(mId, mType);
1242 if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType)) {
1243 LifeVibes::setMasterMute(audioOutputType, muted);
1244 }
1245#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001246 mMasterMute = muted;
1247 return NO_ERROR;
1248}
1249
Eric Laurenta553c252009-07-17 12:17:14 -07001250float AudioFlinger::PlaybackThread::masterVolume() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001251{
1252 return mMasterVolume;
1253}
1254
Eric Laurenta553c252009-07-17 12:17:14 -07001255bool AudioFlinger::PlaybackThread::masterMute() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001256{
1257 return mMasterMute;
1258}
1259
Eric Laurenta553c252009-07-17 12:17:14 -07001260status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001261{
Glenn Kasten871c16c2010-03-05 12:18:01 -08001262#ifdef LVMX
1263 int audioOutputType = LifeVibes::getMixerType(mId, mType);
1264 if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType)) {
1265 LifeVibes::setStreamVolume(audioOutputType, stream, value);
1266 }
1267#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001268 mStreamTypes[stream].volume = value;
1269 return NO_ERROR;
1270}
1271
Eric Laurenta553c252009-07-17 12:17:14 -07001272status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001273{
Glenn Kasten871c16c2010-03-05 12:18:01 -08001274#ifdef LVMX
1275 int audioOutputType = LifeVibes::getMixerType(mId, mType);
1276 if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType)) {
1277 LifeVibes::setStreamMute(audioOutputType, stream, muted);
1278 }
1279#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001280 mStreamTypes[stream].mute = muted;
1281 return NO_ERROR;
1282}
1283
Eric Laurenta553c252009-07-17 12:17:14 -07001284float AudioFlinger::PlaybackThread::streamVolume(int stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001285{
1286 return mStreamTypes[stream].volume;
1287}
1288
Eric Laurenta553c252009-07-17 12:17:14 -07001289bool AudioFlinger::PlaybackThread::streamMute(int stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001290{
1291 return mStreamTypes[stream].mute;
1292}
1293
Eric Laurent23f25cd2010-01-25 08:49:09 -08001294bool AudioFlinger::PlaybackThread::isStreamActive(int stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001295{
Eric Laurenta553c252009-07-17 12:17:14 -07001296 Mutex::Autolock _l(mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001297 size_t count = mActiveTracks.size();
1298 for (size_t i = 0 ; i < count ; ++i) {
1299 sp<Track> t = mActiveTracks[i].promote();
1300 if (t == 0) continue;
1301 Track* const track = t.get();
Eric Laurent23f25cd2010-01-25 08:49:09 -08001302 if (t->type() == stream)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001303 return true;
1304 }
1305 return false;
1306}
1307
Eric Laurenta553c252009-07-17 12:17:14 -07001308// addTrack_l() must be called with ThreadBase::mLock held
1309status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001310{
1311 status_t status = ALREADY_EXISTS;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001312
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001313 // set retry count for buffer fill
1314 track->mRetryCount = kMaxTrackStartupRetries;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001315 if (mActiveTracks.indexOf(track) < 0) {
1316 // the track is newly added, make sure it fills up all its
1317 // buffers before playing. This is to ensure the client will
1318 // effectively get the latency it requested.
1319 track->mFillingUpStatus = Track::FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001320 track->mResetDone = false;
Eric Laurenta553c252009-07-17 12:17:14 -07001321 mActiveTracks.add(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001322 if (track->mainBuffer() != mMixBuffer) {
1323 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1324 if (chain != 0) {
1325 LOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
1326 chain->startTrack();
1327 }
1328 }
1329
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001330 status = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001331 }
Eric Laurenta553c252009-07-17 12:17:14 -07001332
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001333 LOGV("mWaitWorkCV.broadcast");
Eric Laurenta553c252009-07-17 12:17:14 -07001334 mWaitWorkCV.broadcast();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001335
1336 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001337}
1338
Eric Laurenta553c252009-07-17 12:17:14 -07001339// destroyTrack_l() must be called with ThreadBase::mLock held
1340void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001341{
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001342 track->mState = TrackBase::TERMINATED;
1343 if (mActiveTracks.indexOf(track) < 0) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001344 mTracks.remove(track);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001345 deleteTrackName_l(track->name());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001346 }
1347}
1348
Eric Laurenta553c252009-07-17 12:17:14 -07001349String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001350{
Eric Laurenta553c252009-07-17 12:17:14 -07001351 return mOutput->getParameters(keys);
1352}
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001353
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001354// destroyTrack_l() must be called with AudioFlinger::mLock held
1355void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
Eric Laurenta553c252009-07-17 12:17:14 -07001356 AudioSystem::OutputDescriptor desc;
1357 void *param2 = 0;
1358
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001359 LOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Eric Laurenta553c252009-07-17 12:17:14 -07001360
1361 switch (event) {
1362 case AudioSystem::OUTPUT_OPENED:
1363 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Eric Laurentb0a01472010-05-14 05:45:46 -07001364 desc.channels = mChannels;
Eric Laurenta553c252009-07-17 12:17:14 -07001365 desc.samplingRate = mSampleRate;
1366 desc.format = mFormat;
1367 desc.frameCount = mFrameCount;
1368 desc.latency = latency();
1369 param2 = &desc;
1370 break;
1371
1372 case AudioSystem::STREAM_CONFIG_CHANGED:
1373 param2 = &param;
1374 case AudioSystem::OUTPUT_CLOSED:
1375 default:
1376 break;
1377 }
Eric Laurent49f02be2009-11-19 09:00:56 -08001378 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurenta553c252009-07-17 12:17:14 -07001379}
1380
1381void AudioFlinger::PlaybackThread::readOutputParameters()
1382{
1383 mSampleRate = mOutput->sampleRate();
Eric Laurentb0a01472010-05-14 05:45:46 -07001384 mChannels = mOutput->channels();
1385 mChannelCount = (uint16_t)AudioSystem::popCount(mChannels);
Eric Laurenta553c252009-07-17 12:17:14 -07001386 mFormat = mOutput->format();
Eric Laurentb0a01472010-05-14 05:45:46 -07001387 mFrameSize = (uint16_t)mOutput->frameSize();
Eric Laurenta553c252009-07-17 12:17:14 -07001388 mFrameCount = mOutput->bufferSize() / mFrameSize;
1389
Eric Laurenta553c252009-07-17 12:17:14 -07001390 // FIXME - Current mixer implementation only supports stereo output: Always
1391 // Allocate a stereo buffer even if HW output is mono.
Eric Laurent65b65452010-06-01 23:49:17 -07001392 if (mMixBuffer != NULL) delete[] mMixBuffer;
Eric Laurenta553c252009-07-17 12:17:14 -07001393 mMixBuffer = new int16_t[mFrameCount * 2];
1394 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
Eric Laurent65b65452010-06-01 23:49:17 -07001395
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001396 // force reconfiguration of effect chains and engines to take new buffer size and audio
1397 // parameters into account
1398 // Note that mLock is not held when readOutputParameters() is called from the constructor
1399 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1400 // matter.
1401 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1402 Vector< sp<EffectChain> > effectChains = mEffectChains;
1403 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent493941b2010-07-28 01:32:47 -07001404 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001405 }
Eric Laurenta553c252009-07-17 12:17:14 -07001406}
1407
Eric Laurent0986e792010-01-19 17:37:09 -08001408status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1409{
1410 if (halFrames == 0 || dspFrames == 0) {
1411 return BAD_VALUE;
1412 }
1413 if (mOutput == 0) {
1414 return INVALID_OPERATION;
1415 }
1416 *halFrames = mBytesWritten/mOutput->frameSize();
1417
1418 return mOutput->getRenderPosition(dspFrames);
1419}
1420
Eric Laurent493941b2010-07-28 01:32:47 -07001421uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Eric Laurent65b65452010-06-01 23:49:17 -07001422{
1423 Mutex::Autolock _l(mLock);
Eric Laurent493941b2010-07-28 01:32:47 -07001424 uint32_t result = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07001425 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent493941b2010-07-28 01:32:47 -07001426 result = EFFECT_SESSION;
Eric Laurent65b65452010-06-01 23:49:17 -07001427 }
1428
1429 for (size_t i = 0; i < mTracks.size(); ++i) {
1430 sp<Track> track = mTracks[i];
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001431 if (sessionId == track->sessionId() &&
1432 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent493941b2010-07-28 01:32:47 -07001433 result |= TRACK_SESSION;
1434 break;
Eric Laurent65b65452010-06-01 23:49:17 -07001435 }
1436 }
1437
Eric Laurent493941b2010-07-28 01:32:47 -07001438 return result;
Eric Laurent65b65452010-06-01 23:49:17 -07001439}
1440
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001441uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1442{
1443 // session AudioSystem::SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
1444 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
1445 if (sessionId == AudioSystem::SESSION_OUTPUT_MIX) {
1446 return AudioSystem::getStrategyForStream(AudioSystem::MUSIC);
1447 }
1448 for (size_t i = 0; i < mTracks.size(); i++) {
1449 sp<Track> track = mTracks[i];
1450 if (sessionId == track->sessionId() &&
1451 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
1452 return AudioSystem::getStrategyForStream((AudioSystem::stream_type) track->type());
1453 }
1454 }
1455 return AudioSystem::getStrategyForStream(AudioSystem::MUSIC);
1456}
1457
Eric Laurent65b65452010-06-01 23:49:17 -07001458sp<AudioFlinger::EffectChain> AudioFlinger::PlaybackThread::getEffectChain(int sessionId)
1459{
1460 Mutex::Autolock _l(mLock);
1461 return getEffectChain_l(sessionId);
1462}
1463
1464sp<AudioFlinger::EffectChain> AudioFlinger::PlaybackThread::getEffectChain_l(int sessionId)
1465{
1466 sp<EffectChain> chain;
1467
1468 size_t size = mEffectChains.size();
1469 for (size_t i = 0; i < size; i++) {
1470 if (mEffectChains[i]->sessionId() == sessionId) {
1471 chain = mEffectChains[i];
1472 break;
1473 }
1474 }
1475 return chain;
1476}
1477
Eric Laurent53334cd2010-06-23 17:38:20 -07001478void AudioFlinger::PlaybackThread::setMode(uint32_t mode)
1479{
1480 Mutex::Autolock _l(mLock);
1481 size_t size = mEffectChains.size();
1482 for (size_t i = 0; i < size; i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07001483 mEffectChains[i]->setMode_l(mode);
Eric Laurent53334cd2010-06-23 17:38:20 -07001484 }
1485}
1486
Eric Laurenta553c252009-07-17 12:17:14 -07001487// ----------------------------------------------------------------------------
1488
Eric Laurent65b65452010-06-01 23:49:17 -07001489AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
1490 : PlaybackThread(audioFlinger, output, id, device),
Eric Laurenta553c252009-07-17 12:17:14 -07001491 mAudioMixer(0)
1492{
1493 mType = PlaybackThread::MIXER;
1494 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1495
1496 // FIXME - Current mixer implementation only supports stereo output
1497 if (mChannelCount == 1) {
1498 LOGE("Invalid audio hardware channel count");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001499 }
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001500}
1501
Eric Laurenta553c252009-07-17 12:17:14 -07001502AudioFlinger::MixerThread::~MixerThread()
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001503{
Eric Laurenta553c252009-07-17 12:17:14 -07001504 delete mAudioMixer;
1505}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001506
Eric Laurenta553c252009-07-17 12:17:14 -07001507bool AudioFlinger::MixerThread::threadLoop()
1508{
Eric Laurenta553c252009-07-17 12:17:14 -07001509 Vector< sp<Track> > tracksToRemove;
Eric Laurent059b4be2009-11-09 23:32:22 -08001510 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001511 nsecs_t standbyTime = systemTime();
1512 size_t mixBufferSize = mFrameCount * mFrameSize;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001513 // FIXME: Relaxed timing because of a certain device that can't meet latency
1514 // Should be reduced to 2x after the vendor fixes the driver issue
1515 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
1516 nsecs_t lastWarning = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08001517 bool longStandbyExit = false;
1518 uint32_t activeSleepTime = activeSleepTimeUs();
1519 uint32_t idleSleepTime = idleSleepTimeUs();
1520 uint32_t sleepTime = idleSleepTime;
Eric Laurent65b65452010-06-01 23:49:17 -07001521 Vector< sp<EffectChain> > effectChains;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001522
Eric Laurenta553c252009-07-17 12:17:14 -07001523 while (!exitPending())
1524 {
1525 processConfigEvents();
1526
Eric Laurent059b4be2009-11-09 23:32:22 -08001527 mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001528 { // scope for mLock
1529
1530 Mutex::Autolock _l(mLock);
1531
1532 if (checkForNewParameters_l()) {
1533 mixBufferSize = mFrameCount * mFrameSize;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001534 // FIXME: Relaxed timing because of a certain device that can't meet latency
1535 // Should be reduced to 2x after the vendor fixes the driver issue
1536 maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
Eric Laurent059b4be2009-11-09 23:32:22 -08001537 activeSleepTime = activeSleepTimeUs();
1538 idleSleepTime = idleSleepTimeUs();
Eric Laurenta553c252009-07-17 12:17:14 -07001539 }
1540
1541 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1542
1543 // put audio hardware into standby after short delay
1544 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1545 mSuspended) {
1546 if (!mStandby) {
1547 LOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
1548 mOutput->standby();
1549 mStandby = true;
1550 mBytesWritten = 0;
1551 }
1552
1553 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1554 // we're about to wait, flush the binder command buffer
1555 IPCThreadState::self()->flushCommands();
1556
1557 if (exitPending()) break;
1558
1559 // wait until we have something to do...
1560 LOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
1561 mWaitWorkCV.wait(mLock);
1562 LOGV("MixerThread %p TID %d waking up\n", this, gettid());
1563
1564 if (mMasterMute == false) {
1565 char value[PROPERTY_VALUE_MAX];
1566 property_get("ro.audio.silent", value, "0");
1567 if (atoi(value)) {
1568 LOGD("Silence is golden");
1569 setMasterMute(true);
1570 }
1571 }
1572
1573 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent059b4be2009-11-09 23:32:22 -08001574 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07001575 continue;
1576 }
1577 }
1578
Eric Laurent059b4be2009-11-09 23:32:22 -08001579 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07001580
1581 // prevent any changes in effect chain list and in each effect chain
1582 // during mixing and effect process as the audio buffers could be deleted
1583 // or modified if an effect is created or deleted
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001584 lockEffectChains_l(effectChains);
Eric Laurenta553c252009-07-17 12:17:14 -07001585 }
1586
Eric Laurent059b4be2009-11-09 23:32:22 -08001587 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07001588 // mix buffers...
Eric Laurent65b65452010-06-01 23:49:17 -07001589 mAudioMixer->process();
Eric Laurentf69a3f82009-09-22 00:35:48 -07001590 sleepTime = 0;
1591 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent65b65452010-06-01 23:49:17 -07001592 //TODO: delay standby when effects have a tail
Eric Laurent96c08a62009-09-07 08:38:38 -07001593 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07001594 // If no tracks are ready, sleep once for the duration of an output
1595 // buffer size, then write 0s to the output
1596 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08001597 if (mixerStatus == MIXER_TRACKS_ENABLED) {
1598 sleepTime = activeSleepTime;
1599 } else {
1600 sleepTime = idleSleepTime;
1601 }
1602 } else if (mBytesWritten != 0 ||
1603 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Eric Laurent65b65452010-06-01 23:49:17 -07001604 memset (mMixBuffer, 0, mixBufferSize);
Eric Laurent96c08a62009-09-07 08:38:38 -07001605 sleepTime = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08001606 LOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Eric Laurent96c08a62009-09-07 08:38:38 -07001607 }
Eric Laurent65b65452010-06-01 23:49:17 -07001608 // TODO add standby time extension fct of effect tail
Eric Laurentf69a3f82009-09-22 00:35:48 -07001609 }
1610
1611 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07001612 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07001613 }
1614 // sleepTime == 0 means we must write to audio hardware
1615 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07001616 for (size_t i = 0; i < effectChains.size(); i ++) {
1617 effectChains[i]->process_l();
1618 }
1619 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001620 unlockEffectChains(effectChains);
Glenn Kasten871c16c2010-03-05 12:18:01 -08001621#ifdef LVMX
1622 int audioOutputType = LifeVibes::getMixerType(mId, mType);
1623 if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType)) {
Eric Laurent65b65452010-06-01 23:49:17 -07001624 LifeVibes::process(audioOutputType, mMixBuffer, mixBufferSize);
Glenn Kasten871c16c2010-03-05 12:18:01 -08001625 }
1626#endif
Eric Laurent65b65452010-06-01 23:49:17 -07001627 mLastWriteTime = systemTime();
1628 mInWrite = true;
1629 mBytesWritten += mixBufferSize;
1630
1631 int bytesWritten = (int)mOutput->write(mMixBuffer, mixBufferSize);
Eric Laurent0986e792010-01-19 17:37:09 -08001632 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07001633 mNumWrites++;
1634 mInWrite = false;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001635 nsecs_t now = systemTime();
1636 nsecs_t delta = now - mLastWriteTime;
Eric Laurentf69a3f82009-09-22 00:35:48 -07001637 if (delta > maxPeriod) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07001638 mNumDelayedWrites++;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001639 if ((now - lastWarning) > kWarningThrottle) {
1640 LOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
1641 ns2ms(delta), mNumDelayedWrites, this);
1642 lastWarning = now;
1643 }
Eric Laurent059b4be2009-11-09 23:32:22 -08001644 if (mStandby) {
1645 longStandbyExit = true;
1646 }
Eric Laurenta553c252009-07-17 12:17:14 -07001647 }
Eric Laurent059b4be2009-11-09 23:32:22 -08001648 mStandby = false;
Eric Laurentf69a3f82009-09-22 00:35:48 -07001649 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07001650 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001651 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07001652 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07001653 }
1654
1655 // finally let go of all our tracks, without the lock held
1656 // since we can't guarantee the destructors won't acquire that
1657 // same lock.
1658 tracksToRemove.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07001659
1660 // Effect chains will be actually deleted here if they were removed from
1661 // mEffectChains list during mixing or effects processing
1662 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07001663 }
1664
1665 if (!mStandby) {
1666 mOutput->standby();
1667 }
Eric Laurenta553c252009-07-17 12:17:14 -07001668
1669 LOGV("MixerThread %p exiting", this);
1670 return false;
1671}
1672
1673// prepareTracks_l() must be called with ThreadBase::mLock held
Eric Laurent059b4be2009-11-09 23:32:22 -08001674uint32_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
Eric Laurenta553c252009-07-17 12:17:14 -07001675{
1676
Eric Laurent059b4be2009-11-09 23:32:22 -08001677 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001678 // find out which tracks need to be processed
1679 size_t count = activeTracks.size();
Eric Laurent65b65452010-06-01 23:49:17 -07001680 size_t mixedTracks = 0;
1681 size_t tracksWithEffect = 0;
Glenn Kasten871c16c2010-03-05 12:18:01 -08001682
1683 float masterVolume = mMasterVolume;
1684 bool masterMute = mMasterMute;
1685
Eric Laurent8cc93b92010-08-11 05:20:11 -07001686 if (masterMute) {
1687 masterVolume = 0;
1688 }
Glenn Kasten871c16c2010-03-05 12:18:01 -08001689#ifdef LVMX
1690 bool tracksConnectedChanged = false;
1691 bool stateChanged = false;
1692
1693 int audioOutputType = LifeVibes::getMixerType(mId, mType);
1694 if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType))
1695 {
1696 int activeTypes = 0;
1697 for (size_t i=0 ; i<count ; i++) {
1698 sp<Track> t = activeTracks[i].promote();
1699 if (t == 0) continue;
1700 Track* const track = t.get();
1701 int iTracktype=track->type();
1702 activeTypes |= 1<<track->type();
1703 }
1704 LifeVibes::computeVolumes(audioOutputType, activeTypes, tracksConnectedChanged, stateChanged, masterVolume, masterMute);
1705 }
1706#endif
Eric Laurent65b65452010-06-01 23:49:17 -07001707 // Delegate master volume control to effect in output mix effect chain if needed
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001708 sp<EffectChain> chain = getEffectChain_l(AudioSystem::SESSION_OUTPUT_MIX);
Eric Laurent65b65452010-06-01 23:49:17 -07001709 if (chain != 0) {
Eric Laurent8cc93b92010-08-11 05:20:11 -07001710 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurent76c40f72010-07-15 12:50:15 -07001711 chain->setVolume_l(&v, &v);
Eric Laurent65b65452010-06-01 23:49:17 -07001712 masterVolume = (float)((v + (1 << 23)) >> 24);
1713 chain.clear();
1714 }
Glenn Kasten871c16c2010-03-05 12:18:01 -08001715
Eric Laurenta553c252009-07-17 12:17:14 -07001716 for (size_t i=0 ; i<count ; i++) {
1717 sp<Track> t = activeTracks[i].promote();
1718 if (t == 0) continue;
1719
1720 Track* const track = t.get();
1721 audio_track_cblk_t* cblk = track->cblk();
1722
1723 // The first time a track is added we wait
1724 // for all its buffers to be filled before processing it
1725 mAudioMixer->setActiveTrack(track->name());
Eric Laurent9a30fc12010-10-05 14:41:42 -07001726 if (cblk->framesReady() && track->isReady() &&
Eric Laurent71f37cd2010-03-31 12:21:17 -07001727 !track->isPaused() && !track->isTerminated())
Eric Laurenta553c252009-07-17 12:17:14 -07001728 {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08001729 //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 -07001730
Eric Laurent65b65452010-06-01 23:49:17 -07001731 mixedTracks++;
1732
1733 // track->mainBuffer() != mMixBuffer means there is an effect chain
1734 // connected to the track
1735 chain.clear();
1736 if (track->mainBuffer() != mMixBuffer) {
1737 chain = getEffectChain_l(track->sessionId());
1738 // Delegate volume control to effect in track effect chain if needed
1739 if (chain != 0) {
1740 tracksWithEffect++;
1741 } else {
1742 LOGW("prepareTracks_l(): track %08x attached to effect but no chain found on session %d",
1743 track->name(), track->sessionId());
1744 }
1745 }
1746
1747
1748 int param = AudioMixer::VOLUME;
1749 if (track->mFillingUpStatus == Track::FS_FILLED) {
1750 // no ramp for the first volume setting
1751 track->mFillingUpStatus = Track::FS_ACTIVE;
1752 if (track->mState == TrackBase::RESUMING) {
1753 track->mState = TrackBase::ACTIVE;
1754 param = AudioMixer::RAMP_VOLUME;
1755 }
1756 } else if (cblk->server != 0) {
1757 // If the track is stopped before the first frame was mixed,
1758 // do not apply ramp
1759 param = AudioMixer::RAMP_VOLUME;
1760 }
1761
Eric Laurenta553c252009-07-17 12:17:14 -07001762 // compute volume for this track
Eric Laurent27a2fdf2010-09-10 17:44:44 -07001763 uint32_t vl, vr, va;
Eric Laurent2a6b80b2010-07-29 23:43:43 -07001764 if (track->isMuted() || track->isPausing() ||
Eric Laurenta553c252009-07-17 12:17:14 -07001765 mStreamTypes[track->type()].mute) {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07001766 vl = vr = va = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07001767 if (track->isPausing()) {
1768 track->setPaused();
1769 }
1770 } else {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07001771
Glenn Kasten871c16c2010-03-05 12:18:01 -08001772 // read original volumes with volume control
Eric Laurenta553c252009-07-17 12:17:14 -07001773 float typeVolume = mStreamTypes[track->type()].volume;
Glenn Kasten871c16c2010-03-05 12:18:01 -08001774#ifdef LVMX
1775 bool streamMute=false;
1776 // read the volume from the LivesVibes audio engine.
1777 if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType))
1778 {
1779 LifeVibes::getStreamVolumes(audioOutputType, track->type(), &typeVolume, &streamMute);
1780 if (streamMute) {
1781 typeVolume = 0;
1782 }
1783 }
1784#endif
1785 float v = masterVolume * typeVolume;
Eric Laurent27a2fdf2010-09-10 17:44:44 -07001786 vl = (uint32_t)(v * cblk->volume[0]) << 12;
1787 vr = (uint32_t)(v * cblk->volume[1]) << 12;
Eric Laurenta553c252009-07-17 12:17:14 -07001788
Eric Laurent27a2fdf2010-09-10 17:44:44 -07001789 va = (uint32_t)(v * cblk->sendLevel);
Eric Laurenta553c252009-07-17 12:17:14 -07001790 }
Eric Laurent27a2fdf2010-09-10 17:44:44 -07001791 // Delegate volume control to effect in track effect chain if needed
1792 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
1793 // Do not ramp volume if volume is controlled by effect
1794 param = AudioMixer::VOLUME;
1795 track->mHasVolumeController = true;
1796 } else {
1797 // force no volume ramp when volume controller was just disabled or removed
1798 // from effect chain to avoid volume spike
1799 if (track->mHasVolumeController) {
1800 param = AudioMixer::VOLUME;
1801 }
1802 track->mHasVolumeController = false;
1803 }
1804
1805 // Convert volumes from 8.24 to 4.12 format
1806 int16_t left, right, aux;
1807 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
1808 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
1809 left = int16_t(v_clamped);
1810 v_clamped = (vr + (1 << 11)) >> 12;
1811 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
1812 right = int16_t(v_clamped);
1813
1814 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
1815 aux = int16_t(va);
Eric Laurent65b65452010-06-01 23:49:17 -07001816
Glenn Kasten871c16c2010-03-05 12:18:01 -08001817#ifdef LVMX
1818 if ( tracksConnectedChanged || stateChanged )
1819 {
1820 // only do the ramp when the volume is changed by the user / application
1821 param = AudioMixer::VOLUME;
1822 }
1823#endif
Eric Laurent65b65452010-06-01 23:49:17 -07001824
1825 // XXX: these things DON'T need to be done each time
1826 mAudioMixer->setBufferProvider(track);
1827 mAudioMixer->enable(AudioMixer::MIXING);
1828
1829 mAudioMixer->setParameter(param, AudioMixer::VOLUME0, (void *)left);
1830 mAudioMixer->setParameter(param, AudioMixer::VOLUME1, (void *)right);
1831 mAudioMixer->setParameter(param, AudioMixer::AUXLEVEL, (void *)aux);
Eric Laurenta553c252009-07-17 12:17:14 -07001832 mAudioMixer->setParameter(
1833 AudioMixer::TRACK,
Eric Laurent65b65452010-06-01 23:49:17 -07001834 AudioMixer::FORMAT, (void *)track->format());
Eric Laurenta553c252009-07-17 12:17:14 -07001835 mAudioMixer->setParameter(
1836 AudioMixer::TRACK,
Eric Laurent65b65452010-06-01 23:49:17 -07001837 AudioMixer::CHANNEL_COUNT, (void *)track->channelCount());
Eric Laurenta553c252009-07-17 12:17:14 -07001838 mAudioMixer->setParameter(
1839 AudioMixer::RESAMPLE,
1840 AudioMixer::SAMPLE_RATE,
Eric Laurent65b65452010-06-01 23:49:17 -07001841 (void *)(cblk->sampleRate));
1842 mAudioMixer->setParameter(
1843 AudioMixer::TRACK,
1844 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
1845 mAudioMixer->setParameter(
1846 AudioMixer::TRACK,
1847 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
Eric Laurenta553c252009-07-17 12:17:14 -07001848
1849 // reset retry count
1850 track->mRetryCount = kMaxTrackRetries;
Eric Laurent059b4be2009-11-09 23:32:22 -08001851 mixerStatus = MIXER_TRACKS_READY;
Eric Laurenta553c252009-07-17 12:17:14 -07001852 } else {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08001853 //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 -07001854 if (track->isStopped()) {
1855 track->reset();
1856 }
1857 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
1858 // We have consumed all the buffers of this track.
1859 // Remove it from the list of active tracks.
1860 tracksToRemove->add(track);
Eric Laurenta553c252009-07-17 12:17:14 -07001861 } else {
1862 // No buffers for this track. Give it a few chances to
1863 // fill a buffer, then remove it from active list.
1864 if (--(track->mRetryCount) <= 0) {
Eric Laurent62443f52009-10-05 20:29:18 -07001865 LOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", track->name(), this);
Eric Laurenta553c252009-07-17 12:17:14 -07001866 tracksToRemove->add(track);
Eric Laurent4712baa2010-09-30 16:12:31 -07001867 // indicate to client process that the track was disabled because of underrun
1868 cblk->flags |= CBLK_DISABLED_ON;
Eric Laurent059b4be2009-11-09 23:32:22 -08001869 } else if (mixerStatus != MIXER_TRACKS_READY) {
1870 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07001871 }
Eric Laurenta553c252009-07-17 12:17:14 -07001872 }
Eric Laurent65b65452010-06-01 23:49:17 -07001873 mAudioMixer->disable(AudioMixer::MIXING);
Eric Laurenta553c252009-07-17 12:17:14 -07001874 }
1875 }
1876
1877 // remove all the tracks that need to be...
1878 count = tracksToRemove->size();
1879 if (UNLIKELY(count)) {
1880 for (size_t i=0 ; i<count ; i++) {
1881 const sp<Track>& track = tracksToRemove->itemAt(i);
1882 mActiveTracks.remove(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001883 if (track->mainBuffer() != mMixBuffer) {
1884 chain = getEffectChain_l(track->sessionId());
1885 if (chain != 0) {
1886 LOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
1887 chain->stopTrack();
1888 }
1889 }
Eric Laurenta553c252009-07-17 12:17:14 -07001890 if (track->isTerminated()) {
1891 mTracks.remove(track);
1892 deleteTrackName_l(track->mName);
1893 }
1894 }
1895 }
1896
Eric Laurent65b65452010-06-01 23:49:17 -07001897 // mix buffer must be cleared if all tracks are connected to an
1898 // effect chain as in this case the mixer will not write to
1899 // mix buffer and track effects will accumulate into it
1900 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
1901 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
1902 }
1903
Eric Laurent059b4be2009-11-09 23:32:22 -08001904 return mixerStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07001905}
1906
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001907void AudioFlinger::MixerThread::invalidateTracks(int streamType)
Eric Laurenta553c252009-07-17 12:17:14 -07001908{
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001909 LOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
1910 this, streamType, mTracks.size());
Eric Laurenta553c252009-07-17 12:17:14 -07001911 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001912
Eric Laurenta553c252009-07-17 12:17:14 -07001913 size_t size = mTracks.size();
1914 for (size_t i = 0; i < size; i++) {
1915 sp<Track> t = mTracks[i];
1916 if (t->type() == streamType) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001917 t->mCblk->lock.lock();
1918 t->mCblk->flags |= CBLK_INVALID_ON;
1919 t->mCblk->cv.signal();
1920 t->mCblk->lock.unlock();
Eric Laurenta553c252009-07-17 12:17:14 -07001921 }
Eric Laurent53334cd2010-06-23 17:38:20 -07001922 }
1923}
Eric Laurenta553c252009-07-17 12:17:14 -07001924
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001925
Eric Laurenta553c252009-07-17 12:17:14 -07001926// getTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001927int AudioFlinger::MixerThread::getTrackName_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001928{
1929 return mAudioMixer->getTrackName();
1930}
1931
Eric Laurenta553c252009-07-17 12:17:14 -07001932// deleteTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001933void AudioFlinger::MixerThread::deleteTrackName_l(int name)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001934{
Eric Laurent0a080292009-12-07 10:53:10 -08001935 LOGV("remove track (%d) and delete from mixer", name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001936 mAudioMixer->deleteTrackName(name);
1937}
1938
Eric Laurenta553c252009-07-17 12:17:14 -07001939// checkForNewParameters_l() must be called with ThreadBase::mLock held
1940bool AudioFlinger::MixerThread::checkForNewParameters_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001941{
Eric Laurenta553c252009-07-17 12:17:14 -07001942 bool reconfig = false;
1943
Eric Laurent8fce46a2009-08-04 09:45:33 -07001944 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07001945 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07001946 String8 keyValuePair = mNewParameters[0];
1947 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07001948 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07001949
Eric Laurenta553c252009-07-17 12:17:14 -07001950 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
1951 reconfig = true;
1952 }
1953 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
1954 if (value != AudioSystem::PCM_16_BIT) {
1955 status = BAD_VALUE;
1956 } else {
1957 reconfig = true;
1958 }
1959 }
1960 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
1961 if (value != AudioSystem::CHANNEL_OUT_STEREO) {
1962 status = BAD_VALUE;
1963 } else {
1964 reconfig = true;
1965 }
1966 }
1967 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
1968 // do not accept frame count changes if tracks are open as the track buffer
1969 // size depends on frame count and correct behavior would not be garantied
1970 // if frame count is changed after track creation
1971 if (!mTracks.isEmpty()) {
1972 status = INVALID_OPERATION;
1973 } else {
1974 reconfig = true;
1975 }
1976 }
Eric Laurent65b65452010-06-01 23:49:17 -07001977 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
1978 // forward device change to effects that have requested to be
1979 // aware of attached audio device.
1980 mDevice = (uint32_t)value;
1981 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07001982 mEffectChains[i]->setDevice_l(mDevice);
Eric Laurent65b65452010-06-01 23:49:17 -07001983 }
1984 }
1985
Eric Laurenta553c252009-07-17 12:17:14 -07001986 if (status == NO_ERROR) {
Eric Laurent8fce46a2009-08-04 09:45:33 -07001987 status = mOutput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07001988 if (!mStandby && status == INVALID_OPERATION) {
1989 mOutput->standby();
1990 mStandby = true;
1991 mBytesWritten = 0;
Eric Laurent8fce46a2009-08-04 09:45:33 -07001992 status = mOutput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07001993 }
1994 if (status == NO_ERROR && reconfig) {
1995 delete mAudioMixer;
1996 readOutputParameters();
1997 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1998 for (size_t i = 0; i < mTracks.size() ; i++) {
1999 int name = getTrackName_l();
2000 if (name < 0) break;
2001 mTracks[i]->mName = name;
Eric Laurent6f7e0972009-08-10 08:15:12 -07002002 // limit track sample rate to 2 x new output sample rate
2003 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2004 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2005 }
Eric Laurenta553c252009-07-17 12:17:14 -07002006 }
Eric Laurent8fce46a2009-08-04 09:45:33 -07002007 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07002008 }
2009 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08002010
2011 mNewParameters.removeAt(0);
2012
Eric Laurenta553c252009-07-17 12:17:14 -07002013 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07002014 mParamCond.signal();
Eric Laurent8fce46a2009-08-04 09:45:33 -07002015 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07002016 }
2017 return reconfig;
2018}
2019
2020status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2021{
2022 const size_t SIZE = 256;
2023 char buffer[SIZE];
2024 String8 result;
2025
2026 PlaybackThread::dumpInternals(fd, args);
2027
2028 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2029 result.append(buffer);
2030 write(fd, result.string(), result.size());
2031 return NO_ERROR;
2032}
2033
Eric Laurent059b4be2009-11-09 23:32:22 -08002034uint32_t AudioFlinger::MixerThread::activeSleepTimeUs()
Eric Laurent62443f52009-10-05 20:29:18 -07002035{
Eric Laurent059b4be2009-11-09 23:32:22 -08002036 return (uint32_t)(mOutput->latency() * 1000) / 2;
2037}
2038
2039uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2040{
Eric Laurenta54d7d32010-07-29 06:50:24 -07002041 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Eric Laurent62443f52009-10-05 20:29:18 -07002042}
2043
Eric Laurent8448a792010-08-18 18:13:17 -07002044uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2045{
2046 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2047}
2048
Eric Laurenta553c252009-07-17 12:17:14 -07002049// ----------------------------------------------------------------------------
Eric Laurent65b65452010-06-01 23:49:17 -07002050AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
2051 : PlaybackThread(audioFlinger, output, id, device)
Eric Laurenta553c252009-07-17 12:17:14 -07002052{
2053 mType = PlaybackThread::DIRECT;
2054}
2055
2056AudioFlinger::DirectOutputThread::~DirectOutputThread()
2057{
2058}
2059
2060
Eric Laurent65b65452010-06-01 23:49:17 -07002061static inline int16_t clamp16(int32_t sample)
2062{
2063 if ((sample>>15) ^ (sample>>31))
2064 sample = 0x7FFF ^ (sample>>31);
2065 return sample;
2066}
2067
2068static inline
2069int32_t mul(int16_t in, int16_t v)
2070{
2071#if defined(__arm__) && !defined(__thumb__)
2072 int32_t out;
2073 asm( "smulbb %[out], %[in], %[v] \n"
2074 : [out]"=r"(out)
2075 : [in]"%r"(in), [v]"r"(v)
2076 : );
2077 return out;
2078#else
2079 return in * int32_t(v);
2080#endif
2081}
2082
2083void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2084{
2085 // Do not apply volume on compressed audio
2086 if (!AudioSystem::isLinearPCM(mFormat)) {
2087 return;
2088 }
2089
2090 // convert to signed 16 bit before volume calculation
2091 if (mFormat == AudioSystem::PCM_8_BIT) {
2092 size_t count = mFrameCount * mChannelCount;
2093 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2094 int16_t *dst = mMixBuffer + count-1;
2095 while(count--) {
2096 *dst-- = (int16_t)(*src--^0x80) << 8;
2097 }
2098 }
2099
2100 size_t frameCount = mFrameCount;
2101 int16_t *out = mMixBuffer;
2102 if (ramp) {
2103 if (mChannelCount == 1) {
2104 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2105 int32_t vlInc = d / (int32_t)frameCount;
2106 int32_t vl = ((int32_t)mLeftVolShort << 16);
2107 do {
2108 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2109 out++;
2110 vl += vlInc;
2111 } while (--frameCount);
2112
2113 } else {
2114 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2115 int32_t vlInc = d / (int32_t)frameCount;
2116 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2117 int32_t vrInc = d / (int32_t)frameCount;
2118 int32_t vl = ((int32_t)mLeftVolShort << 16);
2119 int32_t vr = ((int32_t)mRightVolShort << 16);
2120 do {
2121 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2122 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2123 out += 2;
2124 vl += vlInc;
2125 vr += vrInc;
2126 } while (--frameCount);
2127 }
2128 } else {
2129 if (mChannelCount == 1) {
2130 do {
2131 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2132 out++;
2133 } while (--frameCount);
2134 } else {
2135 do {
2136 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2137 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2138 out += 2;
2139 } while (--frameCount);
2140 }
2141 }
2142
2143 // convert back to unsigned 8 bit after volume calculation
2144 if (mFormat == AudioSystem::PCM_8_BIT) {
2145 size_t count = mFrameCount * mChannelCount;
2146 int16_t *src = mMixBuffer;
2147 uint8_t *dst = (uint8_t *)mMixBuffer;
2148 while(count--) {
2149 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2150 }
2151 }
2152
2153 mLeftVolShort = leftVol;
2154 mRightVolShort = rightVol;
2155}
2156
Eric Laurenta553c252009-07-17 12:17:14 -07002157bool AudioFlinger::DirectOutputThread::threadLoop()
2158{
Eric Laurent059b4be2009-11-09 23:32:22 -08002159 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002160 sp<Track> trackToRemove;
2161 sp<Track> activeTrack;
2162 nsecs_t standbyTime = systemTime();
2163 int8_t *curBuf;
2164 size_t mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent059b4be2009-11-09 23:32:22 -08002165 uint32_t activeSleepTime = activeSleepTimeUs();
2166 uint32_t idleSleepTime = idleSleepTimeUs();
2167 uint32_t sleepTime = idleSleepTime;
Eric Laurentef9500f2010-03-11 14:47:00 -08002168 // use shorter standby delay as on normal output to release
2169 // hardware resources as soon as possible
2170 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
Eric Laurent059b4be2009-11-09 23:32:22 -08002171
Eric Laurenta553c252009-07-17 12:17:14 -07002172 while (!exitPending())
2173 {
Eric Laurent65b65452010-06-01 23:49:17 -07002174 bool rampVolume;
2175 uint16_t leftVol;
2176 uint16_t rightVol;
2177 Vector< sp<EffectChain> > effectChains;
2178
Eric Laurenta553c252009-07-17 12:17:14 -07002179 processConfigEvents();
2180
Eric Laurent059b4be2009-11-09 23:32:22 -08002181 mixerStatus = MIXER_IDLE;
2182
Eric Laurenta553c252009-07-17 12:17:14 -07002183 { // scope for the mLock
2184
2185 Mutex::Autolock _l(mLock);
2186
2187 if (checkForNewParameters_l()) {
2188 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent059b4be2009-11-09 23:32:22 -08002189 activeSleepTime = activeSleepTimeUs();
2190 idleSleepTime = idleSleepTimeUs();
Eric Laurentef9500f2010-03-11 14:47:00 -08002191 standbyDelay = microseconds(activeSleepTime*2);
Eric Laurenta553c252009-07-17 12:17:14 -07002192 }
2193
2194 // put audio hardware into standby after short delay
2195 if UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2196 mSuspended) {
2197 // wait until we have something to do...
2198 if (!mStandby) {
2199 LOGV("Audio hardware entering standby, mixer %p\n", this);
2200 mOutput->standby();
2201 mStandby = true;
2202 mBytesWritten = 0;
2203 }
2204
2205 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2206 // we're about to wait, flush the binder command buffer
2207 IPCThreadState::self()->flushCommands();
2208
2209 if (exitPending()) break;
2210
2211 LOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
2212 mWaitWorkCV.wait(mLock);
2213 LOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
2214
2215 if (mMasterMute == false) {
2216 char value[PROPERTY_VALUE_MAX];
2217 property_get("ro.audio.silent", value, "0");
2218 if (atoi(value)) {
2219 LOGD("Silence is golden");
2220 setMasterMute(true);
2221 }
2222 }
2223
Eric Laurentef9500f2010-03-11 14:47:00 -08002224 standbyTime = systemTime() + standbyDelay;
Eric Laurent059b4be2009-11-09 23:32:22 -08002225 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07002226 continue;
2227 }
2228 }
2229
Eric Laurent65b65452010-06-01 23:49:17 -07002230 effectChains = mEffectChains;
2231
Eric Laurenta553c252009-07-17 12:17:14 -07002232 // find out which tracks need to be processed
2233 if (mActiveTracks.size() != 0) {
2234 sp<Track> t = mActiveTracks[0].promote();
2235 if (t == 0) continue;
2236
2237 Track* const track = t.get();
2238 audio_track_cblk_t* cblk = track->cblk();
2239
2240 // The first time a track is added we wait
2241 // for all its buffers to be filled before processing it
Eric Laurent9a30fc12010-10-05 14:41:42 -07002242 if (cblk->framesReady() && track->isReady() &&
Eric Laurent380558b2010-04-09 06:11:48 -07002243 !track->isPaused() && !track->isTerminated())
Eric Laurenta553c252009-07-17 12:17:14 -07002244 {
2245 //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
2246
Eric Laurent65b65452010-06-01 23:49:17 -07002247 if (track->mFillingUpStatus == Track::FS_FILLED) {
2248 track->mFillingUpStatus = Track::FS_ACTIVE;
2249 mLeftVolFloat = mRightVolFloat = 0;
2250 mLeftVolShort = mRightVolShort = 0;
2251 if (track->mState == TrackBase::RESUMING) {
2252 track->mState = TrackBase::ACTIVE;
2253 rampVolume = true;
2254 }
2255 } else if (cblk->server != 0) {
2256 // If the track is stopped before the first frame was mixed,
2257 // do not apply ramp
2258 rampVolume = true;
2259 }
Eric Laurenta553c252009-07-17 12:17:14 -07002260 // compute volume for this track
2261 float left, right;
2262 if (track->isMuted() || mMasterMute || track->isPausing() ||
2263 mStreamTypes[track->type()].mute) {
2264 left = right = 0;
2265 if (track->isPausing()) {
2266 track->setPaused();
2267 }
2268 } else {
2269 float typeVolume = mStreamTypes[track->type()].volume;
2270 float v = mMasterVolume * typeVolume;
2271 float v_clamped = v * cblk->volume[0];
2272 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2273 left = v_clamped/MAX_GAIN;
2274 v_clamped = v * cblk->volume[1];
2275 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2276 right = v_clamped/MAX_GAIN;
2277 }
2278
Eric Laurent65b65452010-06-01 23:49:17 -07002279 if (left != mLeftVolFloat || right != mRightVolFloat) {
2280 mLeftVolFloat = left;
2281 mRightVolFloat = right;
Eric Laurenta553c252009-07-17 12:17:14 -07002282
Eric Laurent65b65452010-06-01 23:49:17 -07002283 // If audio HAL implements volume control,
2284 // force software volume to nominal value
2285 if (mOutput->setVolume(left, right) == NO_ERROR) {
2286 left = 1.0f;
2287 right = 1.0f;
Eric Laurenta553c252009-07-17 12:17:14 -07002288 }
Eric Laurent65b65452010-06-01 23:49:17 -07002289
2290 // Convert volumes from float to 8.24
2291 uint32_t vl = (uint32_t)(left * (1 << 24));
2292 uint32_t vr = (uint32_t)(right * (1 << 24));
2293
2294 // Delegate volume control to effect in track effect chain if needed
2295 // only one effect chain can be present on DirectOutputThread, so if
2296 // there is one, the track is connected to it
2297 if (!effectChains.isEmpty()) {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002298 // Do not ramp volume if volume is controlled by effect
Eric Laurent76c40f72010-07-15 12:50:15 -07002299 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002300 rampVolume = false;
2301 }
2302 }
2303
2304 // Convert volumes from 8.24 to 4.12 format
2305 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2306 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2307 leftVol = (uint16_t)v_clamped;
2308 v_clamped = (vr + (1 << 11)) >> 12;
2309 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2310 rightVol = (uint16_t)v_clamped;
2311 } else {
2312 leftVol = mLeftVolShort;
2313 rightVol = mRightVolShort;
2314 rampVolume = false;
Eric Laurenta553c252009-07-17 12:17:14 -07002315 }
2316
2317 // reset retry count
Eric Laurentef9500f2010-03-11 14:47:00 -08002318 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurenta553c252009-07-17 12:17:14 -07002319 activeTrack = t;
Eric Laurent059b4be2009-11-09 23:32:22 -08002320 mixerStatus = MIXER_TRACKS_READY;
Eric Laurenta553c252009-07-17 12:17:14 -07002321 } else {
2322 //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
2323 if (track->isStopped()) {
2324 track->reset();
2325 }
2326 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2327 // We have consumed all the buffers of this track.
2328 // Remove it from the list of active tracks.
2329 trackToRemove = track;
2330 } else {
2331 // No buffers for this track. Give it a few chances to
2332 // fill a buffer, then remove it from active list.
2333 if (--(track->mRetryCount) <= 0) {
2334 LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
2335 trackToRemove = track;
Eric Laurent059b4be2009-11-09 23:32:22 -08002336 } else {
2337 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07002338 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002339 }
Eric Laurenta553c252009-07-17 12:17:14 -07002340 }
2341 }
2342
2343 // remove all the tracks that need to be...
2344 if (UNLIKELY(trackToRemove != 0)) {
2345 mActiveTracks.remove(trackToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07002346 if (!effectChains.isEmpty()) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002347 LOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
2348 trackToRemove->sessionId());
Eric Laurent65b65452010-06-01 23:49:17 -07002349 effectChains[0]->stopTrack();
2350 }
Eric Laurenta553c252009-07-17 12:17:14 -07002351 if (trackToRemove->isTerminated()) {
2352 mTracks.remove(trackToRemove);
2353 deleteTrackName_l(trackToRemove->mName);
2354 }
2355 }
Eric Laurent65b65452010-06-01 23:49:17 -07002356
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002357 lockEffectChains_l(effectChains);
Eric Laurenta553c252009-07-17 12:17:14 -07002358 }
2359
Eric Laurent059b4be2009-11-09 23:32:22 -08002360 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002361 AudioBufferProvider::Buffer buffer;
2362 size_t frameCount = mFrameCount;
2363 curBuf = (int8_t *)mMixBuffer;
2364 // output audio to hardware
Eric Laurent65b65452010-06-01 23:49:17 -07002365 while (frameCount) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002366 buffer.frameCount = frameCount;
2367 activeTrack->getNextBuffer(&buffer);
2368 if (UNLIKELY(buffer.raw == 0)) {
2369 memset(curBuf, 0, frameCount * mFrameSize);
2370 break;
2371 }
2372 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2373 frameCount -= buffer.frameCount;
2374 curBuf += buffer.frameCount * mFrameSize;
2375 activeTrack->releaseBuffer(&buffer);
2376 }
2377 sleepTime = 0;
Eric Laurentef9500f2010-03-11 14:47:00 -08002378 standbyTime = systemTime() + standbyDelay;
Eric Laurent96c08a62009-09-07 08:38:38 -07002379 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07002380 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002381 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2382 sleepTime = activeSleepTime;
2383 } else {
2384 sleepTime = idleSleepTime;
2385 }
Eric Laurent62443f52009-10-05 20:29:18 -07002386 } else if (mBytesWritten != 0 && AudioSystem::isLinearPCM(mFormat)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002387 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent96c08a62009-09-07 08:38:38 -07002388 sleepTime = 0;
Eric Laurent96c08a62009-09-07 08:38:38 -07002389 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002390 }
Eric Laurent96c08a62009-09-07 08:38:38 -07002391
Eric Laurentf69a3f82009-09-22 00:35:48 -07002392 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07002393 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07002394 }
2395 // sleepTime == 0 means we must write to audio hardware
2396 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07002397 if (mixerStatus == MIXER_TRACKS_READY) {
2398 applyVolume(leftVol, rightVol, rampVolume);
2399 }
2400 for (size_t i = 0; i < effectChains.size(); i ++) {
2401 effectChains[i]->process_l();
2402 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002403 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07002404
Eric Laurentf69a3f82009-09-22 00:35:48 -07002405 mLastWriteTime = systemTime();
2406 mInWrite = true;
Eric Laurent0986e792010-01-19 17:37:09 -08002407 mBytesWritten += mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002408 int bytesWritten = (int)mOutput->write(mMixBuffer, mixBufferSize);
Eric Laurent0986e792010-01-19 17:37:09 -08002409 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002410 mNumWrites++;
2411 mInWrite = false;
2412 mStandby = false;
2413 } else {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002414 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002415 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07002416 }
2417
2418 // finally let go of removed track, without the lock held
2419 // since we can't guarantee the destructors won't acquire that
2420 // same lock.
2421 trackToRemove.clear();
2422 activeTrack.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07002423
2424 // Effect chains will be actually deleted here if they were removed from
2425 // mEffectChains list during mixing or effects processing
2426 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07002427 }
2428
2429 if (!mStandby) {
2430 mOutput->standby();
2431 }
Eric Laurenta553c252009-07-17 12:17:14 -07002432
2433 LOGV("DirectOutputThread %p exiting", this);
2434 return false;
2435}
2436
2437// getTrackName_l() must be called with ThreadBase::mLock held
2438int AudioFlinger::DirectOutputThread::getTrackName_l()
2439{
2440 return 0;
2441}
2442
2443// deleteTrackName_l() must be called with ThreadBase::mLock held
2444void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2445{
2446}
2447
2448// checkForNewParameters_l() must be called with ThreadBase::mLock held
2449bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2450{
2451 bool reconfig = false;
2452
Eric Laurent8fce46a2009-08-04 09:45:33 -07002453 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07002454 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002455 String8 keyValuePair = mNewParameters[0];
2456 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002457 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002458
Eric Laurenta553c252009-07-17 12:17:14 -07002459 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2460 // do not accept frame count changes if tracks are open as the track buffer
2461 // size depends on frame count and correct behavior would not be garantied
2462 // if frame count is changed after track creation
2463 if (!mTracks.isEmpty()) {
2464 status = INVALID_OPERATION;
2465 } else {
2466 reconfig = true;
2467 }
2468 }
2469 if (status == NO_ERROR) {
Eric Laurent8fce46a2009-08-04 09:45:33 -07002470 status = mOutput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002471 if (!mStandby && status == INVALID_OPERATION) {
2472 mOutput->standby();
2473 mStandby = true;
2474 mBytesWritten = 0;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002475 status = mOutput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002476 }
2477 if (status == NO_ERROR && reconfig) {
2478 readOutputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07002479 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07002480 }
2481 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08002482
2483 mNewParameters.removeAt(0);
2484
Eric Laurenta553c252009-07-17 12:17:14 -07002485 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07002486 mParamCond.signal();
Eric Laurent8fce46a2009-08-04 09:45:33 -07002487 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07002488 }
2489 return reconfig;
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08002490}
2491
Eric Laurent059b4be2009-11-09 23:32:22 -08002492uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
Eric Laurent62443f52009-10-05 20:29:18 -07002493{
2494 uint32_t time;
2495 if (AudioSystem::isLinearPCM(mFormat)) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002496 time = (uint32_t)(mOutput->latency() * 1000) / 2;
2497 } else {
2498 time = 10000;
2499 }
2500 return time;
2501}
2502
2503uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2504{
2505 uint32_t time;
2506 if (AudioSystem::isLinearPCM(mFormat)) {
Eric Laurenta54d7d32010-07-29 06:50:24 -07002507 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Eric Laurent62443f52009-10-05 20:29:18 -07002508 } else {
2509 time = 10000;
2510 }
2511 return time;
2512}
2513
Eric Laurent8448a792010-08-18 18:13:17 -07002514uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2515{
2516 uint32_t time;
2517 if (AudioSystem::isLinearPCM(mFormat)) {
2518 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2519 } else {
2520 time = 10000;
2521 }
2522 return time;
2523}
2524
2525
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002526// ----------------------------------------------------------------------------
2527
Eric Laurent49f02be2009-11-19 09:00:56 -08002528AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread, int id)
Eric Laurent65b65452010-06-01 23:49:17 -07002529 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device()), mWaitTimeMs(UINT_MAX)
Eric Laurenta553c252009-07-17 12:17:14 -07002530{
2531 mType = PlaybackThread::DUPLICATING;
2532 addOutputTrack(mainThread);
2533}
2534
2535AudioFlinger::DuplicatingThread::~DuplicatingThread()
2536{
Eric Laurent0a080292009-12-07 10:53:10 -08002537 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2538 mOutputTracks[i]->destroy();
2539 }
Eric Laurenta553c252009-07-17 12:17:14 -07002540 mOutputTracks.clear();
2541}
2542
2543bool AudioFlinger::DuplicatingThread::threadLoop()
2544{
Eric Laurenta553c252009-07-17 12:17:14 -07002545 Vector< sp<Track> > tracksToRemove;
Eric Laurent059b4be2009-11-09 23:32:22 -08002546 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002547 nsecs_t standbyTime = systemTime();
2548 size_t mixBufferSize = mFrameCount*mFrameSize;
2549 SortedVector< sp<OutputTrack> > outputTracks;
Eric Laurent62443f52009-10-05 20:29:18 -07002550 uint32_t writeFrames = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08002551 uint32_t activeSleepTime = activeSleepTimeUs();
2552 uint32_t idleSleepTime = idleSleepTimeUs();
2553 uint32_t sleepTime = idleSleepTime;
Eric Laurent65b65452010-06-01 23:49:17 -07002554 Vector< sp<EffectChain> > effectChains;
Eric Laurenta553c252009-07-17 12:17:14 -07002555
2556 while (!exitPending())
2557 {
2558 processConfigEvents();
2559
Eric Laurent059b4be2009-11-09 23:32:22 -08002560 mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002561 { // scope for the mLock
2562
2563 Mutex::Autolock _l(mLock);
2564
2565 if (checkForNewParameters_l()) {
2566 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002567 updateWaitTime();
Eric Laurent059b4be2009-11-09 23:32:22 -08002568 activeSleepTime = activeSleepTimeUs();
2569 idleSleepTime = idleSleepTimeUs();
Eric Laurenta553c252009-07-17 12:17:14 -07002570 }
2571
2572 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
2573
2574 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2575 outputTracks.add(mOutputTracks[i]);
2576 }
2577
2578 // put audio hardware into standby after short delay
2579 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
2580 mSuspended) {
2581 if (!mStandby) {
2582 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurenta553c252009-07-17 12:17:14 -07002583 outputTracks[i]->stop();
Eric Laurenta553c252009-07-17 12:17:14 -07002584 }
2585 mStandby = true;
2586 mBytesWritten = 0;
2587 }
2588
2589 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
2590 // we're about to wait, flush the binder command buffer
2591 IPCThreadState::self()->flushCommands();
2592 outputTracks.clear();
2593
2594 if (exitPending()) break;
2595
2596 LOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
2597 mWaitWorkCV.wait(mLock);
2598 LOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
2599 if (mMasterMute == false) {
2600 char value[PROPERTY_VALUE_MAX];
2601 property_get("ro.audio.silent", value, "0");
2602 if (atoi(value)) {
2603 LOGD("Silence is golden");
2604 setMasterMute(true);
2605 }
2606 }
2607
2608 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent059b4be2009-11-09 23:32:22 -08002609 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07002610 continue;
2611 }
2612 }
2613
Eric Laurent059b4be2009-11-09 23:32:22 -08002614 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07002615
2616 // prevent any changes in effect chain list and in each effect chain
2617 // during mixing and effect process as the audio buffers could be deleted
2618 // or modified if an effect is created or deleted
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002619 lockEffectChains_l(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002620 }
Eric Laurenta553c252009-07-17 12:17:14 -07002621
Eric Laurent059b4be2009-11-09 23:32:22 -08002622 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurenta553c252009-07-17 12:17:14 -07002623 // mix buffers...
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002624 if (outputsReady(outputTracks)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002625 mAudioMixer->process();
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002626 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07002627 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002628 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002629 sleepTime = 0;
Eric Laurent62443f52009-10-05 20:29:18 -07002630 writeFrames = mFrameCount;
Eric Laurenta553c252009-07-17 12:17:14 -07002631 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07002632 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002633 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2634 sleepTime = activeSleepTime;
2635 } else {
2636 sleepTime = idleSleepTime;
2637 }
Eric Laurent62443f52009-10-05 20:29:18 -07002638 } else if (mBytesWritten != 0) {
2639 // flush remaining overflow buffers in output tracks
2640 for (size_t i = 0; i < outputTracks.size(); i++) {
2641 if (outputTracks[i]->isActive()) {
2642 sleepTime = 0;
2643 writeFrames = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07002644 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent62443f52009-10-05 20:29:18 -07002645 break;
2646 }
2647 }
Eric Laurenta553c252009-07-17 12:17:14 -07002648 }
2649 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002650
2651 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07002652 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07002653 }
2654 // sleepTime == 0 means we must write to audio hardware
2655 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07002656 for (size_t i = 0; i < effectChains.size(); i ++) {
2657 effectChains[i]->process_l();
2658 }
2659 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002660 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07002661
Eric Laurent62443f52009-10-05 20:29:18 -07002662 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002663 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurent65b65452010-06-01 23:49:17 -07002664 outputTracks[i]->write(mMixBuffer, writeFrames);
Eric Laurenta553c252009-07-17 12:17:14 -07002665 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002666 mStandby = false;
2667 mBytesWritten += mixBufferSize;
Eric Laurenta553c252009-07-17 12:17:14 -07002668 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07002669 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002670 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002671 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07002672 }
2673
2674 // finally let go of all our tracks, without the lock held
2675 // since we can't guarantee the destructors won't acquire that
2676 // same lock.
2677 tracksToRemove.clear();
2678 outputTracks.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07002679
2680 // Effect chains will be actually deleted here if they were removed from
2681 // mEffectChains list during mixing or effects processing
2682 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07002683 }
2684
Eric Laurenta553c252009-07-17 12:17:14 -07002685 return false;
2686}
2687
2688void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
2689{
2690 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
2691 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002692 this,
Eric Laurenta553c252009-07-17 12:17:14 -07002693 mSampleRate,
2694 mFormat,
2695 mChannelCount,
2696 frameCount);
Eric Laurent6c30a712009-08-10 23:22:32 -07002697 if (outputTrack->cblk() != NULL) {
2698 thread->setStreamVolume(AudioSystem::NUM_STREAM_TYPES, 1.0f);
2699 mOutputTracks.add(outputTrack);
2700 LOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002701 updateWaitTime();
Eric Laurent6c30a712009-08-10 23:22:32 -07002702 }
Eric Laurenta553c252009-07-17 12:17:14 -07002703}
2704
2705void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
2706{
2707 Mutex::Autolock _l(mLock);
2708 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2709 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
Eric Laurent6c30a712009-08-10 23:22:32 -07002710 mOutputTracks[i]->destroy();
Eric Laurenta553c252009-07-17 12:17:14 -07002711 mOutputTracks.removeAt(i);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002712 updateWaitTime();
Eric Laurenta553c252009-07-17 12:17:14 -07002713 return;
2714 }
2715 }
2716 LOGV("removeOutputTrack(): unkonwn thread: %p", thread);
2717}
2718
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002719void AudioFlinger::DuplicatingThread::updateWaitTime()
2720{
2721 mWaitTimeMs = UINT_MAX;
2722 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2723 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
2724 if (strong != NULL) {
2725 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
2726 if (waitTimeMs < mWaitTimeMs) {
2727 mWaitTimeMs = waitTimeMs;
2728 }
2729 }
2730 }
2731}
2732
2733
2734bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
2735{
2736 for (size_t i = 0; i < outputTracks.size(); i++) {
2737 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
2738 if (thread == 0) {
2739 LOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
2740 return false;
2741 }
2742 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2743 if (playbackThread->standby() && !playbackThread->isSuspended()) {
2744 LOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
2745 return false;
2746 }
2747 }
2748 return true;
2749}
2750
2751uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
2752{
2753 return (mWaitTimeMs * 1000) / 2;
2754}
2755
Eric Laurenta553c252009-07-17 12:17:14 -07002756// ----------------------------------------------------------------------------
2757
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002758// TrackBase constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07002759AudioFlinger::ThreadBase::TrackBase::TrackBase(
2760 const wp<ThreadBase>& thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002761 const sp<Client>& client,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002762 uint32_t sampleRate,
2763 int format,
2764 int channelCount,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002765 int frameCount,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002766 uint32_t flags,
Eric Laurent65b65452010-06-01 23:49:17 -07002767 const sp<IMemory>& sharedBuffer,
2768 int sessionId)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002769 : RefBase(),
Eric Laurenta553c252009-07-17 12:17:14 -07002770 mThread(thread),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002771 mClient(client),
Eric Laurent8a77a992009-09-09 05:16:08 -07002772 mCblk(0),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002773 mFrameCount(0),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002774 mState(IDLE),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002775 mClientTid(-1),
2776 mFormat(format),
Eric Laurent65b65452010-06-01 23:49:17 -07002777 mFlags(flags & ~SYSTEM_FLAGS_MASK),
2778 mSessionId(sessionId)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002779{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002780 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
2781
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002782 // LOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002783 size_t size = sizeof(audio_track_cblk_t);
2784 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
2785 if (sharedBuffer == 0) {
2786 size += bufferSize;
2787 }
2788
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002789 if (client != NULL) {
2790 mCblkMemory = client->heap()->allocate(size);
2791 if (mCblkMemory != 0) {
2792 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
2793 if (mCblk) { // construct the shared structure in-place.
2794 new(mCblk) audio_track_cblk_t();
2795 // clear all buffers
2796 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07002797 mCblk->sampleRate = sampleRate;
Eric Laurentb0a01472010-05-14 05:45:46 -07002798 mCblk->channelCount = (uint8_t)channelCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002799 if (sharedBuffer == 0) {
2800 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2801 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2802 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent4712baa2010-09-30 16:12:31 -07002803 // written to buffer (other flags are cleared)
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002804 mCblk->flags = CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002805 } else {
2806 mBuffer = sharedBuffer->pointer();
2807 }
2808 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002809 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002810 } else {
2811 LOGE("not enough memory for AudioTrack size=%u", size);
2812 client->heap()->dump("AudioTrack");
2813 return;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002814 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002815 } else {
2816 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
2817 if (mCblk) { // construct the shared structure in-place.
2818 new(mCblk) audio_track_cblk_t();
2819 // clear all buffers
2820 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07002821 mCblk->sampleRate = sampleRate;
Eric Laurentb0a01472010-05-14 05:45:46 -07002822 mCblk->channelCount = (uint8_t)channelCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002823 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2824 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2825 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent4712baa2010-09-30 16:12:31 -07002826 // written to buffer (other flags are cleared)
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002827 mCblk->flags = CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002828 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
2829 }
2830 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002831}
2832
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002833AudioFlinger::ThreadBase::TrackBase::~TrackBase()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002834{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002835 if (mCblk) {
Eric Laurenta553c252009-07-17 12:17:14 -07002836 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
2837 if (mClient == NULL) {
2838 delete mCblk;
2839 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002840 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002841 mCblkMemory.clear(); // and free the shared memory
Eric Laurentb9481d82009-09-17 05:12:56 -07002842 if (mClient != NULL) {
2843 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
2844 mClient.clear();
2845 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002846}
2847
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002848void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002849{
2850 buffer->raw = 0;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002851 mFrameCount = buffer->frameCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002852 step();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002853 buffer->frameCount = 0;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002854}
2855
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002856bool AudioFlinger::ThreadBase::TrackBase::step() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002857 bool result;
2858 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002859
2860 result = cblk->stepServer(mFrameCount);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002861 if (!result) {
2862 LOGV("stepServer failed acquiring cblk mutex");
2863 mFlags |= STEPSERVER_FAILED;
2864 }
2865 return result;
2866}
2867
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002868void AudioFlinger::ThreadBase::TrackBase::reset() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002869 audio_track_cblk_t* cblk = this->cblk();
2870
2871 cblk->user = 0;
2872 cblk->server = 0;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002873 cblk->userBase = 0;
2874 cblk->serverBase = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002875 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002876 LOGV("TrackBase::reset");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002877}
2878
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002879sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002880{
2881 return mCblkMemory;
2882}
2883
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002884int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
The Android Open Source Project10592532009-03-18 17:39:46 -07002885 return (int)mCblk->sampleRate;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002886}
2887
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002888int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
Eric Laurentb0a01472010-05-14 05:45:46 -07002889 return (int)mCblk->channelCount;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002890}
2891
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002892void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002893 audio_track_cblk_t* cblk = this->cblk();
Eric Laurenta553c252009-07-17 12:17:14 -07002894 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
2895 int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002896
2897 // Check validity of returned pointer in case the track control block would have been corrupted.
Eric Laurenta553c252009-07-17 12:17:14 -07002898 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
2899 ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
The Android Open Source Project10592532009-03-18 17:39:46 -07002900 LOGE("TrackBase::getBuffer buffer out of range:\n start: %p, end %p , mBuffer %p mBufferEnd %p\n \
Eric Laurentb0a01472010-05-14 05:45:46 -07002901 server %d, serverBase %d, user %d, userBase %d, channelCount %d",
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002902 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Eric Laurentb0a01472010-05-14 05:45:46 -07002903 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, cblk->channelCount);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002904 return 0;
2905 }
2906
2907 return bufferStart;
2908}
2909
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002910// ----------------------------------------------------------------------------
2911
Eric Laurenta553c252009-07-17 12:17:14 -07002912// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
2913AudioFlinger::PlaybackThread::Track::Track(
2914 const wp<ThreadBase>& thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002915 const sp<Client>& client,
2916 int streamType,
2917 uint32_t sampleRate,
2918 int format,
2919 int channelCount,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002920 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07002921 const sp<IMemory>& sharedBuffer,
2922 int sessionId)
2923 : TrackBase(thread, client, sampleRate, format, channelCount, frameCount, 0, sharedBuffer, sessionId),
Eric Laurenta92ebfa2010-08-31 13:50:07 -07002924 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
2925 mAuxEffectId(0), mHasVolumeController(false)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002926{
Eric Laurent8a77a992009-09-09 05:16:08 -07002927 if (mCblk != NULL) {
2928 sp<ThreadBase> baseThread = thread.promote();
2929 if (baseThread != 0) {
2930 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
2931 mName = playbackThread->getTrackName_l();
Eric Laurent65b65452010-06-01 23:49:17 -07002932 mMainBuffer = playbackThread->mixBuffer();
Eric Laurent8a77a992009-09-09 05:16:08 -07002933 }
2934 LOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2935 if (mName < 0) {
2936 LOGE("no more track names available");
2937 }
2938 mVolume[0] = 1.0f;
2939 mVolume[1] = 1.0f;
2940 mStreamType = streamType;
2941 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
2942 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
2943 mCblk->frameSize = AudioSystem::isLinearPCM(format) ? channelCount * sizeof(int16_t) : sizeof(int8_t);
Eric Laurenta553c252009-07-17 12:17:14 -07002944 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002945}
2946
Eric Laurenta553c252009-07-17 12:17:14 -07002947AudioFlinger::PlaybackThread::Track::~Track()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002948{
Eric Laurenta553c252009-07-17 12:17:14 -07002949 LOGV("PlaybackThread::Track destructor");
2950 sp<ThreadBase> thread = mThread.promote();
2951 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08002952 Mutex::Autolock _l(thread->mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07002953 mState = TERMINATED;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002954 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002955}
2956
Eric Laurenta553c252009-07-17 12:17:14 -07002957void AudioFlinger::PlaybackThread::Track::destroy()
2958{
2959 // NOTE: destroyTrack_l() can remove a strong reference to this Track
2960 // by removing it from mTracks vector, so there is a risk that this Tracks's
2961 // desctructor is called. As the destructor needs to lock mLock,
2962 // we must acquire a strong reference on this Track before locking mLock
2963 // here so that the destructor is called only when exiting this function.
2964 // On the other hand, as long as Track::destroy() is only called by
2965 // TrackHandle destructor, the TrackHandle still holds a strong ref on
2966 // this Track with its member mTrack.
2967 sp<Track> keep(this);
2968 { // scope for mLock
2969 sp<ThreadBase> thread = mThread.promote();
2970 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08002971 if (!isOutputTrack()) {
2972 if (mState == ACTIVE || mState == RESUMING) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002973 AudioSystem::stopOutput(thread->id(),
2974 (AudioSystem::stream_type)mStreamType,
2975 mSessionId);
Eric Laurentac196e12009-12-01 02:17:41 -08002976 }
2977 AudioSystem::releaseOutput(thread->id());
Eric Laurent49f02be2009-11-19 09:00:56 -08002978 }
Eric Laurenta553c252009-07-17 12:17:14 -07002979 Mutex::Autolock _l(thread->mLock);
2980 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2981 playbackThread->destroyTrack_l(this);
2982 }
2983 }
2984}
2985
2986void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002987{
Eric Laurent65b65452010-06-01 23:49:17 -07002988 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 -07002989 mName - AudioMixer::TRACK0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002990 (mClient == NULL) ? getpid() : mClient->pid(),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002991 mStreamType,
2992 mFormat,
Eric Laurentb0a01472010-05-14 05:45:46 -07002993 mCblk->channelCount,
Eric Laurent65b65452010-06-01 23:49:17 -07002994 mSessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002995 mFrameCount,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002996 mState,
2997 mMute,
2998 mFillingUpStatus,
2999 mCblk->sampleRate,
3000 mCblk->volume[0],
3001 mCblk->volume[1],
3002 mCblk->server,
Eric Laurent65b65452010-06-01 23:49:17 -07003003 mCblk->user,
3004 (int)mMainBuffer,
3005 (int)mAuxBuffer);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003006}
3007
Eric Laurenta553c252009-07-17 12:17:14 -07003008status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003009{
3010 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003011 uint32_t framesReady;
3012 uint32_t framesReq = buffer->frameCount;
3013
3014 // Check if last stepServer failed, try to step now
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003015 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3016 if (!step()) goto getNextBuffer_exit;
3017 LOGV("stepServer recovered");
3018 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3019 }
3020
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003021 framesReady = cblk->framesReady();
3022
3023 if (LIKELY(framesReady)) {
3024 uint32_t s = cblk->server;
3025 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3026
3027 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3028 if (framesReq > framesReady) {
3029 framesReq = framesReady;
3030 }
3031 if (s + framesReq > bufferEnd) {
3032 framesReq = bufferEnd - s;
3033 }
3034
3035 buffer->raw = getBuffer(s, framesReq);
3036 if (buffer->raw == 0) goto getNextBuffer_exit;
3037
3038 buffer->frameCount = framesReq;
3039 return NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003040 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003041
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003042getNextBuffer_exit:
3043 buffer->raw = 0;
3044 buffer->frameCount = 0;
Eric Laurent62443f52009-10-05 20:29:18 -07003045 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 -07003046 return NOT_ENOUGH_DATA;
3047}
3048
Eric Laurenta553c252009-07-17 12:17:14 -07003049bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurent9a30fc12010-10-05 14:41:42 -07003050 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003051
3052 if (mCblk->framesReady() >= mCblk->frameCount ||
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003053 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003054 mFillingUpStatus = FS_FILLED;
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003055 mCblk->flags &= ~CBLK_FORCEREADY_MSK;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003056 return true;
3057 }
3058 return false;
3059}
3060
Eric Laurenta553c252009-07-17 12:17:14 -07003061status_t AudioFlinger::PlaybackThread::Track::start()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003062{
Eric Laurent49f02be2009-11-19 09:00:56 -08003063 status_t status = NO_ERROR;
Eric Laurent0d7e0482010-07-19 06:24:46 -07003064 LOGV("start(%d), calling thread %d session %d",
3065 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Eric Laurenta553c252009-07-17 12:17:14 -07003066 sp<ThreadBase> thread = mThread.promote();
3067 if (thread != 0) {
3068 Mutex::Autolock _l(thread->mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08003069 int state = mState;
3070 // here the track could be either new, or restarted
3071 // in both cases "unstop" the track
3072 if (mState == PAUSED) {
3073 mState = TrackBase::RESUMING;
3074 LOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
3075 } else {
3076 mState = TrackBase::ACTIVE;
3077 LOGV("? => ACTIVE (%d) on thread %p", mName, this);
3078 }
3079
3080 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3081 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003082 status = AudioSystem::startOutput(thread->id(),
3083 (AudioSystem::stream_type)mStreamType,
3084 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003085 thread->mLock.lock();
3086 }
3087 if (status == NO_ERROR) {
3088 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3089 playbackThread->addTrack_l(this);
3090 } else {
3091 mState = state;
3092 }
3093 } else {
3094 status = BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -07003095 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003096 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003097}
3098
Eric Laurenta553c252009-07-17 12:17:14 -07003099void AudioFlinger::PlaybackThread::Track::stop()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003100{
Eric Laurenta553c252009-07-17 12:17:14 -07003101 LOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3102 sp<ThreadBase> thread = mThread.promote();
3103 if (thread != 0) {
3104 Mutex::Autolock _l(thread->mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08003105 int state = mState;
Eric Laurenta553c252009-07-17 12:17:14 -07003106 if (mState > STOPPED) {
3107 mState = STOPPED;
3108 // If the track is not active (PAUSED and buffers full), flush buffers
3109 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3110 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3111 reset();
3112 }
Eric Laurent62443f52009-10-05 20:29:18 -07003113 LOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003114 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003115 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3116 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003117 AudioSystem::stopOutput(thread->id(),
3118 (AudioSystem::stream_type)mStreamType,
3119 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003120 thread->mLock.lock();
3121 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003122 }
3123}
3124
Eric Laurenta553c252009-07-17 12:17:14 -07003125void AudioFlinger::PlaybackThread::Track::pause()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003126{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003127 LOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurenta553c252009-07-17 12:17:14 -07003128 sp<ThreadBase> thread = mThread.promote();
3129 if (thread != 0) {
3130 Mutex::Autolock _l(thread->mLock);
3131 if (mState == ACTIVE || mState == RESUMING) {
3132 mState = PAUSING;
Eric Laurent62443f52009-10-05 20:29:18 -07003133 LOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurent49f02be2009-11-19 09:00:56 -08003134 if (!isOutputTrack()) {
3135 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003136 AudioSystem::stopOutput(thread->id(),
3137 (AudioSystem::stream_type)mStreamType,
3138 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003139 thread->mLock.lock();
3140 }
Eric Laurenta553c252009-07-17 12:17:14 -07003141 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003142 }
3143}
3144
Eric Laurenta553c252009-07-17 12:17:14 -07003145void AudioFlinger::PlaybackThread::Track::flush()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003146{
3147 LOGV("flush(%d)", mName);
Eric Laurenta553c252009-07-17 12:17:14 -07003148 sp<ThreadBase> thread = mThread.promote();
3149 if (thread != 0) {
3150 Mutex::Autolock _l(thread->mLock);
3151 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3152 return;
3153 }
3154 // No point remaining in PAUSED state after a flush => go to
3155 // STOPPED state
3156 mState = STOPPED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003157
Eric Laurenta553c252009-07-17 12:17:14 -07003158 mCblk->lock.lock();
3159 // NOTE: reset() will reset cblk->user and cblk->server with
3160 // the risk that at the same time, the AudioMixer is trying to read
3161 // data. In this case, getNextBuffer() would return a NULL pointer
3162 // as audio buffer => the AudioMixer code MUST always test that pointer
3163 // returned by getNextBuffer() is not NULL!
3164 reset();
3165 mCblk->lock.unlock();
3166 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003167}
3168
Eric Laurenta553c252009-07-17 12:17:14 -07003169void AudioFlinger::PlaybackThread::Track::reset()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003170{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003171 // Do not reset twice to avoid discarding data written just after a flush and before
3172 // the audioflinger thread detects the track is stopped.
3173 if (!mResetDone) {
3174 TrackBase::reset();
3175 // Force underrun condition to avoid false underrun callback until first data is
3176 // written to buffer
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003177 mCblk->flags |= CBLK_UNDERRUN_ON;
3178 mCblk->flags &= ~CBLK_FORCEREADY_MSK;
Eric Laurenta553c252009-07-17 12:17:14 -07003179 mFillingUpStatus = FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003180 mResetDone = true;
3181 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003182}
3183
Eric Laurenta553c252009-07-17 12:17:14 -07003184void AudioFlinger::PlaybackThread::Track::mute(bool muted)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003185{
3186 mMute = muted;
3187}
3188
Eric Laurenta553c252009-07-17 12:17:14 -07003189void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003190{
3191 mVolume[0] = left;
3192 mVolume[1] = right;
3193}
3194
Eric Laurent65b65452010-06-01 23:49:17 -07003195status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3196{
3197 status_t status = DEAD_OBJECT;
3198 sp<ThreadBase> thread = mThread.promote();
3199 if (thread != 0) {
3200 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3201 status = playbackThread->attachAuxEffect(this, EffectId);
3202 }
3203 return status;
3204}
3205
3206void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3207{
3208 mAuxEffectId = EffectId;
3209 mAuxBuffer = buffer;
3210}
3211
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003212// ----------------------------------------------------------------------------
3213
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003214// RecordTrack constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07003215AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3216 const wp<ThreadBase>& thread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003217 const sp<Client>& client,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003218 uint32_t sampleRate,
3219 int format,
3220 int channelCount,
3221 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07003222 uint32_t flags,
3223 int sessionId)
Eric Laurenta553c252009-07-17 12:17:14 -07003224 : TrackBase(thread, client, sampleRate, format,
Eric Laurent65b65452010-06-01 23:49:17 -07003225 channelCount, frameCount, flags, 0, sessionId),
Eric Laurenta553c252009-07-17 12:17:14 -07003226 mOverflow(false)
3227{
Eric Laurent8a77a992009-09-09 05:16:08 -07003228 if (mCblk != NULL) {
3229 LOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
3230 if (format == AudioSystem::PCM_16_BIT) {
3231 mCblk->frameSize = channelCount * sizeof(int16_t);
3232 } else if (format == AudioSystem::PCM_8_BIT) {
3233 mCblk->frameSize = channelCount * sizeof(int8_t);
3234 } else {
3235 mCblk->frameSize = sizeof(int8_t);
3236 }
3237 }
Eric Laurenta553c252009-07-17 12:17:14 -07003238}
3239
3240AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003241{
Eric Laurent49f02be2009-11-19 09:00:56 -08003242 sp<ThreadBase> thread = mThread.promote();
3243 if (thread != 0) {
3244 AudioSystem::releaseInput(thread->id());
3245 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003246}
3247
Eric Laurenta553c252009-07-17 12:17:14 -07003248status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003249{
3250 audio_track_cblk_t* cblk = this->cblk();
3251 uint32_t framesAvail;
3252 uint32_t framesReq = buffer->frameCount;
3253
3254 // Check if last stepServer failed, try to step now
3255 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3256 if (!step()) goto getNextBuffer_exit;
3257 LOGV("stepServer recovered");
3258 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3259 }
3260
3261 framesAvail = cblk->framesAvailable_l();
3262
3263 if (LIKELY(framesAvail)) {
3264 uint32_t s = cblk->server;
3265 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3266
3267 if (framesReq > framesAvail) {
3268 framesReq = framesAvail;
3269 }
3270 if (s + framesReq > bufferEnd) {
3271 framesReq = bufferEnd - s;
3272 }
3273
3274 buffer->raw = getBuffer(s, framesReq);
3275 if (buffer->raw == 0) goto getNextBuffer_exit;
3276
3277 buffer->frameCount = framesReq;
3278 return NO_ERROR;
3279 }
3280
3281getNextBuffer_exit:
3282 buffer->raw = 0;
3283 buffer->frameCount = 0;
3284 return NOT_ENOUGH_DATA;
3285}
3286
Eric Laurenta553c252009-07-17 12:17:14 -07003287status_t AudioFlinger::RecordThread::RecordTrack::start()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003288{
Eric Laurenta553c252009-07-17 12:17:14 -07003289 sp<ThreadBase> thread = mThread.promote();
3290 if (thread != 0) {
3291 RecordThread *recordThread = (RecordThread *)thread.get();
3292 return recordThread->start(this);
Eric Laurent49f02be2009-11-19 09:00:56 -08003293 } else {
3294 return BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -07003295 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003296}
3297
Eric Laurenta553c252009-07-17 12:17:14 -07003298void AudioFlinger::RecordThread::RecordTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003299{
Eric Laurenta553c252009-07-17 12:17:14 -07003300 sp<ThreadBase> thread = mThread.promote();
3301 if (thread != 0) {
3302 RecordThread *recordThread = (RecordThread *)thread.get();
3303 recordThread->stop(this);
3304 TrackBase::reset();
3305 // Force overerrun condition to avoid false overrun callback until first data is
3306 // read from buffer
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003307 mCblk->flags |= CBLK_UNDERRUN_ON;
Eric Laurenta553c252009-07-17 12:17:14 -07003308 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003309}
3310
Eric Laurent3fdb1262009-11-07 00:01:32 -08003311void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3312{
Eric Laurent65b65452010-06-01 23:49:17 -07003313 snprintf(buffer, size, " %05d %03u %03u %05d %04u %01d %05u %08x %08x\n",
Eric Laurent3fdb1262009-11-07 00:01:32 -08003314 (mClient == NULL) ? getpid() : mClient->pid(),
3315 mFormat,
Eric Laurentb0a01472010-05-14 05:45:46 -07003316 mCblk->channelCount,
Eric Laurent65b65452010-06-01 23:49:17 -07003317 mSessionId,
Eric Laurent3fdb1262009-11-07 00:01:32 -08003318 mFrameCount,
3319 mState,
3320 mCblk->sampleRate,
3321 mCblk->server,
3322 mCblk->user);
3323}
3324
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003325
3326// ----------------------------------------------------------------------------
3327
Eric Laurenta553c252009-07-17 12:17:14 -07003328AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3329 const wp<ThreadBase>& thread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003330 DuplicatingThread *sourceThread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003331 uint32_t sampleRate,
3332 int format,
3333 int channelCount,
3334 int frameCount)
Eric Laurent65b65452010-06-01 23:49:17 -07003335 : Track(thread, NULL, AudioSystem::NUM_STREAM_TYPES, sampleRate, format, channelCount, frameCount, NULL, 0),
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003336 mActive(false), mSourceThread(sourceThread)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003337{
Eric Laurenta553c252009-07-17 12:17:14 -07003338
3339 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
Eric Laurent6c30a712009-08-10 23:22:32 -07003340 if (mCblk != NULL) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003341 mCblk->flags |= CBLK_DIRECTION_OUT;
Eric Laurent6c30a712009-08-10 23:22:32 -07003342 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
3343 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
3344 mOutBuffer.frameCount = 0;
Eric Laurent6c30a712009-08-10 23:22:32 -07003345 playbackThread->mTracks.add(this);
Eric Laurentb0a01472010-05-14 05:45:46 -07003346 LOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, mCblk->frameCount %d, mCblk->sampleRate %d, mCblk->channelCount %d mBufferEnd %p",
3347 mCblk, mBuffer, mCblk->buffers, mCblk->frameCount, mCblk->sampleRate, mCblk->channelCount, mBufferEnd);
Eric Laurent6c30a712009-08-10 23:22:32 -07003348 } else {
3349 LOGW("Error creating output track on thread %p", playbackThread);
3350 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003351}
3352
Eric Laurenta553c252009-07-17 12:17:14 -07003353AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003354{
Eric Laurent6c30a712009-08-10 23:22:32 -07003355 clearBufferQueue();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003356}
3357
Eric Laurenta553c252009-07-17 12:17:14 -07003358status_t AudioFlinger::PlaybackThread::OutputTrack::start()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003359{
3360 status_t status = Track::start();
Eric Laurenta553c252009-07-17 12:17:14 -07003361 if (status != NO_ERROR) {
3362 return status;
3363 }
3364
3365 mActive = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003366 mRetryCount = 127;
3367 return status;
3368}
3369
Eric Laurenta553c252009-07-17 12:17:14 -07003370void AudioFlinger::PlaybackThread::OutputTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003371{
3372 Track::stop();
3373 clearBufferQueue();
3374 mOutBuffer.frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003375 mActive = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003376}
3377
Eric Laurenta553c252009-07-17 12:17:14 -07003378bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003379{
3380 Buffer *pInBuffer;
3381 Buffer inBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003382 uint32_t channelCount = mCblk->channelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003383 bool outputBufferFull = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003384 inBuffer.frameCount = frames;
3385 inBuffer.i16 = data;
Eric Laurenta553c252009-07-17 12:17:14 -07003386
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003387 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
Eric Laurenta553c252009-07-17 12:17:14 -07003388
Eric Laurent62443f52009-10-05 20:29:18 -07003389 if (!mActive && frames != 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003390 start();
3391 sp<ThreadBase> thread = mThread.promote();
3392 if (thread != 0) {
3393 MixerThread *mixerThread = (MixerThread *)thread.get();
3394 if (mCblk->frameCount > frames){
3395 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3396 uint32_t startFrames = (mCblk->frameCount - frames);
3397 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003398 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
Eric Laurenta553c252009-07-17 12:17:14 -07003399 pInBuffer->frameCount = startFrames;
3400 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003401 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
Eric Laurenta553c252009-07-17 12:17:14 -07003402 mBufferQueue.add(pInBuffer);
3403 } else {
3404 LOGW ("OutputTrack::write() %p no more buffers in queue", this);
3405 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003406 }
Eric Laurenta553c252009-07-17 12:17:14 -07003407 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003408 }
3409
Eric Laurenta553c252009-07-17 12:17:14 -07003410 while (waitTimeLeftMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003411 // First write pending buffers, then new data
3412 if (mBufferQueue.size()) {
3413 pInBuffer = mBufferQueue.itemAt(0);
3414 } else {
3415 pInBuffer = &inBuffer;
3416 }
Eric Laurenta553c252009-07-17 12:17:14 -07003417
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003418 if (pInBuffer->frameCount == 0) {
3419 break;
3420 }
Eric Laurenta553c252009-07-17 12:17:14 -07003421
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003422 if (mOutBuffer.frameCount == 0) {
3423 mOutBuffer.frameCount = pInBuffer->frameCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003424 nsecs_t startTime = systemTime();
3425 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003426 LOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Eric Laurenta553c252009-07-17 12:17:14 -07003427 outputBufferFull = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003428 break;
3429 }
Eric Laurenta553c252009-07-17 12:17:14 -07003430 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
Eric Laurenta553c252009-07-17 12:17:14 -07003431 if (waitTimeLeftMs >= waitTimeMs) {
3432 waitTimeLeftMs -= waitTimeMs;
3433 } else {
3434 waitTimeLeftMs = 0;
3435 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003436 }
Eric Laurenta553c252009-07-17 12:17:14 -07003437
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003438 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
Eric Laurentb0a01472010-05-14 05:45:46 -07003439 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003440 mCblk->stepUser(outFrames);
3441 pInBuffer->frameCount -= outFrames;
Eric Laurentb0a01472010-05-14 05:45:46 -07003442 pInBuffer->i16 += outFrames * channelCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003443 mOutBuffer.frameCount -= outFrames;
Eric Laurentb0a01472010-05-14 05:45:46 -07003444 mOutBuffer.i16 += outFrames * channelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003445
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003446 if (pInBuffer->frameCount == 0) {
3447 if (mBufferQueue.size()) {
3448 mBufferQueue.removeAt(0);
3449 delete [] pInBuffer->mBuffer;
3450 delete pInBuffer;
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003451 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 -08003452 } else {
3453 break;
3454 }
3455 }
3456 }
Eric Laurenta553c252009-07-17 12:17:14 -07003457
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003458 // If we could not write all frames, allocate a buffer and queue it for next time.
3459 if (inBuffer.frameCount) {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003460 sp<ThreadBase> thread = mThread.promote();
3461 if (thread != 0 && !thread->standby()) {
3462 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3463 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003464 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003465 pInBuffer->frameCount = inBuffer.frameCount;
3466 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003467 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003468 mBufferQueue.add(pInBuffer);
3469 LOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
3470 } else {
3471 LOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
3472 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003473 }
3474 }
Eric Laurenta553c252009-07-17 12:17:14 -07003475
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003476 // Calling write() with a 0 length buffer, means that no more data will be written:
Eric Laurenta553c252009-07-17 12:17:14 -07003477 // 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 -08003478 // by output mixer.
Eric Laurenta553c252009-07-17 12:17:14 -07003479 if (frames == 0 && mBufferQueue.size() == 0) {
3480 if (mCblk->user < mCblk->frameCount) {
3481 frames = mCblk->frameCount - mCblk->user;
3482 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003483 pInBuffer->mBuffer = new int16_t[frames * channelCount];
Eric Laurenta553c252009-07-17 12:17:14 -07003484 pInBuffer->frameCount = frames;
3485 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003486 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
Eric Laurenta553c252009-07-17 12:17:14 -07003487 mBufferQueue.add(pInBuffer);
Eric Laurent62443f52009-10-05 20:29:18 -07003488 } else if (mActive) {
Eric Laurenta553c252009-07-17 12:17:14 -07003489 stop();
3490 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003491 }
3492
Eric Laurenta553c252009-07-17 12:17:14 -07003493 return outputBufferFull;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003494}
3495
Eric Laurenta553c252009-07-17 12:17:14 -07003496status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003497{
3498 int active;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003499 status_t result;
3500 audio_track_cblk_t* cblk = mCblk;
3501 uint32_t framesReq = buffer->frameCount;
3502
Eric Laurenta553c252009-07-17 12:17:14 -07003503// LOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003504 buffer->frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003505
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003506 uint32_t framesAvail = cblk->framesAvailable();
3507
Eric Laurenta553c252009-07-17 12:17:14 -07003508
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003509 if (framesAvail == 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003510 Mutex::Autolock _l(cblk->lock);
3511 goto start_loop_here;
3512 while (framesAvail == 0) {
3513 active = mActive;
3514 if (UNLIKELY(!active)) {
3515 LOGV("Not active and NO_MORE_BUFFERS");
3516 return AudioTrack::NO_MORE_BUFFERS;
3517 }
3518 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3519 if (result != NO_ERROR) {
3520 return AudioTrack::NO_MORE_BUFFERS;
3521 }
3522 // read the server count again
3523 start_loop_here:
3524 framesAvail = cblk->framesAvailable_l();
3525 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003526 }
3527
Eric Laurenta553c252009-07-17 12:17:14 -07003528// if (framesAvail < framesReq) {
3529// return AudioTrack::NO_MORE_BUFFERS;
3530// }
3531
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003532 if (framesReq > framesAvail) {
3533 framesReq = framesAvail;
3534 }
3535
3536 uint32_t u = cblk->user;
3537 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
3538
3539 if (u + framesReq > bufferEnd) {
3540 framesReq = bufferEnd - u;
3541 }
3542
3543 buffer->frameCount = framesReq;
3544 buffer->raw = (void *)cblk->buffer(u);
3545 return NO_ERROR;
3546}
3547
3548
Eric Laurenta553c252009-07-17 12:17:14 -07003549void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003550{
3551 size_t size = mBufferQueue.size();
3552 Buffer *pBuffer;
Eric Laurenta553c252009-07-17 12:17:14 -07003553
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003554 for (size_t i = 0; i < size; i++) {
3555 pBuffer = mBufferQueue.itemAt(i);
3556 delete [] pBuffer->mBuffer;
3557 delete pBuffer;
3558 }
3559 mBufferQueue.clear();
3560}
3561
3562// ----------------------------------------------------------------------------
3563
3564AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
3565 : RefBase(),
3566 mAudioFlinger(audioFlinger),
Mathias Agopian6faf7892010-01-25 19:00:00 -08003567 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003568 mPid(pid)
3569{
3570 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
3571}
3572
Eric Laurentb9481d82009-09-17 05:12:56 -07003573// Client destructor must be called with AudioFlinger::mLock held
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003574AudioFlinger::Client::~Client()
3575{
Eric Laurentb9481d82009-09-17 05:12:56 -07003576 mAudioFlinger->removeClient_l(mPid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003577}
3578
3579const sp<MemoryDealer>& AudioFlinger::Client::heap() const
3580{
3581 return mMemoryDealer;
3582}
3583
3584// ----------------------------------------------------------------------------
3585
Eric Laurent4f0f17d2010-05-12 02:05:53 -07003586AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
3587 const sp<IAudioFlingerClient>& client,
3588 pid_t pid)
3589 : mAudioFlinger(audioFlinger), mPid(pid), mClient(client)
3590{
3591}
3592
3593AudioFlinger::NotificationClient::~NotificationClient()
3594{
3595 mClient.clear();
3596}
3597
3598void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
3599{
3600 sp<NotificationClient> keep(this);
3601 {
3602 mAudioFlinger->removeNotificationClient(mPid);
3603 }
3604}
3605
3606// ----------------------------------------------------------------------------
3607
Eric Laurenta553c252009-07-17 12:17:14 -07003608AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003609 : BnAudioTrack(),
3610 mTrack(track)
3611{
3612}
3613
3614AudioFlinger::TrackHandle::~TrackHandle() {
3615 // just stop the track on deletion, associated resources
3616 // will be freed from the main thread once all pending buffers have
3617 // been played. Unless it's not in the active track list, in which
3618 // case we free everything now...
3619 mTrack->destroy();
3620}
3621
3622status_t AudioFlinger::TrackHandle::start() {
3623 return mTrack->start();
3624}
3625
3626void AudioFlinger::TrackHandle::stop() {
3627 mTrack->stop();
3628}
3629
3630void AudioFlinger::TrackHandle::flush() {
3631 mTrack->flush();
3632}
3633
3634void AudioFlinger::TrackHandle::mute(bool e) {
3635 mTrack->mute(e);
3636}
3637
3638void AudioFlinger::TrackHandle::pause() {
3639 mTrack->pause();
3640}
3641
3642void AudioFlinger::TrackHandle::setVolume(float left, float right) {
3643 mTrack->setVolume(left, right);
3644}
3645
3646sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
3647 return mTrack->getCblk();
3648}
3649
Eric Laurent65b65452010-06-01 23:49:17 -07003650status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
3651{
3652 return mTrack->attachAuxEffect(EffectId);
3653}
3654
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003655status_t AudioFlinger::TrackHandle::onTransact(
3656 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3657{
3658 return BnAudioTrack::onTransact(code, data, reply, flags);
3659}
3660
3661// ----------------------------------------------------------------------------
3662
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003663sp<IAudioRecord> AudioFlinger::openRecord(
3664 pid_t pid,
Eric Laurentddb78e72009-07-28 08:44:33 -07003665 int input,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003666 uint32_t sampleRate,
3667 int format,
3668 int channelCount,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003669 int frameCount,
3670 uint32_t flags,
Eric Laurent65b65452010-06-01 23:49:17 -07003671 int *sessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003672 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003673{
Eric Laurenta553c252009-07-17 12:17:14 -07003674 sp<RecordThread::RecordTrack> recordTrack;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003675 sp<RecordHandle> recordHandle;
3676 sp<Client> client;
3677 wp<Client> wclient;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003678 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07003679 RecordThread *thread;
3680 size_t inFrameCount;
Eric Laurent65b65452010-06-01 23:49:17 -07003681 int lSessionId;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003682
3683 // check calling permissions
3684 if (!recordingAllowed()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003685 lStatus = PERMISSION_DENIED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003686 goto Exit;
3687 }
3688
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003689 // add client to list
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003690 { // scope for mLock
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003691 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07003692 thread = checkRecordThread_l(input);
3693 if (thread == NULL) {
3694 lStatus = BAD_VALUE;
3695 goto Exit;
3696 }
3697
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003698 wclient = mClients.valueFor(pid);
3699 if (wclient != NULL) {
3700 client = wclient.promote();
3701 } else {
3702 client = new Client(this, pid);
3703 mClients.add(pid, client);
3704 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003705
Eric Laurent65b65452010-06-01 23:49:17 -07003706 // If no audio session id is provided, create one here
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003707 if (sessionId != NULL && *sessionId != AudioSystem::SESSION_OUTPUT_MIX) {
Eric Laurent65b65452010-06-01 23:49:17 -07003708 lSessionId = *sessionId;
3709 } else {
Eric Laurentf3d6dd02010-11-18 08:40:16 -08003710 lSessionId = nextUniqueId_l();
Eric Laurent65b65452010-06-01 23:49:17 -07003711 if (sessionId != NULL) {
3712 *sessionId = lSessionId;
3713 }
3714 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003715 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurenta553c252009-07-17 12:17:14 -07003716 recordTrack = new RecordThread::RecordTrack(thread, client, sampleRate,
Eric Laurent65b65452010-06-01 23:49:17 -07003717 format, channelCount, frameCount, flags, lSessionId);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003718 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003719 if (recordTrack->getCblk() == NULL) {
Eric Laurentb9481d82009-09-17 05:12:56 -07003720 // remove local strong reference to Client before deleting the RecordTrack so that the Client
3721 // destructor is called by the TrackBase destructor with mLock held
3722 client.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003723 recordTrack.clear();
3724 lStatus = NO_MEMORY;
3725 goto Exit;
3726 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003727
3728 // return to handle to client
3729 recordHandle = new RecordHandle(recordTrack);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003730 lStatus = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003731
3732Exit:
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003733 if (status) {
3734 *status = lStatus;
3735 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003736 return recordHandle;
3737}
3738
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003739// ----------------------------------------------------------------------------
3740
Eric Laurenta553c252009-07-17 12:17:14 -07003741AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003742 : BnAudioRecord(),
3743 mRecordTrack(recordTrack)
3744{
3745}
3746
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003747AudioFlinger::RecordHandle::~RecordHandle() {
3748 stop();
3749}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003750
3751status_t AudioFlinger::RecordHandle::start() {
3752 LOGV("RecordHandle::start()");
3753 return mRecordTrack->start();
3754}
3755
3756void AudioFlinger::RecordHandle::stop() {
3757 LOGV("RecordHandle::stop()");
3758 mRecordTrack->stop();
3759}
3760
3761sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
3762 return mRecordTrack->getCblk();
3763}
3764
3765status_t AudioFlinger::RecordHandle::onTransact(
3766 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3767{
3768 return BnAudioRecord::onTransact(code, data, reply, flags);
3769}
3770
3771// ----------------------------------------------------------------------------
3772
Eric Laurent49f02be2009-11-19 09:00:56 -08003773AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger, AudioStreamIn *input, uint32_t sampleRate, uint32_t channels, int id) :
3774 ThreadBase(audioFlinger, id),
Eric Laurenta553c252009-07-17 12:17:14 -07003775 mInput(input), mResampler(0), mRsmpOutBuffer(0), mRsmpInBuffer(0)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003776{
Eric Laurenta553c252009-07-17 12:17:14 -07003777 mReqChannelCount = AudioSystem::popCount(channels);
3778 mReqSampleRate = sampleRate;
3779 readInputParameters();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003780}
3781
Eric Laurenta553c252009-07-17 12:17:14 -07003782
3783AudioFlinger::RecordThread::~RecordThread()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003784{
Eric Laurenta553c252009-07-17 12:17:14 -07003785 delete[] mRsmpInBuffer;
3786 if (mResampler != 0) {
3787 delete mResampler;
3788 delete[] mRsmpOutBuffer;
3789 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003790}
3791
Eric Laurenta553c252009-07-17 12:17:14 -07003792void AudioFlinger::RecordThread::onFirstRef()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003793{
Eric Laurenta553c252009-07-17 12:17:14 -07003794 const size_t SIZE = 256;
3795 char buffer[SIZE];
3796
3797 snprintf(buffer, SIZE, "Record Thread %p", this);
3798
3799 run(buffer, PRIORITY_URGENT_AUDIO);
3800}
Eric Laurent49f02be2009-11-19 09:00:56 -08003801
Eric Laurenta553c252009-07-17 12:17:14 -07003802bool AudioFlinger::RecordThread::threadLoop()
3803{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003804 AudioBufferProvider::Buffer buffer;
Eric Laurenta553c252009-07-17 12:17:14 -07003805 sp<RecordTrack> activeTrack;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003806
Eric Laurent4712baa2010-09-30 16:12:31 -07003807 nsecs_t lastWarning = 0;
3808
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003809 // start recording
3810 while (!exitPending()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003811
Eric Laurenta553c252009-07-17 12:17:14 -07003812 processConfigEvents();
3813
3814 { // scope for mLock
3815 Mutex::Autolock _l(mLock);
3816 checkForNewParameters_l();
3817 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
3818 if (!mStandby) {
3819 mInput->standby();
3820 mStandby = true;
3821 }
3822
3823 if (exitPending()) break;
3824
3825 LOGV("RecordThread: loop stopping");
3826 // go to sleep
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003827 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07003828 LOGV("RecordThread: loop starting");
3829 continue;
3830 }
3831 if (mActiveTrack != 0) {
3832 if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08003833 if (!mStandby) {
3834 mInput->standby();
3835 mStandby = true;
3836 }
Eric Laurenta553c252009-07-17 12:17:14 -07003837 mActiveTrack.clear();
3838 mStartStopCond.broadcast();
3839 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
Eric Laurenta553c252009-07-17 12:17:14 -07003840 if (mReqChannelCount != mActiveTrack->channelCount()) {
3841 mActiveTrack.clear();
Eric Laurent9cc489a22009-12-05 05:20:01 -08003842 mStartStopCond.broadcast();
3843 } else if (mBytesRead != 0) {
3844 // record start succeeds only if first read from audio input
3845 // succeeds
3846 if (mBytesRead > 0) {
3847 mActiveTrack->mState = TrackBase::ACTIVE;
3848 } else {
3849 mActiveTrack.clear();
3850 }
3851 mStartStopCond.broadcast();
Eric Laurenta553c252009-07-17 12:17:14 -07003852 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08003853 mStandby = false;
Eric Laurenta553c252009-07-17 12:17:14 -07003854 }
Eric Laurenta553c252009-07-17 12:17:14 -07003855 }
3856 }
3857
3858 if (mActiveTrack != 0) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08003859 if (mActiveTrack->mState != TrackBase::ACTIVE &&
3860 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent49f02be2009-11-19 09:00:56 -08003861 usleep(5000);
3862 continue;
3863 }
Eric Laurenta553c252009-07-17 12:17:14 -07003864 buffer.frameCount = mFrameCount;
3865 if (LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
3866 size_t framesOut = buffer.frameCount;
3867 if (mResampler == 0) {
3868 // no resampling
3869 while (framesOut) {
3870 size_t framesIn = mFrameCount - mRsmpInIndex;
3871 if (framesIn) {
3872 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
3873 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
3874 if (framesIn > framesOut)
3875 framesIn = framesOut;
3876 mRsmpInIndex += framesIn;
3877 framesOut -= framesIn;
Eric Laurentb0a01472010-05-14 05:45:46 -07003878 if ((int)mChannelCount == mReqChannelCount ||
Eric Laurenta553c252009-07-17 12:17:14 -07003879 mFormat != AudioSystem::PCM_16_BIT) {
3880 memcpy(dst, src, framesIn * mFrameSize);
3881 } else {
3882 int16_t *src16 = (int16_t *)src;
3883 int16_t *dst16 = (int16_t *)dst;
3884 if (mChannelCount == 1) {
3885 while (framesIn--) {
3886 *dst16++ = *src16;
3887 *dst16++ = *src16++;
3888 }
3889 } else {
3890 while (framesIn--) {
3891 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
3892 src16 += 2;
3893 }
3894 }
3895 }
3896 }
3897 if (framesOut && mFrameCount == mRsmpInIndex) {
Eric Laurenta553c252009-07-17 12:17:14 -07003898 if (framesOut == mFrameCount &&
Eric Laurentb0a01472010-05-14 05:45:46 -07003899 ((int)mChannelCount == mReqChannelCount || mFormat != AudioSystem::PCM_16_BIT)) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08003900 mBytesRead = mInput->read(buffer.raw, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07003901 framesOut = 0;
3902 } else {
Eric Laurent9cc489a22009-12-05 05:20:01 -08003903 mBytesRead = mInput->read(mRsmpInBuffer, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07003904 mRsmpInIndex = 0;
3905 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08003906 if (mBytesRead < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003907 LOGE("Error reading audio input");
Eric Laurent9cc489a22009-12-05 05:20:01 -08003908 if (mActiveTrack->mState == TrackBase::ACTIVE) {
Eric Laurentba8811f2010-03-02 18:38:06 -08003909 // Force input into standby so that it tries to
3910 // recover at next read attempt
3911 mInput->standby();
3912 usleep(5000);
Eric Laurent9cc489a22009-12-05 05:20:01 -08003913 }
Eric Laurenta553c252009-07-17 12:17:14 -07003914 mRsmpInIndex = mFrameCount;
3915 framesOut = 0;
3916 buffer.frameCount = 0;
3917 }
3918 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003919 }
3920 } else {
Eric Laurenta553c252009-07-17 12:17:14 -07003921 // resampling
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003922
Eric Laurenta553c252009-07-17 12:17:14 -07003923 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
3924 // alter output frame count as if we were expecting stereo samples
3925 if (mChannelCount == 1 && mReqChannelCount == 1) {
3926 framesOut >>= 1;
3927 }
3928 mResampler->resample(mRsmpOutBuffer, framesOut, this);
3929 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
3930 // are 32 bit aligned which should be always true.
3931 if (mChannelCount == 2 && mReqChannelCount == 1) {
3932 AudioMixer::ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
3933 // the resampler always outputs stereo samples: do post stereo to mono conversion
3934 int16_t *src = (int16_t *)mRsmpOutBuffer;
3935 int16_t *dst = buffer.i16;
3936 while (framesOut--) {
3937 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
3938 src += 2;
3939 }
3940 } else {
3941 AudioMixer::ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
3942 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003943
Eric Laurenta553c252009-07-17 12:17:14 -07003944 }
3945 mActiveTrack->releaseBuffer(&buffer);
3946 mActiveTrack->overflow();
3947 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003948 // client isn't retrieving buffers fast enough
3949 else {
Eric Laurent4712baa2010-09-30 16:12:31 -07003950 if (!mActiveTrack->setOverflow()) {
3951 nsecs_t now = systemTime();
3952 if ((now - lastWarning) > kWarningThrottle) {
3953 LOGW("RecordThread: buffer overflow");
3954 lastWarning = now;
3955 }
3956 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003957 // Release the processor for a while before asking for a new buffer.
3958 // This will give the application more chance to read from the buffer and
3959 // clear the overflow.
3960 usleep(5000);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003961 }
3962 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003963 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003964
Eric Laurenta553c252009-07-17 12:17:14 -07003965 if (!mStandby) {
3966 mInput->standby();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003967 }
Eric Laurenta553c252009-07-17 12:17:14 -07003968 mActiveTrack.clear();
3969
Eric Laurent49f02be2009-11-19 09:00:56 -08003970 mStartStopCond.broadcast();
3971
Eric Laurenta553c252009-07-17 12:17:14 -07003972 LOGV("RecordThread %p exiting", this);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003973 return false;
3974}
3975
Eric Laurenta553c252009-07-17 12:17:14 -07003976status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003977{
Eric Laurenta553c252009-07-17 12:17:14 -07003978 LOGV("RecordThread::start");
Eric Laurent49f02be2009-11-19 09:00:56 -08003979 sp <ThreadBase> strongMe = this;
3980 status_t status = NO_ERROR;
3981 {
3982 AutoMutex lock(&mLock);
3983 if (mActiveTrack != 0) {
3984 if (recordTrack != mActiveTrack.get()) {
3985 status = -EBUSY;
3986 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08003987 mActiveTrack->mState = TrackBase::ACTIVE;
Eric Laurent49f02be2009-11-19 09:00:56 -08003988 }
3989 return status;
3990 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003991
Eric Laurent49f02be2009-11-19 09:00:56 -08003992 recordTrack->mState = TrackBase::IDLE;
3993 mActiveTrack = recordTrack;
3994 mLock.unlock();
3995 status_t status = AudioSystem::startInput(mId);
3996 mLock.lock();
3997 if (status != NO_ERROR) {
3998 mActiveTrack.clear();
3999 return status;
4000 }
4001 mActiveTrack->mState = TrackBase::RESUMING;
Eric Laurent9cc489a22009-12-05 05:20:01 -08004002 mRsmpInIndex = mFrameCount;
4003 mBytesRead = 0;
Eric Laurent49f02be2009-11-19 09:00:56 -08004004 // signal thread to start
4005 LOGV("Signal record thread");
4006 mWaitWorkCV.signal();
4007 // do not wait for mStartStopCond if exiting
4008 if (mExiting) {
4009 mActiveTrack.clear();
4010 status = INVALID_OPERATION;
4011 goto startError;
4012 }
4013 mStartStopCond.wait(mLock);
4014 if (mActiveTrack == 0) {
4015 LOGV("Record failed to start");
4016 status = BAD_VALUE;
4017 goto startError;
4018 }
Eric Laurenta553c252009-07-17 12:17:14 -07004019 LOGV("Record started OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08004020 return status;
Eric Laurenta553c252009-07-17 12:17:14 -07004021 }
Eric Laurent49f02be2009-11-19 09:00:56 -08004022startError:
4023 AudioSystem::stopInput(mId);
4024 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004025}
4026
Eric Laurenta553c252009-07-17 12:17:14 -07004027void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
4028 LOGV("RecordThread::stop");
Eric Laurent49f02be2009-11-19 09:00:56 -08004029 sp <ThreadBase> strongMe = this;
4030 {
4031 AutoMutex lock(&mLock);
4032 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4033 mActiveTrack->mState = TrackBase::PAUSING;
4034 // do not wait for mStartStopCond if exiting
4035 if (mExiting) {
4036 return;
4037 }
4038 mStartStopCond.wait(mLock);
4039 // if we have been restarted, recordTrack == mActiveTrack.get() here
4040 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4041 mLock.unlock();
4042 AudioSystem::stopInput(mId);
4043 mLock.lock();
Eric Laurent9cc489a22009-12-05 05:20:01 -08004044 LOGV("Record stopped OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08004045 }
4046 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004047 }
4048}
4049
Eric Laurenta553c252009-07-17 12:17:14 -07004050status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004051{
4052 const size_t SIZE = 256;
4053 char buffer[SIZE];
4054 String8 result;
4055 pid_t pid = 0;
4056
Eric Laurent3fdb1262009-11-07 00:01:32 -08004057 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4058 result.append(buffer);
4059
4060 if (mActiveTrack != 0) {
4061 result.append("Active Track:\n");
Eric Laurent65b65452010-06-01 23:49:17 -07004062 result.append(" Clien Fmt Chn Session Buf S SRate Serv User\n");
Eric Laurent3fdb1262009-11-07 00:01:32 -08004063 mActiveTrack->dump(buffer, SIZE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004064 result.append(buffer);
Eric Laurent3fdb1262009-11-07 00:01:32 -08004065
4066 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4067 result.append(buffer);
4068 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4069 result.append(buffer);
4070 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != 0));
4071 result.append(buffer);
4072 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4073 result.append(buffer);
4074 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4075 result.append(buffer);
4076
4077
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004078 } else {
4079 result.append("No record client\n");
4080 }
4081 write(fd, result.string(), result.size());
Eric Laurent3fdb1262009-11-07 00:01:32 -08004082
4083 dumpBase(fd, args);
4084
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004085 return NO_ERROR;
4086}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004087
Eric Laurenta553c252009-07-17 12:17:14 -07004088status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4089{
4090 size_t framesReq = buffer->frameCount;
4091 size_t framesReady = mFrameCount - mRsmpInIndex;
4092 int channelCount;
4093
4094 if (framesReady == 0) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08004095 mBytesRead = mInput->read(mRsmpInBuffer, mInputBytes);
4096 if (mBytesRead < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07004097 LOGE("RecordThread::getNextBuffer() Error reading audio input");
Eric Laurent9cc489a22009-12-05 05:20:01 -08004098 if (mActiveTrack->mState == TrackBase::ACTIVE) {
Eric Laurentba8811f2010-03-02 18:38:06 -08004099 // Force input into standby so that it tries to
4100 // recover at next read attempt
4101 mInput->standby();
4102 usleep(5000);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004103 }
Eric Laurenta553c252009-07-17 12:17:14 -07004104 buffer->raw = 0;
4105 buffer->frameCount = 0;
4106 return NOT_ENOUGH_DATA;
4107 }
4108 mRsmpInIndex = 0;
4109 framesReady = mFrameCount;
4110 }
4111
4112 if (framesReq > framesReady) {
4113 framesReq = framesReady;
4114 }
4115
4116 if (mChannelCount == 1 && mReqChannelCount == 2) {
4117 channelCount = 1;
4118 } else {
4119 channelCount = 2;
4120 }
4121 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4122 buffer->frameCount = framesReq;
4123 return NO_ERROR;
4124}
4125
4126void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4127{
4128 mRsmpInIndex += buffer->frameCount;
4129 buffer->frameCount = 0;
4130}
4131
4132bool AudioFlinger::RecordThread::checkForNewParameters_l()
4133{
4134 bool reconfig = false;
4135
Eric Laurent8fce46a2009-08-04 09:45:33 -07004136 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07004137 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07004138 String8 keyValuePair = mNewParameters[0];
4139 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07004140 int value;
4141 int reqFormat = mFormat;
4142 int reqSamplingRate = mReqSampleRate;
4143 int reqChannelCount = mReqChannelCount;
Eric Laurent8fce46a2009-08-04 09:45:33 -07004144
Eric Laurenta553c252009-07-17 12:17:14 -07004145 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4146 reqSamplingRate = value;
4147 reconfig = true;
4148 }
4149 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
4150 reqFormat = value;
4151 reconfig = true;
4152 }
4153 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
4154 reqChannelCount = AudioSystem::popCount(value);
4155 reconfig = true;
4156 }
4157 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4158 // do not accept frame count changes if tracks are open as the track buffer
4159 // size depends on frame count and correct behavior would not be garantied
4160 // if frame count is changed after track creation
4161 if (mActiveTrack != 0) {
4162 status = INVALID_OPERATION;
4163 } else {
4164 reconfig = true;
4165 }
4166 }
4167 if (status == NO_ERROR) {
Eric Laurent8fce46a2009-08-04 09:45:33 -07004168 status = mInput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07004169 if (status == INVALID_OPERATION) {
4170 mInput->standby();
Eric Laurent8fce46a2009-08-04 09:45:33 -07004171 status = mInput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07004172 }
4173 if (reconfig) {
4174 if (status == BAD_VALUE &&
4175 reqFormat == mInput->format() && reqFormat == AudioSystem::PCM_16_BIT &&
4176 ((int)mInput->sampleRate() <= 2 * reqSamplingRate) &&
4177 (AudioSystem::popCount(mInput->channels()) < 3) && (reqChannelCount < 3)) {
4178 status = NO_ERROR;
4179 }
4180 if (status == NO_ERROR) {
4181 readInputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07004182 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07004183 }
4184 }
4185 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08004186
4187 mNewParameters.removeAt(0);
4188
Eric Laurenta553c252009-07-17 12:17:14 -07004189 mParamStatus = status;
4190 mParamCond.signal();
Eric Laurent8fce46a2009-08-04 09:45:33 -07004191 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07004192 }
4193 return reconfig;
4194}
4195
4196String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4197{
4198 return mInput->getParameters(keys);
4199}
4200
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004201void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
Eric Laurenta553c252009-07-17 12:17:14 -07004202 AudioSystem::OutputDescriptor desc;
4203 void *param2 = 0;
4204
4205 switch (event) {
4206 case AudioSystem::INPUT_OPENED:
4207 case AudioSystem::INPUT_CONFIG_CHANGED:
Eric Laurentb0a01472010-05-14 05:45:46 -07004208 desc.channels = mChannels;
Eric Laurenta553c252009-07-17 12:17:14 -07004209 desc.samplingRate = mSampleRate;
4210 desc.format = mFormat;
4211 desc.frameCount = mFrameCount;
4212 desc.latency = 0;
4213 param2 = &desc;
4214 break;
4215
4216 case AudioSystem::INPUT_CLOSED:
4217 default:
4218 break;
4219 }
Eric Laurent49f02be2009-11-19 09:00:56 -08004220 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurenta553c252009-07-17 12:17:14 -07004221}
4222
4223void AudioFlinger::RecordThread::readInputParameters()
4224{
4225 if (mRsmpInBuffer) delete mRsmpInBuffer;
4226 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
4227 if (mResampler) delete mResampler;
4228 mResampler = 0;
4229
4230 mSampleRate = mInput->sampleRate();
Eric Laurentb0a01472010-05-14 05:45:46 -07004231 mChannels = mInput->channels();
4232 mChannelCount = (uint16_t)AudioSystem::popCount(mChannels);
Eric Laurenta553c252009-07-17 12:17:14 -07004233 mFormat = mInput->format();
Eric Laurentb0a01472010-05-14 05:45:46 -07004234 mFrameSize = (uint16_t)mInput->frameSize();
Eric Laurenta553c252009-07-17 12:17:14 -07004235 mInputBytes = mInput->bufferSize();
4236 mFrameCount = mInputBytes / mFrameSize;
4237 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4238
4239 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4240 {
4241 int channelCount;
4242 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4243 // stereo to mono post process as the resampler always outputs stereo.
4244 if (mChannelCount == 1 && mReqChannelCount == 2) {
4245 channelCount = 1;
4246 } else {
4247 channelCount = 2;
4248 }
4249 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4250 mResampler->setSampleRate(mSampleRate);
4251 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4252 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4253
4254 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4255 if (mChannelCount == 1 && mReqChannelCount == 1) {
4256 mFrameCount >>= 1;
4257 }
4258
4259 }
4260 mRsmpInIndex = mFrameCount;
4261}
4262
Eric Laurent47d0a922010-02-26 02:47:27 -08004263unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4264{
4265 return mInput->getInputFramesLost();
4266}
4267
Eric Laurenta553c252009-07-17 12:17:14 -07004268// ----------------------------------------------------------------------------
4269
Eric Laurentddb78e72009-07-28 08:44:33 -07004270int AudioFlinger::openOutput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07004271 uint32_t *pSamplingRate,
4272 uint32_t *pFormat,
4273 uint32_t *pChannels,
4274 uint32_t *pLatencyMs,
4275 uint32_t flags)
4276{
4277 status_t status;
4278 PlaybackThread *thread = NULL;
4279 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4280 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4281 uint32_t format = pFormat ? *pFormat : 0;
4282 uint32_t channels = pChannels ? *pChannels : 0;
4283 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
4284
4285 LOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
4286 pDevices ? *pDevices : 0,
4287 samplingRate,
4288 format,
4289 channels,
4290 flags);
4291
4292 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004293 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004294 }
4295 Mutex::Autolock _l(mLock);
4296
4297 AudioStreamOut *output = mAudioHardware->openOutputStream(*pDevices,
4298 (int *)&format,
4299 &channels,
4300 &samplingRate,
4301 &status);
4302 LOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
4303 output,
4304 samplingRate,
4305 format,
4306 channels,
4307 status);
4308
4309 mHardwareStatus = AUDIO_HW_IDLE;
4310 if (output != 0) {
Eric Laurentf3d6dd02010-11-18 08:40:16 -08004311 int id = nextUniqueId_l();
Eric Laurenta553c252009-07-17 12:17:14 -07004312 if ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) ||
4313 (format != AudioSystem::PCM_16_BIT) ||
4314 (channels != AudioSystem::CHANNEL_OUT_STEREO)) {
Eric Laurent65b65452010-06-01 23:49:17 -07004315 thread = new DirectOutputThread(this, output, id, *pDevices);
4316 LOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004317 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07004318 thread = new MixerThread(this, output, id, *pDevices);
4319 LOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Glenn Kasten871c16c2010-03-05 12:18:01 -08004320
4321#ifdef LVMX
4322 unsigned bitsPerSample =
4323 (format == AudioSystem::PCM_16_BIT) ? 16 :
4324 ((format == AudioSystem::PCM_8_BIT) ? 8 : 0);
4325 unsigned channelCount = (channels == AudioSystem::CHANNEL_OUT_STEREO) ? 2 : 1;
4326 int audioOutputType = LifeVibes::threadIdToAudioOutputType(thread->id());
4327
4328 LifeVibes::init_aot(audioOutputType, samplingRate, bitsPerSample, channelCount);
4329 LifeVibes::setDevice(audioOutputType, *pDevices);
4330#endif
4331
Eric Laurenta553c252009-07-17 12:17:14 -07004332 }
Eric Laurent65b65452010-06-01 23:49:17 -07004333 mPlaybackThreads.add(id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004334
4335 if (pSamplingRate) *pSamplingRate = samplingRate;
4336 if (pFormat) *pFormat = format;
4337 if (pChannels) *pChannels = channels;
4338 if (pLatencyMs) *pLatencyMs = thread->latency();
Eric Laurent9cc489a22009-12-05 05:20:01 -08004339
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004340 // notify client processes of the new output creation
4341 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004342 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004343 }
4344
Eric Laurent9cc489a22009-12-05 05:20:01 -08004345 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004346}
4347
Eric Laurentddb78e72009-07-28 08:44:33 -07004348int AudioFlinger::openDuplicateOutput(int output1, int output2)
Eric Laurenta553c252009-07-17 12:17:14 -07004349{
4350 Mutex::Autolock _l(mLock);
Eric Laurentddb78e72009-07-28 08:44:33 -07004351 MixerThread *thread1 = checkMixerThread_l(output1);
4352 MixerThread *thread2 = checkMixerThread_l(output2);
Eric Laurenta553c252009-07-17 12:17:14 -07004353
Eric Laurentddb78e72009-07-28 08:44:33 -07004354 if (thread1 == NULL || thread2 == NULL) {
4355 LOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
4356 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004357 }
4358
Eric Laurentf3d6dd02010-11-18 08:40:16 -08004359 int id = nextUniqueId_l();
Eric Laurent65b65452010-06-01 23:49:17 -07004360 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
Eric Laurentddb78e72009-07-28 08:44:33 -07004361 thread->addOutputTrack(thread2);
Eric Laurent65b65452010-06-01 23:49:17 -07004362 mPlaybackThreads.add(id, thread);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004363 // notify client processes of the new output creation
4364 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004365 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004366}
4367
Eric Laurentddb78e72009-07-28 08:44:33 -07004368status_t AudioFlinger::closeOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004369{
Eric Laurent49018a52009-08-04 08:37:05 -07004370 // keep strong reference on the playback thread so that
4371 // it is not destroyed while exit() is executed
4372 sp <PlaybackThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07004373 {
4374 Mutex::Autolock _l(mLock);
4375 thread = checkPlaybackThread_l(output);
4376 if (thread == NULL) {
4377 return BAD_VALUE;
4378 }
4379
Eric Laurentddb78e72009-07-28 08:44:33 -07004380 LOGV("closeOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004381
4382 if (thread->type() == PlaybackThread::MIXER) {
4383 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004384 if (mPlaybackThreads.valueAt(i)->type() == PlaybackThread::DUPLICATING) {
4385 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Eric Laurent49018a52009-08-04 08:37:05 -07004386 dupThread->removeOutputTrack((MixerThread *)thread.get());
Eric Laurenta553c252009-07-17 12:17:14 -07004387 }
4388 }
4389 }
Eric Laurent296a0ec2009-09-15 07:10:12 -07004390 void *param2 = 0;
Eric Laurent49f02be2009-11-19 09:00:56 -08004391 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
Eric Laurentddb78e72009-07-28 08:44:33 -07004392 mPlaybackThreads.removeItem(output);
Eric Laurenta553c252009-07-17 12:17:14 -07004393 }
4394 thread->exit();
4395
Eric Laurent49018a52009-08-04 08:37:05 -07004396 if (thread->type() != PlaybackThread::DUPLICATING) {
4397 mAudioHardware->closeOutputStream(thread->getOutput());
4398 }
Eric Laurenta553c252009-07-17 12:17:14 -07004399 return NO_ERROR;
4400}
4401
Eric Laurentddb78e72009-07-28 08:44:33 -07004402status_t AudioFlinger::suspendOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004403{
4404 Mutex::Autolock _l(mLock);
4405 PlaybackThread *thread = checkPlaybackThread_l(output);
4406
4407 if (thread == NULL) {
4408 return BAD_VALUE;
4409 }
4410
Eric Laurentddb78e72009-07-28 08:44:33 -07004411 LOGV("suspendOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004412 thread->suspend();
4413
4414 return NO_ERROR;
4415}
4416
Eric Laurentddb78e72009-07-28 08:44:33 -07004417status_t AudioFlinger::restoreOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004418{
4419 Mutex::Autolock _l(mLock);
4420 PlaybackThread *thread = checkPlaybackThread_l(output);
4421
4422 if (thread == NULL) {
4423 return BAD_VALUE;
4424 }
4425
Eric Laurentddb78e72009-07-28 08:44:33 -07004426 LOGV("restoreOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004427
4428 thread->restore();
4429
4430 return NO_ERROR;
4431}
4432
Eric Laurentddb78e72009-07-28 08:44:33 -07004433int AudioFlinger::openInput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07004434 uint32_t *pSamplingRate,
4435 uint32_t *pFormat,
4436 uint32_t *pChannels,
4437 uint32_t acoustics)
4438{
4439 status_t status;
4440 RecordThread *thread = NULL;
4441 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4442 uint32_t format = pFormat ? *pFormat : 0;
4443 uint32_t channels = pChannels ? *pChannels : 0;
4444 uint32_t reqSamplingRate = samplingRate;
4445 uint32_t reqFormat = format;
4446 uint32_t reqChannels = channels;
4447
4448 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004449 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004450 }
4451 Mutex::Autolock _l(mLock);
4452
4453 AudioStreamIn *input = mAudioHardware->openInputStream(*pDevices,
4454 (int *)&format,
4455 &channels,
4456 &samplingRate,
4457 &status,
4458 (AudioSystem::audio_in_acoustics)acoustics);
4459 LOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
4460 input,
4461 samplingRate,
4462 format,
4463 channels,
4464 acoustics,
4465 status);
4466
4467 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
4468 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
4469 // or stereo to mono conversions on 16 bit PCM inputs.
4470 if (input == 0 && status == BAD_VALUE &&
4471 reqFormat == format && format == AudioSystem::PCM_16_BIT &&
4472 (samplingRate <= 2 * reqSamplingRate) &&
4473 (AudioSystem::popCount(channels) < 3) && (AudioSystem::popCount(reqChannels) < 3)) {
4474 LOGV("openInput() reopening with proposed sampling rate and channels");
4475 input = mAudioHardware->openInputStream(*pDevices,
4476 (int *)&format,
4477 &channels,
4478 &samplingRate,
4479 &status,
4480 (AudioSystem::audio_in_acoustics)acoustics);
4481 }
4482
4483 if (input != 0) {
Eric Laurentf3d6dd02010-11-18 08:40:16 -08004484 int id = nextUniqueId_l();
Eric Laurenta553c252009-07-17 12:17:14 -07004485 // Start record thread
Eric Laurent65b65452010-06-01 23:49:17 -07004486 thread = new RecordThread(this, input, reqSamplingRate, reqChannels, id);
4487 mRecordThreads.add(id, thread);
4488 LOGV("openInput() created record thread: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004489 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
4490 if (pFormat) *pFormat = format;
4491 if (pChannels) *pChannels = reqChannels;
4492
4493 input->standby();
Eric Laurent9cc489a22009-12-05 05:20:01 -08004494
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004495 // notify client processes of the new input creation
4496 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004497 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004498 }
4499
Eric Laurent9cc489a22009-12-05 05:20:01 -08004500 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004501}
4502
Eric Laurentddb78e72009-07-28 08:44:33 -07004503status_t AudioFlinger::closeInput(int input)
Eric Laurenta553c252009-07-17 12:17:14 -07004504{
Eric Laurent49018a52009-08-04 08:37:05 -07004505 // keep strong reference on the record thread so that
4506 // it is not destroyed while exit() is executed
4507 sp <RecordThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07004508 {
4509 Mutex::Autolock _l(mLock);
4510 thread = checkRecordThread_l(input);
4511 if (thread == NULL) {
4512 return BAD_VALUE;
4513 }
4514
Eric Laurentddb78e72009-07-28 08:44:33 -07004515 LOGV("closeInput() %d", input);
Eric Laurent296a0ec2009-09-15 07:10:12 -07004516 void *param2 = 0;
Eric Laurent49f02be2009-11-19 09:00:56 -08004517 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
Eric Laurentddb78e72009-07-28 08:44:33 -07004518 mRecordThreads.removeItem(input);
Eric Laurenta553c252009-07-17 12:17:14 -07004519 }
4520 thread->exit();
4521
Eric Laurent49018a52009-08-04 08:37:05 -07004522 mAudioHardware->closeInputStream(thread->getInput());
4523
Eric Laurenta553c252009-07-17 12:17:14 -07004524 return NO_ERROR;
4525}
4526
Eric Laurentddb78e72009-07-28 08:44:33 -07004527status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004528{
4529 Mutex::Autolock _l(mLock);
4530 MixerThread *dstThread = checkMixerThread_l(output);
4531 if (dstThread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004532 LOGW("setStreamOutput() bad output id %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004533 return BAD_VALUE;
4534 }
4535
Eric Laurentddb78e72009-07-28 08:44:33 -07004536 LOGV("setStreamOutput() stream %d to output %d", stream, output);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004537 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
Eric Laurenta553c252009-07-17 12:17:14 -07004538
4539 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004540 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurenta553c252009-07-17 12:17:14 -07004541 if (thread != dstThread &&
4542 thread->type() != PlaybackThread::DIRECT) {
4543 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004544 srcThread->invalidateTracks(stream);
Eric Laurenta553c252009-07-17 12:17:14 -07004545 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004546 }
Eric Laurentd069f322009-09-01 05:56:26 -07004547
Eric Laurenta553c252009-07-17 12:17:14 -07004548 return NO_ERROR;
4549}
4550
Eric Laurent65b65452010-06-01 23:49:17 -07004551
4552int AudioFlinger::newAudioSessionId()
4553{
Eric Laurentf3d6dd02010-11-18 08:40:16 -08004554 AutoMutex _l(mLock);
4555 return nextUniqueId_l();
Eric Laurent65b65452010-06-01 23:49:17 -07004556}
4557
Eric Laurenta553c252009-07-17 12:17:14 -07004558// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07004559AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
Eric Laurenta553c252009-07-17 12:17:14 -07004560{
4561 PlaybackThread *thread = NULL;
Eric Laurentddb78e72009-07-28 08:44:33 -07004562 if (mPlaybackThreads.indexOfKey(output) >= 0) {
4563 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
Eric Laurenta553c252009-07-17 12:17:14 -07004564 }
Eric Laurenta553c252009-07-17 12:17:14 -07004565 return thread;
4566}
4567
4568// checkMixerThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07004569AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
Eric Laurenta553c252009-07-17 12:17:14 -07004570{
4571 PlaybackThread *thread = checkPlaybackThread_l(output);
4572 if (thread != NULL) {
4573 if (thread->type() == PlaybackThread::DIRECT) {
4574 thread = NULL;
4575 }
4576 }
4577 return (MixerThread *)thread;
4578}
4579
4580// checkRecordThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07004581AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
Eric Laurenta553c252009-07-17 12:17:14 -07004582{
4583 RecordThread *thread = NULL;
Eric Laurentddb78e72009-07-28 08:44:33 -07004584 if (mRecordThreads.indexOfKey(input) >= 0) {
4585 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
Eric Laurenta553c252009-07-17 12:17:14 -07004586 }
Eric Laurenta553c252009-07-17 12:17:14 -07004587 return thread;
4588}
4589
Eric Laurentf3d6dd02010-11-18 08:40:16 -08004590// nextUniqueId_l() must be called with AudioFlinger::mLock held
4591int AudioFlinger::nextUniqueId_l()
Eric Laurent65b65452010-06-01 23:49:17 -07004592{
Eric Laurentf3d6dd02010-11-18 08:40:16 -08004593 return mNextUniqueId++;
Eric Laurent65b65452010-06-01 23:49:17 -07004594}
4595
4596// ----------------------------------------------------------------------------
4597// Effect management
4598// ----------------------------------------------------------------------------
4599
4600
4601status_t AudioFlinger::loadEffectLibrary(const char *libPath, int *handle)
4602{
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004603 // check calling permissions
4604 if (!settingsAllowed()) {
4605 return PERMISSION_DENIED;
4606 }
4607 // only allow libraries loaded from /system/lib/soundfx for now
4608 if (strncmp(gEffectLibPath, libPath, strlen(gEffectLibPath)) != 0) {
4609 return PERMISSION_DENIED;
4610 }
4611
Eric Laurent65b65452010-06-01 23:49:17 -07004612 Mutex::Autolock _l(mLock);
4613 return EffectLoadLibrary(libPath, handle);
4614}
4615
4616status_t AudioFlinger::unloadEffectLibrary(int handle)
4617{
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004618 // check calling permissions
4619 if (!settingsAllowed()) {
4620 return PERMISSION_DENIED;
4621 }
4622
Eric Laurent65b65452010-06-01 23:49:17 -07004623 Mutex::Autolock _l(mLock);
4624 return EffectUnloadLibrary(handle);
4625}
4626
4627status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects)
4628{
4629 Mutex::Autolock _l(mLock);
4630 return EffectQueryNumberEffects(numEffects);
4631}
4632
Eric Laurent53334cd2010-06-23 17:38:20 -07004633status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor)
Eric Laurent65b65452010-06-01 23:49:17 -07004634{
4635 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07004636 return EffectQueryEffect(index, descriptor);
Eric Laurent65b65452010-06-01 23:49:17 -07004637}
4638
4639status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid, effect_descriptor_t *descriptor)
4640{
4641 Mutex::Autolock _l(mLock);
4642 return EffectGetDescriptor(pUuid, descriptor);
4643}
4644
Eric Laurentdf9b81c2010-07-02 08:12:41 -07004645
4646// this UUID must match the one defined in media/libeffects/EffectVisualizer.cpp
4647static const effect_uuid_t VISUALIZATION_UUID_ =
4648 {0xd069d9e0, 0x8329, 0x11df, 0x9168, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}};
4649
Eric Laurent65b65452010-06-01 23:49:17 -07004650sp<IEffect> AudioFlinger::createEffect(pid_t pid,
4651 effect_descriptor_t *pDesc,
4652 const sp<IEffectClient>& effectClient,
4653 int32_t priority,
4654 int output,
4655 int sessionId,
4656 status_t *status,
4657 int *id,
4658 int *enabled)
4659{
4660 status_t lStatus = NO_ERROR;
4661 sp<EffectHandle> handle;
4662 effect_interface_t itfe;
4663 effect_descriptor_t desc;
4664 sp<Client> client;
4665 wp<Client> wclient;
4666
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004667 LOGV("createEffect pid %d, client %p, priority %d, sessionId %d, output %d",
4668 pid, effectClient.get(), priority, sessionId, output);
Eric Laurent65b65452010-06-01 23:49:17 -07004669
4670 if (pDesc == NULL) {
4671 lStatus = BAD_VALUE;
4672 goto Exit;
4673 }
4674
Eric Laurent98c92592010-09-23 16:10:16 -07004675 // check audio settings permission for global effects
4676 if (sessionId == AudioSystem::SESSION_OUTPUT_MIX && !settingsAllowed()) {
4677 lStatus = PERMISSION_DENIED;
4678 goto Exit;
4679 }
4680
4681 // Session AudioSystem::SESSION_OUTPUT_STAGE is reserved for output stage effects
4682 // that can only be created by audio policy manager (running in same process)
4683 if (sessionId == AudioSystem::SESSION_OUTPUT_STAGE && getpid() != pid) {
4684 lStatus = PERMISSION_DENIED;
4685 goto Exit;
4686 }
4687
4688 // check recording permission for visualizer
4689 if ((memcmp(&pDesc->type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0 ||
4690 memcmp(&pDesc->uuid, &VISUALIZATION_UUID_, sizeof(effect_uuid_t)) == 0) &&
4691 !recordingAllowed()) {
4692 lStatus = PERMISSION_DENIED;
4693 goto Exit;
4694 }
4695
4696 if (output == 0) {
4697 if (sessionId == AudioSystem::SESSION_OUTPUT_STAGE) {
4698 // output must be specified by AudioPolicyManager when using session
4699 // AudioSystem::SESSION_OUTPUT_STAGE
4700 lStatus = BAD_VALUE;
4701 goto Exit;
4702 } else if (sessionId == AudioSystem::SESSION_OUTPUT_MIX) {
4703 // if the output returned by getOutputForEffect() is removed before we lock the
4704 // mutex below, the call to checkPlaybackThread_l(output) below will detect it
4705 // and we will exit safely
4706 output = AudioSystem::getOutputForEffect(&desc);
4707 }
4708 }
4709
Eric Laurent65b65452010-06-01 23:49:17 -07004710 {
4711 Mutex::Autolock _l(mLock);
4712
Eric Laurentdf9b81c2010-07-02 08:12:41 -07004713
Eric Laurent65b65452010-06-01 23:49:17 -07004714 if (!EffectIsNullUuid(&pDesc->uuid)) {
4715 // if uuid is specified, request effect descriptor
4716 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
4717 if (lStatus < 0) {
4718 LOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
4719 goto Exit;
4720 }
4721 } else {
4722 // if uuid is not specified, look for an available implementation
4723 // of the required type in effect factory
4724 if (EffectIsNullUuid(&pDesc->type)) {
4725 LOGW("createEffect() no effect type");
4726 lStatus = BAD_VALUE;
4727 goto Exit;
4728 }
4729 uint32_t numEffects = 0;
4730 effect_descriptor_t d;
4731 bool found = false;
4732
4733 lStatus = EffectQueryNumberEffects(&numEffects);
4734 if (lStatus < 0) {
4735 LOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
4736 goto Exit;
4737 }
Eric Laurent53334cd2010-06-23 17:38:20 -07004738 for (uint32_t i = 0; i < numEffects; i++) {
4739 lStatus = EffectQueryEffect(i, &desc);
Eric Laurent65b65452010-06-01 23:49:17 -07004740 if (lStatus < 0) {
Eric Laurent53334cd2010-06-23 17:38:20 -07004741 LOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07004742 continue;
4743 }
4744 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
4745 // If matching type found save effect descriptor. If the session is
4746 // 0 and the effect is not auxiliary, continue enumeration in case
4747 // an auxiliary version of this effect type is available
4748 found = true;
4749 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004750 if (sessionId != AudioSystem::SESSION_OUTPUT_MIX ||
Eric Laurent65b65452010-06-01 23:49:17 -07004751 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
4752 break;
4753 }
4754 }
4755 }
4756 if (!found) {
4757 lStatus = BAD_VALUE;
4758 LOGW("createEffect() effect not found");
4759 goto Exit;
4760 }
4761 // For same effect type, chose auxiliary version over insert version if
4762 // connect to output mix (Compliance to OpenSL ES)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004763 if (sessionId == AudioSystem::SESSION_OUTPUT_MIX &&
Eric Laurent65b65452010-06-01 23:49:17 -07004764 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
4765 memcpy(&desc, &d, sizeof(effect_descriptor_t));
4766 }
4767 }
4768
4769 // Do not allow auxiliary effects on a session different from 0 (output mix)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004770 if (sessionId != AudioSystem::SESSION_OUTPUT_MIX &&
Eric Laurent65b65452010-06-01 23:49:17 -07004771 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
4772 lStatus = INVALID_OPERATION;
4773 goto Exit;
4774 }
4775
4776 // return effect descriptor
4777 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
4778
4779 // If output is not specified try to find a matching audio session ID in one of the
4780 // output threads.
Eric Laurent98c92592010-09-23 16:10:16 -07004781 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
4782 // because of code checking output when entering the function.
Eric Laurent65b65452010-06-01 23:49:17 -07004783 if (output == 0) {
Eric Laurent98c92592010-09-23 16:10:16 -07004784 // look for the thread where the specified audio session is present
4785 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
4786 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
4787 output = mPlaybackThreads.keyAt(i);
4788 break;
Eric Laurent493941b2010-07-28 01:32:47 -07004789 }
Eric Laurent65b65452010-06-01 23:49:17 -07004790 }
Eric Laurent98c92592010-09-23 16:10:16 -07004791 // If no output thread contains the requested session ID, default to
4792 // first output. The effect chain will be moved to the correct output
4793 // thread when a track with the same session ID is created
4794 if (output == 0 && mPlaybackThreads.size()) {
4795 output = mPlaybackThreads.keyAt(0);
4796 }
Eric Laurent65b65452010-06-01 23:49:17 -07004797 }
Eric Laurent98c92592010-09-23 16:10:16 -07004798 LOGV("createEffect() got output %d for effect %s", output, desc.name);
Eric Laurent65b65452010-06-01 23:49:17 -07004799 PlaybackThread *thread = checkPlaybackThread_l(output);
4800 if (thread == NULL) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004801 LOGE("createEffect() unknown output thread");
Eric Laurent65b65452010-06-01 23:49:17 -07004802 lStatus = BAD_VALUE;
4803 goto Exit;
4804 }
4805
Eric Laurent98c92592010-09-23 16:10:16 -07004806 // TODO: allow attachment of effect to inputs
4807
Eric Laurent65b65452010-06-01 23:49:17 -07004808 wclient = mClients.valueFor(pid);
4809
4810 if (wclient != NULL) {
4811 client = wclient.promote();
4812 } else {
4813 client = new Client(this, pid);
4814 mClients.add(pid, client);
4815 }
4816
4817 // create effect on selected output trhead
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004818 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
4819 &desc, enabled, &lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07004820 if (handle != 0 && id != NULL) {
4821 *id = handle->id();
4822 }
4823 }
4824
4825Exit:
4826 if(status) {
4827 *status = lStatus;
4828 }
4829 return handle;
4830}
4831
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004832status_t AudioFlinger::moveEffects(int session, int srcOutput, int dstOutput)
4833{
4834 LOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
4835 session, srcOutput, dstOutput);
4836 Mutex::Autolock _l(mLock);
4837 if (srcOutput == dstOutput) {
4838 LOGW("moveEffects() same dst and src outputs %d", dstOutput);
4839 return NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07004840 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004841 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
4842 if (srcThread == NULL) {
4843 LOGW("moveEffects() bad srcOutput %d", srcOutput);
4844 return BAD_VALUE;
Eric Laurent53334cd2010-06-23 17:38:20 -07004845 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004846 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
4847 if (dstThread == NULL) {
4848 LOGW("moveEffects() bad dstOutput %d", dstOutput);
4849 return BAD_VALUE;
4850 }
4851
4852 Mutex::Autolock _dl(dstThread->mLock);
4853 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent493941b2010-07-28 01:32:47 -07004854 moveEffectChain_l(session, srcThread, dstThread, false);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004855
Eric Laurent53334cd2010-06-23 17:38:20 -07004856 return NO_ERROR;
4857}
4858
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004859// moveEffectChain_l mustbe called with both srcThread and dstThread mLocks held
4860status_t AudioFlinger::moveEffectChain_l(int session,
4861 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent493941b2010-07-28 01:32:47 -07004862 AudioFlinger::PlaybackThread *dstThread,
4863 bool reRegister)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004864{
4865 LOGV("moveEffectChain_l() session %d from thread %p to thread %p",
4866 session, srcThread, dstThread);
4867
4868 sp<EffectChain> chain = srcThread->getEffectChain_l(session);
4869 if (chain == 0) {
4870 LOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
4871 session, srcThread);
4872 return INVALID_OPERATION;
4873 }
4874
Eric Laurent493941b2010-07-28 01:32:47 -07004875 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004876 // so that a new chain is created with correct parameters when first effect is added. This is
4877 // otherwise unecessary as removeEffect_l() will remove the chain when last effect is
4878 // removed.
4879 srcThread->removeEffectChain_l(chain);
4880
4881 // transfer all effects one by one so that new effect chain is created on new thread with
4882 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent493941b2010-07-28 01:32:47 -07004883 int dstOutput = dstThread->id();
4884 sp<EffectChain> dstChain;
4885 uint32_t strategy;
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004886 sp<EffectModule> effect = chain->getEffectFromId_l(0);
4887 while (effect != 0) {
4888 srcThread->removeEffect_l(effect);
4889 dstThread->addEffect_l(effect);
Eric Laurent493941b2010-07-28 01:32:47 -07004890 // if the move request is not received from audio policy manager, the effect must be
4891 // re-registered with the new strategy and output
4892 if (dstChain == 0) {
4893 dstChain = effect->chain().promote();
4894 if (dstChain == 0) {
4895 LOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
4896 srcThread->addEffect_l(effect);
4897 return NO_INIT;
4898 }
4899 strategy = dstChain->strategy();
4900 }
4901 if (reRegister) {
4902 AudioSystem::unregisterEffect(effect->id());
4903 AudioSystem::registerEffect(&effect->desc(),
4904 dstOutput,
4905 strategy,
4906 session,
4907 effect->id());
4908 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004909 effect = chain->getEffectFromId_l(0);
4910 }
4911
4912 return NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07004913}
4914
Eric Laurent65b65452010-06-01 23:49:17 -07004915// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
4916sp<AudioFlinger::EffectHandle> AudioFlinger::PlaybackThread::createEffect_l(
4917 const sp<AudioFlinger::Client>& client,
4918 const sp<IEffectClient>& effectClient,
4919 int32_t priority,
4920 int sessionId,
4921 effect_descriptor_t *desc,
4922 int *enabled,
4923 status_t *status
4924 )
4925{
4926 sp<EffectModule> effect;
4927 sp<EffectHandle> handle;
4928 status_t lStatus;
4929 sp<Track> track;
4930 sp<EffectChain> chain;
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004931 bool chainCreated = false;
Eric Laurent65b65452010-06-01 23:49:17 -07004932 bool effectCreated = false;
Eric Laurent53334cd2010-06-23 17:38:20 -07004933 bool effectRegistered = false;
Eric Laurent65b65452010-06-01 23:49:17 -07004934
4935 if (mOutput == 0) {
4936 LOGW("createEffect_l() Audio driver not initialized.");
4937 lStatus = NO_INIT;
4938 goto Exit;
4939 }
4940
4941 // Do not allow auxiliary effect on session other than 0
4942 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY &&
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004943 sessionId != AudioSystem::SESSION_OUTPUT_MIX) {
4944 LOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
4945 desc->name, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07004946 lStatus = BAD_VALUE;
4947 goto Exit;
4948 }
4949
4950 // Do not allow effects with session ID 0 on direct output or duplicating threads
4951 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004952 if (sessionId == AudioSystem::SESSION_OUTPUT_MIX && mType != MIXER) {
4953 LOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
4954 desc->name, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07004955 lStatus = BAD_VALUE;
4956 goto Exit;
4957 }
4958
4959 LOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
4960
4961 { // scope for mLock
4962 Mutex::Autolock _l(mLock);
4963
4964 // check for existing effect chain with the requested audio session
4965 chain = getEffectChain_l(sessionId);
4966 if (chain == 0) {
4967 // create a new chain for this session
4968 LOGV("createEffect_l() new effect chain for session %d", sessionId);
4969 chain = new EffectChain(this, sessionId);
4970 addEffectChain_l(chain);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004971 chain->setStrategy(getStrategyForSession_l(sessionId));
4972 chainCreated = true;
Eric Laurent65b65452010-06-01 23:49:17 -07004973 } else {
Eric Laurent76c40f72010-07-15 12:50:15 -07004974 effect = chain->getEffectFromDesc_l(desc);
Eric Laurent65b65452010-06-01 23:49:17 -07004975 }
4976
4977 LOGV("createEffect_l() got effect %p on chain %p", effect == 0 ? 0 : effect.get(), chain.get());
4978
4979 if (effect == 0) {
Eric Laurentf3d6dd02010-11-18 08:40:16 -08004980 int id = mAudioFlinger->nextUniqueId_l();
Eric Laurent53334cd2010-06-23 17:38:20 -07004981 // Check CPU and memory usage
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004982 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Eric Laurent53334cd2010-06-23 17:38:20 -07004983 if (lStatus != NO_ERROR) {
4984 goto Exit;
4985 }
4986 effectRegistered = true;
Eric Laurent65b65452010-06-01 23:49:17 -07004987 // create a new effect module if none present in the chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004988 effect = new EffectModule(this, chain, desc, id, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07004989 lStatus = effect->status();
4990 if (lStatus != NO_ERROR) {
4991 goto Exit;
4992 }
Eric Laurent76c40f72010-07-15 12:50:15 -07004993 lStatus = chain->addEffect_l(effect);
Eric Laurent65b65452010-06-01 23:49:17 -07004994 if (lStatus != NO_ERROR) {
4995 goto Exit;
4996 }
Eric Laurent53334cd2010-06-23 17:38:20 -07004997 effectCreated = true;
Eric Laurent65b65452010-06-01 23:49:17 -07004998
4999 effect->setDevice(mDevice);
Eric Laurent53334cd2010-06-23 17:38:20 -07005000 effect->setMode(mAudioFlinger->getMode());
Eric Laurent65b65452010-06-01 23:49:17 -07005001 }
5002 // create effect handle and connect it to effect module
5003 handle = new EffectHandle(effect, client, effectClient, priority);
5004 lStatus = effect->addHandle(handle);
5005 if (enabled) {
5006 *enabled = (int)effect->isEnabled();
5007 }
5008 }
5009
5010Exit:
5011 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005012 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07005013 if (effectCreated) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005014 chain->removeEffect_l(effect);
Eric Laurent65b65452010-06-01 23:49:17 -07005015 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005016 if (effectRegistered) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005017 AudioSystem::unregisterEffect(effect->id());
5018 }
5019 if (chainCreated) {
5020 removeEffectChain_l(chain);
Eric Laurent53334cd2010-06-23 17:38:20 -07005021 }
Eric Laurent65b65452010-06-01 23:49:17 -07005022 handle.clear();
5023 }
5024
5025 if(status) {
5026 *status = lStatus;
5027 }
5028 return handle;
5029}
5030
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005031// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5032// PlaybackThread::mLock held
5033status_t AudioFlinger::PlaybackThread::addEffect_l(const sp<EffectModule>& effect)
5034{
5035 // check for existing effect chain with the requested audio session
5036 int sessionId = effect->sessionId();
5037 sp<EffectChain> chain = getEffectChain_l(sessionId);
5038 bool chainCreated = false;
5039
5040 if (chain == 0) {
5041 // create a new chain for this session
5042 LOGV("addEffect_l() new effect chain for session %d", sessionId);
5043 chain = new EffectChain(this, sessionId);
5044 addEffectChain_l(chain);
5045 chain->setStrategy(getStrategyForSession_l(sessionId));
5046 chainCreated = true;
5047 }
5048 LOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
5049
5050 if (chain->getEffectFromId_l(effect->id()) != 0) {
5051 LOGW("addEffect_l() %p effect %s already present in chain %p",
5052 this, effect->desc().name, chain.get());
5053 return BAD_VALUE;
5054 }
5055
5056 status_t status = chain->addEffect_l(effect);
5057 if (status != NO_ERROR) {
5058 if (chainCreated) {
5059 removeEffectChain_l(chain);
5060 }
5061 return status;
5062 }
5063
5064 effect->setDevice(mDevice);
5065 effect->setMode(mAudioFlinger->getMode());
5066 return NO_ERROR;
5067}
5068
5069void AudioFlinger::PlaybackThread::removeEffect_l(const sp<EffectModule>& effect) {
5070
5071 LOGV("removeEffect_l() %p effect %p", this, effect.get());
Eric Laurent53334cd2010-06-23 17:38:20 -07005072 effect_descriptor_t desc = effect->desc();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005073 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5074 detachAuxEffect_l(effect->id());
5075 }
5076
5077 sp<EffectChain> chain = effect->chain().promote();
5078 if (chain != 0) {
5079 // remove effect chain if removing last effect
5080 if (chain->removeEffect_l(effect) == 0) {
5081 removeEffectChain_l(chain);
5082 }
5083 } else {
5084 LOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
5085 }
5086}
5087
5088void AudioFlinger::PlaybackThread::disconnectEffect(const sp<EffectModule>& effect,
5089 const wp<EffectHandle>& handle) {
Eric Laurent53334cd2010-06-23 17:38:20 -07005090 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005091 LOGV("disconnectEffect() %p effect %p", this, effect.get());
Eric Laurent53334cd2010-06-23 17:38:20 -07005092 // delete the effect module if removing last handle on it
5093 if (effect->removeHandle(handle) == 0) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005094 removeEffect_l(effect);
5095 AudioSystem::unregisterEffect(effect->id());
Eric Laurent53334cd2010-06-23 17:38:20 -07005096 }
5097}
5098
Eric Laurent65b65452010-06-01 23:49:17 -07005099status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5100{
5101 int session = chain->sessionId();
5102 int16_t *buffer = mMixBuffer;
Eric Laurent53334cd2010-06-23 17:38:20 -07005103 bool ownsBuffer = false;
Eric Laurent65b65452010-06-01 23:49:17 -07005104
5105 LOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Eric Laurent53334cd2010-06-23 17:38:20 -07005106 if (session > 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07005107 // Only one effect chain can be present in direct output thread and it uses
5108 // the mix buffer as input
5109 if (mType != DIRECT) {
5110 size_t numSamples = mFrameCount * mChannelCount;
5111 buffer = new int16_t[numSamples];
5112 memset(buffer, 0, numSamples * sizeof(int16_t));
5113 LOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
5114 ownsBuffer = true;
5115 }
Eric Laurent65b65452010-06-01 23:49:17 -07005116
Eric Laurent53334cd2010-06-23 17:38:20 -07005117 // Attach all tracks with same session ID to this chain.
5118 for (size_t i = 0; i < mTracks.size(); ++i) {
5119 sp<Track> track = mTracks[i];
5120 if (session == track->sessionId()) {
5121 LOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
5122 track->setMainBuffer(buffer);
5123 }
5124 }
5125
5126 // indicate all active tracks in the chain
5127 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5128 sp<Track> track = mActiveTracks[i].promote();
5129 if (track == 0) continue;
5130 if (session == track->sessionId()) {
5131 LOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
5132 chain->startTrack();
5133 }
Eric Laurent65b65452010-06-01 23:49:17 -07005134 }
5135 }
5136
Eric Laurent53334cd2010-06-23 17:38:20 -07005137 chain->setInBuffer(buffer, ownsBuffer);
5138 chain->setOutBuffer(mMixBuffer);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005139 // Effect chain for session AudioSystem::SESSION_OUTPUT_STAGE is inserted at end of effect
5140 // chains list in order to be processed last as it contains output stage effects
5141 // Effect chain for session AudioSystem::SESSION_OUTPUT_MIX is inserted before
5142 // session AudioSystem::SESSION_OUTPUT_STAGE to be processed
Eric Laurent53334cd2010-06-23 17:38:20 -07005143 // after track specific effects and before output stage
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005144 // It is therefore mandatory that AudioSystem::SESSION_OUTPUT_MIX == 0 and
5145 // that AudioSystem::SESSION_OUTPUT_STAGE < AudioSystem::SESSION_OUTPUT_MIX
5146 // Effect chain for other sessions are inserted at beginning of effect
5147 // chains list to be processed before output mix effects. Relative order between other
5148 // sessions is not important
Eric Laurent53334cd2010-06-23 17:38:20 -07005149 size_t size = mEffectChains.size();
5150 size_t i = 0;
5151 for (i = 0; i < size; i++) {
5152 if (mEffectChains[i]->sessionId() < session) break;
Eric Laurent65b65452010-06-01 23:49:17 -07005153 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005154 mEffectChains.insertAt(chain, i);
Eric Laurent65b65452010-06-01 23:49:17 -07005155
5156 return NO_ERROR;
5157}
5158
5159size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
5160{
5161 int session = chain->sessionId();
5162
5163 LOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
5164
5165 for (size_t i = 0; i < mEffectChains.size(); i++) {
5166 if (chain == mEffectChains[i]) {
5167 mEffectChains.removeAt(i);
5168 // detach all tracks with same session ID from this chain
5169 for (size_t i = 0; i < mTracks.size(); ++i) {
5170 sp<Track> track = mTracks[i];
5171 if (session == track->sessionId()) {
5172 track->setMainBuffer(mMixBuffer);
5173 }
5174 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005175 break;
Eric Laurent65b65452010-06-01 23:49:17 -07005176 }
5177 }
5178 return mEffectChains.size();
5179}
5180
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005181void AudioFlinger::PlaybackThread::lockEffectChains_l(
5182 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
Eric Laurent65b65452010-06-01 23:49:17 -07005183{
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005184 effectChains = mEffectChains;
Eric Laurent65b65452010-06-01 23:49:17 -07005185 for (size_t i = 0; i < mEffectChains.size(); i++) {
5186 mEffectChains[i]->lock();
5187 }
5188}
5189
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005190void AudioFlinger::PlaybackThread::unlockEffectChains(
5191 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
Eric Laurent65b65452010-06-01 23:49:17 -07005192{
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005193 for (size_t i = 0; i < effectChains.size(); i++) {
5194 effectChains[i]->unlock();
Eric Laurent65b65452010-06-01 23:49:17 -07005195 }
5196}
5197
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005198
Eric Laurent65b65452010-06-01 23:49:17 -07005199sp<AudioFlinger::EffectModule> AudioFlinger::PlaybackThread::getEffect_l(int sessionId, int effectId)
5200{
5201 sp<EffectModule> effect;
5202
5203 sp<EffectChain> chain = getEffectChain_l(sessionId);
5204 if (chain != 0) {
Eric Laurent76c40f72010-07-15 12:50:15 -07005205 effect = chain->getEffectFromId_l(effectId);
Eric Laurent65b65452010-06-01 23:49:17 -07005206 }
5207 return effect;
5208}
5209
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005210status_t AudioFlinger::PlaybackThread::attachAuxEffect(
5211 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Eric Laurent65b65452010-06-01 23:49:17 -07005212{
5213 Mutex::Autolock _l(mLock);
5214 return attachAuxEffect_l(track, EffectId);
5215}
5216
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005217status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
5218 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Eric Laurent65b65452010-06-01 23:49:17 -07005219{
5220 status_t status = NO_ERROR;
5221
5222 if (EffectId == 0) {
5223 track->setAuxBuffer(0, NULL);
5224 } else {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005225 // Auxiliary effects are always in audio session AudioSystem::SESSION_OUTPUT_MIX
5226 sp<EffectModule> effect = getEffect_l(AudioSystem::SESSION_OUTPUT_MIX, EffectId);
Eric Laurent65b65452010-06-01 23:49:17 -07005227 if (effect != 0) {
5228 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5229 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
5230 } else {
5231 status = INVALID_OPERATION;
5232 }
5233 } else {
5234 status = BAD_VALUE;
5235 }
5236 }
5237 return status;
5238}
5239
5240void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
5241{
5242 for (size_t i = 0; i < mTracks.size(); ++i) {
5243 sp<Track> track = mTracks[i];
5244 if (track->auxEffectId() == effectId) {
5245 attachAuxEffect_l(track, 0);
5246 }
5247 }
5248}
5249
5250// ----------------------------------------------------------------------------
5251// EffectModule implementation
5252// ----------------------------------------------------------------------------
5253
5254#undef LOG_TAG
5255#define LOG_TAG "AudioFlinger::EffectModule"
5256
5257AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
5258 const wp<AudioFlinger::EffectChain>& chain,
5259 effect_descriptor_t *desc,
5260 int id,
5261 int sessionId)
5262 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
5263 mStatus(NO_INIT), mState(IDLE)
5264{
5265 LOGV("Constructor %p", this);
5266 int lStatus;
5267 sp<ThreadBase> thread = mThread.promote();
5268 if (thread == 0) {
5269 return;
5270 }
5271 PlaybackThread *p = (PlaybackThread *)thread.get();
5272
5273 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
5274
5275 // create effect engine from effect factory
Eric Laurent53334cd2010-06-23 17:38:20 -07005276 mStatus = EffectCreate(&desc->uuid, sessionId, p->id(), &mEffectInterface);
5277
Eric Laurent65b65452010-06-01 23:49:17 -07005278 if (mStatus != NO_ERROR) {
5279 return;
5280 }
5281 lStatus = init();
5282 if (lStatus < 0) {
5283 mStatus = lStatus;
5284 goto Error;
5285 }
5286
5287 LOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
5288 return;
5289Error:
5290 EffectRelease(mEffectInterface);
5291 mEffectInterface = NULL;
5292 LOGV("Constructor Error %d", mStatus);
5293}
5294
5295AudioFlinger::EffectModule::~EffectModule()
5296{
5297 LOGV("Destructor %p", this);
5298 if (mEffectInterface != NULL) {
5299 // release effect engine
5300 EffectRelease(mEffectInterface);
5301 }
5302}
5303
5304status_t AudioFlinger::EffectModule::addHandle(sp<EffectHandle>& handle)
5305{
5306 status_t status;
5307
5308 Mutex::Autolock _l(mLock);
5309 // First handle in mHandles has highest priority and controls the effect module
5310 int priority = handle->priority();
5311 size_t size = mHandles.size();
5312 sp<EffectHandle> h;
5313 size_t i;
5314 for (i = 0; i < size; i++) {
5315 h = mHandles[i].promote();
5316 if (h == 0) continue;
5317 if (h->priority() <= priority) break;
5318 }
5319 // if inserted in first place, move effect control from previous owner to this handle
5320 if (i == 0) {
5321 if (h != 0) {
5322 h->setControl(false, true);
5323 }
5324 handle->setControl(true, false);
5325 status = NO_ERROR;
5326 } else {
5327 status = ALREADY_EXISTS;
5328 }
5329 mHandles.insertAt(handle, i);
5330 return status;
5331}
5332
5333size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
5334{
5335 Mutex::Autolock _l(mLock);
5336 size_t size = mHandles.size();
5337 size_t i;
5338 for (i = 0; i < size; i++) {
5339 if (mHandles[i] == handle) break;
5340 }
5341 if (i == size) {
5342 return size;
5343 }
5344 mHandles.removeAt(i);
5345 size = mHandles.size();
5346 // if removed from first place, move effect control from this handle to next in line
5347 if (i == 0 && size != 0) {
5348 sp<EffectHandle> h = mHandles[0].promote();
5349 if (h != 0) {
5350 h->setControl(true, true);
5351 }
5352 }
5353
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07005354 // Release effect engine here so that it is done immediately. Otherwise it will be released
5355 // by the destructor when the last strong reference on the this object is released which can
5356 // happen after next process is called on this effect.
5357 if (size == 0 && mEffectInterface != NULL) {
5358 // release effect engine
5359 EffectRelease(mEffectInterface);
5360 mEffectInterface = NULL;
5361 }
5362
Eric Laurent65b65452010-06-01 23:49:17 -07005363 return size;
5364}
5365
5366void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle)
5367{
5368 // keep a strong reference on this EffectModule to avoid calling the
5369 // destructor before we exit
5370 sp<EffectModule> keep(this);
Eric Laurent53334cd2010-06-23 17:38:20 -07005371 {
5372 sp<ThreadBase> thread = mThread.promote();
5373 if (thread != 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07005374 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurent53334cd2010-06-23 17:38:20 -07005375 playbackThread->disconnectEffect(keep, handle);
Eric Laurent65b65452010-06-01 23:49:17 -07005376 }
5377 }
5378}
5379
Eric Laurent7d850f22010-07-09 13:34:17 -07005380void AudioFlinger::EffectModule::updateState() {
5381 Mutex::Autolock _l(mLock);
5382
5383 switch (mState) {
5384 case RESTART:
5385 reset_l();
5386 // FALL THROUGH
5387
5388 case STARTING:
5389 // clear auxiliary effect input buffer for next accumulation
5390 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5391 memset(mConfig.inputCfg.buffer.raw,
5392 0,
5393 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
5394 }
5395 start_l();
5396 mState = ACTIVE;
5397 break;
5398 case STOPPING:
5399 stop_l();
5400 mDisableWaitCnt = mMaxDisableWaitCnt;
5401 mState = STOPPED;
5402 break;
5403 case STOPPED:
5404 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
5405 // turn off sequence.
5406 if (--mDisableWaitCnt == 0) {
5407 reset_l();
5408 mState = IDLE;
5409 }
5410 break;
5411 default: //IDLE , ACTIVE
5412 break;
5413 }
5414}
5415
Eric Laurent65b65452010-06-01 23:49:17 -07005416void AudioFlinger::EffectModule::process()
5417{
5418 Mutex::Autolock _l(mLock);
5419
Eric Laurent7d850f22010-07-09 13:34:17 -07005420 if (mEffectInterface == NULL ||
5421 mConfig.inputCfg.buffer.raw == NULL ||
5422 mConfig.outputCfg.buffer.raw == NULL) {
Eric Laurent65b65452010-06-01 23:49:17 -07005423 return;
5424 }
5425
Eric Laurenta92ebfa2010-08-31 13:50:07 -07005426 if (isProcessEnabled()) {
Eric Laurent65b65452010-06-01 23:49:17 -07005427 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
5428 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5429 AudioMixer::ditherAndClamp(mConfig.inputCfg.buffer.s32,
5430 mConfig.inputCfg.buffer.s32,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005431 mConfig.inputCfg.buffer.frameCount/2);
Eric Laurent65b65452010-06-01 23:49:17 -07005432 }
5433
Eric Laurent65b65452010-06-01 23:49:17 -07005434 // do the actual processing in the effect engine
Eric Laurent7d850f22010-07-09 13:34:17 -07005435 int ret = (*mEffectInterface)->process(mEffectInterface,
5436 &mConfig.inputCfg.buffer,
5437 &mConfig.outputCfg.buffer);
5438
5439 // force transition to IDLE state when engine is ready
5440 if (mState == STOPPED && ret == -ENODATA) {
5441 mDisableWaitCnt = 1;
5442 }
Eric Laurent65b65452010-06-01 23:49:17 -07005443
5444 // clear auxiliary effect input buffer for next accumulation
5445 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent67b5ed32011-01-19 18:36:13 -08005446 memset(mConfig.inputCfg.buffer.raw, 0,
5447 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Eric Laurent65b65452010-06-01 23:49:17 -07005448 }
5449 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent67b5ed32011-01-19 18:36:13 -08005450 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
5451 // If an insert effect is idle and input buffer is different from output buffer,
5452 // accumulate input onto output
Eric Laurent65b65452010-06-01 23:49:17 -07005453 sp<EffectChain> chain = mChain.promote();
5454 if (chain != 0 && chain->activeTracks() != 0) {
Eric Laurent67b5ed32011-01-19 18:36:13 -08005455 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
5456 int16_t *in = mConfig.inputCfg.buffer.s16;
5457 int16_t *out = mConfig.outputCfg.buffer.s16;
5458 for (size_t i = 0; i < frameCnt; i++) {
5459 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Eric Laurent65b65452010-06-01 23:49:17 -07005460 }
Eric Laurent65b65452010-06-01 23:49:17 -07005461 }
5462 }
5463}
5464
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005465void AudioFlinger::EffectModule::reset_l()
Eric Laurent65b65452010-06-01 23:49:17 -07005466{
5467 if (mEffectInterface == NULL) {
5468 return;
5469 }
5470 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
5471}
5472
5473status_t AudioFlinger::EffectModule::configure()
5474{
5475 uint32_t channels;
5476 if (mEffectInterface == NULL) {
5477 return NO_INIT;
5478 }
5479
5480 sp<ThreadBase> thread = mThread.promote();
5481 if (thread == 0) {
5482 return DEAD_OBJECT;
5483 }
5484
5485 // TODO: handle configuration of effects replacing track process
5486 if (thread->channelCount() == 1) {
5487 channels = CHANNEL_MONO;
5488 } else {
5489 channels = CHANNEL_STEREO;
5490 }
5491
5492 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5493 mConfig.inputCfg.channels = CHANNEL_MONO;
5494 } else {
5495 mConfig.inputCfg.channels = channels;
5496 }
5497 mConfig.outputCfg.channels = channels;
Eric Laurent53334cd2010-06-23 17:38:20 -07005498 mConfig.inputCfg.format = SAMPLE_FORMAT_PCM_S15;
5499 mConfig.outputCfg.format = SAMPLE_FORMAT_PCM_S15;
Eric Laurent65b65452010-06-01 23:49:17 -07005500 mConfig.inputCfg.samplingRate = thread->sampleRate();
5501 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
5502 mConfig.inputCfg.bufferProvider.cookie = NULL;
5503 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
5504 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
5505 mConfig.outputCfg.bufferProvider.cookie = NULL;
5506 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
5507 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
5508 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
5509 // Insert effect:
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005510 // - in session AudioSystem::SESSION_OUTPUT_MIX or AudioSystem::SESSION_OUTPUT_STAGE,
5511 // always overwrites output buffer: input buffer == output buffer
Eric Laurent65b65452010-06-01 23:49:17 -07005512 // - in other sessions:
5513 // last effect in the chain accumulates in output buffer: input buffer != output buffer
5514 // other effect: overwrites output buffer: input buffer == output buffer
5515 // Auxiliary effect:
5516 // accumulates in output buffer: input buffer != output buffer
5517 // Therefore: accumulate <=> input buffer != output buffer
5518 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
5519 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
5520 } else {
5521 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
5522 }
5523 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
5524 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
5525 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
5526 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
5527
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005528 LOGV("configure() %p thread %p buffer %p framecount %d",
5529 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
5530
Eric Laurent65b65452010-06-01 23:49:17 -07005531 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005532 uint32_t size = sizeof(int);
5533 status_t status = (*mEffectInterface)->command(mEffectInterface,
5534 EFFECT_CMD_CONFIGURE,
5535 sizeof(effect_config_t),
5536 &mConfig,
5537 &size,
5538 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005539 if (status == 0) {
5540 status = cmdStatus;
5541 }
Eric Laurent7d850f22010-07-09 13:34:17 -07005542
5543 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
5544 (1000 * mConfig.outputCfg.buffer.frameCount);
5545
Eric Laurent65b65452010-06-01 23:49:17 -07005546 return status;
5547}
5548
5549status_t AudioFlinger::EffectModule::init()
5550{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005551 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07005552 if (mEffectInterface == NULL) {
5553 return NO_INIT;
5554 }
5555 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005556 uint32_t size = sizeof(status_t);
5557 status_t status = (*mEffectInterface)->command(mEffectInterface,
5558 EFFECT_CMD_INIT,
5559 0,
5560 NULL,
5561 &size,
5562 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005563 if (status == 0) {
5564 status = cmdStatus;
5565 }
5566 return status;
5567}
5568
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005569status_t AudioFlinger::EffectModule::start_l()
Eric Laurent65b65452010-06-01 23:49:17 -07005570{
5571 if (mEffectInterface == NULL) {
5572 return NO_INIT;
5573 }
5574 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005575 uint32_t size = sizeof(status_t);
5576 status_t status = (*mEffectInterface)->command(mEffectInterface,
5577 EFFECT_CMD_ENABLE,
5578 0,
5579 NULL,
5580 &size,
5581 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005582 if (status == 0) {
5583 status = cmdStatus;
5584 }
5585 return status;
5586}
5587
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005588status_t AudioFlinger::EffectModule::stop_l()
Eric Laurent65b65452010-06-01 23:49:17 -07005589{
5590 if (mEffectInterface == NULL) {
5591 return NO_INIT;
5592 }
5593 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005594 uint32_t size = sizeof(status_t);
5595 status_t status = (*mEffectInterface)->command(mEffectInterface,
5596 EFFECT_CMD_DISABLE,
5597 0,
5598 NULL,
5599 &size,
5600 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005601 if (status == 0) {
5602 status = cmdStatus;
5603 }
5604 return status;
5605}
5606
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005607status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
5608 uint32_t cmdSize,
5609 void *pCmdData,
5610 uint32_t *replySize,
5611 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07005612{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005613 Mutex::Autolock _l(mLock);
5614// LOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Eric Laurent65b65452010-06-01 23:49:17 -07005615
5616 if (mEffectInterface == NULL) {
5617 return NO_INIT;
5618 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005619 status_t status = (*mEffectInterface)->command(mEffectInterface,
5620 cmdCode,
5621 cmdSize,
5622 pCmdData,
5623 replySize,
5624 pReplyData);
Eric Laurent65b65452010-06-01 23:49:17 -07005625 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005626 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Eric Laurent65b65452010-06-01 23:49:17 -07005627 for (size_t i = 1; i < mHandles.size(); i++) {
5628 sp<EffectHandle> h = mHandles[i].promote();
5629 if (h != 0) {
5630 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
5631 }
5632 }
5633 }
5634 return status;
5635}
5636
5637status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
5638{
5639 Mutex::Autolock _l(mLock);
5640 LOGV("setEnabled %p enabled %d", this, enabled);
5641
5642 if (enabled != isEnabled()) {
5643 switch (mState) {
5644 // going from disabled to enabled
5645 case IDLE:
Eric Laurent7d850f22010-07-09 13:34:17 -07005646 mState = STARTING;
5647 break;
5648 case STOPPED:
5649 mState = RESTART;
Eric Laurent65b65452010-06-01 23:49:17 -07005650 break;
5651 case STOPPING:
5652 mState = ACTIVE;
5653 break;
Eric Laurent65b65452010-06-01 23:49:17 -07005654
5655 // going from enabled to disabled
Eric Laurent7d850f22010-07-09 13:34:17 -07005656 case RESTART:
Eric Laurenta92ebfa2010-08-31 13:50:07 -07005657 mState = STOPPED;
5658 break;
Eric Laurent65b65452010-06-01 23:49:17 -07005659 case STARTING:
Eric Laurent7d850f22010-07-09 13:34:17 -07005660 mState = IDLE;
Eric Laurent65b65452010-06-01 23:49:17 -07005661 break;
5662 case ACTIVE:
5663 mState = STOPPING;
5664 break;
5665 }
5666 for (size_t i = 1; i < mHandles.size(); i++) {
5667 sp<EffectHandle> h = mHandles[i].promote();
5668 if (h != 0) {
5669 h->setEnabled(enabled);
5670 }
5671 }
5672 }
5673 return NO_ERROR;
5674}
5675
5676bool AudioFlinger::EffectModule::isEnabled()
5677{
5678 switch (mState) {
Eric Laurent7d850f22010-07-09 13:34:17 -07005679 case RESTART:
Eric Laurent65b65452010-06-01 23:49:17 -07005680 case STARTING:
5681 case ACTIVE:
5682 return true;
5683 case IDLE:
5684 case STOPPING:
5685 case STOPPED:
5686 default:
5687 return false;
5688 }
5689}
5690
Eric Laurenta92ebfa2010-08-31 13:50:07 -07005691bool AudioFlinger::EffectModule::isProcessEnabled()
5692{
5693 switch (mState) {
5694 case RESTART:
5695 case ACTIVE:
5696 case STOPPING:
5697 case STOPPED:
5698 return true;
5699 case IDLE:
5700 case STARTING:
5701 default:
5702 return false;
5703 }
5704}
5705
Eric Laurent65b65452010-06-01 23:49:17 -07005706status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
5707{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005708 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07005709 status_t status = NO_ERROR;
5710
5711 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
5712 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurenta92ebfa2010-08-31 13:50:07 -07005713 if (isProcessEnabled() &&
Eric Laurent0d7e0482010-07-19 06:24:46 -07005714 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
5715 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Eric Laurent65b65452010-06-01 23:49:17 -07005716 status_t cmdStatus;
5717 uint32_t volume[2];
5718 uint32_t *pVolume = NULL;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005719 uint32_t size = sizeof(volume);
Eric Laurent65b65452010-06-01 23:49:17 -07005720 volume[0] = *left;
5721 volume[1] = *right;
5722 if (controller) {
5723 pVolume = volume;
5724 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005725 status = (*mEffectInterface)->command(mEffectInterface,
5726 EFFECT_CMD_SET_VOLUME,
5727 size,
5728 volume,
5729 &size,
5730 pVolume);
Eric Laurent65b65452010-06-01 23:49:17 -07005731 if (controller && status == NO_ERROR && size == sizeof(volume)) {
5732 *left = volume[0];
5733 *right = volume[1];
5734 }
5735 }
5736 return status;
5737}
5738
5739status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
5740{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005741 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07005742 status_t status = NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07005743 if ((mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
5744 // convert device bit field from AudioSystem to EffectApi format.
5745 device = deviceAudioSystemToEffectApi(device);
5746 if (device == 0) {
5747 return BAD_VALUE;
5748 }
Eric Laurent65b65452010-06-01 23:49:17 -07005749 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005750 uint32_t size = sizeof(status_t);
5751 status = (*mEffectInterface)->command(mEffectInterface,
5752 EFFECT_CMD_SET_DEVICE,
5753 sizeof(uint32_t),
5754 &device,
5755 &size,
5756 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005757 if (status == NO_ERROR) {
5758 status = cmdStatus;
5759 }
5760 }
5761 return status;
5762}
5763
Eric Laurent53334cd2010-06-23 17:38:20 -07005764status_t AudioFlinger::EffectModule::setMode(uint32_t mode)
5765{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005766 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07005767 status_t status = NO_ERROR;
5768 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
5769 // convert audio mode from AudioSystem to EffectApi format.
5770 int effectMode = modeAudioSystemToEffectApi(mode);
5771 if (effectMode < 0) {
5772 return BAD_VALUE;
5773 }
5774 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005775 uint32_t size = sizeof(status_t);
5776 status = (*mEffectInterface)->command(mEffectInterface,
5777 EFFECT_CMD_SET_AUDIO_MODE,
5778 sizeof(int),
5779 &effectMode,
5780 &size,
5781 &cmdStatus);
Eric Laurent53334cd2010-06-23 17:38:20 -07005782 if (status == NO_ERROR) {
5783 status = cmdStatus;
5784 }
5785 }
5786 return status;
5787}
5788
5789// update this table when AudioSystem::audio_devices or audio_device_e (in EffectApi.h) are modified
5790const uint32_t AudioFlinger::EffectModule::sDeviceConvTable[] = {
5791 DEVICE_EARPIECE, // AudioSystem::DEVICE_OUT_EARPIECE
5792 DEVICE_SPEAKER, // AudioSystem::DEVICE_OUT_SPEAKER
5793 DEVICE_WIRED_HEADSET, // case AudioSystem::DEVICE_OUT_WIRED_HEADSET
5794 DEVICE_WIRED_HEADPHONE, // AudioSystem::DEVICE_OUT_WIRED_HEADPHONE
5795 DEVICE_BLUETOOTH_SCO, // AudioSystem::DEVICE_OUT_BLUETOOTH_SCO
5796 DEVICE_BLUETOOTH_SCO_HEADSET, // AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_HEADSET
5797 DEVICE_BLUETOOTH_SCO_CARKIT, // AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_CARKIT
5798 DEVICE_BLUETOOTH_A2DP, // AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP
5799 DEVICE_BLUETOOTH_A2DP_HEADPHONES, // AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES
5800 DEVICE_BLUETOOTH_A2DP_SPEAKER, // AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER
5801 DEVICE_AUX_DIGITAL // AudioSystem::DEVICE_OUT_AUX_DIGITAL
5802};
5803
5804uint32_t AudioFlinger::EffectModule::deviceAudioSystemToEffectApi(uint32_t device)
5805{
5806 uint32_t deviceOut = 0;
5807 while (device) {
5808 const uint32_t i = 31 - __builtin_clz(device);
5809 device &= ~(1 << i);
5810 if (i >= sizeof(sDeviceConvTable)/sizeof(uint32_t)) {
5811 LOGE("device convertion error for AudioSystem device 0x%08x", device);
5812 return 0;
5813 }
5814 deviceOut |= (uint32_t)sDeviceConvTable[i];
5815 }
5816 return deviceOut;
5817}
5818
5819// update this table when AudioSystem::audio_mode or audio_mode_e (in EffectApi.h) are modified
5820const uint32_t AudioFlinger::EffectModule::sModeConvTable[] = {
5821 AUDIO_MODE_NORMAL, // AudioSystem::MODE_NORMAL
5822 AUDIO_MODE_RINGTONE, // AudioSystem::MODE_RINGTONE
Jean-Michel Trivi8f677d62010-11-15 12:11:32 -08005823 AUDIO_MODE_IN_CALL, // AudioSystem::MODE_IN_CALL
5824 AUDIO_MODE_IN_CALL // AudioSystem::MODE_IN_COMMUNICATION, same conversion as for MODE_IN_CALL
Eric Laurent53334cd2010-06-23 17:38:20 -07005825};
5826
5827int AudioFlinger::EffectModule::modeAudioSystemToEffectApi(uint32_t mode)
5828{
5829 int modeOut = -1;
5830 if (mode < sizeof(sModeConvTable) / sizeof(uint32_t)) {
5831 modeOut = (int)sModeConvTable[mode];
5832 }
5833 return modeOut;
5834}
Eric Laurent65b65452010-06-01 23:49:17 -07005835
5836status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
5837{
5838 const size_t SIZE = 256;
5839 char buffer[SIZE];
5840 String8 result;
5841
5842 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
5843 result.append(buffer);
5844
5845 bool locked = tryLock(mLock);
5846 // failed to lock - AudioFlinger is probably deadlocked
5847 if (!locked) {
5848 result.append("\t\tCould not lock Fx mutex:\n");
5849 }
5850
5851 result.append("\t\tSession Status State Engine:\n");
5852 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
5853 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
5854 result.append(buffer);
5855
5856 result.append("\t\tDescriptor:\n");
5857 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
5858 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
5859 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
5860 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
5861 result.append(buffer);
5862 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
5863 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
5864 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
5865 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
5866 result.append(buffer);
5867 snprintf(buffer, SIZE, "\t\t- apiVersion: %04X\n\t\t- flags: %08X\n",
5868 mDescriptor.apiVersion,
5869 mDescriptor.flags);
5870 result.append(buffer);
5871 snprintf(buffer, SIZE, "\t\t- name: %s\n",
5872 mDescriptor.name);
5873 result.append(buffer);
5874 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
5875 mDescriptor.implementor);
5876 result.append(buffer);
5877
5878 result.append("\t\t- Input configuration:\n");
5879 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
5880 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
5881 (uint32_t)mConfig.inputCfg.buffer.raw,
5882 mConfig.inputCfg.buffer.frameCount,
5883 mConfig.inputCfg.samplingRate,
5884 mConfig.inputCfg.channels,
5885 mConfig.inputCfg.format);
5886 result.append(buffer);
5887
5888 result.append("\t\t- Output configuration:\n");
5889 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
5890 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
5891 (uint32_t)mConfig.outputCfg.buffer.raw,
5892 mConfig.outputCfg.buffer.frameCount,
5893 mConfig.outputCfg.samplingRate,
5894 mConfig.outputCfg.channels,
5895 mConfig.outputCfg.format);
5896 result.append(buffer);
5897
5898 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
5899 result.append(buffer);
5900 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
5901 for (size_t i = 0; i < mHandles.size(); ++i) {
5902 sp<EffectHandle> handle = mHandles[i].promote();
5903 if (handle != 0) {
5904 handle->dump(buffer, SIZE);
5905 result.append(buffer);
5906 }
5907 }
5908
5909 result.append("\n");
5910
5911 write(fd, result.string(), result.length());
5912
5913 if (locked) {
5914 mLock.unlock();
5915 }
5916
5917 return NO_ERROR;
5918}
5919
5920// ----------------------------------------------------------------------------
5921// EffectHandle implementation
5922// ----------------------------------------------------------------------------
5923
5924#undef LOG_TAG
5925#define LOG_TAG "AudioFlinger::EffectHandle"
5926
5927AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
5928 const sp<AudioFlinger::Client>& client,
5929 const sp<IEffectClient>& effectClient,
5930 int32_t priority)
5931 : BnEffect(),
5932 mEffect(effect), mEffectClient(effectClient), mClient(client), mPriority(priority), mHasControl(false)
5933{
5934 LOGV("constructor %p", this);
5935
5936 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
5937 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
5938 if (mCblkMemory != 0) {
5939 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
5940
5941 if (mCblk) {
5942 new(mCblk) effect_param_cblk_t();
5943 mBuffer = (uint8_t *)mCblk + bufOffset;
5944 }
5945 } else {
5946 LOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
5947 return;
5948 }
5949}
5950
5951AudioFlinger::EffectHandle::~EffectHandle()
5952{
5953 LOGV("Destructor %p", this);
5954 disconnect();
5955}
5956
5957status_t AudioFlinger::EffectHandle::enable()
5958{
5959 if (!mHasControl) return INVALID_OPERATION;
5960 if (mEffect == 0) return DEAD_OBJECT;
5961
5962 return mEffect->setEnabled(true);
5963}
5964
5965status_t AudioFlinger::EffectHandle::disable()
5966{
5967 if (!mHasControl) return INVALID_OPERATION;
5968 if (mEffect == NULL) return DEAD_OBJECT;
5969
5970 return mEffect->setEnabled(false);
5971}
5972
5973void AudioFlinger::EffectHandle::disconnect()
5974{
5975 if (mEffect == 0) {
5976 return;
5977 }
5978 mEffect->disconnect(this);
5979 // release sp on module => module destructor can be called now
5980 mEffect.clear();
5981 if (mCblk) {
5982 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
5983 }
5984 mCblkMemory.clear(); // and free the shared memory
5985 if (mClient != 0) {
5986 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
5987 mClient.clear();
5988 }
5989}
5990
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005991status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
5992 uint32_t cmdSize,
5993 void *pCmdData,
5994 uint32_t *replySize,
5995 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07005996{
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005997// LOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
5998// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Eric Laurent65b65452010-06-01 23:49:17 -07005999
6000 // only get parameter command is permitted for applications not controlling the effect
6001 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
6002 return INVALID_OPERATION;
6003 }
6004 if (mEffect == 0) return DEAD_OBJECT;
6005
6006 // handle commands that are not forwarded transparently to effect engine
6007 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
6008 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
6009 // no risk to block the whole media server process or mixer threads is we are stuck here
6010 Mutex::Autolock _l(mCblk->lock);
6011 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
6012 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
6013 mCblk->serverIndex = 0;
6014 mCblk->clientIndex = 0;
6015 return BAD_VALUE;
6016 }
6017 status_t status = NO_ERROR;
6018 while (mCblk->serverIndex < mCblk->clientIndex) {
6019 int reply;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006020 uint32_t rsize = sizeof(int);
Eric Laurent65b65452010-06-01 23:49:17 -07006021 int *p = (int *)(mBuffer + mCblk->serverIndex);
6022 int size = *p++;
Eric Laurent53334cd2010-06-23 17:38:20 -07006023 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
6024 LOGW("command(): invalid parameter block size");
6025 break;
6026 }
Eric Laurent65b65452010-06-01 23:49:17 -07006027 effect_param_t *param = (effect_param_t *)p;
Eric Laurent53334cd2010-06-23 17:38:20 -07006028 if (param->psize == 0 || param->vsize == 0) {
6029 LOGW("command(): null parameter or value size");
6030 mCblk->serverIndex += size;
6031 continue;
6032 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006033 uint32_t psize = sizeof(effect_param_t) +
6034 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
6035 param->vsize;
6036 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
6037 psize,
6038 p,
6039 &rsize,
6040 &reply);
Eric Laurente65280c2010-09-02 11:56:55 -07006041 // stop at first error encountered
6042 if (ret != NO_ERROR) {
Eric Laurent65b65452010-06-01 23:49:17 -07006043 status = ret;
Eric Laurente65280c2010-09-02 11:56:55 -07006044 *(int *)pReplyData = reply;
6045 break;
6046 } else if (reply != NO_ERROR) {
6047 *(int *)pReplyData = reply;
6048 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006049 }
6050 mCblk->serverIndex += size;
6051 }
6052 mCblk->serverIndex = 0;
6053 mCblk->clientIndex = 0;
6054 return status;
6055 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurente65280c2010-09-02 11:56:55 -07006056 *(int *)pReplyData = NO_ERROR;
Eric Laurent65b65452010-06-01 23:49:17 -07006057 return enable();
6058 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurente65280c2010-09-02 11:56:55 -07006059 *(int *)pReplyData = NO_ERROR;
Eric Laurent65b65452010-06-01 23:49:17 -07006060 return disable();
6061 }
6062
6063 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
6064}
6065
6066sp<IMemory> AudioFlinger::EffectHandle::getCblk() const {
6067 return mCblkMemory;
6068}
6069
6070void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal)
6071{
6072 LOGV("setControl %p control %d", this, hasControl);
6073
6074 mHasControl = hasControl;
6075 if (signal && mEffectClient != 0) {
6076 mEffectClient->controlStatusChanged(hasControl);
6077 }
6078}
6079
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006080void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
6081 uint32_t cmdSize,
6082 void *pCmdData,
6083 uint32_t replySize,
6084 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07006085{
6086 if (mEffectClient != 0) {
6087 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
6088 }
6089}
6090
6091
6092
6093void AudioFlinger::EffectHandle::setEnabled(bool enabled)
6094{
6095 if (mEffectClient != 0) {
6096 mEffectClient->enableStatusChanged(enabled);
6097 }
6098}
6099
6100status_t AudioFlinger::EffectHandle::onTransact(
6101 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6102{
6103 return BnEffect::onTransact(code, data, reply, flags);
6104}
6105
6106
6107void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
6108{
6109 bool locked = tryLock(mCblk->lock);
6110
6111 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
6112 (mClient == NULL) ? getpid() : mClient->pid(),
6113 mPriority,
6114 mHasControl,
6115 !locked,
6116 mCblk->clientIndex,
6117 mCblk->serverIndex
6118 );
6119
6120 if (locked) {
6121 mCblk->lock.unlock();
6122 }
6123}
6124
6125#undef LOG_TAG
6126#define LOG_TAG "AudioFlinger::EffectChain"
6127
6128AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
6129 int sessionId)
Eric Laurent76c40f72010-07-15 12:50:15 -07006130 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mOwnInBuffer(false),
Eric Laurent2a6b80b2010-07-29 23:43:43 -07006131 mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
6132 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Eric Laurent65b65452010-06-01 23:49:17 -07006133{
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006134 mStrategy = AudioSystem::getStrategyForStream(AudioSystem::MUSIC);
Eric Laurent65b65452010-06-01 23:49:17 -07006135}
6136
6137AudioFlinger::EffectChain::~EffectChain()
6138{
6139 if (mOwnInBuffer) {
6140 delete mInBuffer;
6141 }
6142
6143}
6144
Eric Laurent76c40f72010-07-15 12:50:15 -07006145// getEffectFromDesc_l() must be called with PlaybackThread::mLock held
6146sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Eric Laurent65b65452010-06-01 23:49:17 -07006147{
6148 sp<EffectModule> effect;
6149 size_t size = mEffects.size();
6150
6151 for (size_t i = 0; i < size; i++) {
6152 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
6153 effect = mEffects[i];
6154 break;
6155 }
6156 }
6157 return effect;
6158}
6159
Eric Laurent76c40f72010-07-15 12:50:15 -07006160// getEffectFromId_l() must be called with PlaybackThread::mLock held
6161sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Eric Laurent65b65452010-06-01 23:49:17 -07006162{
6163 sp<EffectModule> effect;
6164 size_t size = mEffects.size();
6165
6166 for (size_t i = 0; i < size; i++) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006167 // by convention, return first effect if id provided is 0 (0 is never a valid id)
6168 if (id == 0 || mEffects[i]->id() == id) {
Eric Laurent65b65452010-06-01 23:49:17 -07006169 effect = mEffects[i];
6170 break;
6171 }
6172 }
6173 return effect;
6174}
6175
6176// Must be called with EffectChain::mLock locked
6177void AudioFlinger::EffectChain::process_l()
6178{
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07006179 sp<ThreadBase> thread = mThread.promote();
6180 if (thread == 0) {
6181 LOGW("process_l(): cannot promote mixer thread");
6182 return;
6183 }
6184 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
6185 bool isGlobalSession = (mSessionId == AudioSystem::SESSION_OUTPUT_MIX) ||
6186 (mSessionId == AudioSystem::SESSION_OUTPUT_STAGE);
6187 bool tracksOnSession = false;
6188 if (!isGlobalSession) {
6189 tracksOnSession =
6190 playbackThread->hasAudioSession(mSessionId) & PlaybackThread::TRACK_SESSION;
6191 }
6192
Eric Laurent65b65452010-06-01 23:49:17 -07006193 size_t size = mEffects.size();
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07006194 // do not process effect if no track is present in same audio session
6195 if (isGlobalSession || tracksOnSession) {
6196 for (size_t i = 0; i < size; i++) {
6197 mEffects[i]->process();
6198 }
Eric Laurent65b65452010-06-01 23:49:17 -07006199 }
Eric Laurent7d850f22010-07-09 13:34:17 -07006200 for (size_t i = 0; i < size; i++) {
6201 mEffects[i]->updateState();
6202 }
Eric Laurent65b65452010-06-01 23:49:17 -07006203 // if no track is active, input buffer must be cleared here as the mixer process
6204 // will not do it
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07006205 if (tracksOnSession &&
6206 activeTracks() == 0) {
6207 size_t numSamples = playbackThread->frameCount() * playbackThread->channelCount();
6208 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
Eric Laurent65b65452010-06-01 23:49:17 -07006209 }
6210}
6211
Eric Laurent76c40f72010-07-15 12:50:15 -07006212// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006213status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Eric Laurent65b65452010-06-01 23:49:17 -07006214{
6215 effect_descriptor_t desc = effect->desc();
6216 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
6217
6218 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006219 effect->setChain(this);
6220 sp<ThreadBase> thread = mThread.promote();
6221 if (thread == 0) {
6222 return NO_INIT;
6223 }
6224 effect->setThread(thread);
Eric Laurent65b65452010-06-01 23:49:17 -07006225
6226 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6227 // Auxiliary effects are inserted at the beginning of mEffects vector as
6228 // they are processed first and accumulated in chain input buffer
6229 mEffects.insertAt(effect, 0);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006230
Eric Laurent65b65452010-06-01 23:49:17 -07006231 // the input buffer for auxiliary effect contains mono samples in
6232 // 32 bit format. This is to avoid saturation in AudoMixer
6233 // accumulation stage. Saturation is done in EffectModule::process() before
6234 // calling the process in effect engine
6235 size_t numSamples = thread->frameCount();
6236 int32_t *buffer = new int32_t[numSamples];
6237 memset(buffer, 0, numSamples * sizeof(int32_t));
6238 effect->setInBuffer((int16_t *)buffer);
6239 // auxiliary effects output samples to chain input buffer for further processing
6240 // by insert effects
6241 effect->setOutBuffer(mInBuffer);
6242 } else {
6243 // Insert effects are inserted at the end of mEffects vector as they are processed
6244 // after track and auxiliary effects.
Eric Laurent53334cd2010-06-23 17:38:20 -07006245 // Insert effect order as a function of indicated preference:
6246 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
6247 // another effect is present
6248 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
6249 // last effect claiming first position
6250 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
6251 // first effect claiming last position
Eric Laurent65b65452010-06-01 23:49:17 -07006252 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
Eric Laurent53334cd2010-06-23 17:38:20 -07006253 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
6254 // already present
Eric Laurent65b65452010-06-01 23:49:17 -07006255
6256 int size = (int)mEffects.size();
6257 int idx_insert = size;
6258 int idx_insert_first = -1;
6259 int idx_insert_last = -1;
6260
6261 for (int i = 0; i < size; i++) {
6262 effect_descriptor_t d = mEffects[i]->desc();
6263 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
6264 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
6265 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
6266 // check invalid effect chaining combinations
6267 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
Eric Laurent53334cd2010-06-23 17:38:20 -07006268 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Eric Laurent76c40f72010-07-15 12:50:15 -07006269 LOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Eric Laurent65b65452010-06-01 23:49:17 -07006270 return INVALID_OPERATION;
6271 }
Eric Laurent53334cd2010-06-23 17:38:20 -07006272 // remember position of first insert effect and by default
6273 // select this as insert position for new effect
Eric Laurent65b65452010-06-01 23:49:17 -07006274 if (idx_insert == size) {
6275 idx_insert = i;
6276 }
Eric Laurent53334cd2010-06-23 17:38:20 -07006277 // remember position of last insert effect claiming
6278 // first position
Eric Laurent65b65452010-06-01 23:49:17 -07006279 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
6280 idx_insert_first = i;
6281 }
Eric Laurent53334cd2010-06-23 17:38:20 -07006282 // remember position of first insert effect claiming
6283 // last position
6284 if (iPref == EFFECT_FLAG_INSERT_LAST &&
6285 idx_insert_last == -1) {
Eric Laurent65b65452010-06-01 23:49:17 -07006286 idx_insert_last = i;
6287 }
6288 }
6289 }
6290
Eric Laurent53334cd2010-06-23 17:38:20 -07006291 // modify idx_insert from first position if needed
6292 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
6293 if (idx_insert_last != -1) {
6294 idx_insert = idx_insert_last;
6295 } else {
6296 idx_insert = size;
6297 }
6298 } else {
6299 if (idx_insert_first != -1) {
6300 idx_insert = idx_insert_first + 1;
6301 }
Eric Laurent65b65452010-06-01 23:49:17 -07006302 }
6303
6304 // always read samples from chain input buffer
6305 effect->setInBuffer(mInBuffer);
6306
6307 // if last effect in the chain, output samples to chain
6308 // output buffer, otherwise to chain input buffer
6309 if (idx_insert == size) {
6310 if (idx_insert != 0) {
6311 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
6312 mEffects[idx_insert-1]->configure();
6313 }
6314 effect->setOutBuffer(mOutBuffer);
6315 } else {
6316 effect->setOutBuffer(mInBuffer);
6317 }
Eric Laurent53334cd2010-06-23 17:38:20 -07006318 mEffects.insertAt(effect, idx_insert);
Eric Laurent65b65452010-06-01 23:49:17 -07006319
Eric Laurent76c40f72010-07-15 12:50:15 -07006320 LOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Eric Laurent65b65452010-06-01 23:49:17 -07006321 }
6322 effect->configure();
6323 return NO_ERROR;
6324}
6325
Eric Laurent76c40f72010-07-15 12:50:15 -07006326// removeEffect_l() must be called with PlaybackThread::mLock held
6327size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Eric Laurent65b65452010-06-01 23:49:17 -07006328{
6329 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07006330 int size = (int)mEffects.size();
6331 int i;
6332 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
6333
6334 for (i = 0; i < size; i++) {
6335 if (effect == mEffects[i]) {
6336 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
6337 delete[] effect->inBuffer();
6338 } else {
6339 if (i == size - 1 && i != 0) {
6340 mEffects[i - 1]->setOutBuffer(mOutBuffer);
6341 mEffects[i - 1]->configure();
6342 }
6343 }
6344 mEffects.removeAt(i);
Eric Laurent76c40f72010-07-15 12:50:15 -07006345 LOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Eric Laurent65b65452010-06-01 23:49:17 -07006346 break;
6347 }
6348 }
Eric Laurent65b65452010-06-01 23:49:17 -07006349
6350 return mEffects.size();
6351}
6352
Eric Laurent76c40f72010-07-15 12:50:15 -07006353// setDevice_l() must be called with PlaybackThread::mLock held
6354void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Eric Laurent65b65452010-06-01 23:49:17 -07006355{
6356 size_t size = mEffects.size();
6357 for (size_t i = 0; i < size; i++) {
6358 mEffects[i]->setDevice(device);
6359 }
6360}
6361
Eric Laurent76c40f72010-07-15 12:50:15 -07006362// setMode_l() must be called with PlaybackThread::mLock held
6363void AudioFlinger::EffectChain::setMode_l(uint32_t mode)
Eric Laurent53334cd2010-06-23 17:38:20 -07006364{
6365 size_t size = mEffects.size();
6366 for (size_t i = 0; i < size; i++) {
6367 mEffects[i]->setMode(mode);
6368 }
6369}
6370
Eric Laurent76c40f72010-07-15 12:50:15 -07006371// setVolume_l() must be called with PlaybackThread::mLock held
6372bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Eric Laurent65b65452010-06-01 23:49:17 -07006373{
6374 uint32_t newLeft = *left;
6375 uint32_t newRight = *right;
6376 bool hasControl = false;
Eric Laurent76c40f72010-07-15 12:50:15 -07006377 int ctrlIdx = -1;
6378 size_t size = mEffects.size();
Eric Laurent65b65452010-06-01 23:49:17 -07006379
Eric Laurent76c40f72010-07-15 12:50:15 -07006380 // first update volume controller
6381 for (size_t i = size; i > 0; i--) {
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006382 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurent76c40f72010-07-15 12:50:15 -07006383 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
6384 ctrlIdx = i - 1;
Eric Laurent0d7e0482010-07-19 06:24:46 -07006385 hasControl = true;
Eric Laurent76c40f72010-07-15 12:50:15 -07006386 break;
6387 }
6388 }
6389
6390 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurent0d7e0482010-07-19 06:24:46 -07006391 if (hasControl) {
6392 *left = mNewLeftVolume;
6393 *right = mNewRightVolume;
6394 }
6395 return hasControl;
Eric Laurent76c40f72010-07-15 12:50:15 -07006396 }
6397
6398 mVolumeCtrlIdx = ctrlIdx;
Eric Laurent0d7e0482010-07-19 06:24:46 -07006399 mLeftVolume = newLeft;
6400 mRightVolume = newRight;
Eric Laurent76c40f72010-07-15 12:50:15 -07006401
6402 // second get volume update from volume controller
6403 if (ctrlIdx >= 0) {
6404 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurent0d7e0482010-07-19 06:24:46 -07006405 mNewLeftVolume = newLeft;
6406 mNewRightVolume = newRight;
Eric Laurent65b65452010-06-01 23:49:17 -07006407 }
6408 // then indicate volume to all other effects in chain.
6409 // Pass altered volume to effects before volume controller
6410 // and requested volume to effects after controller
6411 uint32_t lVol = newLeft;
6412 uint32_t rVol = newRight;
Eric Laurent76c40f72010-07-15 12:50:15 -07006413
Eric Laurent65b65452010-06-01 23:49:17 -07006414 for (size_t i = 0; i < size; i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07006415 if ((int)i == ctrlIdx) continue;
6416 // this also works for ctrlIdx == -1 when there is no volume controller
6417 if ((int)i > ctrlIdx) {
Eric Laurent65b65452010-06-01 23:49:17 -07006418 lVol = *left;
6419 rVol = *right;
6420 }
6421 mEffects[i]->setVolume(&lVol, &rVol, false);
6422 }
6423 *left = newLeft;
6424 *right = newRight;
6425
6426 return hasControl;
6427}
6428
Eric Laurent65b65452010-06-01 23:49:17 -07006429status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
6430{
6431 const size_t SIZE = 256;
6432 char buffer[SIZE];
6433 String8 result;
6434
6435 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
6436 result.append(buffer);
6437
6438 bool locked = tryLock(mLock);
6439 // failed to lock - AudioFlinger is probably deadlocked
6440 if (!locked) {
6441 result.append("\tCould not lock mutex:\n");
6442 }
6443
Eric Laurent76c40f72010-07-15 12:50:15 -07006444 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
6445 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Eric Laurent65b65452010-06-01 23:49:17 -07006446 mEffects.size(),
6447 (uint32_t)mInBuffer,
6448 (uint32_t)mOutBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -07006449 mActiveTrackCnt);
6450 result.append(buffer);
6451 write(fd, result.string(), result.size());
6452
6453 for (size_t i = 0; i < mEffects.size(); ++i) {
6454 sp<EffectModule> effect = mEffects[i];
6455 if (effect != 0) {
6456 effect->dump(fd, args);
6457 }
6458 }
6459
6460 if (locked) {
6461 mLock.unlock();
6462 }
6463
6464 return NO_ERROR;
6465}
6466
6467#undef LOG_TAG
6468#define LOG_TAG "AudioFlinger"
6469
Eric Laurenta553c252009-07-17 12:17:14 -07006470// ----------------------------------------------------------------------------
6471
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07006472status_t AudioFlinger::onTransact(
6473 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6474{
6475 return BnAudioFlinger::onTransact(code, data, reply, flags);
6476}
6477
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07006478}; // namespace android