blob: ef7164152367096e908cfea720199147dbb210cf [file] [log] [blame]
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001/* //device/include/server/AudioFlinger/AudioFlinger.cpp
2**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
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
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070027#include <binder/IServiceManager.h>
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -070028#include <utils/Log.h>
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070029#include <binder/Parcel.h>
30#include <binder/IPCThreadState.h>
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -070031#include <utils/String16.h>
32#include <utils/threads.h>
33
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -080034#include <cutils/properties.h>
35
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -070036#include <media/AudioTrack.h>
37#include <media/AudioRecord.h>
38
39#include <private/media/AudioTrackShared.h>
40
The Android Open Source Project8a7a6752009-01-15 16:12:10 -080041#include <hardware_legacy/AudioHardwareInterface.h>
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -070042
43#include "AudioMixer.h"
44#include "AudioFlinger.h"
45
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -080046#ifdef WITH_A2DP
47#include "A2dpAudioInterface.h"
48#endif
49
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080050// ----------------------------------------------------------------------------
51// the sim build doesn't have gettid
52
53#ifndef HAVE_GETTID
54# define gettid getpid
55#endif
56
57// ----------------------------------------------------------------------------
58
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -070059namespace android {
60
The Android Open Source Project4f68be12009-03-18 17:39:46 -070061static const char* kDeadlockedString = "AudioFlinger may be deadlocked\n";
62static const char* kHardwareLockedString = "Hardware lock is taken\n";
63
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -080064//static const nsecs_t kStandbyTimeInNsecs = seconds(3);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -070065static const unsigned long kBufferRecoveryInUsecs = 2000;
66static const unsigned long kMaxBufferRecoveryInUsecs = 20000;
67static const float MAX_GAIN = 4096.0f;
68
69// retry counts for buffer fill timeout
70// 50 * ~20msecs = 1 second
71static const int8_t kMaxTrackRetries = 50;
72static const int8_t kMaxTrackStartupRetries = 50;
73
The Android Open Source Project22f8def2009-03-09 11:52:12 -070074static const int kDumpLockRetries = 50;
75static const int kDumpLockSleep = 20000;
76
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -070078#define AUDIOFLINGER_SECURITY_ENABLED 1
79
80// ----------------------------------------------------------------------------
81
82static bool recordingAllowed() {
83#ifndef HAVE_ANDROID_OS
84 return true;
85#endif
86#if AUDIOFLINGER_SECURITY_ENABLED
87 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
88 bool ok = checkCallingPermission(String16("android.permission.RECORD_AUDIO"));
89 if (!ok) LOGE("Request requires android.permission.RECORD_AUDIO");
90 return ok;
91#else
92 if (!checkCallingPermission(String16("android.permission.RECORD_AUDIO")))
93 LOGW("WARNING: Need to add android.permission.RECORD_AUDIO to manifest");
94 return true;
95#endif
96}
97
98static bool settingsAllowed() {
99#ifndef HAVE_ANDROID_OS
100 return true;
101#endif
102#if AUDIOFLINGER_SECURITY_ENABLED
103 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
104 bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
105 if (!ok) LOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
106 return ok;
107#else
108 if (!checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS")))
109 LOGW("WARNING: Need to add android.permission.MODIFY_AUDIO_SETTINGS to manifest");
110 return true;
111#endif
112}
113
114// ----------------------------------------------------------------------------
115
116AudioFlinger::AudioFlinger()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800117 : BnAudioFlinger(),
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700118 mAudioHardware(0), mMasterVolume(1.0f), mMasterMute(false), mNextThreadId(0)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700119{
120 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent9d91ad52009-07-17 12:17:14 -0700121
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700122 mAudioHardware = AudioHardwareInterface::create();
Eric Laurent9d91ad52009-07-17 12:17:14 -0700123
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700124 mHardwareStatus = AUDIO_HW_INIT;
125 if (mAudioHardware->initCheck() == NO_ERROR) {
126 // open 16-bit output stream for s/w mixer
Eric Laurent9d91ad52009-07-17 12:17:14 -0700127
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800128 setMode(AudioSystem::MODE_NORMAL);
129
130 setMasterVolume(1.0f);
131 setMasterMute(false);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700132 } else {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700133 LOGE("Couldn't even initialize the stubbed audio hardware!");
134 }
135}
136
137AudioFlinger::~AudioFlinger()
138{
Eric Laurentc80b1a02009-08-28 10:39:03 -0700139 while (!mRecordThreads.isEmpty()) {
140 // closeInput() will remove first entry from mRecordThreads
141 closeInput(mRecordThreads.keyAt(0));
142 }
143 while (!mPlaybackThreads.isEmpty()) {
144 // closeOutput() will remove first entry from mPlaybackThreads
145 closeOutput(mPlaybackThreads.keyAt(0));
146 }
147 if (mAudioHardware) {
148 delete mAudioHardware;
149 }
The Android Open Source Project27629322009-01-09 17:51:23 -0800150}
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800151
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700152
The Android Open Source Projectbcef13b2009-03-11 12:11:56 -0700153
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700154status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
155{
156 const size_t SIZE = 256;
157 char buffer[SIZE];
158 String8 result;
159
160 result.append("Clients:\n");
161 for (size_t i = 0; i < mClients.size(); ++i) {
162 wp<Client> wClient = mClients.valueAt(i);
163 if (wClient != 0) {
164 sp<Client> client = wClient.promote();
165 if (client != 0) {
166 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
167 result.append(buffer);
168 }
169 }
170 }
171 write(fd, result.string(), result.size());
172 return NO_ERROR;
173}
174
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700175
176status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
177{
178 const size_t SIZE = 256;
179 char buffer[SIZE];
180 String8 result;
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700181 int hardwareStatus = mHardwareStatus;
Eric Laurent9d91ad52009-07-17 12:17:14 -0700182
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700183 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700184 result.append(buffer);
185 write(fd, result.string(), result.size());
186 return NO_ERROR;
187}
188
189status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
190{
191 const size_t SIZE = 256;
192 char buffer[SIZE];
193 String8 result;
194 snprintf(buffer, SIZE, "Permission Denial: "
195 "can't dump AudioFlinger from pid=%d, uid=%d\n",
196 IPCThreadState::self()->getCallingPid(),
197 IPCThreadState::self()->getCallingUid());
198 result.append(buffer);
199 write(fd, result.string(), result.size());
200 return NO_ERROR;
201}
202
The Android Open Source Project4f68be12009-03-18 17:39:46 -0700203static bool tryLock(Mutex& mutex)
204{
205 bool locked = false;
206 for (int i = 0; i < kDumpLockRetries; ++i) {
207 if (mutex.tryLock() == NO_ERROR) {
208 locked = true;
209 break;
210 }
211 usleep(kDumpLockSleep);
212 }
213 return locked;
214}
215
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700216status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
217{
218 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
219 dumpPermissionDenial(fd, args);
220 } else {
The Android Open Source Project4f68be12009-03-18 17:39:46 -0700221 // get state of hardware lock
222 bool hardwareLocked = tryLock(mHardwareLock);
223 if (!hardwareLocked) {
224 String8 result(kHardwareLockedString);
225 write(fd, result.string(), result.size());
226 } else {
227 mHardwareLock.unlock();
228 }
229
230 bool locked = tryLock(mLock);
231
232 // failed to lock - AudioFlinger is probably deadlocked
233 if (!locked) {
234 String8 result(kDeadlockedString);
235 write(fd, result.string(), result.size());
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700236 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700237
238 dumpClients(fd, args);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700239 dumpInternals(fd, args);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800240
Eric Laurent9d91ad52009-07-17 12:17:14 -0700241 // dump playback threads
242 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700243 mPlaybackThreads.valueAt(i)->dump(fd, args);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700244 }
245
246 // dump record threads
Eric Laurentfd558a92009-07-23 13:35:01 -0700247 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700248 mRecordThreads.valueAt(i)->dump(fd, args);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700249 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800250
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700251 if (mAudioHardware) {
252 mAudioHardware->dumpState(fd, args);
253 }
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700254 if (locked) mLock.unlock();
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700255 }
256 return NO_ERROR;
257}
258
Eric Laurent9d91ad52009-07-17 12:17:14 -0700259
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700260// IAudioFlinger interface
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800261
262
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700263sp<IAudioTrack> AudioFlinger::createTrack(
264 pid_t pid,
265 int streamType,
266 uint32_t sampleRate,
267 int format,
268 int channelCount,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800269 int frameCount,
270 uint32_t flags,
271 const sp<IMemory>& sharedBuffer,
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700272 int output,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800273 status_t *status)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700274{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700275 sp<PlaybackThread::Track> track;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700276 sp<TrackHandle> trackHandle;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700277 sp<Client> client;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800278 wp<Client> wclient;
279 status_t lStatus;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700280
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800281 if (streamType >= AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800282 LOGE("invalid stream type");
283 lStatus = BAD_VALUE;
284 goto Exit;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700285 }
286
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800287 {
288 Mutex::Autolock _l(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700289 PlaybackThread *thread = checkPlaybackThread_l(output);
290 if (thread == NULL) {
291 LOGE("unknown output thread");
292 lStatus = BAD_VALUE;
293 goto Exit;
294 }
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800295
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800296 wclient = mClients.valueFor(pid);
297
298 if (wclient != NULL) {
299 client = wclient.promote();
300 } else {
301 client = new Client(this, pid);
302 mClients.add(pid, client);
303 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700304 track = thread->createTrack_l(client, streamType, sampleRate, format,
305 channelCount, frameCount, sharedBuffer, &lStatus);
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700306 }
307 if (lStatus == NO_ERROR) {
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800308 trackHandle = new TrackHandle(track);
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700309 } else {
310 track.clear();
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800311 }
312
313Exit:
314 if(status) {
315 *status = lStatus;
316 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700317 return trackHandle;
318}
319
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700320uint32_t AudioFlinger::sampleRate(int output) const
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700321{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700322 Mutex::Autolock _l(mLock);
323 PlaybackThread *thread = checkPlaybackThread_l(output);
324 if (thread == NULL) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700325 LOGW("sampleRate() unknown thread %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700326 return 0;
327 }
328 return thread->sampleRate();
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700329}
330
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700331int AudioFlinger::channelCount(int output) const
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700332{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700333 Mutex::Autolock _l(mLock);
334 PlaybackThread *thread = checkPlaybackThread_l(output);
335 if (thread == NULL) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700336 LOGW("channelCount() unknown thread %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700337 return 0;
338 }
339 return thread->channelCount();
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700340}
341
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700342int AudioFlinger::format(int output) const
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700343{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700344 Mutex::Autolock _l(mLock);
345 PlaybackThread *thread = checkPlaybackThread_l(output);
346 if (thread == NULL) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700347 LOGW("format() unknown thread %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700348 return 0;
349 }
350 return thread->format();
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700351}
352
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700353size_t AudioFlinger::frameCount(int output) const
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700354{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700355 Mutex::Autolock _l(mLock);
356 PlaybackThread *thread = checkPlaybackThread_l(output);
357 if (thread == NULL) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700358 LOGW("frameCount() unknown thread %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700359 return 0;
360 }
361 return thread->frameCount();
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700362}
363
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700364uint32_t AudioFlinger::latency(int output) const
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800365{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700366 Mutex::Autolock _l(mLock);
367 PlaybackThread *thread = checkPlaybackThread_l(output);
368 if (thread == NULL) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700369 LOGW("latency() unknown thread %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700370 return 0;
371 }
372 return thread->latency();
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800373}
374
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700375status_t AudioFlinger::setMasterVolume(float value)
376{
377 // check calling permissions
378 if (!settingsAllowed()) {
379 return PERMISSION_DENIED;
380 }
381
382 // when hw supports master volume, don't scale in sw mixer
383 AutoMutex lock(mHardwareLock);
384 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
385 if (mAudioHardware->setMasterVolume(value) == NO_ERROR) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800386 value = 1.0f;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700387 }
388 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent9d91ad52009-07-17 12:17:14 -0700389
390 mMasterVolume = value;
391 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700392 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700393
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700394 return NO_ERROR;
395}
396
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700397status_t AudioFlinger::setMode(int mode)
398{
399 // check calling permissions
400 if (!settingsAllowed()) {
401 return PERMISSION_DENIED;
402 }
403 if ((mode < 0) || (mode >= AudioSystem::NUM_MODES)) {
404 LOGW("Illegal value: setMode(%d)", mode);
405 return BAD_VALUE;
406 }
407
408 AutoMutex lock(mHardwareLock);
409 mHardwareStatus = AUDIO_HW_SET_MODE;
410 status_t ret = mAudioHardware->setMode(mode);
411 mHardwareStatus = AUDIO_HW_IDLE;
412 return ret;
413}
414
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700415status_t AudioFlinger::setMicMute(bool state)
416{
417 // check calling permissions
418 if (!settingsAllowed()) {
419 return PERMISSION_DENIED;
420 }
421
422 AutoMutex lock(mHardwareLock);
423 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
424 status_t ret = mAudioHardware->setMicMute(state);
425 mHardwareStatus = AUDIO_HW_IDLE;
426 return ret;
427}
428
429bool AudioFlinger::getMicMute() const
430{
431 bool state = AudioSystem::MODE_INVALID;
432 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
433 mAudioHardware->getMicMute(&state);
434 mHardwareStatus = AUDIO_HW_IDLE;
435 return state;
436}
437
438status_t AudioFlinger::setMasterMute(bool muted)
439{
440 // check calling permissions
441 if (!settingsAllowed()) {
442 return PERMISSION_DENIED;
443 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700444
445 mMasterMute = muted;
446 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700447 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700448
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700449 return NO_ERROR;
450}
451
452float AudioFlinger::masterVolume() const
453{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700454 return mMasterVolume;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700455}
456
457bool AudioFlinger::masterMute() const
458{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700459 return mMasterMute;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700460}
461
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700462status_t AudioFlinger::setStreamVolume(int stream, float value, int output)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700463{
464 // check calling permissions
465 if (!settingsAllowed()) {
466 return PERMISSION_DENIED;
467 }
468
Eric Laurent9d91ad52009-07-17 12:17:14 -0700469 if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700470 return BAD_VALUE;
471 }
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800472
Eric Laurent9d91ad52009-07-17 12:17:14 -0700473 AutoMutex lock(mLock);
474 PlaybackThread *thread = NULL;
475 if (output) {
476 thread = checkPlaybackThread_l(output);
477 if (thread == NULL) {
478 return BAD_VALUE;
479 }
480 }
481
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700482 status_t ret = NO_ERROR;
Eric Laurent9d91ad52009-07-17 12:17:14 -0700483
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800484 if (stream == AudioSystem::VOICE_CALL ||
485 stream == AudioSystem::BLUETOOTH_SCO) {
Eric Laurent4dd495b2009-04-21 07:56:33 -0700486 float hwValue;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800487 if (stream == AudioSystem::VOICE_CALL) {
Jean-Baptiste Queru732ca392009-03-18 11:33:14 -0700488 hwValue = (float)AudioSystem::logToLinear(value)/100.0f;
Eric Laurent4dd495b2009-04-21 07:56:33 -0700489 // offset value to reflect actual hardware volume that never reaches 0
490 // 1% corresponds roughly to first step in VOICE_CALL stream volume setting (see AudioService.java)
491 value = 0.01 + 0.99 * value;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800492 } else { // (type == AudioSystem::BLUETOOTH_SCO)
Jean-Baptiste Queru732ca392009-03-18 11:33:14 -0700493 hwValue = 1.0f;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800494 }
495
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700496 AutoMutex lock(mHardwareLock);
497 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
Jean-Baptiste Queru732ca392009-03-18 11:33:14 -0700498 ret = mAudioHardware->setVoiceVolume(hwValue);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700499 mHardwareStatus = AUDIO_HW_IDLE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800500
Eric Laurent9d91ad52009-07-17 12:17:14 -0700501 }
502
503 mStreamTypes[stream].volume = value;
504
505 if (thread == NULL) {
506 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700507 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700508
509 } else {
510 thread->setStreamVolume(stream, value);
511 }
Eric Laurent4dd495b2009-04-21 07:56:33 -0700512
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700513 return ret;
514}
515
516status_t AudioFlinger::setStreamMute(int stream, bool muted)
517{
518 // check calling permissions
519 if (!settingsAllowed()) {
520 return PERMISSION_DENIED;
521 }
522
Eric Laurent9d91ad52009-07-17 12:17:14 -0700523 if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES ||
Eric Laurentb1596ee2009-03-26 01:57:59 -0700524 uint32_t(stream) == AudioSystem::ENFORCED_AUDIBLE) {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700525 return BAD_VALUE;
526 }
The Android Open Source Project4f68be12009-03-18 17:39:46 -0700527
Eric Laurent9d91ad52009-07-17 12:17:14 -0700528 mStreamTypes[stream].mute = muted;
529 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700530 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800531
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700532 return NO_ERROR;
533}
534
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700535float AudioFlinger::streamVolume(int stream, int output) const
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700536{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700537 if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700538 return 0.0f;
539 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700540
541 AutoMutex lock(mLock);
542 float volume;
543 if (output) {
544 PlaybackThread *thread = checkPlaybackThread_l(output);
545 if (thread == NULL) {
546 return 0.0f;
547 }
548 volume = thread->streamVolume(stream);
549 } else {
550 volume = mStreamTypes[stream].volume;
551 }
552
Eric Laurent4dd495b2009-04-21 07:56:33 -0700553 // remove correction applied by setStreamVolume()
Jean-Baptiste Queru732ca392009-03-18 11:33:14 -0700554 if (stream == AudioSystem::VOICE_CALL) {
Eric Laurent4dd495b2009-04-21 07:56:33 -0700555 volume = (volume - 0.01) / 0.99 ;
James E. Blair6015dfc2009-01-17 13:30:20 -0800556 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700557
Eric Laurent4dd495b2009-04-21 07:56:33 -0700558 return volume;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700559}
560
561bool AudioFlinger::streamMute(int stream) const
562{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700563 if (stream < 0 || stream >= (int)AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700564 return true;
565 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700566
567 return mStreamTypes[stream].mute;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700568}
569
570bool AudioFlinger::isMusicActive() const
571{
Eric Laurentb025ca02009-07-09 03:20:57 -0700572 Mutex::Autolock _l(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700573 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700574 if (mPlaybackThreads.valueAt(i)->isMusicActive()) {
Eric Laurent9d91ad52009-07-17 12:17:14 -0700575 return true;
576 }
577 }
578 return false;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700579}
580
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700581status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700582{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700583 status_t result;
584
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700585 LOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
Eric Laurent9d91ad52009-07-17 12:17:14 -0700586 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
587 // check calling permissions
588 if (!settingsAllowed()) {
589 return PERMISSION_DENIED;
The Android Open Source Project8a7a6752009-01-15 16:12:10 -0800590 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700591
592 // ioHandle == 0 means the parameters are global to the audio hardware interface
593 if (ioHandle == 0) {
594 AutoMutex lock(mHardwareLock);
595 mHardwareStatus = AUDIO_SET_PARAMETER;
596 result = mAudioHardware->setParameters(keyValuePairs);
597 mHardwareStatus = AUDIO_HW_IDLE;
598 return result;
599 }
600
601 // Check if parameters are for an output
602 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
603 if (playbackThread != NULL) {
604 return playbackThread->setParameters(keyValuePairs);
605 }
606
607 // Check if parameters are for an input
608 RecordThread *recordThread = checkRecordThread_l(ioHandle);
609 if (recordThread != NULL) {
610 return recordThread->setParameters(keyValuePairs);
611 }
612
613 return BAD_VALUE;
614}
615
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700616String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
Eric Laurent9d91ad52009-07-17 12:17:14 -0700617{
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700618// LOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
Eric Laurent9d91ad52009-07-17 12:17:14 -0700619// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
620
621 if (ioHandle == 0) {
622 return mAudioHardware->getParameters(keys);
623 }
624 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
625 if (playbackThread != NULL) {
626 return playbackThread->getParameters(keys);
627 }
628 RecordThread *recordThread = checkRecordThread_l(ioHandle);
629 if (recordThread != NULL) {
630 return recordThread->getParameters(keys);
631 }
632 return String8("");
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700633}
634
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800635size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
636{
637 return mAudioHardware->getInputBufferSize(sampleRate, format, channelCount);
638}
639
640void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
641{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700642
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800643 LOGV("registerClient() %p, tid %d, calling tid %d", client.get(), gettid(), IPCThreadState::self()->getCallingPid());
644 Mutex::Autolock _l(mLock);
645
646 sp<IBinder> binder = client->asBinder();
647 if (mNotificationClients.indexOf(binder) < 0) {
648 LOGV("Adding notification client %p", binder.get());
649 binder->linkToDeath(this);
650 mNotificationClients.add(binder);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700651 }
652
653 // the config change is always sent from playback or record threads to avoid deadlock
654 // with AudioSystem::gLock
655 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700656 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700657 }
658
659 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700660 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800661 }
662}
663
664void AudioFlinger::binderDied(const wp<IBinder>& who) {
Eric Laurent9d91ad52009-07-17 12:17:14 -0700665
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800666 LOGV("binderDied() %p, tid %d, calling tid %d", who.unsafe_get(), gettid(), IPCThreadState::self()->getCallingPid());
667 Mutex::Autolock _l(mLock);
668
669 IBinder *binder = who.unsafe_get();
670
671 if (binder != NULL) {
672 int index = mNotificationClients.indexOf(binder);
673 if (index >= 0) {
674 LOGV("Removing notification client %p", binder);
675 mNotificationClients.removeAt(index);
676 }
677 }
678}
679
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700680void AudioFlinger::audioConfigChanged(int event, const sp<ThreadBase>& thread, void *param2) {
Eric Laurent9d91ad52009-07-17 12:17:14 -0700681 Mutex::Autolock _l(mLock);
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700682 int ioHandle = 0;
683
684 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
685 if (mPlaybackThreads.valueAt(i) == thread) {
686 ioHandle = mPlaybackThreads.keyAt(i);
687 break;
688 }
689 }
690 if (ioHandle == 0) {
691 for (size_t i = 0; i < mRecordThreads.size(); i++) {
692 if (mRecordThreads.valueAt(i) == thread) {
693 ioHandle = mRecordThreads.keyAt(i);
694 break;
695 }
696 }
697 }
698
699 if (ioHandle != 0) {
700 size_t size = mNotificationClients.size();
701 for (size_t i = 0; i < size; i++) {
702 sp<IBinder> binder = mNotificationClients.itemAt(i);
703 LOGV("audioConfigChanged() Notifying change to client %p", binder.get());
704 sp<IAudioFlingerClient> client = interface_cast<IAudioFlingerClient> (binder);
705 client->ioConfigChanged(event, ioHandle, param2);
706 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700707 }
708}
709
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700710void AudioFlinger::removeClient(pid_t pid)
711{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800712 LOGV("removeClient() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700713 Mutex::Autolock _l(mLock);
714 mClients.removeItem(pid);
715}
716
Eric Laurent9d91ad52009-07-17 12:17:14 -0700717// ----------------------------------------------------------------------------
718
719AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger)
720 : Thread(false),
721 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
Eric Laurent3464c012009-08-04 09:45:33 -0700722 mFormat(0), mFrameSize(1), mStandby(false)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700723{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800724}
725
Eric Laurent9d91ad52009-07-17 12:17:14 -0700726AudioFlinger::ThreadBase::~ThreadBase()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800727{
Eric Laurent3464c012009-08-04 09:45:33 -0700728 mParamCond.broadcast();
729 mNewParameters.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800730}
731
Eric Laurent9d91ad52009-07-17 12:17:14 -0700732void AudioFlinger::ThreadBase::exit()
The Android Open Source Projectbcef13b2009-03-11 12:11:56 -0700733{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700734 // keep a strong ref on ourself so that we want get
735 // destroyed in the middle of requestExitAndWait()
736 sp <ThreadBase> strongMe = this;
737
738 LOGV("ThreadBase::exit");
739 {
740 AutoMutex lock(&mLock);
741 requestExit();
742 mWaitWorkCV.signal();
The Android Open Source Projectbcef13b2009-03-11 12:11:56 -0700743 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700744 requestExitAndWait();
The Android Open Source Projectbcef13b2009-03-11 12:11:56 -0700745}
Eric Laurent9d91ad52009-07-17 12:17:14 -0700746
747uint32_t AudioFlinger::ThreadBase::sampleRate() const
748{
749 return mSampleRate;
750}
751
752int AudioFlinger::ThreadBase::channelCount() const
753{
754 return mChannelCount;
755}
756
757int AudioFlinger::ThreadBase::format() const
758{
759 return mFormat;
760}
761
762size_t AudioFlinger::ThreadBase::frameCount() const
763{
764 return mFrameCount;
765}
766
767status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
768{
Eric Laurent3464c012009-08-04 09:45:33 -0700769 status_t status;
Eric Laurent9d91ad52009-07-17 12:17:14 -0700770
Eric Laurent3464c012009-08-04 09:45:33 -0700771 LOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Eric Laurent9d91ad52009-07-17 12:17:14 -0700772 Mutex::Autolock _l(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700773
Eric Laurent3464c012009-08-04 09:45:33 -0700774 mNewParameters.add(keyValuePairs);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700775 mWaitWorkCV.signal();
776 mParamCond.wait(mLock);
Eric Laurent3464c012009-08-04 09:45:33 -0700777 status = mParamStatus;
778 mWaitWorkCV.signal();
779 return status;
Eric Laurent9d91ad52009-07-17 12:17:14 -0700780}
781
782void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
783{
784 Mutex::Autolock _l(mLock);
Eric Laurent3464c012009-08-04 09:45:33 -0700785 sendConfigEvent_l(event, param);
786}
787
788// sendConfigEvent_l() must be called with ThreadBase::mLock held
789void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
790{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700791 ConfigEvent *configEvent = new ConfigEvent();
792 configEvent->mEvent = event;
793 configEvent->mParam = param;
794 mConfigEvents.add(configEvent);
795 LOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
796 mWaitWorkCV.signal();
797}
798
799void AudioFlinger::ThreadBase::processConfigEvents()
800{
801 mLock.lock();
802 while(!mConfigEvents.isEmpty()) {
803 LOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
804 ConfigEvent *configEvent = mConfigEvents[0];
805 mConfigEvents.removeAt(0);
806 // release mLock because audioConfigChanged() will call
807 // Audioflinger::audioConfigChanged() which locks AudioFlinger mLock thus creating
808 // potential cross deadlock between AudioFlinger::mLock and mLock
809 mLock.unlock();
810 audioConfigChanged(configEvent->mEvent, configEvent->mParam);
811 delete configEvent;
812 mLock.lock();
813 }
814 mLock.unlock();
815}
816
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800817
818// ----------------------------------------------------------------------------
819
Eric Laurent9d91ad52009-07-17 12:17:14 -0700820AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output)
821 : ThreadBase(audioFlinger),
Eric Laurentf9df2492009-08-06 08:49:39 -0700822 mMixBuffer(0), mSuspended(0), mBytesWritten(0), mOutput(output),
Eric Laurent9395d9b2009-07-23 13:17:39 -0700823 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800824{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700825 readOutputParameters();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800826
Eric Laurent9d91ad52009-07-17 12:17:14 -0700827 mMasterVolume = mAudioFlinger->masterVolume();
828 mMasterMute = mAudioFlinger->masterMute();
829
830 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
831 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
832 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800833 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700834 // notify client processes that a new input has been opened
835 sendConfigEvent(AudioSystem::OUTPUT_OPENED);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800836}
837
Eric Laurent9d91ad52009-07-17 12:17:14 -0700838AudioFlinger::PlaybackThread::~PlaybackThread()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800839{
840 delete [] mMixBuffer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800841}
842
Eric Laurent9d91ad52009-07-17 12:17:14 -0700843status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800844{
845 dumpInternals(fd, args);
846 dumpTracks(fd, args);
847 return NO_ERROR;
848}
849
Eric Laurent9d91ad52009-07-17 12:17:14 -0700850status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800851{
852 const size_t SIZE = 256;
853 char buffer[SIZE];
854 String8 result;
855
Eric Laurent9d91ad52009-07-17 12:17:14 -0700856 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800857 result.append(buffer);
858 result.append(" Name Clien Typ Fmt Chn Buf S M F SRate LeftV RighV Serv User\n");
859 for (size_t i = 0; i < mTracks.size(); ++i) {
Eric Laurentc828f6a2009-03-31 14:34:35 -0700860 sp<Track> track = mTracks[i];
861 if (track != 0) {
862 track->dump(buffer, SIZE);
863 result.append(buffer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800864 }
865 }
866
Eric Laurent9d91ad52009-07-17 12:17:14 -0700867 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800868 result.append(buffer);
869 result.append(" Name Clien Typ Fmt Chn Buf S M F SRate LeftV RighV Serv User\n");
870 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Eric Laurentc828f6a2009-03-31 14:34:35 -0700871 wp<Track> wTrack = mActiveTracks[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800872 if (wTrack != 0) {
873 sp<Track> track = wTrack.promote();
874 if (track != 0) {
875 track->dump(buffer, SIZE);
876 result.append(buffer);
877 }
878 }
879 }
880 write(fd, result.string(), result.size());
881 return NO_ERROR;
882}
883
Eric Laurent9d91ad52009-07-17 12:17:14 -0700884status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800885{
886 const size_t SIZE = 256;
887 char buffer[SIZE];
888 String8 result;
889
Eric Laurent9d91ad52009-07-17 12:17:14 -0700890 snprintf(buffer, SIZE, "Output thread %p internals\n", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800891 result.append(buffer);
892 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
893 result.append(buffer);
894 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
895 result.append(buffer);
896 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
897 result.append(buffer);
898 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
899 result.append(buffer);
900 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
901 result.append(buffer);
902 write(fd, result.string(), result.size());
903 return NO_ERROR;
904}
905
906// Thread virtuals
Eric Laurent9d91ad52009-07-17 12:17:14 -0700907status_t AudioFlinger::PlaybackThread::readyToRun()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800908{
909 if (mSampleRate == 0) {
910 LOGE("No working audio driver found.");
911 return NO_INIT;
912 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700913 LOGI("AudioFlinger's thread %p ready to run", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800914 return NO_ERROR;
915}
916
Eric Laurent9d91ad52009-07-17 12:17:14 -0700917void AudioFlinger::PlaybackThread::onFirstRef()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800918{
919 const size_t SIZE = 256;
920 char buffer[SIZE];
921
Eric Laurent9d91ad52009-07-17 12:17:14 -0700922 snprintf(buffer, SIZE, "Playback Thread %p", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800923
924 run(buffer, ANDROID_PRIORITY_URGENT_AUDIO);
925}
926
Eric Laurent9d91ad52009-07-17 12:17:14 -0700927// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
928sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800929 const sp<AudioFlinger::Client>& client,
930 int streamType,
931 uint32_t sampleRate,
932 int format,
933 int channelCount,
934 int frameCount,
935 const sp<IMemory>& sharedBuffer,
936 status_t *status)
937{
938 sp<Track> track;
939 status_t lStatus;
Eric Laurent9d91ad52009-07-17 12:17:14 -0700940
941 if (mType == DIRECT) {
942 if (sampleRate != mSampleRate || format != mFormat || channelCount != mChannelCount) {
943 LOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelCount %d for output %p",
944 sampleRate, format, channelCount, mOutput);
945 lStatus = BAD_VALUE;
946 goto Exit;
947 }
948 } else {
949 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
950 if (sampleRate > mSampleRate*2) {
951 LOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
952 lStatus = BAD_VALUE;
953 goto Exit;
954 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800955 }
956
Eric Laurent9d91ad52009-07-17 12:17:14 -0700957 if (mOutput == 0) {
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700958 LOGE("Audio driver not initialized.");
959 lStatus = NO_INIT;
960 goto Exit;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800961 }
962
Eric Laurent9d91ad52009-07-17 12:17:14 -0700963 { // scope for mLock
964 Mutex::Autolock _l(mLock);
965 track = new Track(this, client, streamType, sampleRate, format,
966 channelCount, frameCount, sharedBuffer);
967 if (track->getCblk() == NULL) {
968 lStatus = NO_MEMORY;
969 goto Exit;
970 }
971 mTracks.add(track);
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700972 }
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700973 lStatus = NO_ERROR;
974
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800975Exit:
976 if(status) {
977 *status = lStatus;
978 }
979 return track;
980}
981
Eric Laurent9d91ad52009-07-17 12:17:14 -0700982uint32_t AudioFlinger::PlaybackThread::latency() const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800983{
984 if (mOutput) {
985 return mOutput->latency();
986 }
987 else {
988 return 0;
989 }
990}
991
Eric Laurent9d91ad52009-07-17 12:17:14 -0700992status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800993{
994 mMasterVolume = value;
995 return NO_ERROR;
996}
997
Eric Laurent9d91ad52009-07-17 12:17:14 -0700998status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800999{
1000 mMasterMute = muted;
1001 return NO_ERROR;
1002}
1003
Eric Laurent9d91ad52009-07-17 12:17:14 -07001004float AudioFlinger::PlaybackThread::masterVolume() const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001005{
1006 return mMasterVolume;
1007}
1008
Eric Laurent9d91ad52009-07-17 12:17:14 -07001009bool AudioFlinger::PlaybackThread::masterMute() const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001010{
1011 return mMasterMute;
1012}
1013
Eric Laurent9d91ad52009-07-17 12:17:14 -07001014status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001015{
1016 mStreamTypes[stream].volume = value;
1017 return NO_ERROR;
1018}
1019
Eric Laurent9d91ad52009-07-17 12:17:14 -07001020status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001021{
1022 mStreamTypes[stream].mute = muted;
1023 return NO_ERROR;
1024}
1025
Eric Laurent9d91ad52009-07-17 12:17:14 -07001026float AudioFlinger::PlaybackThread::streamVolume(int stream) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001027{
1028 return mStreamTypes[stream].volume;
1029}
1030
Eric Laurent9d91ad52009-07-17 12:17:14 -07001031bool AudioFlinger::PlaybackThread::streamMute(int stream) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001032{
1033 return mStreamTypes[stream].mute;
1034}
1035
Eric Laurent9d91ad52009-07-17 12:17:14 -07001036bool AudioFlinger::PlaybackThread::isMusicActive() const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001037{
Eric Laurent9d91ad52009-07-17 12:17:14 -07001038 Mutex::Autolock _l(mLock);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001039 size_t count = mActiveTracks.size();
1040 for (size_t i = 0 ; i < count ; ++i) {
1041 sp<Track> t = mActiveTracks[i].promote();
1042 if (t == 0) continue;
1043 Track* const track = t.get();
Eric Laurent9395d9b2009-07-23 13:17:39 -07001044 if (t->type() == AudioSystem::MUSIC)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001045 return true;
1046 }
1047 return false;
1048}
1049
Eric Laurent9d91ad52009-07-17 12:17:14 -07001050// addTrack_l() must be called with ThreadBase::mLock held
1051status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001052{
1053 status_t status = ALREADY_EXISTS;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001054
1055 // here the track could be either new, or restarted
1056 // in both cases "unstop" the track
1057 if (track->isPaused()) {
1058 track->mState = TrackBase::RESUMING;
1059 LOGV("PAUSED => RESUMING (%d)", track->name());
1060 } else {
1061 track->mState = TrackBase::ACTIVE;
1062 LOGV("? => ACTIVE (%d)", track->name());
1063 }
1064 // set retry count for buffer fill
1065 track->mRetryCount = kMaxTrackStartupRetries;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001066 if (mActiveTracks.indexOf(track) < 0) {
1067 // the track is newly added, make sure it fills up all its
1068 // buffers before playing. This is to ensure the client will
1069 // effectively get the latency it requested.
1070 track->mFillingUpStatus = Track::FS_FILLING;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08001071 track->mResetDone = false;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001072 mActiveTracks.add(track);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001073 status = NO_ERROR;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001074 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07001075
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001076 LOGV("mWaitWorkCV.broadcast");
Eric Laurent9d91ad52009-07-17 12:17:14 -07001077 mWaitWorkCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001078
1079 return status;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001080}
1081
Eric Laurent9d91ad52009-07-17 12:17:14 -07001082// destroyTrack_l() must be called with ThreadBase::mLock held
1083void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001084{
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001085 track->mState = TrackBase::TERMINATED;
1086 if (mActiveTracks.indexOf(track) < 0) {
1087 LOGV("remove track (%d) and delete from mixer", track->name());
1088 mTracks.remove(track);
The Android Open Source Project22f8def2009-03-09 11:52:12 -07001089 deleteTrackName_l(track->name());
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001090 }
1091}
1092
Eric Laurent9d91ad52009-07-17 12:17:14 -07001093String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
The Android Open Source Projecte41dd752009-01-22 00:13:42 -08001094{
Eric Laurent9d91ad52009-07-17 12:17:14 -07001095 return mOutput->getParameters(keys);
1096}
The Android Open Source Projecte41dd752009-01-22 00:13:42 -08001097
Eric Laurent9d91ad52009-07-17 12:17:14 -07001098void AudioFlinger::PlaybackThread::audioConfigChanged(int event, int param) {
1099 AudioSystem::OutputDescriptor desc;
1100 void *param2 = 0;
1101
1102 LOGV("PlaybackThread::audioConfigChanged, thread %p, event %d, param %d", this, event, param);
1103
1104 switch (event) {
1105 case AudioSystem::OUTPUT_OPENED:
1106 case AudioSystem::OUTPUT_CONFIG_CHANGED:
1107 desc.channels = mChannelCount;
1108 desc.samplingRate = mSampleRate;
1109 desc.format = mFormat;
1110 desc.frameCount = mFrameCount;
1111 desc.latency = latency();
1112 param2 = &desc;
1113 break;
1114
1115 case AudioSystem::STREAM_CONFIG_CHANGED:
1116 param2 = &param;
1117 case AudioSystem::OUTPUT_CLOSED:
1118 default:
1119 break;
1120 }
1121 mAudioFlinger->audioConfigChanged(event, this, param2);
1122}
1123
1124void AudioFlinger::PlaybackThread::readOutputParameters()
1125{
1126 mSampleRate = mOutput->sampleRate();
1127 mChannelCount = AudioSystem::popCount(mOutput->channels());
1128
1129 mFormat = mOutput->format();
1130 mFrameSize = mOutput->frameSize();
1131 mFrameCount = mOutput->bufferSize() / mFrameSize;
1132
1133 mMinBytesToWrite = (mOutput->latency() * mSampleRate * mFrameSize) / 1000;
1134 // FIXME - Current mixer implementation only supports stereo output: Always
1135 // Allocate a stereo buffer even if HW output is mono.
1136 if (mMixBuffer != NULL) delete mMixBuffer;
1137 mMixBuffer = new int16_t[mFrameCount * 2];
1138 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1139}
1140
1141// ----------------------------------------------------------------------------
1142
1143AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output)
1144 : PlaybackThread(audioFlinger, output),
1145 mAudioMixer(0)
1146{
1147 mType = PlaybackThread::MIXER;
1148 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1149
1150 // FIXME - Current mixer implementation only supports stereo output
1151 if (mChannelCount == 1) {
1152 LOGE("Invalid audio hardware channel count");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001153 }
The Android Open Source Projecte41dd752009-01-22 00:13:42 -08001154}
1155
Eric Laurent9d91ad52009-07-17 12:17:14 -07001156AudioFlinger::MixerThread::~MixerThread()
The Android Open Source Projecte41dd752009-01-22 00:13:42 -08001157{
Eric Laurent9d91ad52009-07-17 12:17:14 -07001158 delete mAudioMixer;
1159}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001160
Eric Laurent9d91ad52009-07-17 12:17:14 -07001161bool AudioFlinger::MixerThread::threadLoop()
1162{
1163 unsigned long sleepTime = kBufferRecoveryInUsecs;
1164 int16_t* curBuf = mMixBuffer;
1165 Vector< sp<Track> > tracksToRemove;
1166 size_t enabledTracks = 0;
1167 nsecs_t standbyTime = systemTime();
1168 size_t mixBufferSize = mFrameCount * mFrameSize;
1169 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 2;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001170
Eric Laurent9d91ad52009-07-17 12:17:14 -07001171 while (!exitPending())
1172 {
1173 processConfigEvents();
1174
1175 enabledTracks = 0;
1176 { // scope for mLock
1177
1178 Mutex::Autolock _l(mLock);
1179
1180 if (checkForNewParameters_l()) {
1181 mixBufferSize = mFrameCount * mFrameSize;
1182 maxPeriod = seconds(mFrameCount) / mSampleRate * 2;
1183 }
1184
1185 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1186
1187 // put audio hardware into standby after short delay
1188 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1189 mSuspended) {
1190 if (!mStandby) {
1191 LOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
1192 mOutput->standby();
1193 mStandby = true;
1194 mBytesWritten = 0;
1195 }
1196
1197 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1198 // we're about to wait, flush the binder command buffer
1199 IPCThreadState::self()->flushCommands();
1200
1201 if (exitPending()) break;
1202
1203 // wait until we have something to do...
1204 LOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
1205 mWaitWorkCV.wait(mLock);
1206 LOGV("MixerThread %p TID %d waking up\n", this, gettid());
1207
1208 if (mMasterMute == false) {
1209 char value[PROPERTY_VALUE_MAX];
1210 property_get("ro.audio.silent", value, "0");
1211 if (atoi(value)) {
1212 LOGD("Silence is golden");
1213 setMasterMute(true);
1214 }
1215 }
1216
1217 standbyTime = systemTime() + kStandbyTimeInNsecs;
1218 continue;
1219 }
1220 }
1221
1222 enabledTracks = prepareTracks_l(activeTracks, &tracksToRemove);
1223 }
1224
1225 if (LIKELY(enabledTracks)) {
1226 // mix buffers...
1227 mAudioMixer->process(curBuf);
1228
1229 // output audio to hardware
1230 if (mSuspended) {
1231 usleep(kMaxBufferRecoveryInUsecs);
1232 } else {
1233 mLastWriteTime = systemTime();
1234 mInWrite = true;
1235 int bytesWritten = (int)mOutput->write(curBuf, mixBufferSize);
1236 if (bytesWritten > 0) mBytesWritten += bytesWritten;
1237 mNumWrites++;
1238 mInWrite = false;
1239 mStandby = false;
1240 nsecs_t temp = systemTime();
1241 standbyTime = temp + kStandbyTimeInNsecs;
1242 nsecs_t delta = temp - mLastWriteTime;
1243 if (delta > maxPeriod) {
1244 LOGW("write blocked for %llu msecs", ns2ms(delta));
1245 mNumDelayedWrites++;
1246 }
1247 sleepTime = kBufferRecoveryInUsecs;
1248 }
1249 } else {
1250 // There was nothing to mix this round, which means all
1251 // active tracks were late. Sleep a little bit to give
1252 // them another chance. If we're too late, the audio
1253 // hardware will zero-fill for us.
1254 // LOGV("thread %p no buffers - usleep(%lu)", this, sleepTime);
1255 usleep(sleepTime);
1256 if (sleepTime < kMaxBufferRecoveryInUsecs) {
1257 sleepTime += kBufferRecoveryInUsecs;
1258 }
1259 }
1260
1261 // finally let go of all our tracks, without the lock held
1262 // since we can't guarantee the destructors won't acquire that
1263 // same lock.
1264 tracksToRemove.clear();
1265 }
1266
1267 if (!mStandby) {
1268 mOutput->standby();
1269 }
1270 sendConfigEvent(AudioSystem::OUTPUT_CLOSED);
1271 processConfigEvents();
1272
1273 LOGV("MixerThread %p exiting", this);
1274 return false;
1275}
1276
1277// prepareTracks_l() must be called with ThreadBase::mLock held
1278size_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
1279{
1280
1281 size_t enabledTracks = 0;
1282 // find out which tracks need to be processed
1283 size_t count = activeTracks.size();
1284 for (size_t i=0 ; i<count ; i++) {
1285 sp<Track> t = activeTracks[i].promote();
1286 if (t == 0) continue;
1287
1288 Track* const track = t.get();
1289 audio_track_cblk_t* cblk = track->cblk();
1290
1291 // The first time a track is added we wait
1292 // for all its buffers to be filled before processing it
1293 mAudioMixer->setActiveTrack(track->name());
1294 if (cblk->framesReady() && (track->isReady() || track->isStopped()) &&
1295 !track->isPaused())
1296 {
1297 //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
1298
1299 // compute volume for this track
1300 int16_t left, right;
1301 if (track->isMuted() || mMasterMute || track->isPausing() ||
1302 mStreamTypes[track->type()].mute) {
1303 left = right = 0;
1304 if (track->isPausing()) {
1305 track->setPaused();
1306 }
1307 } else {
1308 float typeVolume = mStreamTypes[track->type()].volume;
1309 float v = mMasterVolume * typeVolume;
1310 float v_clamped = v * cblk->volume[0];
1311 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
1312 left = int16_t(v_clamped);
1313 v_clamped = v * cblk->volume[1];
1314 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
1315 right = int16_t(v_clamped);
1316 }
1317
1318 // XXX: these things DON'T need to be done each time
1319 mAudioMixer->setBufferProvider(track);
1320 mAudioMixer->enable(AudioMixer::MIXING);
1321
1322 int param;
1323 if ( track->mFillingUpStatus == Track::FS_FILLED) {
1324 // no ramp for the first volume setting
1325 track->mFillingUpStatus = Track::FS_ACTIVE;
1326 if (track->mState == TrackBase::RESUMING) {
1327 track->mState = TrackBase::ACTIVE;
1328 param = AudioMixer::RAMP_VOLUME;
1329 } else {
1330 param = AudioMixer::VOLUME;
1331 }
1332 } else {
1333 param = AudioMixer::RAMP_VOLUME;
1334 }
1335 mAudioMixer->setParameter(param, AudioMixer::VOLUME0, left);
1336 mAudioMixer->setParameter(param, AudioMixer::VOLUME1, right);
1337 mAudioMixer->setParameter(
1338 AudioMixer::TRACK,
1339 AudioMixer::FORMAT, track->format());
1340 mAudioMixer->setParameter(
1341 AudioMixer::TRACK,
1342 AudioMixer::CHANNEL_COUNT, track->channelCount());
1343 mAudioMixer->setParameter(
1344 AudioMixer::RESAMPLE,
1345 AudioMixer::SAMPLE_RATE,
1346 int(cblk->sampleRate));
1347
1348 // reset retry count
1349 track->mRetryCount = kMaxTrackRetries;
1350 enabledTracks++;
1351 } else {
1352 //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
1353 if (track->isStopped()) {
1354 track->reset();
1355 }
1356 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
1357 // We have consumed all the buffers of this track.
1358 // Remove it from the list of active tracks.
1359 tracksToRemove->add(track);
1360 mAudioMixer->disable(AudioMixer::MIXING);
1361 } else {
1362 // No buffers for this track. Give it a few chances to
1363 // fill a buffer, then remove it from active list.
1364 if (--(track->mRetryCount) <= 0) {
1365 LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
1366 tracksToRemove->add(track);
1367 }
1368 // For tracks using static shared memry buffer, make sure that we have
1369 // written enough data to audio hardware before disabling the track
1370 // NOTE: this condition with arrive before track->mRetryCount <= 0 so we
1371 // don't care about code removing track from active list above.
1372 if ((track->mSharedBuffer == 0) || (mBytesWritten >= mMinBytesToWrite)) {
1373 mAudioMixer->disable(AudioMixer::MIXING);
1374 } else {
1375 enabledTracks++;
1376 }
1377 }
1378 }
1379 }
1380
1381 // remove all the tracks that need to be...
1382 count = tracksToRemove->size();
1383 if (UNLIKELY(count)) {
1384 for (size_t i=0 ; i<count ; i++) {
1385 const sp<Track>& track = tracksToRemove->itemAt(i);
1386 mActiveTracks.remove(track);
1387 if (track->isTerminated()) {
1388 mTracks.remove(track);
1389 deleteTrackName_l(track->mName);
1390 }
1391 }
1392 }
1393
1394 return enabledTracks;
1395}
1396
1397void AudioFlinger::MixerThread::getTracks(
1398 SortedVector < sp<Track> >& tracks,
1399 SortedVector < wp<Track> >& activeTracks,
1400 int streamType)
1401{
1402 LOGV ("MixerThread::getTracks() mixer %p, mTracks.size %d, mActiveTracks.size %d", this, mTracks.size(), mActiveTracks.size());
1403 Mutex::Autolock _l(mLock);
1404 size_t size = mTracks.size();
1405 for (size_t i = 0; i < size; i++) {
1406 sp<Track> t = mTracks[i];
1407 if (t->type() == streamType) {
1408 tracks.add(t);
1409 int j = mActiveTracks.indexOf(t);
1410 if (j >= 0) {
1411 t = mActiveTracks[j].promote();
1412 if (t != NULL) {
1413 activeTracks.add(t);
1414 }
1415 }
1416 }
1417 }
1418
1419 size = activeTracks.size();
1420 for (size_t i = 0; i < size; i++) {
1421 mActiveTracks.remove(activeTracks[i]);
1422 }
1423
1424 size = tracks.size();
1425 for (size_t i = 0; i < size; i++) {
1426 sp<Track> t = tracks[i];
1427 mTracks.remove(t);
1428 deleteTrackName_l(t->name());
1429 }
1430}
1431
1432void AudioFlinger::MixerThread::putTracks(
1433 SortedVector < sp<Track> >& tracks,
1434 SortedVector < wp<Track> >& activeTracks)
1435{
1436 LOGV ("MixerThread::putTracks() mixer %p, tracks.size %d, activeTracks.size %d", this, tracks.size(), activeTracks.size());
1437 Mutex::Autolock _l(mLock);
1438 size_t size = tracks.size();
1439 for (size_t i = 0; i < size ; i++) {
1440 sp<Track> t = tracks[i];
1441 int name = getTrackName_l();
1442
1443 if (name < 0) return;
1444
1445 t->mName = name;
1446 t->mThread = this;
1447 mTracks.add(t);
1448
1449 int j = activeTracks.indexOf(t);
1450 if (j >= 0) {
1451 mActiveTracks.add(t);
Eric Laurent06437712009-09-01 05:56:26 -07001452 // force buffer refilling and no ramp volume when the track is mixed for the first time
1453 t->mFillingUpStatus = Track::FS_FILLING;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001454 }
1455 }
1456}
1457
Eric Laurent9d91ad52009-07-17 12:17:14 -07001458// getTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Project22f8def2009-03-09 11:52:12 -07001459int AudioFlinger::MixerThread::getTrackName_l()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001460{
1461 return mAudioMixer->getTrackName();
1462}
1463
Eric Laurent9d91ad52009-07-17 12:17:14 -07001464// deleteTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Project22f8def2009-03-09 11:52:12 -07001465void AudioFlinger::MixerThread::deleteTrackName_l(int name)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001466{
1467 mAudioMixer->deleteTrackName(name);
1468}
1469
Eric Laurent9d91ad52009-07-17 12:17:14 -07001470// checkForNewParameters_l() must be called with ThreadBase::mLock held
1471bool AudioFlinger::MixerThread::checkForNewParameters_l()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001472{
Eric Laurent9d91ad52009-07-17 12:17:14 -07001473 bool reconfig = false;
1474
Eric Laurent3464c012009-08-04 09:45:33 -07001475 while (!mNewParameters.isEmpty()) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07001476 status_t status = NO_ERROR;
Eric Laurent3464c012009-08-04 09:45:33 -07001477 String8 keyValuePair = mNewParameters[0];
1478 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001479 int value;
Eric Laurent3464c012009-08-04 09:45:33 -07001480
1481 mNewParameters.removeAt(0);
1482
Eric Laurent9d91ad52009-07-17 12:17:14 -07001483 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
1484 reconfig = true;
1485 }
1486 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
1487 if (value != AudioSystem::PCM_16_BIT) {
1488 status = BAD_VALUE;
1489 } else {
1490 reconfig = true;
1491 }
1492 }
1493 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
1494 if (value != AudioSystem::CHANNEL_OUT_STEREO) {
1495 status = BAD_VALUE;
1496 } else {
1497 reconfig = true;
1498 }
1499 }
1500 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
1501 // do not accept frame count changes if tracks are open as the track buffer
1502 // size depends on frame count and correct behavior would not be garantied
1503 // if frame count is changed after track creation
1504 if (!mTracks.isEmpty()) {
1505 status = INVALID_OPERATION;
1506 } else {
1507 reconfig = true;
1508 }
1509 }
1510 if (status == NO_ERROR) {
Eric Laurent3464c012009-08-04 09:45:33 -07001511 status = mOutput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001512 if (!mStandby && status == INVALID_OPERATION) {
1513 mOutput->standby();
1514 mStandby = true;
1515 mBytesWritten = 0;
Eric Laurent3464c012009-08-04 09:45:33 -07001516 status = mOutput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001517 }
1518 if (status == NO_ERROR && reconfig) {
1519 delete mAudioMixer;
1520 readOutputParameters();
1521 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1522 for (size_t i = 0; i < mTracks.size() ; i++) {
1523 int name = getTrackName_l();
1524 if (name < 0) break;
1525 mTracks[i]->mName = name;
Eric Laurent878c0e12009-08-10 08:15:12 -07001526 // limit track sample rate to 2 x new output sample rate
1527 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
1528 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
1529 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07001530 }
Eric Laurent3464c012009-08-04 09:45:33 -07001531 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001532 }
1533 }
1534 mParamStatus = status;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001535 mParamCond.signal();
Eric Laurent3464c012009-08-04 09:45:33 -07001536 mWaitWorkCV.wait(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001537 }
1538 return reconfig;
1539}
1540
1541status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
1542{
1543 const size_t SIZE = 256;
1544 char buffer[SIZE];
1545 String8 result;
1546
1547 PlaybackThread::dumpInternals(fd, args);
1548
1549 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
1550 result.append(buffer);
1551 write(fd, result.string(), result.size());
1552 return NO_ERROR;
1553}
1554
1555// ----------------------------------------------------------------------------
1556AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output)
1557 : PlaybackThread(audioFlinger, output),
1558 mLeftVolume (1.0), mRightVolume(1.0)
1559{
1560 mType = PlaybackThread::DIRECT;
1561}
1562
1563AudioFlinger::DirectOutputThread::~DirectOutputThread()
1564{
1565}
1566
1567
1568bool AudioFlinger::DirectOutputThread::threadLoop()
1569{
1570 unsigned long sleepTime = kBufferRecoveryInUsecs;
1571 sp<Track> trackToRemove;
1572 sp<Track> activeTrack;
1573 nsecs_t standbyTime = systemTime();
1574 int8_t *curBuf;
1575 size_t mixBufferSize = mFrameCount*mFrameSize;
1576
1577 while (!exitPending())
1578 {
1579 processConfigEvents();
1580
1581 { // scope for the mLock
1582
1583 Mutex::Autolock _l(mLock);
1584
1585 if (checkForNewParameters_l()) {
1586 mixBufferSize = mFrameCount*mFrameSize;
1587 }
1588
1589 // put audio hardware into standby after short delay
1590 if UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
1591 mSuspended) {
1592 // wait until we have something to do...
1593 if (!mStandby) {
1594 LOGV("Audio hardware entering standby, mixer %p\n", this);
1595 mOutput->standby();
1596 mStandby = true;
1597 mBytesWritten = 0;
1598 }
1599
1600 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
1601 // we're about to wait, flush the binder command buffer
1602 IPCThreadState::self()->flushCommands();
1603
1604 if (exitPending()) break;
1605
1606 LOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
1607 mWaitWorkCV.wait(mLock);
1608 LOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
1609
1610 if (mMasterMute == false) {
1611 char value[PROPERTY_VALUE_MAX];
1612 property_get("ro.audio.silent", value, "0");
1613 if (atoi(value)) {
1614 LOGD("Silence is golden");
1615 setMasterMute(true);
1616 }
1617 }
1618
1619 standbyTime = systemTime() + kStandbyTimeInNsecs;
1620 continue;
1621 }
1622 }
1623
1624 // find out which tracks need to be processed
1625 if (mActiveTracks.size() != 0) {
1626 sp<Track> t = mActiveTracks[0].promote();
1627 if (t == 0) continue;
1628
1629 Track* const track = t.get();
1630 audio_track_cblk_t* cblk = track->cblk();
1631
1632 // The first time a track is added we wait
1633 // for all its buffers to be filled before processing it
1634 if (cblk->framesReady() && (track->isReady() || track->isStopped()) &&
1635 !track->isPaused())
1636 {
1637 //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
1638
1639 // compute volume for this track
1640 float left, right;
1641 if (track->isMuted() || mMasterMute || track->isPausing() ||
1642 mStreamTypes[track->type()].mute) {
1643 left = right = 0;
1644 if (track->isPausing()) {
1645 track->setPaused();
1646 }
1647 } else {
1648 float typeVolume = mStreamTypes[track->type()].volume;
1649 float v = mMasterVolume * typeVolume;
1650 float v_clamped = v * cblk->volume[0];
1651 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
1652 left = v_clamped/MAX_GAIN;
1653 v_clamped = v * cblk->volume[1];
1654 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
1655 right = v_clamped/MAX_GAIN;
1656 }
1657
1658 if (left != mLeftVolume || right != mRightVolume) {
1659 mOutput->setVolume(left, right);
1660 left = mLeftVolume;
1661 right = mRightVolume;
1662 }
1663
1664 if (track->mFillingUpStatus == Track::FS_FILLED) {
1665 track->mFillingUpStatus = Track::FS_ACTIVE;
1666 if (track->mState == TrackBase::RESUMING) {
1667 track->mState = TrackBase::ACTIVE;
1668 }
1669 }
1670
1671 // reset retry count
1672 track->mRetryCount = kMaxTrackRetries;
1673 activeTrack = t;
1674 } else {
1675 //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
1676 if (track->isStopped()) {
1677 track->reset();
1678 }
1679 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
1680 // We have consumed all the buffers of this track.
1681 // Remove it from the list of active tracks.
1682 trackToRemove = track;
1683 } else {
1684 // No buffers for this track. Give it a few chances to
1685 // fill a buffer, then remove it from active list.
1686 if (--(track->mRetryCount) <= 0) {
1687 LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
1688 trackToRemove = track;
1689 }
1690
1691 // For tracks using static shared memry buffer, make sure that we have
1692 // written enough data to audio hardware before disabling the track
1693 // NOTE: this condition with arrive before track->mRetryCount <= 0 so we
1694 // don't care about code removing track from active list above.
1695 if ((track->mSharedBuffer != 0) && (mBytesWritten < mMinBytesToWrite)) {
1696 activeTrack = t;
1697 }
1698 }
1699 }
1700 }
1701
1702 // remove all the tracks that need to be...
1703 if (UNLIKELY(trackToRemove != 0)) {
1704 mActiveTracks.remove(trackToRemove);
1705 if (trackToRemove->isTerminated()) {
1706 mTracks.remove(trackToRemove);
1707 deleteTrackName_l(trackToRemove->mName);
1708 }
1709 }
1710 }
1711
1712 if (activeTrack != 0) {
1713 AudioBufferProvider::Buffer buffer;
1714 size_t frameCount = mFrameCount;
1715 curBuf = (int8_t *)mMixBuffer;
1716 // output audio to hardware
1717 mLastWriteTime = systemTime();
1718 mInWrite = true;
1719 while(frameCount) {
1720 buffer.frameCount = frameCount;
1721 activeTrack->getNextBuffer(&buffer);
1722 if (UNLIKELY(buffer.raw == 0)) {
1723 memset(curBuf, 0, frameCount * mFrameSize);
1724 break;
1725 }
1726 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
1727 frameCount -= buffer.frameCount;
1728 curBuf += buffer.frameCount * mFrameSize;
1729 activeTrack->releaseBuffer(&buffer);
1730 }
1731 if (mSuspended) {
1732 usleep(kMaxBufferRecoveryInUsecs);
1733 } else {
1734 int bytesWritten = (int)mOutput->write(mMixBuffer, mixBufferSize);
1735 if (bytesWritten) mBytesWritten += bytesWritten;
1736 mNumWrites++;
1737 mInWrite = false;
1738 mStandby = false;
1739 nsecs_t temp = systemTime();
1740 standbyTime = temp + kStandbyTimeInNsecs;
1741 sleepTime = kBufferRecoveryInUsecs;
1742 }
1743 } else {
1744 // There was nothing to mix this round, which means all
1745 // active tracks were late. Sleep a little bit to give
1746 // them another chance. If we're too late, the audio
1747 // hardware will zero-fill for us.
1748 //LOGV("no buffers - usleep(%lu)", sleepTime);
1749 usleep(sleepTime);
1750 if (sleepTime < kMaxBufferRecoveryInUsecs) {
1751 sleepTime += kBufferRecoveryInUsecs;
1752 }
1753 }
1754
1755 // finally let go of removed track, without the lock held
1756 // since we can't guarantee the destructors won't acquire that
1757 // same lock.
1758 trackToRemove.clear();
1759 activeTrack.clear();
1760 }
1761
1762 if (!mStandby) {
1763 mOutput->standby();
1764 }
1765 sendConfigEvent(AudioSystem::OUTPUT_CLOSED);
1766 processConfigEvents();
1767
1768 LOGV("DirectOutputThread %p exiting", this);
1769 return false;
1770}
1771
1772// getTrackName_l() must be called with ThreadBase::mLock held
1773int AudioFlinger::DirectOutputThread::getTrackName_l()
1774{
1775 return 0;
1776}
1777
1778// deleteTrackName_l() must be called with ThreadBase::mLock held
1779void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
1780{
1781}
1782
1783// checkForNewParameters_l() must be called with ThreadBase::mLock held
1784bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
1785{
1786 bool reconfig = false;
1787
Eric Laurent3464c012009-08-04 09:45:33 -07001788 while (!mNewParameters.isEmpty()) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07001789 status_t status = NO_ERROR;
Eric Laurent3464c012009-08-04 09:45:33 -07001790 String8 keyValuePair = mNewParameters[0];
1791 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001792 int value;
Eric Laurent3464c012009-08-04 09:45:33 -07001793
1794 mNewParameters.removeAt(0);
1795
Eric Laurent9d91ad52009-07-17 12:17:14 -07001796 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
1797 // do not accept frame count changes if tracks are open as the track buffer
1798 // size depends on frame count and correct behavior would not be garantied
1799 // if frame count is changed after track creation
1800 if (!mTracks.isEmpty()) {
1801 status = INVALID_OPERATION;
1802 } else {
1803 reconfig = true;
1804 }
1805 }
1806 if (status == NO_ERROR) {
Eric Laurent3464c012009-08-04 09:45:33 -07001807 status = mOutput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001808 if (!mStandby && status == INVALID_OPERATION) {
1809 mOutput->standby();
1810 mStandby = true;
1811 mBytesWritten = 0;
Eric Laurent3464c012009-08-04 09:45:33 -07001812 status = mOutput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001813 }
1814 if (status == NO_ERROR && reconfig) {
1815 readOutputParameters();
Eric Laurent3464c012009-08-04 09:45:33 -07001816 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001817 }
1818 }
1819 mParamStatus = status;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001820 mParamCond.signal();
Eric Laurent3464c012009-08-04 09:45:33 -07001821 mWaitWorkCV.wait(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001822 }
1823 return reconfig;
The Android Open Source Projecte41dd752009-01-22 00:13:42 -08001824}
1825
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001826// ----------------------------------------------------------------------------
1827
Eric Laurent9d91ad52009-07-17 12:17:14 -07001828AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread)
1829 : MixerThread(audioFlinger, mainThread->getOutput())
1830{
1831 mType = PlaybackThread::DUPLICATING;
1832 addOutputTrack(mainThread);
1833}
1834
1835AudioFlinger::DuplicatingThread::~DuplicatingThread()
1836{
1837 mOutputTracks.clear();
1838}
1839
1840bool AudioFlinger::DuplicatingThread::threadLoop()
1841{
1842 unsigned long sleepTime = kBufferRecoveryInUsecs;
1843 int16_t* curBuf = mMixBuffer;
1844 Vector< sp<Track> > tracksToRemove;
1845 size_t enabledTracks = 0;
1846 nsecs_t standbyTime = systemTime();
1847 size_t mixBufferSize = mFrameCount*mFrameSize;
1848 SortedVector< sp<OutputTrack> > outputTracks;
1849
1850 while (!exitPending())
1851 {
1852 processConfigEvents();
1853
1854 enabledTracks = 0;
1855 { // scope for the mLock
1856
1857 Mutex::Autolock _l(mLock);
1858
1859 if (checkForNewParameters_l()) {
1860 mixBufferSize = mFrameCount*mFrameSize;
1861 }
1862
1863 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1864
1865 for (size_t i = 0; i < mOutputTracks.size(); i++) {
1866 outputTracks.add(mOutputTracks[i]);
1867 }
1868
1869 // put audio hardware into standby after short delay
1870 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1871 mSuspended) {
1872 if (!mStandby) {
1873 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07001874 outputTracks[i]->stop();
Eric Laurent9d91ad52009-07-17 12:17:14 -07001875 }
1876 mStandby = true;
1877 mBytesWritten = 0;
1878 }
1879
1880 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1881 // we're about to wait, flush the binder command buffer
1882 IPCThreadState::self()->flushCommands();
1883 outputTracks.clear();
1884
1885 if (exitPending()) break;
1886
1887 LOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
1888 mWaitWorkCV.wait(mLock);
1889 LOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
1890 if (mMasterMute == false) {
1891 char value[PROPERTY_VALUE_MAX];
1892 property_get("ro.audio.silent", value, "0");
1893 if (atoi(value)) {
1894 LOGD("Silence is golden");
1895 setMasterMute(true);
1896 }
1897 }
1898
1899 standbyTime = systemTime() + kStandbyTimeInNsecs;
1900 sleepTime = kBufferRecoveryInUsecs;
1901 continue;
1902 }
1903 }
1904
1905 enabledTracks = prepareTracks_l(activeTracks, &tracksToRemove);
1906 }
1907
1908 bool mustSleep = true;
1909 if (LIKELY(enabledTracks)) {
1910 // mix buffers...
1911 mAudioMixer->process(curBuf);
1912 if (!mSuspended) {
1913 for (size_t i = 0; i < outputTracks.size(); i++) {
1914 outputTracks[i]->write(curBuf, mFrameCount);
Eric Laurentf5aba822009-08-10 23:22:32 -07001915 mustSleep = false;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001916 }
1917 mStandby = false;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001918 mBytesWritten += mixBufferSize;
1919 }
1920 } else {
1921 // flush remaining overflow buffers in output tracks
1922 for (size_t i = 0; i < outputTracks.size(); i++) {
1923 if (outputTracks[i]->isActive()) {
1924 outputTracks[i]->write(curBuf, 0);
1925 standbyTime = systemTime() + kStandbyTimeInNsecs;
1926 mustSleep = false;
1927 }
1928 }
1929 }
1930 if (mustSleep) {
1931// LOGV("threadLoop() sleeping %d", sleepTime);
1932 usleep(sleepTime);
1933 if (sleepTime < kMaxBufferRecoveryInUsecs) {
1934 sleepTime += kBufferRecoveryInUsecs;
1935 }
1936 } else {
1937 sleepTime = kBufferRecoveryInUsecs;
1938 }
1939
1940 // finally let go of all our tracks, without the lock held
1941 // since we can't guarantee the destructors won't acquire that
1942 // same lock.
1943 tracksToRemove.clear();
1944 outputTracks.clear();
1945 }
1946
Eric Laurentf5aba822009-08-10 23:22:32 -07001947 { // scope for the mLock
1948
1949 Mutex::Autolock _l(mLock);
1950 if (!mStandby) {
1951 LOGV("DuplicatingThread() exiting out of standby");
1952 for (size_t i = 0; i < mOutputTracks.size(); i++) {
1953 mOutputTracks[i]->destroy();
1954 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07001955 }
1956 }
1957
1958 sendConfigEvent(AudioSystem::OUTPUT_CLOSED);
1959 processConfigEvents();
1960
1961 return false;
1962}
1963
1964void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
1965{
1966 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
1967 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
1968 mSampleRate,
1969 mFormat,
1970 mChannelCount,
1971 frameCount);
Eric Laurentf5aba822009-08-10 23:22:32 -07001972 if (outputTrack->cblk() != NULL) {
1973 thread->setStreamVolume(AudioSystem::NUM_STREAM_TYPES, 1.0f);
1974 mOutputTracks.add(outputTrack);
1975 LOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
1976 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07001977}
1978
1979void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
1980{
1981 Mutex::Autolock _l(mLock);
1982 for (size_t i = 0; i < mOutputTracks.size(); i++) {
1983 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
Eric Laurentf5aba822009-08-10 23:22:32 -07001984 mOutputTracks[i]->destroy();
Eric Laurent9d91ad52009-07-17 12:17:14 -07001985 mOutputTracks.removeAt(i);
1986 return;
1987 }
1988 }
1989 LOGV("removeOutputTrack(): unkonwn thread: %p", thread);
1990}
1991
1992
1993// ----------------------------------------------------------------------------
1994
The Android Open Source Project22f8def2009-03-09 11:52:12 -07001995// TrackBase constructor must be called with AudioFlinger::mLock held
Eric Laurent9d91ad52009-07-17 12:17:14 -07001996AudioFlinger::ThreadBase::TrackBase::TrackBase(
1997 const wp<ThreadBase>& thread,
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001998 const sp<Client>& client,
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001999 uint32_t sampleRate,
2000 int format,
2001 int channelCount,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002002 int frameCount,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002003 uint32_t flags,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002004 const sp<IMemory>& sharedBuffer)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002005 : RefBase(),
Eric Laurent9d91ad52009-07-17 12:17:14 -07002006 mThread(thread),
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002007 mClient(client),
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002008 mFrameCount(0),
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002009 mState(IDLE),
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002010 mClientTid(-1),
2011 mFormat(format),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002012 mFlags(flags & ~SYSTEM_FLAGS_MASK)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002013{
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002014 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
2015
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002016 // LOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002017 size_t size = sizeof(audio_track_cblk_t);
2018 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
2019 if (sharedBuffer == 0) {
2020 size += bufferSize;
2021 }
2022
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002023 if (client != NULL) {
2024 mCblkMemory = client->heap()->allocate(size);
2025 if (mCblkMemory != 0) {
2026 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
2027 if (mCblk) { // construct the shared structure in-place.
2028 new(mCblk) audio_track_cblk_t();
2029 // clear all buffers
2030 mCblk->frameCount = frameCount;
Eric Laurent0bac5382009-07-07 07:10:45 -07002031 mCblk->sampleRate = sampleRate;
2032 mCblk->channels = (uint8_t)channelCount;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002033 if (sharedBuffer == 0) {
2034 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2035 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2036 // Force underrun condition to avoid false underrun callback until first data is
2037 // written to buffer
2038 mCblk->flowControlFlag = 1;
2039 } else {
2040 mBuffer = sharedBuffer->pointer();
2041 }
2042 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002043 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002044 } else {
2045 LOGE("not enough memory for AudioTrack size=%u", size);
2046 client->heap()->dump("AudioTrack");
2047 return;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002048 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002049 } else {
2050 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
2051 if (mCblk) { // construct the shared structure in-place.
2052 new(mCblk) audio_track_cblk_t();
2053 // clear all buffers
2054 mCblk->frameCount = frameCount;
Eric Laurent0bac5382009-07-07 07:10:45 -07002055 mCblk->sampleRate = sampleRate;
2056 mCblk->channels = (uint8_t)channelCount;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002057 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2058 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2059 // Force underrun condition to avoid false underrun callback until first data is
2060 // written to buffer
2061 mCblk->flowControlFlag = 1;
2062 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
2063 }
2064 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002065}
2066
Eric Laurent9d91ad52009-07-17 12:17:14 -07002067AudioFlinger::PlaybackThread::TrackBase::~TrackBase()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002068{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002069 if (mCblk) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07002070 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
2071 if (mClient == NULL) {
2072 delete mCblk;
2073 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002074 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002075 mCblkMemory.clear(); // and free the shared memory
2076 mClient.clear();
2077}
2078
Eric Laurent9d91ad52009-07-17 12:17:14 -07002079void AudioFlinger::PlaybackThread::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002080{
2081 buffer->raw = 0;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002082 mFrameCount = buffer->frameCount;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002083 step();
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002084 buffer->frameCount = 0;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002085}
2086
Eric Laurent9d91ad52009-07-17 12:17:14 -07002087bool AudioFlinger::PlaybackThread::TrackBase::step() {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002088 bool result;
2089 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002090
2091 result = cblk->stepServer(mFrameCount);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002092 if (!result) {
2093 LOGV("stepServer failed acquiring cblk mutex");
2094 mFlags |= STEPSERVER_FAILED;
2095 }
2096 return result;
2097}
2098
Eric Laurent9d91ad52009-07-17 12:17:14 -07002099void AudioFlinger::PlaybackThread::TrackBase::reset() {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002100 audio_track_cblk_t* cblk = this->cblk();
2101
2102 cblk->user = 0;
2103 cblk->server = 0;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002104 cblk->userBase = 0;
2105 cblk->serverBase = 0;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002106 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002107 LOGV("TrackBase::reset");
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002108}
2109
Eric Laurent9d91ad52009-07-17 12:17:14 -07002110sp<IMemory> AudioFlinger::PlaybackThread::TrackBase::getCblk() const
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002111{
2112 return mCblkMemory;
2113}
2114
Eric Laurent9d91ad52009-07-17 12:17:14 -07002115int AudioFlinger::PlaybackThread::TrackBase::sampleRate() const {
The Android Open Source Project4f68be12009-03-18 17:39:46 -07002116 return (int)mCblk->sampleRate;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002117}
2118
Eric Laurent9d91ad52009-07-17 12:17:14 -07002119int AudioFlinger::PlaybackThread::TrackBase::channelCount() const {
Eric Laurent0bac5382009-07-07 07:10:45 -07002120 return (int)mCblk->channels;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002121}
2122
Eric Laurent9d91ad52009-07-17 12:17:14 -07002123void* AudioFlinger::PlaybackThread::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002124 audio_track_cblk_t* cblk = this->cblk();
Eric Laurent9d91ad52009-07-17 12:17:14 -07002125 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
2126 int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002127
2128 // Check validity of returned pointer in case the track control block would have been corrupted.
Eric Laurent9d91ad52009-07-17 12:17:14 -07002129 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
2130 ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
The Android Open Source Project4f68be12009-03-18 17:39:46 -07002131 LOGE("TrackBase::getBuffer buffer out of range:\n start: %p, end %p , mBuffer %p mBufferEnd %p\n \
2132 server %d, serverBase %d, user %d, userBase %d, channels %d",
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002133 bufferStart, bufferEnd, mBuffer, mBufferEnd,
The Android Open Source Project4f68be12009-03-18 17:39:46 -07002134 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, cblk->channels);
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002135 return 0;
2136 }
2137
2138 return bufferStart;
2139}
2140
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002141// ----------------------------------------------------------------------------
2142
Eric Laurent9d91ad52009-07-17 12:17:14 -07002143// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
2144AudioFlinger::PlaybackThread::Track::Track(
2145 const wp<ThreadBase>& thread,
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002146 const sp<Client>& client,
2147 int streamType,
2148 uint32_t sampleRate,
2149 int format,
2150 int channelCount,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002151 int frameCount,
2152 const sp<IMemory>& sharedBuffer)
Eric Laurent9d91ad52009-07-17 12:17:14 -07002153 : TrackBase(thread, client, sampleRate, format, channelCount, frameCount, 0, sharedBuffer),
2154 mMute(false), mSharedBuffer(sharedBuffer), mName(-1)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002155{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002156 sp<ThreadBase> baseThread = thread.promote();
2157 if (baseThread != 0) {
2158 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
2159 mName = playbackThread->getTrackName_l();
2160 }
2161 LOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2162 if (mName < 0) {
2163 LOGE("no more track names available");
2164 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002165 mVolume[0] = 1.0f;
2166 mVolume[1] = 1.0f;
Eric Laurent570dd0b2009-05-22 09:18:15 -07002167 mStreamType = streamType;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002168 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
2169 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
2170 mCblk->frameSize = AudioSystem::isLinearPCM(format) ? channelCount * sizeof(int16_t) : sizeof(int8_t);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002171}
2172
Eric Laurent9d91ad52009-07-17 12:17:14 -07002173AudioFlinger::PlaybackThread::Track::~Track()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002174{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002175 LOGV("PlaybackThread::Track destructor");
2176 sp<ThreadBase> thread = mThread.promote();
2177 if (thread != 0) {
2178 Mutex::Autolock _l(thread->mLock);
2179 mState = TERMINATED;
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002180 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002181}
2182
Eric Laurent9d91ad52009-07-17 12:17:14 -07002183void AudioFlinger::PlaybackThread::Track::destroy()
2184{
2185 // NOTE: destroyTrack_l() can remove a strong reference to this Track
2186 // by removing it from mTracks vector, so there is a risk that this Tracks's
2187 // desctructor is called. As the destructor needs to lock mLock,
2188 // we must acquire a strong reference on this Track before locking mLock
2189 // here so that the destructor is called only when exiting this function.
2190 // On the other hand, as long as Track::destroy() is only called by
2191 // TrackHandle destructor, the TrackHandle still holds a strong ref on
2192 // this Track with its member mTrack.
2193 sp<Track> keep(this);
2194 { // scope for mLock
2195 sp<ThreadBase> thread = mThread.promote();
2196 if (thread != 0) {
2197 Mutex::Autolock _l(thread->mLock);
2198 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2199 playbackThread->destroyTrack_l(this);
2200 }
2201 }
2202}
2203
2204void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002205{
2206 snprintf(buffer, size, " %5d %5d %3u %3u %3u %3u %1d %1d %1d %5u %5u %5u %04x %04x\n",
2207 mName - AudioMixer::TRACK0,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002208 (mClient == NULL) ? getpid() : mClient->pid(),
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002209 mStreamType,
2210 mFormat,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002211 mCblk->channels,
2212 mFrameCount,
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002213 mState,
2214 mMute,
2215 mFillingUpStatus,
2216 mCblk->sampleRate,
2217 mCblk->volume[0],
2218 mCblk->volume[1],
2219 mCblk->server,
2220 mCblk->user);
2221}
2222
Eric Laurent9d91ad52009-07-17 12:17:14 -07002223status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002224{
2225 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002226 uint32_t framesReady;
2227 uint32_t framesReq = buffer->frameCount;
2228
2229 // Check if last stepServer failed, try to step now
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002230 if (mFlags & TrackBase::STEPSERVER_FAILED) {
2231 if (!step()) goto getNextBuffer_exit;
2232 LOGV("stepServer recovered");
2233 mFlags &= ~TrackBase::STEPSERVER_FAILED;
2234 }
2235
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002236 framesReady = cblk->framesReady();
2237
2238 if (LIKELY(framesReady)) {
2239 uint32_t s = cblk->server;
2240 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
2241
2242 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
2243 if (framesReq > framesReady) {
2244 framesReq = framesReady;
2245 }
2246 if (s + framesReq > bufferEnd) {
2247 framesReq = bufferEnd - s;
2248 }
2249
2250 buffer->raw = getBuffer(s, framesReq);
2251 if (buffer->raw == 0) goto getNextBuffer_exit;
2252
2253 buffer->frameCount = framesReq;
2254 return NO_ERROR;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002255 }
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002256
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002257getNextBuffer_exit:
2258 buffer->raw = 0;
2259 buffer->frameCount = 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002260 LOGV("getNextBuffer() no more data");
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002261 return NOT_ENOUGH_DATA;
2262}
2263
Eric Laurent9d91ad52009-07-17 12:17:14 -07002264bool AudioFlinger::PlaybackThread::Track::isReady() const {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002265 if (mFillingUpStatus != FS_FILLING) return true;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002266
2267 if (mCblk->framesReady() >= mCblk->frameCount ||
2268 mCblk->forceReady) {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002269 mFillingUpStatus = FS_FILLED;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002270 mCblk->forceReady = 0;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002271 return true;
2272 }
2273 return false;
2274}
2275
Eric Laurent9d91ad52009-07-17 12:17:14 -07002276status_t AudioFlinger::PlaybackThread::Track::start()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002277{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002278 LOGV("start(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2279 sp<ThreadBase> thread = mThread.promote();
2280 if (thread != 0) {
2281 Mutex::Autolock _l(thread->mLock);
2282 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2283 playbackThread->addTrack_l(this);
2284 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002285 return NO_ERROR;
2286}
2287
Eric Laurent9d91ad52009-07-17 12:17:14 -07002288void AudioFlinger::PlaybackThread::Track::stop()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002289{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002290 LOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2291 sp<ThreadBase> thread = mThread.promote();
2292 if (thread != 0) {
2293 Mutex::Autolock _l(thread->mLock);
2294 if (mState > STOPPED) {
2295 mState = STOPPED;
2296 // If the track is not active (PAUSED and buffers full), flush buffers
2297 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2298 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
2299 reset();
2300 }
2301 LOGV("(> STOPPED) => STOPPED (%d)", mName);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002302 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002303 }
2304}
2305
Eric Laurent9d91ad52009-07-17 12:17:14 -07002306void AudioFlinger::PlaybackThread::Track::pause()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002307{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002308 LOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurent9d91ad52009-07-17 12:17:14 -07002309 sp<ThreadBase> thread = mThread.promote();
2310 if (thread != 0) {
2311 Mutex::Autolock _l(thread->mLock);
2312 if (mState == ACTIVE || mState == RESUMING) {
2313 mState = PAUSING;
2314 LOGV("ACTIVE/RESUMING => PAUSING (%d)", mName);
2315 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002316 }
2317}
2318
Eric Laurent9d91ad52009-07-17 12:17:14 -07002319void AudioFlinger::PlaybackThread::Track::flush()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002320{
2321 LOGV("flush(%d)", mName);
Eric Laurent9d91ad52009-07-17 12:17:14 -07002322 sp<ThreadBase> thread = mThread.promote();
2323 if (thread != 0) {
2324 Mutex::Autolock _l(thread->mLock);
2325 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
2326 return;
2327 }
2328 // No point remaining in PAUSED state after a flush => go to
2329 // STOPPED state
2330 mState = STOPPED;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002331
Eric Laurent9d91ad52009-07-17 12:17:14 -07002332 mCblk->lock.lock();
2333 // NOTE: reset() will reset cblk->user and cblk->server with
2334 // the risk that at the same time, the AudioMixer is trying to read
2335 // data. In this case, getNextBuffer() would return a NULL pointer
2336 // as audio buffer => the AudioMixer code MUST always test that pointer
2337 // returned by getNextBuffer() is not NULL!
2338 reset();
2339 mCblk->lock.unlock();
2340 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002341}
2342
Eric Laurent9d91ad52009-07-17 12:17:14 -07002343void AudioFlinger::PlaybackThread::Track::reset()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002344{
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002345 // Do not reset twice to avoid discarding data written just after a flush and before
2346 // the audioflinger thread detects the track is stopped.
2347 if (!mResetDone) {
2348 TrackBase::reset();
2349 // Force underrun condition to avoid false underrun callback until first data is
2350 // written to buffer
2351 mCblk->flowControlFlag = 1;
2352 mCblk->forceReady = 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002353 mFillingUpStatus = FS_FILLING;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002354 mResetDone = true;
2355 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002356}
2357
Eric Laurent9d91ad52009-07-17 12:17:14 -07002358void AudioFlinger::PlaybackThread::Track::mute(bool muted)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002359{
2360 mMute = muted;
2361}
2362
Eric Laurent9d91ad52009-07-17 12:17:14 -07002363void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002364{
2365 mVolume[0] = left;
2366 mVolume[1] = right;
2367}
2368
2369// ----------------------------------------------------------------------------
2370
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002371// RecordTrack constructor must be called with AudioFlinger::mLock held
Eric Laurent9d91ad52009-07-17 12:17:14 -07002372AudioFlinger::RecordThread::RecordTrack::RecordTrack(
2373 const wp<ThreadBase>& thread,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002374 const sp<Client>& client,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002375 uint32_t sampleRate,
2376 int format,
2377 int channelCount,
2378 int frameCount,
2379 uint32_t flags)
Eric Laurent9d91ad52009-07-17 12:17:14 -07002380 : TrackBase(thread, client, sampleRate, format,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002381 channelCount, frameCount, flags, 0),
Eric Laurent9d91ad52009-07-17 12:17:14 -07002382 mOverflow(false)
2383{
2384 LOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
2385 if (format == AudioSystem::PCM_16_BIT) {
2386 mCblk->frameSize = channelCount * sizeof(int16_t);
2387 } else if (format == AudioSystem::PCM_8_BIT) {
2388 mCblk->frameSize = channelCount * sizeof(int8_t);
2389 } else {
2390 mCblk->frameSize = sizeof(int8_t);
2391 }
2392}
2393
2394AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002395{
2396}
2397
Eric Laurent9d91ad52009-07-17 12:17:14 -07002398status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002399{
2400 audio_track_cblk_t* cblk = this->cblk();
2401 uint32_t framesAvail;
2402 uint32_t framesReq = buffer->frameCount;
2403
2404 // Check if last stepServer failed, try to step now
2405 if (mFlags & TrackBase::STEPSERVER_FAILED) {
2406 if (!step()) goto getNextBuffer_exit;
2407 LOGV("stepServer recovered");
2408 mFlags &= ~TrackBase::STEPSERVER_FAILED;
2409 }
2410
2411 framesAvail = cblk->framesAvailable_l();
2412
2413 if (LIKELY(framesAvail)) {
2414 uint32_t s = cblk->server;
2415 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
2416
2417 if (framesReq > framesAvail) {
2418 framesReq = framesAvail;
2419 }
2420 if (s + framesReq > bufferEnd) {
2421 framesReq = bufferEnd - s;
2422 }
2423
2424 buffer->raw = getBuffer(s, framesReq);
2425 if (buffer->raw == 0) goto getNextBuffer_exit;
2426
2427 buffer->frameCount = framesReq;
2428 return NO_ERROR;
2429 }
2430
2431getNextBuffer_exit:
2432 buffer->raw = 0;
2433 buffer->frameCount = 0;
2434 return NOT_ENOUGH_DATA;
2435}
2436
Eric Laurent9d91ad52009-07-17 12:17:14 -07002437status_t AudioFlinger::RecordThread::RecordTrack::start()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002438{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002439 sp<ThreadBase> thread = mThread.promote();
2440 if (thread != 0) {
2441 RecordThread *recordThread = (RecordThread *)thread.get();
2442 return recordThread->start(this);
2443 }
2444 return NO_INIT;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002445}
2446
Eric Laurent9d91ad52009-07-17 12:17:14 -07002447void AudioFlinger::RecordThread::RecordTrack::stop()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002448{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002449 sp<ThreadBase> thread = mThread.promote();
2450 if (thread != 0) {
2451 RecordThread *recordThread = (RecordThread *)thread.get();
2452 recordThread->stop(this);
2453 TrackBase::reset();
2454 // Force overerrun condition to avoid false overrun callback until first data is
2455 // read from buffer
2456 mCblk->flowControlFlag = 1;
2457 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002458}
2459
2460
2461// ----------------------------------------------------------------------------
2462
Eric Laurent9d91ad52009-07-17 12:17:14 -07002463AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
2464 const wp<ThreadBase>& thread,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002465 uint32_t sampleRate,
2466 int format,
2467 int channelCount,
2468 int frameCount)
Eric Laurent9d91ad52009-07-17 12:17:14 -07002469 : Track(thread, NULL, AudioSystem::NUM_STREAM_TYPES, sampleRate, format, channelCount, frameCount, NULL),
2470 mActive(false)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002471{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002472
2473 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
Eric Laurentf5aba822009-08-10 23:22:32 -07002474 if (mCblk != NULL) {
2475 mCblk->out = 1;
2476 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
2477 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
2478 mOutBuffer.frameCount = 0;
2479 mWaitTimeMs = (playbackThread->frameCount() * 2 * 1000) / playbackThread->sampleRate();
2480 playbackThread->mTracks.add(this);
2481 LOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, mCblk->frameCount %d, mCblk->sampleRate %d, mCblk->channels %d mBufferEnd %p mWaitTimeMs %d",
2482 mCblk, mBuffer, mCblk->buffers, mCblk->frameCount, mCblk->sampleRate, mCblk->channels, mBufferEnd, mWaitTimeMs);
2483 } else {
2484 LOGW("Error creating output track on thread %p", playbackThread);
2485 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002486}
2487
Eric Laurent9d91ad52009-07-17 12:17:14 -07002488AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002489{
Eric Laurentf5aba822009-08-10 23:22:32 -07002490 clearBufferQueue();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002491}
2492
Eric Laurent9d91ad52009-07-17 12:17:14 -07002493status_t AudioFlinger::PlaybackThread::OutputTrack::start()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002494{
2495 status_t status = Track::start();
Eric Laurent9d91ad52009-07-17 12:17:14 -07002496 if (status != NO_ERROR) {
2497 return status;
2498 }
2499
2500 mActive = true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002501 mRetryCount = 127;
2502 return status;
2503}
2504
Eric Laurent9d91ad52009-07-17 12:17:14 -07002505void AudioFlinger::PlaybackThread::OutputTrack::stop()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002506{
2507 Track::stop();
2508 clearBufferQueue();
2509 mOutBuffer.frameCount = 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002510 mActive = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002511}
2512
Eric Laurent9d91ad52009-07-17 12:17:14 -07002513bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002514{
2515 Buffer *pInBuffer;
2516 Buffer inBuffer;
2517 uint32_t channels = mCblk->channels;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002518 bool outputBufferFull = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002519 inBuffer.frameCount = frames;
2520 inBuffer.i16 = data;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002521
2522 uint32_t waitTimeLeftMs = mWaitTimeMs;
2523
2524 if (!mActive) {
2525 start();
2526 sp<ThreadBase> thread = mThread.promote();
2527 if (thread != 0) {
2528 MixerThread *mixerThread = (MixerThread *)thread.get();
2529 if (mCblk->frameCount > frames){
2530 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
2531 uint32_t startFrames = (mCblk->frameCount - frames);
2532 pInBuffer = new Buffer;
2533 pInBuffer->mBuffer = new int16_t[startFrames * channels];
2534 pInBuffer->frameCount = startFrames;
2535 pInBuffer->i16 = pInBuffer->mBuffer;
2536 memset(pInBuffer->raw, 0, startFrames * channels * sizeof(int16_t));
2537 mBufferQueue.add(pInBuffer);
2538 } else {
2539 LOGW ("OutputTrack::write() %p no more buffers in queue", this);
2540 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002541 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002542 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002543 }
2544
Eric Laurent9d91ad52009-07-17 12:17:14 -07002545 while (waitTimeLeftMs) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002546 // First write pending buffers, then new data
2547 if (mBufferQueue.size()) {
2548 pInBuffer = mBufferQueue.itemAt(0);
2549 } else {
2550 pInBuffer = &inBuffer;
2551 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002552
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002553 if (pInBuffer->frameCount == 0) {
2554 break;
2555 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002556
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002557 if (mOutBuffer.frameCount == 0) {
2558 mOutBuffer.frameCount = pInBuffer->frameCount;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002559 nsecs_t startTime = systemTime();
2560 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
2561 LOGV ("OutputTrack::write() %p no more output buffers", this);
2562 outputBufferFull = true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002563 break;
2564 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002565 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
2566// LOGV("OutputTrack::write() waitTimeMs %d waitTimeLeftMs %d", waitTimeMs, waitTimeLeftMs)
2567 if (waitTimeLeftMs >= waitTimeMs) {
2568 waitTimeLeftMs -= waitTimeMs;
2569 } else {
2570 waitTimeLeftMs = 0;
2571 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002572 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002573
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002574 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
2575 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channels * sizeof(int16_t));
2576 mCblk->stepUser(outFrames);
2577 pInBuffer->frameCount -= outFrames;
2578 pInBuffer->i16 += outFrames * channels;
2579 mOutBuffer.frameCount -= outFrames;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002580 mOutBuffer.i16 += outFrames * channels;
2581
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002582 if (pInBuffer->frameCount == 0) {
2583 if (mBufferQueue.size()) {
2584 mBufferQueue.removeAt(0);
2585 delete [] pInBuffer->mBuffer;
2586 delete pInBuffer;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002587 LOGV("OutputTrack::write() %p released overflow buffer %d", this, mBufferQueue.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002588 } else {
2589 break;
2590 }
2591 }
2592 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002593
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002594 // If we could not write all frames, allocate a buffer and queue it for next time.
2595 if (inBuffer.frameCount) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07002596 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002597 pInBuffer = new Buffer;
2598 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channels];
2599 pInBuffer->frameCount = inBuffer.frameCount;
2600 pInBuffer->i16 = pInBuffer->mBuffer;
2601 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channels * sizeof(int16_t));
2602 mBufferQueue.add(pInBuffer);
Eric Laurent9d91ad52009-07-17 12:17:14 -07002603 LOGV("OutputTrack::write() %p adding overflow buffer %d", this, mBufferQueue.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002604 } else {
Eric Laurent9d91ad52009-07-17 12:17:14 -07002605 LOGW("OutputTrack::write() %p no more overflow buffers", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002606 }
2607 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002608
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002609 // Calling write() with a 0 length buffer, means that no more data will be written:
Eric Laurent9d91ad52009-07-17 12:17:14 -07002610 // If no more buffers are pending, fill output track buffer to make sure it is started
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002611 // by output mixer.
Eric Laurent9d91ad52009-07-17 12:17:14 -07002612 if (frames == 0 && mBufferQueue.size() == 0) {
2613 if (mCblk->user < mCblk->frameCount) {
2614 frames = mCblk->frameCount - mCblk->user;
2615 pInBuffer = new Buffer;
2616 pInBuffer->mBuffer = new int16_t[frames * channels];
2617 pInBuffer->frameCount = frames;
2618 pInBuffer->i16 = pInBuffer->mBuffer;
2619 memset(pInBuffer->raw, 0, frames * channels * sizeof(int16_t));
2620 mBufferQueue.add(pInBuffer);
2621 } else {
2622 stop();
2623 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002624 }
2625
Eric Laurent9d91ad52009-07-17 12:17:14 -07002626 return outputBufferFull;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002627}
2628
Eric Laurent9d91ad52009-07-17 12:17:14 -07002629status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002630{
2631 int active;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002632 status_t result;
2633 audio_track_cblk_t* cblk = mCblk;
2634 uint32_t framesReq = buffer->frameCount;
2635
Eric Laurent9d91ad52009-07-17 12:17:14 -07002636// LOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002637 buffer->frameCount = 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002638
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002639 uint32_t framesAvail = cblk->framesAvailable();
2640
Eric Laurent9d91ad52009-07-17 12:17:14 -07002641
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002642 if (framesAvail == 0) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07002643 Mutex::Autolock _l(cblk->lock);
2644 goto start_loop_here;
2645 while (framesAvail == 0) {
2646 active = mActive;
2647 if (UNLIKELY(!active)) {
2648 LOGV("Not active and NO_MORE_BUFFERS");
2649 return AudioTrack::NO_MORE_BUFFERS;
2650 }
2651 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
2652 if (result != NO_ERROR) {
2653 return AudioTrack::NO_MORE_BUFFERS;
2654 }
2655 // read the server count again
2656 start_loop_here:
2657 framesAvail = cblk->framesAvailable_l();
2658 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002659 }
2660
Eric Laurent9d91ad52009-07-17 12:17:14 -07002661// if (framesAvail < framesReq) {
2662// return AudioTrack::NO_MORE_BUFFERS;
2663// }
2664
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002665 if (framesReq > framesAvail) {
2666 framesReq = framesAvail;
2667 }
2668
2669 uint32_t u = cblk->user;
2670 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
2671
2672 if (u + framesReq > bufferEnd) {
2673 framesReq = bufferEnd - u;
2674 }
2675
2676 buffer->frameCount = framesReq;
2677 buffer->raw = (void *)cblk->buffer(u);
2678 return NO_ERROR;
2679}
2680
2681
Eric Laurent9d91ad52009-07-17 12:17:14 -07002682void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002683{
2684 size_t size = mBufferQueue.size();
2685 Buffer *pBuffer;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002686
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002687 for (size_t i = 0; i < size; i++) {
2688 pBuffer = mBufferQueue.itemAt(i);
2689 delete [] pBuffer->mBuffer;
2690 delete pBuffer;
2691 }
2692 mBufferQueue.clear();
2693}
2694
2695// ----------------------------------------------------------------------------
2696
2697AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
2698 : RefBase(),
2699 mAudioFlinger(audioFlinger),
2700 mMemoryDealer(new MemoryDealer(1024*1024)),
2701 mPid(pid)
2702{
2703 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
2704}
2705
2706AudioFlinger::Client::~Client()
2707{
2708 mAudioFlinger->removeClient(mPid);
2709}
2710
2711const sp<MemoryDealer>& AudioFlinger::Client::heap() const
2712{
2713 return mMemoryDealer;
2714}
2715
2716// ----------------------------------------------------------------------------
2717
Eric Laurent9d91ad52009-07-17 12:17:14 -07002718AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002719 : BnAudioTrack(),
2720 mTrack(track)
2721{
2722}
2723
2724AudioFlinger::TrackHandle::~TrackHandle() {
2725 // just stop the track on deletion, associated resources
2726 // will be freed from the main thread once all pending buffers have
2727 // been played. Unless it's not in the active track list, in which
2728 // case we free everything now...
2729 mTrack->destroy();
2730}
2731
2732status_t AudioFlinger::TrackHandle::start() {
2733 return mTrack->start();
2734}
2735
2736void AudioFlinger::TrackHandle::stop() {
2737 mTrack->stop();
2738}
2739
2740void AudioFlinger::TrackHandle::flush() {
2741 mTrack->flush();
2742}
2743
2744void AudioFlinger::TrackHandle::mute(bool e) {
2745 mTrack->mute(e);
2746}
2747
2748void AudioFlinger::TrackHandle::pause() {
2749 mTrack->pause();
2750}
2751
2752void AudioFlinger::TrackHandle::setVolume(float left, float right) {
2753 mTrack->setVolume(left, right);
2754}
2755
2756sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
2757 return mTrack->getCblk();
2758}
2759
2760status_t AudioFlinger::TrackHandle::onTransact(
2761 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2762{
2763 return BnAudioTrack::onTransact(code, data, reply, flags);
2764}
2765
2766// ----------------------------------------------------------------------------
2767
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002768sp<IAudioRecord> AudioFlinger::openRecord(
2769 pid_t pid,
Eric Laurente0e9ecc2009-07-28 08:44:33 -07002770 int input,
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002771 uint32_t sampleRate,
2772 int format,
2773 int channelCount,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002774 int frameCount,
2775 uint32_t flags,
2776 status_t *status)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002777{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002778 sp<RecordThread::RecordTrack> recordTrack;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002779 sp<RecordHandle> recordHandle;
2780 sp<Client> client;
2781 wp<Client> wclient;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002782 status_t lStatus;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002783 RecordThread *thread;
2784 size_t inFrameCount;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002785
2786 // check calling permissions
2787 if (!recordingAllowed()) {
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002788 lStatus = PERMISSION_DENIED;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002789 goto Exit;
2790 }
2791
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002792 // add client to list
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002793 { // scope for mLock
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002794 Mutex::Autolock _l(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07002795 thread = checkRecordThread_l(input);
2796 if (thread == NULL) {
2797 lStatus = BAD_VALUE;
2798 goto Exit;
2799 }
2800
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002801 wclient = mClients.valueFor(pid);
2802 if (wclient != NULL) {
2803 client = wclient.promote();
2804 } else {
2805 client = new Client(this, pid);
2806 mClients.add(pid, client);
2807 }
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002808
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002809 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent9d91ad52009-07-17 12:17:14 -07002810 recordTrack = new RecordThread::RecordTrack(thread, client, sampleRate,
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002811 format, channelCount, frameCount, flags);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002812 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002813 if (recordTrack->getCblk() == NULL) {
2814 recordTrack.clear();
2815 lStatus = NO_MEMORY;
2816 goto Exit;
2817 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002818
2819 // return to handle to client
2820 recordHandle = new RecordHandle(recordTrack);
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002821 lStatus = NO_ERROR;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002822
2823Exit:
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002824 if (status) {
2825 *status = lStatus;
2826 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002827 return recordHandle;
2828}
2829
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002830// ----------------------------------------------------------------------------
2831
Eric Laurent9d91ad52009-07-17 12:17:14 -07002832AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002833 : BnAudioRecord(),
2834 mRecordTrack(recordTrack)
2835{
2836}
2837
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002838AudioFlinger::RecordHandle::~RecordHandle() {
2839 stop();
2840}
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002841
2842status_t AudioFlinger::RecordHandle::start() {
2843 LOGV("RecordHandle::start()");
2844 return mRecordTrack->start();
2845}
2846
2847void AudioFlinger::RecordHandle::stop() {
2848 LOGV("RecordHandle::stop()");
2849 mRecordTrack->stop();
2850}
2851
2852sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
2853 return mRecordTrack->getCblk();
2854}
2855
2856status_t AudioFlinger::RecordHandle::onTransact(
2857 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2858{
2859 return BnAudioRecord::onTransact(code, data, reply, flags);
2860}
2861
2862// ----------------------------------------------------------------------------
2863
Eric Laurent9d91ad52009-07-17 12:17:14 -07002864AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger, AudioStreamIn *input, uint32_t sampleRate, uint32_t channels) :
2865 ThreadBase(audioFlinger),
2866 mInput(input), mResampler(0), mRsmpOutBuffer(0), mRsmpInBuffer(0)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002867{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002868 mReqChannelCount = AudioSystem::popCount(channels);
2869 mReqSampleRate = sampleRate;
2870 readInputParameters();
2871 sendConfigEvent(AudioSystem::INPUT_OPENED);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002872}
2873
Eric Laurent9d91ad52009-07-17 12:17:14 -07002874
2875AudioFlinger::RecordThread::~RecordThread()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002876{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002877 delete[] mRsmpInBuffer;
2878 if (mResampler != 0) {
2879 delete mResampler;
2880 delete[] mRsmpOutBuffer;
2881 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002882}
2883
Eric Laurent9d91ad52009-07-17 12:17:14 -07002884void AudioFlinger::RecordThread::onFirstRef()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002885{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002886 const size_t SIZE = 256;
2887 char buffer[SIZE];
2888
2889 snprintf(buffer, SIZE, "Record Thread %p", this);
2890
2891 run(buffer, PRIORITY_URGENT_AUDIO);
2892}
2893bool AudioFlinger::RecordThread::threadLoop()
2894{
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002895 AudioBufferProvider::Buffer buffer;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002896 sp<RecordTrack> activeTrack;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002897
2898 // start recording
2899 while (!exitPending()) {
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002900
Eric Laurent9d91ad52009-07-17 12:17:14 -07002901 processConfigEvents();
2902
2903 { // scope for mLock
2904 Mutex::Autolock _l(mLock);
2905 checkForNewParameters_l();
2906 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
2907 if (!mStandby) {
2908 mInput->standby();
2909 mStandby = true;
2910 }
2911
2912 if (exitPending()) break;
2913
2914 LOGV("RecordThread: loop stopping");
2915 // go to sleep
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002916 mWaitWorkCV.wait(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07002917 LOGV("RecordThread: loop starting");
2918 continue;
2919 }
2920 if (mActiveTrack != 0) {
2921 if (mActiveTrack->mState == TrackBase::PAUSING) {
2922 mActiveTrack.clear();
2923 mStartStopCond.broadcast();
2924 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
2925 mRsmpInIndex = mFrameCount;
2926 if (mReqChannelCount != mActiveTrack->channelCount()) {
2927 mActiveTrack.clear();
2928 } else {
Eric Laurent9e7b8192009-08-10 02:41:54 -07002929 mActiveTrack->mState = TrackBase::ACTIVE;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002930 }
2931 mStartStopCond.broadcast();
2932 }
2933 mStandby = false;
2934 }
2935 }
2936
2937 if (mActiveTrack != 0) {
2938 buffer.frameCount = mFrameCount;
2939 if (LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
2940 size_t framesOut = buffer.frameCount;
2941 if (mResampler == 0) {
2942 // no resampling
2943 while (framesOut) {
2944 size_t framesIn = mFrameCount - mRsmpInIndex;
2945 if (framesIn) {
2946 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
2947 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
2948 if (framesIn > framesOut)
2949 framesIn = framesOut;
2950 mRsmpInIndex += framesIn;
2951 framesOut -= framesIn;
2952 if (mChannelCount == mReqChannelCount ||
2953 mFormat != AudioSystem::PCM_16_BIT) {
2954 memcpy(dst, src, framesIn * mFrameSize);
2955 } else {
2956 int16_t *src16 = (int16_t *)src;
2957 int16_t *dst16 = (int16_t *)dst;
2958 if (mChannelCount == 1) {
2959 while (framesIn--) {
2960 *dst16++ = *src16;
2961 *dst16++ = *src16++;
2962 }
2963 } else {
2964 while (framesIn--) {
2965 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
2966 src16 += 2;
2967 }
2968 }
2969 }
2970 }
2971 if (framesOut && mFrameCount == mRsmpInIndex) {
2972 ssize_t bytesRead;
2973 if (framesOut == mFrameCount &&
2974 (mChannelCount == mReqChannelCount || mFormat != AudioSystem::PCM_16_BIT)) {
2975 bytesRead = mInput->read(buffer.raw, mInputBytes);
2976 framesOut = 0;
2977 } else {
2978 bytesRead = mInput->read(mRsmpInBuffer, mInputBytes);
2979 mRsmpInIndex = 0;
2980 }
2981 if (bytesRead < 0) {
2982 LOGE("Error reading audio input");
2983 sleep(1);
2984 mRsmpInIndex = mFrameCount;
2985 framesOut = 0;
2986 buffer.frameCount = 0;
2987 }
2988 }
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002989 }
2990 } else {
Eric Laurent9d91ad52009-07-17 12:17:14 -07002991 // resampling
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002992
Eric Laurent9d91ad52009-07-17 12:17:14 -07002993 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
2994 // alter output frame count as if we were expecting stereo samples
2995 if (mChannelCount == 1 && mReqChannelCount == 1) {
2996 framesOut >>= 1;
2997 }
2998 mResampler->resample(mRsmpOutBuffer, framesOut, this);
2999 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
3000 // are 32 bit aligned which should be always true.
3001 if (mChannelCount == 2 && mReqChannelCount == 1) {
3002 AudioMixer::ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
3003 // the resampler always outputs stereo samples: do post stereo to mono conversion
3004 int16_t *src = (int16_t *)mRsmpOutBuffer;
3005 int16_t *dst = buffer.i16;
3006 while (framesOut--) {
3007 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
3008 src += 2;
3009 }
3010 } else {
3011 AudioMixer::ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
3012 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003013
Eric Laurent9d91ad52009-07-17 12:17:14 -07003014 }
3015 mActiveTrack->releaseBuffer(&buffer);
3016 mActiveTrack->overflow();
3017 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003018 // client isn't retrieving buffers fast enough
3019 else {
Eric Laurent9d91ad52009-07-17 12:17:14 -07003020 if (!mActiveTrack->setOverflow())
3021 LOGW("RecordThread: buffer overflow");
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003022 // Release the processor for a while before asking for a new buffer.
3023 // This will give the application more chance to read from the buffer and
3024 // clear the overflow.
3025 usleep(5000);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003026 }
3027 }
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003028 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003029
Eric Laurent9d91ad52009-07-17 12:17:14 -07003030 if (!mStandby) {
3031 mInput->standby();
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003032 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003033 mActiveTrack.clear();
3034
3035 sendConfigEvent(AudioSystem::INPUT_CLOSED);
3036 processConfigEvents();
3037
3038 LOGV("RecordThread %p exiting", this);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003039 return false;
3040}
3041
Eric Laurent9d91ad52009-07-17 12:17:14 -07003042status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003043{
Eric Laurent9d91ad52009-07-17 12:17:14 -07003044 LOGV("RecordThread::start");
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003045 AutoMutex lock(&mLock);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003046
Eric Laurent9d91ad52009-07-17 12:17:14 -07003047 if (mActiveTrack != 0) {
3048 if (recordTrack != mActiveTrack.get()) return -EBUSY;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003049
Eric Laurent9d91ad52009-07-17 12:17:14 -07003050 if (mActiveTrack->mState == TrackBase::PAUSING) mActiveTrack->mState = TrackBase::RESUMING;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003051
Eric Laurent9d91ad52009-07-17 12:17:14 -07003052 return NO_ERROR;
3053 }
3054
3055 mActiveTrack = recordTrack;
3056 mActiveTrack->mState = TrackBase::RESUMING;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003057 // signal thread to start
3058 LOGV("Signal record thread");
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003059 mWaitWorkCV.signal();
Eric Laurent9d91ad52009-07-17 12:17:14 -07003060 mStartStopCond.wait(mLock);
3061 if (mActiveTrack != 0) {
3062 LOGV("Record started OK");
3063 return NO_ERROR;
3064 } else {
3065 LOGV("Record failed to start");
3066 return BAD_VALUE;
3067 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003068}
3069
Eric Laurent9d91ad52009-07-17 12:17:14 -07003070void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
3071 LOGV("RecordThread::stop");
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003072 AutoMutex lock(&mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003073 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
3074 mActiveTrack->mState = TrackBase::PAUSING;
3075 mStartStopCond.wait(mLock);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003076 }
3077}
3078
Eric Laurent9d91ad52009-07-17 12:17:14 -07003079status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003080{
3081 const size_t SIZE = 256;
3082 char buffer[SIZE];
3083 String8 result;
3084 pid_t pid = 0;
3085
Eric Laurent9d91ad52009-07-17 12:17:14 -07003086 if (mActiveTrack != 0 && mActiveTrack->mClient != 0) {
3087 snprintf(buffer, SIZE, "Record client pid: %d\n", mActiveTrack->mClient->pid());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003088 result.append(buffer);
3089 } else {
3090 result.append("No record client\n");
3091 }
3092 write(fd, result.string(), result.size());
3093 return NO_ERROR;
3094}
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003095
Eric Laurent9d91ad52009-07-17 12:17:14 -07003096status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3097{
3098 size_t framesReq = buffer->frameCount;
3099 size_t framesReady = mFrameCount - mRsmpInIndex;
3100 int channelCount;
3101
3102 if (framesReady == 0) {
3103 ssize_t bytesRead = mInput->read(mRsmpInBuffer, mInputBytes);
3104 if (bytesRead < 0) {
3105 LOGE("RecordThread::getNextBuffer() Error reading audio input");
3106 sleep(1);
3107 buffer->raw = 0;
3108 buffer->frameCount = 0;
3109 return NOT_ENOUGH_DATA;
3110 }
3111 mRsmpInIndex = 0;
3112 framesReady = mFrameCount;
3113 }
3114
3115 if (framesReq > framesReady) {
3116 framesReq = framesReady;
3117 }
3118
3119 if (mChannelCount == 1 && mReqChannelCount == 2) {
3120 channelCount = 1;
3121 } else {
3122 channelCount = 2;
3123 }
3124 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
3125 buffer->frameCount = framesReq;
3126 return NO_ERROR;
3127}
3128
3129void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3130{
3131 mRsmpInIndex += buffer->frameCount;
3132 buffer->frameCount = 0;
3133}
3134
3135bool AudioFlinger::RecordThread::checkForNewParameters_l()
3136{
3137 bool reconfig = false;
3138
Eric Laurent3464c012009-08-04 09:45:33 -07003139 while (!mNewParameters.isEmpty()) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07003140 status_t status = NO_ERROR;
Eric Laurent3464c012009-08-04 09:45:33 -07003141 String8 keyValuePair = mNewParameters[0];
3142 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003143 int value;
3144 int reqFormat = mFormat;
3145 int reqSamplingRate = mReqSampleRate;
3146 int reqChannelCount = mReqChannelCount;
Eric Laurent3464c012009-08-04 09:45:33 -07003147
3148 mNewParameters.removeAt(0);
3149
Eric Laurent9d91ad52009-07-17 12:17:14 -07003150 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3151 reqSamplingRate = value;
3152 reconfig = true;
3153 }
3154 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
3155 reqFormat = value;
3156 reconfig = true;
3157 }
3158 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
3159 reqChannelCount = AudioSystem::popCount(value);
3160 reconfig = true;
3161 }
3162 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3163 // do not accept frame count changes if tracks are open as the track buffer
3164 // size depends on frame count and correct behavior would not be garantied
3165 // if frame count is changed after track creation
3166 if (mActiveTrack != 0) {
3167 status = INVALID_OPERATION;
3168 } else {
3169 reconfig = true;
3170 }
3171 }
3172 if (status == NO_ERROR) {
Eric Laurent3464c012009-08-04 09:45:33 -07003173 status = mInput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003174 if (status == INVALID_OPERATION) {
3175 mInput->standby();
Eric Laurent3464c012009-08-04 09:45:33 -07003176 status = mInput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003177 }
3178 if (reconfig) {
3179 if (status == BAD_VALUE &&
3180 reqFormat == mInput->format() && reqFormat == AudioSystem::PCM_16_BIT &&
3181 ((int)mInput->sampleRate() <= 2 * reqSamplingRate) &&
3182 (AudioSystem::popCount(mInput->channels()) < 3) && (reqChannelCount < 3)) {
3183 status = NO_ERROR;
3184 }
3185 if (status == NO_ERROR) {
3186 readInputParameters();
Eric Laurent3464c012009-08-04 09:45:33 -07003187 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003188 }
3189 }
3190 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003191 mParamStatus = status;
3192 mParamCond.signal();
Eric Laurent3464c012009-08-04 09:45:33 -07003193 mWaitWorkCV.wait(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003194 }
3195 return reconfig;
3196}
3197
3198String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
3199{
3200 return mInput->getParameters(keys);
3201}
3202
3203void AudioFlinger::RecordThread::audioConfigChanged(int event, int param) {
3204 AudioSystem::OutputDescriptor desc;
3205 void *param2 = 0;
3206
3207 switch (event) {
3208 case AudioSystem::INPUT_OPENED:
3209 case AudioSystem::INPUT_CONFIG_CHANGED:
3210 desc.channels = mChannelCount;
3211 desc.samplingRate = mSampleRate;
3212 desc.format = mFormat;
3213 desc.frameCount = mFrameCount;
3214 desc.latency = 0;
3215 param2 = &desc;
3216 break;
3217
3218 case AudioSystem::INPUT_CLOSED:
3219 default:
3220 break;
3221 }
3222 mAudioFlinger->audioConfigChanged(event, this, param2);
3223}
3224
3225void AudioFlinger::RecordThread::readInputParameters()
3226{
3227 if (mRsmpInBuffer) delete mRsmpInBuffer;
3228 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
3229 if (mResampler) delete mResampler;
3230 mResampler = 0;
3231
3232 mSampleRate = mInput->sampleRate();
3233 mChannelCount = AudioSystem::popCount(mInput->channels());
3234 mFormat = mInput->format();
3235 mFrameSize = mInput->frameSize();
3236 mInputBytes = mInput->bufferSize();
3237 mFrameCount = mInputBytes / mFrameSize;
3238 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
3239
3240 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
3241 {
3242 int channelCount;
3243 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
3244 // stereo to mono post process as the resampler always outputs stereo.
3245 if (mChannelCount == 1 && mReqChannelCount == 2) {
3246 channelCount = 1;
3247 } else {
3248 channelCount = 2;
3249 }
3250 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
3251 mResampler->setSampleRate(mSampleRate);
3252 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
3253 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
3254
3255 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
3256 if (mChannelCount == 1 && mReqChannelCount == 1) {
3257 mFrameCount >>= 1;
3258 }
3259
3260 }
3261 mRsmpInIndex = mFrameCount;
3262}
3263
3264// ----------------------------------------------------------------------------
3265
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003266int AudioFlinger::openOutput(uint32_t *pDevices,
Eric Laurent9d91ad52009-07-17 12:17:14 -07003267 uint32_t *pSamplingRate,
3268 uint32_t *pFormat,
3269 uint32_t *pChannels,
3270 uint32_t *pLatencyMs,
3271 uint32_t flags)
3272{
3273 status_t status;
3274 PlaybackThread *thread = NULL;
3275 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
3276 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
3277 uint32_t format = pFormat ? *pFormat : 0;
3278 uint32_t channels = pChannels ? *pChannels : 0;
3279 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
3280
3281 LOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
3282 pDevices ? *pDevices : 0,
3283 samplingRate,
3284 format,
3285 channels,
3286 flags);
3287
3288 if (pDevices == NULL || *pDevices == 0) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003289 return 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003290 }
3291 Mutex::Autolock _l(mLock);
3292
3293 AudioStreamOut *output = mAudioHardware->openOutputStream(*pDevices,
3294 (int *)&format,
3295 &channels,
3296 &samplingRate,
3297 &status);
3298 LOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
3299 output,
3300 samplingRate,
3301 format,
3302 channels,
3303 status);
3304
3305 mHardwareStatus = AUDIO_HW_IDLE;
3306 if (output != 0) {
3307 if ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) ||
3308 (format != AudioSystem::PCM_16_BIT) ||
3309 (channels != AudioSystem::CHANNEL_OUT_STEREO)) {
3310 thread = new DirectOutputThread(this, output);
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003311 LOGV("openOutput() created direct output: ID %d thread %p", (mNextThreadId + 1), thread);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003312 } else {
3313 thread = new MixerThread(this, output);
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003314 LOGV("openOutput() created mixer output: ID %d thread %p", (mNextThreadId + 1), thread);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003315 }
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003316 mPlaybackThreads.add(++mNextThreadId, thread);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003317
3318 if (pSamplingRate) *pSamplingRate = samplingRate;
3319 if (pFormat) *pFormat = format;
3320 if (pChannels) *pChannels = channels;
3321 if (pLatencyMs) *pLatencyMs = thread->latency();
3322 }
3323
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003324 return mNextThreadId;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003325}
3326
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003327int AudioFlinger::openDuplicateOutput(int output1, int output2)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003328{
3329 Mutex::Autolock _l(mLock);
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003330 MixerThread *thread1 = checkMixerThread_l(output1);
3331 MixerThread *thread2 = checkMixerThread_l(output2);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003332
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003333 if (thread1 == NULL || thread2 == NULL) {
3334 LOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
3335 return 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003336 }
3337
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003338
3339 DuplicatingThread *thread = new DuplicatingThread(this, thread1);
3340 thread->addOutputTrack(thread2);
3341 mPlaybackThreads.add(++mNextThreadId, thread);
3342 return mNextThreadId;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003343}
3344
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003345status_t AudioFlinger::closeOutput(int output)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003346{
Eric Laurentdae20d92009-08-04 08:37:05 -07003347 // keep strong reference on the playback thread so that
3348 // it is not destroyed while exit() is executed
3349 sp <PlaybackThread> thread;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003350 {
3351 Mutex::Autolock _l(mLock);
3352 thread = checkPlaybackThread_l(output);
3353 if (thread == NULL) {
3354 return BAD_VALUE;
3355 }
3356
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003357 LOGV("closeOutput() %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003358
3359 if (thread->type() == PlaybackThread::MIXER) {
3360 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003361 if (mPlaybackThreads.valueAt(i)->type() == PlaybackThread::DUPLICATING) {
3362 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Eric Laurentdae20d92009-08-04 08:37:05 -07003363 dupThread->removeOutputTrack((MixerThread *)thread.get());
Eric Laurent9d91ad52009-07-17 12:17:14 -07003364 }
3365 }
3366 }
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003367 mPlaybackThreads.removeItem(output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003368 }
3369 thread->exit();
3370
Eric Laurentdae20d92009-08-04 08:37:05 -07003371 if (thread->type() != PlaybackThread::DUPLICATING) {
3372 mAudioHardware->closeOutputStream(thread->getOutput());
3373 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003374 return NO_ERROR;
3375}
3376
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003377status_t AudioFlinger::suspendOutput(int output)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003378{
3379 Mutex::Autolock _l(mLock);
3380 PlaybackThread *thread = checkPlaybackThread_l(output);
3381
3382 if (thread == NULL) {
3383 return BAD_VALUE;
3384 }
3385
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003386 LOGV("suspendOutput() %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003387 thread->suspend();
3388
3389 return NO_ERROR;
3390}
3391
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003392status_t AudioFlinger::restoreOutput(int output)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003393{
3394 Mutex::Autolock _l(mLock);
3395 PlaybackThread *thread = checkPlaybackThread_l(output);
3396
3397 if (thread == NULL) {
3398 return BAD_VALUE;
3399 }
3400
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003401 LOGV("restoreOutput() %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003402
3403 thread->restore();
3404
3405 return NO_ERROR;
3406}
3407
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003408int AudioFlinger::openInput(uint32_t *pDevices,
Eric Laurent9d91ad52009-07-17 12:17:14 -07003409 uint32_t *pSamplingRate,
3410 uint32_t *pFormat,
3411 uint32_t *pChannels,
3412 uint32_t acoustics)
3413{
3414 status_t status;
3415 RecordThread *thread = NULL;
3416 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
3417 uint32_t format = pFormat ? *pFormat : 0;
3418 uint32_t channels = pChannels ? *pChannels : 0;
3419 uint32_t reqSamplingRate = samplingRate;
3420 uint32_t reqFormat = format;
3421 uint32_t reqChannels = channels;
3422
3423 if (pDevices == NULL || *pDevices == 0) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003424 return 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003425 }
3426 Mutex::Autolock _l(mLock);
3427
3428 AudioStreamIn *input = mAudioHardware->openInputStream(*pDevices,
3429 (int *)&format,
3430 &channels,
3431 &samplingRate,
3432 &status,
3433 (AudioSystem::audio_in_acoustics)acoustics);
3434 LOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
3435 input,
3436 samplingRate,
3437 format,
3438 channels,
3439 acoustics,
3440 status);
3441
3442 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
3443 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
3444 // or stereo to mono conversions on 16 bit PCM inputs.
3445 if (input == 0 && status == BAD_VALUE &&
3446 reqFormat == format && format == AudioSystem::PCM_16_BIT &&
3447 (samplingRate <= 2 * reqSamplingRate) &&
3448 (AudioSystem::popCount(channels) < 3) && (AudioSystem::popCount(reqChannels) < 3)) {
3449 LOGV("openInput() reopening with proposed sampling rate and channels");
3450 input = mAudioHardware->openInputStream(*pDevices,
3451 (int *)&format,
3452 &channels,
3453 &samplingRate,
3454 &status,
3455 (AudioSystem::audio_in_acoustics)acoustics);
3456 }
3457
3458 if (input != 0) {
3459 // Start record thread
3460 thread = new RecordThread(this, input, reqSamplingRate, reqChannels);
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003461 mRecordThreads.add(++mNextThreadId, thread);
3462 LOGV("openInput() created record thread: ID %d thread %p", mNextThreadId, thread);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003463 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
3464 if (pFormat) *pFormat = format;
3465 if (pChannels) *pChannels = reqChannels;
3466
3467 input->standby();
3468 }
3469
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003470 return mNextThreadId;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003471}
3472
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003473status_t AudioFlinger::closeInput(int input)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003474{
Eric Laurentdae20d92009-08-04 08:37:05 -07003475 // keep strong reference on the record thread so that
3476 // it is not destroyed while exit() is executed
3477 sp <RecordThread> thread;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003478 {
3479 Mutex::Autolock _l(mLock);
3480 thread = checkRecordThread_l(input);
3481 if (thread == NULL) {
3482 return BAD_VALUE;
3483 }
3484
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003485 LOGV("closeInput() %d", input);
3486 mRecordThreads.removeItem(input);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003487 }
3488 thread->exit();
3489
Eric Laurentdae20d92009-08-04 08:37:05 -07003490 mAudioHardware->closeInputStream(thread->getInput());
3491
Eric Laurent9d91ad52009-07-17 12:17:14 -07003492 return NO_ERROR;
3493}
3494
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003495status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003496{
3497 Mutex::Autolock _l(mLock);
3498 MixerThread *dstThread = checkMixerThread_l(output);
3499 if (dstThread == NULL) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003500 LOGW("setStreamOutput() bad output id %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003501 return BAD_VALUE;
3502 }
3503
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003504 LOGV("setStreamOutput() stream %d to output %d", stream, output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003505
3506 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003507 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent9d91ad52009-07-17 12:17:14 -07003508 if (thread != dstThread &&
3509 thread->type() != PlaybackThread::DIRECT) {
3510 MixerThread *srcThread = (MixerThread *)thread;
3511 SortedVector < sp<MixerThread::Track> > tracks;
3512 SortedVector < wp<MixerThread::Track> > activeTracks;
3513 srcThread->getTracks(tracks, activeTracks, stream);
3514 if (tracks.size()) {
3515 dstThread->putTracks(tracks, activeTracks);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003516 }
3517 }
3518 }
3519
Eric Laurent06437712009-09-01 05:56:26 -07003520 dstThread->sendConfigEvent(AudioSystem::STREAM_CONFIG_CHANGED, stream);
3521
Eric Laurent9d91ad52009-07-17 12:17:14 -07003522 return NO_ERROR;
3523}
3524
3525// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003526AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
Eric Laurent9d91ad52009-07-17 12:17:14 -07003527{
3528 PlaybackThread *thread = NULL;
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003529 if (mPlaybackThreads.indexOfKey(output) >= 0) {
3530 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
Eric Laurent9d91ad52009-07-17 12:17:14 -07003531 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003532 return thread;
3533}
3534
3535// checkMixerThread_l() must be called with AudioFlinger::mLock held
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003536AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
Eric Laurent9d91ad52009-07-17 12:17:14 -07003537{
3538 PlaybackThread *thread = checkPlaybackThread_l(output);
3539 if (thread != NULL) {
3540 if (thread->type() == PlaybackThread::DIRECT) {
3541 thread = NULL;
3542 }
3543 }
3544 return (MixerThread *)thread;
3545}
3546
3547// checkRecordThread_l() must be called with AudioFlinger::mLock held
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003548AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
Eric Laurent9d91ad52009-07-17 12:17:14 -07003549{
3550 RecordThread *thread = NULL;
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003551 if (mRecordThreads.indexOfKey(input) >= 0) {
3552 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
Eric Laurent9d91ad52009-07-17 12:17:14 -07003553 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003554 return thread;
3555}
3556
3557// ----------------------------------------------------------------------------
3558
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003559status_t AudioFlinger::onTransact(
3560 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3561{
3562 return BnAudioFlinger::onTransact(code, data, reply, flags);
3563}
3564
3565// ----------------------------------------------------------------------------
Eric Laurent9d91ad52009-07-17 12:17:14 -07003566
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003567void AudioFlinger::instantiate() {
3568 defaultServiceManager()->addService(
3569 String16("media.audio_flinger"), new AudioFlinger());
3570}
3571
3572}; // namespace android