blob: 024868729adb12379a7d47fc5a72ef51fbb57396 [file] [log] [blame]
Glenn Kasten99e53b82012-01-19 08:59:58 -08001/*
Mathias Agopian65ab4712010-07-14 17:59:35 -07002**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
22#include <math.h>
23#include <signal.h>
24#include <sys/time.h>
25#include <sys/resource.h>
26
Gloria Wang9ee159b2011-02-24 14:51:45 -080027#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070028#include <binder/IServiceManager.h>
29#include <utils/Log.h>
30#include <binder/Parcel.h>
31#include <binder/IPCThreadState.h>
32#include <utils/String16.h>
33#include <utils/threads.h>
Eric Laurent38ccae22011-03-28 18:37:07 -070034#include <utils/Atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070035
Dima Zavinfce7a472011-04-19 22:30:36 -070036#include <cutils/bitops.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070037#include <cutils/properties.h>
Glenn Kastenf6b16782011-12-15 09:51:17 -080038#include <cutils/compiler.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070039
Gloria Wang9ee159b2011-02-24 14:51:45 -080040#include <media/IMediaPlayerService.h>
Glenn Kasten25b248e2012-01-03 15:28:29 -080041#include <media/IMediaDeathNotifier.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070042
43#include <private/media/AudioTrackShared.h>
44#include <private/media/AudioEffectShared.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070045
Dima Zavin64760242011-05-11 14:15:23 -070046#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070047#include <hardware/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070048
49#include "AudioMixer.h"
50#include "AudioFlinger.h"
Glenn Kasten44deb052012-02-05 18:09:08 -080051#include "ServiceUtilities.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070052
Mathias Agopian65ab4712010-07-14 17:59:35 -070053#include <media/EffectsFactoryApi.h>
Eric Laurent6d8b6942011-06-24 07:01:31 -070054#include <audio_effects/effect_visualizer.h>
Eric Laurent59bd0da2011-08-01 09:52:20 -070055#include <audio_effects/effect_ns.h>
56#include <audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070057
Glenn Kasten3b21c502011-12-15 09:52:39 -080058#include <audio_utils/primitives.h>
59
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070060#include <cpustats/ThreadCpuUsage.h>
Eric Laurentfeb0db62011-07-22 09:04:31 -070061#include <powermanager/PowerManager.h>
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070062// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
63
Mathias Agopian65ab4712010-07-14 17:59:35 -070064// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070065
Eric Laurentde070132010-07-13 04:45:46 -070066
Mathias Agopian65ab4712010-07-14 17:59:35 -070067namespace android {
68
Glenn Kastenec1d6b52011-12-12 09:04:45 -080069static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
70static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -070071
72//static const nsecs_t kStandbyTimeInNsecs = seconds(3);
73static const float MAX_GAIN = 4096.0f;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -080074static const uint32_t MAX_GAIN_INT = 0x1000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070075
76// retry counts for buffer fill timeout
77// 50 * ~20msecs = 1 second
78static const int8_t kMaxTrackRetries = 50;
79static const int8_t kMaxTrackStartupRetries = 50;
80// allow less retry attempts on direct output thread.
81// direct outputs can be a scarce resource in audio hardware and should
82// be released as quickly as possible.
83static const int8_t kMaxTrackRetriesDirect = 2;
84
85static const int kDumpLockRetries = 50;
Glenn Kasten7dede872011-12-13 11:04:14 -080086static const int kDumpLockSleepUs = 20000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070087
Glenn Kasten7dede872011-12-13 11:04:14 -080088// don't warn about blocked writes or record buffer overflows more often than this
89static const nsecs_t kWarningThrottleNs = seconds(5);
Mathias Agopian65ab4712010-07-14 17:59:35 -070090
Eric Laurent7c7f10b2011-06-17 21:29:58 -070091// RecordThread loop sleep time upon application overrun or audio HAL read error
92static const int kRecordThreadSleepUs = 5000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070093
Glenn Kasten7dede872011-12-13 11:04:14 -080094// maximum time to wait for setParameters to complete
95static const nsecs_t kSetParametersTimeoutNs = seconds(2);
Eric Laurent60cd0a02011-09-13 11:40:21 -070096
Eric Laurent7cafbb32011-11-22 18:50:29 -080097// minimum sleep time for the mixer thread loop when tracks are active but in underrun
98static const uint32_t kMinThreadSleepTimeUs = 5000;
99// maximum divider applied to the active sleep time in the mixer thread loop
100static const uint32_t kMaxThreadSleepTimeShift = 2;
101
102
Mathias Agopian65ab4712010-07-14 17:59:35 -0700103// ----------------------------------------------------------------------------
104
Gloria Wang9ee159b2011-02-24 14:51:45 -0800105// To collect the amplifier usage
106static void addBatteryData(uint32_t params) {
Glenn Kasten25b248e2012-01-03 15:28:29 -0800107 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
108 if (service == NULL) {
109 // it already logged
Gloria Wang9ee159b2011-02-24 14:51:45 -0800110 return;
111 }
112
113 service->addBatteryData(params);
114}
115
Dima Zavin799a70e2011-04-18 16:57:27 -0700116static int load_audio_interface(const char *if_name, const hw_module_t **mod,
117 audio_hw_device_t **dev)
118{
119 int rc;
120
121 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, mod);
122 if (rc)
123 goto out;
124
125 rc = audio_hw_device_open(*mod, dev);
Steve Block29357bc2012-01-06 19:20:56 +0000126 ALOGE_IF(rc, "couldn't open audio hw device in %s.%s (%s)",
Dima Zavin799a70e2011-04-18 16:57:27 -0700127 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
128 if (rc)
129 goto out;
130
131 return 0;
132
133out:
134 *mod = NULL;
135 *dev = NULL;
136 return rc;
137}
138
Glenn Kastenec1d6b52011-12-12 09:04:45 -0800139static const char * const audio_interfaces[] = {
Dima Zavin799a70e2011-04-18 16:57:27 -0700140 "primary",
141 "a2dp",
142 "usb",
143};
144#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
145
Mathias Agopian65ab4712010-07-14 17:59:35 -0700146// ----------------------------------------------------------------------------
147
148AudioFlinger::AudioFlinger()
149 : BnAudioFlinger(),
Glenn Kasten84afa3b2012-01-25 15:28:08 -0800150 mPrimaryHardwareDev(NULL),
151 mHardwareStatus(AUDIO_HW_IDLE), // see also onFirstRef()
152 mMasterVolume(1.0f), mMasterMute(false), mNextUniqueId(1),
153 mMode(AUDIO_MODE_INVALID),
Eric Laurentbee53372011-08-29 12:42:48 -0700154 mBtNrecIsOff(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700155{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700156}
157
158void AudioFlinger::onFirstRef()
159{
Dima Zavin799a70e2011-04-18 16:57:27 -0700160 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700161
Eric Laurent93575202011-01-18 18:39:02 -0800162 Mutex::Autolock _l(mLock);
163
Dima Zavin799a70e2011-04-18 16:57:27 -0700164 /* TODO: move all this work into an Init() function */
Mathias Agopian65ab4712010-07-14 17:59:35 -0700165
Dima Zavin799a70e2011-04-18 16:57:27 -0700166 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
167 const hw_module_t *mod;
168 audio_hw_device_t *dev;
Dima Zavinfce7a472011-04-19 22:30:36 -0700169
Dima Zavin799a70e2011-04-18 16:57:27 -0700170 rc = load_audio_interface(audio_interfaces[i], &mod, &dev);
171 if (rc)
172 continue;
173
Steve Blockdf64d152012-01-04 20:05:49 +0000174 ALOGI("Loaded %s audio interface from %s (%s)", audio_interfaces[i],
Dima Zavin799a70e2011-04-18 16:57:27 -0700175 mod->name, mod->id);
176 mAudioHwDevs.push(dev);
177
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800178 if (mPrimaryHardwareDev == NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700179 mPrimaryHardwareDev = dev;
Steve Blockdf64d152012-01-04 20:05:49 +0000180 ALOGI("Using '%s' (%s.%s) as the primary audio interface",
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700181 mod->name, mod->id, audio_interfaces[i]);
Dima Zavin799a70e2011-04-18 16:57:27 -0700182 }
183 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700184
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800185 if (mPrimaryHardwareDev == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000186 ALOGE("Primary audio interface not found");
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800187 // proceed, all later accesses to mPrimaryHardwareDev verify it's safe with initCheck()
Dima Zavin799a70e2011-04-18 16:57:27 -0700188 }
189
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800190 // Currently (mPrimaryHardwareDev == NULL) == (mAudioHwDevs.size() == 0), but the way the
191 // primary HW dev is selected can change so these conditions might not always be equivalent.
192 // When that happens, re-visit all the code that assumes this.
193
194 AutoMutex lock(mHardwareLock);
195
Dima Zavin799a70e2011-04-18 16:57:27 -0700196 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
197 audio_hw_device_t *dev = mAudioHwDevs[i];
198
199 mHardwareStatus = AUDIO_HW_INIT;
200 rc = dev->init_check(dev);
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800201 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700202 if (rc == 0) {
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800203 mMode = AUDIO_MODE_NORMAL; // assigned multiple times with same value
Dima Zavin799a70e2011-04-18 16:57:27 -0700204 mHardwareStatus = AUDIO_HW_SET_MODE;
205 dev->set_mode(dev, mMode);
206 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
207 dev->set_master_volume(dev, 1.0f);
208 mHardwareStatus = AUDIO_HW_IDLE;
209 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700210 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700211}
212
213AudioFlinger::~AudioFlinger()
214{
Dima Zavin799a70e2011-04-18 16:57:27 -0700215
Mathias Agopian65ab4712010-07-14 17:59:35 -0700216 while (!mRecordThreads.isEmpty()) {
217 // closeInput() will remove first entry from mRecordThreads
218 closeInput(mRecordThreads.keyAt(0));
219 }
220 while (!mPlaybackThreads.isEmpty()) {
221 // closeOutput() will remove first entry from mPlaybackThreads
222 closeOutput(mPlaybackThreads.keyAt(0));
223 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700224
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800225 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
226 // no mHardwareLock needed, as there are no other references to this
227 audio_hw_device_close(mAudioHwDevs[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700228 }
229}
230
Dima Zavin799a70e2011-04-18 16:57:27 -0700231audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(uint32_t devices)
232{
233 /* first matching HW device is returned */
234 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
235 audio_hw_device_t *dev = mAudioHwDevs[i];
236 if ((dev->get_supported_devices(dev) & devices) == devices)
237 return dev;
238 }
239 return NULL;
240}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700241
242status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
243{
244 const size_t SIZE = 256;
245 char buffer[SIZE];
246 String8 result;
247
248 result.append("Clients:\n");
249 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800250 sp<Client> client = mClients.valueAt(i).promote();
251 if (client != 0) {
252 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
253 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700254 }
255 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700256
257 result.append("Global session refs:\n");
258 result.append(" session pid cnt\n");
259 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
260 AudioSessionRef *r = mAudioSessionRefs[i];
261 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->sessionid, r->pid, r->cnt);
262 result.append(buffer);
263 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700264 write(fd, result.string(), result.size());
265 return NO_ERROR;
266}
267
268
269status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
270{
271 const size_t SIZE = 256;
272 char buffer[SIZE];
273 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800274 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700275
276 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
277 result.append(buffer);
278 write(fd, result.string(), result.size());
279 return NO_ERROR;
280}
281
282status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
283{
284 const size_t SIZE = 256;
285 char buffer[SIZE];
286 String8 result;
287 snprintf(buffer, SIZE, "Permission Denial: "
288 "can't dump AudioFlinger from pid=%d, uid=%d\n",
289 IPCThreadState::self()->getCallingPid(),
290 IPCThreadState::self()->getCallingUid());
291 result.append(buffer);
292 write(fd, result.string(), result.size());
293 return NO_ERROR;
294}
295
296static bool tryLock(Mutex& mutex)
297{
298 bool locked = false;
299 for (int i = 0; i < kDumpLockRetries; ++i) {
300 if (mutex.tryLock() == NO_ERROR) {
301 locked = true;
302 break;
303 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800304 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700305 }
306 return locked;
307}
308
309status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
310{
Glenn Kasten44deb052012-02-05 18:09:08 -0800311 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700312 dumpPermissionDenial(fd, args);
313 } else {
314 // get state of hardware lock
315 bool hardwareLocked = tryLock(mHardwareLock);
316 if (!hardwareLocked) {
317 String8 result(kHardwareLockedString);
318 write(fd, result.string(), result.size());
319 } else {
320 mHardwareLock.unlock();
321 }
322
323 bool locked = tryLock(mLock);
324
325 // failed to lock - AudioFlinger is probably deadlocked
326 if (!locked) {
327 String8 result(kDeadlockedString);
328 write(fd, result.string(), result.size());
329 }
330
331 dumpClients(fd, args);
332 dumpInternals(fd, args);
333
334 // dump playback threads
335 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
336 mPlaybackThreads.valueAt(i)->dump(fd, args);
337 }
338
339 // dump record threads
340 for (size_t i = 0; i < mRecordThreads.size(); i++) {
341 mRecordThreads.valueAt(i)->dump(fd, args);
342 }
343
Dima Zavin799a70e2011-04-18 16:57:27 -0700344 // dump all hardware devs
345 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
346 audio_hw_device_t *dev = mAudioHwDevs[i];
347 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700348 }
349 if (locked) mLock.unlock();
350 }
351 return NO_ERROR;
352}
353
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800354sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid)
355{
356 // If pid is already in the mClients wp<> map, then use that entry
357 // (for which promote() is always != 0), otherwise create a new entry and Client.
358 sp<Client> client = mClients.valueFor(pid).promote();
359 if (client == 0) {
360 client = new Client(this, pid);
361 mClients.add(pid, client);
362 }
363
364 return client;
365}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700366
367// IAudioFlinger interface
368
369
370sp<IAudioTrack> AudioFlinger::createTrack(
371 pid_t pid,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800372 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700373 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800374 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700375 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700376 int frameCount,
377 uint32_t flags,
378 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800379 audio_io_handle_t output,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700380 int *sessionId,
381 status_t *status)
382{
383 sp<PlaybackThread::Track> track;
384 sp<TrackHandle> trackHandle;
385 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700386 status_t lStatus;
387 int lSessionId;
388
Glenn Kasten263709e2012-01-06 08:40:01 -0800389 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
390 // but if someone uses binder directly they could bypass that and cause us to crash
391 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000392 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700393 lStatus = BAD_VALUE;
394 goto Exit;
395 }
396
397 {
398 Mutex::Autolock _l(mLock);
399 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700400 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700401 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000402 ALOGE("unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700403 lStatus = BAD_VALUE;
404 goto Exit;
405 }
406
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800407 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700408
Steve Block3856b092011-10-20 11:56:00 +0100409 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700410 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentde070132010-07-13 04:45:46 -0700411 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700412 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
413 if (mPlaybackThreads.keyAt(i) != output) {
414 // prevent same audio session on different output threads
415 uint32_t sessions = t->hasAudioSession(*sessionId);
416 if (sessions & PlaybackThread::TRACK_SESSION) {
Steve Block29357bc2012-01-06 19:20:56 +0000417 ALOGE("createTrack() session ID %d already in use", *sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700418 lStatus = BAD_VALUE;
419 goto Exit;
420 }
421 // check if an effect with same session ID is waiting for a track to be created
422 if (sessions & PlaybackThread::EFFECT_SESSION) {
423 effectThread = t.get();
424 }
Eric Laurentde070132010-07-13 04:45:46 -0700425 }
426 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700427 lSessionId = *sessionId;
428 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700429 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700430 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700431 if (sessionId != NULL) {
432 *sessionId = lSessionId;
433 }
434 }
Steve Block3856b092011-10-20 11:56:00 +0100435 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700436
437 track = thread->createTrack_l(client, streamType, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700438 channelMask, frameCount, sharedBuffer, lSessionId, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700439
440 // move effect chain to this output thread if an effect on same session was waiting
441 // for a track to be created
442 if (lStatus == NO_ERROR && effectThread != NULL) {
443 Mutex::Autolock _dl(thread->mLock);
444 Mutex::Autolock _sl(effectThread->mLock);
445 moveEffectChain_l(lSessionId, effectThread, thread, true);
446 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700447 }
448 if (lStatus == NO_ERROR) {
449 trackHandle = new TrackHandle(track);
450 } else {
451 // remove local strong reference to Client before deleting the Track so that the Client
452 // destructor is called by the TrackBase destructor with mLock held
453 client.clear();
454 track.clear();
455 }
456
457Exit:
458 if(status) {
459 *status = lStatus;
460 }
461 return trackHandle;
462}
463
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800464uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700465{
466 Mutex::Autolock _l(mLock);
467 PlaybackThread *thread = checkPlaybackThread_l(output);
468 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000469 ALOGW("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700470 return 0;
471 }
472 return thread->sampleRate();
473}
474
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800475int AudioFlinger::channelCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700476{
477 Mutex::Autolock _l(mLock);
478 PlaybackThread *thread = checkPlaybackThread_l(output);
479 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000480 ALOGW("channelCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700481 return 0;
482 }
483 return thread->channelCount();
484}
485
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800486audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700487{
488 Mutex::Autolock _l(mLock);
489 PlaybackThread *thread = checkPlaybackThread_l(output);
490 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000491 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800492 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700493 }
494 return thread->format();
495}
496
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800497size_t AudioFlinger::frameCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700498{
499 Mutex::Autolock _l(mLock);
500 PlaybackThread *thread = checkPlaybackThread_l(output);
501 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000502 ALOGW("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700503 return 0;
504 }
505 return thread->frameCount();
506}
507
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800508uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700509{
510 Mutex::Autolock _l(mLock);
511 PlaybackThread *thread = checkPlaybackThread_l(output);
512 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000513 ALOGW("latency() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700514 return 0;
515 }
516 return thread->latency();
517}
518
519status_t AudioFlinger::setMasterVolume(float value)
520{
Eric Laurenta1884f92011-08-23 08:25:03 -0700521 status_t ret = initCheck();
522 if (ret != NO_ERROR) {
523 return ret;
524 }
525
Mathias Agopian65ab4712010-07-14 17:59:35 -0700526 // check calling permissions
527 if (!settingsAllowed()) {
528 return PERMISSION_DENIED;
529 }
530
531 // when hw supports master volume, don't scale in sw mixer
Eric Laurent93575202011-01-18 18:39:02 -0800532 { // scope for the lock
533 AutoMutex lock(mHardwareLock);
534 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Dima Zavin799a70e2011-04-18 16:57:27 -0700535 if (mPrimaryHardwareDev->set_master_volume(mPrimaryHardwareDev, value) == NO_ERROR) {
Eric Laurent93575202011-01-18 18:39:02 -0800536 value = 1.0f;
537 }
538 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700539 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700540
Eric Laurent93575202011-01-18 18:39:02 -0800541 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700542 mMasterVolume = value;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800543 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700544 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
545
546 return NO_ERROR;
547}
548
Glenn Kastenf78aee72012-01-04 11:00:47 -0800549status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700550{
Eric Laurenta1884f92011-08-23 08:25:03 -0700551 status_t ret = initCheck();
552 if (ret != NO_ERROR) {
553 return ret;
554 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700555
556 // check calling permissions
557 if (!settingsAllowed()) {
558 return PERMISSION_DENIED;
559 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800560 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000561 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700562 return BAD_VALUE;
563 }
564
565 { // scope for the lock
566 AutoMutex lock(mHardwareLock);
567 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700568 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700569 mHardwareStatus = AUDIO_HW_IDLE;
570 }
571
572 if (NO_ERROR == ret) {
573 Mutex::Autolock _l(mLock);
574 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800575 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700576 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700577 }
578
579 return ret;
580}
581
582status_t AudioFlinger::setMicMute(bool state)
583{
Eric Laurenta1884f92011-08-23 08:25:03 -0700584 status_t ret = initCheck();
585 if (ret != NO_ERROR) {
586 return ret;
587 }
588
Mathias Agopian65ab4712010-07-14 17:59:35 -0700589 // check calling permissions
590 if (!settingsAllowed()) {
591 return PERMISSION_DENIED;
592 }
593
594 AutoMutex lock(mHardwareLock);
595 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurenta1884f92011-08-23 08:25:03 -0700596 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700597 mHardwareStatus = AUDIO_HW_IDLE;
598 return ret;
599}
600
601bool AudioFlinger::getMicMute() const
602{
Eric Laurenta1884f92011-08-23 08:25:03 -0700603 status_t ret = initCheck();
604 if (ret != NO_ERROR) {
605 return false;
606 }
607
Dima Zavinfce7a472011-04-19 22:30:36 -0700608 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800609 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700610 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700611 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700612 mHardwareStatus = AUDIO_HW_IDLE;
613 return state;
614}
615
616status_t AudioFlinger::setMasterMute(bool muted)
617{
618 // check calling permissions
619 if (!settingsAllowed()) {
620 return PERMISSION_DENIED;
621 }
622
Eric Laurent93575202011-01-18 18:39:02 -0800623 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -0800624 // This is an optimization, so PlaybackThread doesn't have to look at the one from AudioFlinger
Mathias Agopian65ab4712010-07-14 17:59:35 -0700625 mMasterMute = muted;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800626 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700627 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
628
629 return NO_ERROR;
630}
631
632float AudioFlinger::masterVolume() const
633{
Glenn Kasten98067102011-12-13 11:47:54 -0800634 Mutex::Autolock _l(mLock);
635 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700636}
637
638bool AudioFlinger::masterMute() const
639{
Glenn Kasten98067102011-12-13 11:47:54 -0800640 Mutex::Autolock _l(mLock);
641 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700642}
643
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800644status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
645 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700646{
647 // check calling permissions
648 if (!settingsAllowed()) {
649 return PERMISSION_DENIED;
650 }
651
Glenn Kasten263709e2012-01-06 08:40:01 -0800652 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000653 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700654 return BAD_VALUE;
655 }
656
657 AutoMutex lock(mLock);
658 PlaybackThread *thread = NULL;
659 if (output) {
660 thread = checkPlaybackThread_l(output);
661 if (thread == NULL) {
662 return BAD_VALUE;
663 }
664 }
665
666 mStreamTypes[stream].volume = value;
667
668 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800669 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700670 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
671 }
672 } else {
673 thread->setStreamVolume(stream, value);
674 }
675
676 return NO_ERROR;
677}
678
Glenn Kastenfff6d712012-01-12 16:38:12 -0800679status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700680{
681 // check calling permissions
682 if (!settingsAllowed()) {
683 return PERMISSION_DENIED;
684 }
685
Glenn Kasten263709e2012-01-06 08:40:01 -0800686 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -0700687 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000688 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700689 return BAD_VALUE;
690 }
691
Eric Laurent93575202011-01-18 18:39:02 -0800692 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700693 mStreamTypes[stream].mute = muted;
694 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
695 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
696
697 return NO_ERROR;
698}
699
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800700float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700701{
Glenn Kasten263709e2012-01-06 08:40:01 -0800702 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700703 return 0.0f;
704 }
705
706 AutoMutex lock(mLock);
707 float volume;
708 if (output) {
709 PlaybackThread *thread = checkPlaybackThread_l(output);
710 if (thread == NULL) {
711 return 0.0f;
712 }
713 volume = thread->streamVolume(stream);
714 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -0800715 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700716 }
717
718 return volume;
719}
720
Glenn Kastenfff6d712012-01-12 16:38:12 -0800721bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700722{
Glenn Kasten263709e2012-01-06 08:40:01 -0800723 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700724 return true;
725 }
726
Glenn Kasten6637baa2012-01-09 09:40:36 -0800727 AutoMutex lock(mLock);
728 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700729}
730
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800731status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700732{
733 status_t result;
734
Glenn Kasten23d82a92012-02-03 11:10:00 -0800735 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700736 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
737 // check calling permissions
738 if (!settingsAllowed()) {
739 return PERMISSION_DENIED;
740 }
741
Mathias Agopian65ab4712010-07-14 17:59:35 -0700742 // ioHandle == 0 means the parameters are global to the audio hardware interface
743 if (ioHandle == 0) {
744 AutoMutex lock(mHardwareLock);
745 mHardwareStatus = AUDIO_SET_PARAMETER;
Dima Zavin799a70e2011-04-18 16:57:27 -0700746 status_t final_result = NO_ERROR;
747 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
748 audio_hw_device_t *dev = mAudioHwDevs[i];
749 result = dev->set_parameters(dev, keyValuePairs.string());
750 final_result = result ?: final_result;
751 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700752 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700753 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
754 AudioParameter param = AudioParameter(keyValuePairs);
755 String8 value;
756 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
757 Mutex::Autolock _l(mLock);
Eric Laurentbee53372011-08-29 12:42:48 -0700758 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
759 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700760 for (size_t i = 0; i < mRecordThreads.size(); i++) {
761 sp<RecordThread> thread = mRecordThreads.valueAt(i);
762 RecordThread::RecordTrack *track = thread->track();
763 if (track != NULL) {
764 audio_devices_t device = (audio_devices_t)(
765 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurentbee53372011-08-29 12:42:48 -0700766 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700767 thread->setEffectSuspended(FX_IID_AEC,
768 suspend,
769 track->sessionId());
770 thread->setEffectSuspended(FX_IID_NS,
771 suspend,
772 track->sessionId());
773 }
774 }
Eric Laurentbee53372011-08-29 12:42:48 -0700775 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700776 }
777 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700778 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700779 }
780
781 // hold a strong ref on thread in case closeOutput() or closeInput() is called
782 // and the thread is exited once the lock is released
783 sp<ThreadBase> thread;
784 {
785 Mutex::Autolock _l(mLock);
786 thread = checkPlaybackThread_l(ioHandle);
787 if (thread == NULL) {
788 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -0800789 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700790 // indicate output device change to all input threads for pre processing
791 AudioParameter param = AudioParameter(keyValuePairs);
792 int value;
793 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
794 for (size_t i = 0; i < mRecordThreads.size(); i++) {
795 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
796 }
797 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700798 }
799 }
Glenn Kasten7378ca52012-01-20 13:44:40 -0800800 if (thread != 0) {
801 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700802 }
803 return BAD_VALUE;
804}
805
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800806String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700807{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800808// ALOGV("getParameters() io %d, keys %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700809// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
810
811 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700812 String8 out_s8;
813
Dima Zavin799a70e2011-04-18 16:57:27 -0700814 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
815 audio_hw_device_t *dev = mAudioHwDevs[i];
816 char *s = dev->get_parameters(dev, keys.string());
817 out_s8 += String8(s);
818 free(s);
819 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700820 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700821 }
822
823 Mutex::Autolock _l(mLock);
824
825 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
826 if (playbackThread != NULL) {
827 return playbackThread->getParameters(keys);
828 }
829 RecordThread *recordThread = checkRecordThread_l(ioHandle);
830 if (recordThread != NULL) {
831 return recordThread->getParameters(keys);
832 }
833 return String8("");
834}
835
Glenn Kastenf587ba52012-01-26 16:25:10 -0800836size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format, int channelCount) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700837{
Eric Laurenta1884f92011-08-23 08:25:03 -0700838 status_t ret = initCheck();
839 if (ret != NO_ERROR) {
840 return 0;
841 }
842
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800843 AutoMutex lock(mHardwareLock);
844 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
845 size_t size = mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
846 mHardwareStatus = AUDIO_HW_IDLE;
847 return size;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700848}
849
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800850unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700851{
852 if (ioHandle == 0) {
853 return 0;
854 }
855
856 Mutex::Autolock _l(mLock);
857
858 RecordThread *recordThread = checkRecordThread_l(ioHandle);
859 if (recordThread != NULL) {
860 return recordThread->getInputFramesLost();
861 }
862 return 0;
863}
864
865status_t AudioFlinger::setVoiceVolume(float value)
866{
Eric Laurenta1884f92011-08-23 08:25:03 -0700867 status_t ret = initCheck();
868 if (ret != NO_ERROR) {
869 return ret;
870 }
871
Mathias Agopian65ab4712010-07-14 17:59:35 -0700872 // check calling permissions
873 if (!settingsAllowed()) {
874 return PERMISSION_DENIED;
875 }
876
877 AutoMutex lock(mHardwareLock);
878 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -0700879 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700880 mHardwareStatus = AUDIO_HW_IDLE;
881
882 return ret;
883}
884
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800885status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
886 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700887{
888 status_t status;
889
890 Mutex::Autolock _l(mLock);
891
892 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
893 if (playbackThread != NULL) {
894 return playbackThread->getRenderPosition(halFrames, dspFrames);
895 }
896
897 return BAD_VALUE;
898}
899
900void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
901{
902
903 Mutex::Autolock _l(mLock);
904
Glenn Kastenbb001922012-02-03 11:10:26 -0800905 pid_t pid = IPCThreadState::self()->getCallingPid();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700906 if (mNotificationClients.indexOfKey(pid) < 0) {
907 sp<NotificationClient> notificationClient = new NotificationClient(this,
908 client,
909 pid);
Steve Block3856b092011-10-20 11:56:00 +0100910 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700911
912 mNotificationClients.add(pid, notificationClient);
913
914 sp<IBinder> binder = client->asBinder();
915 binder->linkToDeath(notificationClient);
916
917 // the config change is always sent from playback or record threads to avoid deadlock
918 // with AudioSystem::gLock
919 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
920 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
921 }
922
923 for (size_t i = 0; i < mRecordThreads.size(); i++) {
924 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
925 }
926 }
927}
928
929void AudioFlinger::removeNotificationClient(pid_t pid)
930{
931 Mutex::Autolock _l(mLock);
932
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800933 ssize_t index = mNotificationClients.indexOfKey(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700934 if (index >= 0) {
935 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
Steve Block3856b092011-10-20 11:56:00 +0100936 ALOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700937 mNotificationClients.removeItem(pid);
938 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700939
Steve Block3856b092011-10-20 11:56:00 +0100940 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800941 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700942 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800943 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700944 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Steve Block3856b092011-10-20 11:56:00 +0100945 ALOGV(" pid %d @ %d", ref->pid, i);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700946 if (ref->pid == pid) {
Steve Block3856b092011-10-20 11:56:00 +0100947 ALOGV(" removing entry for pid %d session %d", pid, ref->sessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700948 mAudioSessionRefs.removeAt(i);
949 delete ref;
950 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700951 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800952 } else {
953 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700954 }
955 }
956 if (removed) {
957 purgeStaleEffects_l();
958 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700959}
960
961// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800962void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700963{
964 size_t size = mNotificationClients.size();
965 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -0800966 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
967 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700968 }
969}
970
971// removeClient_l() must be called with AudioFlinger::mLock held
972void AudioFlinger::removeClient_l(pid_t pid)
973{
Steve Block3856b092011-10-20 11:56:00 +0100974 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700975 mClients.removeItem(pid);
976}
977
978
979// ----------------------------------------------------------------------------
980
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800981AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
982 uint32_t device, type_t type)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700983 : Thread(false),
Glenn Kasten23bb8be2012-01-26 10:38:26 -0800984 mType(type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -0800985 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0),
986 // mChannelMask
987 mChannelCount(0),
988 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
989 mParamStatus(NO_ERROR),
Glenn Kastenb28686f2012-01-06 08:39:38 -0800990 mStandby(false), mId(id),
Glenn Kasten84afa3b2012-01-25 15:28:08 -0800991 mDevice(device),
992 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -0700993{
994}
995
996AudioFlinger::ThreadBase::~ThreadBase()
997{
998 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -0700999 // do not lock the mutex in destructor
1000 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001001 if (mPowerManager != 0) {
1002 sp<IBinder> binder = mPowerManager->asBinder();
1003 binder->unlinkToDeath(mDeathRecipient);
1004 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001005}
1006
1007void AudioFlinger::ThreadBase::exit()
1008{
Steve Block3856b092011-10-20 11:56:00 +01001009 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001010 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001011 // This lock prevents the following race in thread (uniprocessor for illustration):
1012 // if (!exitPending()) {
1013 // // context switch from here to exit()
1014 // // exit() calls requestExit(), what exitPending() observes
1015 // // exit() calls signal(), which is dropped since no waiters
1016 // // context switch back from exit() to here
1017 // mWaitWorkCV.wait(...);
1018 // // now thread is hung
1019 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001020 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001021 requestExit();
1022 mWaitWorkCV.signal();
1023 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001024 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1025 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001026 requestExitAndWait();
1027}
1028
Mathias Agopian65ab4712010-07-14 17:59:35 -07001029status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1030{
1031 status_t status;
1032
Steve Block3856b092011-10-20 11:56:00 +01001033 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001034 Mutex::Autolock _l(mLock);
1035
1036 mNewParameters.add(keyValuePairs);
1037 mWaitWorkCV.signal();
1038 // wait condition with timeout in case the thread loop has exited
1039 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001040 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001041 status = mParamStatus;
1042 mWaitWorkCV.signal();
1043 } else {
1044 status = TIMED_OUT;
1045 }
1046 return status;
1047}
1048
1049void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1050{
1051 Mutex::Autolock _l(mLock);
1052 sendConfigEvent_l(event, param);
1053}
1054
1055// sendConfigEvent_l() must be called with ThreadBase::mLock held
1056void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1057{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001058 ConfigEvent configEvent;
1059 configEvent.mEvent = event;
1060 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001061 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001062 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001063 mWaitWorkCV.signal();
1064}
1065
1066void AudioFlinger::ThreadBase::processConfigEvents()
1067{
1068 mLock.lock();
1069 while(!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001070 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001071 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001072 mConfigEvents.removeAt(0);
1073 // release mLock before locking AudioFlinger mLock: lock order is always
1074 // AudioFlinger then ThreadBase to avoid cross deadlock
1075 mLock.unlock();
1076 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001077 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001078 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001079 mLock.lock();
1080 }
1081 mLock.unlock();
1082}
1083
1084status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1085{
1086 const size_t SIZE = 256;
1087 char buffer[SIZE];
1088 String8 result;
1089
1090 bool locked = tryLock(mLock);
1091 if (!locked) {
1092 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1093 write(fd, buffer, strlen(buffer));
1094 }
1095
1096 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1097 result.append(buffer);
1098 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1099 result.append(buffer);
1100 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1101 result.append(buffer);
1102 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1103 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001104 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1105 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001106 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1107 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001108 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001109 result.append(buffer);
1110
1111 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1112 result.append(buffer);
1113 result.append(" Index Command");
1114 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1115 snprintf(buffer, SIZE, "\n %02d ", i);
1116 result.append(buffer);
1117 result.append(mNewParameters[i]);
1118 }
1119
1120 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1121 result.append(buffer);
1122 snprintf(buffer, SIZE, " Index event param\n");
1123 result.append(buffer);
1124 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001125 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001126 result.append(buffer);
1127 }
1128 result.append("\n");
1129
1130 write(fd, result.string(), result.size());
1131
1132 if (locked) {
1133 mLock.unlock();
1134 }
1135 return NO_ERROR;
1136}
1137
Eric Laurent1d2bff02011-07-24 17:49:51 -07001138status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1139{
1140 const size_t SIZE = 256;
1141 char buffer[SIZE];
1142 String8 result;
1143
1144 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1145 write(fd, buffer, strlen(buffer));
1146
1147 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1148 sp<EffectChain> chain = mEffectChains[i];
1149 if (chain != 0) {
1150 chain->dump(fd, args);
1151 }
1152 }
1153 return NO_ERROR;
1154}
1155
Eric Laurentfeb0db62011-07-22 09:04:31 -07001156void AudioFlinger::ThreadBase::acquireWakeLock()
1157{
1158 Mutex::Autolock _l(mLock);
1159 acquireWakeLock_l();
1160}
1161
1162void AudioFlinger::ThreadBase::acquireWakeLock_l()
1163{
1164 if (mPowerManager == 0) {
1165 // use checkService() to avoid blocking if power service is not up yet
1166 sp<IBinder> binder =
1167 defaultServiceManager()->checkService(String16("power"));
1168 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001169 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001170 } else {
1171 mPowerManager = interface_cast<IPowerManager>(binder);
1172 binder->linkToDeath(mDeathRecipient);
1173 }
1174 }
1175 if (mPowerManager != 0) {
1176 sp<IBinder> binder = new BBinder();
1177 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1178 binder,
1179 String16(mName));
1180 if (status == NO_ERROR) {
1181 mWakeLockToken = binder;
1182 }
Steve Block3856b092011-10-20 11:56:00 +01001183 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001184 }
1185}
1186
1187void AudioFlinger::ThreadBase::releaseWakeLock()
1188{
1189 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001190 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001191}
1192
1193void AudioFlinger::ThreadBase::releaseWakeLock_l()
1194{
1195 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001196 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001197 if (mPowerManager != 0) {
1198 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1199 }
1200 mWakeLockToken.clear();
1201 }
1202}
1203
1204void AudioFlinger::ThreadBase::clearPowerManager()
1205{
1206 Mutex::Autolock _l(mLock);
1207 releaseWakeLock_l();
1208 mPowerManager.clear();
1209}
1210
1211void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1212{
1213 sp<ThreadBase> thread = mThread.promote();
1214 if (thread != 0) {
1215 thread->clearPowerManager();
1216 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001217 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001218}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001219
Eric Laurent59255e42011-07-27 19:49:51 -07001220void AudioFlinger::ThreadBase::setEffectSuspended(
1221 const effect_uuid_t *type, bool suspend, int sessionId)
1222{
1223 Mutex::Autolock _l(mLock);
1224 setEffectSuspended_l(type, suspend, sessionId);
1225}
1226
1227void AudioFlinger::ThreadBase::setEffectSuspended_l(
1228 const effect_uuid_t *type, bool suspend, int sessionId)
1229{
Glenn Kasten090f0192012-01-30 13:00:02 -08001230 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001231 if (chain != 0) {
1232 if (type != NULL) {
1233 chain->setEffectSuspended_l(type, suspend);
1234 } else {
1235 chain->setEffectSuspendedAll_l(suspend);
1236 }
1237 }
1238
1239 updateSuspendedSessions_l(type, suspend, sessionId);
1240}
1241
1242void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1243{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001244 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001245 if (index < 0) {
1246 return;
1247 }
1248
1249 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1250 mSuspendedSessions.editValueAt(index);
1251
1252 for (size_t i = 0; i < sessionEffects.size(); i++) {
1253 sp <SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1254 for (int j = 0; j < desc->mRefCount; j++) {
1255 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1256 chain->setEffectSuspendedAll_l(true);
1257 } else {
Steve Block3856b092011-10-20 11:56:00 +01001258 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07001259 desc->mType.timeLow);
1260 chain->setEffectSuspended_l(&desc->mType, true);
1261 }
1262 }
1263 }
1264}
1265
Eric Laurent59255e42011-07-27 19:49:51 -07001266void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1267 bool suspend,
1268 int sessionId)
1269{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001270 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001271
1272 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1273
1274 if (suspend) {
1275 if (index >= 0) {
1276 sessionEffects = mSuspendedSessions.editValueAt(index);
1277 } else {
1278 mSuspendedSessions.add(sessionId, sessionEffects);
1279 }
1280 } else {
1281 if (index < 0) {
1282 return;
1283 }
1284 sessionEffects = mSuspendedSessions.editValueAt(index);
1285 }
1286
1287
1288 int key = EffectChain::kKeyForSuspendAll;
1289 if (type != NULL) {
1290 key = type->timeLow;
1291 }
1292 index = sessionEffects.indexOfKey(key);
1293
1294 sp <SuspendedSessionDesc> desc;
1295 if (suspend) {
1296 if (index >= 0) {
1297 desc = sessionEffects.valueAt(index);
1298 } else {
1299 desc = new SuspendedSessionDesc();
1300 if (type != NULL) {
1301 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1302 }
1303 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001304 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001305 }
1306 desc->mRefCount++;
1307 } else {
1308 if (index < 0) {
1309 return;
1310 }
1311 desc = sessionEffects.valueAt(index);
1312 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001313 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001314 sessionEffects.removeItemsAt(index);
1315 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001316 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001317 sessionId);
1318 mSuspendedSessions.removeItem(sessionId);
1319 }
1320 }
1321 }
1322 if (!sessionEffects.isEmpty()) {
1323 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1324 }
1325}
1326
1327void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1328 bool enabled,
1329 int sessionId)
1330{
1331 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001332 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1333}
Eric Laurent59255e42011-07-27 19:49:51 -07001334
Eric Laurenta85a74a2011-10-19 11:44:54 -07001335void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1336 bool enabled,
1337 int sessionId)
1338{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001339 if (mType != RECORD) {
1340 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1341 // another session. This gives the priority to well behaved effect control panels
1342 // and applications not using global effects.
1343 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1344 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1345 }
1346 }
Eric Laurent59255e42011-07-27 19:49:51 -07001347
1348 sp<EffectChain> chain = getEffectChain_l(sessionId);
1349 if (chain != 0) {
1350 chain->checkSuspendOnEffectEnabled(effect, enabled);
1351 }
1352}
1353
Mathias Agopian65ab4712010-07-14 17:59:35 -07001354// ----------------------------------------------------------------------------
1355
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001356AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1357 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001358 audio_io_handle_t id,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001359 uint32_t device,
1360 type_t type)
1361 : ThreadBase(audioFlinger, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001362 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1363 // Assumes constructor is called by AudioFlinger with it's mLock held,
1364 // but it would be safer to explicitly pass initial masterMute as parameter
1365 mMasterMute(audioFlinger->masterMute_l()),
1366 // mStreamTypes[] initialized in constructor body
1367 mOutput(output),
1368 // Assumes constructor is called by AudioFlinger with it's mLock held,
1369 // but it would be safer to explicitly pass initial masterVolume as parameter
1370 mMasterVolume(audioFlinger->masterVolume_l()),
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001371 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001372{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001373 snprintf(mName, kNameLength, "AudioOut_%d", id);
1374
Mathias Agopian65ab4712010-07-14 17:59:35 -07001375 readOutputParameters();
1376
Glenn Kasten263709e2012-01-06 08:40:01 -08001377 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001378 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1379 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1380 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001381 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1382 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Glenn Kasten263709e2012-01-06 08:40:01 -08001383 // initialized by stream_type_t default constructor
1384 // mStreamTypes[stream].valid = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001385 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001386 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1387 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001388}
1389
1390AudioFlinger::PlaybackThread::~PlaybackThread()
1391{
1392 delete [] mMixBuffer;
1393}
1394
1395status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1396{
1397 dumpInternals(fd, args);
1398 dumpTracks(fd, args);
1399 dumpEffectChains(fd, args);
1400 return NO_ERROR;
1401}
1402
1403status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1404{
1405 const size_t SIZE = 256;
1406 char buffer[SIZE];
1407 String8 result;
1408
1409 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1410 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001411 result.append(" Name Clien Typ Fmt Chn mask Session Buf S M F SRate LeftV RighV Serv User Main buf Aux Buf\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001412 for (size_t i = 0; i < mTracks.size(); ++i) {
1413 sp<Track> track = mTracks[i];
1414 if (track != 0) {
1415 track->dump(buffer, SIZE);
1416 result.append(buffer);
1417 }
1418 }
1419
1420 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1421 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001422 result.append(" Name Clien Typ Fmt Chn mask Session Buf S M F SRate LeftV RighV Serv User Main buf Aux Buf\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001423 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001424 sp<Track> track = mActiveTracks[i].promote();
1425 if (track != 0) {
1426 track->dump(buffer, SIZE);
1427 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001428 }
1429 }
1430 write(fd, result.string(), result.size());
1431 return NO_ERROR;
1432}
1433
Mathias Agopian65ab4712010-07-14 17:59:35 -07001434status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1435{
1436 const size_t SIZE = 256;
1437 char buffer[SIZE];
1438 String8 result;
1439
1440 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1441 result.append(buffer);
1442 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1443 result.append(buffer);
1444 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1445 result.append(buffer);
1446 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1447 result.append(buffer);
1448 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1449 result.append(buffer);
1450 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1451 result.append(buffer);
1452 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1453 result.append(buffer);
1454 write(fd, result.string(), result.size());
1455
1456 dumpBase(fd, args);
1457
1458 return NO_ERROR;
1459}
1460
1461// Thread virtuals
1462status_t AudioFlinger::PlaybackThread::readyToRun()
1463{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001464 status_t status = initCheck();
1465 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001466 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001467 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001468 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001469 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001470 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001471}
1472
1473void AudioFlinger::PlaybackThread::onFirstRef()
1474{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001475 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001476}
1477
1478// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1479sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1480 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001481 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001482 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001483 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001484 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001485 int frameCount,
1486 const sp<IMemory>& sharedBuffer,
1487 int sessionId,
1488 status_t *status)
1489{
1490 sp<Track> track;
1491 status_t lStatus;
1492
1493 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001494 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1495 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001496 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001497 "for output %p with format %d",
1498 sampleRate, format, channelMask, mOutput, mFormat);
1499 lStatus = BAD_VALUE;
1500 goto Exit;
1501 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001502 }
1503 } else {
1504 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1505 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001506 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001507 lStatus = BAD_VALUE;
1508 goto Exit;
1509 }
1510 }
1511
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001512 lStatus = initCheck();
1513 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001514 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001515 goto Exit;
1516 }
1517
1518 { // scope for mLock
1519 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001520
1521 // all tracks in same audio session must share the same routing strategy otherwise
1522 // conflicts will happen when tracks are moved from one output to another by audio policy
1523 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001524 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001525 for (size_t i = 0; i < mTracks.size(); ++i) {
1526 sp<Track> t = mTracks[i];
1527 if (t != 0) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001528 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001529 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001530 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001531 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001532 lStatus = BAD_VALUE;
1533 goto Exit;
1534 }
1535 }
1536 }
1537
Mathias Agopian65ab4712010-07-14 17:59:35 -07001538 track = new Track(this, client, streamType, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001539 channelMask, frameCount, sharedBuffer, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001540 if (track->getCblk() == NULL || track->name() < 0) {
1541 lStatus = NO_MEMORY;
1542 goto Exit;
1543 }
1544 mTracks.add(track);
1545
1546 sp<EffectChain> chain = getEffectChain_l(sessionId);
1547 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001548 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001549 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001550 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001551 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001552 }
Eric Laurent9f6530f2011-08-30 10:18:54 -07001553
1554 // invalidate track immediately if the stream type was moved to another thread since
1555 // createTrack() was called by the client process.
1556 if (!mStreamTypes[streamType].valid) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001557 ALOGW("createTrack_l() on thread %p: invalidating track on stream %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07001558 this, streamType);
1559 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1560 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001561 }
1562 lStatus = NO_ERROR;
1563
1564Exit:
1565 if(status) {
1566 *status = lStatus;
1567 }
1568 return track;
1569}
1570
1571uint32_t AudioFlinger::PlaybackThread::latency() const
1572{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001573 Mutex::Autolock _l(mLock);
1574 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001575 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001576 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001577 return 0;
1578 }
1579}
1580
Glenn Kasten6637baa2012-01-09 09:40:36 -08001581void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001582{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001583 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001584 mMasterVolume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001585}
1586
Glenn Kasten6637baa2012-01-09 09:40:36 -08001587void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001588{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001589 Mutex::Autolock _l(mLock);
1590 setMasterMute_l(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001591}
1592
Glenn Kasten6637baa2012-01-09 09:40:36 -08001593void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001594{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001595 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001596 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001597}
1598
Glenn Kasten6637baa2012-01-09 09:40:36 -08001599void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001600{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001601 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001602 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001603}
1604
Glenn Kastenfff6d712012-01-12 16:38:12 -08001605float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001606{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001607 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001608 return mStreamTypes[stream].volume;
1609}
1610
Mathias Agopian65ab4712010-07-14 17:59:35 -07001611// addTrack_l() must be called with ThreadBase::mLock held
1612status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1613{
1614 status_t status = ALREADY_EXISTS;
1615
1616 // set retry count for buffer fill
1617 track->mRetryCount = kMaxTrackStartupRetries;
1618 if (mActiveTracks.indexOf(track) < 0) {
1619 // the track is newly added, make sure it fills up all its
1620 // buffers before playing. This is to ensure the client will
1621 // effectively get the latency it requested.
1622 track->mFillingUpStatus = Track::FS_FILLING;
1623 track->mResetDone = false;
1624 mActiveTracks.add(track);
1625 if (track->mainBuffer() != mMixBuffer) {
1626 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1627 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001628 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001629 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001630 }
1631 }
1632
1633 status = NO_ERROR;
1634 }
1635
Steve Block3856b092011-10-20 11:56:00 +01001636 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001637 mWaitWorkCV.broadcast();
1638
1639 return status;
1640}
1641
1642// destroyTrack_l() must be called with ThreadBase::mLock held
1643void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1644{
1645 track->mState = TrackBase::TERMINATED;
1646 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001647 removeTrack_l(track);
1648 }
1649}
1650
1651void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1652{
1653 mTracks.remove(track);
1654 deleteTrackName_l(track->name());
1655 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1656 if (chain != 0) {
1657 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001658 }
1659}
1660
1661String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1662{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001663 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001664 char *s;
1665
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001666 Mutex::Autolock _l(mLock);
1667 if (initCheck() != NO_ERROR) {
1668 return out_s8;
1669 }
1670
Dima Zavin799a70e2011-04-18 16:57:27 -07001671 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001672 out_s8 = String8(s);
1673 free(s);
1674 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001675}
1676
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001677// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001678void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1679 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001680 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001681
Steve Block3856b092011-10-20 11:56:00 +01001682 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001683
1684 switch (event) {
1685 case AudioSystem::OUTPUT_OPENED:
1686 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001687 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001688 desc.samplingRate = mSampleRate;
1689 desc.format = mFormat;
1690 desc.frameCount = mFrameCount;
1691 desc.latency = latency();
1692 param2 = &desc;
1693 break;
1694
1695 case AudioSystem::STREAM_CONFIG_CHANGED:
1696 param2 = &param;
1697 case AudioSystem::OUTPUT_CLOSED:
1698 default:
1699 break;
1700 }
1701 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1702}
1703
1704void AudioFlinger::PlaybackThread::readOutputParameters()
1705{
Dima Zavin799a70e2011-04-18 16:57:27 -07001706 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001707 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1708 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001709 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001710 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001711 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001712
1713 // FIXME - Current mixer implementation only supports stereo output: Always
1714 // Allocate a stereo buffer even if HW output is mono.
Glenn Kastene9dd0172012-01-27 18:08:45 -08001715 delete[] mMixBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001716 mMixBuffer = new int16_t[mFrameCount * 2];
1717 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1718
Eric Laurentde070132010-07-13 04:45:46 -07001719 // force reconfiguration of effect chains and engines to take new buffer size and audio
1720 // parameters into account
1721 // Note that mLock is not held when readOutputParameters() is called from the constructor
1722 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1723 // matter.
1724 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1725 Vector< sp<EffectChain> > effectChains = mEffectChains;
1726 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001727 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001728 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001729}
1730
1731status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1732{
Glenn Kastena0d68332012-01-27 16:47:15 -08001733 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001734 return BAD_VALUE;
1735 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001736 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001737 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001738 return INVALID_OPERATION;
1739 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001740 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001741
Dima Zavin799a70e2011-04-18 16:57:27 -07001742 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001743}
1744
Eric Laurent39e94f82010-07-28 01:32:47 -07001745uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001746{
1747 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001748 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001749 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001750 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001751 }
1752
1753 for (size_t i = 0; i < mTracks.size(); ++i) {
1754 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001755 if (sessionId == track->sessionId() &&
1756 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001757 result |= TRACK_SESSION;
1758 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001759 }
1760 }
1761
Eric Laurent39e94f82010-07-28 01:32:47 -07001762 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001763}
1764
Eric Laurentde070132010-07-13 04:45:46 -07001765uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1766{
Dima Zavinfce7a472011-04-19 22:30:36 -07001767 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07001768 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07001769 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1770 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001771 }
1772 for (size_t i = 0; i < mTracks.size(); i++) {
1773 sp<Track> track = mTracks[i];
1774 if (sessionId == track->sessionId() &&
1775 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001776 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07001777 }
1778 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001779 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001780}
1781
Mathias Agopian65ab4712010-07-14 17:59:35 -07001782
Glenn Kastenaed850d2012-01-26 09:46:34 -08001783AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001784{
1785 Mutex::Autolock _l(mLock);
1786 return mOutput;
1787}
1788
1789AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1790{
1791 Mutex::Autolock _l(mLock);
1792 AudioStreamOut *output = mOutput;
1793 mOutput = NULL;
1794 return output;
1795}
1796
1797// this method must always be called either with ThreadBase mLock held or inside the thread loop
1798audio_stream_t* AudioFlinger::PlaybackThread::stream()
1799{
1800 if (mOutput == NULL) {
1801 return NULL;
1802 }
1803 return &mOutput->stream->common;
1804}
1805
Eric Laurent162b40b2011-12-05 09:47:19 -08001806uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs()
1807{
1808 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
1809 // decoding and transfer time. So sleeping for half of the latency would likely cause
1810 // underruns
1811 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
1812 return (uint32_t)((uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000);
1813 } else {
1814 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
1815 }
1816}
1817
Mathias Agopian65ab4712010-07-14 17:59:35 -07001818// ----------------------------------------------------------------------------
1819
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001820AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001821 audio_io_handle_t id, uint32_t device, type_t type)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001822 : PlaybackThread(audioFlinger, output, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001823 mAudioMixer(new AudioMixer(mFrameCount, mSampleRate)),
1824 mPrevMixerStatus(MIXER_IDLE)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001825{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001826 // FIXME - Current mixer implementation only supports stereo output
1827 if (mChannelCount == 1) {
Steve Block29357bc2012-01-06 19:20:56 +00001828 ALOGE("Invalid audio hardware channel count");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001829 }
1830}
1831
1832AudioFlinger::MixerThread::~MixerThread()
1833{
1834 delete mAudioMixer;
1835}
1836
1837bool AudioFlinger::MixerThread::threadLoop()
1838{
1839 Vector< sp<Track> > tracksToRemove;
Glenn Kasten29c23c32012-01-26 13:37:52 -08001840 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001841 nsecs_t standbyTime = systemTime();
1842 size_t mixBufferSize = mFrameCount * mFrameSize;
1843 // FIXME: Relaxed timing because of a certain device that can't meet latency
1844 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07001845 // increase threshold again due to low power audio mode. The way this warning threshold is
1846 // calculated and its usefulness should be reconsidered anyway.
1847 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001848 nsecs_t lastWarning = 0;
1849 bool longStandbyExit = false;
1850 uint32_t activeSleepTime = activeSleepTimeUs();
1851 uint32_t idleSleepTime = idleSleepTimeUs();
1852 uint32_t sleepTime = idleSleepTime;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001853 uint32_t sleepTimeShift = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001854 Vector< sp<EffectChain> > effectChains;
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001855#ifdef DEBUG_CPU_USAGE
1856 ThreadCpuUsage cpu;
1857 const CentralTendencyStatistics& stats = cpu.statistics();
1858#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001859
Eric Laurentfeb0db62011-07-22 09:04:31 -07001860 acquireWakeLock();
1861
Mathias Agopian65ab4712010-07-14 17:59:35 -07001862 while (!exitPending())
1863 {
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001864#ifdef DEBUG_CPU_USAGE
1865 cpu.sampleAndEnable();
1866 unsigned n = stats.n();
1867 // cpu.elapsed() is expensive, so don't call it every loop
1868 if ((n & 127) == 1) {
1869 long long elapsed = cpu.elapsed();
1870 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1871 double perLoop = elapsed / (double) n;
1872 double perLoop100 = perLoop * 0.01;
1873 double mean = stats.mean();
1874 double stddev = stats.stddev();
1875 double minimum = stats.minimum();
1876 double maximum = stats.maximum();
1877 cpu.resetStatistics();
Steve Blockdf64d152012-01-04 20:05:49 +00001878 ALOGI("CPU usage over past %.1f secs (%u mixer loops at %.1f mean ms per loop):\n us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f",
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001879 elapsed * .000000001, n, perLoop * .000001,
1880 mean * .001,
1881 stddev * .001,
1882 minimum * .001,
1883 maximum * .001,
1884 mean / perLoop100,
1885 stddev / perLoop100,
1886 minimum / perLoop100,
1887 maximum / perLoop100);
1888 }
1889 }
1890#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001891 processConfigEvents();
1892
1893 mixerStatus = MIXER_IDLE;
1894 { // scope for mLock
1895
1896 Mutex::Autolock _l(mLock);
1897
1898 if (checkForNewParameters_l()) {
1899 mixBufferSize = mFrameCount * mFrameSize;
1900 // FIXME: Relaxed timing because of a certain device that can't meet latency
1901 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07001902 // increase threshold again due to low power audio mode. The way this warning
1903 // threshold is calculated and its usefulness should be reconsidered anyway.
1904 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001905 activeSleepTime = activeSleepTimeUs();
1906 idleSleepTime = idleSleepTimeUs();
1907 }
1908
1909 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1910
1911 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08001912 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1913 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001914 if (!mStandby) {
Glenn Kasten90bebef2012-01-27 15:24:38 -08001915 ALOGV("Audio hardware entering standby, mixer %p, mSuspended %d", this, mSuspended);
Dima Zavin799a70e2011-04-18 16:57:27 -07001916 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001917 mStandby = true;
1918 mBytesWritten = 0;
1919 }
1920
1921 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1922 // we're about to wait, flush the binder command buffer
1923 IPCThreadState::self()->flushCommands();
1924
1925 if (exitPending()) break;
1926
Eric Laurentfeb0db62011-07-22 09:04:31 -07001927 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001928 // wait until we have something to do...
Glenn Kasten90bebef2012-01-27 15:24:38 -08001929 ALOGV("MixerThread %p TID %d going to sleep", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001930 mWaitWorkCV.wait(mLock);
Glenn Kasten90bebef2012-01-27 15:24:38 -08001931 ALOGV("MixerThread %p TID %d waking up", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07001932 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001933
Eric Laurent27741442012-01-17 19:20:12 -08001934 mPrevMixerStatus = MIXER_IDLE;
Glenn Kastenf1d45922012-01-13 15:54:24 -08001935 if (!mMasterMute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001936 char value[PROPERTY_VALUE_MAX];
1937 property_get("ro.audio.silent", value, "0");
1938 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00001939 ALOGD("Silence is golden");
Glenn Kasten6637baa2012-01-09 09:40:36 -08001940 setMasterMute_l(true);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001941 }
1942 }
1943
1944 standbyTime = systemTime() + kStandbyTimeInNsecs;
1945 sleepTime = idleSleepTime;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001946 sleepTimeShift = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001947 continue;
1948 }
1949 }
1950
1951 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
1952
1953 // prevent any changes in effect chain list and in each effect chain
1954 // during mixing and effect process as the audio buffers could be deleted
1955 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07001956 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08001957 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001958
Glenn Kastenf6b16782011-12-15 09:51:17 -08001959 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001960 // mix buffers...
1961 mAudioMixer->process();
Eric Laurent21e4b6e2012-01-23 18:56:59 -08001962 // increase sleep time progressively when application underrun condition clears.
1963 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
1964 // that a steady state of alternating ready/not ready conditions keeps the sleep time
1965 // such that we would underrun the audio HAL.
1966 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
Eric Laurent7cafbb32011-11-22 18:50:29 -08001967 sleepTimeShift--;
1968 }
Eric Laurent21e4b6e2012-01-23 18:56:59 -08001969 sleepTime = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001970 standbyTime = systemTime() + kStandbyTimeInNsecs;
1971 //TODO: delay standby when effects have a tail
1972 } else {
1973 // If no tracks are ready, sleep once for the duration of an output
1974 // buffer size, then write 0s to the output
1975 if (sleepTime == 0) {
1976 if (mixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurent7cafbb32011-11-22 18:50:29 -08001977 sleepTime = activeSleepTime >> sleepTimeShift;
1978 if (sleepTime < kMinThreadSleepTimeUs) {
1979 sleepTime = kMinThreadSleepTimeUs;
1980 }
1981 // reduce sleep time in case of consecutive application underruns to avoid
1982 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
1983 // duration we would end up writing less data than needed by the audio HAL if
1984 // the condition persists.
1985 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
1986 sleepTimeShift++;
1987 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001988 } else {
1989 sleepTime = idleSleepTime;
1990 }
1991 } else if (mBytesWritten != 0 ||
1992 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
1993 memset (mMixBuffer, 0, mixBufferSize);
1994 sleepTime = 0;
Steve Block3856b092011-10-20 11:56:00 +01001995 ALOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001996 }
1997 // TODO add standby time extension fct of effect tail
1998 }
1999
2000 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002001 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002002 }
2003 // sleepTime == 0 means we must write to audio hardware
2004 if (sleepTime == 0) {
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002005 for (size_t i = 0; i < effectChains.size(); i ++) {
2006 effectChains[i]->process_l();
2007 }
2008 // enable changes in effect chain
2009 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002010 mLastWriteTime = systemTime();
2011 mInWrite = true;
2012 mBytesWritten += mixBufferSize;
2013
Dima Zavin799a70e2011-04-18 16:57:27 -07002014 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002015 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2016 mNumWrites++;
2017 mInWrite = false;
2018 nsecs_t now = systemTime();
2019 nsecs_t delta = now - mLastWriteTime;
Eric Laurent5c4e8182011-10-18 15:42:27 -07002020 if (!mStandby && delta > maxPeriod) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002021 mNumDelayedWrites++;
Glenn Kasten7dede872011-12-13 11:04:14 -08002022 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002023 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Mathias Agopian65ab4712010-07-14 17:59:35 -07002024 ns2ms(delta), mNumDelayedWrites, this);
2025 lastWarning = now;
2026 }
2027 if (mStandby) {
2028 longStandbyExit = true;
2029 }
2030 }
2031 mStandby = false;
2032 } else {
2033 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07002034 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002035 usleep(sleepTime);
2036 }
2037
2038 // finally let go of all our tracks, without the lock held
2039 // since we can't guarantee the destructors won't acquire that
2040 // same lock.
2041 tracksToRemove.clear();
2042
2043 // Effect chains will be actually deleted here if they were removed from
2044 // mEffectChains list during mixing or effects processing
2045 effectChains.clear();
2046 }
2047
2048 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002049 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002050 }
2051
Eric Laurentfeb0db62011-07-22 09:04:31 -07002052 releaseWakeLock();
2053
Steve Block3856b092011-10-20 11:56:00 +01002054 ALOGV("MixerThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002055 return false;
2056}
2057
2058// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002059AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2060 const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002061{
2062
Glenn Kasten29c23c32012-01-26 13:37:52 -08002063 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002064 // find out which tracks need to be processed
2065 size_t count = activeTracks.size();
2066 size_t mixedTracks = 0;
2067 size_t tracksWithEffect = 0;
2068
2069 float masterVolume = mMasterVolume;
2070 bool masterMute = mMasterMute;
2071
Eric Laurent571d49c2010-08-11 05:20:11 -07002072 if (masterMute) {
2073 masterVolume = 0;
2074 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002075 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002076 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002077 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002078 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002079 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002080 masterVolume = (float)((v + (1 << 23)) >> 24);
2081 chain.clear();
2082 }
2083
2084 for (size_t i=0 ; i<count ; i++) {
2085 sp<Track> t = activeTracks[i].promote();
2086 if (t == 0) continue;
2087
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002088 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002089 Track* const track = t.get();
2090 audio_track_cblk_t* cblk = track->cblk();
2091
2092 // The first time a track is added we wait
2093 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002094 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08002095 // make sure that we have enough frames to mix one full buffer.
2096 // enforce this condition only once to enable draining the buffer in case the client
2097 // app does not call stop() and relies on underrun to stop:
Eric Laurent27741442012-01-17 19:20:12 -08002098 // hence the test on (mPrevMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08002099 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07002100 uint32_t minFrames = 1;
Eric Laurenta47b69c2011-11-08 18:10:16 -08002101 if (!track->isStopped() && !track->isPausing() &&
Eric Laurent27741442012-01-17 19:20:12 -08002102 (mPrevMixerStatus == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07002103 if (t->sampleRate() == (int)mSampleRate) {
2104 minFrames = mFrameCount;
2105 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08002106 // +1 for rounding and +1 for additional sample needed for interpolation
2107 minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
2108 // add frames already consumed but not yet released by the resampler
2109 // because cblk->framesReady() will include these frames
2110 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2111 // the minimum track buffer size is normally twice the number of frames necessary
2112 // to fill one buffer and the resampler should not leave more than one buffer worth
2113 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00002114 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07002115 }
2116 }
2117 if ((cblk->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002118 !track->isPaused() && !track->isTerminated())
2119 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002120 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002121
2122 mixedTracks++;
2123
2124 // track->mainBuffer() != mMixBuffer means there is an effect chain
2125 // connected to the track
2126 chain.clear();
2127 if (track->mainBuffer() != mMixBuffer) {
2128 chain = getEffectChain_l(track->sessionId());
2129 // Delegate volume control to effect in track effect chain if needed
2130 if (chain != 0) {
2131 tracksWithEffect++;
2132 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00002133 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002134 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002135 }
2136 }
2137
2138
2139 int param = AudioMixer::VOLUME;
2140 if (track->mFillingUpStatus == Track::FS_FILLED) {
2141 // no ramp for the first volume setting
2142 track->mFillingUpStatus = Track::FS_ACTIVE;
2143 if (track->mState == TrackBase::RESUMING) {
2144 track->mState = TrackBase::ACTIVE;
2145 param = AudioMixer::RAMP_VOLUME;
2146 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002147 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002148 } else if (cblk->server != 0) {
2149 // If the track is stopped before the first frame was mixed,
2150 // do not apply ramp
2151 param = AudioMixer::RAMP_VOLUME;
2152 }
2153
2154 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002155 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002156 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08002157 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002158 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002159 if (track->isPausing()) {
2160 track->setPaused();
2161 }
2162 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002163
Mathias Agopian65ab4712010-07-14 17:59:35 -07002164 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08002165 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002166 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002167 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002168 vl = vlr & 0xFFFF;
2169 vr = vlr >> 16;
2170 // track volumes come from shared memory, so can't be trusted and must be clamped
2171 if (vl > MAX_GAIN_INT) {
2172 ALOGV("Track left volume out of range: %04X", vl);
2173 vl = MAX_GAIN_INT;
2174 }
2175 if (vr > MAX_GAIN_INT) {
2176 ALOGV("Track right volume out of range: %04X", vr);
2177 vr = MAX_GAIN_INT;
2178 }
2179 // now apply the master volume and stream type volume
2180 vl = (uint32_t)(v * vl) << 12;
2181 vr = (uint32_t)(v * vr) << 12;
2182 // assuming master volume and stream type volume each go up to 1.0,
2183 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07002184
Glenn Kasten05632a52012-01-03 14:22:33 -08002185 uint16_t sendLevel = cblk->getSendLevel_U4_12();
2186 // send level comes from shared memory and so may be corrupt
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002187 if (sendLevel >= MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08002188 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002189 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08002190 }
2191 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002192 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002193 // Delegate volume control to effect in track effect chain if needed
2194 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2195 // Do not ramp volume if volume is controlled by effect
2196 param = AudioMixer::VOLUME;
2197 track->mHasVolumeController = true;
2198 } else {
2199 // force no volume ramp when volume controller was just disabled or removed
2200 // from effect chain to avoid volume spike
2201 if (track->mHasVolumeController) {
2202 param = AudioMixer::VOLUME;
2203 }
2204 track->mHasVolumeController = false;
2205 }
2206
2207 // Convert volumes from 8.24 to 4.12 format
2208 int16_t left, right, aux;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002209 // This additional clamping is needed in case chain->setVolume_l() overshot
Eric Laurente0aed6d2010-09-10 17:44:44 -07002210 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2211 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2212 left = int16_t(v_clamped);
2213 v_clamped = (vr + (1 << 11)) >> 12;
2214 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2215 right = int16_t(v_clamped);
2216
2217 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
2218 aux = int16_t(va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002219
Mathias Agopian65ab4712010-07-14 17:59:35 -07002220 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002221 mAudioMixer->setBufferProvider(name, track);
2222 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002223
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002224 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)left);
2225 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)right);
2226 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)aux);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002227 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002228 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002229 AudioMixer::TRACK,
2230 AudioMixer::FORMAT, (void *)track->format());
2231 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002232 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002233 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002234 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002235 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002236 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002237 AudioMixer::RESAMPLE,
2238 AudioMixer::SAMPLE_RATE,
2239 (void *)(cblk->sampleRate));
2240 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002241 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002242 AudioMixer::TRACK,
2243 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2244 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002245 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002246 AudioMixer::TRACK,
2247 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2248
2249 // reset retry count
2250 track->mRetryCount = kMaxTrackRetries;
Eric Laurent27741442012-01-17 19:20:12 -08002251 // If one track is ready, set the mixer ready if:
2252 // - the mixer was not ready during previous round OR
2253 // - no other track is not ready
2254 if (mPrevMixerStatus != MIXER_TRACKS_READY ||
2255 mixerStatus != MIXER_TRACKS_ENABLED) {
2256 mixerStatus = MIXER_TRACKS_READY;
2257 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002258 } else {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002259 //ALOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002260 if (track->isStopped()) {
2261 track->reset();
2262 }
2263 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2264 // We have consumed all the buffers of this track.
2265 // Remove it from the list of active tracks.
2266 tracksToRemove->add(track);
2267 } else {
2268 // No buffers for this track. Give it a few chances to
2269 // fill a buffer, then remove it from active list.
2270 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002271 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002272 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07002273 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07002274 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08002275 // If one track is not ready, mark the mixer also not ready if:
2276 // - the mixer was ready during previous round OR
2277 // - no other track is ready
2278 } else if (mPrevMixerStatus == MIXER_TRACKS_READY ||
2279 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002280 mixerStatus = MIXER_TRACKS_ENABLED;
2281 }
2282 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002283 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002284 }
2285 }
2286
2287 // remove all the tracks that need to be...
2288 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08002289 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002290 for (size_t i=0 ; i<count ; i++) {
2291 const sp<Track>& track = tracksToRemove->itemAt(i);
2292 mActiveTracks.remove(track);
2293 if (track->mainBuffer() != mMixBuffer) {
2294 chain = getEffectChain_l(track->sessionId());
2295 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01002296 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002297 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002298 }
2299 }
2300 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002301 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002302 }
2303 }
2304 }
2305
2306 // mix buffer must be cleared if all tracks are connected to an
2307 // effect chain as in this case the mixer will not write to
2308 // mix buffer and track effects will accumulate into it
2309 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2310 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2311 }
2312
Eric Laurent27741442012-01-17 19:20:12 -08002313 mPrevMixerStatus = mixerStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002314 return mixerStatus;
2315}
2316
Glenn Kastenfff6d712012-01-12 16:38:12 -08002317void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002318{
Steve Block3856b092011-10-20 11:56:00 +01002319 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07002320 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002321 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07002322
Mathias Agopian65ab4712010-07-14 17:59:35 -07002323 size_t size = mTracks.size();
2324 for (size_t i = 0; i < size; i++) {
2325 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08002326 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07002327 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002328 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002329 }
2330 }
2331}
2332
Glenn Kastenfff6d712012-01-12 16:38:12 -08002333void AudioFlinger::PlaybackThread::setStreamValid(audio_stream_type_t streamType, bool valid)
Eric Laurent9f6530f2011-08-30 10:18:54 -07002334{
Steve Block3856b092011-10-20 11:56:00 +01002335 ALOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07002336 this, streamType, valid);
2337 Mutex::Autolock _l(mLock);
2338
2339 mStreamTypes[streamType].valid = valid;
2340}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002341
2342// getTrackName_l() must be called with ThreadBase::mLock held
2343int AudioFlinger::MixerThread::getTrackName_l()
2344{
2345 return mAudioMixer->getTrackName();
2346}
2347
2348// deleteTrackName_l() must be called with ThreadBase::mLock held
2349void AudioFlinger::MixerThread::deleteTrackName_l(int name)
2350{
Steve Block3856b092011-10-20 11:56:00 +01002351 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002352 mAudioMixer->deleteTrackName(name);
2353}
2354
2355// checkForNewParameters_l() must be called with ThreadBase::mLock held
2356bool AudioFlinger::MixerThread::checkForNewParameters_l()
2357{
2358 bool reconfig = false;
2359
2360 while (!mNewParameters.isEmpty()) {
2361 status_t status = NO_ERROR;
2362 String8 keyValuePair = mNewParameters[0];
2363 AudioParameter param = AudioParameter(keyValuePair);
2364 int value;
2365
2366 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2367 reconfig = true;
2368 }
2369 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08002370 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002371 status = BAD_VALUE;
2372 } else {
2373 reconfig = true;
2374 }
2375 }
2376 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002377 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002378 status = BAD_VALUE;
2379 } else {
2380 reconfig = true;
2381 }
2382 }
2383 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2384 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08002385 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07002386 // if frame count is changed after track creation
2387 if (!mTracks.isEmpty()) {
2388 status = INVALID_OPERATION;
2389 } else {
2390 reconfig = true;
2391 }
2392 }
2393 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002394 // when changing the audio output device, call addBatteryData to notify
2395 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07002396 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002397 uint32_t params = 0;
2398 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07002399 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002400 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2401 }
2402
2403 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07002404 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08002405 // check if any other device (except speaker) is on
2406 if (value & deviceWithoutSpeaker ) {
2407 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2408 }
2409
2410 if (params != 0) {
2411 addBatteryData(params);
2412 }
2413 }
2414
Mathias Agopian65ab4712010-07-14 17:59:35 -07002415 // forward device change to effects that have requested to be
2416 // aware of attached audio device.
2417 mDevice = (uint32_t)value;
2418 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07002419 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002420 }
2421 }
2422
2423 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002424 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002425 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002426 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002427 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002428 mStandby = true;
2429 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002430 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002431 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002432 }
2433 if (status == NO_ERROR && reconfig) {
2434 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08002435 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
2436 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002437 readOutputParameters();
2438 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2439 for (size_t i = 0; i < mTracks.size() ; i++) {
2440 int name = getTrackName_l();
2441 if (name < 0) break;
2442 mTracks[i]->mName = name;
2443 // limit track sample rate to 2 x new output sample rate
2444 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2445 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2446 }
2447 }
2448 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2449 }
2450 }
2451
2452 mNewParameters.removeAt(0);
2453
2454 mParamStatus = status;
2455 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002456 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2457 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002458 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002459 }
2460 return reconfig;
2461}
2462
2463status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2464{
2465 const size_t SIZE = 256;
2466 char buffer[SIZE];
2467 String8 result;
2468
2469 PlaybackThread::dumpInternals(fd, args);
2470
2471 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2472 result.append(buffer);
2473 write(fd, result.string(), result.size());
2474 return NO_ERROR;
2475}
2476
Mathias Agopian65ab4712010-07-14 17:59:35 -07002477uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2478{
Eric Laurent60e18242010-07-29 06:50:24 -07002479 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002480}
2481
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002482uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2483{
2484 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2485}
2486
Mathias Agopian65ab4712010-07-14 17:59:35 -07002487// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002488AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
2489 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002490 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002491 // mLeftVolFloat, mRightVolFloat
2492 // mLeftVolShort, mRightVolShort
Mathias Agopian65ab4712010-07-14 17:59:35 -07002493{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002494}
2495
2496AudioFlinger::DirectOutputThread::~DirectOutputThread()
2497{
2498}
2499
Mathias Agopian65ab4712010-07-14 17:59:35 -07002500void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2501{
2502 // Do not apply volume on compressed audio
Dima Zavinfce7a472011-04-19 22:30:36 -07002503 if (!audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002504 return;
2505 }
2506
2507 // convert to signed 16 bit before volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002508 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002509 size_t count = mFrameCount * mChannelCount;
2510 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2511 int16_t *dst = mMixBuffer + count-1;
2512 while(count--) {
2513 *dst-- = (int16_t)(*src--^0x80) << 8;
2514 }
2515 }
2516
2517 size_t frameCount = mFrameCount;
2518 int16_t *out = mMixBuffer;
2519 if (ramp) {
2520 if (mChannelCount == 1) {
2521 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2522 int32_t vlInc = d / (int32_t)frameCount;
2523 int32_t vl = ((int32_t)mLeftVolShort << 16);
2524 do {
2525 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2526 out++;
2527 vl += vlInc;
2528 } while (--frameCount);
2529
2530 } else {
2531 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2532 int32_t vlInc = d / (int32_t)frameCount;
2533 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2534 int32_t vrInc = d / (int32_t)frameCount;
2535 int32_t vl = ((int32_t)mLeftVolShort << 16);
2536 int32_t vr = ((int32_t)mRightVolShort << 16);
2537 do {
2538 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2539 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2540 out += 2;
2541 vl += vlInc;
2542 vr += vrInc;
2543 } while (--frameCount);
2544 }
2545 } else {
2546 if (mChannelCount == 1) {
2547 do {
2548 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2549 out++;
2550 } while (--frameCount);
2551 } else {
2552 do {
2553 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2554 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2555 out += 2;
2556 } while (--frameCount);
2557 }
2558 }
2559
2560 // convert back to unsigned 8 bit after volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002561 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002562 size_t count = mFrameCount * mChannelCount;
2563 int16_t *src = mMixBuffer;
2564 uint8_t *dst = (uint8_t *)mMixBuffer;
2565 while(count--) {
2566 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2567 }
2568 }
2569
2570 mLeftVolShort = leftVol;
2571 mRightVolShort = rightVol;
2572}
2573
2574bool AudioFlinger::DirectOutputThread::threadLoop()
2575{
Glenn Kasten29c23c32012-01-26 13:37:52 -08002576 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002577 sp<Track> trackToRemove;
2578 sp<Track> activeTrack;
2579 nsecs_t standbyTime = systemTime();
2580 int8_t *curBuf;
2581 size_t mixBufferSize = mFrameCount*mFrameSize;
2582 uint32_t activeSleepTime = activeSleepTimeUs();
2583 uint32_t idleSleepTime = idleSleepTimeUs();
2584 uint32_t sleepTime = idleSleepTime;
2585 // use shorter standby delay as on normal output to release
2586 // hardware resources as soon as possible
2587 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
2588
Eric Laurentfeb0db62011-07-22 09:04:31 -07002589 acquireWakeLock();
2590
Mathias Agopian65ab4712010-07-14 17:59:35 -07002591 while (!exitPending())
2592 {
2593 bool rampVolume;
2594 uint16_t leftVol;
2595 uint16_t rightVol;
2596 Vector< sp<EffectChain> > effectChains;
2597
2598 processConfigEvents();
2599
2600 mixerStatus = MIXER_IDLE;
2601
2602 { // scope for the mLock
2603
2604 Mutex::Autolock _l(mLock);
2605
2606 if (checkForNewParameters_l()) {
2607 mixBufferSize = mFrameCount*mFrameSize;
2608 activeSleepTime = activeSleepTimeUs();
2609 idleSleepTime = idleSleepTimeUs();
2610 standbyDelay = microseconds(activeSleepTime*2);
2611 }
2612
2613 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08002614 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2615 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002616 // wait until we have something to do...
2617 if (!mStandby) {
Glenn Kasten90bebef2012-01-27 15:24:38 -08002618 ALOGV("Audio hardware entering standby, mixer %p", this);
Dima Zavin799a70e2011-04-18 16:57:27 -07002619 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002620 mStandby = true;
2621 mBytesWritten = 0;
2622 }
2623
2624 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2625 // we're about to wait, flush the binder command buffer
2626 IPCThreadState::self()->flushCommands();
2627
2628 if (exitPending()) break;
2629
Eric Laurentfeb0db62011-07-22 09:04:31 -07002630 releaseWakeLock_l();
Glenn Kasten90bebef2012-01-27 15:24:38 -08002631 ALOGV("DirectOutputThread %p TID %d going to sleep", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002632 mWaitWorkCV.wait(mLock);
Glenn Kasten90bebef2012-01-27 15:24:38 -08002633 ALOGV("DirectOutputThread %p TID %d waking up in active mode", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002634 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002635
Glenn Kastenf1d45922012-01-13 15:54:24 -08002636 if (!mMasterMute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002637 char value[PROPERTY_VALUE_MAX];
2638 property_get("ro.audio.silent", value, "0");
2639 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00002640 ALOGD("Silence is golden");
Glenn Kasten6637baa2012-01-09 09:40:36 -08002641 setMasterMute_l(true);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002642 }
2643 }
2644
2645 standbyTime = systemTime() + standbyDelay;
2646 sleepTime = idleSleepTime;
2647 continue;
2648 }
2649 }
2650
2651 effectChains = mEffectChains;
2652
2653 // find out which tracks need to be processed
2654 if (mActiveTracks.size() != 0) {
2655 sp<Track> t = mActiveTracks[0].promote();
2656 if (t == 0) continue;
2657
2658 Track* const track = t.get();
2659 audio_track_cblk_t* cblk = track->cblk();
2660
2661 // The first time a track is added we wait
2662 // for all its buffers to be filled before processing it
Eric Laurentaf59ce22010-10-05 14:41:42 -07002663 if (cblk->framesReady() && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002664 !track->isPaused() && !track->isTerminated())
2665 {
Steve Block3856b092011-10-20 11:56:00 +01002666 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002667
2668 if (track->mFillingUpStatus == Track::FS_FILLED) {
2669 track->mFillingUpStatus = Track::FS_ACTIVE;
2670 mLeftVolFloat = mRightVolFloat = 0;
2671 mLeftVolShort = mRightVolShort = 0;
2672 if (track->mState == TrackBase::RESUMING) {
2673 track->mState = TrackBase::ACTIVE;
2674 rampVolume = true;
2675 }
2676 } else if (cblk->server != 0) {
2677 // If the track is stopped before the first frame was mixed,
2678 // do not apply ramp
2679 rampVolume = true;
2680 }
2681 // compute volume for this track
2682 float left, right;
2683 if (track->isMuted() || mMasterMute || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08002684 mStreamTypes[track->streamType()].mute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002685 left = right = 0;
2686 if (track->isPausing()) {
2687 track->setPaused();
2688 }
2689 } else {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002690 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002691 float v = mMasterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002692 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002693 float v_clamped = v * (vlr & 0xFFFF);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002694 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2695 left = v_clamped/MAX_GAIN;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002696 v_clamped = v * (vlr >> 16);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002697 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2698 right = v_clamped/MAX_GAIN;
2699 }
2700
2701 if (left != mLeftVolFloat || right != mRightVolFloat) {
2702 mLeftVolFloat = left;
2703 mRightVolFloat = right;
2704
2705 // If audio HAL implements volume control,
2706 // force software volume to nominal value
Dima Zavin799a70e2011-04-18 16:57:27 -07002707 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002708 left = 1.0f;
2709 right = 1.0f;
2710 }
2711
2712 // Convert volumes from float to 8.24
2713 uint32_t vl = (uint32_t)(left * (1 << 24));
2714 uint32_t vr = (uint32_t)(right * (1 << 24));
2715
2716 // Delegate volume control to effect in track effect chain if needed
2717 // only one effect chain can be present on DirectOutputThread, so if
2718 // there is one, the track is connected to it
2719 if (!effectChains.isEmpty()) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002720 // Do not ramp volume if volume is controlled by effect
Eric Laurentcab11242010-07-15 12:50:15 -07002721 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002722 rampVolume = false;
2723 }
2724 }
2725
2726 // Convert volumes from 8.24 to 4.12 format
2727 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2728 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2729 leftVol = (uint16_t)v_clamped;
2730 v_clamped = (vr + (1 << 11)) >> 12;
2731 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2732 rightVol = (uint16_t)v_clamped;
2733 } else {
2734 leftVol = mLeftVolShort;
2735 rightVol = mRightVolShort;
2736 rampVolume = false;
2737 }
2738
2739 // reset retry count
2740 track->mRetryCount = kMaxTrackRetriesDirect;
2741 activeTrack = t;
2742 mixerStatus = MIXER_TRACKS_READY;
2743 } else {
Steve Block3856b092011-10-20 11:56:00 +01002744 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002745 if (track->isStopped()) {
2746 track->reset();
2747 }
2748 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2749 // We have consumed all the buffers of this track.
2750 // Remove it from the list of active tracks.
2751 trackToRemove = track;
2752 } else {
2753 // No buffers for this track. Give it a few chances to
2754 // fill a buffer, then remove it from active list.
2755 if (--(track->mRetryCount) <= 0) {
Steve Block3856b092011-10-20 11:56:00 +01002756 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002757 trackToRemove = track;
2758 } else {
2759 mixerStatus = MIXER_TRACKS_ENABLED;
2760 }
2761 }
2762 }
2763 }
2764
2765 // remove all the tracks that need to be...
Glenn Kastenf6b16782011-12-15 09:51:17 -08002766 if (CC_UNLIKELY(trackToRemove != 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002767 mActiveTracks.remove(trackToRemove);
2768 if (!effectChains.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01002769 ALOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
Eric Laurentde070132010-07-13 04:45:46 -07002770 trackToRemove->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002771 effectChains[0]->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002772 }
2773 if (trackToRemove->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002774 removeTrack_l(trackToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002775 }
2776 }
2777
Eric Laurentde070132010-07-13 04:45:46 -07002778 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002779 }
2780
Glenn Kastenf6b16782011-12-15 09:51:17 -08002781 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002782 AudioBufferProvider::Buffer buffer;
2783 size_t frameCount = mFrameCount;
2784 curBuf = (int8_t *)mMixBuffer;
2785 // output audio to hardware
2786 while (frameCount) {
2787 buffer.frameCount = frameCount;
2788 activeTrack->getNextBuffer(&buffer);
Glenn Kastenf6b16782011-12-15 09:51:17 -08002789 if (CC_UNLIKELY(buffer.raw == NULL)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002790 memset(curBuf, 0, frameCount * mFrameSize);
2791 break;
2792 }
2793 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2794 frameCount -= buffer.frameCount;
2795 curBuf += buffer.frameCount * mFrameSize;
2796 activeTrack->releaseBuffer(&buffer);
2797 }
2798 sleepTime = 0;
2799 standbyTime = systemTime() + standbyDelay;
2800 } else {
2801 if (sleepTime == 0) {
2802 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2803 sleepTime = activeSleepTime;
2804 } else {
2805 sleepTime = idleSleepTime;
2806 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002807 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002808 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
2809 sleepTime = 0;
2810 }
2811 }
2812
2813 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002814 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002815 }
2816 // sleepTime == 0 means we must write to audio hardware
2817 if (sleepTime == 0) {
2818 if (mixerStatus == MIXER_TRACKS_READY) {
2819 applyVolume(leftVol, rightVol, rampVolume);
2820 }
2821 for (size_t i = 0; i < effectChains.size(); i ++) {
2822 effectChains[i]->process_l();
2823 }
Eric Laurentde070132010-07-13 04:45:46 -07002824 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002825
2826 mLastWriteTime = systemTime();
2827 mInWrite = true;
2828 mBytesWritten += mixBufferSize;
Dima Zavin799a70e2011-04-18 16:57:27 -07002829 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002830 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2831 mNumWrites++;
2832 mInWrite = false;
2833 mStandby = false;
2834 } else {
Eric Laurentde070132010-07-13 04:45:46 -07002835 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002836 usleep(sleepTime);
2837 }
2838
2839 // finally let go of removed track, without the lock held
2840 // since we can't guarantee the destructors won't acquire that
2841 // same lock.
2842 trackToRemove.clear();
2843 activeTrack.clear();
2844
2845 // Effect chains will be actually deleted here if they were removed from
2846 // mEffectChains list during mixing or effects processing
2847 effectChains.clear();
2848 }
2849
2850 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002851 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002852 }
2853
Eric Laurentfeb0db62011-07-22 09:04:31 -07002854 releaseWakeLock();
2855
Steve Block3856b092011-10-20 11:56:00 +01002856 ALOGV("DirectOutputThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002857 return false;
2858}
2859
2860// getTrackName_l() must be called with ThreadBase::mLock held
2861int AudioFlinger::DirectOutputThread::getTrackName_l()
2862{
2863 return 0;
2864}
2865
2866// deleteTrackName_l() must be called with ThreadBase::mLock held
2867void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2868{
2869}
2870
2871// checkForNewParameters_l() must be called with ThreadBase::mLock held
2872bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2873{
2874 bool reconfig = false;
2875
2876 while (!mNewParameters.isEmpty()) {
2877 status_t status = NO_ERROR;
2878 String8 keyValuePair = mNewParameters[0];
2879 AudioParameter param = AudioParameter(keyValuePair);
2880 int value;
2881
2882 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2883 // do not accept frame count changes if tracks are open as the track buffer
2884 // size depends on frame count and correct behavior would not be garantied
2885 // if frame count is changed after track creation
2886 if (!mTracks.isEmpty()) {
2887 status = INVALID_OPERATION;
2888 } else {
2889 reconfig = true;
2890 }
2891 }
2892 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002893 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002894 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002895 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002896 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002897 mStandby = true;
2898 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002899 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002900 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002901 }
2902 if (status == NO_ERROR && reconfig) {
2903 readOutputParameters();
2904 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2905 }
2906 }
2907
2908 mNewParameters.removeAt(0);
2909
2910 mParamStatus = status;
2911 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002912 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2913 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002914 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002915 }
2916 return reconfig;
2917}
2918
2919uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
2920{
2921 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002922 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08002923 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002924 } else {
2925 time = 10000;
2926 }
2927 return time;
2928}
2929
2930uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2931{
2932 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002933 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07002934 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002935 } else {
2936 time = 10000;
2937 }
2938 return time;
2939}
2940
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002941uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2942{
2943 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002944 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002945 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2946 } else {
2947 time = 10000;
2948 }
2949 return time;
2950}
2951
2952
Mathias Agopian65ab4712010-07-14 17:59:35 -07002953// ----------------------------------------------------------------------------
2954
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002955AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002956 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002957 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
2958 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002959{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002960 addOutputTrack(mainThread);
2961}
2962
2963AudioFlinger::DuplicatingThread::~DuplicatingThread()
2964{
2965 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2966 mOutputTracks[i]->destroy();
2967 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002968}
2969
2970bool AudioFlinger::DuplicatingThread::threadLoop()
2971{
2972 Vector< sp<Track> > tracksToRemove;
Glenn Kasten29c23c32012-01-26 13:37:52 -08002973 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002974 nsecs_t standbyTime = systemTime();
2975 size_t mixBufferSize = mFrameCount*mFrameSize;
2976 SortedVector< sp<OutputTrack> > outputTracks;
2977 uint32_t writeFrames = 0;
2978 uint32_t activeSleepTime = activeSleepTimeUs();
2979 uint32_t idleSleepTime = idleSleepTimeUs();
2980 uint32_t sleepTime = idleSleepTime;
2981 Vector< sp<EffectChain> > effectChains;
2982
Eric Laurentfeb0db62011-07-22 09:04:31 -07002983 acquireWakeLock();
2984
Mathias Agopian65ab4712010-07-14 17:59:35 -07002985 while (!exitPending())
2986 {
2987 processConfigEvents();
2988
2989 mixerStatus = MIXER_IDLE;
2990 { // scope for the mLock
2991
2992 Mutex::Autolock _l(mLock);
2993
2994 if (checkForNewParameters_l()) {
2995 mixBufferSize = mFrameCount*mFrameSize;
2996 updateWaitTime();
2997 activeSleepTime = activeSleepTimeUs();
2998 idleSleepTime = idleSleepTimeUs();
2999 }
3000
3001 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
3002
3003 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3004 outputTracks.add(mOutputTracks[i]);
3005 }
3006
3007 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08003008 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
3009 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003010 if (!mStandby) {
3011 for (size_t i = 0; i < outputTracks.size(); i++) {
3012 outputTracks[i]->stop();
3013 }
3014 mStandby = true;
3015 mBytesWritten = 0;
3016 }
3017
3018 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
3019 // we're about to wait, flush the binder command buffer
3020 IPCThreadState::self()->flushCommands();
3021 outputTracks.clear();
3022
3023 if (exitPending()) break;
3024
Eric Laurentfeb0db62011-07-22 09:04:31 -07003025 releaseWakeLock_l();
Glenn Kasten90bebef2012-01-27 15:24:38 -08003026 ALOGV("DuplicatingThread %p TID %d going to sleep", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003027 mWaitWorkCV.wait(mLock);
Glenn Kasten90bebef2012-01-27 15:24:38 -08003028 ALOGV("DuplicatingThread %p TID %d waking up", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07003029 acquireWakeLock_l();
3030
Eric Laurent27741442012-01-17 19:20:12 -08003031 mPrevMixerStatus = MIXER_IDLE;
Glenn Kastenf1d45922012-01-13 15:54:24 -08003032 if (!mMasterMute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003033 char value[PROPERTY_VALUE_MAX];
3034 property_get("ro.audio.silent", value, "0");
3035 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00003036 ALOGD("Silence is golden");
Glenn Kasten6637baa2012-01-09 09:40:36 -08003037 setMasterMute_l(true);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003038 }
3039 }
3040
3041 standbyTime = systemTime() + kStandbyTimeInNsecs;
3042 sleepTime = idleSleepTime;
3043 continue;
3044 }
3045 }
3046
3047 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
3048
3049 // prevent any changes in effect chain list and in each effect chain
3050 // during mixing and effect process as the audio buffers could be deleted
3051 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07003052 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003053 }
3054
Glenn Kastenf6b16782011-12-15 09:51:17 -08003055 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003056 // mix buffers...
3057 if (outputsReady(outputTracks)) {
3058 mAudioMixer->process();
3059 } else {
3060 memset(mMixBuffer, 0, mixBufferSize);
3061 }
3062 sleepTime = 0;
3063 writeFrames = mFrameCount;
3064 } else {
3065 if (sleepTime == 0) {
3066 if (mixerStatus == MIXER_TRACKS_ENABLED) {
3067 sleepTime = activeSleepTime;
3068 } else {
3069 sleepTime = idleSleepTime;
3070 }
3071 } else if (mBytesWritten != 0) {
3072 // flush remaining overflow buffers in output tracks
3073 for (size_t i = 0; i < outputTracks.size(); i++) {
3074 if (outputTracks[i]->isActive()) {
3075 sleepTime = 0;
3076 writeFrames = 0;
3077 memset(mMixBuffer, 0, mixBufferSize);
3078 break;
3079 }
3080 }
3081 }
3082 }
3083
3084 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003085 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003086 }
3087 // sleepTime == 0 means we must write to audio hardware
3088 if (sleepTime == 0) {
3089 for (size_t i = 0; i < effectChains.size(); i ++) {
3090 effectChains[i]->process_l();
3091 }
3092 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003093 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003094
3095 standbyTime = systemTime() + kStandbyTimeInNsecs;
3096 for (size_t i = 0; i < outputTracks.size(); i++) {
3097 outputTracks[i]->write(mMixBuffer, writeFrames);
3098 }
3099 mStandby = false;
3100 mBytesWritten += mixBufferSize;
3101 } else {
3102 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003103 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003104 usleep(sleepTime);
3105 }
3106
3107 // finally let go of all our tracks, without the lock held
3108 // since we can't guarantee the destructors won't acquire that
3109 // same lock.
3110 tracksToRemove.clear();
3111 outputTracks.clear();
3112
3113 // Effect chains will be actually deleted here if they were removed from
3114 // mEffectChains list during mixing or effects processing
3115 effectChains.clear();
3116 }
3117
Eric Laurentfeb0db62011-07-22 09:04:31 -07003118 releaseWakeLock();
3119
Mathias Agopian65ab4712010-07-14 17:59:35 -07003120 return false;
3121}
3122
3123void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3124{
Glenn Kasten99e53b82012-01-19 08:59:58 -08003125 // FIXME explain this formula
Mathias Agopian65ab4712010-07-14 17:59:35 -07003126 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
3127 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
3128 this,
3129 mSampleRate,
3130 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003131 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003132 frameCount);
3133 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003134 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003135 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003136 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003137 updateWaitTime();
3138 }
3139}
3140
3141void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3142{
3143 Mutex::Autolock _l(mLock);
3144 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3145 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
3146 mOutputTracks[i]->destroy();
3147 mOutputTracks.removeAt(i);
3148 updateWaitTime();
3149 return;
3150 }
3151 }
Steve Block3856b092011-10-20 11:56:00 +01003152 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003153}
3154
3155void AudioFlinger::DuplicatingThread::updateWaitTime()
3156{
3157 mWaitTimeMs = UINT_MAX;
3158 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3159 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08003160 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003161 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3162 if (waitTimeMs < mWaitTimeMs) {
3163 mWaitTimeMs = waitTimeMs;
3164 }
3165 }
3166 }
3167}
3168
3169
3170bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
3171{
3172 for (size_t i = 0; i < outputTracks.size(); i++) {
3173 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
3174 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003175 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003176 return false;
3177 }
3178 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3179 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01003180 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003181 return false;
3182 }
3183 }
3184 return true;
3185}
3186
3187uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3188{
3189 return (mWaitTimeMs * 1000) / 2;
3190}
3191
3192// ----------------------------------------------------------------------------
3193
3194// TrackBase constructor must be called with AudioFlinger::mLock held
3195AudioFlinger::ThreadBase::TrackBase::TrackBase(
3196 const wp<ThreadBase>& thread,
3197 const sp<Client>& client,
3198 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003199 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003200 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003201 int frameCount,
3202 uint32_t flags,
3203 const sp<IMemory>& sharedBuffer,
3204 int sessionId)
3205 : RefBase(),
3206 mThread(thread),
3207 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003208 mCblk(NULL),
3209 // mBuffer
3210 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07003211 mFrameCount(0),
3212 mState(IDLE),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003213 mFormat(format),
3214 mFlags(flags & ~SYSTEM_FLAGS_MASK),
3215 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003216 // mChannelCount
3217 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07003218{
Steve Block3856b092011-10-20 11:56:00 +01003219 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003220
Steve Blockb8a80522011-12-20 16:23:08 +00003221 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003222 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003223 uint8_t channelCount = popcount(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003224 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3225 if (sharedBuffer == 0) {
3226 size += bufferSize;
3227 }
3228
3229 if (client != NULL) {
3230 mCblkMemory = client->heap()->allocate(size);
3231 if (mCblkMemory != 0) {
3232 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08003233 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003234 new(mCblk) audio_track_cblk_t();
3235 // clear all buffers
3236 mCblk->frameCount = frameCount;
3237 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003238 mChannelCount = channelCount;
3239 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003240 if (sharedBuffer == 0) {
3241 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3242 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3243 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003244 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003245 mCblk->flags = CBLK_UNDERRUN_ON;
3246 } else {
3247 mBuffer = sharedBuffer->pointer();
3248 }
3249 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3250 }
3251 } else {
Steve Block29357bc2012-01-06 19:20:56 +00003252 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003253 client->heap()->dump("AudioTrack");
3254 return;
3255 }
3256 } else {
3257 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kasten4a6f0282012-01-06 15:03:11 -08003258 // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003259 new(mCblk) audio_track_cblk_t();
3260 // clear all buffers
3261 mCblk->frameCount = frameCount;
3262 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003263 mChannelCount = channelCount;
3264 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003265 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3266 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3267 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003268 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003269 mCblk->flags = CBLK_UNDERRUN_ON;
3270 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003271 }
3272}
3273
3274AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3275{
Glenn Kastena0d68332012-01-27 16:47:15 -08003276 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003277 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003278 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003279 } else {
3280 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003281 }
3282 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08003283 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08003284 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003285 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07003286 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08003287 // If the client's reference count drops to zero, the associated destructor
3288 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
3289 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003290 mClient.clear();
3291 }
3292}
3293
3294void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3295{
Glenn Kastene0feee32011-12-13 11:53:26 -08003296 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003297 mFrameCount = buffer->frameCount;
3298 step();
3299 buffer->frameCount = 0;
3300}
3301
3302bool AudioFlinger::ThreadBase::TrackBase::step() {
3303 bool result;
3304 audio_track_cblk_t* cblk = this->cblk();
3305
3306 result = cblk->stepServer(mFrameCount);
3307 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01003308 ALOGV("stepServer failed acquiring cblk mutex");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003309 mFlags |= STEPSERVER_FAILED;
3310 }
3311 return result;
3312}
3313
3314void AudioFlinger::ThreadBase::TrackBase::reset() {
3315 audio_track_cblk_t* cblk = this->cblk();
3316
3317 cblk->user = 0;
3318 cblk->server = 0;
3319 cblk->userBase = 0;
3320 cblk->serverBase = 0;
3321 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
Steve Block3856b092011-10-20 11:56:00 +01003322 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003323}
3324
Mathias Agopian65ab4712010-07-14 17:59:35 -07003325int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3326 return (int)mCblk->sampleRate;
3327}
3328
Mathias Agopian65ab4712010-07-14 17:59:35 -07003329void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3330 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08003331 size_t frameSize = cblk->frameSize;
3332 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
3333 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003334
3335 // Check validity of returned pointer in case the track control block would have been corrupted.
3336 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
Glenn Kastenb9980652012-01-11 09:48:27 -08003337 ((unsigned long)bufferStart & (unsigned long)(frameSize - 1))) {
Steve Block29357bc2012-01-06 19:20:56 +00003338 ALOGE("TrackBase::getBuffer buffer out of range:\n start: %p, end %p , mBuffer %p mBufferEnd %p\n \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003339 server %d, serverBase %d, user %d, userBase %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003340 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003341 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
Glenn Kastena0d68332012-01-27 16:47:15 -08003342 return NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003343 }
3344
3345 return bufferStart;
3346}
3347
3348// ----------------------------------------------------------------------------
3349
3350// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3351AudioFlinger::PlaybackThread::Track::Track(
3352 const wp<ThreadBase>& thread,
3353 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08003354 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003355 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003356 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003357 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003358 int frameCount,
3359 const sp<IMemory>& sharedBuffer,
3360 int sessionId)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003361 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId),
Eric Laurent8f45bd72010-08-31 13:50:07 -07003362 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3363 mAuxEffectId(0), mHasVolumeController(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003364{
3365 if (mCblk != NULL) {
3366 sp<ThreadBase> baseThread = thread.promote();
3367 if (baseThread != 0) {
3368 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
3369 mName = playbackThread->getTrackName_l();
3370 mMainBuffer = playbackThread->mixBuffer();
3371 }
Glenn Kasten23d82a92012-02-03 11:10:00 -08003372 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003373 if (mName < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00003374 ALOGE("no more track names available");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003375 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003376 mStreamType = streamType;
3377 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3378 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07003379 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003380 }
3381}
3382
3383AudioFlinger::PlaybackThread::Track::~Track()
3384{
Steve Block3856b092011-10-20 11:56:00 +01003385 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003386 sp<ThreadBase> thread = mThread.promote();
3387 if (thread != 0) {
3388 Mutex::Autolock _l(thread->mLock);
3389 mState = TERMINATED;
3390 }
3391}
3392
3393void AudioFlinger::PlaybackThread::Track::destroy()
3394{
3395 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3396 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08003397 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003398 // we must acquire a strong reference on this Track before locking mLock
3399 // here so that the destructor is called only when exiting this function.
3400 // On the other hand, as long as Track::destroy() is only called by
3401 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3402 // this Track with its member mTrack.
3403 sp<Track> keep(this);
3404 { // scope for mLock
3405 sp<ThreadBase> thread = mThread.promote();
3406 if (thread != 0) {
3407 if (!isOutputTrack()) {
3408 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08003409 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08003410
3411 // to track the speaker usage
3412 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003413 }
3414 AudioSystem::releaseOutput(thread->id());
3415 }
3416 Mutex::Autolock _l(thread->mLock);
3417 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3418 playbackThread->destroyTrack_l(this);
3419 }
3420 }
3421}
3422
3423void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3424{
Glenn Kasten83d86532012-01-17 14:39:34 -08003425 uint32_t vlr = mCblk->getVolumeLR();
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003426 snprintf(buffer, size, " %05d %05d %03u %03u 0x%08x %05u %04u %1d %1d %1d %05u %05u %05u 0x%08x 0x%08x 0x%08x 0x%08x\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003427 mName - AudioMixer::TRACK0,
Glenn Kasten44deb052012-02-05 18:09:08 -08003428 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003429 mStreamType,
3430 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003431 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003432 mSessionId,
3433 mFrameCount,
3434 mState,
3435 mMute,
3436 mFillingUpStatus,
3437 mCblk->sampleRate,
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003438 vlr & 0xFFFF,
3439 vlr >> 16,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003440 mCblk->server,
3441 mCblk->user,
3442 (int)mMainBuffer,
3443 (int)mAuxBuffer);
3444}
3445
3446status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3447{
3448 audio_track_cblk_t* cblk = this->cblk();
3449 uint32_t framesReady;
3450 uint32_t framesReq = buffer->frameCount;
3451
3452 // Check if last stepServer failed, try to step now
3453 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3454 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01003455 ALOGV("stepServer recovered");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003456 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3457 }
3458
3459 framesReady = cblk->framesReady();
3460
Glenn Kastenf6b16782011-12-15 09:51:17 -08003461 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003462 uint32_t s = cblk->server;
3463 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3464
3465 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3466 if (framesReq > framesReady) {
3467 framesReq = framesReady;
3468 }
3469 if (s + framesReq > bufferEnd) {
3470 framesReq = bufferEnd - s;
3471 }
3472
3473 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08003474 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003475
3476 buffer->frameCount = framesReq;
3477 return NO_ERROR;
3478 }
3479
3480getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08003481 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003482 buffer->frameCount = 0;
Steve Block3856b092011-10-20 11:56:00 +01003483 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003484 return NOT_ENOUGH_DATA;
3485}
3486
3487bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07003488 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003489
3490 if (mCblk->framesReady() >= mCblk->frameCount ||
3491 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3492 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07003493 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003494 return true;
3495 }
3496 return false;
3497}
3498
Glenn Kasten6dbc1352012-02-02 10:56:47 -08003499status_t AudioFlinger::PlaybackThread::Track::start(pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003500{
3501 status_t status = NO_ERROR;
Glenn Kasten6dbc1352012-02-02 10:56:47 -08003502 ALOGV("start(%d), calling pid %d session %d tid %d",
3503 mName, IPCThreadState::self()->getCallingPid(), mSessionId, tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003504 sp<ThreadBase> thread = mThread.promote();
3505 if (thread != 0) {
3506 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003507 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003508 // here the track could be either new, or restarted
3509 // in both cases "unstop" the track
3510 if (mState == PAUSED) {
3511 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01003512 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003513 } else {
3514 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01003515 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003516 }
3517
3518 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3519 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003520 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003521 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003522
3523 // to track the speaker usage
3524 if (status == NO_ERROR) {
3525 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3526 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003527 }
3528 if (status == NO_ERROR) {
3529 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3530 playbackThread->addTrack_l(this);
3531 } else {
3532 mState = state;
3533 }
3534 } else {
3535 status = BAD_VALUE;
3536 }
3537 return status;
3538}
3539
3540void AudioFlinger::PlaybackThread::Track::stop()
3541{
Glenn Kasten23d82a92012-02-03 11:10:00 -08003542 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003543 sp<ThreadBase> thread = mThread.promote();
3544 if (thread != 0) {
3545 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003546 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003547 if (mState > STOPPED) {
3548 mState = STOPPED;
3549 // If the track is not active (PAUSED and buffers full), flush buffers
3550 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3551 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3552 reset();
3553 }
Steve Block3856b092011-10-20 11:56:00 +01003554 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003555 }
3556 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3557 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003558 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003559 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003560
3561 // to track the speaker usage
3562 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003563 }
3564 }
3565}
3566
3567void AudioFlinger::PlaybackThread::Track::pause()
3568{
Glenn Kasten23d82a92012-02-03 11:10:00 -08003569 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003570 sp<ThreadBase> thread = mThread.promote();
3571 if (thread != 0) {
3572 Mutex::Autolock _l(thread->mLock);
3573 if (mState == ACTIVE || mState == RESUMING) {
3574 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01003575 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003576 if (!isOutputTrack()) {
3577 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003578 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003579 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003580
3581 // to track the speaker usage
3582 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003583 }
3584 }
3585 }
3586}
3587
3588void AudioFlinger::PlaybackThread::Track::flush()
3589{
Steve Block3856b092011-10-20 11:56:00 +01003590 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003591 sp<ThreadBase> thread = mThread.promote();
3592 if (thread != 0) {
3593 Mutex::Autolock _l(thread->mLock);
3594 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3595 return;
3596 }
3597 // No point remaining in PAUSED state after a flush => go to
3598 // STOPPED state
3599 mState = STOPPED;
3600
Eric Laurent38ccae22011-03-28 18:37:07 -07003601 // do not reset the track if it is still in the process of being stopped or paused.
3602 // this will be done by prepareTracks_l() when the track is stopped.
3603 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3604 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3605 reset();
3606 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003607 }
3608}
3609
3610void AudioFlinger::PlaybackThread::Track::reset()
3611{
3612 // Do not reset twice to avoid discarding data written just after a flush and before
3613 // the audioflinger thread detects the track is stopped.
3614 if (!mResetDone) {
3615 TrackBase::reset();
3616 // Force underrun condition to avoid false underrun callback until first data is
3617 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07003618 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3619 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003620 mFillingUpStatus = FS_FILLING;
3621 mResetDone = true;
3622 }
3623}
3624
3625void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3626{
3627 mMute = muted;
3628}
3629
Mathias Agopian65ab4712010-07-14 17:59:35 -07003630status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3631{
3632 status_t status = DEAD_OBJECT;
3633 sp<ThreadBase> thread = mThread.promote();
3634 if (thread != 0) {
3635 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3636 status = playbackThread->attachAuxEffect(this, EffectId);
3637 }
3638 return status;
3639}
3640
3641void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3642{
3643 mAuxEffectId = EffectId;
3644 mAuxBuffer = buffer;
3645}
3646
3647// ----------------------------------------------------------------------------
3648
3649// RecordTrack constructor must be called with AudioFlinger::mLock held
3650AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3651 const wp<ThreadBase>& thread,
3652 const sp<Client>& client,
3653 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003654 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003655 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003656 int frameCount,
3657 uint32_t flags,
3658 int sessionId)
3659 : TrackBase(thread, client, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003660 channelMask, frameCount, flags, 0, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003661 mOverflow(false)
3662{
3663 if (mCblk != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01003664 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07003665 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003666 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavinfce7a472011-04-19 22:30:36 -07003667 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003668 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003669 } else {
3670 mCblk->frameSize = sizeof(int8_t);
3671 }
3672 }
3673}
3674
3675AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
3676{
3677 sp<ThreadBase> thread = mThread.promote();
3678 if (thread != 0) {
3679 AudioSystem::releaseInput(thread->id());
3680 }
3681}
3682
3683status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3684{
3685 audio_track_cblk_t* cblk = this->cblk();
3686 uint32_t framesAvail;
3687 uint32_t framesReq = buffer->frameCount;
3688
3689 // Check if last stepServer failed, try to step now
3690 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3691 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01003692 ALOGV("stepServer recovered");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003693 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3694 }
3695
3696 framesAvail = cblk->framesAvailable_l();
3697
Glenn Kastenf6b16782011-12-15 09:51:17 -08003698 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003699 uint32_t s = cblk->server;
3700 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3701
3702 if (framesReq > framesAvail) {
3703 framesReq = framesAvail;
3704 }
3705 if (s + framesReq > bufferEnd) {
3706 framesReq = bufferEnd - s;
3707 }
3708
3709 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08003710 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003711
3712 buffer->frameCount = framesReq;
3713 return NO_ERROR;
3714 }
3715
3716getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08003717 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003718 buffer->frameCount = 0;
3719 return NOT_ENOUGH_DATA;
3720}
3721
Glenn Kasten6dbc1352012-02-02 10:56:47 -08003722status_t AudioFlinger::RecordThread::RecordTrack::start(pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003723{
3724 sp<ThreadBase> thread = mThread.promote();
3725 if (thread != 0) {
3726 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten6dbc1352012-02-02 10:56:47 -08003727 return recordThread->start(this, tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003728 } else {
3729 return BAD_VALUE;
3730 }
3731}
3732
3733void AudioFlinger::RecordThread::RecordTrack::stop()
3734{
3735 sp<ThreadBase> thread = mThread.promote();
3736 if (thread != 0) {
3737 RecordThread *recordThread = (RecordThread *)thread.get();
3738 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07003739 TrackBase::reset();
3740 // Force overerrun condition to avoid false overrun callback until first data is
3741 // read from buffer
3742 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003743 }
3744}
3745
3746void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3747{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003748 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08003749 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003750 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003751 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003752 mSessionId,
3753 mFrameCount,
3754 mState,
3755 mCblk->sampleRate,
3756 mCblk->server,
3757 mCblk->user);
3758}
3759
3760
3761// ----------------------------------------------------------------------------
3762
3763AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3764 const wp<ThreadBase>& thread,
3765 DuplicatingThread *sourceThread,
3766 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003767 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003768 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003769 int frameCount)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003770 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003771 mActive(false), mSourceThread(sourceThread)
3772{
3773
3774 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
3775 if (mCblk != NULL) {
3776 mCblk->flags |= CBLK_DIRECTION_OUT;
3777 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003778 mOutBuffer.frameCount = 0;
3779 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01003780 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003781 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
3782 mCblk, mBuffer, mCblk->buffers,
3783 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003784 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003785 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003786 }
3787}
3788
3789AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
3790{
3791 clearBufferQueue();
3792}
3793
Glenn Kasten6dbc1352012-02-02 10:56:47 -08003794status_t AudioFlinger::PlaybackThread::OutputTrack::start(pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003795{
Glenn Kasten6dbc1352012-02-02 10:56:47 -08003796 status_t status = Track::start(tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003797 if (status != NO_ERROR) {
3798 return status;
3799 }
3800
3801 mActive = true;
3802 mRetryCount = 127;
3803 return status;
3804}
3805
3806void AudioFlinger::PlaybackThread::OutputTrack::stop()
3807{
3808 Track::stop();
3809 clearBufferQueue();
3810 mOutBuffer.frameCount = 0;
3811 mActive = false;
3812}
3813
3814bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
3815{
3816 Buffer *pInBuffer;
3817 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003818 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003819 bool outputBufferFull = false;
3820 inBuffer.frameCount = frames;
3821 inBuffer.i16 = data;
3822
3823 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
3824
3825 if (!mActive && frames != 0) {
Glenn Kasten6dbc1352012-02-02 10:56:47 -08003826 start(0);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003827 sp<ThreadBase> thread = mThread.promote();
3828 if (thread != 0) {
3829 MixerThread *mixerThread = (MixerThread *)thread.get();
3830 if (mCblk->frameCount > frames){
3831 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3832 uint32_t startFrames = (mCblk->frameCount - frames);
3833 pInBuffer = new Buffer;
3834 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
3835 pInBuffer->frameCount = startFrames;
3836 pInBuffer->i16 = pInBuffer->mBuffer;
3837 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
3838 mBufferQueue.add(pInBuffer);
3839 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003840 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003841 }
3842 }
3843 }
3844 }
3845
3846 while (waitTimeLeftMs) {
3847 // First write pending buffers, then new data
3848 if (mBufferQueue.size()) {
3849 pInBuffer = mBufferQueue.itemAt(0);
3850 } else {
3851 pInBuffer = &inBuffer;
3852 }
3853
3854 if (pInBuffer->frameCount == 0) {
3855 break;
3856 }
3857
3858 if (mOutBuffer.frameCount == 0) {
3859 mOutBuffer.frameCount = pInBuffer->frameCount;
3860 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08003861 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01003862 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003863 outputBufferFull = true;
3864 break;
3865 }
3866 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
3867 if (waitTimeLeftMs >= waitTimeMs) {
3868 waitTimeLeftMs -= waitTimeMs;
3869 } else {
3870 waitTimeLeftMs = 0;
3871 }
3872 }
3873
3874 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
3875 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
3876 mCblk->stepUser(outFrames);
3877 pInBuffer->frameCount -= outFrames;
3878 pInBuffer->i16 += outFrames * channelCount;
3879 mOutBuffer.frameCount -= outFrames;
3880 mOutBuffer.i16 += outFrames * channelCount;
3881
3882 if (pInBuffer->frameCount == 0) {
3883 if (mBufferQueue.size()) {
3884 mBufferQueue.removeAt(0);
3885 delete [] pInBuffer->mBuffer;
3886 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01003887 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003888 } else {
3889 break;
3890 }
3891 }
3892 }
3893
3894 // If we could not write all frames, allocate a buffer and queue it for next time.
3895 if (inBuffer.frameCount) {
3896 sp<ThreadBase> thread = mThread.promote();
3897 if (thread != 0 && !thread->standby()) {
3898 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3899 pInBuffer = new Buffer;
3900 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
3901 pInBuffer->frameCount = inBuffer.frameCount;
3902 pInBuffer->i16 = pInBuffer->mBuffer;
3903 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
3904 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01003905 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003906 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003907 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003908 }
3909 }
3910 }
3911
3912 // Calling write() with a 0 length buffer, means that no more data will be written:
3913 // If no more buffers are pending, fill output track buffer to make sure it is started
3914 // by output mixer.
3915 if (frames == 0 && mBufferQueue.size() == 0) {
3916 if (mCblk->user < mCblk->frameCount) {
3917 frames = mCblk->frameCount - mCblk->user;
3918 pInBuffer = new Buffer;
3919 pInBuffer->mBuffer = new int16_t[frames * channelCount];
3920 pInBuffer->frameCount = frames;
3921 pInBuffer->i16 = pInBuffer->mBuffer;
3922 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
3923 mBufferQueue.add(pInBuffer);
3924 } else if (mActive) {
3925 stop();
3926 }
3927 }
3928
3929 return outputBufferFull;
3930}
3931
3932status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
3933{
3934 int active;
3935 status_t result;
3936 audio_track_cblk_t* cblk = mCblk;
3937 uint32_t framesReq = buffer->frameCount;
3938
Steve Block3856b092011-10-20 11:56:00 +01003939// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003940 buffer->frameCount = 0;
3941
3942 uint32_t framesAvail = cblk->framesAvailable();
3943
3944
3945 if (framesAvail == 0) {
3946 Mutex::Autolock _l(cblk->lock);
3947 goto start_loop_here;
3948 while (framesAvail == 0) {
3949 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08003950 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01003951 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08003952 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003953 }
3954 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3955 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08003956 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003957 }
3958 // read the server count again
3959 start_loop_here:
3960 framesAvail = cblk->framesAvailable_l();
3961 }
3962 }
3963
3964// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08003965// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003966// }
3967
3968 if (framesReq > framesAvail) {
3969 framesReq = framesAvail;
3970 }
3971
3972 uint32_t u = cblk->user;
3973 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
3974
3975 if (u + framesReq > bufferEnd) {
3976 framesReq = bufferEnd - u;
3977 }
3978
3979 buffer->frameCount = framesReq;
3980 buffer->raw = (void *)cblk->buffer(u);
3981 return NO_ERROR;
3982}
3983
3984
3985void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
3986{
3987 size_t size = mBufferQueue.size();
3988 Buffer *pBuffer;
3989
3990 for (size_t i = 0; i < size; i++) {
3991 pBuffer = mBufferQueue.itemAt(i);
3992 delete [] pBuffer->mBuffer;
3993 delete pBuffer;
3994 }
3995 mBufferQueue.clear();
3996}
3997
3998// ----------------------------------------------------------------------------
3999
4000AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4001 : RefBase(),
4002 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08004003 // FIXME should be a "k" constant not hard-coded, in .h or ro. property, see 4 lines below
Mathias Agopian65ab4712010-07-14 17:59:35 -07004004 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
4005 mPid(pid)
4006{
4007 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4008}
4009
4010// Client destructor must be called with AudioFlinger::mLock held
4011AudioFlinger::Client::~Client()
4012{
4013 mAudioFlinger->removeClient_l(mPid);
4014}
4015
Glenn Kasten435dbe62012-01-30 10:15:48 -08004016sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004017{
4018 return mMemoryDealer;
4019}
4020
4021// ----------------------------------------------------------------------------
4022
4023AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4024 const sp<IAudioFlingerClient>& client,
4025 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004026 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004027{
4028}
4029
4030AudioFlinger::NotificationClient::~NotificationClient()
4031{
Mathias Agopian65ab4712010-07-14 17:59:35 -07004032}
4033
4034void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4035{
4036 sp<NotificationClient> keep(this);
4037 {
4038 mAudioFlinger->removeNotificationClient(mPid);
4039 }
4040}
4041
4042// ----------------------------------------------------------------------------
4043
4044AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
4045 : BnAudioTrack(),
4046 mTrack(track)
4047{
4048}
4049
4050AudioFlinger::TrackHandle::~TrackHandle() {
4051 // just stop the track on deletion, associated resources
4052 // will be freed from the main thread once all pending buffers have
4053 // been played. Unless it's not in the active track list, in which
4054 // case we free everything now...
4055 mTrack->destroy();
4056}
4057
Glenn Kasten90716c52012-01-26 13:40:12 -08004058sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4059 return mTrack->getCblk();
4060}
4061
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004062status_t AudioFlinger::TrackHandle::start(pid_t tid) {
4063 return mTrack->start(tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004064}
4065
4066void AudioFlinger::TrackHandle::stop() {
4067 mTrack->stop();
4068}
4069
4070void AudioFlinger::TrackHandle::flush() {
4071 mTrack->flush();
4072}
4073
4074void AudioFlinger::TrackHandle::mute(bool e) {
4075 mTrack->mute(e);
4076}
4077
4078void AudioFlinger::TrackHandle::pause() {
4079 mTrack->pause();
4080}
4081
Mathias Agopian65ab4712010-07-14 17:59:35 -07004082status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4083{
4084 return mTrack->attachAuxEffect(EffectId);
4085}
4086
4087status_t AudioFlinger::TrackHandle::onTransact(
4088 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4089{
4090 return BnAudioTrack::onTransact(code, data, reply, flags);
4091}
4092
4093// ----------------------------------------------------------------------------
4094
4095sp<IAudioRecord> AudioFlinger::openRecord(
4096 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004097 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004098 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004099 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004100 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004101 int frameCount,
4102 uint32_t flags,
4103 int *sessionId,
4104 status_t *status)
4105{
4106 sp<RecordThread::RecordTrack> recordTrack;
4107 sp<RecordHandle> recordHandle;
4108 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004109 status_t lStatus;
4110 RecordThread *thread;
4111 size_t inFrameCount;
4112 int lSessionId;
4113
4114 // check calling permissions
4115 if (!recordingAllowed()) {
4116 lStatus = PERMISSION_DENIED;
4117 goto Exit;
4118 }
4119
4120 // add client to list
4121 { // scope for mLock
4122 Mutex::Autolock _l(mLock);
4123 thread = checkRecordThread_l(input);
4124 if (thread == NULL) {
4125 lStatus = BAD_VALUE;
4126 goto Exit;
4127 }
4128
Glenn Kasten98ec94c2012-01-25 14:28:29 -08004129 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004130
4131 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07004132 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004133 lSessionId = *sessionId;
4134 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004135 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004136 if (sessionId != NULL) {
4137 *sessionId = lSessionId;
4138 }
4139 }
4140 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004141 recordTrack = thread->createRecordTrack_l(client,
4142 sampleRate,
4143 format,
4144 channelMask,
4145 frameCount,
4146 flags,
4147 lSessionId,
4148 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004149 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004150 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004151 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4152 // destructor is called by the TrackBase destructor with mLock held
4153 client.clear();
4154 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004155 goto Exit;
4156 }
4157
4158 // return to handle to client
4159 recordHandle = new RecordHandle(recordTrack);
4160 lStatus = NO_ERROR;
4161
4162Exit:
4163 if (status) {
4164 *status = lStatus;
4165 }
4166 return recordHandle;
4167}
4168
4169// ----------------------------------------------------------------------------
4170
4171AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
4172 : BnAudioRecord(),
4173 mRecordTrack(recordTrack)
4174{
4175}
4176
4177AudioFlinger::RecordHandle::~RecordHandle() {
4178 stop();
4179}
4180
Glenn Kasten90716c52012-01-26 13:40:12 -08004181sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4182 return mRecordTrack->getCblk();
4183}
4184
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004185status_t AudioFlinger::RecordHandle::start(pid_t tid) {
Steve Block3856b092011-10-20 11:56:00 +01004186 ALOGV("RecordHandle::start()");
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004187 return mRecordTrack->start(tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004188}
4189
4190void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01004191 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004192 mRecordTrack->stop();
4193}
4194
Mathias Agopian65ab4712010-07-14 17:59:35 -07004195status_t AudioFlinger::RecordHandle::onTransact(
4196 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4197{
4198 return BnAudioRecord::onTransact(code, data, reply, flags);
4199}
4200
4201// ----------------------------------------------------------------------------
4202
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004203AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4204 AudioStreamIn *input,
4205 uint32_t sampleRate,
4206 uint32_t channels,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004207 audio_io_handle_t id,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004208 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004209 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004210 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
4211 // mRsmpInIndex and mInputBytes set by readInputParameters()
4212 mReqChannelCount(popcount(channels)),
4213 mReqSampleRate(sampleRate)
4214 // mBytesRead is only meaningful while active, and so is cleared in start()
4215 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004216{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004217 snprintf(mName, kNameLength, "AudioIn_%d", id);
4218
Mathias Agopian65ab4712010-07-14 17:59:35 -07004219 readInputParameters();
4220}
4221
4222
4223AudioFlinger::RecordThread::~RecordThread()
4224{
4225 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08004226 delete mResampler;
4227 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004228}
4229
4230void AudioFlinger::RecordThread::onFirstRef()
4231{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004232 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004233}
4234
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004235status_t AudioFlinger::RecordThread::readyToRun()
4236{
4237 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00004238 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004239 return status;
4240}
4241
Mathias Agopian65ab4712010-07-14 17:59:35 -07004242bool AudioFlinger::RecordThread::threadLoop()
4243{
4244 AudioBufferProvider::Buffer buffer;
4245 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004246 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004247
Eric Laurent44d98482010-09-30 16:12:31 -07004248 nsecs_t lastWarning = 0;
4249
Eric Laurentfeb0db62011-07-22 09:04:31 -07004250 acquireWakeLock();
4251
Mathias Agopian65ab4712010-07-14 17:59:35 -07004252 // start recording
4253 while (!exitPending()) {
4254
4255 processConfigEvents();
4256
4257 { // scope for mLock
4258 Mutex::Autolock _l(mLock);
4259 checkForNewParameters_l();
4260 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4261 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004262 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004263 mStandby = true;
4264 }
4265
4266 if (exitPending()) break;
4267
Eric Laurentfeb0db62011-07-22 09:04:31 -07004268 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01004269 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004270 // go to sleep
4271 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01004272 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07004273 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004274 continue;
4275 }
4276 if (mActiveTrack != 0) {
4277 if (mActiveTrack->mState == TrackBase::PAUSING) {
4278 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004279 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004280 mStandby = true;
4281 }
4282 mActiveTrack.clear();
4283 mStartStopCond.broadcast();
4284 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4285 if (mReqChannelCount != mActiveTrack->channelCount()) {
4286 mActiveTrack.clear();
4287 mStartStopCond.broadcast();
4288 } else if (mBytesRead != 0) {
4289 // record start succeeds only if first read from audio input
4290 // succeeds
4291 if (mBytesRead > 0) {
4292 mActiveTrack->mState = TrackBase::ACTIVE;
4293 } else {
4294 mActiveTrack.clear();
4295 }
4296 mStartStopCond.broadcast();
4297 }
4298 mStandby = false;
4299 }
4300 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004301 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004302 }
4303
4304 if (mActiveTrack != 0) {
4305 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4306 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004307 unlockEffectChains(effectChains);
4308 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004309 continue;
4310 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004311 for (size_t i = 0; i < effectChains.size(); i ++) {
4312 effectChains[i]->process_l();
4313 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004314
Mathias Agopian65ab4712010-07-14 17:59:35 -07004315 buffer.frameCount = mFrameCount;
Glenn Kastenf6b16782011-12-15 09:51:17 -08004316 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004317 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08004318 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004319 // no resampling
4320 while (framesOut) {
4321 size_t framesIn = mFrameCount - mRsmpInIndex;
4322 if (framesIn) {
4323 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4324 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4325 if (framesIn > framesOut)
4326 framesIn = framesOut;
4327 mRsmpInIndex += framesIn;
4328 framesOut -= framesIn;
4329 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07004330 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004331 memcpy(dst, src, framesIn * mFrameSize);
4332 } else {
4333 int16_t *src16 = (int16_t *)src;
4334 int16_t *dst16 = (int16_t *)dst;
4335 if (mChannelCount == 1) {
4336 while (framesIn--) {
4337 *dst16++ = *src16;
4338 *dst16++ = *src16++;
4339 }
4340 } else {
4341 while (framesIn--) {
4342 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4343 src16 += 2;
4344 }
4345 }
4346 }
4347 }
4348 if (framesOut && mFrameCount == mRsmpInIndex) {
4349 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004350 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004351 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004352 framesOut = 0;
4353 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07004354 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004355 mRsmpInIndex = 0;
4356 }
4357 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00004358 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004359 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4360 // Force input into standby so that it tries to
4361 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004362 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004363 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004364 }
4365 mRsmpInIndex = mFrameCount;
4366 framesOut = 0;
4367 buffer.frameCount = 0;
4368 }
4369 }
4370 }
4371 } else {
4372 // resampling
4373
4374 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4375 // alter output frame count as if we were expecting stereo samples
4376 if (mChannelCount == 1 && mReqChannelCount == 1) {
4377 framesOut >>= 1;
4378 }
4379 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4380 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4381 // are 32 bit aligned which should be always true.
4382 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004383 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004384 // the resampler always outputs stereo samples: do post stereo to mono conversion
4385 int16_t *src = (int16_t *)mRsmpOutBuffer;
4386 int16_t *dst = buffer.i16;
4387 while (framesOut--) {
4388 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4389 src += 2;
4390 }
4391 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004392 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004393 }
4394
4395 }
4396 mActiveTrack->releaseBuffer(&buffer);
4397 mActiveTrack->overflow();
4398 }
4399 // client isn't retrieving buffers fast enough
4400 else {
Eric Laurent44d98482010-09-30 16:12:31 -07004401 if (!mActiveTrack->setOverflow()) {
4402 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08004403 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004404 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07004405 lastWarning = now;
4406 }
4407 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004408 // Release the processor for a while before asking for a new buffer.
4409 // This will give the application more chance to read from the buffer and
4410 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004411 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004412 }
4413 }
Eric Laurentec437d82011-07-26 20:54:46 -07004414 // enable changes in effect chain
4415 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004416 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004417 }
4418
4419 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004420 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004421 }
4422 mActiveTrack.clear();
4423
4424 mStartStopCond.broadcast();
4425
Eric Laurentfeb0db62011-07-22 09:04:31 -07004426 releaseWakeLock();
4427
Steve Block3856b092011-10-20 11:56:00 +01004428 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004429 return false;
4430}
4431
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004432
4433sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4434 const sp<AudioFlinger::Client>& client,
4435 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004436 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004437 int channelMask,
4438 int frameCount,
4439 uint32_t flags,
4440 int sessionId,
4441 status_t *status)
4442{
4443 sp<RecordTrack> track;
4444 status_t lStatus;
4445
4446 lStatus = initCheck();
4447 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00004448 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004449 goto Exit;
4450 }
4451
4452 { // scope for mLock
4453 Mutex::Autolock _l(mLock);
4454
4455 track = new RecordTrack(this, client, sampleRate,
4456 format, channelMask, frameCount, flags, sessionId);
4457
Glenn Kasten7378ca52012-01-20 13:44:40 -08004458 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004459 lStatus = NO_MEMORY;
4460 goto Exit;
4461 }
4462
4463 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004464 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4465 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004466 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004467 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4468 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004469 }
4470 lStatus = NO_ERROR;
4471
4472Exit:
4473 if (status) {
4474 *status = lStatus;
4475 }
4476 return track;
4477}
4478
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004479status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack, pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004480{
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004481 ALOGV("RecordThread::start tid=%d", tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004482 sp <ThreadBase> strongMe = this;
4483 status_t status = NO_ERROR;
4484 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08004485 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004486 if (mActiveTrack != 0) {
4487 if (recordTrack != mActiveTrack.get()) {
4488 status = -EBUSY;
4489 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4490 mActiveTrack->mState = TrackBase::ACTIVE;
4491 }
4492 return status;
4493 }
4494
4495 recordTrack->mState = TrackBase::IDLE;
4496 mActiveTrack = recordTrack;
4497 mLock.unlock();
4498 status_t status = AudioSystem::startInput(mId);
4499 mLock.lock();
4500 if (status != NO_ERROR) {
4501 mActiveTrack.clear();
4502 return status;
4503 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004504 mRsmpInIndex = mFrameCount;
4505 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08004506 if (mResampler != NULL) {
4507 mResampler->reset();
4508 }
4509 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004510 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01004511 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004512 mWaitWorkCV.signal();
4513 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08004514 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004515 mActiveTrack.clear();
4516 status = INVALID_OPERATION;
4517 goto startError;
4518 }
4519 mStartStopCond.wait(mLock);
4520 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01004521 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004522 status = BAD_VALUE;
4523 goto startError;
4524 }
Steve Block3856b092011-10-20 11:56:00 +01004525 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004526 return status;
4527 }
4528startError:
4529 AudioSystem::stopInput(mId);
4530 return status;
4531}
4532
4533void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01004534 ALOGV("RecordThread::stop");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004535 sp <ThreadBase> strongMe = this;
4536 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08004537 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004538 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4539 mActiveTrack->mState = TrackBase::PAUSING;
4540 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08004541 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004542 return;
4543 }
4544 mStartStopCond.wait(mLock);
4545 // if we have been restarted, recordTrack == mActiveTrack.get() here
4546 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4547 mLock.unlock();
4548 AudioSystem::stopInput(mId);
4549 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01004550 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004551 }
4552 }
4553 }
4554}
4555
4556status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4557{
4558 const size_t SIZE = 256;
4559 char buffer[SIZE];
4560 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004561
4562 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4563 result.append(buffer);
4564
4565 if (mActiveTrack != 0) {
4566 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004567 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004568 mActiveTrack->dump(buffer, SIZE);
4569 result.append(buffer);
4570
4571 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4572 result.append(buffer);
4573 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4574 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08004575 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07004576 result.append(buffer);
4577 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4578 result.append(buffer);
4579 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4580 result.append(buffer);
4581
4582
4583 } else {
4584 result.append("No record client\n");
4585 }
4586 write(fd, result.string(), result.size());
4587
4588 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07004589 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004590
4591 return NO_ERROR;
4592}
4593
4594status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4595{
4596 size_t framesReq = buffer->frameCount;
4597 size_t framesReady = mFrameCount - mRsmpInIndex;
4598 int channelCount;
4599
4600 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004601 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004602 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00004603 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004604 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4605 // Force input into standby so that it tries to
4606 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004607 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004608 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004609 }
Glenn Kastene0feee32011-12-13 11:53:26 -08004610 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004611 buffer->frameCount = 0;
4612 return NOT_ENOUGH_DATA;
4613 }
4614 mRsmpInIndex = 0;
4615 framesReady = mFrameCount;
4616 }
4617
4618 if (framesReq > framesReady) {
4619 framesReq = framesReady;
4620 }
4621
4622 if (mChannelCount == 1 && mReqChannelCount == 2) {
4623 channelCount = 1;
4624 } else {
4625 channelCount = 2;
4626 }
4627 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4628 buffer->frameCount = framesReq;
4629 return NO_ERROR;
4630}
4631
4632void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4633{
4634 mRsmpInIndex += buffer->frameCount;
4635 buffer->frameCount = 0;
4636}
4637
4638bool AudioFlinger::RecordThread::checkForNewParameters_l()
4639{
4640 bool reconfig = false;
4641
4642 while (!mNewParameters.isEmpty()) {
4643 status_t status = NO_ERROR;
4644 String8 keyValuePair = mNewParameters[0];
4645 AudioParameter param = AudioParameter(keyValuePair);
4646 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08004647 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004648 int reqSamplingRate = mReqSampleRate;
4649 int reqChannelCount = mReqChannelCount;
4650
4651 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4652 reqSamplingRate = value;
4653 reconfig = true;
4654 }
4655 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08004656 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004657 reconfig = true;
4658 }
4659 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004660 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004661 reconfig = true;
4662 }
4663 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4664 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08004665 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07004666 // if frame count is changed after track creation
4667 if (mActiveTrack != 0) {
4668 status = INVALID_OPERATION;
4669 } else {
4670 reconfig = true;
4671 }
4672 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004673 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4674 // forward device change to effects that have requested to be
4675 // aware of attached audio device.
4676 for (size_t i = 0; i < mEffectChains.size(); i++) {
4677 mEffectChains[i]->setDevice_l(value);
4678 }
4679 // store input device and output device but do not forward output device to audio HAL.
4680 // Note that status is ignored by the caller for output device
4681 // (see AudioFlinger::setParameters()
4682 if (value & AUDIO_DEVICE_OUT_ALL) {
4683 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
4684 status = BAD_VALUE;
4685 } else {
4686 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07004687 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4688 if (mTrack != NULL) {
4689 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004690 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004691 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
4692 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
4693 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004694 }
4695 mDevice |= (uint32_t)value;
4696 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004697 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004698 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004699 if (status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004700 mInput->stream->common.standby(&mInput->stream->common);
4701 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004702 }
4703 if (reconfig) {
4704 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004705 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004706 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004707 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
4708 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004709 (reqChannelCount < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004710 status = NO_ERROR;
4711 }
4712 if (status == NO_ERROR) {
4713 readInputParameters();
4714 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
4715 }
4716 }
4717 }
4718
4719 mNewParameters.removeAt(0);
4720
4721 mParamStatus = status;
4722 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07004723 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4724 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08004725 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004726 }
4727 return reconfig;
4728}
4729
4730String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4731{
Dima Zavinfce7a472011-04-19 22:30:36 -07004732 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004733 String8 out_s8 = String8();
4734
4735 Mutex::Autolock _l(mLock);
4736 if (initCheck() != NO_ERROR) {
4737 return out_s8;
4738 }
Dima Zavinfce7a472011-04-19 22:30:36 -07004739
Dima Zavin799a70e2011-04-18 16:57:27 -07004740 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07004741 out_s8 = String8(s);
4742 free(s);
4743 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004744}
4745
4746void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
4747 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08004748 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004749
4750 switch (event) {
4751 case AudioSystem::INPUT_OPENED:
4752 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004753 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004754 desc.samplingRate = mSampleRate;
4755 desc.format = mFormat;
4756 desc.frameCount = mFrameCount;
4757 desc.latency = 0;
4758 param2 = &desc;
4759 break;
4760
4761 case AudioSystem::INPUT_CLOSED:
4762 default:
4763 break;
4764 }
4765 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
4766}
4767
4768void AudioFlinger::RecordThread::readInputParameters()
4769{
Glenn Kastene9dd0172012-01-27 18:08:45 -08004770 delete mRsmpInBuffer;
4771 // mRsmpInBuffer is always assigned a new[] below
4772 delete mRsmpOutBuffer;
4773 mRsmpOutBuffer = NULL;
4774 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08004775 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004776
Dima Zavin799a70e2011-04-18 16:57:27 -07004777 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004778 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
4779 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07004780 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08004781 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07004782 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004783 mFrameCount = mInputBytes / mFrameSize;
4784 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4785
4786 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4787 {
4788 int channelCount;
4789 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4790 // stereo to mono post process as the resampler always outputs stereo.
4791 if (mChannelCount == 1 && mReqChannelCount == 2) {
4792 channelCount = 1;
4793 } else {
4794 channelCount = 2;
4795 }
4796 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4797 mResampler->setSampleRate(mSampleRate);
4798 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4799 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4800
4801 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4802 if (mChannelCount == 1 && mReqChannelCount == 1) {
4803 mFrameCount >>= 1;
4804 }
4805
4806 }
4807 mRsmpInIndex = mFrameCount;
4808}
4809
4810unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4811{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004812 Mutex::Autolock _l(mLock);
4813 if (initCheck() != NO_ERROR) {
4814 return 0;
4815 }
4816
Dima Zavin799a70e2011-04-18 16:57:27 -07004817 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004818}
4819
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004820uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
4821{
4822 Mutex::Autolock _l(mLock);
4823 uint32_t result = 0;
4824 if (getEffectChain_l(sessionId) != 0) {
4825 result = EFFECT_SESSION;
4826 }
4827
4828 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
4829 result |= TRACK_SESSION;
4830 }
4831
4832 return result;
4833}
4834
Eric Laurent59bd0da2011-08-01 09:52:20 -07004835AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
4836{
4837 Mutex::Autolock _l(mLock);
4838 return mTrack;
4839}
4840
Glenn Kastenaed850d2012-01-26 09:46:34 -08004841AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004842{
4843 Mutex::Autolock _l(mLock);
4844 return mInput;
4845}
4846
4847AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
4848{
4849 Mutex::Autolock _l(mLock);
4850 AudioStreamIn *input = mInput;
4851 mInput = NULL;
4852 return input;
4853}
4854
4855// this method must always be called either with ThreadBase mLock held or inside the thread loop
4856audio_stream_t* AudioFlinger::RecordThread::stream()
4857{
4858 if (mInput == NULL) {
4859 return NULL;
4860 }
4861 return &mInput->stream->common;
4862}
4863
4864
Mathias Agopian65ab4712010-07-14 17:59:35 -07004865// ----------------------------------------------------------------------------
4866
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004867audio_io_handle_t AudioFlinger::openOutput(uint32_t *pDevices,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004868 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004869 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004870 uint32_t *pChannels,
4871 uint32_t *pLatencyMs,
4872 uint32_t flags)
4873{
4874 status_t status;
4875 PlaybackThread *thread = NULL;
4876 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4877 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08004878 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004879 uint32_t channels = pChannels ? *pChannels : 0;
4880 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07004881 audio_stream_out_t *outStream;
4882 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004883
Steve Block3856b092011-10-20 11:56:00 +01004884 ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004885 pDevices ? *pDevices : 0,
4886 samplingRate,
4887 format,
4888 channels,
4889 flags);
4890
4891 if (pDevices == NULL || *pDevices == 0) {
4892 return 0;
4893 }
Dima Zavin799a70e2011-04-18 16:57:27 -07004894
Mathias Agopian65ab4712010-07-14 17:59:35 -07004895 Mutex::Autolock _l(mLock);
4896
Dima Zavin799a70e2011-04-18 16:57:27 -07004897 outHwDev = findSuitableHwDev_l(*pDevices);
4898 if (outHwDev == NULL)
4899 return 0;
4900
Glenn Kasten58f30212012-01-12 12:27:51 -08004901 status = outHwDev->open_output_stream(outHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07004902 &channels, &samplingRate, &outStream);
Steve Block3856b092011-10-20 11:56:00 +01004903 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07004904 outStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004905 samplingRate,
4906 format,
4907 channels,
4908 status);
4909
4910 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -07004911 if (outStream != NULL) {
4912 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004913 audio_io_handle_t id = nextUniqueId();
Dima Zavin799a70e2011-04-18 16:57:27 -07004914
Dima Zavinfce7a472011-04-19 22:30:36 -07004915 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
4916 (format != AUDIO_FORMAT_PCM_16_BIT) ||
4917 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004918 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01004919 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004920 } else {
4921 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01004922 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004923 }
4924 mPlaybackThreads.add(id, thread);
4925
Glenn Kastena0d68332012-01-27 16:47:15 -08004926 if (pSamplingRate != NULL) *pSamplingRate = samplingRate;
4927 if (pFormat != NULL) *pFormat = format;
4928 if (pChannels != NULL) *pChannels = channels;
4929 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004930
4931 // notify client processes of the new output creation
4932 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4933 return id;
4934 }
4935
4936 return 0;
4937}
4938
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004939audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
4940 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004941{
4942 Mutex::Autolock _l(mLock);
4943 MixerThread *thread1 = checkMixerThread_l(output1);
4944 MixerThread *thread2 = checkMixerThread_l(output2);
4945
4946 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004947 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004948 return 0;
4949 }
4950
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004951 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004952 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
4953 thread->addOutputTrack(thread2);
4954 mPlaybackThreads.add(id, thread);
4955 // notify client processes of the new output creation
4956 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4957 return id;
4958}
4959
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004960status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004961{
4962 // keep strong reference on the playback thread so that
4963 // it is not destroyed while exit() is executed
4964 sp <PlaybackThread> thread;
4965 {
4966 Mutex::Autolock _l(mLock);
4967 thread = checkPlaybackThread_l(output);
4968 if (thread == NULL) {
4969 return BAD_VALUE;
4970 }
4971
Steve Block3856b092011-10-20 11:56:00 +01004972 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004973
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004974 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004975 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004976 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004977 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
4978 dupThread->removeOutputTrack((MixerThread *)thread.get());
4979 }
4980 }
4981 }
Glenn Kastena0d68332012-01-27 16:47:15 -08004982 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004983 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
4984 mPlaybackThreads.removeItem(output);
4985 }
4986 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08004987 // The thread entity (active unit of execution) is no longer running here,
4988 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004989
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004990 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004991 AudioStreamOut *out = thread->clearOutput();
Glenn Kastenaed850d2012-01-26 09:46:34 -08004992 assert(out != NULL);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004993 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07004994 out->hwDev->close_output_stream(out->hwDev, out->stream);
4995 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004996 }
4997 return NO_ERROR;
4998}
4999
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005000status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005001{
5002 Mutex::Autolock _l(mLock);
5003 PlaybackThread *thread = checkPlaybackThread_l(output);
5004
5005 if (thread == NULL) {
5006 return BAD_VALUE;
5007 }
5008
Steve Block3856b092011-10-20 11:56:00 +01005009 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005010 thread->suspend();
5011
5012 return NO_ERROR;
5013}
5014
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005015status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005016{
5017 Mutex::Autolock _l(mLock);
5018 PlaybackThread *thread = checkPlaybackThread_l(output);
5019
5020 if (thread == NULL) {
5021 return BAD_VALUE;
5022 }
5023
Steve Block3856b092011-10-20 11:56:00 +01005024 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005025
5026 thread->restore();
5027
5028 return NO_ERROR;
5029}
5030
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005031audio_io_handle_t AudioFlinger::openInput(uint32_t *pDevices,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005032 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005033 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005034 uint32_t *pChannels,
Glenn Kastende9719b2012-01-27 12:32:34 -08005035 audio_in_acoustics_t acoustics)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005036{
5037 status_t status;
5038 RecordThread *thread = NULL;
5039 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08005040 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005041 uint32_t channels = pChannels ? *pChannels : 0;
5042 uint32_t reqSamplingRate = samplingRate;
Glenn Kasten58f30212012-01-12 12:27:51 -08005043 audio_format_t reqFormat = format;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005044 uint32_t reqChannels = channels;
Dima Zavin799a70e2011-04-18 16:57:27 -07005045 audio_stream_in_t *inStream;
5046 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005047
5048 if (pDevices == NULL || *pDevices == 0) {
5049 return 0;
5050 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005051
Mathias Agopian65ab4712010-07-14 17:59:35 -07005052 Mutex::Autolock _l(mLock);
5053
Dima Zavin799a70e2011-04-18 16:57:27 -07005054 inHwDev = findSuitableHwDev_l(*pDevices);
5055 if (inHwDev == NULL)
5056 return 0;
5057
Glenn Kasten58f30212012-01-12 12:27:51 -08005058 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005059 &channels, &samplingRate,
Glenn Kastende9719b2012-01-27 12:32:34 -08005060 acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005061 &inStream);
Steve Block3856b092011-10-20 11:56:00 +01005062 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005063 inStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005064 samplingRate,
5065 format,
5066 channels,
5067 acoustics,
5068 status);
5069
5070 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5071 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5072 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin799a70e2011-04-18 16:57:27 -07005073 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005074 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005075 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005076 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Steve Block3856b092011-10-20 11:56:00 +01005077 ALOGV("openInput() reopening with proposed sampling rate and channels");
Glenn Kasten58f30212012-01-12 12:27:51 -08005078 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005079 &channels, &samplingRate,
Glenn Kastende9719b2012-01-27 12:32:34 -08005080 acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005081 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005082 }
5083
Dima Zavin799a70e2011-04-18 16:57:27 -07005084 if (inStream != NULL) {
5085 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5086
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005087 audio_io_handle_t id = nextUniqueId();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005088 // Start record thread
5089 // RecorThread require both input and output device indication to forward to audio
5090 // pre processing modules
5091 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5092 thread = new RecordThread(this,
5093 input,
5094 reqSamplingRate,
5095 reqChannels,
5096 id,
5097 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005098 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01005099 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08005100 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
5101 if (pFormat != NULL) *pFormat = format;
5102 if (pChannels != NULL) *pChannels = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005103
Dima Zavin799a70e2011-04-18 16:57:27 -07005104 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005105
5106 // notify client processes of the new input creation
5107 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
5108 return id;
5109 }
5110
5111 return 0;
5112}
5113
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005114status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005115{
5116 // keep strong reference on the record thread so that
5117 // it is not destroyed while exit() is executed
5118 sp <RecordThread> thread;
5119 {
5120 Mutex::Autolock _l(mLock);
5121 thread = checkRecordThread_l(input);
5122 if (thread == NULL) {
5123 return BAD_VALUE;
5124 }
5125
Steve Block3856b092011-10-20 11:56:00 +01005126 ALOGV("closeInput() %d", input);
Glenn Kastena0d68332012-01-27 16:47:15 -08005127 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005128 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
5129 mRecordThreads.removeItem(input);
5130 }
5131 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08005132 // The thread entity (active unit of execution) is no longer running here,
5133 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07005134
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005135 AudioStreamIn *in = thread->clearInput();
Glenn Kastenaed850d2012-01-26 09:46:34 -08005136 assert(in != NULL);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005137 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005138 in->hwDev->close_input_stream(in->hwDev, in->stream);
5139 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005140
5141 return NO_ERROR;
5142}
5143
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005144status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005145{
5146 Mutex::Autolock _l(mLock);
5147 MixerThread *dstThread = checkMixerThread_l(output);
5148 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005149 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005150 return BAD_VALUE;
5151 }
5152
Steve Block3856b092011-10-20 11:56:00 +01005153 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005154 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
5155
Eric Laurent9f6530f2011-08-30 10:18:54 -07005156 dstThread->setStreamValid(stream, true);
5157
Mathias Agopian65ab4712010-07-14 17:59:35 -07005158 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5159 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
5160 if (thread != dstThread &&
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005161 thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005162 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent9f6530f2011-08-30 10:18:54 -07005163 srcThread->setStreamValid(stream, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005164 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005165 }
Eric Laurentde070132010-07-13 04:45:46 -07005166 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005167
5168 return NO_ERROR;
5169}
5170
5171
5172int AudioFlinger::newAudioSessionId()
5173{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005174 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005175}
5176
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005177void AudioFlinger::acquireAudioSessionId(int audioSession)
5178{
5179 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08005180 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005181 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08005182 size_t num = mAudioSessionRefs.size();
5183 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005184 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
5185 if (ref->sessionid == audioSession && ref->pid == caller) {
5186 ref->cnt++;
Steve Block3856b092011-10-20 11:56:00 +01005187 ALOGV(" incremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005188 return;
5189 }
5190 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005191 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
5192 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005193}
5194
5195void AudioFlinger::releaseAudioSessionId(int audioSession)
5196{
5197 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08005198 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005199 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08005200 size_t num = mAudioSessionRefs.size();
5201 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005202 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
5203 if (ref->sessionid == audioSession && ref->pid == caller) {
5204 ref->cnt--;
Steve Block3856b092011-10-20 11:56:00 +01005205 ALOGV(" decremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005206 if (ref->cnt == 0) {
5207 mAudioSessionRefs.removeAt(i);
5208 delete ref;
5209 purgeStaleEffects_l();
5210 }
5211 return;
5212 }
5213 }
Steve Block5ff1dd52012-01-05 23:22:43 +00005214 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005215}
5216
5217void AudioFlinger::purgeStaleEffects_l() {
5218
Steve Block3856b092011-10-20 11:56:00 +01005219 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005220
5221 Vector< sp<EffectChain> > chains;
5222
5223 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5224 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5225 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5226 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07005227 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5228 chains.push(ec);
5229 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005230 }
5231 }
5232 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5233 sp<RecordThread> t = mRecordThreads.valueAt(i);
5234 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5235 sp<EffectChain> ec = t->mEffectChains[j];
5236 chains.push(ec);
5237 }
5238 }
5239
5240 for (size_t i = 0; i < chains.size(); i++) {
5241 sp<EffectChain> ec = chains[i];
5242 int sessionid = ec->sessionId();
5243 sp<ThreadBase> t = ec->mThread.promote();
5244 if (t == 0) {
5245 continue;
5246 }
5247 size_t numsessionrefs = mAudioSessionRefs.size();
5248 bool found = false;
5249 for (size_t k = 0; k < numsessionrefs; k++) {
5250 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
5251 if (ref->sessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01005252 ALOGV(" session %d still exists for %d with %d refs",
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005253 sessionid, ref->pid, ref->cnt);
5254 found = true;
5255 break;
5256 }
5257 }
5258 if (!found) {
5259 // remove all effects from the chain
5260 while (ec->mEffects.size()) {
5261 sp<EffectModule> effect = ec->mEffects[0];
5262 effect->unPin();
5263 Mutex::Autolock _l (t->mLock);
5264 t->removeEffect_l(effect);
5265 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5266 sp<EffectHandle> handle = effect->mHandles[j].promote();
5267 if (handle != 0) {
5268 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07005269 if (handle->mHasControl && handle->mEnabled) {
5270 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
5271 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005272 }
5273 }
5274 AudioSystem::unregisterEffect(effect->id());
5275 }
5276 }
5277 }
5278 return;
5279}
5280
Mathias Agopian65ab4712010-07-14 17:59:35 -07005281// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005282AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005283{
5284 PlaybackThread *thread = NULL;
5285 if (mPlaybackThreads.indexOfKey(output) >= 0) {
5286 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
5287 }
5288 return thread;
5289}
5290
5291// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005292AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005293{
5294 PlaybackThread *thread = checkPlaybackThread_l(output);
5295 if (thread != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005296 if (thread->type() == ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005297 thread = NULL;
5298 }
5299 }
5300 return (MixerThread *)thread;
5301}
5302
5303// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005304AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005305{
5306 RecordThread *thread = NULL;
5307 if (mRecordThreads.indexOfKey(input) >= 0) {
5308 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
5309 }
5310 return thread;
5311}
5312
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005313uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07005314{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005315 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005316}
5317
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005318AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l()
5319{
5320 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5321 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005322 AudioStreamOut *output = thread->getOutput();
5323 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005324 return thread;
5325 }
5326 }
5327 return NULL;
5328}
5329
5330uint32_t AudioFlinger::primaryOutputDevice_l()
5331{
5332 PlaybackThread *thread = primaryPlaybackThread_l();
5333
5334 if (thread == NULL) {
5335 return 0;
5336 }
5337
5338 return thread->device();
5339}
5340
5341
Mathias Agopian65ab4712010-07-14 17:59:35 -07005342// ----------------------------------------------------------------------------
5343// Effect management
5344// ----------------------------------------------------------------------------
5345
5346
Glenn Kastenf587ba52012-01-26 16:25:10 -08005347status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005348{
5349 Mutex::Autolock _l(mLock);
5350 return EffectQueryNumberEffects(numEffects);
5351}
5352
Glenn Kastenf587ba52012-01-26 16:25:10 -08005353status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005354{
5355 Mutex::Autolock _l(mLock);
5356 return EffectQueryEffect(index, descriptor);
5357}
5358
Glenn Kasten5e92a782012-01-30 07:40:52 -08005359status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08005360 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005361{
5362 Mutex::Autolock _l(mLock);
5363 return EffectGetDescriptor(pUuid, descriptor);
5364}
5365
5366
Mathias Agopian65ab4712010-07-14 17:59:35 -07005367sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5368 effect_descriptor_t *pDesc,
5369 const sp<IEffectClient>& effectClient,
5370 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005371 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005372 int sessionId,
5373 status_t *status,
5374 int *id,
5375 int *enabled)
5376{
5377 status_t lStatus = NO_ERROR;
5378 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005379 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005380
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005381 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005382 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005383
5384 if (pDesc == NULL) {
5385 lStatus = BAD_VALUE;
5386 goto Exit;
5387 }
5388
Eric Laurent84e9a102010-09-23 16:10:16 -07005389 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005390 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005391 lStatus = PERMISSION_DENIED;
5392 goto Exit;
5393 }
5394
Dima Zavinfce7a472011-04-19 22:30:36 -07005395 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07005396 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08005397 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005398 lStatus = PERMISSION_DENIED;
5399 goto Exit;
5400 }
5401
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005402 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005403 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005404 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07005405 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07005406 lStatus = BAD_VALUE;
5407 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07005408 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005409 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005410 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07005411 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005412 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07005413 }
5414 }
5415
Mathias Agopian65ab4712010-07-14 17:59:35 -07005416 {
5417 Mutex::Autolock _l(mLock);
5418
Mathias Agopian65ab4712010-07-14 17:59:35 -07005419
5420 if (!EffectIsNullUuid(&pDesc->uuid)) {
5421 // if uuid is specified, request effect descriptor
5422 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5423 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005424 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005425 goto Exit;
5426 }
5427 } else {
5428 // if uuid is not specified, look for an available implementation
5429 // of the required type in effect factory
5430 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005431 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005432 lStatus = BAD_VALUE;
5433 goto Exit;
5434 }
5435 uint32_t numEffects = 0;
5436 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005437 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07005438 bool found = false;
5439
5440 lStatus = EffectQueryNumberEffects(&numEffects);
5441 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005442 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005443 goto Exit;
5444 }
5445 for (uint32_t i = 0; i < numEffects; i++) {
5446 lStatus = EffectQueryEffect(i, &desc);
5447 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005448 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005449 continue;
5450 }
5451 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5452 // If matching type found save effect descriptor. If the session is
5453 // 0 and the effect is not auxiliary, continue enumeration in case
5454 // an auxiliary version of this effect type is available
5455 found = true;
5456 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07005457 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07005458 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5459 break;
5460 }
5461 }
5462 }
5463 if (!found) {
5464 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00005465 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005466 goto Exit;
5467 }
5468 // For same effect type, chose auxiliary version over insert version if
5469 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07005470 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005471 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
5472 memcpy(&desc, &d, sizeof(effect_descriptor_t));
5473 }
5474 }
5475
5476 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07005477 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005478 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5479 lStatus = INVALID_OPERATION;
5480 goto Exit;
5481 }
5482
Eric Laurent59255e42011-07-27 19:49:51 -07005483 // check recording permission for visualizer
5484 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
5485 !recordingAllowed()) {
5486 lStatus = PERMISSION_DENIED;
5487 goto Exit;
5488 }
5489
Mathias Agopian65ab4712010-07-14 17:59:35 -07005490 // return effect descriptor
5491 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
5492
5493 // If output is not specified try to find a matching audio session ID in one of the
5494 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07005495 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
5496 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005497 // Note: io is never 0 when creating an effect on an input
5498 if (io == 0) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005499 // look for the thread where the specified audio session is present
5500 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5501 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005502 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07005503 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07005504 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005505 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005506 if (io == 0) {
5507 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5508 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5509 io = mRecordThreads.keyAt(i);
5510 break;
5511 }
5512 }
5513 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005514 // If no output thread contains the requested session ID, default to
5515 // first output. The effect chain will be moved to the correct output
5516 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005517 if (io == 0 && mPlaybackThreads.size()) {
5518 io = mPlaybackThreads.keyAt(0);
5519 }
Steve Block3856b092011-10-20 11:56:00 +01005520 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005521 }
5522 ThreadBase *thread = checkRecordThread_l(io);
5523 if (thread == NULL) {
5524 thread = checkPlaybackThread_l(io);
5525 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00005526 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005527 lStatus = BAD_VALUE;
5528 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07005529 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005530 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005531
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005532 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005533
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005534 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07005535 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
5536 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005537 if (handle != 0 && id != NULL) {
5538 *id = handle->id();
5539 }
5540 }
5541
5542Exit:
5543 if(status) {
5544 *status = lStatus;
5545 }
5546 return handle;
5547}
5548
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005549status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
5550 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07005551{
Steve Block3856b092011-10-20 11:56:00 +01005552 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07005553 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005554 Mutex::Autolock _l(mLock);
5555 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005556 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005557 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005558 }
Eric Laurentde070132010-07-13 04:45:46 -07005559 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
5560 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005561 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005562 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005563 }
Eric Laurentde070132010-07-13 04:45:46 -07005564 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
5565 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005566 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005567 return BAD_VALUE;
5568 }
5569
5570 Mutex::Autolock _dl(dstThread->mLock);
5571 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07005572 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07005573
Mathias Agopian65ab4712010-07-14 17:59:35 -07005574 return NO_ERROR;
5575}
5576
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005577// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07005578status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07005579 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07005580 AudioFlinger::PlaybackThread *dstThread,
5581 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07005582{
Steve Block3856b092011-10-20 11:56:00 +01005583 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005584 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07005585
Eric Laurent59255e42011-07-27 19:49:51 -07005586 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07005587 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005588 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005589 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07005590 return INVALID_OPERATION;
5591 }
5592
Eric Laurent39e94f82010-07-28 01:32:47 -07005593 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07005594 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07005595 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07005596 // removed.
5597 srcThread->removeEffectChain_l(chain);
5598
5599 // transfer all effects one by one so that new effect chain is created on new thread with
5600 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005601 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07005602 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005603 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07005604 sp<EffectModule> effect = chain->getEffectFromId_l(0);
5605 while (effect != 0) {
5606 srcThread->removeEffect_l(effect);
5607 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07005608 // removeEffect_l() has stopped the effect if it was active so it must be restarted
5609 if (effect->state() == EffectModule::ACTIVE ||
5610 effect->state() == EffectModule::STOPPING) {
5611 effect->start();
5612 }
Eric Laurent39e94f82010-07-28 01:32:47 -07005613 // if the move request is not received from audio policy manager, the effect must be
5614 // re-registered with the new strategy and output
5615 if (dstChain == 0) {
5616 dstChain = effect->chain().promote();
5617 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005618 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07005619 srcThread->addEffect_l(effect);
5620 return NO_INIT;
5621 }
5622 strategy = dstChain->strategy();
5623 }
5624 if (reRegister) {
5625 AudioSystem::unregisterEffect(effect->id());
5626 AudioSystem::registerEffect(&effect->desc(),
5627 dstOutput,
5628 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07005629 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07005630 effect->id());
5631 }
Eric Laurentde070132010-07-13 04:45:46 -07005632 effect = chain->getEffectFromId_l(0);
5633 }
5634
5635 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005636}
5637
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005638
Mathias Agopian65ab4712010-07-14 17:59:35 -07005639// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005640sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07005641 const sp<AudioFlinger::Client>& client,
5642 const sp<IEffectClient>& effectClient,
5643 int32_t priority,
5644 int sessionId,
5645 effect_descriptor_t *desc,
5646 int *enabled,
5647 status_t *status
5648 )
5649{
5650 sp<EffectModule> effect;
5651 sp<EffectHandle> handle;
5652 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005653 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07005654 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005655 bool effectCreated = false;
5656 bool effectRegistered = false;
5657
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005658 lStatus = initCheck();
5659 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005660 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005661 goto Exit;
5662 }
5663
5664 // Do not allow effects with session ID 0 on direct output or duplicating threads
5665 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07005666 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005667 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07005668 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005669 lStatus = BAD_VALUE;
5670 goto Exit;
5671 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005672 // Only Pre processor effects are allowed on input threads and only on input threads
5673 if ((mType == RECORD &&
5674 (desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) ||
5675 (mType != RECORD &&
5676 (desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005677 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005678 desc->name, desc->flags, mType);
5679 lStatus = BAD_VALUE;
5680 goto Exit;
5681 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005682
Steve Block3856b092011-10-20 11:56:00 +01005683 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005684
5685 { // scope for mLock
5686 Mutex::Autolock _l(mLock);
5687
5688 // check for existing effect chain with the requested audio session
5689 chain = getEffectChain_l(sessionId);
5690 if (chain == 0) {
5691 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01005692 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005693 chain = new EffectChain(this, sessionId);
5694 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07005695 chain->setStrategy(getStrategyForSession_l(sessionId));
5696 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005697 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07005698 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005699 }
5700
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08005701 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005702
5703 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005704 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005705 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07005706 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005707 if (lStatus != NO_ERROR) {
5708 goto Exit;
5709 }
5710 effectRegistered = true;
5711 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07005712 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005713 lStatus = effect->status();
5714 if (lStatus != NO_ERROR) {
5715 goto Exit;
5716 }
Eric Laurentcab11242010-07-15 12:50:15 -07005717 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005718 if (lStatus != NO_ERROR) {
5719 goto Exit;
5720 }
5721 effectCreated = true;
5722
5723 effect->setDevice(mDevice);
5724 effect->setMode(mAudioFlinger->getMode());
5725 }
5726 // create effect handle and connect it to effect module
5727 handle = new EffectHandle(effect, client, effectClient, priority);
5728 lStatus = effect->addHandle(handle);
Glenn Kastena0d68332012-01-27 16:47:15 -08005729 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005730 *enabled = (int)effect->isEnabled();
5731 }
5732 }
5733
5734Exit:
5735 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07005736 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005737 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07005738 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005739 }
5740 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07005741 AudioSystem::unregisterEffect(effect->id());
5742 }
5743 if (chainCreated) {
5744 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005745 }
5746 handle.clear();
5747 }
5748
5749 if(status) {
5750 *status = lStatus;
5751 }
5752 return handle;
5753}
5754
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005755sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
5756{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005757 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08005758 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005759}
5760
Eric Laurentde070132010-07-13 04:45:46 -07005761// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5762// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005763status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07005764{
5765 // check for existing effect chain with the requested audio session
5766 int sessionId = effect->sessionId();
5767 sp<EffectChain> chain = getEffectChain_l(sessionId);
5768 bool chainCreated = false;
5769
5770 if (chain == 0) {
5771 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01005772 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07005773 chain = new EffectChain(this, sessionId);
5774 addEffectChain_l(chain);
5775 chain->setStrategy(getStrategyForSession_l(sessionId));
5776 chainCreated = true;
5777 }
Steve Block3856b092011-10-20 11:56:00 +01005778 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07005779
5780 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005781 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07005782 this, effect->desc().name, chain.get());
5783 return BAD_VALUE;
5784 }
5785
5786 status_t status = chain->addEffect_l(effect);
5787 if (status != NO_ERROR) {
5788 if (chainCreated) {
5789 removeEffectChain_l(chain);
5790 }
5791 return status;
5792 }
5793
5794 effect->setDevice(mDevice);
5795 effect->setMode(mAudioFlinger->getMode());
5796 return NO_ERROR;
5797}
5798
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005799void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07005800
Steve Block3856b092011-10-20 11:56:00 +01005801 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005802 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07005803 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5804 detachAuxEffect_l(effect->id());
5805 }
5806
5807 sp<EffectChain> chain = effect->chain().promote();
5808 if (chain != 0) {
5809 // remove effect chain if removing last effect
5810 if (chain->removeEffect_l(effect) == 0) {
5811 removeEffectChain_l(chain);
5812 }
5813 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005814 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07005815 }
5816}
5817
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005818void AudioFlinger::ThreadBase::lockEffectChains_l(
5819 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5820{
5821 effectChains = mEffectChains;
5822 for (size_t i = 0; i < mEffectChains.size(); i++) {
5823 mEffectChains[i]->lock();
5824 }
5825}
5826
5827void AudioFlinger::ThreadBase::unlockEffectChains(
5828 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5829{
5830 for (size_t i = 0; i < effectChains.size(); i++) {
5831 effectChains[i]->unlock();
5832 }
5833}
5834
5835sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
5836{
5837 Mutex::Autolock _l(mLock);
5838 return getEffectChain_l(sessionId);
5839}
5840
5841sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
5842{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005843 size_t size = mEffectChains.size();
5844 for (size_t i = 0; i < size; i++) {
5845 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08005846 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005847 }
5848 }
Glenn Kasten090f0192012-01-30 13:00:02 -08005849 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005850}
5851
Glenn Kastenf78aee72012-01-04 11:00:47 -08005852void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005853{
5854 Mutex::Autolock _l(mLock);
5855 size_t size = mEffectChains.size();
5856 for (size_t i = 0; i < size; i++) {
5857 mEffectChains[i]->setMode_l(mode);
5858 }
5859}
5860
5861void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005862 const wp<EffectHandle>& handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08005863 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07005864
Mathias Agopian65ab4712010-07-14 17:59:35 -07005865 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01005866 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005867 // delete the effect module if removing last handle on it
5868 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08005869 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005870 removeEffect_l(effect);
5871 AudioSystem::unregisterEffect(effect->id());
5872 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005873 }
5874}
5875
5876status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5877{
5878 int session = chain->sessionId();
5879 int16_t *buffer = mMixBuffer;
5880 bool ownsBuffer = false;
5881
Steve Block3856b092011-10-20 11:56:00 +01005882 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005883 if (session > 0) {
5884 // Only one effect chain can be present in direct output thread and it uses
5885 // the mix buffer as input
5886 if (mType != DIRECT) {
5887 size_t numSamples = mFrameCount * mChannelCount;
5888 buffer = new int16_t[numSamples];
5889 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01005890 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005891 ownsBuffer = true;
5892 }
5893
5894 // Attach all tracks with same session ID to this chain.
5895 for (size_t i = 0; i < mTracks.size(); ++i) {
5896 sp<Track> track = mTracks[i];
5897 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005898 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005899 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07005900 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005901 }
5902 }
5903
5904 // indicate all active tracks in the chain
5905 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5906 sp<Track> track = mActiveTracks[i].promote();
5907 if (track == 0) continue;
5908 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005909 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07005910 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005911 }
5912 }
5913 }
5914
5915 chain->setInBuffer(buffer, ownsBuffer);
5916 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07005917 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07005918 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005919 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
5920 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07005921 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07005922 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
5923 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07005924 // Effect chain for other sessions are inserted at beginning of effect
5925 // chains list to be processed before output mix effects. Relative order between other
5926 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07005927 size_t size = mEffectChains.size();
5928 size_t i = 0;
5929 for (i = 0; i < size; i++) {
5930 if (mEffectChains[i]->sessionId() < session) break;
5931 }
5932 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07005933 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005934
5935 return NO_ERROR;
5936}
5937
5938size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
5939{
5940 int session = chain->sessionId();
5941
Steve Block3856b092011-10-20 11:56:00 +01005942 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005943
5944 for (size_t i = 0; i < mEffectChains.size(); i++) {
5945 if (chain == mEffectChains[i]) {
5946 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07005947 // detach all active tracks from the chain
5948 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5949 sp<Track> track = mActiveTracks[i].promote();
5950 if (track == 0) continue;
5951 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005952 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07005953 chain.get(), session);
5954 chain->decActiveTrackCnt();
5955 }
5956 }
5957
Mathias Agopian65ab4712010-07-14 17:59:35 -07005958 // detach all tracks with same session ID from this chain
5959 for (size_t i = 0; i < mTracks.size(); ++i) {
5960 sp<Track> track = mTracks[i];
5961 if (session == track->sessionId()) {
5962 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07005963 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005964 }
5965 }
Eric Laurentde070132010-07-13 04:45:46 -07005966 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005967 }
5968 }
5969 return mEffectChains.size();
5970}
5971
Eric Laurentde070132010-07-13 04:45:46 -07005972status_t AudioFlinger::PlaybackThread::attachAuxEffect(
5973 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005974{
5975 Mutex::Autolock _l(mLock);
5976 return attachAuxEffect_l(track, EffectId);
5977}
5978
Eric Laurentde070132010-07-13 04:45:46 -07005979status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
5980 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005981{
5982 status_t status = NO_ERROR;
5983
5984 if (EffectId == 0) {
5985 track->setAuxBuffer(0, NULL);
5986 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07005987 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
5988 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005989 if (effect != 0) {
5990 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5991 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
5992 } else {
5993 status = INVALID_OPERATION;
5994 }
5995 } else {
5996 status = BAD_VALUE;
5997 }
5998 }
5999 return status;
6000}
6001
6002void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6003{
6004 for (size_t i = 0; i < mTracks.size(); ++i) {
6005 sp<Track> track = mTracks[i];
6006 if (track->auxEffectId() == effectId) {
6007 attachAuxEffect_l(track, 0);
6008 }
6009 }
6010}
6011
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006012status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6013{
6014 // only one chain per input thread
6015 if (mEffectChains.size() != 0) {
6016 return INVALID_OPERATION;
6017 }
Steve Block3856b092011-10-20 11:56:00 +01006018 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006019
6020 chain->setInBuffer(NULL);
6021 chain->setOutBuffer(NULL);
6022
Eric Laurent59255e42011-07-27 19:49:51 -07006023 checkSuspendOnAddEffectChain_l(chain);
6024
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006025 mEffectChains.add(chain);
6026
6027 return NO_ERROR;
6028}
6029
6030size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6031{
Steve Block3856b092011-10-20 11:56:00 +01006032 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00006033 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006034 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6035 chain.get(), mEffectChains.size(), this);
6036 if (mEffectChains.size() == 1) {
6037 mEffectChains.removeAt(0);
6038 }
6039 return 0;
6040}
6041
Mathias Agopian65ab4712010-07-14 17:59:35 -07006042// ----------------------------------------------------------------------------
6043// EffectModule implementation
6044// ----------------------------------------------------------------------------
6045
6046#undef LOG_TAG
6047#define LOG_TAG "AudioFlinger::EffectModule"
6048
6049AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
6050 const wp<AudioFlinger::EffectChain>& chain,
6051 effect_descriptor_t *desc,
6052 int id,
6053 int sessionId)
6054 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006055 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006056{
Steve Block3856b092011-10-20 11:56:00 +01006057 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006058 int lStatus;
6059 sp<ThreadBase> thread = mThread.promote();
6060 if (thread == 0) {
6061 return;
6062 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006063
6064 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6065
6066 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006067 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006068
6069 if (mStatus != NO_ERROR) {
6070 return;
6071 }
6072 lStatus = init();
6073 if (lStatus < 0) {
6074 mStatus = lStatus;
6075 goto Error;
6076 }
6077
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006078 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6079 mPinned = true;
6080 }
Steve Block3856b092011-10-20 11:56:00 +01006081 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006082 return;
6083Error:
6084 EffectRelease(mEffectInterface);
6085 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01006086 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006087}
6088
6089AudioFlinger::EffectModule::~EffectModule()
6090{
Steve Block3856b092011-10-20 11:56:00 +01006091 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006092 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006093 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6094 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6095 sp<ThreadBase> thread = mThread.promote();
6096 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006097 audio_stream_t *stream = thread->stream();
6098 if (stream != NULL) {
6099 stream->remove_audio_effect(stream, mEffectInterface);
6100 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006101 }
6102 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006103 // release effect engine
6104 EffectRelease(mEffectInterface);
6105 }
6106}
6107
Glenn Kasten435dbe62012-01-30 10:15:48 -08006108status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006109{
6110 status_t status;
6111
6112 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006113 int priority = handle->priority();
6114 size_t size = mHandles.size();
6115 sp<EffectHandle> h;
6116 size_t i;
6117 for (i = 0; i < size; i++) {
6118 h = mHandles[i].promote();
6119 if (h == 0) continue;
6120 if (h->priority() <= priority) break;
6121 }
6122 // if inserted in first place, move effect control from previous owner to this handle
6123 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006124 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006125 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006126 enabled = h->enabled();
6127 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006128 }
Eric Laurent59255e42011-07-27 19:49:51 -07006129 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006130 status = NO_ERROR;
6131 } else {
6132 status = ALREADY_EXISTS;
6133 }
Steve Block3856b092011-10-20 11:56:00 +01006134 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006135 mHandles.insertAt(handle, i);
6136 return status;
6137}
6138
6139size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6140{
6141 Mutex::Autolock _l(mLock);
6142 size_t size = mHandles.size();
6143 size_t i;
6144 for (i = 0; i < size; i++) {
6145 if (mHandles[i] == handle) break;
6146 }
6147 if (i == size) {
6148 return size;
6149 }
Steve Block3856b092011-10-20 11:56:00 +01006150 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07006151
6152 bool enabled = false;
6153 EffectHandle *hdl = handle.unsafe_get();
Glenn Kastena0d68332012-01-27 16:47:15 -08006154 if (hdl != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01006155 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07006156 enabled = hdl->enabled();
6157 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006158 mHandles.removeAt(i);
6159 size = mHandles.size();
6160 // if removed from first place, move effect control from this handle to next in line
6161 if (i == 0 && size != 0) {
6162 sp<EffectHandle> h = mHandles[0].promote();
6163 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006164 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006165 }
6166 }
6167
Eric Laurentec437d82011-07-26 20:54:46 -07006168 // Prevent calls to process() and other functions on effect interface from now on.
6169 // The effect engine will be released by the destructor when the last strong reference on
6170 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006171 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07006172 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07006173 }
6174
Mathias Agopian65ab4712010-07-14 17:59:35 -07006175 return size;
6176}
6177
Eric Laurent59255e42011-07-27 19:49:51 -07006178sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6179{
6180 Mutex::Autolock _l(mLock);
Glenn Kasten090f0192012-01-30 13:00:02 -08006181 return mHandles.size() != 0 ? mHandles[0].promote() : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07006182}
6183
Glenn Kasten58123c32012-02-03 10:32:24 -08006184void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006185{
Glenn Kasten90bebef2012-01-27 15:24:38 -08006186 ALOGV("disconnect() %p handle %p", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006187 // keep a strong reference on this EffectModule to avoid calling the
6188 // destructor before we exit
6189 sp<EffectModule> keep(this);
6190 {
6191 sp<ThreadBase> thread = mThread.promote();
6192 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08006193 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006194 }
6195 }
6196}
6197
6198void AudioFlinger::EffectModule::updateState() {
6199 Mutex::Autolock _l(mLock);
6200
6201 switch (mState) {
6202 case RESTART:
6203 reset_l();
6204 // FALL THROUGH
6205
6206 case STARTING:
6207 // clear auxiliary effect input buffer for next accumulation
6208 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6209 memset(mConfig.inputCfg.buffer.raw,
6210 0,
6211 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6212 }
6213 start_l();
6214 mState = ACTIVE;
6215 break;
6216 case STOPPING:
6217 stop_l();
6218 mDisableWaitCnt = mMaxDisableWaitCnt;
6219 mState = STOPPED;
6220 break;
6221 case STOPPED:
6222 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6223 // turn off sequence.
6224 if (--mDisableWaitCnt == 0) {
6225 reset_l();
6226 mState = IDLE;
6227 }
6228 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006229 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07006230 break;
6231 }
6232}
6233
6234void AudioFlinger::EffectModule::process()
6235{
6236 Mutex::Autolock _l(mLock);
6237
Eric Laurentec437d82011-07-26 20:54:46 -07006238 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006239 mConfig.inputCfg.buffer.raw == NULL ||
6240 mConfig.outputCfg.buffer.raw == NULL) {
6241 return;
6242 }
6243
Eric Laurent8f45bd72010-08-31 13:50:07 -07006244 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006245 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6246 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006247 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006248 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07006249 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006250 }
6251
6252 // do the actual processing in the effect engine
6253 int ret = (*mEffectInterface)->process(mEffectInterface,
6254 &mConfig.inputCfg.buffer,
6255 &mConfig.outputCfg.buffer);
6256
6257 // force transition to IDLE state when engine is ready
6258 if (mState == STOPPED && ret == -ENODATA) {
6259 mDisableWaitCnt = 1;
6260 }
6261
6262 // clear auxiliary effect input buffer for next accumulation
6263 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08006264 memset(mConfig.inputCfg.buffer.raw, 0,
6265 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006266 }
6267 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08006268 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6269 // If an insert effect is idle and input buffer is different from output buffer,
6270 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07006271 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07006272 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08006273 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6274 int16_t *in = mConfig.inputCfg.buffer.s16;
6275 int16_t *out = mConfig.outputCfg.buffer.s16;
6276 for (size_t i = 0; i < frameCnt; i++) {
6277 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006278 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006279 }
6280 }
6281}
6282
6283void AudioFlinger::EffectModule::reset_l()
6284{
6285 if (mEffectInterface == NULL) {
6286 return;
6287 }
6288 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6289}
6290
6291status_t AudioFlinger::EffectModule::configure()
6292{
6293 uint32_t channels;
6294 if (mEffectInterface == NULL) {
6295 return NO_INIT;
6296 }
6297
6298 sp<ThreadBase> thread = mThread.promote();
6299 if (thread == 0) {
6300 return DEAD_OBJECT;
6301 }
6302
6303 // TODO: handle configuration of effects replacing track process
6304 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006305 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006306 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07006307 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006308 }
6309
6310 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006311 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006312 } else {
6313 mConfig.inputCfg.channels = channels;
6314 }
6315 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07006316 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6317 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006318 mConfig.inputCfg.samplingRate = thread->sampleRate();
6319 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6320 mConfig.inputCfg.bufferProvider.cookie = NULL;
6321 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6322 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6323 mConfig.outputCfg.bufferProvider.cookie = NULL;
6324 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6325 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6326 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6327 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07006328 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07006329 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07006330 // - in other sessions:
6331 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6332 // other effect: overwrites output buffer: input buffer == output buffer
6333 // Auxiliary effect:
6334 // accumulates in output buffer: input buffer != output buffer
6335 // Therefore: accumulate <=> input buffer != output buffer
6336 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6337 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6338 } else {
6339 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6340 }
6341 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6342 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6343 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6344 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6345
Steve Block3856b092011-10-20 11:56:00 +01006346 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07006347 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6348
Mathias Agopian65ab4712010-07-14 17:59:35 -07006349 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006350 uint32_t size = sizeof(int);
6351 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08006352 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07006353 sizeof(effect_config_t),
6354 &mConfig,
6355 &size,
6356 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006357 if (status == 0) {
6358 status = cmdStatus;
6359 }
6360
6361 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6362 (1000 * mConfig.outputCfg.buffer.frameCount);
6363
6364 return status;
6365}
6366
6367status_t AudioFlinger::EffectModule::init()
6368{
6369 Mutex::Autolock _l(mLock);
6370 if (mEffectInterface == NULL) {
6371 return NO_INIT;
6372 }
6373 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006374 uint32_t size = sizeof(status_t);
6375 status_t status = (*mEffectInterface)->command(mEffectInterface,
6376 EFFECT_CMD_INIT,
6377 0,
6378 NULL,
6379 &size,
6380 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006381 if (status == 0) {
6382 status = cmdStatus;
6383 }
6384 return status;
6385}
6386
Eric Laurentec35a142011-10-05 17:42:25 -07006387status_t AudioFlinger::EffectModule::start()
6388{
6389 Mutex::Autolock _l(mLock);
6390 return start_l();
6391}
6392
Mathias Agopian65ab4712010-07-14 17:59:35 -07006393status_t AudioFlinger::EffectModule::start_l()
6394{
6395 if (mEffectInterface == NULL) {
6396 return NO_INIT;
6397 }
6398 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006399 uint32_t size = sizeof(status_t);
6400 status_t status = (*mEffectInterface)->command(mEffectInterface,
6401 EFFECT_CMD_ENABLE,
6402 0,
6403 NULL,
6404 &size,
6405 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006406 if (status == 0) {
6407 status = cmdStatus;
6408 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006409 if (status == 0 &&
6410 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6411 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6412 sp<ThreadBase> thread = mThread.promote();
6413 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006414 audio_stream_t *stream = thread->stream();
6415 if (stream != NULL) {
6416 stream->add_audio_effect(stream, mEffectInterface);
6417 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006418 }
6419 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006420 return status;
6421}
6422
Eric Laurentec437d82011-07-26 20:54:46 -07006423status_t AudioFlinger::EffectModule::stop()
6424{
6425 Mutex::Autolock _l(mLock);
6426 return stop_l();
6427}
6428
Mathias Agopian65ab4712010-07-14 17:59:35 -07006429status_t AudioFlinger::EffectModule::stop_l()
6430{
6431 if (mEffectInterface == NULL) {
6432 return NO_INIT;
6433 }
6434 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006435 uint32_t size = sizeof(status_t);
6436 status_t status = (*mEffectInterface)->command(mEffectInterface,
6437 EFFECT_CMD_DISABLE,
6438 0,
6439 NULL,
6440 &size,
6441 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006442 if (status == 0) {
6443 status = cmdStatus;
6444 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006445 if (status == 0 &&
6446 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6447 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6448 sp<ThreadBase> thread = mThread.promote();
6449 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006450 audio_stream_t *stream = thread->stream();
6451 if (stream != NULL) {
6452 stream->remove_audio_effect(stream, mEffectInterface);
6453 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006454 }
6455 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006456 return status;
6457}
6458
Eric Laurent25f43952010-07-28 05:40:18 -07006459status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6460 uint32_t cmdSize,
6461 void *pCmdData,
6462 uint32_t *replySize,
6463 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006464{
6465 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006466// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006467
Eric Laurentec437d82011-07-26 20:54:46 -07006468 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006469 return NO_INIT;
6470 }
Eric Laurent25f43952010-07-28 05:40:18 -07006471 status_t status = (*mEffectInterface)->command(mEffectInterface,
6472 cmdCode,
6473 cmdSize,
6474 pCmdData,
6475 replySize,
6476 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006477 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07006478 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006479 for (size_t i = 1; i < mHandles.size(); i++) {
6480 sp<EffectHandle> h = mHandles[i].promote();
6481 if (h != 0) {
6482 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
6483 }
6484 }
6485 }
6486 return status;
6487}
6488
6489status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
6490{
Eric Laurentdb7c0792011-08-10 10:37:50 -07006491
Mathias Agopian65ab4712010-07-14 17:59:35 -07006492 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006493 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006494
6495 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006496 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
6497 if (enabled && status != NO_ERROR) {
6498 return status;
6499 }
6500
Mathias Agopian65ab4712010-07-14 17:59:35 -07006501 switch (mState) {
6502 // going from disabled to enabled
6503 case IDLE:
6504 mState = STARTING;
6505 break;
6506 case STOPPED:
6507 mState = RESTART;
6508 break;
6509 case STOPPING:
6510 mState = ACTIVE;
6511 break;
6512
6513 // going from enabled to disabled
6514 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006515 mState = STOPPED;
6516 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006517 case STARTING:
6518 mState = IDLE;
6519 break;
6520 case ACTIVE:
6521 mState = STOPPING;
6522 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006523 case DESTROYED:
6524 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006525 }
6526 for (size_t i = 1; i < mHandles.size(); i++) {
6527 sp<EffectHandle> h = mHandles[i].promote();
6528 if (h != 0) {
6529 h->setEnabled(enabled);
6530 }
6531 }
6532 }
6533 return NO_ERROR;
6534}
6535
Glenn Kastenc59c0042012-02-02 14:06:11 -08006536bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006537{
6538 switch (mState) {
6539 case RESTART:
6540 case STARTING:
6541 case ACTIVE:
6542 return true;
6543 case IDLE:
6544 case STOPPING:
6545 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07006546 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07006547 default:
6548 return false;
6549 }
6550}
6551
Glenn Kastenc59c0042012-02-02 14:06:11 -08006552bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07006553{
6554 switch (mState) {
6555 case RESTART:
6556 case ACTIVE:
6557 case STOPPING:
6558 case STOPPED:
6559 return true;
6560 case IDLE:
6561 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07006562 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006563 default:
6564 return false;
6565 }
6566}
6567
Mathias Agopian65ab4712010-07-14 17:59:35 -07006568status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
6569{
6570 Mutex::Autolock _l(mLock);
6571 status_t status = NO_ERROR;
6572
6573 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
6574 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07006575 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07006576 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
6577 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006578 status_t cmdStatus;
6579 uint32_t volume[2];
6580 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07006581 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006582 volume[0] = *left;
6583 volume[1] = *right;
6584 if (controller) {
6585 pVolume = volume;
6586 }
Eric Laurent25f43952010-07-28 05:40:18 -07006587 status = (*mEffectInterface)->command(mEffectInterface,
6588 EFFECT_CMD_SET_VOLUME,
6589 size,
6590 volume,
6591 &size,
6592 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006593 if (controller && status == NO_ERROR && size == sizeof(volume)) {
6594 *left = volume[0];
6595 *right = volume[1];
6596 }
6597 }
6598 return status;
6599}
6600
6601status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
6602{
6603 Mutex::Autolock _l(mLock);
6604 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006605 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
6606 // audio pre processing modules on RecordThread can receive both output and
6607 // input device indication in the same call
6608 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
6609 if (dev) {
6610 status_t cmdStatus;
6611 uint32_t size = sizeof(status_t);
6612
6613 status = (*mEffectInterface)->command(mEffectInterface,
6614 EFFECT_CMD_SET_DEVICE,
6615 sizeof(uint32_t),
6616 &dev,
6617 &size,
6618 &cmdStatus);
6619 if (status == NO_ERROR) {
6620 status = cmdStatus;
6621 }
6622 }
6623 dev = device & AUDIO_DEVICE_IN_ALL;
6624 if (dev) {
6625 status_t cmdStatus;
6626 uint32_t size = sizeof(status_t);
6627
6628 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
6629 EFFECT_CMD_SET_INPUT_DEVICE,
6630 sizeof(uint32_t),
6631 &dev,
6632 &size,
6633 &cmdStatus);
6634 if (status2 == NO_ERROR) {
6635 status2 = cmdStatus;
6636 }
6637 if (status == NO_ERROR) {
6638 status = status2;
6639 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006640 }
6641 }
6642 return status;
6643}
6644
Glenn Kastenf78aee72012-01-04 11:00:47 -08006645status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006646{
6647 Mutex::Autolock _l(mLock);
6648 status_t status = NO_ERROR;
6649 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006650 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006651 uint32_t size = sizeof(status_t);
6652 status = (*mEffectInterface)->command(mEffectInterface,
6653 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08006654 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07006655 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07006656 &size,
6657 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006658 if (status == NO_ERROR) {
6659 status = cmdStatus;
6660 }
6661 }
6662 return status;
6663}
6664
Eric Laurent59255e42011-07-27 19:49:51 -07006665void AudioFlinger::EffectModule::setSuspended(bool suspended)
6666{
6667 Mutex::Autolock _l(mLock);
6668 mSuspended = suspended;
6669}
Glenn Kastena3a85482012-01-04 11:01:11 -08006670
6671bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07006672{
6673 Mutex::Autolock _l(mLock);
6674 return mSuspended;
6675}
6676
Mathias Agopian65ab4712010-07-14 17:59:35 -07006677status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
6678{
6679 const size_t SIZE = 256;
6680 char buffer[SIZE];
6681 String8 result;
6682
6683 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
6684 result.append(buffer);
6685
6686 bool locked = tryLock(mLock);
6687 // failed to lock - AudioFlinger is probably deadlocked
6688 if (!locked) {
6689 result.append("\t\tCould not lock Fx mutex:\n");
6690 }
6691
6692 result.append("\t\tSession Status State Engine:\n");
6693 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
6694 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
6695 result.append(buffer);
6696
6697 result.append("\t\tDescriptor:\n");
6698 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6699 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
6700 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
6701 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
6702 result.append(buffer);
6703 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6704 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
6705 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
6706 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
6707 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07006708 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07006709 mDescriptor.apiVersion,
6710 mDescriptor.flags);
6711 result.append(buffer);
6712 snprintf(buffer, SIZE, "\t\t- name: %s\n",
6713 mDescriptor.name);
6714 result.append(buffer);
6715 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
6716 mDescriptor.implementor);
6717 result.append(buffer);
6718
6719 result.append("\t\t- Input configuration:\n");
6720 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6721 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6722 (uint32_t)mConfig.inputCfg.buffer.raw,
6723 mConfig.inputCfg.buffer.frameCount,
6724 mConfig.inputCfg.samplingRate,
6725 mConfig.inputCfg.channels,
6726 mConfig.inputCfg.format);
6727 result.append(buffer);
6728
6729 result.append("\t\t- Output configuration:\n");
6730 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6731 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6732 (uint32_t)mConfig.outputCfg.buffer.raw,
6733 mConfig.outputCfg.buffer.frameCount,
6734 mConfig.outputCfg.samplingRate,
6735 mConfig.outputCfg.channels,
6736 mConfig.outputCfg.format);
6737 result.append(buffer);
6738
6739 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
6740 result.append(buffer);
6741 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
6742 for (size_t i = 0; i < mHandles.size(); ++i) {
6743 sp<EffectHandle> handle = mHandles[i].promote();
6744 if (handle != 0) {
6745 handle->dump(buffer, SIZE);
6746 result.append(buffer);
6747 }
6748 }
6749
6750 result.append("\n");
6751
6752 write(fd, result.string(), result.length());
6753
6754 if (locked) {
6755 mLock.unlock();
6756 }
6757
6758 return NO_ERROR;
6759}
6760
6761// ----------------------------------------------------------------------------
6762// EffectHandle implementation
6763// ----------------------------------------------------------------------------
6764
6765#undef LOG_TAG
6766#define LOG_TAG "AudioFlinger::EffectHandle"
6767
6768AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
6769 const sp<AudioFlinger::Client>& client,
6770 const sp<IEffectClient>& effectClient,
6771 int32_t priority)
6772 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006773 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006774 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006775{
Steve Block3856b092011-10-20 11:56:00 +01006776 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006777
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006778 if (client == 0) {
6779 return;
6780 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006781 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
6782 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
6783 if (mCblkMemory != 0) {
6784 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
6785
Glenn Kastena0d68332012-01-27 16:47:15 -08006786 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006787 new(mCblk) effect_param_cblk_t();
6788 mBuffer = (uint8_t *)mCblk + bufOffset;
6789 }
6790 } else {
Steve Block29357bc2012-01-06 19:20:56 +00006791 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006792 return;
6793 }
6794}
6795
6796AudioFlinger::EffectHandle::~EffectHandle()
6797{
Steve Block3856b092011-10-20 11:56:00 +01006798 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006799 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01006800 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006801}
6802
6803status_t AudioFlinger::EffectHandle::enable()
6804{
Steve Block3856b092011-10-20 11:56:00 +01006805 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006806 if (!mHasControl) return INVALID_OPERATION;
6807 if (mEffect == 0) return DEAD_OBJECT;
6808
Eric Laurentdb7c0792011-08-10 10:37:50 -07006809 if (mEnabled) {
6810 return NO_ERROR;
6811 }
6812
Eric Laurent59255e42011-07-27 19:49:51 -07006813 mEnabled = true;
6814
6815 sp<ThreadBase> thread = mEffect->thread().promote();
6816 if (thread != 0) {
6817 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
6818 }
6819
6820 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
6821 if (mEffect->suspended()) {
6822 return NO_ERROR;
6823 }
6824
Eric Laurentdb7c0792011-08-10 10:37:50 -07006825 status_t status = mEffect->setEnabled(true);
6826 if (status != NO_ERROR) {
6827 if (thread != 0) {
6828 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6829 }
6830 mEnabled = false;
6831 }
6832 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006833}
6834
6835status_t AudioFlinger::EffectHandle::disable()
6836{
Steve Block3856b092011-10-20 11:56:00 +01006837 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006838 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07006839 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006840
Eric Laurentdb7c0792011-08-10 10:37:50 -07006841 if (!mEnabled) {
6842 return NO_ERROR;
6843 }
Eric Laurent59255e42011-07-27 19:49:51 -07006844 mEnabled = false;
6845
6846 if (mEffect->suspended()) {
6847 return NO_ERROR;
6848 }
6849
6850 status_t status = mEffect->setEnabled(false);
6851
6852 sp<ThreadBase> thread = mEffect->thread().promote();
6853 if (thread != 0) {
6854 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6855 }
6856
6857 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006858}
6859
6860void AudioFlinger::EffectHandle::disconnect()
6861{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006862 disconnect(true);
6863}
6864
Glenn Kasten58123c32012-02-03 10:32:24 -08006865void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006866{
Glenn Kasten58123c32012-02-03 10:32:24 -08006867 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006868 if (mEffect == 0) {
6869 return;
6870 }
Glenn Kasten58123c32012-02-03 10:32:24 -08006871 mEffect->disconnect(this, unpinIfLast);
Eric Laurent59255e42011-07-27 19:49:51 -07006872
Eric Laurenta85a74a2011-10-19 11:44:54 -07006873 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006874 sp<ThreadBase> thread = mEffect->thread().promote();
6875 if (thread != 0) {
6876 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6877 }
Eric Laurent59255e42011-07-27 19:49:51 -07006878 }
6879
Mathias Agopian65ab4712010-07-14 17:59:35 -07006880 // release sp on module => module destructor can be called now
6881 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006882 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08006883 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08006884 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006885 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
6886 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08006887 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08006888 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07006889 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
6890 mClient.clear();
6891 }
6892}
6893
Eric Laurent25f43952010-07-28 05:40:18 -07006894status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
6895 uint32_t cmdSize,
6896 void *pCmdData,
6897 uint32_t *replySize,
6898 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006899{
Steve Block3856b092011-10-20 11:56:00 +01006900// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07006901// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006902
6903 // only get parameter command is permitted for applications not controlling the effect
6904 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
6905 return INVALID_OPERATION;
6906 }
6907 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006908 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006909
6910 // handle commands that are not forwarded transparently to effect engine
6911 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
6912 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
6913 // no risk to block the whole media server process or mixer threads is we are stuck here
6914 Mutex::Autolock _l(mCblk->lock);
6915 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
6916 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
6917 mCblk->serverIndex = 0;
6918 mCblk->clientIndex = 0;
6919 return BAD_VALUE;
6920 }
6921 status_t status = NO_ERROR;
6922 while (mCblk->serverIndex < mCblk->clientIndex) {
6923 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07006924 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006925 int *p = (int *)(mBuffer + mCblk->serverIndex);
6926 int size = *p++;
6927 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006928 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006929 break;
6930 }
6931 effect_param_t *param = (effect_param_t *)p;
6932 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006933 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006934 mCblk->serverIndex += size;
6935 continue;
6936 }
Eric Laurent25f43952010-07-28 05:40:18 -07006937 uint32_t psize = sizeof(effect_param_t) +
6938 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
6939 param->vsize;
6940 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
6941 psize,
6942 p,
6943 &rsize,
6944 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07006945 // stop at first error encountered
6946 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006947 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07006948 *(int *)pReplyData = reply;
6949 break;
6950 } else if (reply != NO_ERROR) {
6951 *(int *)pReplyData = reply;
6952 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006953 }
6954 mCblk->serverIndex += size;
6955 }
6956 mCblk->serverIndex = 0;
6957 mCblk->clientIndex = 0;
6958 return status;
6959 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07006960 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006961 return enable();
6962 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07006963 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006964 return disable();
6965 }
6966
6967 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
6968}
6969
Eric Laurent59255e42011-07-27 19:49:51 -07006970void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006971{
Steve Block3856b092011-10-20 11:56:00 +01006972 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006973
6974 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07006975 mEnabled = enabled;
6976
Mathias Agopian65ab4712010-07-14 17:59:35 -07006977 if (signal && mEffectClient != 0) {
6978 mEffectClient->controlStatusChanged(hasControl);
6979 }
6980}
6981
Eric Laurent25f43952010-07-28 05:40:18 -07006982void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
6983 uint32_t cmdSize,
6984 void *pCmdData,
6985 uint32_t replySize,
6986 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006987{
6988 if (mEffectClient != 0) {
6989 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
6990 }
6991}
6992
6993
6994
6995void AudioFlinger::EffectHandle::setEnabled(bool enabled)
6996{
6997 if (mEffectClient != 0) {
6998 mEffectClient->enableStatusChanged(enabled);
6999 }
7000}
7001
7002status_t AudioFlinger::EffectHandle::onTransact(
7003 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7004{
7005 return BnEffect::onTransact(code, data, reply, flags);
7006}
7007
7008
7009void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7010{
Glenn Kastena0d68332012-01-27 16:47:15 -08007011 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007012
7013 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08007014 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07007015 mPriority,
7016 mHasControl,
7017 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007018 mCblk ? mCblk->clientIndex : 0,
7019 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07007020 );
7021
7022 if (locked) {
7023 mCblk->lock.unlock();
7024 }
7025}
7026
7027#undef LOG_TAG
7028#define LOG_TAG "AudioFlinger::EffectChain"
7029
7030AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
7031 int sessionId)
Eric Laurent544fe9b2011-11-11 15:42:52 -08007032 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07007033 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7034 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007035{
Dima Zavinfce7a472011-04-19 22:30:36 -07007036 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007037 sp<ThreadBase> thread = mThread.promote();
7038 if (thread == 0) {
7039 return;
7040 }
7041 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7042 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007043}
7044
7045AudioFlinger::EffectChain::~EffectChain()
7046{
7047 if (mOwnInBuffer) {
7048 delete mInBuffer;
7049 }
7050
7051}
7052
Eric Laurent59255e42011-07-27 19:49:51 -07007053// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007054sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007055{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007056 size_t size = mEffects.size();
7057
7058 for (size_t i = 0; i < size; i++) {
7059 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007060 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07007061 }
7062 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007063 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007064}
7065
Eric Laurent59255e42011-07-27 19:49:51 -07007066// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007067sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007068{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007069 size_t size = mEffects.size();
7070
7071 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07007072 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7073 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007074 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07007075 }
7076 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007077 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007078}
7079
Eric Laurent59255e42011-07-27 19:49:51 -07007080// getEffectFromType_l() must be called with ThreadBase::mLock held
7081sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7082 const effect_uuid_t *type)
7083{
Eric Laurent59255e42011-07-27 19:49:51 -07007084 size_t size = mEffects.size();
7085
7086 for (size_t i = 0; i < size; i++) {
7087 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007088 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07007089 }
7090 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007091 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07007092}
7093
Mathias Agopian65ab4712010-07-14 17:59:35 -07007094// Must be called with EffectChain::mLock locked
7095void AudioFlinger::EffectChain::process_l()
7096{
Eric Laurentdac69112010-09-28 14:09:57 -07007097 sp<ThreadBase> thread = mThread.promote();
7098 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007099 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07007100 return;
7101 }
Dima Zavinfce7a472011-04-19 22:30:36 -07007102 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7103 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007104 // always process effects unless no more tracks are on the session and the effect tail
7105 // has been rendered
7106 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07007107 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007108 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07007109
Eric Laurent544fe9b2011-11-11 15:42:52 -08007110 if (!tracksOnSession && mTailBufferCount == 0) {
7111 doProcess = false;
7112 }
7113
7114 if (activeTrackCnt() == 0) {
7115 // if no track is active and the effect tail has not been rendered,
7116 // the input buffer must be cleared here as the mixer process will not do it
7117 if (tracksOnSession || mTailBufferCount > 0) {
7118 size_t numSamples = thread->frameCount() * thread->channelCount();
7119 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7120 if (mTailBufferCount > 0) {
7121 mTailBufferCount--;
7122 }
7123 }
7124 }
Eric Laurentdac69112010-09-28 14:09:57 -07007125 }
7126
Mathias Agopian65ab4712010-07-14 17:59:35 -07007127 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08007128 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07007129 for (size_t i = 0; i < size; i++) {
7130 mEffects[i]->process();
7131 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007132 }
7133 for (size_t i = 0; i < size; i++) {
7134 mEffects[i]->updateState();
7135 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007136}
7137
Eric Laurentcab11242010-07-15 12:50:15 -07007138// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07007139status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007140{
7141 effect_descriptor_t desc = effect->desc();
7142 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7143
7144 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07007145 effect->setChain(this);
7146 sp<ThreadBase> thread = mThread.promote();
7147 if (thread == 0) {
7148 return NO_INIT;
7149 }
7150 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007151
7152 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7153 // Auxiliary effects are inserted at the beginning of mEffects vector as
7154 // they are processed first and accumulated in chain input buffer
7155 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07007156
Mathias Agopian65ab4712010-07-14 17:59:35 -07007157 // the input buffer for auxiliary effect contains mono samples in
7158 // 32 bit format. This is to avoid saturation in AudoMixer
7159 // accumulation stage. Saturation is done in EffectModule::process() before
7160 // calling the process in effect engine
7161 size_t numSamples = thread->frameCount();
7162 int32_t *buffer = new int32_t[numSamples];
7163 memset(buffer, 0, numSamples * sizeof(int32_t));
7164 effect->setInBuffer((int16_t *)buffer);
7165 // auxiliary effects output samples to chain input buffer for further processing
7166 // by insert effects
7167 effect->setOutBuffer(mInBuffer);
7168 } else {
7169 // Insert effects are inserted at the end of mEffects vector as they are processed
7170 // after track and auxiliary effects.
7171 // Insert effect order as a function of indicated preference:
7172 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7173 // another effect is present
7174 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7175 // last effect claiming first position
7176 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7177 // first effect claiming last position
7178 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
7179 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7180 // already present
7181
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007182 size_t size = mEffects.size();
7183 size_t idx_insert = size;
7184 ssize_t idx_insert_first = -1;
7185 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007186
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007187 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007188 effect_descriptor_t d = mEffects[i]->desc();
7189 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7190 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7191 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7192 // check invalid effect chaining combinations
7193 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
7194 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007195 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007196 return INVALID_OPERATION;
7197 }
7198 // remember position of first insert effect and by default
7199 // select this as insert position for new effect
7200 if (idx_insert == size) {
7201 idx_insert = i;
7202 }
7203 // remember position of last insert effect claiming
7204 // first position
7205 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7206 idx_insert_first = i;
7207 }
7208 // remember position of first insert effect claiming
7209 // last position
7210 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7211 idx_insert_last == -1) {
7212 idx_insert_last = i;
7213 }
7214 }
7215 }
7216
7217 // modify idx_insert from first position if needed
7218 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7219 if (idx_insert_last != -1) {
7220 idx_insert = idx_insert_last;
7221 } else {
7222 idx_insert = size;
7223 }
7224 } else {
7225 if (idx_insert_first != -1) {
7226 idx_insert = idx_insert_first + 1;
7227 }
7228 }
7229
7230 // always read samples from chain input buffer
7231 effect->setInBuffer(mInBuffer);
7232
7233 // if last effect in the chain, output samples to chain
7234 // output buffer, otherwise to chain input buffer
7235 if (idx_insert == size) {
7236 if (idx_insert != 0) {
7237 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7238 mEffects[idx_insert-1]->configure();
7239 }
7240 effect->setOutBuffer(mOutBuffer);
7241 } else {
7242 effect->setOutBuffer(mInBuffer);
7243 }
7244 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007245
Steve Block3856b092011-10-20 11:56:00 +01007246 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007247 }
7248 effect->configure();
7249 return NO_ERROR;
7250}
7251
Eric Laurentcab11242010-07-15 12:50:15 -07007252// removeEffect_l() must be called with PlaybackThread::mLock held
7253size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007254{
7255 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007256 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007257 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7258
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007259 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007260 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07007261 // calling stop here will remove pre-processing effect from the audio HAL.
7262 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7263 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07007264 if (mEffects[i]->state() == EffectModule::ACTIVE ||
7265 mEffects[i]->state() == EffectModule::STOPPING) {
7266 mEffects[i]->stop();
7267 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007268 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7269 delete[] effect->inBuffer();
7270 } else {
7271 if (i == size - 1 && i != 0) {
7272 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7273 mEffects[i - 1]->configure();
7274 }
7275 }
7276 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01007277 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007278 break;
7279 }
7280 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007281
7282 return mEffects.size();
7283}
7284
Eric Laurentcab11242010-07-15 12:50:15 -07007285// setDevice_l() must be called with PlaybackThread::mLock held
7286void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007287{
7288 size_t size = mEffects.size();
7289 for (size_t i = 0; i < size; i++) {
7290 mEffects[i]->setDevice(device);
7291 }
7292}
7293
Eric Laurentcab11242010-07-15 12:50:15 -07007294// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08007295void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007296{
7297 size_t size = mEffects.size();
7298 for (size_t i = 0; i < size; i++) {
7299 mEffects[i]->setMode(mode);
7300 }
7301}
7302
Eric Laurentcab11242010-07-15 12:50:15 -07007303// setVolume_l() must be called with PlaybackThread::mLock held
7304bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007305{
7306 uint32_t newLeft = *left;
7307 uint32_t newRight = *right;
7308 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07007309 int ctrlIdx = -1;
7310 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007311
Eric Laurentcab11242010-07-15 12:50:15 -07007312 // first update volume controller
7313 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07007314 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07007315 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7316 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07007317 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07007318 break;
7319 }
7320 }
7321
7322 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07007323 if (hasControl) {
7324 *left = mNewLeftVolume;
7325 *right = mNewRightVolume;
7326 }
7327 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07007328 }
7329
7330 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07007331 mLeftVolume = newLeft;
7332 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007333
7334 // second get volume update from volume controller
7335 if (ctrlIdx >= 0) {
7336 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07007337 mNewLeftVolume = newLeft;
7338 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007339 }
7340 // then indicate volume to all other effects in chain.
7341 // Pass altered volume to effects before volume controller
7342 // and requested volume to effects after controller
7343 uint32_t lVol = newLeft;
7344 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007345
Mathias Agopian65ab4712010-07-14 17:59:35 -07007346 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07007347 if ((int)i == ctrlIdx) continue;
7348 // this also works for ctrlIdx == -1 when there is no volume controller
7349 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007350 lVol = *left;
7351 rVol = *right;
7352 }
7353 mEffects[i]->setVolume(&lVol, &rVol, false);
7354 }
7355 *left = newLeft;
7356 *right = newRight;
7357
7358 return hasControl;
7359}
7360
Mathias Agopian65ab4712010-07-14 17:59:35 -07007361status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7362{
7363 const size_t SIZE = 256;
7364 char buffer[SIZE];
7365 String8 result;
7366
7367 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7368 result.append(buffer);
7369
7370 bool locked = tryLock(mLock);
7371 // failed to lock - AudioFlinger is probably deadlocked
7372 if (!locked) {
7373 result.append("\tCould not lock mutex:\n");
7374 }
7375
Eric Laurentcab11242010-07-15 12:50:15 -07007376 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7377 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007378 mEffects.size(),
7379 (uint32_t)mInBuffer,
7380 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007381 mActiveTrackCnt);
7382 result.append(buffer);
7383 write(fd, result.string(), result.size());
7384
7385 for (size_t i = 0; i < mEffects.size(); ++i) {
7386 sp<EffectModule> effect = mEffects[i];
7387 if (effect != 0) {
7388 effect->dump(fd, args);
7389 }
7390 }
7391
7392 if (locked) {
7393 mLock.unlock();
7394 }
7395
7396 return NO_ERROR;
7397}
7398
Eric Laurent59255e42011-07-27 19:49:51 -07007399// must be called with ThreadBase::mLock held
7400void AudioFlinger::EffectChain::setEffectSuspended_l(
7401 const effect_uuid_t *type, bool suspend)
7402{
7403 sp<SuspendedEffectDesc> desc;
7404 // use effect type UUID timelow as key as there is no real risk of identical
7405 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007406 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07007407 if (suspend) {
7408 if (index >= 0) {
7409 desc = mSuspendedEffects.valueAt(index);
7410 } else {
7411 desc = new SuspendedEffectDesc();
7412 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7413 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01007414 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07007415 }
7416 if (desc->mRefCount++ == 0) {
7417 sp<EffectModule> effect = getEffectIfEnabled(type);
7418 if (effect != 0) {
7419 desc->mEffect = effect;
7420 effect->setSuspended(true);
7421 effect->setEnabled(false);
7422 }
7423 }
7424 } else {
7425 if (index < 0) {
7426 return;
7427 }
7428 desc = mSuspendedEffects.valueAt(index);
7429 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007430 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07007431 desc->mRefCount = 1;
7432 }
7433 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01007434 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007435 if (desc->mEffect != 0) {
7436 sp<EffectModule> effect = desc->mEffect.promote();
7437 if (effect != 0) {
7438 effect->setSuspended(false);
7439 sp<EffectHandle> handle = effect->controlHandle();
7440 if (handle != 0) {
7441 effect->setEnabled(handle->enabled());
7442 }
7443 }
7444 desc->mEffect.clear();
7445 }
7446 mSuspendedEffects.removeItemsAt(index);
7447 }
7448 }
7449}
7450
7451// must be called with ThreadBase::mLock held
7452void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7453{
7454 sp<SuspendedEffectDesc> desc;
7455
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007456 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07007457 if (suspend) {
7458 if (index >= 0) {
7459 desc = mSuspendedEffects.valueAt(index);
7460 } else {
7461 desc = new SuspendedEffectDesc();
7462 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01007463 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07007464 }
7465 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08007466 Vector< sp<EffectModule> > effects;
7467 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07007468 for (size_t i = 0; i < effects.size(); i++) {
7469 setEffectSuspended_l(&effects[i]->desc().type, true);
7470 }
7471 }
7472 } else {
7473 if (index < 0) {
7474 return;
7475 }
7476 desc = mSuspendedEffects.valueAt(index);
7477 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007478 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07007479 desc->mRefCount = 1;
7480 }
7481 if (--desc->mRefCount == 0) {
7482 Vector<const effect_uuid_t *> types;
7483 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
7484 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
7485 continue;
7486 }
7487 types.add(&mSuspendedEffects.valueAt(i)->mType);
7488 }
7489 for (size_t i = 0; i < types.size(); i++) {
7490 setEffectSuspended_l(types[i], false);
7491 }
Steve Block3856b092011-10-20 11:56:00 +01007492 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007493 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
7494 }
7495 }
7496}
7497
Eric Laurent6bffdb82011-09-23 08:40:41 -07007498
7499// The volume effect is used for automated tests only
7500#ifndef OPENSL_ES_H_
7501static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
7502 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
7503const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
7504#endif //OPENSL_ES_H_
7505
Eric Laurentdb7c0792011-08-10 10:37:50 -07007506bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
7507{
7508 // auxiliary effects and visualizer are never suspended on output mix
7509 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
7510 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07007511 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
7512 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007513 return false;
7514 }
7515 return true;
7516}
7517
Glenn Kastend0539712012-01-30 12:56:03 -08007518void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07007519{
Glenn Kastend0539712012-01-30 12:56:03 -08007520 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07007521 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08007522 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
7523 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07007524 }
Eric Laurent59255e42011-07-27 19:49:51 -07007525 }
Eric Laurent59255e42011-07-27 19:49:51 -07007526}
7527
7528sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
7529 const effect_uuid_t *type)
7530{
Glenn Kasten090f0192012-01-30 13:00:02 -08007531 sp<EffectModule> effect = getEffectFromType_l(type);
7532 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07007533}
7534
7535void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
7536 bool enabled)
7537{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007538 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07007539 if (enabled) {
7540 if (index < 0) {
7541 // if the effect is not suspend check if all effects are suspended
7542 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7543 if (index < 0) {
7544 return;
7545 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07007546 if (!isEffectEligibleForSuspend(effect->desc())) {
7547 return;
7548 }
Eric Laurent59255e42011-07-27 19:49:51 -07007549 setEffectSuspended_l(&effect->desc().type, enabled);
7550 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07007551 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007552 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07007553 return;
7554 }
Eric Laurent59255e42011-07-27 19:49:51 -07007555 }
Steve Block3856b092011-10-20 11:56:00 +01007556 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07007557 effect->desc().type.timeLow);
7558 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7559 // if effect is requested to suspended but was not yet enabled, supend it now.
7560 if (desc->mEffect == 0) {
7561 desc->mEffect = effect;
7562 effect->setEnabled(false);
7563 effect->setSuspended(true);
7564 }
7565 } else {
7566 if (index < 0) {
7567 return;
7568 }
Steve Block3856b092011-10-20 11:56:00 +01007569 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07007570 effect->desc().type.timeLow);
7571 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7572 desc->mEffect.clear();
7573 effect->setSuspended(false);
7574 }
7575}
7576
Mathias Agopian65ab4712010-07-14 17:59:35 -07007577#undef LOG_TAG
7578#define LOG_TAG "AudioFlinger"
7579
7580// ----------------------------------------------------------------------------
7581
7582status_t AudioFlinger::onTransact(
7583 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7584{
7585 return BnAudioFlinger::onTransact(code, data, reply, flags);
7586}
7587
Mathias Agopian65ab4712010-07-14 17:59:35 -07007588}; // namespace android