blob: 2b08ab59f87b6fce6080d414537d0f43561af8e0 [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
Gloria Wang9b3f1522011-02-24 14:51:45 -080027#include <binder/IPCThreadState.h>
Mathias Agopian07952722009-05-19 19:08:10 -070028#include <binder/IServiceManager.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070029#include <utils/Log.h>
Mathias Agopian07952722009-05-19 19:08:10 -070030#include <binder/Parcel.h>
31#include <binder/IPCThreadState.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070032#include <utils/String16.h>
33#include <utils/threads.h>
34
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080035#include <cutils/properties.h>
36
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070037#include <media/AudioTrack.h>
38#include <media/AudioRecord.h>
Gloria Wang9b3f1522011-02-24 14:51:45 -080039#include <media/IMediaPlayerService.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070040
41#include <private/media/AudioTrackShared.h>
Eric Laurent65b65452010-06-01 23:49:17 -070042#include <private/media/AudioEffectShared.h>
The Android Open Source Project9266c552009-01-15 16:12:10 -080043#include <hardware_legacy/AudioHardwareInterface.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070044
45#include "AudioMixer.h"
46#include "AudioFlinger.h"
47
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080048#ifdef WITH_A2DP
49#include "A2dpAudioInterface.h"
50#endif
51
Eric Laurent53334cd2010-06-23 17:38:20 -070052#include <media/EffectsFactoryApi.h>
Eric Laurentdf9b81c2010-07-02 08:12:41 -070053#include <media/EffectVisualizerApi.h>
Eric Laurent65b65452010-06-01 23:49:17 -070054
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055// ----------------------------------------------------------------------------
56// the sim build doesn't have gettid
57
58#ifndef HAVE_GETTID
59# define gettid getpid
60#endif
61
62// ----------------------------------------------------------------------------
63
Eric Laurent8ed6ed02010-07-13 04:45:46 -070064extern const char * const gEffectLibPath;
65
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070066namespace android {
67
The Android Open Source Project10592532009-03-18 17:39:46 -070068static const char* kDeadlockedString = "AudioFlinger may be deadlocked\n";
69static const char* kHardwareLockedString = "Hardware lock is taken\n";
70
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080071//static const nsecs_t kStandbyTimeInNsecs = seconds(3);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070072static const float MAX_GAIN = 4096.0f;
Eric Laurent65b65452010-06-01 23:49:17 -070073static const float MAX_GAIN_INT = 0x1000;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070074
75// retry counts for buffer fill timeout
76// 50 * ~20msecs = 1 second
77static const int8_t kMaxTrackRetries = 50;
78static const int8_t kMaxTrackStartupRetries = 50;
Eric Laurentef9500f2010-03-11 14:47:00 -080079// allow less retry attempts on direct output thread.
80// direct outputs can be a scarce resource in audio hardware and should
81// be released as quickly as possible.
82static const int8_t kMaxTrackRetriesDirect = 2;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070083
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -070084static const int kDumpLockRetries = 50;
85static const int kDumpLockSleep = 20000;
86
Dave Sparksd0ac8c02009-09-30 03:09:03 -070087static const nsecs_t kWarningThrottle = seconds(5);
88
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070090#define AUDIOFLINGER_SECURITY_ENABLED 1
91
92// ----------------------------------------------------------------------------
93
94static bool recordingAllowed() {
95#ifndef HAVE_ANDROID_OS
96 return true;
97#endif
98#if AUDIOFLINGER_SECURITY_ENABLED
99 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
100 bool ok = checkCallingPermission(String16("android.permission.RECORD_AUDIO"));
101 if (!ok) LOGE("Request requires android.permission.RECORD_AUDIO");
102 return ok;
103#else
104 if (!checkCallingPermission(String16("android.permission.RECORD_AUDIO")))
105 LOGW("WARNING: Need to add android.permission.RECORD_AUDIO to manifest");
106 return true;
107#endif
108}
109
110static bool settingsAllowed() {
111#ifndef HAVE_ANDROID_OS
112 return true;
113#endif
114#if AUDIOFLINGER_SECURITY_ENABLED
115 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
116 bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
117 if (!ok) LOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
118 return ok;
119#else
120 if (!checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS")))
121 LOGW("WARNING: Need to add android.permission.MODIFY_AUDIO_SETTINGS to manifest");
122 return true;
123#endif
124}
125
Gloria Wang9b3f1522011-02-24 14:51:45 -0800126// To collect the amplifier usage
127static void addBatteryData(uint32_t params) {
128 sp<IBinder> binder =
129 defaultServiceManager()->getService(String16("media.player"));
130 sp<IMediaPlayerService> service = interface_cast<IMediaPlayerService>(binder);
131 if (service.get() == NULL) {
132 LOGW("Cannot connect to the MediaPlayerService for battery tracking");
133 return;
134 }
135
136 service->addBatteryData(params);
137}
138
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700139// ----------------------------------------------------------------------------
140
141AudioFlinger::AudioFlinger()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800142 : BnAudioFlinger(),
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700143 mAudioHardware(0), mMasterVolume(1.0f), mMasterMute(false), mNextUniqueId(1)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700144{
Eric Laurent01635942011-01-18 18:39:02 -0800145 Mutex::Autolock _l(mLock);
146
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700147 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -0700148
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700149 mAudioHardware = AudioHardwareInterface::create();
Eric Laurenta553c252009-07-17 12:17:14 -0700150
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700151 mHardwareStatus = AUDIO_HW_INIT;
152 if (mAudioHardware->initCheck() == NO_ERROR) {
Eric Laurent01635942011-01-18 18:39:02 -0800153 AutoMutex lock(mHardwareLock);
Eric Laurent53334cd2010-06-23 17:38:20 -0700154 mMode = AudioSystem::MODE_NORMAL;
Eric Laurent01635942011-01-18 18:39:02 -0800155 mHardwareStatus = AUDIO_HW_SET_MODE;
156 mAudioHardware->setMode(mMode);
157 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
158 mAudioHardware->setMasterVolume(1.0f);
159 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -0700160 } else {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700161 LOGE("Couldn't even initialize the stubbed audio hardware!");
162 }
163}
164
165AudioFlinger::~AudioFlinger()
166{
Eric Laurent7954c462009-08-28 10:39:03 -0700167 while (!mRecordThreads.isEmpty()) {
168 // closeInput() will remove first entry from mRecordThreads
169 closeInput(mRecordThreads.keyAt(0));
170 }
171 while (!mPlaybackThreads.isEmpty()) {
172 // closeOutput() will remove first entry from mPlaybackThreads
173 closeOutput(mPlaybackThreads.keyAt(0));
174 }
175 if (mAudioHardware) {
176 delete mAudioHardware;
177 }
The Android Open Source Projectb7986892009-01-09 17:51:23 -0800178}
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800179
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700180
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700181
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700182status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
183{
184 const size_t SIZE = 256;
185 char buffer[SIZE];
186 String8 result;
187
188 result.append("Clients:\n");
189 for (size_t i = 0; i < mClients.size(); ++i) {
190 wp<Client> wClient = mClients.valueAt(i);
191 if (wClient != 0) {
192 sp<Client> client = wClient.promote();
193 if (client != 0) {
194 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
195 result.append(buffer);
196 }
197 }
198 }
199 write(fd, result.string(), result.size());
200 return NO_ERROR;
201}
202
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700203
204status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
205{
206 const size_t SIZE = 256;
207 char buffer[SIZE];
208 String8 result;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700209 int hardwareStatus = mHardwareStatus;
Eric Laurenta553c252009-07-17 12:17:14 -0700210
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700211 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700212 result.append(buffer);
213 write(fd, result.string(), result.size());
214 return NO_ERROR;
215}
216
217status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
218{
219 const size_t SIZE = 256;
220 char buffer[SIZE];
221 String8 result;
222 snprintf(buffer, SIZE, "Permission Denial: "
223 "can't dump AudioFlinger from pid=%d, uid=%d\n",
224 IPCThreadState::self()->getCallingPid(),
225 IPCThreadState::self()->getCallingUid());
226 result.append(buffer);
227 write(fd, result.string(), result.size());
228 return NO_ERROR;
229}
230
The Android Open Source Project10592532009-03-18 17:39:46 -0700231static bool tryLock(Mutex& mutex)
232{
233 bool locked = false;
234 for (int i = 0; i < kDumpLockRetries; ++i) {
235 if (mutex.tryLock() == NO_ERROR) {
236 locked = true;
237 break;
238 }
239 usleep(kDumpLockSleep);
240 }
241 return locked;
242}
243
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700244status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
245{
246 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
247 dumpPermissionDenial(fd, args);
248 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -0700249 // get state of hardware lock
250 bool hardwareLocked = tryLock(mHardwareLock);
251 if (!hardwareLocked) {
252 String8 result(kHardwareLockedString);
253 write(fd, result.string(), result.size());
254 } else {
255 mHardwareLock.unlock();
256 }
257
258 bool locked = tryLock(mLock);
259
260 // failed to lock - AudioFlinger is probably deadlocked
261 if (!locked) {
262 String8 result(kDeadlockedString);
263 write(fd, result.string(), result.size());
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700264 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700265
266 dumpClients(fd, args);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700267 dumpInternals(fd, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800268
Eric Laurenta553c252009-07-17 12:17:14 -0700269 // dump playback threads
270 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700271 mPlaybackThreads.valueAt(i)->dump(fd, args);
Eric Laurenta553c252009-07-17 12:17:14 -0700272 }
273
274 // dump record threads
Eric Laurent102313a2009-07-23 13:35:01 -0700275 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700276 mRecordThreads.valueAt(i)->dump(fd, args);
Eric Laurenta553c252009-07-17 12:17:14 -0700277 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800278
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700279 if (mAudioHardware) {
280 mAudioHardware->dumpState(fd, args);
281 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700282 if (locked) mLock.unlock();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700283 }
284 return NO_ERROR;
285}
286
Eric Laurenta553c252009-07-17 12:17:14 -0700287
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700288// IAudioFlinger interface
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800289
290
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700291sp<IAudioTrack> AudioFlinger::createTrack(
292 pid_t pid,
293 int streamType,
294 uint32_t sampleRate,
295 int format,
296 int channelCount,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800297 int frameCount,
298 uint32_t flags,
299 const sp<IMemory>& sharedBuffer,
Eric Laurentddb78e72009-07-28 08:44:33 -0700300 int output,
Eric Laurent65b65452010-06-01 23:49:17 -0700301 int *sessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800302 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700303{
Eric Laurenta553c252009-07-17 12:17:14 -0700304 sp<PlaybackThread::Track> track;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700305 sp<TrackHandle> trackHandle;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700306 sp<Client> client;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800307 wp<Client> wclient;
308 status_t lStatus;
Eric Laurent65b65452010-06-01 23:49:17 -0700309 int lSessionId;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700310
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800311 if (streamType >= AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800312 LOGE("invalid stream type");
313 lStatus = BAD_VALUE;
314 goto Exit;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700315 }
316
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800317 {
318 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700319 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent493941b2010-07-28 01:32:47 -0700320 PlaybackThread *effectThread = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -0700321 if (thread == NULL) {
322 LOGE("unknown output thread");
323 lStatus = BAD_VALUE;
324 goto Exit;
325 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800326
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800327 wclient = mClients.valueFor(pid);
328
329 if (wclient != NULL) {
330 client = wclient.promote();
331 } else {
332 client = new Client(this, pid);
333 mClients.add(pid, client);
334 }
Eric Laurent65b65452010-06-01 23:49:17 -0700335
Eric Laurent65b65452010-06-01 23:49:17 -0700336 LOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700337 if (sessionId != NULL && *sessionId != AudioSystem::SESSION_OUTPUT_MIX) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700338 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent493941b2010-07-28 01:32:47 -0700339 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
340 if (mPlaybackThreads.keyAt(i) != output) {
341 // prevent same audio session on different output threads
342 uint32_t sessions = t->hasAudioSession(*sessionId);
343 if (sessions & PlaybackThread::TRACK_SESSION) {
344 lStatus = BAD_VALUE;
345 goto Exit;
346 }
347 // check if an effect with same session ID is waiting for a track to be created
348 if (sessions & PlaybackThread::EFFECT_SESSION) {
349 effectThread = t.get();
350 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700351 }
352 }
Eric Laurent65b65452010-06-01 23:49:17 -0700353 lSessionId = *sessionId;
354 } else {
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700355 // if no audio session id is provided, create one here
Eric Laurentf3d6dd02010-11-18 08:40:16 -0800356 lSessionId = nextUniqueId_l();
Eric Laurent65b65452010-06-01 23:49:17 -0700357 if (sessionId != NULL) {
358 *sessionId = lSessionId;
359 }
360 }
361 LOGV("createTrack() lSessionId: %d", lSessionId);
362
Eric Laurenta553c252009-07-17 12:17:14 -0700363 track = thread->createTrack_l(client, streamType, sampleRate, format,
Eric Laurent65b65452010-06-01 23:49:17 -0700364 channelCount, frameCount, sharedBuffer, lSessionId, &lStatus);
Eric Laurent493941b2010-07-28 01:32:47 -0700365
366 // move effect chain to this output thread if an effect on same session was waiting
367 // for a track to be created
368 if (lStatus == NO_ERROR && effectThread != NULL) {
369 Mutex::Autolock _dl(thread->mLock);
370 Mutex::Autolock _sl(effectThread->mLock);
371 moveEffectChain_l(lSessionId, effectThread, thread, true);
372 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700373 }
374 if (lStatus == NO_ERROR) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800375 trackHandle = new TrackHandle(track);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700376 } else {
Eric Laurentb9481d82009-09-17 05:12:56 -0700377 // remove local strong reference to Client before deleting the Track so that the Client
378 // destructor is called by the TrackBase destructor with mLock held
379 client.clear();
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700380 track.clear();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800381 }
382
383Exit:
384 if(status) {
385 *status = lStatus;
386 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700387 return trackHandle;
388}
389
Eric Laurentddb78e72009-07-28 08:44:33 -0700390uint32_t AudioFlinger::sampleRate(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700391{
Eric Laurenta553c252009-07-17 12:17:14 -0700392 Mutex::Autolock _l(mLock);
393 PlaybackThread *thread = checkPlaybackThread_l(output);
394 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700395 LOGW("sampleRate() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700396 return 0;
397 }
398 return thread->sampleRate();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700399}
400
Eric Laurentddb78e72009-07-28 08:44:33 -0700401int AudioFlinger::channelCount(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700402{
Eric Laurenta553c252009-07-17 12:17:14 -0700403 Mutex::Autolock _l(mLock);
404 PlaybackThread *thread = checkPlaybackThread_l(output);
405 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700406 LOGW("channelCount() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700407 return 0;
408 }
409 return thread->channelCount();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700410}
411
Eric Laurentddb78e72009-07-28 08:44:33 -0700412int AudioFlinger::format(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700413{
Eric Laurenta553c252009-07-17 12:17:14 -0700414 Mutex::Autolock _l(mLock);
415 PlaybackThread *thread = checkPlaybackThread_l(output);
416 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700417 LOGW("format() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700418 return 0;
419 }
420 return thread->format();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700421}
422
Eric Laurentddb78e72009-07-28 08:44:33 -0700423size_t AudioFlinger::frameCount(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700424{
Eric Laurenta553c252009-07-17 12:17:14 -0700425 Mutex::Autolock _l(mLock);
426 PlaybackThread *thread = checkPlaybackThread_l(output);
427 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700428 LOGW("frameCount() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700429 return 0;
430 }
431 return thread->frameCount();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700432}
433
Eric Laurentddb78e72009-07-28 08:44:33 -0700434uint32_t AudioFlinger::latency(int output) const
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800435{
Eric Laurenta553c252009-07-17 12:17:14 -0700436 Mutex::Autolock _l(mLock);
437 PlaybackThread *thread = checkPlaybackThread_l(output);
438 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700439 LOGW("latency() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700440 return 0;
441 }
442 return thread->latency();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800443}
444
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700445status_t AudioFlinger::setMasterVolume(float value)
446{
447 // check calling permissions
448 if (!settingsAllowed()) {
449 return PERMISSION_DENIED;
450 }
451
452 // when hw supports master volume, don't scale in sw mixer
Eric Laurent01635942011-01-18 18:39:02 -0800453 { // scope for the lock
454 AutoMutex lock(mHardwareLock);
455 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
456 if (mAudioHardware->setMasterVolume(value) == NO_ERROR) {
457 value = 1.0f;
458 }
459 mHardwareStatus = AUDIO_HW_IDLE;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700460 }
Eric Laurenta553c252009-07-17 12:17:14 -0700461
Eric Laurent01635942011-01-18 18:39:02 -0800462 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700463 mMasterVolume = value;
464 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700465 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700466
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700467 return NO_ERROR;
468}
469
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700470status_t AudioFlinger::setMode(int mode)
471{
Eric Laurent53334cd2010-06-23 17:38:20 -0700472 status_t ret;
473
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700474 // check calling permissions
475 if (!settingsAllowed()) {
476 return PERMISSION_DENIED;
477 }
478 if ((mode < 0) || (mode >= AudioSystem::NUM_MODES)) {
479 LOGW("Illegal value: setMode(%d)", mode);
480 return BAD_VALUE;
481 }
482
Eric Laurent53334cd2010-06-23 17:38:20 -0700483 { // scope for the lock
484 AutoMutex lock(mHardwareLock);
485 mHardwareStatus = AUDIO_HW_SET_MODE;
486 ret = mAudioHardware->setMode(mode);
487 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten871c16c2010-03-05 12:18:01 -0800488 }
Eric Laurent53334cd2010-06-23 17:38:20 -0700489
490 if (NO_ERROR == ret) {
491 Mutex::Autolock _l(mLock);
492 mMode = mode;
493 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
494 mPlaybackThreads.valueAt(i)->setMode(mode);
Eric Laurent53334cd2010-06-23 17:38:20 -0700495 }
496
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700497 return ret;
498}
499
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700500status_t AudioFlinger::setMicMute(bool state)
501{
502 // check calling permissions
503 if (!settingsAllowed()) {
504 return PERMISSION_DENIED;
505 }
506
507 AutoMutex lock(mHardwareLock);
508 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
509 status_t ret = mAudioHardware->setMicMute(state);
510 mHardwareStatus = AUDIO_HW_IDLE;
511 return ret;
512}
513
514bool AudioFlinger::getMicMute() const
515{
516 bool state = AudioSystem::MODE_INVALID;
517 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
518 mAudioHardware->getMicMute(&state);
519 mHardwareStatus = AUDIO_HW_IDLE;
520 return state;
521}
522
523status_t AudioFlinger::setMasterMute(bool muted)
524{
525 // check calling permissions
526 if (!settingsAllowed()) {
527 return PERMISSION_DENIED;
528 }
Eric Laurenta553c252009-07-17 12:17:14 -0700529
Eric Laurent01635942011-01-18 18:39:02 -0800530 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700531 mMasterMute = muted;
532 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700533 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Eric Laurenta553c252009-07-17 12:17:14 -0700534
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700535 return NO_ERROR;
536}
537
538float AudioFlinger::masterVolume() const
539{
Eric Laurenta553c252009-07-17 12:17:14 -0700540 return mMasterVolume;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700541}
542
543bool AudioFlinger::masterMute() const
544{
Eric Laurenta553c252009-07-17 12:17:14 -0700545 return mMasterMute;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700546}
547
Eric Laurentddb78e72009-07-28 08:44:33 -0700548status_t AudioFlinger::setStreamVolume(int stream, float value, int output)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700549{
550 // check calling permissions
551 if (!settingsAllowed()) {
552 return PERMISSION_DENIED;
553 }
554
Eric Laurenta553c252009-07-17 12:17:14 -0700555 if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700556 return BAD_VALUE;
557 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800558
Eric Laurenta553c252009-07-17 12:17:14 -0700559 AutoMutex lock(mLock);
560 PlaybackThread *thread = NULL;
561 if (output) {
562 thread = checkPlaybackThread_l(output);
563 if (thread == NULL) {
564 return BAD_VALUE;
565 }
566 }
567
Eric Laurenta553c252009-07-17 12:17:14 -0700568 mStreamTypes[stream].volume = value;
569
570 if (thread == NULL) {
Eric Laurent415f3e22009-10-21 08:14:22 -0700571 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700572 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Eric Laurent415f3e22009-10-21 08:14:22 -0700573 }
Eric Laurenta553c252009-07-17 12:17:14 -0700574 } else {
575 thread->setStreamVolume(stream, value);
576 }
Eric Laurentef028272009-04-21 07:56:33 -0700577
Eric Laurent415f3e22009-10-21 08:14:22 -0700578 return NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700579}
580
581status_t AudioFlinger::setStreamMute(int stream, bool muted)
582{
583 // check calling permissions
584 if (!settingsAllowed()) {
585 return PERMISSION_DENIED;
586 }
587
Eric Laurenta553c252009-07-17 12:17:14 -0700588 if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES ||
Eric Laurenteeea9222009-03-26 01:57:59 -0700589 uint32_t(stream) == AudioSystem::ENFORCED_AUDIBLE) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700590 return BAD_VALUE;
591 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700592
Eric Laurent01635942011-01-18 18:39:02 -0800593 AutoMutex lock(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700594 mStreamTypes[stream].mute = muted;
595 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700596 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800597
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700598 return NO_ERROR;
599}
600
Eric Laurentddb78e72009-07-28 08:44:33 -0700601float AudioFlinger::streamVolume(int stream, int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700602{
Eric Laurenta553c252009-07-17 12:17:14 -0700603 if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700604 return 0.0f;
605 }
Eric Laurenta553c252009-07-17 12:17:14 -0700606
607 AutoMutex lock(mLock);
608 float volume;
609 if (output) {
610 PlaybackThread *thread = checkPlaybackThread_l(output);
611 if (thread == NULL) {
612 return 0.0f;
613 }
614 volume = thread->streamVolume(stream);
615 } else {
616 volume = mStreamTypes[stream].volume;
617 }
618
Eric Laurentef028272009-04-21 07:56:33 -0700619 return volume;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700620}
621
622bool AudioFlinger::streamMute(int stream) const
623{
Eric Laurenta553c252009-07-17 12:17:14 -0700624 if (stream < 0 || stream >= (int)AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700625 return true;
626 }
Eric Laurenta553c252009-07-17 12:17:14 -0700627
628 return mStreamTypes[stream].mute;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700629}
630
Eric Laurentddb78e72009-07-28 08:44:33 -0700631status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700632{
Eric Laurenta553c252009-07-17 12:17:14 -0700633 status_t result;
634
Eric Laurentddb78e72009-07-28 08:44:33 -0700635 LOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
Eric Laurenta553c252009-07-17 12:17:14 -0700636 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
637 // check calling permissions
638 if (!settingsAllowed()) {
639 return PERMISSION_DENIED;
The Android Open Source Project9266c552009-01-15 16:12:10 -0800640 }
Eric Laurenta553c252009-07-17 12:17:14 -0700641
642 // ioHandle == 0 means the parameters are global to the audio hardware interface
643 if (ioHandle == 0) {
644 AutoMutex lock(mHardwareLock);
645 mHardwareStatus = AUDIO_SET_PARAMETER;
646 result = mAudioHardware->setParameters(keyValuePairs);
647 mHardwareStatus = AUDIO_HW_IDLE;
648 return result;
649 }
650
Eric Laurentb7d94602009-09-29 11:12:57 -0700651 // hold a strong ref on thread in case closeOutput() or closeInput() is called
652 // and the thread is exited once the lock is released
653 sp<ThreadBase> thread;
654 {
655 Mutex::Autolock _l(mLock);
656 thread = checkPlaybackThread_l(ioHandle);
657 if (thread == NULL) {
658 thread = checkRecordThread_l(ioHandle);
659 }
Eric Laurenta553c252009-07-17 12:17:14 -0700660 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700661 if (thread != NULL) {
Glenn Kasten871c16c2010-03-05 12:18:01 -0800662 result = thread->setParameters(keyValuePairs);
Glenn Kasten871c16c2010-03-05 12:18:01 -0800663 return result;
Eric Laurenta553c252009-07-17 12:17:14 -0700664 }
Eric Laurenta553c252009-07-17 12:17:14 -0700665 return BAD_VALUE;
666}
667
Eric Laurentddb78e72009-07-28 08:44:33 -0700668String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
Eric Laurenta553c252009-07-17 12:17:14 -0700669{
Eric Laurentddb78e72009-07-28 08:44:33 -0700670// LOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
Eric Laurenta553c252009-07-17 12:17:14 -0700671// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
672
673 if (ioHandle == 0) {
674 return mAudioHardware->getParameters(keys);
675 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700676
677 Mutex::Autolock _l(mLock);
678
Eric Laurenta553c252009-07-17 12:17:14 -0700679 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
680 if (playbackThread != NULL) {
681 return playbackThread->getParameters(keys);
682 }
683 RecordThread *recordThread = checkRecordThread_l(ioHandle);
684 if (recordThread != NULL) {
685 return recordThread->getParameters(keys);
686 }
687 return String8("");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700688}
689
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800690size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
691{
692 return mAudioHardware->getInputBufferSize(sampleRate, format, channelCount);
693}
694
Eric Laurent47d0a922010-02-26 02:47:27 -0800695unsigned int AudioFlinger::getInputFramesLost(int ioHandle)
696{
697 if (ioHandle == 0) {
698 return 0;
699 }
700
701 Mutex::Autolock _l(mLock);
702
703 RecordThread *recordThread = checkRecordThread_l(ioHandle);
704 if (recordThread != NULL) {
705 return recordThread->getInputFramesLost();
706 }
707 return 0;
708}
709
Eric Laurent415f3e22009-10-21 08:14:22 -0700710status_t AudioFlinger::setVoiceVolume(float value)
711{
712 // check calling permissions
713 if (!settingsAllowed()) {
714 return PERMISSION_DENIED;
715 }
716
717 AutoMutex lock(mHardwareLock);
718 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
719 status_t ret = mAudioHardware->setVoiceVolume(value);
720 mHardwareStatus = AUDIO_HW_IDLE;
721
722 return ret;
723}
724
Eric Laurent0986e792010-01-19 17:37:09 -0800725status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int output)
726{
727 status_t status;
728
729 Mutex::Autolock _l(mLock);
730
731 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
732 if (playbackThread != NULL) {
733 return playbackThread->getRenderPosition(halFrames, dspFrames);
734 }
735
736 return BAD_VALUE;
737}
738
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800739void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
740{
Eric Laurenta553c252009-07-17 12:17:14 -0700741
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800742 Mutex::Autolock _l(mLock);
743
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700744 int pid = IPCThreadState::self()->getCallingPid();
745 if (mNotificationClients.indexOfKey(pid) < 0) {
746 sp<NotificationClient> notificationClient = new NotificationClient(this,
747 client,
748 pid);
749 LOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Eric Laurenta553c252009-07-17 12:17:14 -0700750
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700751 mNotificationClients.add(pid, notificationClient);
Eric Laurenta553c252009-07-17 12:17:14 -0700752
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700753 sp<IBinder> binder = client->asBinder();
754 binder->linkToDeath(notificationClient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800755
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700756 // the config change is always sent from playback or record threads to avoid deadlock
757 // with AudioSystem::gLock
758 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
759 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
760 }
Eric Laurenta553c252009-07-17 12:17:14 -0700761
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700762 for (size_t i = 0; i < mRecordThreads.size(); i++) {
763 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800764 }
765 }
766}
767
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700768void AudioFlinger::removeNotificationClient(pid_t pid)
769{
770 Mutex::Autolock _l(mLock);
771
772 int index = mNotificationClients.indexOfKey(pid);
773 if (index >= 0) {
774 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
775 LOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700776 mNotificationClients.removeItem(pid);
777 }
778}
779
Eric Laurent296a0ec2009-09-15 07:10:12 -0700780// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700781void AudioFlinger::audioConfigChanged_l(int event, int ioHandle, void *param2)
782{
Eric Laurent49f02be2009-11-19 09:00:56 -0800783 size_t size = mNotificationClients.size();
784 for (size_t i = 0; i < size; i++) {
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700785 mNotificationClients.valueAt(i)->client()->ioConfigChanged(event, ioHandle, param2);
Eric Laurenta553c252009-07-17 12:17:14 -0700786 }
787}
788
Eric Laurentb9481d82009-09-17 05:12:56 -0700789// removeClient_l() must be called with AudioFlinger::mLock held
790void AudioFlinger::removeClient_l(pid_t pid)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700791{
Eric Laurentb9481d82009-09-17 05:12:56 -0700792 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 -0700793 mClients.removeItem(pid);
794}
795
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700796
Eric Laurenta553c252009-07-17 12:17:14 -0700797// ----------------------------------------------------------------------------
798
Eric Laurent49f02be2009-11-19 09:00:56 -0800799AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, int id)
Eric Laurenta553c252009-07-17 12:17:14 -0700800 : Thread(false),
801 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
Eric Laurentb0a01472010-05-14 05:45:46 -0700802 mFrameSize(1), mFormat(0), mStandby(false), mId(id), mExiting(false)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700803{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800804}
805
Eric Laurenta553c252009-07-17 12:17:14 -0700806AudioFlinger::ThreadBase::~ThreadBase()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800807{
Eric Laurent8fce46a2009-08-04 09:45:33 -0700808 mParamCond.broadcast();
809 mNewParameters.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800810}
811
Eric Laurenta553c252009-07-17 12:17:14 -0700812void AudioFlinger::ThreadBase::exit()
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700813{
Eric Laurentb7d94602009-09-29 11:12:57 -0700814 // keep a strong ref on ourself so that we wont get
Eric Laurenta553c252009-07-17 12:17:14 -0700815 // destroyed in the middle of requestExitAndWait()
816 sp <ThreadBase> strongMe = this;
817
818 LOGV("ThreadBase::exit");
819 {
820 AutoMutex lock(&mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -0800821 mExiting = true;
Eric Laurenta553c252009-07-17 12:17:14 -0700822 requestExit();
823 mWaitWorkCV.signal();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700824 }
Eric Laurenta553c252009-07-17 12:17:14 -0700825 requestExitAndWait();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700826}
Eric Laurenta553c252009-07-17 12:17:14 -0700827
828uint32_t AudioFlinger::ThreadBase::sampleRate() const
829{
830 return mSampleRate;
831}
832
833int AudioFlinger::ThreadBase::channelCount() const
834{
Eric Laurentb0a01472010-05-14 05:45:46 -0700835 return (int)mChannelCount;
Eric Laurenta553c252009-07-17 12:17:14 -0700836}
837
838int AudioFlinger::ThreadBase::format() const
839{
840 return mFormat;
841}
842
843size_t AudioFlinger::ThreadBase::frameCount() const
844{
845 return mFrameCount;
846}
847
848status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
849{
Eric Laurent8fce46a2009-08-04 09:45:33 -0700850 status_t status;
Eric Laurenta553c252009-07-17 12:17:14 -0700851
Eric Laurent8fce46a2009-08-04 09:45:33 -0700852 LOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Eric Laurenta553c252009-07-17 12:17:14 -0700853 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700854
Eric Laurent8fce46a2009-08-04 09:45:33 -0700855 mNewParameters.add(keyValuePairs);
Eric Laurenta553c252009-07-17 12:17:14 -0700856 mWaitWorkCV.signal();
Eric Laurentb7d94602009-09-29 11:12:57 -0700857 // wait condition with timeout in case the thread loop has exited
858 // before the request could be processed
859 if (mParamCond.waitRelative(mLock, seconds(2)) == NO_ERROR) {
860 status = mParamStatus;
861 mWaitWorkCV.signal();
862 } else {
863 status = TIMED_OUT;
864 }
Eric Laurent8fce46a2009-08-04 09:45:33 -0700865 return status;
Eric Laurenta553c252009-07-17 12:17:14 -0700866}
867
868void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
869{
870 Mutex::Autolock _l(mLock);
Eric Laurent8fce46a2009-08-04 09:45:33 -0700871 sendConfigEvent_l(event, param);
872}
873
874// sendConfigEvent_l() must be called with ThreadBase::mLock held
875void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
876{
Eric Laurenta553c252009-07-17 12:17:14 -0700877 ConfigEvent *configEvent = new ConfigEvent();
878 configEvent->mEvent = event;
879 configEvent->mParam = param;
880 mConfigEvents.add(configEvent);
881 LOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
882 mWaitWorkCV.signal();
883}
884
885void AudioFlinger::ThreadBase::processConfigEvents()
886{
887 mLock.lock();
888 while(!mConfigEvents.isEmpty()) {
889 LOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
890 ConfigEvent *configEvent = mConfigEvents[0];
891 mConfigEvents.removeAt(0);
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700892 // release mLock before locking AudioFlinger mLock: lock order is always
893 // AudioFlinger then ThreadBase to avoid cross deadlock
Eric Laurenta553c252009-07-17 12:17:14 -0700894 mLock.unlock();
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700895 mAudioFlinger->mLock.lock();
896 audioConfigChanged_l(configEvent->mEvent, configEvent->mParam);
897 mAudioFlinger->mLock.unlock();
Eric Laurenta553c252009-07-17 12:17:14 -0700898 delete configEvent;
899 mLock.lock();
900 }
901 mLock.unlock();
902}
903
Eric Laurent3fdb1262009-11-07 00:01:32 -0800904status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
905{
906 const size_t SIZE = 256;
907 char buffer[SIZE];
908 String8 result;
909
910 bool locked = tryLock(mLock);
911 if (!locked) {
912 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
913 write(fd, buffer, strlen(buffer));
914 }
915
916 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
917 result.append(buffer);
918 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
919 result.append(buffer);
920 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
921 result.append(buffer);
922 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
923 result.append(buffer);
924 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
925 result.append(buffer);
926 snprintf(buffer, SIZE, "Frame size: %d\n", mFrameSize);
927 result.append(buffer);
928
929 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
930 result.append(buffer);
931 result.append(" Index Command");
932 for (size_t i = 0; i < mNewParameters.size(); ++i) {
933 snprintf(buffer, SIZE, "\n %02d ", i);
934 result.append(buffer);
935 result.append(mNewParameters[i]);
936 }
937
938 snprintf(buffer, SIZE, "\n\nPending config events: \n");
939 result.append(buffer);
940 snprintf(buffer, SIZE, " Index event param\n");
941 result.append(buffer);
942 for (size_t i = 0; i < mConfigEvents.size(); i++) {
943 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i]->mEvent, mConfigEvents[i]->mParam);
944 result.append(buffer);
945 }
946 result.append("\n");
947
948 write(fd, result.string(), result.size());
949
950 if (locked) {
951 mLock.unlock();
952 }
953 return NO_ERROR;
954}
955
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800956
957// ----------------------------------------------------------------------------
958
Eric Laurent65b65452010-06-01 23:49:17 -0700959AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Eric Laurent49f02be2009-11-19 09:00:56 -0800960 : ThreadBase(audioFlinger, id),
Eric Laurentd5603c12009-08-06 08:49:39 -0700961 mMixBuffer(0), mSuspended(0), mBytesWritten(0), mOutput(output),
Eric Laurent65b65452010-06-01 23:49:17 -0700962 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
963 mDevice(device)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800964{
Eric Laurenta553c252009-07-17 12:17:14 -0700965 readOutputParameters();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800966
Eric Laurenta553c252009-07-17 12:17:14 -0700967 mMasterVolume = mAudioFlinger->masterVolume();
968 mMasterMute = mAudioFlinger->masterMute();
969
970 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
971 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
972 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800973 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800974}
975
Eric Laurenta553c252009-07-17 12:17:14 -0700976AudioFlinger::PlaybackThread::~PlaybackThread()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800977{
978 delete [] mMixBuffer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800979}
980
Eric Laurenta553c252009-07-17 12:17:14 -0700981status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800982{
983 dumpInternals(fd, args);
984 dumpTracks(fd, args);
Eric Laurent65b65452010-06-01 23:49:17 -0700985 dumpEffectChains(fd, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800986 return NO_ERROR;
987}
988
Eric Laurenta553c252009-07-17 12:17:14 -0700989status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800990{
991 const size_t SIZE = 256;
992 char buffer[SIZE];
993 String8 result;
994
Eric Laurenta553c252009-07-17 12:17:14 -0700995 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800996 result.append(buffer);
Eric Laurent65b65452010-06-01 23:49:17 -0700997 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 -0800998 for (size_t i = 0; i < mTracks.size(); ++i) {
Eric Laurentd3b4d0c2009-03-31 14:34:35 -0700999 sp<Track> track = mTracks[i];
1000 if (track != 0) {
1001 track->dump(buffer, SIZE);
1002 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001003 }
1004 }
1005
Eric Laurenta553c252009-07-17 12:17:14 -07001006 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001007 result.append(buffer);
Eric Laurent65b65452010-06-01 23:49:17 -07001008 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 -08001009 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Eric Laurentd3b4d0c2009-03-31 14:34:35 -07001010 wp<Track> wTrack = mActiveTracks[i];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001011 if (wTrack != 0) {
1012 sp<Track> track = wTrack.promote();
1013 if (track != 0) {
1014 track->dump(buffer, SIZE);
1015 result.append(buffer);
1016 }
1017 }
1018 }
1019 write(fd, result.string(), result.size());
1020 return NO_ERROR;
1021}
1022
Eric Laurent65b65452010-06-01 23:49:17 -07001023status_t AudioFlinger::PlaybackThread::dumpEffectChains(int fd, const Vector<String16>& args)
1024{
1025 const size_t SIZE = 256;
1026 char buffer[SIZE];
1027 String8 result;
1028
1029 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1030 write(fd, buffer, strlen(buffer));
1031
1032 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1033 sp<EffectChain> chain = mEffectChains[i];
1034 if (chain != 0) {
1035 chain->dump(fd, args);
1036 }
1037 }
1038 return NO_ERROR;
1039}
1040
Eric Laurenta553c252009-07-17 12:17:14 -07001041status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001042{
1043 const size_t SIZE = 256;
1044 char buffer[SIZE];
1045 String8 result;
1046
Eric Laurent3fdb1262009-11-07 00:01:32 -08001047 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001048 result.append(buffer);
1049 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1050 result.append(buffer);
1051 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1052 result.append(buffer);
1053 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1054 result.append(buffer);
1055 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1056 result.append(buffer);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08001057 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1058 result.append(buffer);
Eric Laurent65b65452010-06-01 23:49:17 -07001059 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1060 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001061 write(fd, result.string(), result.size());
Eric Laurent3fdb1262009-11-07 00:01:32 -08001062
1063 dumpBase(fd, args);
1064
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001065 return NO_ERROR;
1066}
1067
1068// Thread virtuals
Eric Laurenta553c252009-07-17 12:17:14 -07001069status_t AudioFlinger::PlaybackThread::readyToRun()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001070{
1071 if (mSampleRate == 0) {
1072 LOGE("No working audio driver found.");
1073 return NO_INIT;
1074 }
Eric Laurenta553c252009-07-17 12:17:14 -07001075 LOGI("AudioFlinger's thread %p ready to run", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001076 return NO_ERROR;
1077}
1078
Eric Laurenta553c252009-07-17 12:17:14 -07001079void AudioFlinger::PlaybackThread::onFirstRef()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001080{
1081 const size_t SIZE = 256;
1082 char buffer[SIZE];
1083
Eric Laurenta553c252009-07-17 12:17:14 -07001084 snprintf(buffer, SIZE, "Playback Thread %p", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001085
1086 run(buffer, ANDROID_PRIORITY_URGENT_AUDIO);
1087}
1088
Eric Laurenta553c252009-07-17 12:17:14 -07001089// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1090sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001091 const sp<AudioFlinger::Client>& client,
1092 int streamType,
1093 uint32_t sampleRate,
1094 int format,
1095 int channelCount,
1096 int frameCount,
1097 const sp<IMemory>& sharedBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -07001098 int sessionId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001099 status_t *status)
1100{
1101 sp<Track> track;
1102 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07001103
1104 if (mType == DIRECT) {
Eric Laurentb0a01472010-05-14 05:45:46 -07001105 if (sampleRate != mSampleRate || format != mFormat || channelCount != (int)mChannelCount) {
Eric Laurenta553c252009-07-17 12:17:14 -07001106 LOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelCount %d for output %p",
1107 sampleRate, format, channelCount, mOutput);
1108 lStatus = BAD_VALUE;
1109 goto Exit;
1110 }
1111 } else {
1112 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1113 if (sampleRate > mSampleRate*2) {
1114 LOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
1115 lStatus = BAD_VALUE;
1116 goto Exit;
1117 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001118 }
1119
Eric Laurenta553c252009-07-17 12:17:14 -07001120 if (mOutput == 0) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001121 LOGE("Audio driver not initialized.");
1122 lStatus = NO_INIT;
1123 goto Exit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001124 }
1125
Eric Laurenta553c252009-07-17 12:17:14 -07001126 { // scope for mLock
1127 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001128
1129 // all tracks in same audio session must share the same routing strategy otherwise
1130 // conflicts will happen when tracks are moved from one output to another by audio policy
1131 // manager
1132 uint32_t strategy =
1133 AudioSystem::getStrategyForStream((AudioSystem::stream_type)streamType);
1134 for (size_t i = 0; i < mTracks.size(); ++i) {
1135 sp<Track> t = mTracks[i];
1136 if (t != 0) {
1137 if (sessionId == t->sessionId() &&
1138 strategy != AudioSystem::getStrategyForStream((AudioSystem::stream_type)t->type())) {
1139 lStatus = BAD_VALUE;
1140 goto Exit;
1141 }
1142 }
1143 }
1144
Eric Laurenta553c252009-07-17 12:17:14 -07001145 track = new Track(this, client, streamType, sampleRate, format,
Eric Laurent65b65452010-06-01 23:49:17 -07001146 channelCount, frameCount, sharedBuffer, sessionId);
Eric Laurent73b60352009-11-09 04:45:39 -08001147 if (track->getCblk() == NULL || track->name() < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07001148 lStatus = NO_MEMORY;
1149 goto Exit;
1150 }
1151 mTracks.add(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001152
1153 sp<EffectChain> chain = getEffectChain_l(sessionId);
1154 if (chain != 0) {
1155 LOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1156 track->setMainBuffer(chain->inBuffer());
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001157 chain->setStrategy(AudioSystem::getStrategyForStream((AudioSystem::stream_type)track->type()));
Eric Laurent65b65452010-06-01 23:49:17 -07001158 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001159 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001160 lStatus = NO_ERROR;
1161
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001162Exit:
1163 if(status) {
1164 *status = lStatus;
1165 }
1166 return track;
1167}
1168
Eric Laurenta553c252009-07-17 12:17:14 -07001169uint32_t AudioFlinger::PlaybackThread::latency() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001170{
1171 if (mOutput) {
1172 return mOutput->latency();
1173 }
1174 else {
1175 return 0;
1176 }
1177}
1178
Eric Laurenta553c252009-07-17 12:17:14 -07001179status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001180{
1181 mMasterVolume = value;
1182 return NO_ERROR;
1183}
1184
Eric Laurenta553c252009-07-17 12:17:14 -07001185status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001186{
1187 mMasterMute = muted;
1188 return NO_ERROR;
1189}
1190
Eric Laurenta553c252009-07-17 12:17:14 -07001191float AudioFlinger::PlaybackThread::masterVolume() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001192{
1193 return mMasterVolume;
1194}
1195
Eric Laurenta553c252009-07-17 12:17:14 -07001196bool AudioFlinger::PlaybackThread::masterMute() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001197{
1198 return mMasterMute;
1199}
1200
Eric Laurenta553c252009-07-17 12:17:14 -07001201status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001202{
1203 mStreamTypes[stream].volume = value;
1204 return NO_ERROR;
1205}
1206
Eric Laurenta553c252009-07-17 12:17:14 -07001207status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001208{
1209 mStreamTypes[stream].mute = muted;
1210 return NO_ERROR;
1211}
1212
Eric Laurenta553c252009-07-17 12:17:14 -07001213float AudioFlinger::PlaybackThread::streamVolume(int stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001214{
1215 return mStreamTypes[stream].volume;
1216}
1217
Eric Laurenta553c252009-07-17 12:17:14 -07001218bool AudioFlinger::PlaybackThread::streamMute(int stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001219{
1220 return mStreamTypes[stream].mute;
1221}
1222
Eric Laurenta553c252009-07-17 12:17:14 -07001223// addTrack_l() must be called with ThreadBase::mLock held
1224status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001225{
1226 status_t status = ALREADY_EXISTS;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001227
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001228 // set retry count for buffer fill
1229 track->mRetryCount = kMaxTrackStartupRetries;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001230 if (mActiveTracks.indexOf(track) < 0) {
1231 // the track is newly added, make sure it fills up all its
1232 // buffers before playing. This is to ensure the client will
1233 // effectively get the latency it requested.
1234 track->mFillingUpStatus = Track::FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001235 track->mResetDone = false;
Eric Laurenta553c252009-07-17 12:17:14 -07001236 mActiveTracks.add(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001237 if (track->mainBuffer() != mMixBuffer) {
1238 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1239 if (chain != 0) {
1240 LOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
1241 chain->startTrack();
1242 }
1243 }
1244
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001245 status = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001246 }
Eric Laurenta553c252009-07-17 12:17:14 -07001247
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001248 LOGV("mWaitWorkCV.broadcast");
Eric Laurenta553c252009-07-17 12:17:14 -07001249 mWaitWorkCV.broadcast();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001250
1251 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001252}
1253
Eric Laurenta553c252009-07-17 12:17:14 -07001254// destroyTrack_l() must be called with ThreadBase::mLock held
1255void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001256{
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001257 track->mState = TrackBase::TERMINATED;
1258 if (mActiveTracks.indexOf(track) < 0) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001259 mTracks.remove(track);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001260 deleteTrackName_l(track->name());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001261 }
1262}
1263
Eric Laurenta553c252009-07-17 12:17:14 -07001264String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001265{
Eric Laurenta553c252009-07-17 12:17:14 -07001266 return mOutput->getParameters(keys);
1267}
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001268
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001269// destroyTrack_l() must be called with AudioFlinger::mLock held
1270void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
Eric Laurenta553c252009-07-17 12:17:14 -07001271 AudioSystem::OutputDescriptor desc;
1272 void *param2 = 0;
1273
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001274 LOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Eric Laurenta553c252009-07-17 12:17:14 -07001275
1276 switch (event) {
1277 case AudioSystem::OUTPUT_OPENED:
1278 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Eric Laurentb0a01472010-05-14 05:45:46 -07001279 desc.channels = mChannels;
Eric Laurenta553c252009-07-17 12:17:14 -07001280 desc.samplingRate = mSampleRate;
1281 desc.format = mFormat;
1282 desc.frameCount = mFrameCount;
1283 desc.latency = latency();
1284 param2 = &desc;
1285 break;
1286
1287 case AudioSystem::STREAM_CONFIG_CHANGED:
1288 param2 = &param;
1289 case AudioSystem::OUTPUT_CLOSED:
1290 default:
1291 break;
1292 }
Eric Laurent49f02be2009-11-19 09:00:56 -08001293 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurenta553c252009-07-17 12:17:14 -07001294}
1295
1296void AudioFlinger::PlaybackThread::readOutputParameters()
1297{
1298 mSampleRate = mOutput->sampleRate();
Eric Laurentb0a01472010-05-14 05:45:46 -07001299 mChannels = mOutput->channels();
1300 mChannelCount = (uint16_t)AudioSystem::popCount(mChannels);
Eric Laurenta553c252009-07-17 12:17:14 -07001301 mFormat = mOutput->format();
Eric Laurentb0a01472010-05-14 05:45:46 -07001302 mFrameSize = (uint16_t)mOutput->frameSize();
Eric Laurenta553c252009-07-17 12:17:14 -07001303 mFrameCount = mOutput->bufferSize() / mFrameSize;
1304
Eric Laurenta553c252009-07-17 12:17:14 -07001305 // FIXME - Current mixer implementation only supports stereo output: Always
1306 // Allocate a stereo buffer even if HW output is mono.
Eric Laurent65b65452010-06-01 23:49:17 -07001307 if (mMixBuffer != NULL) delete[] mMixBuffer;
Eric Laurenta553c252009-07-17 12:17:14 -07001308 mMixBuffer = new int16_t[mFrameCount * 2];
1309 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
Eric Laurent65b65452010-06-01 23:49:17 -07001310
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001311 // force reconfiguration of effect chains and engines to take new buffer size and audio
1312 // parameters into account
1313 // Note that mLock is not held when readOutputParameters() is called from the constructor
1314 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1315 // matter.
1316 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1317 Vector< sp<EffectChain> > effectChains = mEffectChains;
1318 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent493941b2010-07-28 01:32:47 -07001319 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001320 }
Eric Laurenta553c252009-07-17 12:17:14 -07001321}
1322
Eric Laurent0986e792010-01-19 17:37:09 -08001323status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1324{
1325 if (halFrames == 0 || dspFrames == 0) {
1326 return BAD_VALUE;
1327 }
1328 if (mOutput == 0) {
1329 return INVALID_OPERATION;
1330 }
1331 *halFrames = mBytesWritten/mOutput->frameSize();
1332
1333 return mOutput->getRenderPosition(dspFrames);
1334}
1335
Eric Laurent493941b2010-07-28 01:32:47 -07001336uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Eric Laurent65b65452010-06-01 23:49:17 -07001337{
1338 Mutex::Autolock _l(mLock);
Eric Laurent493941b2010-07-28 01:32:47 -07001339 uint32_t result = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07001340 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent493941b2010-07-28 01:32:47 -07001341 result = EFFECT_SESSION;
Eric Laurent65b65452010-06-01 23:49:17 -07001342 }
1343
1344 for (size_t i = 0; i < mTracks.size(); ++i) {
1345 sp<Track> track = mTracks[i];
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001346 if (sessionId == track->sessionId() &&
1347 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent493941b2010-07-28 01:32:47 -07001348 result |= TRACK_SESSION;
1349 break;
Eric Laurent65b65452010-06-01 23:49:17 -07001350 }
1351 }
1352
Eric Laurent493941b2010-07-28 01:32:47 -07001353 return result;
Eric Laurent65b65452010-06-01 23:49:17 -07001354}
1355
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001356uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1357{
1358 // session AudioSystem::SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
1359 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
1360 if (sessionId == AudioSystem::SESSION_OUTPUT_MIX) {
1361 return AudioSystem::getStrategyForStream(AudioSystem::MUSIC);
1362 }
1363 for (size_t i = 0; i < mTracks.size(); i++) {
1364 sp<Track> track = mTracks[i];
1365 if (sessionId == track->sessionId() &&
1366 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
1367 return AudioSystem::getStrategyForStream((AudioSystem::stream_type) track->type());
1368 }
1369 }
1370 return AudioSystem::getStrategyForStream(AudioSystem::MUSIC);
1371}
1372
Eric Laurent65b65452010-06-01 23:49:17 -07001373sp<AudioFlinger::EffectChain> AudioFlinger::PlaybackThread::getEffectChain(int sessionId)
1374{
1375 Mutex::Autolock _l(mLock);
1376 return getEffectChain_l(sessionId);
1377}
1378
1379sp<AudioFlinger::EffectChain> AudioFlinger::PlaybackThread::getEffectChain_l(int sessionId)
1380{
1381 sp<EffectChain> chain;
1382
1383 size_t size = mEffectChains.size();
1384 for (size_t i = 0; i < size; i++) {
1385 if (mEffectChains[i]->sessionId() == sessionId) {
1386 chain = mEffectChains[i];
1387 break;
1388 }
1389 }
1390 return chain;
1391}
1392
Eric Laurent53334cd2010-06-23 17:38:20 -07001393void AudioFlinger::PlaybackThread::setMode(uint32_t mode)
1394{
1395 Mutex::Autolock _l(mLock);
1396 size_t size = mEffectChains.size();
1397 for (size_t i = 0; i < size; i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07001398 mEffectChains[i]->setMode_l(mode);
Eric Laurent53334cd2010-06-23 17:38:20 -07001399 }
1400}
1401
Eric Laurenta553c252009-07-17 12:17:14 -07001402// ----------------------------------------------------------------------------
1403
Eric Laurent65b65452010-06-01 23:49:17 -07001404AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
1405 : PlaybackThread(audioFlinger, output, id, device),
Eric Laurenta553c252009-07-17 12:17:14 -07001406 mAudioMixer(0)
1407{
1408 mType = PlaybackThread::MIXER;
1409 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1410
1411 // FIXME - Current mixer implementation only supports stereo output
1412 if (mChannelCount == 1) {
1413 LOGE("Invalid audio hardware channel count");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001414 }
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001415}
1416
Eric Laurenta553c252009-07-17 12:17:14 -07001417AudioFlinger::MixerThread::~MixerThread()
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001418{
Eric Laurenta553c252009-07-17 12:17:14 -07001419 delete mAudioMixer;
1420}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001421
Eric Laurenta553c252009-07-17 12:17:14 -07001422bool AudioFlinger::MixerThread::threadLoop()
1423{
Eric Laurenta553c252009-07-17 12:17:14 -07001424 Vector< sp<Track> > tracksToRemove;
Eric Laurent059b4be2009-11-09 23:32:22 -08001425 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001426 nsecs_t standbyTime = systemTime();
1427 size_t mixBufferSize = mFrameCount * mFrameSize;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001428 // FIXME: Relaxed timing because of a certain device that can't meet latency
1429 // Should be reduced to 2x after the vendor fixes the driver issue
1430 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
1431 nsecs_t lastWarning = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08001432 bool longStandbyExit = false;
1433 uint32_t activeSleepTime = activeSleepTimeUs();
1434 uint32_t idleSleepTime = idleSleepTimeUs();
1435 uint32_t sleepTime = idleSleepTime;
Eric Laurent65b65452010-06-01 23:49:17 -07001436 Vector< sp<EffectChain> > effectChains;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001437
Eric Laurenta553c252009-07-17 12:17:14 -07001438 while (!exitPending())
1439 {
1440 processConfigEvents();
1441
Eric Laurent059b4be2009-11-09 23:32:22 -08001442 mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001443 { // scope for mLock
1444
1445 Mutex::Autolock _l(mLock);
1446
1447 if (checkForNewParameters_l()) {
1448 mixBufferSize = mFrameCount * mFrameSize;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001449 // FIXME: Relaxed timing because of a certain device that can't meet latency
1450 // Should be reduced to 2x after the vendor fixes the driver issue
1451 maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
Eric Laurent059b4be2009-11-09 23:32:22 -08001452 activeSleepTime = activeSleepTimeUs();
1453 idleSleepTime = idleSleepTimeUs();
Eric Laurenta553c252009-07-17 12:17:14 -07001454 }
1455
1456 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1457
1458 // put audio hardware into standby after short delay
1459 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1460 mSuspended) {
1461 if (!mStandby) {
1462 LOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
1463 mOutput->standby();
1464 mStandby = true;
1465 mBytesWritten = 0;
1466 }
1467
1468 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1469 // we're about to wait, flush the binder command buffer
1470 IPCThreadState::self()->flushCommands();
1471
1472 if (exitPending()) break;
1473
1474 // wait until we have something to do...
1475 LOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
1476 mWaitWorkCV.wait(mLock);
1477 LOGV("MixerThread %p TID %d waking up\n", this, gettid());
1478
1479 if (mMasterMute == false) {
1480 char value[PROPERTY_VALUE_MAX];
1481 property_get("ro.audio.silent", value, "0");
1482 if (atoi(value)) {
1483 LOGD("Silence is golden");
1484 setMasterMute(true);
1485 }
1486 }
1487
1488 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent059b4be2009-11-09 23:32:22 -08001489 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07001490 continue;
1491 }
1492 }
1493
Eric Laurent059b4be2009-11-09 23:32:22 -08001494 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07001495
1496 // prevent any changes in effect chain list and in each effect chain
1497 // during mixing and effect process as the audio buffers could be deleted
1498 // or modified if an effect is created or deleted
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001499 lockEffectChains_l(effectChains);
Eric Laurenta553c252009-07-17 12:17:14 -07001500 }
1501
Eric Laurent059b4be2009-11-09 23:32:22 -08001502 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07001503 // mix buffers...
Eric Laurent65b65452010-06-01 23:49:17 -07001504 mAudioMixer->process();
Eric Laurentf69a3f82009-09-22 00:35:48 -07001505 sleepTime = 0;
1506 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent65b65452010-06-01 23:49:17 -07001507 //TODO: delay standby when effects have a tail
Eric Laurent96c08a62009-09-07 08:38:38 -07001508 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07001509 // If no tracks are ready, sleep once for the duration of an output
1510 // buffer size, then write 0s to the output
1511 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08001512 if (mixerStatus == MIXER_TRACKS_ENABLED) {
1513 sleepTime = activeSleepTime;
1514 } else {
1515 sleepTime = idleSleepTime;
1516 }
1517 } else if (mBytesWritten != 0 ||
1518 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Eric Laurent65b65452010-06-01 23:49:17 -07001519 memset (mMixBuffer, 0, mixBufferSize);
Eric Laurent96c08a62009-09-07 08:38:38 -07001520 sleepTime = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08001521 LOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Eric Laurent96c08a62009-09-07 08:38:38 -07001522 }
Eric Laurent65b65452010-06-01 23:49:17 -07001523 // TODO add standby time extension fct of effect tail
Eric Laurentf69a3f82009-09-22 00:35:48 -07001524 }
1525
1526 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07001527 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07001528 }
1529 // sleepTime == 0 means we must write to audio hardware
1530 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07001531 for (size_t i = 0; i < effectChains.size(); i ++) {
1532 effectChains[i]->process_l();
1533 }
1534 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001535 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07001536 mLastWriteTime = systemTime();
1537 mInWrite = true;
1538 mBytesWritten += mixBufferSize;
1539
1540 int bytesWritten = (int)mOutput->write(mMixBuffer, mixBufferSize);
Eric Laurent0986e792010-01-19 17:37:09 -08001541 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07001542 mNumWrites++;
1543 mInWrite = false;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001544 nsecs_t now = systemTime();
1545 nsecs_t delta = now - mLastWriteTime;
Eric Laurentf69a3f82009-09-22 00:35:48 -07001546 if (delta > maxPeriod) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07001547 mNumDelayedWrites++;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001548 if ((now - lastWarning) > kWarningThrottle) {
1549 LOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
1550 ns2ms(delta), mNumDelayedWrites, this);
1551 lastWarning = now;
1552 }
Eric Laurent059b4be2009-11-09 23:32:22 -08001553 if (mStandby) {
1554 longStandbyExit = true;
1555 }
Eric Laurenta553c252009-07-17 12:17:14 -07001556 }
Eric Laurent059b4be2009-11-09 23:32:22 -08001557 mStandby = false;
Eric Laurentf69a3f82009-09-22 00:35:48 -07001558 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07001559 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001560 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07001561 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07001562 }
1563
1564 // finally let go of all our tracks, without the lock held
1565 // since we can't guarantee the destructors won't acquire that
1566 // same lock.
1567 tracksToRemove.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07001568
1569 // Effect chains will be actually deleted here if they were removed from
1570 // mEffectChains list during mixing or effects processing
1571 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07001572 }
1573
1574 if (!mStandby) {
1575 mOutput->standby();
1576 }
Eric Laurenta553c252009-07-17 12:17:14 -07001577
1578 LOGV("MixerThread %p exiting", this);
1579 return false;
1580}
1581
1582// prepareTracks_l() must be called with ThreadBase::mLock held
Eric Laurent059b4be2009-11-09 23:32:22 -08001583uint32_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
Eric Laurenta553c252009-07-17 12:17:14 -07001584{
1585
Eric Laurent059b4be2009-11-09 23:32:22 -08001586 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001587 // find out which tracks need to be processed
1588 size_t count = activeTracks.size();
Eric Laurent65b65452010-06-01 23:49:17 -07001589 size_t mixedTracks = 0;
1590 size_t tracksWithEffect = 0;
Glenn Kasten871c16c2010-03-05 12:18:01 -08001591
1592 float masterVolume = mMasterVolume;
1593 bool masterMute = mMasterMute;
1594
Eric Laurent8cc93b92010-08-11 05:20:11 -07001595 if (masterMute) {
1596 masterVolume = 0;
1597 }
Eric Laurent65b65452010-06-01 23:49:17 -07001598 // Delegate master volume control to effect in output mix effect chain if needed
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001599 sp<EffectChain> chain = getEffectChain_l(AudioSystem::SESSION_OUTPUT_MIX);
Eric Laurent65b65452010-06-01 23:49:17 -07001600 if (chain != 0) {
Eric Laurent8cc93b92010-08-11 05:20:11 -07001601 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurent76c40f72010-07-15 12:50:15 -07001602 chain->setVolume_l(&v, &v);
Eric Laurent65b65452010-06-01 23:49:17 -07001603 masterVolume = (float)((v + (1 << 23)) >> 24);
1604 chain.clear();
1605 }
Glenn Kasten871c16c2010-03-05 12:18:01 -08001606
Eric Laurenta553c252009-07-17 12:17:14 -07001607 for (size_t i=0 ; i<count ; i++) {
1608 sp<Track> t = activeTracks[i].promote();
1609 if (t == 0) continue;
1610
1611 Track* const track = t.get();
1612 audio_track_cblk_t* cblk = track->cblk();
1613
1614 // The first time a track is added we wait
1615 // for all its buffers to be filled before processing it
1616 mAudioMixer->setActiveTrack(track->name());
Eric Laurent9a30fc12010-10-05 14:41:42 -07001617 if (cblk->framesReady() && track->isReady() &&
Eric Laurent71f37cd2010-03-31 12:21:17 -07001618 !track->isPaused() && !track->isTerminated())
Eric Laurenta553c252009-07-17 12:17:14 -07001619 {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08001620 //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 -07001621
Eric Laurent65b65452010-06-01 23:49:17 -07001622 mixedTracks++;
1623
1624 // track->mainBuffer() != mMixBuffer means there is an effect chain
1625 // connected to the track
1626 chain.clear();
1627 if (track->mainBuffer() != mMixBuffer) {
1628 chain = getEffectChain_l(track->sessionId());
1629 // Delegate volume control to effect in track effect chain if needed
1630 if (chain != 0) {
1631 tracksWithEffect++;
1632 } else {
1633 LOGW("prepareTracks_l(): track %08x attached to effect but no chain found on session %d",
1634 track->name(), track->sessionId());
1635 }
1636 }
1637
1638
1639 int param = AudioMixer::VOLUME;
1640 if (track->mFillingUpStatus == Track::FS_FILLED) {
1641 // no ramp for the first volume setting
1642 track->mFillingUpStatus = Track::FS_ACTIVE;
1643 if (track->mState == TrackBase::RESUMING) {
1644 track->mState = TrackBase::ACTIVE;
1645 param = AudioMixer::RAMP_VOLUME;
1646 }
Eric Laurent4bb21c42011-02-28 16:52:51 -08001647 mAudioMixer->setParameter(AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent65b65452010-06-01 23:49:17 -07001648 } else if (cblk->server != 0) {
1649 // If the track is stopped before the first frame was mixed,
1650 // do not apply ramp
1651 param = AudioMixer::RAMP_VOLUME;
1652 }
1653
Eric Laurenta553c252009-07-17 12:17:14 -07001654 // compute volume for this track
Eric Laurent27a2fdf2010-09-10 17:44:44 -07001655 uint32_t vl, vr, va;
Eric Laurent2a6b80b2010-07-29 23:43:43 -07001656 if (track->isMuted() || track->isPausing() ||
Eric Laurenta553c252009-07-17 12:17:14 -07001657 mStreamTypes[track->type()].mute) {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07001658 vl = vr = va = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07001659 if (track->isPausing()) {
1660 track->setPaused();
1661 }
1662 } else {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07001663
Glenn Kasten871c16c2010-03-05 12:18:01 -08001664 // read original volumes with volume control
Eric Laurenta553c252009-07-17 12:17:14 -07001665 float typeVolume = mStreamTypes[track->type()].volume;
Glenn Kasten871c16c2010-03-05 12:18:01 -08001666 float v = masterVolume * typeVolume;
Eric Laurent27a2fdf2010-09-10 17:44:44 -07001667 vl = (uint32_t)(v * cblk->volume[0]) << 12;
1668 vr = (uint32_t)(v * cblk->volume[1]) << 12;
Eric Laurenta553c252009-07-17 12:17:14 -07001669
Eric Laurent27a2fdf2010-09-10 17:44:44 -07001670 va = (uint32_t)(v * cblk->sendLevel);
Eric Laurenta553c252009-07-17 12:17:14 -07001671 }
Eric Laurent27a2fdf2010-09-10 17:44:44 -07001672 // Delegate volume control to effect in track effect chain if needed
1673 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
1674 // Do not ramp volume if volume is controlled by effect
1675 param = AudioMixer::VOLUME;
1676 track->mHasVolumeController = true;
1677 } else {
1678 // force no volume ramp when volume controller was just disabled or removed
1679 // from effect chain to avoid volume spike
1680 if (track->mHasVolumeController) {
1681 param = AudioMixer::VOLUME;
1682 }
1683 track->mHasVolumeController = false;
1684 }
1685
1686 // Convert volumes from 8.24 to 4.12 format
1687 int16_t left, right, aux;
1688 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
1689 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
1690 left = int16_t(v_clamped);
1691 v_clamped = (vr + (1 << 11)) >> 12;
1692 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
1693 right = int16_t(v_clamped);
1694
1695 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
1696 aux = int16_t(va);
Eric Laurent65b65452010-06-01 23:49:17 -07001697
Eric Laurent65b65452010-06-01 23:49:17 -07001698 // XXX: these things DON'T need to be done each time
1699 mAudioMixer->setBufferProvider(track);
1700 mAudioMixer->enable(AudioMixer::MIXING);
1701
1702 mAudioMixer->setParameter(param, AudioMixer::VOLUME0, (void *)left);
1703 mAudioMixer->setParameter(param, AudioMixer::VOLUME1, (void *)right);
1704 mAudioMixer->setParameter(param, AudioMixer::AUXLEVEL, (void *)aux);
Eric Laurenta553c252009-07-17 12:17:14 -07001705 mAudioMixer->setParameter(
1706 AudioMixer::TRACK,
Eric Laurent65b65452010-06-01 23:49:17 -07001707 AudioMixer::FORMAT, (void *)track->format());
Eric Laurenta553c252009-07-17 12:17:14 -07001708 mAudioMixer->setParameter(
1709 AudioMixer::TRACK,
Eric Laurent65b65452010-06-01 23:49:17 -07001710 AudioMixer::CHANNEL_COUNT, (void *)track->channelCount());
Eric Laurenta553c252009-07-17 12:17:14 -07001711 mAudioMixer->setParameter(
1712 AudioMixer::RESAMPLE,
1713 AudioMixer::SAMPLE_RATE,
Eric Laurent65b65452010-06-01 23:49:17 -07001714 (void *)(cblk->sampleRate));
1715 mAudioMixer->setParameter(
1716 AudioMixer::TRACK,
1717 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
1718 mAudioMixer->setParameter(
1719 AudioMixer::TRACK,
1720 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
Eric Laurenta553c252009-07-17 12:17:14 -07001721
1722 // reset retry count
1723 track->mRetryCount = kMaxTrackRetries;
Eric Laurent059b4be2009-11-09 23:32:22 -08001724 mixerStatus = MIXER_TRACKS_READY;
Eric Laurenta553c252009-07-17 12:17:14 -07001725 } else {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08001726 //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 -07001727 if (track->isStopped()) {
1728 track->reset();
1729 }
1730 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
1731 // We have consumed all the buffers of this track.
1732 // Remove it from the list of active tracks.
1733 tracksToRemove->add(track);
Eric Laurenta553c252009-07-17 12:17:14 -07001734 } else {
1735 // No buffers for this track. Give it a few chances to
1736 // fill a buffer, then remove it from active list.
1737 if (--(track->mRetryCount) <= 0) {
Eric Laurent62443f52009-10-05 20:29:18 -07001738 LOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", track->name(), this);
Eric Laurenta553c252009-07-17 12:17:14 -07001739 tracksToRemove->add(track);
Eric Laurent4712baa2010-09-30 16:12:31 -07001740 // indicate to client process that the track was disabled because of underrun
1741 cblk->flags |= CBLK_DISABLED_ON;
Eric Laurent059b4be2009-11-09 23:32:22 -08001742 } else if (mixerStatus != MIXER_TRACKS_READY) {
1743 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07001744 }
Eric Laurenta553c252009-07-17 12:17:14 -07001745 }
Eric Laurent65b65452010-06-01 23:49:17 -07001746 mAudioMixer->disable(AudioMixer::MIXING);
Eric Laurenta553c252009-07-17 12:17:14 -07001747 }
1748 }
1749
1750 // remove all the tracks that need to be...
1751 count = tracksToRemove->size();
1752 if (UNLIKELY(count)) {
1753 for (size_t i=0 ; i<count ; i++) {
1754 const sp<Track>& track = tracksToRemove->itemAt(i);
1755 mActiveTracks.remove(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001756 if (track->mainBuffer() != mMixBuffer) {
1757 chain = getEffectChain_l(track->sessionId());
1758 if (chain != 0) {
1759 LOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
1760 chain->stopTrack();
1761 }
1762 }
Eric Laurenta553c252009-07-17 12:17:14 -07001763 if (track->isTerminated()) {
1764 mTracks.remove(track);
1765 deleteTrackName_l(track->mName);
1766 }
1767 }
1768 }
1769
Eric Laurent65b65452010-06-01 23:49:17 -07001770 // mix buffer must be cleared if all tracks are connected to an
1771 // effect chain as in this case the mixer will not write to
1772 // mix buffer and track effects will accumulate into it
1773 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
1774 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
1775 }
1776
Eric Laurent059b4be2009-11-09 23:32:22 -08001777 return mixerStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07001778}
1779
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001780void AudioFlinger::MixerThread::invalidateTracks(int streamType)
Eric Laurenta553c252009-07-17 12:17:14 -07001781{
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001782 LOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
1783 this, streamType, mTracks.size());
Eric Laurenta553c252009-07-17 12:17:14 -07001784 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001785
Eric Laurenta553c252009-07-17 12:17:14 -07001786 size_t size = mTracks.size();
1787 for (size_t i = 0; i < size; i++) {
1788 sp<Track> t = mTracks[i];
1789 if (t->type() == streamType) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001790 t->mCblk->lock.lock();
1791 t->mCblk->flags |= CBLK_INVALID_ON;
1792 t->mCblk->cv.signal();
1793 t->mCblk->lock.unlock();
Eric Laurenta553c252009-07-17 12:17:14 -07001794 }
Eric Laurent53334cd2010-06-23 17:38:20 -07001795 }
1796}
Eric Laurenta553c252009-07-17 12:17:14 -07001797
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001798
Eric Laurenta553c252009-07-17 12:17:14 -07001799// getTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001800int AudioFlinger::MixerThread::getTrackName_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001801{
1802 return mAudioMixer->getTrackName();
1803}
1804
Eric Laurenta553c252009-07-17 12:17:14 -07001805// deleteTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001806void AudioFlinger::MixerThread::deleteTrackName_l(int name)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001807{
Eric Laurent0a080292009-12-07 10:53:10 -08001808 LOGV("remove track (%d) and delete from mixer", name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001809 mAudioMixer->deleteTrackName(name);
1810}
1811
Eric Laurenta553c252009-07-17 12:17:14 -07001812// checkForNewParameters_l() must be called with ThreadBase::mLock held
1813bool AudioFlinger::MixerThread::checkForNewParameters_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001814{
Eric Laurenta553c252009-07-17 12:17:14 -07001815 bool reconfig = false;
1816
Eric Laurent8fce46a2009-08-04 09:45:33 -07001817 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07001818 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07001819 String8 keyValuePair = mNewParameters[0];
1820 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07001821 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07001822
Eric Laurenta553c252009-07-17 12:17:14 -07001823 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
1824 reconfig = true;
1825 }
1826 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
1827 if (value != AudioSystem::PCM_16_BIT) {
1828 status = BAD_VALUE;
1829 } else {
1830 reconfig = true;
1831 }
1832 }
1833 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
1834 if (value != AudioSystem::CHANNEL_OUT_STEREO) {
1835 status = BAD_VALUE;
1836 } else {
1837 reconfig = true;
1838 }
1839 }
1840 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
1841 // do not accept frame count changes if tracks are open as the track buffer
1842 // size depends on frame count and correct behavior would not be garantied
1843 // if frame count is changed after track creation
1844 if (!mTracks.isEmpty()) {
1845 status = INVALID_OPERATION;
1846 } else {
1847 reconfig = true;
1848 }
1849 }
Eric Laurent65b65452010-06-01 23:49:17 -07001850 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08001851 // when changing the audio output device, call addBatteryData to notify
1852 // the change
1853 if (mDevice != value) {
1854 uint32_t params = 0;
1855 // check whether speaker is on
1856 if (value & AudioSystem::DEVICE_OUT_SPEAKER) {
1857 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
1858 }
1859
1860 int deviceWithoutSpeaker
1861 = AudioSystem::DEVICE_OUT_ALL & ~AudioSystem::DEVICE_OUT_SPEAKER;
1862 // check if any other device (except speaker) is on
1863 if (value & deviceWithoutSpeaker ) {
1864 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
1865 }
1866
1867 if (params != 0) {
1868 addBatteryData(params);
1869 }
1870 }
1871
Eric Laurent65b65452010-06-01 23:49:17 -07001872 // forward device change to effects that have requested to be
1873 // aware of attached audio device.
1874 mDevice = (uint32_t)value;
1875 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07001876 mEffectChains[i]->setDevice_l(mDevice);
Eric Laurent65b65452010-06-01 23:49:17 -07001877 }
1878 }
1879
Eric Laurenta553c252009-07-17 12:17:14 -07001880 if (status == NO_ERROR) {
Eric Laurent8fce46a2009-08-04 09:45:33 -07001881 status = mOutput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07001882 if (!mStandby && status == INVALID_OPERATION) {
1883 mOutput->standby();
1884 mStandby = true;
1885 mBytesWritten = 0;
Eric Laurent8fce46a2009-08-04 09:45:33 -07001886 status = mOutput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07001887 }
1888 if (status == NO_ERROR && reconfig) {
1889 delete mAudioMixer;
1890 readOutputParameters();
1891 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1892 for (size_t i = 0; i < mTracks.size() ; i++) {
1893 int name = getTrackName_l();
1894 if (name < 0) break;
1895 mTracks[i]->mName = name;
Eric Laurent6f7e0972009-08-10 08:15:12 -07001896 // limit track sample rate to 2 x new output sample rate
1897 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
1898 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
1899 }
Eric Laurenta553c252009-07-17 12:17:14 -07001900 }
Eric Laurent8fce46a2009-08-04 09:45:33 -07001901 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07001902 }
1903 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08001904
1905 mNewParameters.removeAt(0);
1906
Eric Laurenta553c252009-07-17 12:17:14 -07001907 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07001908 mParamCond.signal();
Eric Laurent8fce46a2009-08-04 09:45:33 -07001909 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07001910 }
1911 return reconfig;
1912}
1913
1914status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
1915{
1916 const size_t SIZE = 256;
1917 char buffer[SIZE];
1918 String8 result;
1919
1920 PlaybackThread::dumpInternals(fd, args);
1921
1922 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
1923 result.append(buffer);
1924 write(fd, result.string(), result.size());
1925 return NO_ERROR;
1926}
1927
Eric Laurent059b4be2009-11-09 23:32:22 -08001928uint32_t AudioFlinger::MixerThread::activeSleepTimeUs()
Eric Laurent62443f52009-10-05 20:29:18 -07001929{
Eric Laurent059b4be2009-11-09 23:32:22 -08001930 return (uint32_t)(mOutput->latency() * 1000) / 2;
1931}
1932
1933uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
1934{
Eric Laurenta54d7d32010-07-29 06:50:24 -07001935 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Eric Laurent62443f52009-10-05 20:29:18 -07001936}
1937
Eric Laurent8448a792010-08-18 18:13:17 -07001938uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
1939{
1940 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
1941}
1942
Eric Laurenta553c252009-07-17 12:17:14 -07001943// ----------------------------------------------------------------------------
Eric Laurent65b65452010-06-01 23:49:17 -07001944AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
1945 : PlaybackThread(audioFlinger, output, id, device)
Eric Laurenta553c252009-07-17 12:17:14 -07001946{
1947 mType = PlaybackThread::DIRECT;
1948}
1949
1950AudioFlinger::DirectOutputThread::~DirectOutputThread()
1951{
1952}
1953
1954
Eric Laurent65b65452010-06-01 23:49:17 -07001955static inline int16_t clamp16(int32_t sample)
1956{
1957 if ((sample>>15) ^ (sample>>31))
1958 sample = 0x7FFF ^ (sample>>31);
1959 return sample;
1960}
1961
1962static inline
1963int32_t mul(int16_t in, int16_t v)
1964{
1965#if defined(__arm__) && !defined(__thumb__)
1966 int32_t out;
1967 asm( "smulbb %[out], %[in], %[v] \n"
1968 : [out]"=r"(out)
1969 : [in]"%r"(in), [v]"r"(v)
1970 : );
1971 return out;
1972#else
1973 return in * int32_t(v);
1974#endif
1975}
1976
1977void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
1978{
1979 // Do not apply volume on compressed audio
1980 if (!AudioSystem::isLinearPCM(mFormat)) {
1981 return;
1982 }
1983
1984 // convert to signed 16 bit before volume calculation
1985 if (mFormat == AudioSystem::PCM_8_BIT) {
1986 size_t count = mFrameCount * mChannelCount;
1987 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
1988 int16_t *dst = mMixBuffer + count-1;
1989 while(count--) {
1990 *dst-- = (int16_t)(*src--^0x80) << 8;
1991 }
1992 }
1993
1994 size_t frameCount = mFrameCount;
1995 int16_t *out = mMixBuffer;
1996 if (ramp) {
1997 if (mChannelCount == 1) {
1998 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
1999 int32_t vlInc = d / (int32_t)frameCount;
2000 int32_t vl = ((int32_t)mLeftVolShort << 16);
2001 do {
2002 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2003 out++;
2004 vl += vlInc;
2005 } while (--frameCount);
2006
2007 } else {
2008 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2009 int32_t vlInc = d / (int32_t)frameCount;
2010 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2011 int32_t vrInc = d / (int32_t)frameCount;
2012 int32_t vl = ((int32_t)mLeftVolShort << 16);
2013 int32_t vr = ((int32_t)mRightVolShort << 16);
2014 do {
2015 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2016 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2017 out += 2;
2018 vl += vlInc;
2019 vr += vrInc;
2020 } while (--frameCount);
2021 }
2022 } else {
2023 if (mChannelCount == 1) {
2024 do {
2025 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2026 out++;
2027 } while (--frameCount);
2028 } else {
2029 do {
2030 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2031 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2032 out += 2;
2033 } while (--frameCount);
2034 }
2035 }
2036
2037 // convert back to unsigned 8 bit after volume calculation
2038 if (mFormat == AudioSystem::PCM_8_BIT) {
2039 size_t count = mFrameCount * mChannelCount;
2040 int16_t *src = mMixBuffer;
2041 uint8_t *dst = (uint8_t *)mMixBuffer;
2042 while(count--) {
2043 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2044 }
2045 }
2046
2047 mLeftVolShort = leftVol;
2048 mRightVolShort = rightVol;
2049}
2050
Eric Laurenta553c252009-07-17 12:17:14 -07002051bool AudioFlinger::DirectOutputThread::threadLoop()
2052{
Eric Laurent059b4be2009-11-09 23:32:22 -08002053 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002054 sp<Track> trackToRemove;
2055 sp<Track> activeTrack;
2056 nsecs_t standbyTime = systemTime();
2057 int8_t *curBuf;
2058 size_t mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent059b4be2009-11-09 23:32:22 -08002059 uint32_t activeSleepTime = activeSleepTimeUs();
2060 uint32_t idleSleepTime = idleSleepTimeUs();
2061 uint32_t sleepTime = idleSleepTime;
Eric Laurentef9500f2010-03-11 14:47:00 -08002062 // use shorter standby delay as on normal output to release
2063 // hardware resources as soon as possible
2064 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
Eric Laurent059b4be2009-11-09 23:32:22 -08002065
Eric Laurenta553c252009-07-17 12:17:14 -07002066 while (!exitPending())
2067 {
Eric Laurent65b65452010-06-01 23:49:17 -07002068 bool rampVolume;
2069 uint16_t leftVol;
2070 uint16_t rightVol;
2071 Vector< sp<EffectChain> > effectChains;
2072
Eric Laurenta553c252009-07-17 12:17:14 -07002073 processConfigEvents();
2074
Eric Laurent059b4be2009-11-09 23:32:22 -08002075 mixerStatus = MIXER_IDLE;
2076
Eric Laurenta553c252009-07-17 12:17:14 -07002077 { // scope for the mLock
2078
2079 Mutex::Autolock _l(mLock);
2080
2081 if (checkForNewParameters_l()) {
2082 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent059b4be2009-11-09 23:32:22 -08002083 activeSleepTime = activeSleepTimeUs();
2084 idleSleepTime = idleSleepTimeUs();
Eric Laurentef9500f2010-03-11 14:47:00 -08002085 standbyDelay = microseconds(activeSleepTime*2);
Eric Laurenta553c252009-07-17 12:17:14 -07002086 }
2087
2088 // put audio hardware into standby after short delay
2089 if UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2090 mSuspended) {
2091 // wait until we have something to do...
2092 if (!mStandby) {
2093 LOGV("Audio hardware entering standby, mixer %p\n", this);
2094 mOutput->standby();
2095 mStandby = true;
2096 mBytesWritten = 0;
2097 }
2098
2099 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2100 // we're about to wait, flush the binder command buffer
2101 IPCThreadState::self()->flushCommands();
2102
2103 if (exitPending()) break;
2104
2105 LOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
2106 mWaitWorkCV.wait(mLock);
2107 LOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
2108
2109 if (mMasterMute == false) {
2110 char value[PROPERTY_VALUE_MAX];
2111 property_get("ro.audio.silent", value, "0");
2112 if (atoi(value)) {
2113 LOGD("Silence is golden");
2114 setMasterMute(true);
2115 }
2116 }
2117
Eric Laurentef9500f2010-03-11 14:47:00 -08002118 standbyTime = systemTime() + standbyDelay;
Eric Laurent059b4be2009-11-09 23:32:22 -08002119 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07002120 continue;
2121 }
2122 }
2123
Eric Laurent65b65452010-06-01 23:49:17 -07002124 effectChains = mEffectChains;
2125
Eric Laurenta553c252009-07-17 12:17:14 -07002126 // find out which tracks need to be processed
2127 if (mActiveTracks.size() != 0) {
2128 sp<Track> t = mActiveTracks[0].promote();
2129 if (t == 0) continue;
2130
2131 Track* const track = t.get();
2132 audio_track_cblk_t* cblk = track->cblk();
2133
2134 // The first time a track is added we wait
2135 // for all its buffers to be filled before processing it
Eric Laurent9a30fc12010-10-05 14:41:42 -07002136 if (cblk->framesReady() && track->isReady() &&
Eric Laurent380558b2010-04-09 06:11:48 -07002137 !track->isPaused() && !track->isTerminated())
Eric Laurenta553c252009-07-17 12:17:14 -07002138 {
2139 //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
2140
Eric Laurent65b65452010-06-01 23:49:17 -07002141 if (track->mFillingUpStatus == Track::FS_FILLED) {
2142 track->mFillingUpStatus = Track::FS_ACTIVE;
2143 mLeftVolFloat = mRightVolFloat = 0;
2144 mLeftVolShort = mRightVolShort = 0;
2145 if (track->mState == TrackBase::RESUMING) {
2146 track->mState = TrackBase::ACTIVE;
2147 rampVolume = true;
2148 }
2149 } else if (cblk->server != 0) {
2150 // If the track is stopped before the first frame was mixed,
2151 // do not apply ramp
2152 rampVolume = true;
2153 }
Eric Laurenta553c252009-07-17 12:17:14 -07002154 // compute volume for this track
2155 float left, right;
2156 if (track->isMuted() || mMasterMute || track->isPausing() ||
2157 mStreamTypes[track->type()].mute) {
2158 left = right = 0;
2159 if (track->isPausing()) {
2160 track->setPaused();
2161 }
2162 } else {
2163 float typeVolume = mStreamTypes[track->type()].volume;
2164 float v = mMasterVolume * typeVolume;
2165 float v_clamped = v * cblk->volume[0];
2166 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2167 left = v_clamped/MAX_GAIN;
2168 v_clamped = v * cblk->volume[1];
2169 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2170 right = v_clamped/MAX_GAIN;
2171 }
2172
Eric Laurent65b65452010-06-01 23:49:17 -07002173 if (left != mLeftVolFloat || right != mRightVolFloat) {
2174 mLeftVolFloat = left;
2175 mRightVolFloat = right;
Eric Laurenta553c252009-07-17 12:17:14 -07002176
Eric Laurent65b65452010-06-01 23:49:17 -07002177 // If audio HAL implements volume control,
2178 // force software volume to nominal value
2179 if (mOutput->setVolume(left, right) == NO_ERROR) {
2180 left = 1.0f;
2181 right = 1.0f;
Eric Laurenta553c252009-07-17 12:17:14 -07002182 }
Eric Laurent65b65452010-06-01 23:49:17 -07002183
2184 // Convert volumes from float to 8.24
2185 uint32_t vl = (uint32_t)(left * (1 << 24));
2186 uint32_t vr = (uint32_t)(right * (1 << 24));
2187
2188 // Delegate volume control to effect in track effect chain if needed
2189 // only one effect chain can be present on DirectOutputThread, so if
2190 // there is one, the track is connected to it
2191 if (!effectChains.isEmpty()) {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002192 // Do not ramp volume if volume is controlled by effect
Eric Laurent76c40f72010-07-15 12:50:15 -07002193 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002194 rampVolume = false;
2195 }
2196 }
2197
2198 // Convert volumes from 8.24 to 4.12 format
2199 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2200 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2201 leftVol = (uint16_t)v_clamped;
2202 v_clamped = (vr + (1 << 11)) >> 12;
2203 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2204 rightVol = (uint16_t)v_clamped;
2205 } else {
2206 leftVol = mLeftVolShort;
2207 rightVol = mRightVolShort;
2208 rampVolume = false;
Eric Laurenta553c252009-07-17 12:17:14 -07002209 }
2210
2211 // reset retry count
Eric Laurentef9500f2010-03-11 14:47:00 -08002212 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurenta553c252009-07-17 12:17:14 -07002213 activeTrack = t;
Eric Laurent059b4be2009-11-09 23:32:22 -08002214 mixerStatus = MIXER_TRACKS_READY;
Eric Laurenta553c252009-07-17 12:17:14 -07002215 } else {
2216 //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
2217 if (track->isStopped()) {
2218 track->reset();
2219 }
2220 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2221 // We have consumed all the buffers of this track.
2222 // Remove it from the list of active tracks.
2223 trackToRemove = track;
2224 } else {
2225 // No buffers for this track. Give it a few chances to
2226 // fill a buffer, then remove it from active list.
2227 if (--(track->mRetryCount) <= 0) {
2228 LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
2229 trackToRemove = track;
Eric Laurent059b4be2009-11-09 23:32:22 -08002230 } else {
2231 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07002232 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002233 }
Eric Laurenta553c252009-07-17 12:17:14 -07002234 }
2235 }
2236
2237 // remove all the tracks that need to be...
2238 if (UNLIKELY(trackToRemove != 0)) {
2239 mActiveTracks.remove(trackToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07002240 if (!effectChains.isEmpty()) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002241 LOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
2242 trackToRemove->sessionId());
Eric Laurent65b65452010-06-01 23:49:17 -07002243 effectChains[0]->stopTrack();
2244 }
Eric Laurenta553c252009-07-17 12:17:14 -07002245 if (trackToRemove->isTerminated()) {
2246 mTracks.remove(trackToRemove);
2247 deleteTrackName_l(trackToRemove->mName);
2248 }
2249 }
Eric Laurent65b65452010-06-01 23:49:17 -07002250
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002251 lockEffectChains_l(effectChains);
Eric Laurenta553c252009-07-17 12:17:14 -07002252 }
2253
Eric Laurent059b4be2009-11-09 23:32:22 -08002254 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002255 AudioBufferProvider::Buffer buffer;
2256 size_t frameCount = mFrameCount;
2257 curBuf = (int8_t *)mMixBuffer;
2258 // output audio to hardware
Eric Laurent65b65452010-06-01 23:49:17 -07002259 while (frameCount) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002260 buffer.frameCount = frameCount;
2261 activeTrack->getNextBuffer(&buffer);
2262 if (UNLIKELY(buffer.raw == 0)) {
2263 memset(curBuf, 0, frameCount * mFrameSize);
2264 break;
2265 }
2266 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2267 frameCount -= buffer.frameCount;
2268 curBuf += buffer.frameCount * mFrameSize;
2269 activeTrack->releaseBuffer(&buffer);
2270 }
2271 sleepTime = 0;
Eric Laurentef9500f2010-03-11 14:47:00 -08002272 standbyTime = systemTime() + standbyDelay;
Eric Laurent96c08a62009-09-07 08:38:38 -07002273 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07002274 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002275 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2276 sleepTime = activeSleepTime;
2277 } else {
2278 sleepTime = idleSleepTime;
2279 }
Eric Laurent62443f52009-10-05 20:29:18 -07002280 } else if (mBytesWritten != 0 && AudioSystem::isLinearPCM(mFormat)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002281 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent96c08a62009-09-07 08:38:38 -07002282 sleepTime = 0;
Eric Laurent96c08a62009-09-07 08:38:38 -07002283 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002284 }
Eric Laurent96c08a62009-09-07 08:38:38 -07002285
Eric Laurentf69a3f82009-09-22 00:35:48 -07002286 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07002287 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07002288 }
2289 // sleepTime == 0 means we must write to audio hardware
2290 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07002291 if (mixerStatus == MIXER_TRACKS_READY) {
2292 applyVolume(leftVol, rightVol, rampVolume);
2293 }
2294 for (size_t i = 0; i < effectChains.size(); i ++) {
2295 effectChains[i]->process_l();
2296 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002297 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07002298
Eric Laurentf69a3f82009-09-22 00:35:48 -07002299 mLastWriteTime = systemTime();
2300 mInWrite = true;
Eric Laurent0986e792010-01-19 17:37:09 -08002301 mBytesWritten += mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002302 int bytesWritten = (int)mOutput->write(mMixBuffer, mixBufferSize);
Eric Laurent0986e792010-01-19 17:37:09 -08002303 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002304 mNumWrites++;
2305 mInWrite = false;
2306 mStandby = false;
2307 } else {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002308 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002309 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07002310 }
2311
2312 // finally let go of removed track, without the lock held
2313 // since we can't guarantee the destructors won't acquire that
2314 // same lock.
2315 trackToRemove.clear();
2316 activeTrack.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07002317
2318 // Effect chains will be actually deleted here if they were removed from
2319 // mEffectChains list during mixing or effects processing
2320 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07002321 }
2322
2323 if (!mStandby) {
2324 mOutput->standby();
2325 }
Eric Laurenta553c252009-07-17 12:17:14 -07002326
2327 LOGV("DirectOutputThread %p exiting", this);
2328 return false;
2329}
2330
2331// getTrackName_l() must be called with ThreadBase::mLock held
2332int AudioFlinger::DirectOutputThread::getTrackName_l()
2333{
2334 return 0;
2335}
2336
2337// deleteTrackName_l() must be called with ThreadBase::mLock held
2338void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2339{
2340}
2341
2342// checkForNewParameters_l() must be called with ThreadBase::mLock held
2343bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2344{
2345 bool reconfig = false;
2346
Eric Laurent8fce46a2009-08-04 09:45:33 -07002347 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07002348 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002349 String8 keyValuePair = mNewParameters[0];
2350 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002351 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002352
Eric Laurenta553c252009-07-17 12:17:14 -07002353 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2354 // do not accept frame count changes if tracks are open as the track buffer
2355 // size depends on frame count and correct behavior would not be garantied
2356 // if frame count is changed after track creation
2357 if (!mTracks.isEmpty()) {
2358 status = INVALID_OPERATION;
2359 } else {
2360 reconfig = true;
2361 }
2362 }
2363 if (status == NO_ERROR) {
Eric Laurent8fce46a2009-08-04 09:45:33 -07002364 status = mOutput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002365 if (!mStandby && status == INVALID_OPERATION) {
2366 mOutput->standby();
2367 mStandby = true;
2368 mBytesWritten = 0;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002369 status = mOutput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002370 }
2371 if (status == NO_ERROR && reconfig) {
2372 readOutputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07002373 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07002374 }
2375 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08002376
2377 mNewParameters.removeAt(0);
2378
Eric Laurenta553c252009-07-17 12:17:14 -07002379 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07002380 mParamCond.signal();
Eric Laurent8fce46a2009-08-04 09:45:33 -07002381 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07002382 }
2383 return reconfig;
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08002384}
2385
Eric Laurent059b4be2009-11-09 23:32:22 -08002386uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
Eric Laurent62443f52009-10-05 20:29:18 -07002387{
2388 uint32_t time;
2389 if (AudioSystem::isLinearPCM(mFormat)) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002390 time = (uint32_t)(mOutput->latency() * 1000) / 2;
2391 } else {
2392 time = 10000;
2393 }
2394 return time;
2395}
2396
2397uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2398{
2399 uint32_t time;
2400 if (AudioSystem::isLinearPCM(mFormat)) {
Eric Laurenta54d7d32010-07-29 06:50:24 -07002401 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Eric Laurent62443f52009-10-05 20:29:18 -07002402 } else {
2403 time = 10000;
2404 }
2405 return time;
2406}
2407
Eric Laurent8448a792010-08-18 18:13:17 -07002408uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2409{
2410 uint32_t time;
2411 if (AudioSystem::isLinearPCM(mFormat)) {
2412 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2413 } else {
2414 time = 10000;
2415 }
2416 return time;
2417}
2418
2419
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002420// ----------------------------------------------------------------------------
2421
Eric Laurent49f02be2009-11-19 09:00:56 -08002422AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread, int id)
Eric Laurent65b65452010-06-01 23:49:17 -07002423 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device()), mWaitTimeMs(UINT_MAX)
Eric Laurenta553c252009-07-17 12:17:14 -07002424{
2425 mType = PlaybackThread::DUPLICATING;
2426 addOutputTrack(mainThread);
2427}
2428
2429AudioFlinger::DuplicatingThread::~DuplicatingThread()
2430{
Eric Laurent0a080292009-12-07 10:53:10 -08002431 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2432 mOutputTracks[i]->destroy();
2433 }
Eric Laurenta553c252009-07-17 12:17:14 -07002434 mOutputTracks.clear();
2435}
2436
2437bool AudioFlinger::DuplicatingThread::threadLoop()
2438{
Eric Laurenta553c252009-07-17 12:17:14 -07002439 Vector< sp<Track> > tracksToRemove;
Eric Laurent059b4be2009-11-09 23:32:22 -08002440 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002441 nsecs_t standbyTime = systemTime();
2442 size_t mixBufferSize = mFrameCount*mFrameSize;
2443 SortedVector< sp<OutputTrack> > outputTracks;
Eric Laurent62443f52009-10-05 20:29:18 -07002444 uint32_t writeFrames = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08002445 uint32_t activeSleepTime = activeSleepTimeUs();
2446 uint32_t idleSleepTime = idleSleepTimeUs();
2447 uint32_t sleepTime = idleSleepTime;
Eric Laurent65b65452010-06-01 23:49:17 -07002448 Vector< sp<EffectChain> > effectChains;
Eric Laurenta553c252009-07-17 12:17:14 -07002449
2450 while (!exitPending())
2451 {
2452 processConfigEvents();
2453
Eric Laurent059b4be2009-11-09 23:32:22 -08002454 mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002455 { // scope for the mLock
2456
2457 Mutex::Autolock _l(mLock);
2458
2459 if (checkForNewParameters_l()) {
2460 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002461 updateWaitTime();
Eric Laurent059b4be2009-11-09 23:32:22 -08002462 activeSleepTime = activeSleepTimeUs();
2463 idleSleepTime = idleSleepTimeUs();
Eric Laurenta553c252009-07-17 12:17:14 -07002464 }
2465
2466 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
2467
2468 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2469 outputTracks.add(mOutputTracks[i]);
2470 }
2471
2472 // put audio hardware into standby after short delay
2473 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
2474 mSuspended) {
2475 if (!mStandby) {
2476 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurenta553c252009-07-17 12:17:14 -07002477 outputTracks[i]->stop();
Eric Laurenta553c252009-07-17 12:17:14 -07002478 }
2479 mStandby = true;
2480 mBytesWritten = 0;
2481 }
2482
2483 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
2484 // we're about to wait, flush the binder command buffer
2485 IPCThreadState::self()->flushCommands();
2486 outputTracks.clear();
2487
2488 if (exitPending()) break;
2489
2490 LOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
2491 mWaitWorkCV.wait(mLock);
2492 LOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
2493 if (mMasterMute == false) {
2494 char value[PROPERTY_VALUE_MAX];
2495 property_get("ro.audio.silent", value, "0");
2496 if (atoi(value)) {
2497 LOGD("Silence is golden");
2498 setMasterMute(true);
2499 }
2500 }
2501
2502 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent059b4be2009-11-09 23:32:22 -08002503 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07002504 continue;
2505 }
2506 }
2507
Eric Laurent059b4be2009-11-09 23:32:22 -08002508 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07002509
2510 // prevent any changes in effect chain list and in each effect chain
2511 // during mixing and effect process as the audio buffers could be deleted
2512 // or modified if an effect is created or deleted
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002513 lockEffectChains_l(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002514 }
Eric Laurenta553c252009-07-17 12:17:14 -07002515
Eric Laurent059b4be2009-11-09 23:32:22 -08002516 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurenta553c252009-07-17 12:17:14 -07002517 // mix buffers...
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002518 if (outputsReady(outputTracks)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002519 mAudioMixer->process();
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002520 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07002521 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002522 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002523 sleepTime = 0;
Eric Laurent62443f52009-10-05 20:29:18 -07002524 writeFrames = mFrameCount;
Eric Laurenta553c252009-07-17 12:17:14 -07002525 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07002526 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002527 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2528 sleepTime = activeSleepTime;
2529 } else {
2530 sleepTime = idleSleepTime;
2531 }
Eric Laurent62443f52009-10-05 20:29:18 -07002532 } else if (mBytesWritten != 0) {
2533 // flush remaining overflow buffers in output tracks
2534 for (size_t i = 0; i < outputTracks.size(); i++) {
2535 if (outputTracks[i]->isActive()) {
2536 sleepTime = 0;
2537 writeFrames = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07002538 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent62443f52009-10-05 20:29:18 -07002539 break;
2540 }
2541 }
Eric Laurenta553c252009-07-17 12:17:14 -07002542 }
2543 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002544
2545 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07002546 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07002547 }
2548 // sleepTime == 0 means we must write to audio hardware
2549 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07002550 for (size_t i = 0; i < effectChains.size(); i ++) {
2551 effectChains[i]->process_l();
2552 }
2553 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002554 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07002555
Eric Laurent62443f52009-10-05 20:29:18 -07002556 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002557 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurent65b65452010-06-01 23:49:17 -07002558 outputTracks[i]->write(mMixBuffer, writeFrames);
Eric Laurenta553c252009-07-17 12:17:14 -07002559 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002560 mStandby = false;
2561 mBytesWritten += mixBufferSize;
Eric Laurenta553c252009-07-17 12:17:14 -07002562 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07002563 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002564 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002565 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07002566 }
2567
2568 // finally let go of all our tracks, without the lock held
2569 // since we can't guarantee the destructors won't acquire that
2570 // same lock.
2571 tracksToRemove.clear();
2572 outputTracks.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07002573
2574 // Effect chains will be actually deleted here if they were removed from
2575 // mEffectChains list during mixing or effects processing
2576 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07002577 }
2578
Eric Laurenta553c252009-07-17 12:17:14 -07002579 return false;
2580}
2581
2582void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
2583{
2584 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
2585 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002586 this,
Eric Laurenta553c252009-07-17 12:17:14 -07002587 mSampleRate,
2588 mFormat,
2589 mChannelCount,
2590 frameCount);
Eric Laurent6c30a712009-08-10 23:22:32 -07002591 if (outputTrack->cblk() != NULL) {
2592 thread->setStreamVolume(AudioSystem::NUM_STREAM_TYPES, 1.0f);
2593 mOutputTracks.add(outputTrack);
2594 LOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002595 updateWaitTime();
Eric Laurent6c30a712009-08-10 23:22:32 -07002596 }
Eric Laurenta553c252009-07-17 12:17:14 -07002597}
2598
2599void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
2600{
2601 Mutex::Autolock _l(mLock);
2602 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2603 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
Eric Laurent6c30a712009-08-10 23:22:32 -07002604 mOutputTracks[i]->destroy();
Eric Laurenta553c252009-07-17 12:17:14 -07002605 mOutputTracks.removeAt(i);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002606 updateWaitTime();
Eric Laurenta553c252009-07-17 12:17:14 -07002607 return;
2608 }
2609 }
2610 LOGV("removeOutputTrack(): unkonwn thread: %p", thread);
2611}
2612
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002613void AudioFlinger::DuplicatingThread::updateWaitTime()
2614{
2615 mWaitTimeMs = UINT_MAX;
2616 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2617 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
2618 if (strong != NULL) {
2619 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
2620 if (waitTimeMs < mWaitTimeMs) {
2621 mWaitTimeMs = waitTimeMs;
2622 }
2623 }
2624 }
2625}
2626
2627
2628bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
2629{
2630 for (size_t i = 0; i < outputTracks.size(); i++) {
2631 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
2632 if (thread == 0) {
2633 LOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
2634 return false;
2635 }
2636 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2637 if (playbackThread->standby() && !playbackThread->isSuspended()) {
2638 LOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
2639 return false;
2640 }
2641 }
2642 return true;
2643}
2644
2645uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
2646{
2647 return (mWaitTimeMs * 1000) / 2;
2648}
2649
Eric Laurenta553c252009-07-17 12:17:14 -07002650// ----------------------------------------------------------------------------
2651
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002652// TrackBase constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07002653AudioFlinger::ThreadBase::TrackBase::TrackBase(
2654 const wp<ThreadBase>& thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002655 const sp<Client>& client,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002656 uint32_t sampleRate,
2657 int format,
2658 int channelCount,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002659 int frameCount,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002660 uint32_t flags,
Eric Laurent65b65452010-06-01 23:49:17 -07002661 const sp<IMemory>& sharedBuffer,
2662 int sessionId)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002663 : RefBase(),
Eric Laurenta553c252009-07-17 12:17:14 -07002664 mThread(thread),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002665 mClient(client),
Eric Laurent8a77a992009-09-09 05:16:08 -07002666 mCblk(0),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002667 mFrameCount(0),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002668 mState(IDLE),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002669 mClientTid(-1),
2670 mFormat(format),
Eric Laurent65b65452010-06-01 23:49:17 -07002671 mFlags(flags & ~SYSTEM_FLAGS_MASK),
2672 mSessionId(sessionId)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002673{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002674 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
2675
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002676 // LOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002677 size_t size = sizeof(audio_track_cblk_t);
2678 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
2679 if (sharedBuffer == 0) {
2680 size += bufferSize;
2681 }
2682
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002683 if (client != NULL) {
2684 mCblkMemory = client->heap()->allocate(size);
2685 if (mCblkMemory != 0) {
2686 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
2687 if (mCblk) { // construct the shared structure in-place.
2688 new(mCblk) audio_track_cblk_t();
2689 // clear all buffers
2690 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07002691 mCblk->sampleRate = sampleRate;
Eric Laurentb0a01472010-05-14 05:45:46 -07002692 mCblk->channelCount = (uint8_t)channelCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002693 if (sharedBuffer == 0) {
2694 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2695 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2696 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent4712baa2010-09-30 16:12:31 -07002697 // written to buffer (other flags are cleared)
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002698 mCblk->flags = CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002699 } else {
2700 mBuffer = sharedBuffer->pointer();
2701 }
2702 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002703 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002704 } else {
2705 LOGE("not enough memory for AudioTrack size=%u", size);
2706 client->heap()->dump("AudioTrack");
2707 return;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002708 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002709 } else {
2710 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
2711 if (mCblk) { // construct the shared structure in-place.
2712 new(mCblk) audio_track_cblk_t();
2713 // clear all buffers
2714 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07002715 mCblk->sampleRate = sampleRate;
Eric Laurentb0a01472010-05-14 05:45:46 -07002716 mCblk->channelCount = (uint8_t)channelCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002717 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2718 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2719 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent4712baa2010-09-30 16:12:31 -07002720 // written to buffer (other flags are cleared)
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002721 mCblk->flags = CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002722 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
2723 }
2724 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002725}
2726
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002727AudioFlinger::ThreadBase::TrackBase::~TrackBase()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002728{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002729 if (mCblk) {
Eric Laurenta553c252009-07-17 12:17:14 -07002730 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
2731 if (mClient == NULL) {
2732 delete mCblk;
2733 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002734 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002735 mCblkMemory.clear(); // and free the shared memory
Eric Laurentb9481d82009-09-17 05:12:56 -07002736 if (mClient != NULL) {
2737 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
2738 mClient.clear();
2739 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002740}
2741
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002742void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002743{
2744 buffer->raw = 0;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002745 mFrameCount = buffer->frameCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002746 step();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002747 buffer->frameCount = 0;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002748}
2749
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002750bool AudioFlinger::ThreadBase::TrackBase::step() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002751 bool result;
2752 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002753
2754 result = cblk->stepServer(mFrameCount);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002755 if (!result) {
2756 LOGV("stepServer failed acquiring cblk mutex");
2757 mFlags |= STEPSERVER_FAILED;
2758 }
2759 return result;
2760}
2761
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002762void AudioFlinger::ThreadBase::TrackBase::reset() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002763 audio_track_cblk_t* cblk = this->cblk();
2764
2765 cblk->user = 0;
2766 cblk->server = 0;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002767 cblk->userBase = 0;
2768 cblk->serverBase = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002769 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002770 LOGV("TrackBase::reset");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002771}
2772
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002773sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002774{
2775 return mCblkMemory;
2776}
2777
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002778int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
The Android Open Source Project10592532009-03-18 17:39:46 -07002779 return (int)mCblk->sampleRate;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002780}
2781
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002782int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
Eric Laurentb0a01472010-05-14 05:45:46 -07002783 return (int)mCblk->channelCount;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002784}
2785
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002786void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002787 audio_track_cblk_t* cblk = this->cblk();
Eric Laurenta553c252009-07-17 12:17:14 -07002788 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
2789 int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002790
2791 // Check validity of returned pointer in case the track control block would have been corrupted.
Eric Laurenta553c252009-07-17 12:17:14 -07002792 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
2793 ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
The Android Open Source Project10592532009-03-18 17:39:46 -07002794 LOGE("TrackBase::getBuffer buffer out of range:\n start: %p, end %p , mBuffer %p mBufferEnd %p\n \
Eric Laurentb0a01472010-05-14 05:45:46 -07002795 server %d, serverBase %d, user %d, userBase %d, channelCount %d",
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002796 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Eric Laurentb0a01472010-05-14 05:45:46 -07002797 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, cblk->channelCount);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002798 return 0;
2799 }
2800
2801 return bufferStart;
2802}
2803
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002804// ----------------------------------------------------------------------------
2805
Eric Laurenta553c252009-07-17 12:17:14 -07002806// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
2807AudioFlinger::PlaybackThread::Track::Track(
2808 const wp<ThreadBase>& thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002809 const sp<Client>& client,
2810 int streamType,
2811 uint32_t sampleRate,
2812 int format,
2813 int channelCount,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002814 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07002815 const sp<IMemory>& sharedBuffer,
2816 int sessionId)
2817 : TrackBase(thread, client, sampleRate, format, channelCount, frameCount, 0, sharedBuffer, sessionId),
Eric Laurenta92ebfa2010-08-31 13:50:07 -07002818 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
2819 mAuxEffectId(0), mHasVolumeController(false)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002820{
Eric Laurent8a77a992009-09-09 05:16:08 -07002821 if (mCblk != NULL) {
2822 sp<ThreadBase> baseThread = thread.promote();
2823 if (baseThread != 0) {
2824 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
2825 mName = playbackThread->getTrackName_l();
Eric Laurent65b65452010-06-01 23:49:17 -07002826 mMainBuffer = playbackThread->mixBuffer();
Eric Laurent8a77a992009-09-09 05:16:08 -07002827 }
2828 LOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2829 if (mName < 0) {
2830 LOGE("no more track names available");
2831 }
2832 mVolume[0] = 1.0f;
2833 mVolume[1] = 1.0f;
2834 mStreamType = streamType;
2835 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
2836 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
2837 mCblk->frameSize = AudioSystem::isLinearPCM(format) ? channelCount * sizeof(int16_t) : sizeof(int8_t);
Eric Laurenta553c252009-07-17 12:17:14 -07002838 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002839}
2840
Eric Laurenta553c252009-07-17 12:17:14 -07002841AudioFlinger::PlaybackThread::Track::~Track()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002842{
Eric Laurenta553c252009-07-17 12:17:14 -07002843 LOGV("PlaybackThread::Track destructor");
2844 sp<ThreadBase> thread = mThread.promote();
2845 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08002846 Mutex::Autolock _l(thread->mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07002847 mState = TERMINATED;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002848 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002849}
2850
Eric Laurenta553c252009-07-17 12:17:14 -07002851void AudioFlinger::PlaybackThread::Track::destroy()
2852{
2853 // NOTE: destroyTrack_l() can remove a strong reference to this Track
2854 // by removing it from mTracks vector, so there is a risk that this Tracks's
2855 // desctructor is called. As the destructor needs to lock mLock,
2856 // we must acquire a strong reference on this Track before locking mLock
2857 // here so that the destructor is called only when exiting this function.
2858 // On the other hand, as long as Track::destroy() is only called by
2859 // TrackHandle destructor, the TrackHandle still holds a strong ref on
2860 // this Track with its member mTrack.
2861 sp<Track> keep(this);
2862 { // scope for mLock
2863 sp<ThreadBase> thread = mThread.promote();
2864 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08002865 if (!isOutputTrack()) {
2866 if (mState == ACTIVE || mState == RESUMING) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002867 AudioSystem::stopOutput(thread->id(),
2868 (AudioSystem::stream_type)mStreamType,
2869 mSessionId);
Gloria Wang9b3f1522011-02-24 14:51:45 -08002870
2871 // to track the speaker usage
2872 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurentac196e12009-12-01 02:17:41 -08002873 }
2874 AudioSystem::releaseOutput(thread->id());
Eric Laurent49f02be2009-11-19 09:00:56 -08002875 }
Eric Laurenta553c252009-07-17 12:17:14 -07002876 Mutex::Autolock _l(thread->mLock);
2877 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2878 playbackThread->destroyTrack_l(this);
2879 }
2880 }
2881}
2882
2883void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002884{
Eric Laurent65b65452010-06-01 23:49:17 -07002885 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 -07002886 mName - AudioMixer::TRACK0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002887 (mClient == NULL) ? getpid() : mClient->pid(),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002888 mStreamType,
2889 mFormat,
Eric Laurentb0a01472010-05-14 05:45:46 -07002890 mCblk->channelCount,
Eric Laurent65b65452010-06-01 23:49:17 -07002891 mSessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002892 mFrameCount,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002893 mState,
2894 mMute,
2895 mFillingUpStatus,
2896 mCblk->sampleRate,
2897 mCblk->volume[0],
2898 mCblk->volume[1],
2899 mCblk->server,
Eric Laurent65b65452010-06-01 23:49:17 -07002900 mCblk->user,
2901 (int)mMainBuffer,
2902 (int)mAuxBuffer);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002903}
2904
Eric Laurenta553c252009-07-17 12:17:14 -07002905status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002906{
2907 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002908 uint32_t framesReady;
2909 uint32_t framesReq = buffer->frameCount;
2910
2911 // Check if last stepServer failed, try to step now
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002912 if (mFlags & TrackBase::STEPSERVER_FAILED) {
2913 if (!step()) goto getNextBuffer_exit;
2914 LOGV("stepServer recovered");
2915 mFlags &= ~TrackBase::STEPSERVER_FAILED;
2916 }
2917
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002918 framesReady = cblk->framesReady();
2919
2920 if (LIKELY(framesReady)) {
2921 uint32_t s = cblk->server;
2922 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
2923
2924 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
2925 if (framesReq > framesReady) {
2926 framesReq = framesReady;
2927 }
2928 if (s + framesReq > bufferEnd) {
2929 framesReq = bufferEnd - s;
2930 }
2931
2932 buffer->raw = getBuffer(s, framesReq);
2933 if (buffer->raw == 0) goto getNextBuffer_exit;
2934
2935 buffer->frameCount = framesReq;
2936 return NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002937 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002938
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002939getNextBuffer_exit:
2940 buffer->raw = 0;
2941 buffer->frameCount = 0;
Eric Laurent62443f52009-10-05 20:29:18 -07002942 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 -07002943 return NOT_ENOUGH_DATA;
2944}
2945
Eric Laurenta553c252009-07-17 12:17:14 -07002946bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurent9a30fc12010-10-05 14:41:42 -07002947 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002948
2949 if (mCblk->framesReady() >= mCblk->frameCount ||
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002950 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002951 mFillingUpStatus = FS_FILLED;
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002952 mCblk->flags &= ~CBLK_FORCEREADY_MSK;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002953 return true;
2954 }
2955 return false;
2956}
2957
Eric Laurenta553c252009-07-17 12:17:14 -07002958status_t AudioFlinger::PlaybackThread::Track::start()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002959{
Eric Laurent49f02be2009-11-19 09:00:56 -08002960 status_t status = NO_ERROR;
Eric Laurent0d7e0482010-07-19 06:24:46 -07002961 LOGV("start(%d), calling thread %d session %d",
2962 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Eric Laurenta553c252009-07-17 12:17:14 -07002963 sp<ThreadBase> thread = mThread.promote();
2964 if (thread != 0) {
2965 Mutex::Autolock _l(thread->mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08002966 int state = mState;
2967 // here the track could be either new, or restarted
2968 // in both cases "unstop" the track
2969 if (mState == PAUSED) {
2970 mState = TrackBase::RESUMING;
2971 LOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
2972 } else {
2973 mState = TrackBase::ACTIVE;
2974 LOGV("? => ACTIVE (%d) on thread %p", mName, this);
2975 }
2976
2977 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
2978 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002979 status = AudioSystem::startOutput(thread->id(),
2980 (AudioSystem::stream_type)mStreamType,
2981 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08002982 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08002983
2984 // to track the speaker usage
2985 if (status == NO_ERROR) {
2986 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2987 }
Eric Laurent49f02be2009-11-19 09:00:56 -08002988 }
2989 if (status == NO_ERROR) {
2990 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2991 playbackThread->addTrack_l(this);
2992 } else {
2993 mState = state;
2994 }
2995 } else {
2996 status = BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -07002997 }
Eric Laurent49f02be2009-11-19 09:00:56 -08002998 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002999}
3000
Eric Laurenta553c252009-07-17 12:17:14 -07003001void AudioFlinger::PlaybackThread::Track::stop()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003002{
Eric Laurenta553c252009-07-17 12:17:14 -07003003 LOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3004 sp<ThreadBase> thread = mThread.promote();
3005 if (thread != 0) {
3006 Mutex::Autolock _l(thread->mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08003007 int state = mState;
Eric Laurenta553c252009-07-17 12:17:14 -07003008 if (mState > STOPPED) {
3009 mState = STOPPED;
3010 // If the track is not active (PAUSED and buffers full), flush buffers
3011 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3012 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3013 reset();
3014 }
Eric Laurent62443f52009-10-05 20:29:18 -07003015 LOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003016 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003017 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3018 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003019 AudioSystem::stopOutput(thread->id(),
3020 (AudioSystem::stream_type)mStreamType,
3021 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003022 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003023
3024 // to track the speaker usage
3025 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent49f02be2009-11-19 09:00:56 -08003026 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003027 }
3028}
3029
Eric Laurenta553c252009-07-17 12:17:14 -07003030void AudioFlinger::PlaybackThread::Track::pause()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003031{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003032 LOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurenta553c252009-07-17 12:17:14 -07003033 sp<ThreadBase> thread = mThread.promote();
3034 if (thread != 0) {
3035 Mutex::Autolock _l(thread->mLock);
3036 if (mState == ACTIVE || mState == RESUMING) {
3037 mState = PAUSING;
Eric Laurent62443f52009-10-05 20:29:18 -07003038 LOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurent49f02be2009-11-19 09:00:56 -08003039 if (!isOutputTrack()) {
3040 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003041 AudioSystem::stopOutput(thread->id(),
3042 (AudioSystem::stream_type)mStreamType,
3043 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003044 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003045
3046 // to track the speaker usage
3047 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent49f02be2009-11-19 09:00:56 -08003048 }
Eric Laurenta553c252009-07-17 12:17:14 -07003049 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003050 }
3051}
3052
Eric Laurenta553c252009-07-17 12:17:14 -07003053void AudioFlinger::PlaybackThread::Track::flush()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003054{
3055 LOGV("flush(%d)", mName);
Eric Laurenta553c252009-07-17 12:17:14 -07003056 sp<ThreadBase> thread = mThread.promote();
3057 if (thread != 0) {
3058 Mutex::Autolock _l(thread->mLock);
3059 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3060 return;
3061 }
3062 // No point remaining in PAUSED state after a flush => go to
3063 // STOPPED state
3064 mState = STOPPED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003065
Eric Laurenta553c252009-07-17 12:17:14 -07003066 mCblk->lock.lock();
3067 // NOTE: reset() will reset cblk->user and cblk->server with
3068 // the risk that at the same time, the AudioMixer is trying to read
3069 // data. In this case, getNextBuffer() would return a NULL pointer
3070 // as audio buffer => the AudioMixer code MUST always test that pointer
3071 // returned by getNextBuffer() is not NULL!
3072 reset();
3073 mCblk->lock.unlock();
3074 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003075}
3076
Eric Laurenta553c252009-07-17 12:17:14 -07003077void AudioFlinger::PlaybackThread::Track::reset()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003078{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003079 // Do not reset twice to avoid discarding data written just after a flush and before
3080 // the audioflinger thread detects the track is stopped.
3081 if (!mResetDone) {
3082 TrackBase::reset();
3083 // Force underrun condition to avoid false underrun callback until first data is
3084 // written to buffer
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003085 mCblk->flags |= CBLK_UNDERRUN_ON;
3086 mCblk->flags &= ~CBLK_FORCEREADY_MSK;
Eric Laurenta553c252009-07-17 12:17:14 -07003087 mFillingUpStatus = FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003088 mResetDone = true;
3089 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003090}
3091
Eric Laurenta553c252009-07-17 12:17:14 -07003092void AudioFlinger::PlaybackThread::Track::mute(bool muted)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003093{
3094 mMute = muted;
3095}
3096
Eric Laurenta553c252009-07-17 12:17:14 -07003097void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003098{
3099 mVolume[0] = left;
3100 mVolume[1] = right;
3101}
3102
Eric Laurent65b65452010-06-01 23:49:17 -07003103status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3104{
3105 status_t status = DEAD_OBJECT;
3106 sp<ThreadBase> thread = mThread.promote();
3107 if (thread != 0) {
3108 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3109 status = playbackThread->attachAuxEffect(this, EffectId);
3110 }
3111 return status;
3112}
3113
3114void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3115{
3116 mAuxEffectId = EffectId;
3117 mAuxBuffer = buffer;
3118}
3119
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003120// ----------------------------------------------------------------------------
3121
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003122// RecordTrack constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07003123AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3124 const wp<ThreadBase>& thread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003125 const sp<Client>& client,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003126 uint32_t sampleRate,
3127 int format,
3128 int channelCount,
3129 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07003130 uint32_t flags,
3131 int sessionId)
Eric Laurenta553c252009-07-17 12:17:14 -07003132 : TrackBase(thread, client, sampleRate, format,
Eric Laurent65b65452010-06-01 23:49:17 -07003133 channelCount, frameCount, flags, 0, sessionId),
Eric Laurenta553c252009-07-17 12:17:14 -07003134 mOverflow(false)
3135{
Eric Laurent8a77a992009-09-09 05:16:08 -07003136 if (mCblk != NULL) {
3137 LOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
3138 if (format == AudioSystem::PCM_16_BIT) {
3139 mCblk->frameSize = channelCount * sizeof(int16_t);
3140 } else if (format == AudioSystem::PCM_8_BIT) {
3141 mCblk->frameSize = channelCount * sizeof(int8_t);
3142 } else {
3143 mCblk->frameSize = sizeof(int8_t);
3144 }
3145 }
Eric Laurenta553c252009-07-17 12:17:14 -07003146}
3147
3148AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003149{
Eric Laurent49f02be2009-11-19 09:00:56 -08003150 sp<ThreadBase> thread = mThread.promote();
3151 if (thread != 0) {
3152 AudioSystem::releaseInput(thread->id());
3153 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003154}
3155
Eric Laurenta553c252009-07-17 12:17:14 -07003156status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003157{
3158 audio_track_cblk_t* cblk = this->cblk();
3159 uint32_t framesAvail;
3160 uint32_t framesReq = buffer->frameCount;
3161
3162 // Check if last stepServer failed, try to step now
3163 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3164 if (!step()) goto getNextBuffer_exit;
3165 LOGV("stepServer recovered");
3166 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3167 }
3168
3169 framesAvail = cblk->framesAvailable_l();
3170
3171 if (LIKELY(framesAvail)) {
3172 uint32_t s = cblk->server;
3173 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3174
3175 if (framesReq > framesAvail) {
3176 framesReq = framesAvail;
3177 }
3178 if (s + framesReq > bufferEnd) {
3179 framesReq = bufferEnd - s;
3180 }
3181
3182 buffer->raw = getBuffer(s, framesReq);
3183 if (buffer->raw == 0) goto getNextBuffer_exit;
3184
3185 buffer->frameCount = framesReq;
3186 return NO_ERROR;
3187 }
3188
3189getNextBuffer_exit:
3190 buffer->raw = 0;
3191 buffer->frameCount = 0;
3192 return NOT_ENOUGH_DATA;
3193}
3194
Eric Laurenta553c252009-07-17 12:17:14 -07003195status_t AudioFlinger::RecordThread::RecordTrack::start()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003196{
Eric Laurenta553c252009-07-17 12:17:14 -07003197 sp<ThreadBase> thread = mThread.promote();
3198 if (thread != 0) {
3199 RecordThread *recordThread = (RecordThread *)thread.get();
3200 return recordThread->start(this);
Eric Laurent49f02be2009-11-19 09:00:56 -08003201 } else {
3202 return BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -07003203 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003204}
3205
Eric Laurenta553c252009-07-17 12:17:14 -07003206void AudioFlinger::RecordThread::RecordTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003207{
Eric Laurenta553c252009-07-17 12:17:14 -07003208 sp<ThreadBase> thread = mThread.promote();
3209 if (thread != 0) {
3210 RecordThread *recordThread = (RecordThread *)thread.get();
3211 recordThread->stop(this);
3212 TrackBase::reset();
3213 // Force overerrun condition to avoid false overrun callback until first data is
3214 // read from buffer
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003215 mCblk->flags |= CBLK_UNDERRUN_ON;
Eric Laurenta553c252009-07-17 12:17:14 -07003216 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003217}
3218
Eric Laurent3fdb1262009-11-07 00:01:32 -08003219void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3220{
Eric Laurent65b65452010-06-01 23:49:17 -07003221 snprintf(buffer, size, " %05d %03u %03u %05d %04u %01d %05u %08x %08x\n",
Eric Laurent3fdb1262009-11-07 00:01:32 -08003222 (mClient == NULL) ? getpid() : mClient->pid(),
3223 mFormat,
Eric Laurentb0a01472010-05-14 05:45:46 -07003224 mCblk->channelCount,
Eric Laurent65b65452010-06-01 23:49:17 -07003225 mSessionId,
Eric Laurent3fdb1262009-11-07 00:01:32 -08003226 mFrameCount,
3227 mState,
3228 mCblk->sampleRate,
3229 mCblk->server,
3230 mCblk->user);
3231}
3232
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003233
3234// ----------------------------------------------------------------------------
3235
Eric Laurenta553c252009-07-17 12:17:14 -07003236AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3237 const wp<ThreadBase>& thread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003238 DuplicatingThread *sourceThread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003239 uint32_t sampleRate,
3240 int format,
3241 int channelCount,
3242 int frameCount)
Eric Laurent65b65452010-06-01 23:49:17 -07003243 : Track(thread, NULL, AudioSystem::NUM_STREAM_TYPES, sampleRate, format, channelCount, frameCount, NULL, 0),
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003244 mActive(false), mSourceThread(sourceThread)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003245{
Eric Laurenta553c252009-07-17 12:17:14 -07003246
3247 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
Eric Laurent6c30a712009-08-10 23:22:32 -07003248 if (mCblk != NULL) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003249 mCblk->flags |= CBLK_DIRECTION_OUT;
Eric Laurent6c30a712009-08-10 23:22:32 -07003250 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
3251 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
3252 mOutBuffer.frameCount = 0;
Eric Laurent6c30a712009-08-10 23:22:32 -07003253 playbackThread->mTracks.add(this);
Eric Laurentb0a01472010-05-14 05:45:46 -07003254 LOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, mCblk->frameCount %d, mCblk->sampleRate %d, mCblk->channelCount %d mBufferEnd %p",
3255 mCblk, mBuffer, mCblk->buffers, mCblk->frameCount, mCblk->sampleRate, mCblk->channelCount, mBufferEnd);
Eric Laurent6c30a712009-08-10 23:22:32 -07003256 } else {
3257 LOGW("Error creating output track on thread %p", playbackThread);
3258 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003259}
3260
Eric Laurenta553c252009-07-17 12:17:14 -07003261AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003262{
Eric Laurent6c30a712009-08-10 23:22:32 -07003263 clearBufferQueue();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003264}
3265
Eric Laurenta553c252009-07-17 12:17:14 -07003266status_t AudioFlinger::PlaybackThread::OutputTrack::start()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003267{
3268 status_t status = Track::start();
Eric Laurenta553c252009-07-17 12:17:14 -07003269 if (status != NO_ERROR) {
3270 return status;
3271 }
3272
3273 mActive = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003274 mRetryCount = 127;
3275 return status;
3276}
3277
Eric Laurenta553c252009-07-17 12:17:14 -07003278void AudioFlinger::PlaybackThread::OutputTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003279{
3280 Track::stop();
3281 clearBufferQueue();
3282 mOutBuffer.frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003283 mActive = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003284}
3285
Eric Laurenta553c252009-07-17 12:17:14 -07003286bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003287{
3288 Buffer *pInBuffer;
3289 Buffer inBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003290 uint32_t channelCount = mCblk->channelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003291 bool outputBufferFull = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003292 inBuffer.frameCount = frames;
3293 inBuffer.i16 = data;
Eric Laurenta553c252009-07-17 12:17:14 -07003294
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003295 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
Eric Laurenta553c252009-07-17 12:17:14 -07003296
Eric Laurent62443f52009-10-05 20:29:18 -07003297 if (!mActive && frames != 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003298 start();
3299 sp<ThreadBase> thread = mThread.promote();
3300 if (thread != 0) {
3301 MixerThread *mixerThread = (MixerThread *)thread.get();
3302 if (mCblk->frameCount > frames){
3303 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3304 uint32_t startFrames = (mCblk->frameCount - frames);
3305 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003306 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
Eric Laurenta553c252009-07-17 12:17:14 -07003307 pInBuffer->frameCount = startFrames;
3308 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003309 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
Eric Laurenta553c252009-07-17 12:17:14 -07003310 mBufferQueue.add(pInBuffer);
3311 } else {
3312 LOGW ("OutputTrack::write() %p no more buffers in queue", this);
3313 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003314 }
Eric Laurenta553c252009-07-17 12:17:14 -07003315 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003316 }
3317
Eric Laurenta553c252009-07-17 12:17:14 -07003318 while (waitTimeLeftMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003319 // First write pending buffers, then new data
3320 if (mBufferQueue.size()) {
3321 pInBuffer = mBufferQueue.itemAt(0);
3322 } else {
3323 pInBuffer = &inBuffer;
3324 }
Eric Laurenta553c252009-07-17 12:17:14 -07003325
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003326 if (pInBuffer->frameCount == 0) {
3327 break;
3328 }
Eric Laurenta553c252009-07-17 12:17:14 -07003329
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003330 if (mOutBuffer.frameCount == 0) {
3331 mOutBuffer.frameCount = pInBuffer->frameCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003332 nsecs_t startTime = systemTime();
3333 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003334 LOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Eric Laurenta553c252009-07-17 12:17:14 -07003335 outputBufferFull = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003336 break;
3337 }
Eric Laurenta553c252009-07-17 12:17:14 -07003338 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
Eric Laurenta553c252009-07-17 12:17:14 -07003339 if (waitTimeLeftMs >= waitTimeMs) {
3340 waitTimeLeftMs -= waitTimeMs;
3341 } else {
3342 waitTimeLeftMs = 0;
3343 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003344 }
Eric Laurenta553c252009-07-17 12:17:14 -07003345
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003346 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
Eric Laurentb0a01472010-05-14 05:45:46 -07003347 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003348 mCblk->stepUser(outFrames);
3349 pInBuffer->frameCount -= outFrames;
Eric Laurentb0a01472010-05-14 05:45:46 -07003350 pInBuffer->i16 += outFrames * channelCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003351 mOutBuffer.frameCount -= outFrames;
Eric Laurentb0a01472010-05-14 05:45:46 -07003352 mOutBuffer.i16 += outFrames * channelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003353
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003354 if (pInBuffer->frameCount == 0) {
3355 if (mBufferQueue.size()) {
3356 mBufferQueue.removeAt(0);
3357 delete [] pInBuffer->mBuffer;
3358 delete pInBuffer;
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003359 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 -08003360 } else {
3361 break;
3362 }
3363 }
3364 }
Eric Laurenta553c252009-07-17 12:17:14 -07003365
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003366 // If we could not write all frames, allocate a buffer and queue it for next time.
3367 if (inBuffer.frameCount) {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003368 sp<ThreadBase> thread = mThread.promote();
3369 if (thread != 0 && !thread->standby()) {
3370 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3371 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003372 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003373 pInBuffer->frameCount = inBuffer.frameCount;
3374 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003375 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003376 mBufferQueue.add(pInBuffer);
3377 LOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
3378 } else {
3379 LOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
3380 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003381 }
3382 }
Eric Laurenta553c252009-07-17 12:17:14 -07003383
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003384 // Calling write() with a 0 length buffer, means that no more data will be written:
Eric Laurenta553c252009-07-17 12:17:14 -07003385 // 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 -08003386 // by output mixer.
Eric Laurenta553c252009-07-17 12:17:14 -07003387 if (frames == 0 && mBufferQueue.size() == 0) {
3388 if (mCblk->user < mCblk->frameCount) {
3389 frames = mCblk->frameCount - mCblk->user;
3390 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003391 pInBuffer->mBuffer = new int16_t[frames * channelCount];
Eric Laurenta553c252009-07-17 12:17:14 -07003392 pInBuffer->frameCount = frames;
3393 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003394 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
Eric Laurenta553c252009-07-17 12:17:14 -07003395 mBufferQueue.add(pInBuffer);
Eric Laurent62443f52009-10-05 20:29:18 -07003396 } else if (mActive) {
Eric Laurenta553c252009-07-17 12:17:14 -07003397 stop();
3398 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003399 }
3400
Eric Laurenta553c252009-07-17 12:17:14 -07003401 return outputBufferFull;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003402}
3403
Eric Laurenta553c252009-07-17 12:17:14 -07003404status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003405{
3406 int active;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003407 status_t result;
3408 audio_track_cblk_t* cblk = mCblk;
3409 uint32_t framesReq = buffer->frameCount;
3410
Eric Laurenta553c252009-07-17 12:17:14 -07003411// LOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003412 buffer->frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003413
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003414 uint32_t framesAvail = cblk->framesAvailable();
3415
Eric Laurenta553c252009-07-17 12:17:14 -07003416
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003417 if (framesAvail == 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003418 Mutex::Autolock _l(cblk->lock);
3419 goto start_loop_here;
3420 while (framesAvail == 0) {
3421 active = mActive;
3422 if (UNLIKELY(!active)) {
3423 LOGV("Not active and NO_MORE_BUFFERS");
3424 return AudioTrack::NO_MORE_BUFFERS;
3425 }
3426 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3427 if (result != NO_ERROR) {
3428 return AudioTrack::NO_MORE_BUFFERS;
3429 }
3430 // read the server count again
3431 start_loop_here:
3432 framesAvail = cblk->framesAvailable_l();
3433 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003434 }
3435
Eric Laurenta553c252009-07-17 12:17:14 -07003436// if (framesAvail < framesReq) {
3437// return AudioTrack::NO_MORE_BUFFERS;
3438// }
3439
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003440 if (framesReq > framesAvail) {
3441 framesReq = framesAvail;
3442 }
3443
3444 uint32_t u = cblk->user;
3445 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
3446
3447 if (u + framesReq > bufferEnd) {
3448 framesReq = bufferEnd - u;
3449 }
3450
3451 buffer->frameCount = framesReq;
3452 buffer->raw = (void *)cblk->buffer(u);
3453 return NO_ERROR;
3454}
3455
3456
Eric Laurenta553c252009-07-17 12:17:14 -07003457void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003458{
3459 size_t size = mBufferQueue.size();
3460 Buffer *pBuffer;
Eric Laurenta553c252009-07-17 12:17:14 -07003461
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003462 for (size_t i = 0; i < size; i++) {
3463 pBuffer = mBufferQueue.itemAt(i);
3464 delete [] pBuffer->mBuffer;
3465 delete pBuffer;
3466 }
3467 mBufferQueue.clear();
3468}
3469
3470// ----------------------------------------------------------------------------
3471
3472AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
3473 : RefBase(),
3474 mAudioFlinger(audioFlinger),
Mathias Agopian6faf7892010-01-25 19:00:00 -08003475 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003476 mPid(pid)
3477{
3478 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
3479}
3480
Eric Laurentb9481d82009-09-17 05:12:56 -07003481// Client destructor must be called with AudioFlinger::mLock held
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003482AudioFlinger::Client::~Client()
3483{
Eric Laurentb9481d82009-09-17 05:12:56 -07003484 mAudioFlinger->removeClient_l(mPid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003485}
3486
3487const sp<MemoryDealer>& AudioFlinger::Client::heap() const
3488{
3489 return mMemoryDealer;
3490}
3491
3492// ----------------------------------------------------------------------------
3493
Eric Laurent4f0f17d2010-05-12 02:05:53 -07003494AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
3495 const sp<IAudioFlingerClient>& client,
3496 pid_t pid)
3497 : mAudioFlinger(audioFlinger), mPid(pid), mClient(client)
3498{
3499}
3500
3501AudioFlinger::NotificationClient::~NotificationClient()
3502{
3503 mClient.clear();
3504}
3505
3506void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
3507{
3508 sp<NotificationClient> keep(this);
3509 {
3510 mAudioFlinger->removeNotificationClient(mPid);
3511 }
3512}
3513
3514// ----------------------------------------------------------------------------
3515
Eric Laurenta553c252009-07-17 12:17:14 -07003516AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003517 : BnAudioTrack(),
3518 mTrack(track)
3519{
3520}
3521
3522AudioFlinger::TrackHandle::~TrackHandle() {
3523 // just stop the track on deletion, associated resources
3524 // will be freed from the main thread once all pending buffers have
3525 // been played. Unless it's not in the active track list, in which
3526 // case we free everything now...
3527 mTrack->destroy();
3528}
3529
3530status_t AudioFlinger::TrackHandle::start() {
3531 return mTrack->start();
3532}
3533
3534void AudioFlinger::TrackHandle::stop() {
3535 mTrack->stop();
3536}
3537
3538void AudioFlinger::TrackHandle::flush() {
3539 mTrack->flush();
3540}
3541
3542void AudioFlinger::TrackHandle::mute(bool e) {
3543 mTrack->mute(e);
3544}
3545
3546void AudioFlinger::TrackHandle::pause() {
3547 mTrack->pause();
3548}
3549
3550void AudioFlinger::TrackHandle::setVolume(float left, float right) {
3551 mTrack->setVolume(left, right);
3552}
3553
3554sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
3555 return mTrack->getCblk();
3556}
3557
Eric Laurent65b65452010-06-01 23:49:17 -07003558status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
3559{
3560 return mTrack->attachAuxEffect(EffectId);
3561}
3562
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003563status_t AudioFlinger::TrackHandle::onTransact(
3564 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3565{
3566 return BnAudioTrack::onTransact(code, data, reply, flags);
3567}
3568
3569// ----------------------------------------------------------------------------
3570
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003571sp<IAudioRecord> AudioFlinger::openRecord(
3572 pid_t pid,
Eric Laurentddb78e72009-07-28 08:44:33 -07003573 int input,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003574 uint32_t sampleRate,
3575 int format,
3576 int channelCount,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003577 int frameCount,
3578 uint32_t flags,
Eric Laurent65b65452010-06-01 23:49:17 -07003579 int *sessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003580 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003581{
Eric Laurenta553c252009-07-17 12:17:14 -07003582 sp<RecordThread::RecordTrack> recordTrack;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003583 sp<RecordHandle> recordHandle;
3584 sp<Client> client;
3585 wp<Client> wclient;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003586 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07003587 RecordThread *thread;
3588 size_t inFrameCount;
Eric Laurent65b65452010-06-01 23:49:17 -07003589 int lSessionId;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003590
3591 // check calling permissions
3592 if (!recordingAllowed()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003593 lStatus = PERMISSION_DENIED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003594 goto Exit;
3595 }
3596
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003597 // add client to list
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003598 { // scope for mLock
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003599 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07003600 thread = checkRecordThread_l(input);
3601 if (thread == NULL) {
3602 lStatus = BAD_VALUE;
3603 goto Exit;
3604 }
3605
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003606 wclient = mClients.valueFor(pid);
3607 if (wclient != NULL) {
3608 client = wclient.promote();
3609 } else {
3610 client = new Client(this, pid);
3611 mClients.add(pid, client);
3612 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003613
Eric Laurent65b65452010-06-01 23:49:17 -07003614 // If no audio session id is provided, create one here
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003615 if (sessionId != NULL && *sessionId != AudioSystem::SESSION_OUTPUT_MIX) {
Eric Laurent65b65452010-06-01 23:49:17 -07003616 lSessionId = *sessionId;
3617 } else {
Eric Laurentf3d6dd02010-11-18 08:40:16 -08003618 lSessionId = nextUniqueId_l();
Eric Laurent65b65452010-06-01 23:49:17 -07003619 if (sessionId != NULL) {
3620 *sessionId = lSessionId;
3621 }
3622 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003623 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurenta553c252009-07-17 12:17:14 -07003624 recordTrack = new RecordThread::RecordTrack(thread, client, sampleRate,
Eric Laurent65b65452010-06-01 23:49:17 -07003625 format, channelCount, frameCount, flags, lSessionId);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003626 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003627 if (recordTrack->getCblk() == NULL) {
Eric Laurentb9481d82009-09-17 05:12:56 -07003628 // remove local strong reference to Client before deleting the RecordTrack so that the Client
3629 // destructor is called by the TrackBase destructor with mLock held
3630 client.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003631 recordTrack.clear();
3632 lStatus = NO_MEMORY;
3633 goto Exit;
3634 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003635
3636 // return to handle to client
3637 recordHandle = new RecordHandle(recordTrack);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003638 lStatus = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003639
3640Exit:
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003641 if (status) {
3642 *status = lStatus;
3643 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003644 return recordHandle;
3645}
3646
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003647// ----------------------------------------------------------------------------
3648
Eric Laurenta553c252009-07-17 12:17:14 -07003649AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003650 : BnAudioRecord(),
3651 mRecordTrack(recordTrack)
3652{
3653}
3654
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003655AudioFlinger::RecordHandle::~RecordHandle() {
3656 stop();
3657}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003658
3659status_t AudioFlinger::RecordHandle::start() {
3660 LOGV("RecordHandle::start()");
3661 return mRecordTrack->start();
3662}
3663
3664void AudioFlinger::RecordHandle::stop() {
3665 LOGV("RecordHandle::stop()");
3666 mRecordTrack->stop();
3667}
3668
3669sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
3670 return mRecordTrack->getCblk();
3671}
3672
3673status_t AudioFlinger::RecordHandle::onTransact(
3674 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3675{
3676 return BnAudioRecord::onTransact(code, data, reply, flags);
3677}
3678
3679// ----------------------------------------------------------------------------
3680
Eric Laurent49f02be2009-11-19 09:00:56 -08003681AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger, AudioStreamIn *input, uint32_t sampleRate, uint32_t channels, int id) :
3682 ThreadBase(audioFlinger, id),
Eric Laurenta553c252009-07-17 12:17:14 -07003683 mInput(input), mResampler(0), mRsmpOutBuffer(0), mRsmpInBuffer(0)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003684{
Eric Laurenta553c252009-07-17 12:17:14 -07003685 mReqChannelCount = AudioSystem::popCount(channels);
3686 mReqSampleRate = sampleRate;
3687 readInputParameters();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003688}
3689
Eric Laurenta553c252009-07-17 12:17:14 -07003690
3691AudioFlinger::RecordThread::~RecordThread()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003692{
Eric Laurenta553c252009-07-17 12:17:14 -07003693 delete[] mRsmpInBuffer;
3694 if (mResampler != 0) {
3695 delete mResampler;
3696 delete[] mRsmpOutBuffer;
3697 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003698}
3699
Eric Laurenta553c252009-07-17 12:17:14 -07003700void AudioFlinger::RecordThread::onFirstRef()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003701{
Eric Laurenta553c252009-07-17 12:17:14 -07003702 const size_t SIZE = 256;
3703 char buffer[SIZE];
3704
3705 snprintf(buffer, SIZE, "Record Thread %p", this);
3706
3707 run(buffer, PRIORITY_URGENT_AUDIO);
3708}
Eric Laurent49f02be2009-11-19 09:00:56 -08003709
Eric Laurenta553c252009-07-17 12:17:14 -07003710bool AudioFlinger::RecordThread::threadLoop()
3711{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003712 AudioBufferProvider::Buffer buffer;
Eric Laurenta553c252009-07-17 12:17:14 -07003713 sp<RecordTrack> activeTrack;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003714
Eric Laurent4712baa2010-09-30 16:12:31 -07003715 nsecs_t lastWarning = 0;
3716
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003717 // start recording
3718 while (!exitPending()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003719
Eric Laurenta553c252009-07-17 12:17:14 -07003720 processConfigEvents();
3721
3722 { // scope for mLock
3723 Mutex::Autolock _l(mLock);
3724 checkForNewParameters_l();
3725 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
3726 if (!mStandby) {
3727 mInput->standby();
3728 mStandby = true;
3729 }
3730
3731 if (exitPending()) break;
3732
3733 LOGV("RecordThread: loop stopping");
3734 // go to sleep
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003735 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07003736 LOGV("RecordThread: loop starting");
3737 continue;
3738 }
3739 if (mActiveTrack != 0) {
3740 if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a2009-12-05 05:20:01 -08003741 if (!mStandby) {
3742 mInput->standby();
3743 mStandby = true;
3744 }
Eric Laurenta553c252009-07-17 12:17:14 -07003745 mActiveTrack.clear();
3746 mStartStopCond.broadcast();
3747 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
Eric Laurenta553c252009-07-17 12:17:14 -07003748 if (mReqChannelCount != mActiveTrack->channelCount()) {
3749 mActiveTrack.clear();
Eric Laurent9cc489a2009-12-05 05:20:01 -08003750 mStartStopCond.broadcast();
3751 } else if (mBytesRead != 0) {
3752 // record start succeeds only if first read from audio input
3753 // succeeds
3754 if (mBytesRead > 0) {
3755 mActiveTrack->mState = TrackBase::ACTIVE;
3756 } else {
3757 mActiveTrack.clear();
3758 }
3759 mStartStopCond.broadcast();
Eric Laurenta553c252009-07-17 12:17:14 -07003760 }
Eric Laurent9cc489a2009-12-05 05:20:01 -08003761 mStandby = false;
Eric Laurenta553c252009-07-17 12:17:14 -07003762 }
Eric Laurenta553c252009-07-17 12:17:14 -07003763 }
3764 }
3765
3766 if (mActiveTrack != 0) {
Eric Laurent9cc489a2009-12-05 05:20:01 -08003767 if (mActiveTrack->mState != TrackBase::ACTIVE &&
3768 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent49f02be2009-11-19 09:00:56 -08003769 usleep(5000);
3770 continue;
3771 }
Eric Laurenta553c252009-07-17 12:17:14 -07003772 buffer.frameCount = mFrameCount;
3773 if (LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
3774 size_t framesOut = buffer.frameCount;
3775 if (mResampler == 0) {
3776 // no resampling
3777 while (framesOut) {
3778 size_t framesIn = mFrameCount - mRsmpInIndex;
3779 if (framesIn) {
3780 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
3781 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
3782 if (framesIn > framesOut)
3783 framesIn = framesOut;
3784 mRsmpInIndex += framesIn;
3785 framesOut -= framesIn;
Eric Laurentb0a01472010-05-14 05:45:46 -07003786 if ((int)mChannelCount == mReqChannelCount ||
Eric Laurenta553c252009-07-17 12:17:14 -07003787 mFormat != AudioSystem::PCM_16_BIT) {
3788 memcpy(dst, src, framesIn * mFrameSize);
3789 } else {
3790 int16_t *src16 = (int16_t *)src;
3791 int16_t *dst16 = (int16_t *)dst;
3792 if (mChannelCount == 1) {
3793 while (framesIn--) {
3794 *dst16++ = *src16;
3795 *dst16++ = *src16++;
3796 }
3797 } else {
3798 while (framesIn--) {
3799 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
3800 src16 += 2;
3801 }
3802 }
3803 }
3804 }
3805 if (framesOut && mFrameCount == mRsmpInIndex) {
Eric Laurenta553c252009-07-17 12:17:14 -07003806 if (framesOut == mFrameCount &&
Eric Laurentb0a01472010-05-14 05:45:46 -07003807 ((int)mChannelCount == mReqChannelCount || mFormat != AudioSystem::PCM_16_BIT)) {
Eric Laurent9cc489a2009-12-05 05:20:01 -08003808 mBytesRead = mInput->read(buffer.raw, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07003809 framesOut = 0;
3810 } else {
Eric Laurent9cc489a2009-12-05 05:20:01 -08003811 mBytesRead = mInput->read(mRsmpInBuffer, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07003812 mRsmpInIndex = 0;
3813 }
Eric Laurent9cc489a2009-12-05 05:20:01 -08003814 if (mBytesRead < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003815 LOGE("Error reading audio input");
Eric Laurent9cc489a2009-12-05 05:20:01 -08003816 if (mActiveTrack->mState == TrackBase::ACTIVE) {
Eric Laurentba8811f2010-03-02 18:38:06 -08003817 // Force input into standby so that it tries to
3818 // recover at next read attempt
3819 mInput->standby();
3820 usleep(5000);
Eric Laurent9cc489a2009-12-05 05:20:01 -08003821 }
Eric Laurenta553c252009-07-17 12:17:14 -07003822 mRsmpInIndex = mFrameCount;
3823 framesOut = 0;
3824 buffer.frameCount = 0;
3825 }
3826 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003827 }
3828 } else {
Eric Laurenta553c252009-07-17 12:17:14 -07003829 // resampling
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003830
Eric Laurenta553c252009-07-17 12:17:14 -07003831 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
3832 // alter output frame count as if we were expecting stereo samples
3833 if (mChannelCount == 1 && mReqChannelCount == 1) {
3834 framesOut >>= 1;
3835 }
3836 mResampler->resample(mRsmpOutBuffer, framesOut, this);
3837 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
3838 // are 32 bit aligned which should be always true.
3839 if (mChannelCount == 2 && mReqChannelCount == 1) {
3840 AudioMixer::ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
3841 // the resampler always outputs stereo samples: do post stereo to mono conversion
3842 int16_t *src = (int16_t *)mRsmpOutBuffer;
3843 int16_t *dst = buffer.i16;
3844 while (framesOut--) {
3845 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
3846 src += 2;
3847 }
3848 } else {
3849 AudioMixer::ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
3850 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003851
Eric Laurenta553c252009-07-17 12:17:14 -07003852 }
3853 mActiveTrack->releaseBuffer(&buffer);
3854 mActiveTrack->overflow();
3855 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003856 // client isn't retrieving buffers fast enough
3857 else {
Eric Laurent4712baa2010-09-30 16:12:31 -07003858 if (!mActiveTrack->setOverflow()) {
3859 nsecs_t now = systemTime();
3860 if ((now - lastWarning) > kWarningThrottle) {
3861 LOGW("RecordThread: buffer overflow");
3862 lastWarning = now;
3863 }
3864 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003865 // Release the processor for a while before asking for a new buffer.
3866 // This will give the application more chance to read from the buffer and
3867 // clear the overflow.
3868 usleep(5000);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003869 }
3870 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003871 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003872
Eric Laurenta553c252009-07-17 12:17:14 -07003873 if (!mStandby) {
3874 mInput->standby();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003875 }
Eric Laurenta553c252009-07-17 12:17:14 -07003876 mActiveTrack.clear();
3877
Eric Laurent49f02be2009-11-19 09:00:56 -08003878 mStartStopCond.broadcast();
3879
Eric Laurenta553c252009-07-17 12:17:14 -07003880 LOGV("RecordThread %p exiting", this);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003881 return false;
3882}
3883
Eric Laurenta553c252009-07-17 12:17:14 -07003884status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003885{
Eric Laurenta553c252009-07-17 12:17:14 -07003886 LOGV("RecordThread::start");
Eric Laurent49f02be2009-11-19 09:00:56 -08003887 sp <ThreadBase> strongMe = this;
3888 status_t status = NO_ERROR;
3889 {
3890 AutoMutex lock(&mLock);
3891 if (mActiveTrack != 0) {
3892 if (recordTrack != mActiveTrack.get()) {
3893 status = -EBUSY;
3894 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a2009-12-05 05:20:01 -08003895 mActiveTrack->mState = TrackBase::ACTIVE;
Eric Laurent49f02be2009-11-19 09:00:56 -08003896 }
3897 return status;
3898 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003899
Eric Laurent49f02be2009-11-19 09:00:56 -08003900 recordTrack->mState = TrackBase::IDLE;
3901 mActiveTrack = recordTrack;
3902 mLock.unlock();
3903 status_t status = AudioSystem::startInput(mId);
3904 mLock.lock();
3905 if (status != NO_ERROR) {
3906 mActiveTrack.clear();
3907 return status;
3908 }
Eric Laurent9cc489a2009-12-05 05:20:01 -08003909 mRsmpInIndex = mFrameCount;
3910 mBytesRead = 0;
Eric Laurent4bb21c42011-02-28 16:52:51 -08003911 if (mResampler != NULL) {
3912 mResampler->reset();
3913 }
3914 mActiveTrack->mState = TrackBase::RESUMING;
Eric Laurent49f02be2009-11-19 09:00:56 -08003915 // signal thread to start
3916 LOGV("Signal record thread");
3917 mWaitWorkCV.signal();
3918 // do not wait for mStartStopCond if exiting
3919 if (mExiting) {
3920 mActiveTrack.clear();
3921 status = INVALID_OPERATION;
3922 goto startError;
3923 }
3924 mStartStopCond.wait(mLock);
3925 if (mActiveTrack == 0) {
3926 LOGV("Record failed to start");
3927 status = BAD_VALUE;
3928 goto startError;
3929 }
Eric Laurenta553c252009-07-17 12:17:14 -07003930 LOGV("Record started OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08003931 return status;
Eric Laurenta553c252009-07-17 12:17:14 -07003932 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003933startError:
3934 AudioSystem::stopInput(mId);
3935 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003936}
3937
Eric Laurenta553c252009-07-17 12:17:14 -07003938void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
3939 LOGV("RecordThread::stop");
Eric Laurent49f02be2009-11-19 09:00:56 -08003940 sp <ThreadBase> strongMe = this;
3941 {
3942 AutoMutex lock(&mLock);
3943 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
3944 mActiveTrack->mState = TrackBase::PAUSING;
3945 // do not wait for mStartStopCond if exiting
3946 if (mExiting) {
3947 return;
3948 }
3949 mStartStopCond.wait(mLock);
3950 // if we have been restarted, recordTrack == mActiveTrack.get() here
3951 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
3952 mLock.unlock();
3953 AudioSystem::stopInput(mId);
3954 mLock.lock();
Eric Laurent9cc489a2009-12-05 05:20:01 -08003955 LOGV("Record stopped OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08003956 }
3957 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003958 }
3959}
3960
Eric Laurenta553c252009-07-17 12:17:14 -07003961status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003962{
3963 const size_t SIZE = 256;
3964 char buffer[SIZE];
3965 String8 result;
3966 pid_t pid = 0;
3967
Eric Laurent3fdb1262009-11-07 00:01:32 -08003968 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
3969 result.append(buffer);
3970
3971 if (mActiveTrack != 0) {
3972 result.append("Active Track:\n");
Eric Laurent65b65452010-06-01 23:49:17 -07003973 result.append(" Clien Fmt Chn Session Buf S SRate Serv User\n");
Eric Laurent3fdb1262009-11-07 00:01:32 -08003974 mActiveTrack->dump(buffer, SIZE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003975 result.append(buffer);
Eric Laurent3fdb1262009-11-07 00:01:32 -08003976
3977 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
3978 result.append(buffer);
3979 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
3980 result.append(buffer);
3981 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != 0));
3982 result.append(buffer);
3983 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
3984 result.append(buffer);
3985 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
3986 result.append(buffer);
3987
3988
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003989 } else {
3990 result.append("No record client\n");
3991 }
3992 write(fd, result.string(), result.size());
Eric Laurent3fdb1262009-11-07 00:01:32 -08003993
3994 dumpBase(fd, args);
3995
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003996 return NO_ERROR;
3997}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003998
Eric Laurenta553c252009-07-17 12:17:14 -07003999status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4000{
4001 size_t framesReq = buffer->frameCount;
4002 size_t framesReady = mFrameCount - mRsmpInIndex;
4003 int channelCount;
4004
4005 if (framesReady == 0) {
Eric Laurent9cc489a2009-12-05 05:20:01 -08004006 mBytesRead = mInput->read(mRsmpInBuffer, mInputBytes);
4007 if (mBytesRead < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07004008 LOGE("RecordThread::getNextBuffer() Error reading audio input");
Eric Laurent9cc489a2009-12-05 05:20:01 -08004009 if (mActiveTrack->mState == TrackBase::ACTIVE) {
Eric Laurentba8811f2010-03-02 18:38:06 -08004010 // Force input into standby so that it tries to
4011 // recover at next read attempt
4012 mInput->standby();
4013 usleep(5000);
Eric Laurent9cc489a2009-12-05 05:20:01 -08004014 }
Eric Laurenta553c252009-07-17 12:17:14 -07004015 buffer->raw = 0;
4016 buffer->frameCount = 0;
4017 return NOT_ENOUGH_DATA;
4018 }
4019 mRsmpInIndex = 0;
4020 framesReady = mFrameCount;
4021 }
4022
4023 if (framesReq > framesReady) {
4024 framesReq = framesReady;
4025 }
4026
4027 if (mChannelCount == 1 && mReqChannelCount == 2) {
4028 channelCount = 1;
4029 } else {
4030 channelCount = 2;
4031 }
4032 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4033 buffer->frameCount = framesReq;
4034 return NO_ERROR;
4035}
4036
4037void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4038{
4039 mRsmpInIndex += buffer->frameCount;
4040 buffer->frameCount = 0;
4041}
4042
4043bool AudioFlinger::RecordThread::checkForNewParameters_l()
4044{
4045 bool reconfig = false;
4046
Eric Laurent8fce46a2009-08-04 09:45:33 -07004047 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07004048 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07004049 String8 keyValuePair = mNewParameters[0];
4050 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07004051 int value;
4052 int reqFormat = mFormat;
4053 int reqSamplingRate = mReqSampleRate;
4054 int reqChannelCount = mReqChannelCount;
Eric Laurent8fce46a2009-08-04 09:45:33 -07004055
Eric Laurenta553c252009-07-17 12:17:14 -07004056 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4057 reqSamplingRate = value;
4058 reconfig = true;
4059 }
4060 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
4061 reqFormat = value;
4062 reconfig = true;
4063 }
4064 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
4065 reqChannelCount = AudioSystem::popCount(value);
4066 reconfig = true;
4067 }
4068 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4069 // do not accept frame count changes if tracks are open as the track buffer
4070 // size depends on frame count and correct behavior would not be garantied
4071 // if frame count is changed after track creation
4072 if (mActiveTrack != 0) {
4073 status = INVALID_OPERATION;
4074 } else {
4075 reconfig = true;
4076 }
4077 }
4078 if (status == NO_ERROR) {
Eric Laurent8fce46a2009-08-04 09:45:33 -07004079 status = mInput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07004080 if (status == INVALID_OPERATION) {
4081 mInput->standby();
Eric Laurent8fce46a2009-08-04 09:45:33 -07004082 status = mInput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07004083 }
4084 if (reconfig) {
4085 if (status == BAD_VALUE &&
4086 reqFormat == mInput->format() && reqFormat == AudioSystem::PCM_16_BIT &&
4087 ((int)mInput->sampleRate() <= 2 * reqSamplingRate) &&
4088 (AudioSystem::popCount(mInput->channels()) < 3) && (reqChannelCount < 3)) {
4089 status = NO_ERROR;
4090 }
4091 if (status == NO_ERROR) {
4092 readInputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07004093 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07004094 }
4095 }
4096 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08004097
4098 mNewParameters.removeAt(0);
4099
Eric Laurenta553c252009-07-17 12:17:14 -07004100 mParamStatus = status;
4101 mParamCond.signal();
Eric Laurent8fce46a2009-08-04 09:45:33 -07004102 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07004103 }
4104 return reconfig;
4105}
4106
4107String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4108{
4109 return mInput->getParameters(keys);
4110}
4111
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004112void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
Eric Laurenta553c252009-07-17 12:17:14 -07004113 AudioSystem::OutputDescriptor desc;
4114 void *param2 = 0;
4115
4116 switch (event) {
4117 case AudioSystem::INPUT_OPENED:
4118 case AudioSystem::INPUT_CONFIG_CHANGED:
Eric Laurentb0a01472010-05-14 05:45:46 -07004119 desc.channels = mChannels;
Eric Laurenta553c252009-07-17 12:17:14 -07004120 desc.samplingRate = mSampleRate;
4121 desc.format = mFormat;
4122 desc.frameCount = mFrameCount;
4123 desc.latency = 0;
4124 param2 = &desc;
4125 break;
4126
4127 case AudioSystem::INPUT_CLOSED:
4128 default:
4129 break;
4130 }
Eric Laurent49f02be2009-11-19 09:00:56 -08004131 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurenta553c252009-07-17 12:17:14 -07004132}
4133
4134void AudioFlinger::RecordThread::readInputParameters()
4135{
4136 if (mRsmpInBuffer) delete mRsmpInBuffer;
4137 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
4138 if (mResampler) delete mResampler;
4139 mResampler = 0;
4140
4141 mSampleRate = mInput->sampleRate();
Eric Laurentb0a01472010-05-14 05:45:46 -07004142 mChannels = mInput->channels();
4143 mChannelCount = (uint16_t)AudioSystem::popCount(mChannels);
Eric Laurenta553c252009-07-17 12:17:14 -07004144 mFormat = mInput->format();
Eric Laurentb0a01472010-05-14 05:45:46 -07004145 mFrameSize = (uint16_t)mInput->frameSize();
Eric Laurenta553c252009-07-17 12:17:14 -07004146 mInputBytes = mInput->bufferSize();
4147 mFrameCount = mInputBytes / mFrameSize;
4148 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4149
4150 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4151 {
4152 int channelCount;
4153 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4154 // stereo to mono post process as the resampler always outputs stereo.
4155 if (mChannelCount == 1 && mReqChannelCount == 2) {
4156 channelCount = 1;
4157 } else {
4158 channelCount = 2;
4159 }
4160 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4161 mResampler->setSampleRate(mSampleRate);
4162 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4163 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4164
4165 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4166 if (mChannelCount == 1 && mReqChannelCount == 1) {
4167 mFrameCount >>= 1;
4168 }
4169
4170 }
4171 mRsmpInIndex = mFrameCount;
4172}
4173
Eric Laurent47d0a922010-02-26 02:47:27 -08004174unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4175{
4176 return mInput->getInputFramesLost();
4177}
4178
Eric Laurenta553c252009-07-17 12:17:14 -07004179// ----------------------------------------------------------------------------
4180
Eric Laurentddb78e72009-07-28 08:44:33 -07004181int AudioFlinger::openOutput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07004182 uint32_t *pSamplingRate,
4183 uint32_t *pFormat,
4184 uint32_t *pChannels,
4185 uint32_t *pLatencyMs,
4186 uint32_t flags)
4187{
4188 status_t status;
4189 PlaybackThread *thread = NULL;
4190 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4191 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4192 uint32_t format = pFormat ? *pFormat : 0;
4193 uint32_t channels = pChannels ? *pChannels : 0;
4194 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
4195
4196 LOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
4197 pDevices ? *pDevices : 0,
4198 samplingRate,
4199 format,
4200 channels,
4201 flags);
4202
4203 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004204 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004205 }
4206 Mutex::Autolock _l(mLock);
4207
4208 AudioStreamOut *output = mAudioHardware->openOutputStream(*pDevices,
4209 (int *)&format,
4210 &channels,
4211 &samplingRate,
4212 &status);
4213 LOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
4214 output,
4215 samplingRate,
4216 format,
4217 channels,
4218 status);
4219
4220 mHardwareStatus = AUDIO_HW_IDLE;
4221 if (output != 0) {
Eric Laurentf3d6dd02010-11-18 08:40:16 -08004222 int id = nextUniqueId_l();
Eric Laurenta553c252009-07-17 12:17:14 -07004223 if ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) ||
4224 (format != AudioSystem::PCM_16_BIT) ||
4225 (channels != AudioSystem::CHANNEL_OUT_STEREO)) {
Eric Laurent65b65452010-06-01 23:49:17 -07004226 thread = new DirectOutputThread(this, output, id, *pDevices);
4227 LOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004228 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07004229 thread = new MixerThread(this, output, id, *pDevices);
4230 LOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004231 }
Eric Laurent65b65452010-06-01 23:49:17 -07004232 mPlaybackThreads.add(id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004233
4234 if (pSamplingRate) *pSamplingRate = samplingRate;
4235 if (pFormat) *pFormat = format;
4236 if (pChannels) *pChannels = channels;
4237 if (pLatencyMs) *pLatencyMs = thread->latency();
Eric Laurent9cc489a2009-12-05 05:20:01 -08004238
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004239 // notify client processes of the new output creation
4240 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004241 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004242 }
4243
Eric Laurent9cc489a2009-12-05 05:20:01 -08004244 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004245}
4246
Eric Laurentddb78e72009-07-28 08:44:33 -07004247int AudioFlinger::openDuplicateOutput(int output1, int output2)
Eric Laurenta553c252009-07-17 12:17:14 -07004248{
4249 Mutex::Autolock _l(mLock);
Eric Laurentddb78e72009-07-28 08:44:33 -07004250 MixerThread *thread1 = checkMixerThread_l(output1);
4251 MixerThread *thread2 = checkMixerThread_l(output2);
Eric Laurenta553c252009-07-17 12:17:14 -07004252
Eric Laurentddb78e72009-07-28 08:44:33 -07004253 if (thread1 == NULL || thread2 == NULL) {
4254 LOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
4255 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004256 }
4257
Eric Laurentf3d6dd02010-11-18 08:40:16 -08004258 int id = nextUniqueId_l();
Eric Laurent65b65452010-06-01 23:49:17 -07004259 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
Eric Laurentddb78e72009-07-28 08:44:33 -07004260 thread->addOutputTrack(thread2);
Eric Laurent65b65452010-06-01 23:49:17 -07004261 mPlaybackThreads.add(id, thread);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004262 // notify client processes of the new output creation
4263 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004264 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004265}
4266
Eric Laurentddb78e72009-07-28 08:44:33 -07004267status_t AudioFlinger::closeOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004268{
Eric Laurent49018a52009-08-04 08:37:05 -07004269 // keep strong reference on the playback thread so that
4270 // it is not destroyed while exit() is executed
4271 sp <PlaybackThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07004272 {
4273 Mutex::Autolock _l(mLock);
4274 thread = checkPlaybackThread_l(output);
4275 if (thread == NULL) {
4276 return BAD_VALUE;
4277 }
4278
Eric Laurentddb78e72009-07-28 08:44:33 -07004279 LOGV("closeOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004280
4281 if (thread->type() == PlaybackThread::MIXER) {
4282 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004283 if (mPlaybackThreads.valueAt(i)->type() == PlaybackThread::DUPLICATING) {
4284 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Eric Laurent49018a52009-08-04 08:37:05 -07004285 dupThread->removeOutputTrack((MixerThread *)thread.get());
Eric Laurenta553c252009-07-17 12:17:14 -07004286 }
4287 }
4288 }
Eric Laurent296a0ec2009-09-15 07:10:12 -07004289 void *param2 = 0;
Eric Laurent49f02be2009-11-19 09:00:56 -08004290 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
Eric Laurentddb78e72009-07-28 08:44:33 -07004291 mPlaybackThreads.removeItem(output);
Eric Laurenta553c252009-07-17 12:17:14 -07004292 }
4293 thread->exit();
4294
Eric Laurent49018a52009-08-04 08:37:05 -07004295 if (thread->type() != PlaybackThread::DUPLICATING) {
4296 mAudioHardware->closeOutputStream(thread->getOutput());
4297 }
Eric Laurenta553c252009-07-17 12:17:14 -07004298 return NO_ERROR;
4299}
4300
Eric Laurentddb78e72009-07-28 08:44:33 -07004301status_t AudioFlinger::suspendOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004302{
4303 Mutex::Autolock _l(mLock);
4304 PlaybackThread *thread = checkPlaybackThread_l(output);
4305
4306 if (thread == NULL) {
4307 return BAD_VALUE;
4308 }
4309
Eric Laurentddb78e72009-07-28 08:44:33 -07004310 LOGV("suspendOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004311 thread->suspend();
4312
4313 return NO_ERROR;
4314}
4315
Eric Laurentddb78e72009-07-28 08:44:33 -07004316status_t AudioFlinger::restoreOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004317{
4318 Mutex::Autolock _l(mLock);
4319 PlaybackThread *thread = checkPlaybackThread_l(output);
4320
4321 if (thread == NULL) {
4322 return BAD_VALUE;
4323 }
4324
Eric Laurentddb78e72009-07-28 08:44:33 -07004325 LOGV("restoreOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004326
4327 thread->restore();
4328
4329 return NO_ERROR;
4330}
4331
Eric Laurentddb78e72009-07-28 08:44:33 -07004332int AudioFlinger::openInput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07004333 uint32_t *pSamplingRate,
4334 uint32_t *pFormat,
4335 uint32_t *pChannels,
4336 uint32_t acoustics)
4337{
4338 status_t status;
4339 RecordThread *thread = NULL;
4340 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4341 uint32_t format = pFormat ? *pFormat : 0;
4342 uint32_t channels = pChannels ? *pChannels : 0;
4343 uint32_t reqSamplingRate = samplingRate;
4344 uint32_t reqFormat = format;
4345 uint32_t reqChannels = channels;
4346
4347 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004348 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004349 }
4350 Mutex::Autolock _l(mLock);
4351
4352 AudioStreamIn *input = mAudioHardware->openInputStream(*pDevices,
4353 (int *)&format,
4354 &channels,
4355 &samplingRate,
4356 &status,
4357 (AudioSystem::audio_in_acoustics)acoustics);
4358 LOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
4359 input,
4360 samplingRate,
4361 format,
4362 channels,
4363 acoustics,
4364 status);
4365
4366 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
4367 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
4368 // or stereo to mono conversions on 16 bit PCM inputs.
4369 if (input == 0 && status == BAD_VALUE &&
4370 reqFormat == format && format == AudioSystem::PCM_16_BIT &&
4371 (samplingRate <= 2 * reqSamplingRate) &&
4372 (AudioSystem::popCount(channels) < 3) && (AudioSystem::popCount(reqChannels) < 3)) {
4373 LOGV("openInput() reopening with proposed sampling rate and channels");
4374 input = mAudioHardware->openInputStream(*pDevices,
4375 (int *)&format,
4376 &channels,
4377 &samplingRate,
4378 &status,
4379 (AudioSystem::audio_in_acoustics)acoustics);
4380 }
4381
4382 if (input != 0) {
Eric Laurentf3d6dd02010-11-18 08:40:16 -08004383 int id = nextUniqueId_l();
Eric Laurenta553c252009-07-17 12:17:14 -07004384 // Start record thread
Eric Laurent65b65452010-06-01 23:49:17 -07004385 thread = new RecordThread(this, input, reqSamplingRate, reqChannels, id);
4386 mRecordThreads.add(id, thread);
4387 LOGV("openInput() created record thread: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004388 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
4389 if (pFormat) *pFormat = format;
4390 if (pChannels) *pChannels = reqChannels;
4391
4392 input->standby();
Eric Laurent9cc489a2009-12-05 05:20:01 -08004393
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004394 // notify client processes of the new input creation
4395 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004396 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004397 }
4398
Eric Laurent9cc489a2009-12-05 05:20:01 -08004399 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004400}
4401
Eric Laurentddb78e72009-07-28 08:44:33 -07004402status_t AudioFlinger::closeInput(int input)
Eric Laurenta553c252009-07-17 12:17:14 -07004403{
Eric Laurent49018a52009-08-04 08:37:05 -07004404 // keep strong reference on the record thread so that
4405 // it is not destroyed while exit() is executed
4406 sp <RecordThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07004407 {
4408 Mutex::Autolock _l(mLock);
4409 thread = checkRecordThread_l(input);
4410 if (thread == NULL) {
4411 return BAD_VALUE;
4412 }
4413
Eric Laurentddb78e72009-07-28 08:44:33 -07004414 LOGV("closeInput() %d", input);
Eric Laurent296a0ec2009-09-15 07:10:12 -07004415 void *param2 = 0;
Eric Laurent49f02be2009-11-19 09:00:56 -08004416 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
Eric Laurentddb78e72009-07-28 08:44:33 -07004417 mRecordThreads.removeItem(input);
Eric Laurenta553c252009-07-17 12:17:14 -07004418 }
4419 thread->exit();
4420
Eric Laurent49018a52009-08-04 08:37:05 -07004421 mAudioHardware->closeInputStream(thread->getInput());
4422
Eric Laurenta553c252009-07-17 12:17:14 -07004423 return NO_ERROR;
4424}
4425
Eric Laurentddb78e72009-07-28 08:44:33 -07004426status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004427{
4428 Mutex::Autolock _l(mLock);
4429 MixerThread *dstThread = checkMixerThread_l(output);
4430 if (dstThread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004431 LOGW("setStreamOutput() bad output id %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004432 return BAD_VALUE;
4433 }
4434
Eric Laurentddb78e72009-07-28 08:44:33 -07004435 LOGV("setStreamOutput() stream %d to output %d", stream, output);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004436 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
Eric Laurenta553c252009-07-17 12:17:14 -07004437
4438 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004439 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurenta553c252009-07-17 12:17:14 -07004440 if (thread != dstThread &&
4441 thread->type() != PlaybackThread::DIRECT) {
4442 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004443 srcThread->invalidateTracks(stream);
Eric Laurenta553c252009-07-17 12:17:14 -07004444 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004445 }
Eric Laurentd069f322009-09-01 05:56:26 -07004446
Eric Laurenta553c252009-07-17 12:17:14 -07004447 return NO_ERROR;
4448}
4449
Eric Laurent65b65452010-06-01 23:49:17 -07004450
4451int AudioFlinger::newAudioSessionId()
4452{
Eric Laurentf3d6dd02010-11-18 08:40:16 -08004453 AutoMutex _l(mLock);
4454 return nextUniqueId_l();
Eric Laurent65b65452010-06-01 23:49:17 -07004455}
4456
Eric Laurenta553c252009-07-17 12:17:14 -07004457// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07004458AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
Eric Laurenta553c252009-07-17 12:17:14 -07004459{
4460 PlaybackThread *thread = NULL;
Eric Laurentddb78e72009-07-28 08:44:33 -07004461 if (mPlaybackThreads.indexOfKey(output) >= 0) {
4462 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
Eric Laurenta553c252009-07-17 12:17:14 -07004463 }
Eric Laurenta553c252009-07-17 12:17:14 -07004464 return thread;
4465}
4466
4467// checkMixerThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07004468AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
Eric Laurenta553c252009-07-17 12:17:14 -07004469{
4470 PlaybackThread *thread = checkPlaybackThread_l(output);
4471 if (thread != NULL) {
4472 if (thread->type() == PlaybackThread::DIRECT) {
4473 thread = NULL;
4474 }
4475 }
4476 return (MixerThread *)thread;
4477}
4478
4479// checkRecordThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07004480AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
Eric Laurenta553c252009-07-17 12:17:14 -07004481{
4482 RecordThread *thread = NULL;
Eric Laurentddb78e72009-07-28 08:44:33 -07004483 if (mRecordThreads.indexOfKey(input) >= 0) {
4484 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
Eric Laurenta553c252009-07-17 12:17:14 -07004485 }
Eric Laurenta553c252009-07-17 12:17:14 -07004486 return thread;
4487}
4488
Eric Laurentf3d6dd02010-11-18 08:40:16 -08004489// nextUniqueId_l() must be called with AudioFlinger::mLock held
4490int AudioFlinger::nextUniqueId_l()
Eric Laurent65b65452010-06-01 23:49:17 -07004491{
Eric Laurentf3d6dd02010-11-18 08:40:16 -08004492 return mNextUniqueId++;
Eric Laurent65b65452010-06-01 23:49:17 -07004493}
4494
4495// ----------------------------------------------------------------------------
4496// Effect management
4497// ----------------------------------------------------------------------------
4498
4499
4500status_t AudioFlinger::loadEffectLibrary(const char *libPath, int *handle)
4501{
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004502 // check calling permissions
4503 if (!settingsAllowed()) {
4504 return PERMISSION_DENIED;
4505 }
4506 // only allow libraries loaded from /system/lib/soundfx for now
4507 if (strncmp(gEffectLibPath, libPath, strlen(gEffectLibPath)) != 0) {
4508 return PERMISSION_DENIED;
4509 }
4510
Eric Laurent65b65452010-06-01 23:49:17 -07004511 Mutex::Autolock _l(mLock);
4512 return EffectLoadLibrary(libPath, handle);
4513}
4514
4515status_t AudioFlinger::unloadEffectLibrary(int handle)
4516{
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004517 // check calling permissions
4518 if (!settingsAllowed()) {
4519 return PERMISSION_DENIED;
4520 }
4521
Eric Laurent65b65452010-06-01 23:49:17 -07004522 Mutex::Autolock _l(mLock);
4523 return EffectUnloadLibrary(handle);
4524}
4525
4526status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects)
4527{
4528 Mutex::Autolock _l(mLock);
4529 return EffectQueryNumberEffects(numEffects);
4530}
4531
Eric Laurent53334cd2010-06-23 17:38:20 -07004532status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor)
Eric Laurent65b65452010-06-01 23:49:17 -07004533{
4534 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07004535 return EffectQueryEffect(index, descriptor);
Eric Laurent65b65452010-06-01 23:49:17 -07004536}
4537
4538status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid, effect_descriptor_t *descriptor)
4539{
4540 Mutex::Autolock _l(mLock);
4541 return EffectGetDescriptor(pUuid, descriptor);
4542}
4543
Eric Laurentdf9b81c2010-07-02 08:12:41 -07004544
4545// this UUID must match the one defined in media/libeffects/EffectVisualizer.cpp
4546static const effect_uuid_t VISUALIZATION_UUID_ =
4547 {0xd069d9e0, 0x8329, 0x11df, 0x9168, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}};
4548
Eric Laurent65b65452010-06-01 23:49:17 -07004549sp<IEffect> AudioFlinger::createEffect(pid_t pid,
4550 effect_descriptor_t *pDesc,
4551 const sp<IEffectClient>& effectClient,
4552 int32_t priority,
4553 int output,
4554 int sessionId,
4555 status_t *status,
4556 int *id,
4557 int *enabled)
4558{
4559 status_t lStatus = NO_ERROR;
4560 sp<EffectHandle> handle;
4561 effect_interface_t itfe;
4562 effect_descriptor_t desc;
4563 sp<Client> client;
4564 wp<Client> wclient;
4565
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004566 LOGV("createEffect pid %d, client %p, priority %d, sessionId %d, output %d",
4567 pid, effectClient.get(), priority, sessionId, output);
Eric Laurent65b65452010-06-01 23:49:17 -07004568
4569 if (pDesc == NULL) {
4570 lStatus = BAD_VALUE;
4571 goto Exit;
4572 }
4573
Eric Laurent98c92592010-09-23 16:10:16 -07004574 // check audio settings permission for global effects
4575 if (sessionId == AudioSystem::SESSION_OUTPUT_MIX && !settingsAllowed()) {
4576 lStatus = PERMISSION_DENIED;
4577 goto Exit;
4578 }
4579
4580 // Session AudioSystem::SESSION_OUTPUT_STAGE is reserved for output stage effects
4581 // that can only be created by audio policy manager (running in same process)
4582 if (sessionId == AudioSystem::SESSION_OUTPUT_STAGE && getpid() != pid) {
4583 lStatus = PERMISSION_DENIED;
4584 goto Exit;
4585 }
4586
4587 // check recording permission for visualizer
4588 if ((memcmp(&pDesc->type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0 ||
4589 memcmp(&pDesc->uuid, &VISUALIZATION_UUID_, sizeof(effect_uuid_t)) == 0) &&
4590 !recordingAllowed()) {
4591 lStatus = PERMISSION_DENIED;
4592 goto Exit;
4593 }
4594
4595 if (output == 0) {
4596 if (sessionId == AudioSystem::SESSION_OUTPUT_STAGE) {
4597 // output must be specified by AudioPolicyManager when using session
4598 // AudioSystem::SESSION_OUTPUT_STAGE
4599 lStatus = BAD_VALUE;
4600 goto Exit;
4601 } else if (sessionId == AudioSystem::SESSION_OUTPUT_MIX) {
4602 // if the output returned by getOutputForEffect() is removed before we lock the
4603 // mutex below, the call to checkPlaybackThread_l(output) below will detect it
4604 // and we will exit safely
4605 output = AudioSystem::getOutputForEffect(&desc);
4606 }
4607 }
4608
Eric Laurent65b65452010-06-01 23:49:17 -07004609 {
4610 Mutex::Autolock _l(mLock);
4611
Eric Laurentdf9b81c2010-07-02 08:12:41 -07004612
Eric Laurent65b65452010-06-01 23:49:17 -07004613 if (!EffectIsNullUuid(&pDesc->uuid)) {
4614 // if uuid is specified, request effect descriptor
4615 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
4616 if (lStatus < 0) {
4617 LOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
4618 goto Exit;
4619 }
4620 } else {
4621 // if uuid is not specified, look for an available implementation
4622 // of the required type in effect factory
4623 if (EffectIsNullUuid(&pDesc->type)) {
4624 LOGW("createEffect() no effect type");
4625 lStatus = BAD_VALUE;
4626 goto Exit;
4627 }
4628 uint32_t numEffects = 0;
4629 effect_descriptor_t d;
4630 bool found = false;
4631
4632 lStatus = EffectQueryNumberEffects(&numEffects);
4633 if (lStatus < 0) {
4634 LOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
4635 goto Exit;
4636 }
Eric Laurent53334cd2010-06-23 17:38:20 -07004637 for (uint32_t i = 0; i < numEffects; i++) {
4638 lStatus = EffectQueryEffect(i, &desc);
Eric Laurent65b65452010-06-01 23:49:17 -07004639 if (lStatus < 0) {
Eric Laurent53334cd2010-06-23 17:38:20 -07004640 LOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07004641 continue;
4642 }
4643 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
4644 // If matching type found save effect descriptor. If the session is
4645 // 0 and the effect is not auxiliary, continue enumeration in case
4646 // an auxiliary version of this effect type is available
4647 found = true;
4648 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004649 if (sessionId != AudioSystem::SESSION_OUTPUT_MIX ||
Eric Laurent65b65452010-06-01 23:49:17 -07004650 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
4651 break;
4652 }
4653 }
4654 }
4655 if (!found) {
4656 lStatus = BAD_VALUE;
4657 LOGW("createEffect() effect not found");
4658 goto Exit;
4659 }
4660 // For same effect type, chose auxiliary version over insert version if
4661 // connect to output mix (Compliance to OpenSL ES)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004662 if (sessionId == AudioSystem::SESSION_OUTPUT_MIX &&
Eric Laurent65b65452010-06-01 23:49:17 -07004663 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
4664 memcpy(&desc, &d, sizeof(effect_descriptor_t));
4665 }
4666 }
4667
4668 // Do not allow auxiliary effects on a session different from 0 (output mix)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004669 if (sessionId != AudioSystem::SESSION_OUTPUT_MIX &&
Eric Laurent65b65452010-06-01 23:49:17 -07004670 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
4671 lStatus = INVALID_OPERATION;
4672 goto Exit;
4673 }
4674
4675 // return effect descriptor
4676 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
4677
4678 // If output is not specified try to find a matching audio session ID in one of the
4679 // output threads.
Eric Laurent98c92592010-09-23 16:10:16 -07004680 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
4681 // because of code checking output when entering the function.
Eric Laurent65b65452010-06-01 23:49:17 -07004682 if (output == 0) {
Eric Laurent98c92592010-09-23 16:10:16 -07004683 // look for the thread where the specified audio session is present
4684 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
4685 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
4686 output = mPlaybackThreads.keyAt(i);
4687 break;
Eric Laurent493941b2010-07-28 01:32:47 -07004688 }
Eric Laurent65b65452010-06-01 23:49:17 -07004689 }
Eric Laurent98c92592010-09-23 16:10:16 -07004690 // If no output thread contains the requested session ID, default to
4691 // first output. The effect chain will be moved to the correct output
4692 // thread when a track with the same session ID is created
4693 if (output == 0 && mPlaybackThreads.size()) {
4694 output = mPlaybackThreads.keyAt(0);
4695 }
Eric Laurent65b65452010-06-01 23:49:17 -07004696 }
Eric Laurent98c92592010-09-23 16:10:16 -07004697 LOGV("createEffect() got output %d for effect %s", output, desc.name);
Eric Laurent65b65452010-06-01 23:49:17 -07004698 PlaybackThread *thread = checkPlaybackThread_l(output);
4699 if (thread == NULL) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004700 LOGE("createEffect() unknown output thread");
Eric Laurent65b65452010-06-01 23:49:17 -07004701 lStatus = BAD_VALUE;
4702 goto Exit;
4703 }
4704
Eric Laurent98c92592010-09-23 16:10:16 -07004705 // TODO: allow attachment of effect to inputs
4706
Eric Laurent65b65452010-06-01 23:49:17 -07004707 wclient = mClients.valueFor(pid);
4708
4709 if (wclient != NULL) {
4710 client = wclient.promote();
4711 } else {
4712 client = new Client(this, pid);
4713 mClients.add(pid, client);
4714 }
4715
4716 // create effect on selected output trhead
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004717 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
4718 &desc, enabled, &lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07004719 if (handle != 0 && id != NULL) {
4720 *id = handle->id();
4721 }
4722 }
4723
4724Exit:
4725 if(status) {
4726 *status = lStatus;
4727 }
4728 return handle;
4729}
4730
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004731status_t AudioFlinger::moveEffects(int session, int srcOutput, int dstOutput)
4732{
4733 LOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
4734 session, srcOutput, dstOutput);
4735 Mutex::Autolock _l(mLock);
4736 if (srcOutput == dstOutput) {
4737 LOGW("moveEffects() same dst and src outputs %d", dstOutput);
4738 return NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07004739 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004740 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
4741 if (srcThread == NULL) {
4742 LOGW("moveEffects() bad srcOutput %d", srcOutput);
4743 return BAD_VALUE;
Eric Laurent53334cd2010-06-23 17:38:20 -07004744 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004745 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
4746 if (dstThread == NULL) {
4747 LOGW("moveEffects() bad dstOutput %d", dstOutput);
4748 return BAD_VALUE;
4749 }
4750
4751 Mutex::Autolock _dl(dstThread->mLock);
4752 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent493941b2010-07-28 01:32:47 -07004753 moveEffectChain_l(session, srcThread, dstThread, false);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004754
Eric Laurent53334cd2010-06-23 17:38:20 -07004755 return NO_ERROR;
4756}
4757
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004758// moveEffectChain_l mustbe called with both srcThread and dstThread mLocks held
4759status_t AudioFlinger::moveEffectChain_l(int session,
4760 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent493941b2010-07-28 01:32:47 -07004761 AudioFlinger::PlaybackThread *dstThread,
4762 bool reRegister)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004763{
4764 LOGV("moveEffectChain_l() session %d from thread %p to thread %p",
4765 session, srcThread, dstThread);
4766
4767 sp<EffectChain> chain = srcThread->getEffectChain_l(session);
4768 if (chain == 0) {
4769 LOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
4770 session, srcThread);
4771 return INVALID_OPERATION;
4772 }
4773
Eric Laurent493941b2010-07-28 01:32:47 -07004774 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004775 // so that a new chain is created with correct parameters when first effect is added. This is
4776 // otherwise unecessary as removeEffect_l() will remove the chain when last effect is
4777 // removed.
4778 srcThread->removeEffectChain_l(chain);
4779
4780 // transfer all effects one by one so that new effect chain is created on new thread with
4781 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent493941b2010-07-28 01:32:47 -07004782 int dstOutput = dstThread->id();
4783 sp<EffectChain> dstChain;
4784 uint32_t strategy;
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004785 sp<EffectModule> effect = chain->getEffectFromId_l(0);
4786 while (effect != 0) {
4787 srcThread->removeEffect_l(effect);
4788 dstThread->addEffect_l(effect);
Eric Laurent493941b2010-07-28 01:32:47 -07004789 // if the move request is not received from audio policy manager, the effect must be
4790 // re-registered with the new strategy and output
4791 if (dstChain == 0) {
4792 dstChain = effect->chain().promote();
4793 if (dstChain == 0) {
4794 LOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
4795 srcThread->addEffect_l(effect);
4796 return NO_INIT;
4797 }
4798 strategy = dstChain->strategy();
4799 }
4800 if (reRegister) {
4801 AudioSystem::unregisterEffect(effect->id());
4802 AudioSystem::registerEffect(&effect->desc(),
4803 dstOutput,
4804 strategy,
4805 session,
4806 effect->id());
4807 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004808 effect = chain->getEffectFromId_l(0);
4809 }
4810
4811 return NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07004812}
4813
Eric Laurent65b65452010-06-01 23:49:17 -07004814// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
4815sp<AudioFlinger::EffectHandle> AudioFlinger::PlaybackThread::createEffect_l(
4816 const sp<AudioFlinger::Client>& client,
4817 const sp<IEffectClient>& effectClient,
4818 int32_t priority,
4819 int sessionId,
4820 effect_descriptor_t *desc,
4821 int *enabled,
4822 status_t *status
4823 )
4824{
4825 sp<EffectModule> effect;
4826 sp<EffectHandle> handle;
4827 status_t lStatus;
4828 sp<Track> track;
4829 sp<EffectChain> chain;
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004830 bool chainCreated = false;
Eric Laurent65b65452010-06-01 23:49:17 -07004831 bool effectCreated = false;
Eric Laurent53334cd2010-06-23 17:38:20 -07004832 bool effectRegistered = false;
Eric Laurent65b65452010-06-01 23:49:17 -07004833
4834 if (mOutput == 0) {
4835 LOGW("createEffect_l() Audio driver not initialized.");
4836 lStatus = NO_INIT;
4837 goto Exit;
4838 }
4839
4840 // Do not allow auxiliary effect on session other than 0
4841 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY &&
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004842 sessionId != AudioSystem::SESSION_OUTPUT_MIX) {
4843 LOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
4844 desc->name, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07004845 lStatus = BAD_VALUE;
4846 goto Exit;
4847 }
4848
4849 // Do not allow effects with session ID 0 on direct output or duplicating threads
4850 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004851 if (sessionId == AudioSystem::SESSION_OUTPUT_MIX && mType != MIXER) {
4852 LOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
4853 desc->name, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07004854 lStatus = BAD_VALUE;
4855 goto Exit;
4856 }
4857
4858 LOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
4859
4860 { // scope for mLock
4861 Mutex::Autolock _l(mLock);
4862
4863 // check for existing effect chain with the requested audio session
4864 chain = getEffectChain_l(sessionId);
4865 if (chain == 0) {
4866 // create a new chain for this session
4867 LOGV("createEffect_l() new effect chain for session %d", sessionId);
4868 chain = new EffectChain(this, sessionId);
4869 addEffectChain_l(chain);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004870 chain->setStrategy(getStrategyForSession_l(sessionId));
4871 chainCreated = true;
Eric Laurent65b65452010-06-01 23:49:17 -07004872 } else {
Eric Laurent76c40f72010-07-15 12:50:15 -07004873 effect = chain->getEffectFromDesc_l(desc);
Eric Laurent65b65452010-06-01 23:49:17 -07004874 }
4875
4876 LOGV("createEffect_l() got effect %p on chain %p", effect == 0 ? 0 : effect.get(), chain.get());
4877
4878 if (effect == 0) {
Eric Laurentf3d6dd02010-11-18 08:40:16 -08004879 int id = mAudioFlinger->nextUniqueId_l();
Eric Laurent53334cd2010-06-23 17:38:20 -07004880 // Check CPU and memory usage
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004881 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Eric Laurent53334cd2010-06-23 17:38:20 -07004882 if (lStatus != NO_ERROR) {
4883 goto Exit;
4884 }
4885 effectRegistered = true;
Eric Laurent65b65452010-06-01 23:49:17 -07004886 // create a new effect module if none present in the chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004887 effect = new EffectModule(this, chain, desc, id, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07004888 lStatus = effect->status();
4889 if (lStatus != NO_ERROR) {
4890 goto Exit;
4891 }
Eric Laurent76c40f72010-07-15 12:50:15 -07004892 lStatus = chain->addEffect_l(effect);
Eric Laurent65b65452010-06-01 23:49:17 -07004893 if (lStatus != NO_ERROR) {
4894 goto Exit;
4895 }
Eric Laurent53334cd2010-06-23 17:38:20 -07004896 effectCreated = true;
Eric Laurent65b65452010-06-01 23:49:17 -07004897
4898 effect->setDevice(mDevice);
Eric Laurent53334cd2010-06-23 17:38:20 -07004899 effect->setMode(mAudioFlinger->getMode());
Eric Laurent65b65452010-06-01 23:49:17 -07004900 }
4901 // create effect handle and connect it to effect module
4902 handle = new EffectHandle(effect, client, effectClient, priority);
4903 lStatus = effect->addHandle(handle);
4904 if (enabled) {
4905 *enabled = (int)effect->isEnabled();
4906 }
4907 }
4908
4909Exit:
4910 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004911 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07004912 if (effectCreated) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004913 chain->removeEffect_l(effect);
Eric Laurent65b65452010-06-01 23:49:17 -07004914 }
Eric Laurent53334cd2010-06-23 17:38:20 -07004915 if (effectRegistered) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004916 AudioSystem::unregisterEffect(effect->id());
4917 }
4918 if (chainCreated) {
4919 removeEffectChain_l(chain);
Eric Laurent53334cd2010-06-23 17:38:20 -07004920 }
Eric Laurent65b65452010-06-01 23:49:17 -07004921 handle.clear();
4922 }
4923
4924 if(status) {
4925 *status = lStatus;
4926 }
4927 return handle;
4928}
4929
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004930// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
4931// PlaybackThread::mLock held
4932status_t AudioFlinger::PlaybackThread::addEffect_l(const sp<EffectModule>& effect)
4933{
4934 // check for existing effect chain with the requested audio session
4935 int sessionId = effect->sessionId();
4936 sp<EffectChain> chain = getEffectChain_l(sessionId);
4937 bool chainCreated = false;
4938
4939 if (chain == 0) {
4940 // create a new chain for this session
4941 LOGV("addEffect_l() new effect chain for session %d", sessionId);
4942 chain = new EffectChain(this, sessionId);
4943 addEffectChain_l(chain);
4944 chain->setStrategy(getStrategyForSession_l(sessionId));
4945 chainCreated = true;
4946 }
4947 LOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
4948
4949 if (chain->getEffectFromId_l(effect->id()) != 0) {
4950 LOGW("addEffect_l() %p effect %s already present in chain %p",
4951 this, effect->desc().name, chain.get());
4952 return BAD_VALUE;
4953 }
4954
4955 status_t status = chain->addEffect_l(effect);
4956 if (status != NO_ERROR) {
4957 if (chainCreated) {
4958 removeEffectChain_l(chain);
4959 }
4960 return status;
4961 }
4962
4963 effect->setDevice(mDevice);
4964 effect->setMode(mAudioFlinger->getMode());
4965 return NO_ERROR;
4966}
4967
4968void AudioFlinger::PlaybackThread::removeEffect_l(const sp<EffectModule>& effect) {
4969
4970 LOGV("removeEffect_l() %p effect %p", this, effect.get());
Eric Laurent53334cd2010-06-23 17:38:20 -07004971 effect_descriptor_t desc = effect->desc();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004972 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
4973 detachAuxEffect_l(effect->id());
4974 }
4975
4976 sp<EffectChain> chain = effect->chain().promote();
4977 if (chain != 0) {
4978 // remove effect chain if removing last effect
4979 if (chain->removeEffect_l(effect) == 0) {
4980 removeEffectChain_l(chain);
4981 }
4982 } else {
4983 LOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
4984 }
4985}
4986
4987void AudioFlinger::PlaybackThread::disconnectEffect(const sp<EffectModule>& effect,
4988 const wp<EffectHandle>& handle) {
Eric Laurent53334cd2010-06-23 17:38:20 -07004989 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004990 LOGV("disconnectEffect() %p effect %p", this, effect.get());
Eric Laurent53334cd2010-06-23 17:38:20 -07004991 // delete the effect module if removing last handle on it
4992 if (effect->removeHandle(handle) == 0) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004993 removeEffect_l(effect);
4994 AudioSystem::unregisterEffect(effect->id());
Eric Laurent53334cd2010-06-23 17:38:20 -07004995 }
4996}
4997
Eric Laurent65b65452010-06-01 23:49:17 -07004998status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
4999{
5000 int session = chain->sessionId();
5001 int16_t *buffer = mMixBuffer;
Eric Laurent53334cd2010-06-23 17:38:20 -07005002 bool ownsBuffer = false;
Eric Laurent65b65452010-06-01 23:49:17 -07005003
5004 LOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Eric Laurent53334cd2010-06-23 17:38:20 -07005005 if (session > 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07005006 // Only one effect chain can be present in direct output thread and it uses
5007 // the mix buffer as input
5008 if (mType != DIRECT) {
5009 size_t numSamples = mFrameCount * mChannelCount;
5010 buffer = new int16_t[numSamples];
5011 memset(buffer, 0, numSamples * sizeof(int16_t));
5012 LOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
5013 ownsBuffer = true;
5014 }
Eric Laurent65b65452010-06-01 23:49:17 -07005015
Eric Laurent53334cd2010-06-23 17:38:20 -07005016 // Attach all tracks with same session ID to this chain.
5017 for (size_t i = 0; i < mTracks.size(); ++i) {
5018 sp<Track> track = mTracks[i];
5019 if (session == track->sessionId()) {
5020 LOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
5021 track->setMainBuffer(buffer);
5022 }
5023 }
5024
5025 // indicate all active tracks in the chain
5026 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5027 sp<Track> track = mActiveTracks[i].promote();
5028 if (track == 0) continue;
5029 if (session == track->sessionId()) {
5030 LOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
5031 chain->startTrack();
5032 }
Eric Laurent65b65452010-06-01 23:49:17 -07005033 }
5034 }
5035
Eric Laurent53334cd2010-06-23 17:38:20 -07005036 chain->setInBuffer(buffer, ownsBuffer);
5037 chain->setOutBuffer(mMixBuffer);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005038 // Effect chain for session AudioSystem::SESSION_OUTPUT_STAGE is inserted at end of effect
5039 // chains list in order to be processed last as it contains output stage effects
5040 // Effect chain for session AudioSystem::SESSION_OUTPUT_MIX is inserted before
5041 // session AudioSystem::SESSION_OUTPUT_STAGE to be processed
Eric Laurent53334cd2010-06-23 17:38:20 -07005042 // after track specific effects and before output stage
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005043 // It is therefore mandatory that AudioSystem::SESSION_OUTPUT_MIX == 0 and
5044 // that AudioSystem::SESSION_OUTPUT_STAGE < AudioSystem::SESSION_OUTPUT_MIX
5045 // Effect chain for other sessions are inserted at beginning of effect
5046 // chains list to be processed before output mix effects. Relative order between other
5047 // sessions is not important
Eric Laurent53334cd2010-06-23 17:38:20 -07005048 size_t size = mEffectChains.size();
5049 size_t i = 0;
5050 for (i = 0; i < size; i++) {
5051 if (mEffectChains[i]->sessionId() < session) break;
Eric Laurent65b65452010-06-01 23:49:17 -07005052 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005053 mEffectChains.insertAt(chain, i);
Eric Laurent65b65452010-06-01 23:49:17 -07005054
5055 return NO_ERROR;
5056}
5057
5058size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
5059{
5060 int session = chain->sessionId();
5061
5062 LOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
5063
5064 for (size_t i = 0; i < mEffectChains.size(); i++) {
5065 if (chain == mEffectChains[i]) {
5066 mEffectChains.removeAt(i);
5067 // detach all tracks with same session ID from this chain
5068 for (size_t i = 0; i < mTracks.size(); ++i) {
5069 sp<Track> track = mTracks[i];
5070 if (session == track->sessionId()) {
5071 track->setMainBuffer(mMixBuffer);
5072 }
5073 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005074 break;
Eric Laurent65b65452010-06-01 23:49:17 -07005075 }
5076 }
5077 return mEffectChains.size();
5078}
5079
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005080void AudioFlinger::PlaybackThread::lockEffectChains_l(
5081 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
Eric Laurent65b65452010-06-01 23:49:17 -07005082{
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005083 effectChains = mEffectChains;
Eric Laurent65b65452010-06-01 23:49:17 -07005084 for (size_t i = 0; i < mEffectChains.size(); i++) {
5085 mEffectChains[i]->lock();
5086 }
5087}
5088
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005089void AudioFlinger::PlaybackThread::unlockEffectChains(
5090 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
Eric Laurent65b65452010-06-01 23:49:17 -07005091{
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005092 for (size_t i = 0; i < effectChains.size(); i++) {
5093 effectChains[i]->unlock();
Eric Laurent65b65452010-06-01 23:49:17 -07005094 }
5095}
5096
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005097
Eric Laurent65b65452010-06-01 23:49:17 -07005098sp<AudioFlinger::EffectModule> AudioFlinger::PlaybackThread::getEffect_l(int sessionId, int effectId)
5099{
5100 sp<EffectModule> effect;
5101
5102 sp<EffectChain> chain = getEffectChain_l(sessionId);
5103 if (chain != 0) {
Eric Laurent76c40f72010-07-15 12:50:15 -07005104 effect = chain->getEffectFromId_l(effectId);
Eric Laurent65b65452010-06-01 23:49:17 -07005105 }
5106 return effect;
5107}
5108
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005109status_t AudioFlinger::PlaybackThread::attachAuxEffect(
5110 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Eric Laurent65b65452010-06-01 23:49:17 -07005111{
5112 Mutex::Autolock _l(mLock);
5113 return attachAuxEffect_l(track, EffectId);
5114}
5115
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005116status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
5117 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Eric Laurent65b65452010-06-01 23:49:17 -07005118{
5119 status_t status = NO_ERROR;
5120
5121 if (EffectId == 0) {
5122 track->setAuxBuffer(0, NULL);
5123 } else {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005124 // Auxiliary effects are always in audio session AudioSystem::SESSION_OUTPUT_MIX
5125 sp<EffectModule> effect = getEffect_l(AudioSystem::SESSION_OUTPUT_MIX, EffectId);
Eric Laurent65b65452010-06-01 23:49:17 -07005126 if (effect != 0) {
5127 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5128 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
5129 } else {
5130 status = INVALID_OPERATION;
5131 }
5132 } else {
5133 status = BAD_VALUE;
5134 }
5135 }
5136 return status;
5137}
5138
5139void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
5140{
5141 for (size_t i = 0; i < mTracks.size(); ++i) {
5142 sp<Track> track = mTracks[i];
5143 if (track->auxEffectId() == effectId) {
5144 attachAuxEffect_l(track, 0);
5145 }
5146 }
5147}
5148
5149// ----------------------------------------------------------------------------
5150// EffectModule implementation
5151// ----------------------------------------------------------------------------
5152
5153#undef LOG_TAG
5154#define LOG_TAG "AudioFlinger::EffectModule"
5155
5156AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
5157 const wp<AudioFlinger::EffectChain>& chain,
5158 effect_descriptor_t *desc,
5159 int id,
5160 int sessionId)
5161 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
5162 mStatus(NO_INIT), mState(IDLE)
5163{
5164 LOGV("Constructor %p", this);
5165 int lStatus;
5166 sp<ThreadBase> thread = mThread.promote();
5167 if (thread == 0) {
5168 return;
5169 }
5170 PlaybackThread *p = (PlaybackThread *)thread.get();
5171
5172 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
5173
5174 // create effect engine from effect factory
Eric Laurent53334cd2010-06-23 17:38:20 -07005175 mStatus = EffectCreate(&desc->uuid, sessionId, p->id(), &mEffectInterface);
5176
Eric Laurent65b65452010-06-01 23:49:17 -07005177 if (mStatus != NO_ERROR) {
5178 return;
5179 }
5180 lStatus = init();
5181 if (lStatus < 0) {
5182 mStatus = lStatus;
5183 goto Error;
5184 }
5185
5186 LOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
5187 return;
5188Error:
5189 EffectRelease(mEffectInterface);
5190 mEffectInterface = NULL;
5191 LOGV("Constructor Error %d", mStatus);
5192}
5193
5194AudioFlinger::EffectModule::~EffectModule()
5195{
5196 LOGV("Destructor %p", this);
5197 if (mEffectInterface != NULL) {
5198 // release effect engine
5199 EffectRelease(mEffectInterface);
5200 }
5201}
5202
5203status_t AudioFlinger::EffectModule::addHandle(sp<EffectHandle>& handle)
5204{
5205 status_t status;
5206
5207 Mutex::Autolock _l(mLock);
5208 // First handle in mHandles has highest priority and controls the effect module
5209 int priority = handle->priority();
5210 size_t size = mHandles.size();
5211 sp<EffectHandle> h;
5212 size_t i;
5213 for (i = 0; i < size; i++) {
5214 h = mHandles[i].promote();
5215 if (h == 0) continue;
5216 if (h->priority() <= priority) break;
5217 }
5218 // if inserted in first place, move effect control from previous owner to this handle
5219 if (i == 0) {
5220 if (h != 0) {
5221 h->setControl(false, true);
5222 }
5223 handle->setControl(true, false);
5224 status = NO_ERROR;
5225 } else {
5226 status = ALREADY_EXISTS;
5227 }
5228 mHandles.insertAt(handle, i);
5229 return status;
5230}
5231
5232size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
5233{
5234 Mutex::Autolock _l(mLock);
5235 size_t size = mHandles.size();
5236 size_t i;
5237 for (i = 0; i < size; i++) {
5238 if (mHandles[i] == handle) break;
5239 }
5240 if (i == size) {
5241 return size;
5242 }
5243 mHandles.removeAt(i);
5244 size = mHandles.size();
5245 // if removed from first place, move effect control from this handle to next in line
5246 if (i == 0 && size != 0) {
5247 sp<EffectHandle> h = mHandles[0].promote();
5248 if (h != 0) {
5249 h->setControl(true, true);
5250 }
5251 }
5252
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07005253 // Release effect engine here so that it is done immediately. Otherwise it will be released
5254 // by the destructor when the last strong reference on the this object is released which can
5255 // happen after next process is called on this effect.
5256 if (size == 0 && mEffectInterface != NULL) {
5257 // release effect engine
5258 EffectRelease(mEffectInterface);
5259 mEffectInterface = NULL;
5260 }
5261
Eric Laurent65b65452010-06-01 23:49:17 -07005262 return size;
5263}
5264
5265void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle)
5266{
5267 // keep a strong reference on this EffectModule to avoid calling the
5268 // destructor before we exit
5269 sp<EffectModule> keep(this);
Eric Laurent53334cd2010-06-23 17:38:20 -07005270 {
5271 sp<ThreadBase> thread = mThread.promote();
5272 if (thread != 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07005273 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurent53334cd2010-06-23 17:38:20 -07005274 playbackThread->disconnectEffect(keep, handle);
Eric Laurent65b65452010-06-01 23:49:17 -07005275 }
5276 }
5277}
5278
Eric Laurent7d850f22010-07-09 13:34:17 -07005279void AudioFlinger::EffectModule::updateState() {
5280 Mutex::Autolock _l(mLock);
5281
5282 switch (mState) {
5283 case RESTART:
5284 reset_l();
5285 // FALL THROUGH
5286
5287 case STARTING:
5288 // clear auxiliary effect input buffer for next accumulation
5289 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5290 memset(mConfig.inputCfg.buffer.raw,
5291 0,
5292 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
5293 }
5294 start_l();
5295 mState = ACTIVE;
5296 break;
5297 case STOPPING:
5298 stop_l();
5299 mDisableWaitCnt = mMaxDisableWaitCnt;
5300 mState = STOPPED;
5301 break;
5302 case STOPPED:
5303 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
5304 // turn off sequence.
5305 if (--mDisableWaitCnt == 0) {
5306 reset_l();
5307 mState = IDLE;
5308 }
5309 break;
5310 default: //IDLE , ACTIVE
5311 break;
5312 }
5313}
5314
Eric Laurent65b65452010-06-01 23:49:17 -07005315void AudioFlinger::EffectModule::process()
5316{
5317 Mutex::Autolock _l(mLock);
5318
Eric Laurent7d850f22010-07-09 13:34:17 -07005319 if (mEffectInterface == NULL ||
5320 mConfig.inputCfg.buffer.raw == NULL ||
5321 mConfig.outputCfg.buffer.raw == NULL) {
Eric Laurent65b65452010-06-01 23:49:17 -07005322 return;
5323 }
5324
Eric Laurenta92ebfa2010-08-31 13:50:07 -07005325 if (isProcessEnabled()) {
Eric Laurent65b65452010-06-01 23:49:17 -07005326 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
5327 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5328 AudioMixer::ditherAndClamp(mConfig.inputCfg.buffer.s32,
5329 mConfig.inputCfg.buffer.s32,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005330 mConfig.inputCfg.buffer.frameCount/2);
Eric Laurent65b65452010-06-01 23:49:17 -07005331 }
5332
Eric Laurent65b65452010-06-01 23:49:17 -07005333 // do the actual processing in the effect engine
Eric Laurent7d850f22010-07-09 13:34:17 -07005334 int ret = (*mEffectInterface)->process(mEffectInterface,
5335 &mConfig.inputCfg.buffer,
5336 &mConfig.outputCfg.buffer);
5337
5338 // force transition to IDLE state when engine is ready
5339 if (mState == STOPPED && ret == -ENODATA) {
5340 mDisableWaitCnt = 1;
5341 }
Eric Laurent65b65452010-06-01 23:49:17 -07005342
5343 // clear auxiliary effect input buffer for next accumulation
5344 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent67b5ed32011-01-19 18:36:13 -08005345 memset(mConfig.inputCfg.buffer.raw, 0,
5346 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Eric Laurent65b65452010-06-01 23:49:17 -07005347 }
5348 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent67b5ed32011-01-19 18:36:13 -08005349 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
5350 // If an insert effect is idle and input buffer is different from output buffer,
5351 // accumulate input onto output
Eric Laurent65b65452010-06-01 23:49:17 -07005352 sp<EffectChain> chain = mChain.promote();
5353 if (chain != 0 && chain->activeTracks() != 0) {
Eric Laurent67b5ed32011-01-19 18:36:13 -08005354 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
5355 int16_t *in = mConfig.inputCfg.buffer.s16;
5356 int16_t *out = mConfig.outputCfg.buffer.s16;
5357 for (size_t i = 0; i < frameCnt; i++) {
5358 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Eric Laurent65b65452010-06-01 23:49:17 -07005359 }
Eric Laurent65b65452010-06-01 23:49:17 -07005360 }
5361 }
5362}
5363
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005364void AudioFlinger::EffectModule::reset_l()
Eric Laurent65b65452010-06-01 23:49:17 -07005365{
5366 if (mEffectInterface == NULL) {
5367 return;
5368 }
5369 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
5370}
5371
5372status_t AudioFlinger::EffectModule::configure()
5373{
5374 uint32_t channels;
5375 if (mEffectInterface == NULL) {
5376 return NO_INIT;
5377 }
5378
5379 sp<ThreadBase> thread = mThread.promote();
5380 if (thread == 0) {
5381 return DEAD_OBJECT;
5382 }
5383
5384 // TODO: handle configuration of effects replacing track process
5385 if (thread->channelCount() == 1) {
5386 channels = CHANNEL_MONO;
5387 } else {
5388 channels = CHANNEL_STEREO;
5389 }
5390
5391 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5392 mConfig.inputCfg.channels = CHANNEL_MONO;
5393 } else {
5394 mConfig.inputCfg.channels = channels;
5395 }
5396 mConfig.outputCfg.channels = channels;
Eric Laurent53334cd2010-06-23 17:38:20 -07005397 mConfig.inputCfg.format = SAMPLE_FORMAT_PCM_S15;
5398 mConfig.outputCfg.format = SAMPLE_FORMAT_PCM_S15;
Eric Laurent65b65452010-06-01 23:49:17 -07005399 mConfig.inputCfg.samplingRate = thread->sampleRate();
5400 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
5401 mConfig.inputCfg.bufferProvider.cookie = NULL;
5402 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
5403 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
5404 mConfig.outputCfg.bufferProvider.cookie = NULL;
5405 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
5406 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
5407 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
5408 // Insert effect:
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005409 // - in session AudioSystem::SESSION_OUTPUT_MIX or AudioSystem::SESSION_OUTPUT_STAGE,
5410 // always overwrites output buffer: input buffer == output buffer
Eric Laurent65b65452010-06-01 23:49:17 -07005411 // - in other sessions:
5412 // last effect in the chain accumulates in output buffer: input buffer != output buffer
5413 // other effect: overwrites output buffer: input buffer == output buffer
5414 // Auxiliary effect:
5415 // accumulates in output buffer: input buffer != output buffer
5416 // Therefore: accumulate <=> input buffer != output buffer
5417 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
5418 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
5419 } else {
5420 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
5421 }
5422 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
5423 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
5424 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
5425 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
5426
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005427 LOGV("configure() %p thread %p buffer %p framecount %d",
5428 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
5429
Eric Laurent65b65452010-06-01 23:49:17 -07005430 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005431 uint32_t size = sizeof(int);
5432 status_t status = (*mEffectInterface)->command(mEffectInterface,
5433 EFFECT_CMD_CONFIGURE,
5434 sizeof(effect_config_t),
5435 &mConfig,
5436 &size,
5437 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005438 if (status == 0) {
5439 status = cmdStatus;
5440 }
Eric Laurent7d850f22010-07-09 13:34:17 -07005441
5442 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
5443 (1000 * mConfig.outputCfg.buffer.frameCount);
5444
Eric Laurent65b65452010-06-01 23:49:17 -07005445 return status;
5446}
5447
5448status_t AudioFlinger::EffectModule::init()
5449{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005450 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07005451 if (mEffectInterface == NULL) {
5452 return NO_INIT;
5453 }
5454 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005455 uint32_t size = sizeof(status_t);
5456 status_t status = (*mEffectInterface)->command(mEffectInterface,
5457 EFFECT_CMD_INIT,
5458 0,
5459 NULL,
5460 &size,
5461 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005462 if (status == 0) {
5463 status = cmdStatus;
5464 }
5465 return status;
5466}
5467
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005468status_t AudioFlinger::EffectModule::start_l()
Eric Laurent65b65452010-06-01 23:49:17 -07005469{
5470 if (mEffectInterface == NULL) {
5471 return NO_INIT;
5472 }
5473 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005474 uint32_t size = sizeof(status_t);
5475 status_t status = (*mEffectInterface)->command(mEffectInterface,
5476 EFFECT_CMD_ENABLE,
5477 0,
5478 NULL,
5479 &size,
5480 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005481 if (status == 0) {
5482 status = cmdStatus;
5483 }
5484 return status;
5485}
5486
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005487status_t AudioFlinger::EffectModule::stop_l()
Eric Laurent65b65452010-06-01 23:49:17 -07005488{
5489 if (mEffectInterface == NULL) {
5490 return NO_INIT;
5491 }
5492 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005493 uint32_t size = sizeof(status_t);
5494 status_t status = (*mEffectInterface)->command(mEffectInterface,
5495 EFFECT_CMD_DISABLE,
5496 0,
5497 NULL,
5498 &size,
5499 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005500 if (status == 0) {
5501 status = cmdStatus;
5502 }
5503 return status;
5504}
5505
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005506status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
5507 uint32_t cmdSize,
5508 void *pCmdData,
5509 uint32_t *replySize,
5510 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07005511{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005512 Mutex::Autolock _l(mLock);
5513// LOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Eric Laurent65b65452010-06-01 23:49:17 -07005514
5515 if (mEffectInterface == NULL) {
5516 return NO_INIT;
5517 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005518 status_t status = (*mEffectInterface)->command(mEffectInterface,
5519 cmdCode,
5520 cmdSize,
5521 pCmdData,
5522 replySize,
5523 pReplyData);
Eric Laurent65b65452010-06-01 23:49:17 -07005524 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005525 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Eric Laurent65b65452010-06-01 23:49:17 -07005526 for (size_t i = 1; i < mHandles.size(); i++) {
5527 sp<EffectHandle> h = mHandles[i].promote();
5528 if (h != 0) {
5529 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
5530 }
5531 }
5532 }
5533 return status;
5534}
5535
5536status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
5537{
5538 Mutex::Autolock _l(mLock);
5539 LOGV("setEnabled %p enabled %d", this, enabled);
5540
5541 if (enabled != isEnabled()) {
5542 switch (mState) {
5543 // going from disabled to enabled
5544 case IDLE:
Eric Laurent7d850f22010-07-09 13:34:17 -07005545 mState = STARTING;
5546 break;
5547 case STOPPED:
5548 mState = RESTART;
Eric Laurent65b65452010-06-01 23:49:17 -07005549 break;
5550 case STOPPING:
5551 mState = ACTIVE;
5552 break;
Eric Laurent65b65452010-06-01 23:49:17 -07005553
5554 // going from enabled to disabled
Eric Laurent7d850f22010-07-09 13:34:17 -07005555 case RESTART:
Eric Laurenta92ebfa2010-08-31 13:50:07 -07005556 mState = STOPPED;
5557 break;
Eric Laurent65b65452010-06-01 23:49:17 -07005558 case STARTING:
Eric Laurent7d850f22010-07-09 13:34:17 -07005559 mState = IDLE;
Eric Laurent65b65452010-06-01 23:49:17 -07005560 break;
5561 case ACTIVE:
5562 mState = STOPPING;
5563 break;
5564 }
5565 for (size_t i = 1; i < mHandles.size(); i++) {
5566 sp<EffectHandle> h = mHandles[i].promote();
5567 if (h != 0) {
5568 h->setEnabled(enabled);
5569 }
5570 }
5571 }
5572 return NO_ERROR;
5573}
5574
5575bool AudioFlinger::EffectModule::isEnabled()
5576{
5577 switch (mState) {
Eric Laurent7d850f22010-07-09 13:34:17 -07005578 case RESTART:
Eric Laurent65b65452010-06-01 23:49:17 -07005579 case STARTING:
5580 case ACTIVE:
5581 return true;
5582 case IDLE:
5583 case STOPPING:
5584 case STOPPED:
5585 default:
5586 return false;
5587 }
5588}
5589
Eric Laurenta92ebfa2010-08-31 13:50:07 -07005590bool AudioFlinger::EffectModule::isProcessEnabled()
5591{
5592 switch (mState) {
5593 case RESTART:
5594 case ACTIVE:
5595 case STOPPING:
5596 case STOPPED:
5597 return true;
5598 case IDLE:
5599 case STARTING:
5600 default:
5601 return false;
5602 }
5603}
5604
Eric Laurent65b65452010-06-01 23:49:17 -07005605status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
5606{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005607 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07005608 status_t status = NO_ERROR;
5609
5610 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
5611 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurenta92ebfa2010-08-31 13:50:07 -07005612 if (isProcessEnabled() &&
Eric Laurent0d7e0482010-07-19 06:24:46 -07005613 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
5614 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Eric Laurent65b65452010-06-01 23:49:17 -07005615 status_t cmdStatus;
5616 uint32_t volume[2];
5617 uint32_t *pVolume = NULL;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005618 uint32_t size = sizeof(volume);
Eric Laurent65b65452010-06-01 23:49:17 -07005619 volume[0] = *left;
5620 volume[1] = *right;
5621 if (controller) {
5622 pVolume = volume;
5623 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005624 status = (*mEffectInterface)->command(mEffectInterface,
5625 EFFECT_CMD_SET_VOLUME,
5626 size,
5627 volume,
5628 &size,
5629 pVolume);
Eric Laurent65b65452010-06-01 23:49:17 -07005630 if (controller && status == NO_ERROR && size == sizeof(volume)) {
5631 *left = volume[0];
5632 *right = volume[1];
5633 }
5634 }
5635 return status;
5636}
5637
5638status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
5639{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005640 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07005641 status_t status = NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07005642 if ((mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
5643 // convert device bit field from AudioSystem to EffectApi format.
5644 device = deviceAudioSystemToEffectApi(device);
5645 if (device == 0) {
5646 return BAD_VALUE;
5647 }
Eric Laurent65b65452010-06-01 23:49:17 -07005648 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005649 uint32_t size = sizeof(status_t);
5650 status = (*mEffectInterface)->command(mEffectInterface,
5651 EFFECT_CMD_SET_DEVICE,
5652 sizeof(uint32_t),
5653 &device,
5654 &size,
5655 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005656 if (status == NO_ERROR) {
5657 status = cmdStatus;
5658 }
5659 }
5660 return status;
5661}
5662
Eric Laurent53334cd2010-06-23 17:38:20 -07005663status_t AudioFlinger::EffectModule::setMode(uint32_t mode)
5664{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005665 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07005666 status_t status = NO_ERROR;
5667 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
5668 // convert audio mode from AudioSystem to EffectApi format.
5669 int effectMode = modeAudioSystemToEffectApi(mode);
5670 if (effectMode < 0) {
5671 return BAD_VALUE;
5672 }
5673 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005674 uint32_t size = sizeof(status_t);
5675 status = (*mEffectInterface)->command(mEffectInterface,
5676 EFFECT_CMD_SET_AUDIO_MODE,
5677 sizeof(int),
5678 &effectMode,
5679 &size,
5680 &cmdStatus);
Eric Laurent53334cd2010-06-23 17:38:20 -07005681 if (status == NO_ERROR) {
5682 status = cmdStatus;
5683 }
5684 }
5685 return status;
5686}
5687
5688// update this table when AudioSystem::audio_devices or audio_device_e (in EffectApi.h) are modified
5689const uint32_t AudioFlinger::EffectModule::sDeviceConvTable[] = {
5690 DEVICE_EARPIECE, // AudioSystem::DEVICE_OUT_EARPIECE
5691 DEVICE_SPEAKER, // AudioSystem::DEVICE_OUT_SPEAKER
5692 DEVICE_WIRED_HEADSET, // case AudioSystem::DEVICE_OUT_WIRED_HEADSET
5693 DEVICE_WIRED_HEADPHONE, // AudioSystem::DEVICE_OUT_WIRED_HEADPHONE
5694 DEVICE_BLUETOOTH_SCO, // AudioSystem::DEVICE_OUT_BLUETOOTH_SCO
5695 DEVICE_BLUETOOTH_SCO_HEADSET, // AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_HEADSET
5696 DEVICE_BLUETOOTH_SCO_CARKIT, // AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_CARKIT
5697 DEVICE_BLUETOOTH_A2DP, // AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP
5698 DEVICE_BLUETOOTH_A2DP_HEADPHONES, // AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES
5699 DEVICE_BLUETOOTH_A2DP_SPEAKER, // AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER
5700 DEVICE_AUX_DIGITAL // AudioSystem::DEVICE_OUT_AUX_DIGITAL
5701};
5702
5703uint32_t AudioFlinger::EffectModule::deviceAudioSystemToEffectApi(uint32_t device)
5704{
5705 uint32_t deviceOut = 0;
5706 while (device) {
5707 const uint32_t i = 31 - __builtin_clz(device);
5708 device &= ~(1 << i);
5709 if (i >= sizeof(sDeviceConvTable)/sizeof(uint32_t)) {
5710 LOGE("device convertion error for AudioSystem device 0x%08x", device);
5711 return 0;
5712 }
5713 deviceOut |= (uint32_t)sDeviceConvTable[i];
5714 }
5715 return deviceOut;
5716}
5717
5718// update this table when AudioSystem::audio_mode or audio_mode_e (in EffectApi.h) are modified
5719const uint32_t AudioFlinger::EffectModule::sModeConvTable[] = {
5720 AUDIO_MODE_NORMAL, // AudioSystem::MODE_NORMAL
5721 AUDIO_MODE_RINGTONE, // AudioSystem::MODE_RINGTONE
Jean-Michel Trivi8f677d62010-11-15 12:11:32 -08005722 AUDIO_MODE_IN_CALL, // AudioSystem::MODE_IN_CALL
5723 AUDIO_MODE_IN_CALL // AudioSystem::MODE_IN_COMMUNICATION, same conversion as for MODE_IN_CALL
Eric Laurent53334cd2010-06-23 17:38:20 -07005724};
5725
5726int AudioFlinger::EffectModule::modeAudioSystemToEffectApi(uint32_t mode)
5727{
5728 int modeOut = -1;
5729 if (mode < sizeof(sModeConvTable) / sizeof(uint32_t)) {
5730 modeOut = (int)sModeConvTable[mode];
5731 }
5732 return modeOut;
5733}
Eric Laurent65b65452010-06-01 23:49:17 -07005734
5735status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
5736{
5737 const size_t SIZE = 256;
5738 char buffer[SIZE];
5739 String8 result;
5740
5741 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
5742 result.append(buffer);
5743
5744 bool locked = tryLock(mLock);
5745 // failed to lock - AudioFlinger is probably deadlocked
5746 if (!locked) {
5747 result.append("\t\tCould not lock Fx mutex:\n");
5748 }
5749
5750 result.append("\t\tSession Status State Engine:\n");
5751 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
5752 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
5753 result.append(buffer);
5754
5755 result.append("\t\tDescriptor:\n");
5756 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
5757 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
5758 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
5759 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
5760 result.append(buffer);
5761 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
5762 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
5763 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
5764 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
5765 result.append(buffer);
5766 snprintf(buffer, SIZE, "\t\t- apiVersion: %04X\n\t\t- flags: %08X\n",
5767 mDescriptor.apiVersion,
5768 mDescriptor.flags);
5769 result.append(buffer);
5770 snprintf(buffer, SIZE, "\t\t- name: %s\n",
5771 mDescriptor.name);
5772 result.append(buffer);
5773 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
5774 mDescriptor.implementor);
5775 result.append(buffer);
5776
5777 result.append("\t\t- Input configuration:\n");
5778 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
5779 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
5780 (uint32_t)mConfig.inputCfg.buffer.raw,
5781 mConfig.inputCfg.buffer.frameCount,
5782 mConfig.inputCfg.samplingRate,
5783 mConfig.inputCfg.channels,
5784 mConfig.inputCfg.format);
5785 result.append(buffer);
5786
5787 result.append("\t\t- Output configuration:\n");
5788 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
5789 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
5790 (uint32_t)mConfig.outputCfg.buffer.raw,
5791 mConfig.outputCfg.buffer.frameCount,
5792 mConfig.outputCfg.samplingRate,
5793 mConfig.outputCfg.channels,
5794 mConfig.outputCfg.format);
5795 result.append(buffer);
5796
5797 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
5798 result.append(buffer);
5799 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
5800 for (size_t i = 0; i < mHandles.size(); ++i) {
5801 sp<EffectHandle> handle = mHandles[i].promote();
5802 if (handle != 0) {
5803 handle->dump(buffer, SIZE);
5804 result.append(buffer);
5805 }
5806 }
5807
5808 result.append("\n");
5809
5810 write(fd, result.string(), result.length());
5811
5812 if (locked) {
5813 mLock.unlock();
5814 }
5815
5816 return NO_ERROR;
5817}
5818
5819// ----------------------------------------------------------------------------
5820// EffectHandle implementation
5821// ----------------------------------------------------------------------------
5822
5823#undef LOG_TAG
5824#define LOG_TAG "AudioFlinger::EffectHandle"
5825
5826AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
5827 const sp<AudioFlinger::Client>& client,
5828 const sp<IEffectClient>& effectClient,
5829 int32_t priority)
5830 : BnEffect(),
5831 mEffect(effect), mEffectClient(effectClient), mClient(client), mPriority(priority), mHasControl(false)
5832{
5833 LOGV("constructor %p", this);
5834
5835 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
5836 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
5837 if (mCblkMemory != 0) {
5838 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
5839
5840 if (mCblk) {
5841 new(mCblk) effect_param_cblk_t();
5842 mBuffer = (uint8_t *)mCblk + bufOffset;
5843 }
5844 } else {
5845 LOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
5846 return;
5847 }
5848}
5849
5850AudioFlinger::EffectHandle::~EffectHandle()
5851{
5852 LOGV("Destructor %p", this);
5853 disconnect();
5854}
5855
5856status_t AudioFlinger::EffectHandle::enable()
5857{
5858 if (!mHasControl) return INVALID_OPERATION;
5859 if (mEffect == 0) return DEAD_OBJECT;
5860
5861 return mEffect->setEnabled(true);
5862}
5863
5864status_t AudioFlinger::EffectHandle::disable()
5865{
5866 if (!mHasControl) return INVALID_OPERATION;
5867 if (mEffect == NULL) return DEAD_OBJECT;
5868
5869 return mEffect->setEnabled(false);
5870}
5871
5872void AudioFlinger::EffectHandle::disconnect()
5873{
5874 if (mEffect == 0) {
5875 return;
5876 }
5877 mEffect->disconnect(this);
5878 // release sp on module => module destructor can be called now
5879 mEffect.clear();
5880 if (mCblk) {
5881 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
5882 }
5883 mCblkMemory.clear(); // and free the shared memory
5884 if (mClient != 0) {
5885 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
5886 mClient.clear();
5887 }
5888}
5889
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005890status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
5891 uint32_t cmdSize,
5892 void *pCmdData,
5893 uint32_t *replySize,
5894 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07005895{
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005896// LOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
5897// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Eric Laurent65b65452010-06-01 23:49:17 -07005898
5899 // only get parameter command is permitted for applications not controlling the effect
5900 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
5901 return INVALID_OPERATION;
5902 }
5903 if (mEffect == 0) return DEAD_OBJECT;
5904
5905 // handle commands that are not forwarded transparently to effect engine
5906 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
5907 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
5908 // no risk to block the whole media server process or mixer threads is we are stuck here
5909 Mutex::Autolock _l(mCblk->lock);
5910 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
5911 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
5912 mCblk->serverIndex = 0;
5913 mCblk->clientIndex = 0;
5914 return BAD_VALUE;
5915 }
5916 status_t status = NO_ERROR;
5917 while (mCblk->serverIndex < mCblk->clientIndex) {
5918 int reply;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005919 uint32_t rsize = sizeof(int);
Eric Laurent65b65452010-06-01 23:49:17 -07005920 int *p = (int *)(mBuffer + mCblk->serverIndex);
5921 int size = *p++;
Eric Laurent53334cd2010-06-23 17:38:20 -07005922 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
5923 LOGW("command(): invalid parameter block size");
5924 break;
5925 }
Eric Laurent65b65452010-06-01 23:49:17 -07005926 effect_param_t *param = (effect_param_t *)p;
Eric Laurent53334cd2010-06-23 17:38:20 -07005927 if (param->psize == 0 || param->vsize == 0) {
5928 LOGW("command(): null parameter or value size");
5929 mCblk->serverIndex += size;
5930 continue;
5931 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005932 uint32_t psize = sizeof(effect_param_t) +
5933 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
5934 param->vsize;
5935 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
5936 psize,
5937 p,
5938 &rsize,
5939 &reply);
Eric Laurente65280c2010-09-02 11:56:55 -07005940 // stop at first error encountered
5941 if (ret != NO_ERROR) {
Eric Laurent65b65452010-06-01 23:49:17 -07005942 status = ret;
Eric Laurente65280c2010-09-02 11:56:55 -07005943 *(int *)pReplyData = reply;
5944 break;
5945 } else if (reply != NO_ERROR) {
5946 *(int *)pReplyData = reply;
5947 break;
Eric Laurent65b65452010-06-01 23:49:17 -07005948 }
5949 mCblk->serverIndex += size;
5950 }
5951 mCblk->serverIndex = 0;
5952 mCblk->clientIndex = 0;
5953 return status;
5954 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurente65280c2010-09-02 11:56:55 -07005955 *(int *)pReplyData = NO_ERROR;
Eric Laurent65b65452010-06-01 23:49:17 -07005956 return enable();
5957 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurente65280c2010-09-02 11:56:55 -07005958 *(int *)pReplyData = NO_ERROR;
Eric Laurent65b65452010-06-01 23:49:17 -07005959 return disable();
5960 }
5961
5962 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
5963}
5964
5965sp<IMemory> AudioFlinger::EffectHandle::getCblk() const {
5966 return mCblkMemory;
5967}
5968
5969void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal)
5970{
5971 LOGV("setControl %p control %d", this, hasControl);
5972
5973 mHasControl = hasControl;
5974 if (signal && mEffectClient != 0) {
5975 mEffectClient->controlStatusChanged(hasControl);
5976 }
5977}
5978
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005979void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
5980 uint32_t cmdSize,
5981 void *pCmdData,
5982 uint32_t replySize,
5983 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07005984{
5985 if (mEffectClient != 0) {
5986 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
5987 }
5988}
5989
5990
5991
5992void AudioFlinger::EffectHandle::setEnabled(bool enabled)
5993{
5994 if (mEffectClient != 0) {
5995 mEffectClient->enableStatusChanged(enabled);
5996 }
5997}
5998
5999status_t AudioFlinger::EffectHandle::onTransact(
6000 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6001{
6002 return BnEffect::onTransact(code, data, reply, flags);
6003}
6004
6005
6006void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
6007{
6008 bool locked = tryLock(mCblk->lock);
6009
6010 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
6011 (mClient == NULL) ? getpid() : mClient->pid(),
6012 mPriority,
6013 mHasControl,
6014 !locked,
6015 mCblk->clientIndex,
6016 mCblk->serverIndex
6017 );
6018
6019 if (locked) {
6020 mCblk->lock.unlock();
6021 }
6022}
6023
6024#undef LOG_TAG
6025#define LOG_TAG "AudioFlinger::EffectChain"
6026
6027AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
6028 int sessionId)
Eric Laurent76c40f72010-07-15 12:50:15 -07006029 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mOwnInBuffer(false),
Eric Laurent2a6b80b2010-07-29 23:43:43 -07006030 mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
6031 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Eric Laurent65b65452010-06-01 23:49:17 -07006032{
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006033 mStrategy = AudioSystem::getStrategyForStream(AudioSystem::MUSIC);
Eric Laurent65b65452010-06-01 23:49:17 -07006034}
6035
6036AudioFlinger::EffectChain::~EffectChain()
6037{
6038 if (mOwnInBuffer) {
6039 delete mInBuffer;
6040 }
6041
6042}
6043
Eric Laurent76c40f72010-07-15 12:50:15 -07006044// getEffectFromDesc_l() must be called with PlaybackThread::mLock held
6045sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Eric Laurent65b65452010-06-01 23:49:17 -07006046{
6047 sp<EffectModule> effect;
6048 size_t size = mEffects.size();
6049
6050 for (size_t i = 0; i < size; i++) {
6051 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
6052 effect = mEffects[i];
6053 break;
6054 }
6055 }
6056 return effect;
6057}
6058
Eric Laurent76c40f72010-07-15 12:50:15 -07006059// getEffectFromId_l() must be called with PlaybackThread::mLock held
6060sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Eric Laurent65b65452010-06-01 23:49:17 -07006061{
6062 sp<EffectModule> effect;
6063 size_t size = mEffects.size();
6064
6065 for (size_t i = 0; i < size; i++) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006066 // by convention, return first effect if id provided is 0 (0 is never a valid id)
6067 if (id == 0 || mEffects[i]->id() == id) {
Eric Laurent65b65452010-06-01 23:49:17 -07006068 effect = mEffects[i];
6069 break;
6070 }
6071 }
6072 return effect;
6073}
6074
6075// Must be called with EffectChain::mLock locked
6076void AudioFlinger::EffectChain::process_l()
6077{
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07006078 sp<ThreadBase> thread = mThread.promote();
6079 if (thread == 0) {
6080 LOGW("process_l(): cannot promote mixer thread");
6081 return;
6082 }
6083 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
6084 bool isGlobalSession = (mSessionId == AudioSystem::SESSION_OUTPUT_MIX) ||
6085 (mSessionId == AudioSystem::SESSION_OUTPUT_STAGE);
6086 bool tracksOnSession = false;
6087 if (!isGlobalSession) {
6088 tracksOnSession =
6089 playbackThread->hasAudioSession(mSessionId) & PlaybackThread::TRACK_SESSION;
6090 }
6091
Eric Laurent65b65452010-06-01 23:49:17 -07006092 size_t size = mEffects.size();
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07006093 // do not process effect if no track is present in same audio session
6094 if (isGlobalSession || tracksOnSession) {
6095 for (size_t i = 0; i < size; i++) {
6096 mEffects[i]->process();
6097 }
Eric Laurent65b65452010-06-01 23:49:17 -07006098 }
Eric Laurent7d850f22010-07-09 13:34:17 -07006099 for (size_t i = 0; i < size; i++) {
6100 mEffects[i]->updateState();
6101 }
Eric Laurent65b65452010-06-01 23:49:17 -07006102 // if no track is active, input buffer must be cleared here as the mixer process
6103 // will not do it
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07006104 if (tracksOnSession &&
6105 activeTracks() == 0) {
6106 size_t numSamples = playbackThread->frameCount() * playbackThread->channelCount();
6107 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
Eric Laurent65b65452010-06-01 23:49:17 -07006108 }
6109}
6110
Eric Laurent76c40f72010-07-15 12:50:15 -07006111// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006112status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Eric Laurent65b65452010-06-01 23:49:17 -07006113{
6114 effect_descriptor_t desc = effect->desc();
6115 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
6116
6117 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006118 effect->setChain(this);
6119 sp<ThreadBase> thread = mThread.promote();
6120 if (thread == 0) {
6121 return NO_INIT;
6122 }
6123 effect->setThread(thread);
Eric Laurent65b65452010-06-01 23:49:17 -07006124
6125 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6126 // Auxiliary effects are inserted at the beginning of mEffects vector as
6127 // they are processed first and accumulated in chain input buffer
6128 mEffects.insertAt(effect, 0);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006129
Eric Laurent65b65452010-06-01 23:49:17 -07006130 // the input buffer for auxiliary effect contains mono samples in
6131 // 32 bit format. This is to avoid saturation in AudoMixer
6132 // accumulation stage. Saturation is done in EffectModule::process() before
6133 // calling the process in effect engine
6134 size_t numSamples = thread->frameCount();
6135 int32_t *buffer = new int32_t[numSamples];
6136 memset(buffer, 0, numSamples * sizeof(int32_t));
6137 effect->setInBuffer((int16_t *)buffer);
6138 // auxiliary effects output samples to chain input buffer for further processing
6139 // by insert effects
6140 effect->setOutBuffer(mInBuffer);
6141 } else {
6142 // Insert effects are inserted at the end of mEffects vector as they are processed
6143 // after track and auxiliary effects.
Eric Laurent53334cd2010-06-23 17:38:20 -07006144 // Insert effect order as a function of indicated preference:
6145 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
6146 // another effect is present
6147 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
6148 // last effect claiming first position
6149 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
6150 // first effect claiming last position
Eric Laurent65b65452010-06-01 23:49:17 -07006151 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
Eric Laurent53334cd2010-06-23 17:38:20 -07006152 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
6153 // already present
Eric Laurent65b65452010-06-01 23:49:17 -07006154
6155 int size = (int)mEffects.size();
6156 int idx_insert = size;
6157 int idx_insert_first = -1;
6158 int idx_insert_last = -1;
6159
6160 for (int i = 0; i < size; i++) {
6161 effect_descriptor_t d = mEffects[i]->desc();
6162 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
6163 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
6164 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
6165 // check invalid effect chaining combinations
6166 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
Eric Laurent53334cd2010-06-23 17:38:20 -07006167 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Eric Laurent76c40f72010-07-15 12:50:15 -07006168 LOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Eric Laurent65b65452010-06-01 23:49:17 -07006169 return INVALID_OPERATION;
6170 }
Eric Laurent53334cd2010-06-23 17:38:20 -07006171 // remember position of first insert effect and by default
6172 // select this as insert position for new effect
Eric Laurent65b65452010-06-01 23:49:17 -07006173 if (idx_insert == size) {
6174 idx_insert = i;
6175 }
Eric Laurent53334cd2010-06-23 17:38:20 -07006176 // remember position of last insert effect claiming
6177 // first position
Eric Laurent65b65452010-06-01 23:49:17 -07006178 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
6179 idx_insert_first = i;
6180 }
Eric Laurent53334cd2010-06-23 17:38:20 -07006181 // remember position of first insert effect claiming
6182 // last position
6183 if (iPref == EFFECT_FLAG_INSERT_LAST &&
6184 idx_insert_last == -1) {
Eric Laurent65b65452010-06-01 23:49:17 -07006185 idx_insert_last = i;
6186 }
6187 }
6188 }
6189
Eric Laurent53334cd2010-06-23 17:38:20 -07006190 // modify idx_insert from first position if needed
6191 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
6192 if (idx_insert_last != -1) {
6193 idx_insert = idx_insert_last;
6194 } else {
6195 idx_insert = size;
6196 }
6197 } else {
6198 if (idx_insert_first != -1) {
6199 idx_insert = idx_insert_first + 1;
6200 }
Eric Laurent65b65452010-06-01 23:49:17 -07006201 }
6202
6203 // always read samples from chain input buffer
6204 effect->setInBuffer(mInBuffer);
6205
6206 // if last effect in the chain, output samples to chain
6207 // output buffer, otherwise to chain input buffer
6208 if (idx_insert == size) {
6209 if (idx_insert != 0) {
6210 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
6211 mEffects[idx_insert-1]->configure();
6212 }
6213 effect->setOutBuffer(mOutBuffer);
6214 } else {
6215 effect->setOutBuffer(mInBuffer);
6216 }
Eric Laurent53334cd2010-06-23 17:38:20 -07006217 mEffects.insertAt(effect, idx_insert);
Eric Laurent65b65452010-06-01 23:49:17 -07006218
Eric Laurent76c40f72010-07-15 12:50:15 -07006219 LOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Eric Laurent65b65452010-06-01 23:49:17 -07006220 }
6221 effect->configure();
6222 return NO_ERROR;
6223}
6224
Eric Laurent76c40f72010-07-15 12:50:15 -07006225// removeEffect_l() must be called with PlaybackThread::mLock held
6226size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Eric Laurent65b65452010-06-01 23:49:17 -07006227{
6228 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07006229 int size = (int)mEffects.size();
6230 int i;
6231 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
6232
6233 for (i = 0; i < size; i++) {
6234 if (effect == mEffects[i]) {
6235 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
6236 delete[] effect->inBuffer();
6237 } else {
6238 if (i == size - 1 && i != 0) {
6239 mEffects[i - 1]->setOutBuffer(mOutBuffer);
6240 mEffects[i - 1]->configure();
6241 }
6242 }
6243 mEffects.removeAt(i);
Eric Laurent76c40f72010-07-15 12:50:15 -07006244 LOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Eric Laurent65b65452010-06-01 23:49:17 -07006245 break;
6246 }
6247 }
Eric Laurent65b65452010-06-01 23:49:17 -07006248
6249 return mEffects.size();
6250}
6251
Eric Laurent76c40f72010-07-15 12:50:15 -07006252// setDevice_l() must be called with PlaybackThread::mLock held
6253void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Eric Laurent65b65452010-06-01 23:49:17 -07006254{
6255 size_t size = mEffects.size();
6256 for (size_t i = 0; i < size; i++) {
6257 mEffects[i]->setDevice(device);
6258 }
6259}
6260
Eric Laurent76c40f72010-07-15 12:50:15 -07006261// setMode_l() must be called with PlaybackThread::mLock held
6262void AudioFlinger::EffectChain::setMode_l(uint32_t mode)
Eric Laurent53334cd2010-06-23 17:38:20 -07006263{
6264 size_t size = mEffects.size();
6265 for (size_t i = 0; i < size; i++) {
6266 mEffects[i]->setMode(mode);
6267 }
6268}
6269
Eric Laurent76c40f72010-07-15 12:50:15 -07006270// setVolume_l() must be called with PlaybackThread::mLock held
6271bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Eric Laurent65b65452010-06-01 23:49:17 -07006272{
6273 uint32_t newLeft = *left;
6274 uint32_t newRight = *right;
6275 bool hasControl = false;
Eric Laurent76c40f72010-07-15 12:50:15 -07006276 int ctrlIdx = -1;
6277 size_t size = mEffects.size();
Eric Laurent65b65452010-06-01 23:49:17 -07006278
Eric Laurent76c40f72010-07-15 12:50:15 -07006279 // first update volume controller
6280 for (size_t i = size; i > 0; i--) {
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006281 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurent76c40f72010-07-15 12:50:15 -07006282 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
6283 ctrlIdx = i - 1;
Eric Laurent0d7e0482010-07-19 06:24:46 -07006284 hasControl = true;
Eric Laurent76c40f72010-07-15 12:50:15 -07006285 break;
6286 }
6287 }
6288
6289 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurent0d7e0482010-07-19 06:24:46 -07006290 if (hasControl) {
6291 *left = mNewLeftVolume;
6292 *right = mNewRightVolume;
6293 }
6294 return hasControl;
Eric Laurent76c40f72010-07-15 12:50:15 -07006295 }
6296
6297 mVolumeCtrlIdx = ctrlIdx;
Eric Laurent0d7e0482010-07-19 06:24:46 -07006298 mLeftVolume = newLeft;
6299 mRightVolume = newRight;
Eric Laurent76c40f72010-07-15 12:50:15 -07006300
6301 // second get volume update from volume controller
6302 if (ctrlIdx >= 0) {
6303 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurent0d7e0482010-07-19 06:24:46 -07006304 mNewLeftVolume = newLeft;
6305 mNewRightVolume = newRight;
Eric Laurent65b65452010-06-01 23:49:17 -07006306 }
6307 // then indicate volume to all other effects in chain.
6308 // Pass altered volume to effects before volume controller
6309 // and requested volume to effects after controller
6310 uint32_t lVol = newLeft;
6311 uint32_t rVol = newRight;
Eric Laurent76c40f72010-07-15 12:50:15 -07006312
Eric Laurent65b65452010-06-01 23:49:17 -07006313 for (size_t i = 0; i < size; i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07006314 if ((int)i == ctrlIdx) continue;
6315 // this also works for ctrlIdx == -1 when there is no volume controller
6316 if ((int)i > ctrlIdx) {
Eric Laurent65b65452010-06-01 23:49:17 -07006317 lVol = *left;
6318 rVol = *right;
6319 }
6320 mEffects[i]->setVolume(&lVol, &rVol, false);
6321 }
6322 *left = newLeft;
6323 *right = newRight;
6324
6325 return hasControl;
6326}
6327
Eric Laurent65b65452010-06-01 23:49:17 -07006328status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
6329{
6330 const size_t SIZE = 256;
6331 char buffer[SIZE];
6332 String8 result;
6333
6334 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
6335 result.append(buffer);
6336
6337 bool locked = tryLock(mLock);
6338 // failed to lock - AudioFlinger is probably deadlocked
6339 if (!locked) {
6340 result.append("\tCould not lock mutex:\n");
6341 }
6342
Eric Laurent76c40f72010-07-15 12:50:15 -07006343 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
6344 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Eric Laurent65b65452010-06-01 23:49:17 -07006345 mEffects.size(),
6346 (uint32_t)mInBuffer,
6347 (uint32_t)mOutBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -07006348 mActiveTrackCnt);
6349 result.append(buffer);
6350 write(fd, result.string(), result.size());
6351
6352 for (size_t i = 0; i < mEffects.size(); ++i) {
6353 sp<EffectModule> effect = mEffects[i];
6354 if (effect != 0) {
6355 effect->dump(fd, args);
6356 }
6357 }
6358
6359 if (locked) {
6360 mLock.unlock();
6361 }
6362
6363 return NO_ERROR;
6364}
6365
6366#undef LOG_TAG
6367#define LOG_TAG "AudioFlinger"
6368
Eric Laurenta553c252009-07-17 12:17:14 -07006369// ----------------------------------------------------------------------------
6370
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07006371status_t AudioFlinger::onTransact(
6372 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6373{
6374 return BnAudioFlinger::onTransact(code, data, reply, flags);
6375}
6376
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07006377}; // namespace android