blob: e534447abfdafdd5cc61d877ee7c204fca3b8613 [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 {
Eric Laurent0f8ab672009-09-17 05:12:56 -0700310 // remove local strong reference to Client before deleting the Track so that the Client
311 // destructor is called by the TrackBase destructor with mLock held
312 client.clear();
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700313 track.clear();
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800314 }
315
316Exit:
317 if(status) {
318 *status = lStatus;
319 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700320 return trackHandle;
321}
322
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700323uint32_t AudioFlinger::sampleRate(int output) const
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700324{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700325 Mutex::Autolock _l(mLock);
326 PlaybackThread *thread = checkPlaybackThread_l(output);
327 if (thread == NULL) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700328 LOGW("sampleRate() unknown thread %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700329 return 0;
330 }
331 return thread->sampleRate();
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700332}
333
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700334int AudioFlinger::channelCount(int output) const
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700335{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700336 Mutex::Autolock _l(mLock);
337 PlaybackThread *thread = checkPlaybackThread_l(output);
338 if (thread == NULL) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700339 LOGW("channelCount() unknown thread %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700340 return 0;
341 }
342 return thread->channelCount();
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700343}
344
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700345int AudioFlinger::format(int output) const
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700346{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700347 Mutex::Autolock _l(mLock);
348 PlaybackThread *thread = checkPlaybackThread_l(output);
349 if (thread == NULL) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700350 LOGW("format() unknown thread %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700351 return 0;
352 }
353 return thread->format();
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700354}
355
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700356size_t AudioFlinger::frameCount(int output) const
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700357{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700358 Mutex::Autolock _l(mLock);
359 PlaybackThread *thread = checkPlaybackThread_l(output);
360 if (thread == NULL) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700361 LOGW("frameCount() unknown thread %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700362 return 0;
363 }
364 return thread->frameCount();
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700365}
366
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700367uint32_t AudioFlinger::latency(int output) const
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800368{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700369 Mutex::Autolock _l(mLock);
370 PlaybackThread *thread = checkPlaybackThread_l(output);
371 if (thread == NULL) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700372 LOGW("latency() unknown thread %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700373 return 0;
374 }
375 return thread->latency();
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800376}
377
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700378status_t AudioFlinger::setMasterVolume(float value)
379{
380 // check calling permissions
381 if (!settingsAllowed()) {
382 return PERMISSION_DENIED;
383 }
384
385 // when hw supports master volume, don't scale in sw mixer
386 AutoMutex lock(mHardwareLock);
387 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
388 if (mAudioHardware->setMasterVolume(value) == NO_ERROR) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800389 value = 1.0f;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700390 }
391 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent9d91ad52009-07-17 12:17:14 -0700392
393 mMasterVolume = value;
394 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700395 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700396
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700397 return NO_ERROR;
398}
399
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700400status_t AudioFlinger::setMode(int mode)
401{
402 // check calling permissions
403 if (!settingsAllowed()) {
404 return PERMISSION_DENIED;
405 }
406 if ((mode < 0) || (mode >= AudioSystem::NUM_MODES)) {
407 LOGW("Illegal value: setMode(%d)", mode);
408 return BAD_VALUE;
409 }
410
411 AutoMutex lock(mHardwareLock);
412 mHardwareStatus = AUDIO_HW_SET_MODE;
413 status_t ret = mAudioHardware->setMode(mode);
414 mHardwareStatus = AUDIO_HW_IDLE;
415 return ret;
416}
417
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700418status_t AudioFlinger::setMicMute(bool state)
419{
420 // check calling permissions
421 if (!settingsAllowed()) {
422 return PERMISSION_DENIED;
423 }
424
425 AutoMutex lock(mHardwareLock);
426 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
427 status_t ret = mAudioHardware->setMicMute(state);
428 mHardwareStatus = AUDIO_HW_IDLE;
429 return ret;
430}
431
432bool AudioFlinger::getMicMute() const
433{
434 bool state = AudioSystem::MODE_INVALID;
435 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
436 mAudioHardware->getMicMute(&state);
437 mHardwareStatus = AUDIO_HW_IDLE;
438 return state;
439}
440
441status_t AudioFlinger::setMasterMute(bool muted)
442{
443 // check calling permissions
444 if (!settingsAllowed()) {
445 return PERMISSION_DENIED;
446 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700447
448 mMasterMute = muted;
449 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700450 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700451
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700452 return NO_ERROR;
453}
454
455float AudioFlinger::masterVolume() const
456{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700457 return mMasterVolume;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700458}
459
460bool AudioFlinger::masterMute() const
461{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700462 return mMasterMute;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700463}
464
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700465status_t AudioFlinger::setStreamVolume(int stream, float value, int output)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700466{
467 // check calling permissions
468 if (!settingsAllowed()) {
469 return PERMISSION_DENIED;
470 }
471
Eric Laurent9d91ad52009-07-17 12:17:14 -0700472 if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700473 return BAD_VALUE;
474 }
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800475
Eric Laurent9d91ad52009-07-17 12:17:14 -0700476 AutoMutex lock(mLock);
477 PlaybackThread *thread = NULL;
478 if (output) {
479 thread = checkPlaybackThread_l(output);
480 if (thread == NULL) {
481 return BAD_VALUE;
482 }
483 }
484
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700485 status_t ret = NO_ERROR;
Eric Laurent9d91ad52009-07-17 12:17:14 -0700486
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800487 if (stream == AudioSystem::VOICE_CALL ||
488 stream == AudioSystem::BLUETOOTH_SCO) {
Eric Laurent4dd495b2009-04-21 07:56:33 -0700489 float hwValue;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800490 if (stream == AudioSystem::VOICE_CALL) {
Jean-Baptiste Queru732ca392009-03-18 11:33:14 -0700491 hwValue = (float)AudioSystem::logToLinear(value)/100.0f;
Eric Laurent4dd495b2009-04-21 07:56:33 -0700492 // offset value to reflect actual hardware volume that never reaches 0
493 // 1% corresponds roughly to first step in VOICE_CALL stream volume setting (see AudioService.java)
494 value = 0.01 + 0.99 * value;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800495 } else { // (type == AudioSystem::BLUETOOTH_SCO)
Jean-Baptiste Queru732ca392009-03-18 11:33:14 -0700496 hwValue = 1.0f;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800497 }
498
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700499 AutoMutex lock(mHardwareLock);
500 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
Jean-Baptiste Queru732ca392009-03-18 11:33:14 -0700501 ret = mAudioHardware->setVoiceVolume(hwValue);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700502 mHardwareStatus = AUDIO_HW_IDLE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800503
Eric Laurent9d91ad52009-07-17 12:17:14 -0700504 }
505
506 mStreamTypes[stream].volume = value;
507
508 if (thread == NULL) {
509 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700510 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700511
512 } else {
513 thread->setStreamVolume(stream, value);
514 }
Eric Laurent4dd495b2009-04-21 07:56:33 -0700515
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700516 return ret;
517}
518
519status_t AudioFlinger::setStreamMute(int stream, bool muted)
520{
521 // check calling permissions
522 if (!settingsAllowed()) {
523 return PERMISSION_DENIED;
524 }
525
Eric Laurent9d91ad52009-07-17 12:17:14 -0700526 if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES ||
Eric Laurentb1596ee2009-03-26 01:57:59 -0700527 uint32_t(stream) == AudioSystem::ENFORCED_AUDIBLE) {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700528 return BAD_VALUE;
529 }
The Android Open Source Project4f68be12009-03-18 17:39:46 -0700530
Eric Laurent9d91ad52009-07-17 12:17:14 -0700531 mStreamTypes[stream].mute = muted;
532 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700533 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800534
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700535 return NO_ERROR;
536}
537
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700538float AudioFlinger::streamVolume(int stream, int output) const
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700539{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700540 if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700541 return 0.0f;
542 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700543
544 AutoMutex lock(mLock);
545 float volume;
546 if (output) {
547 PlaybackThread *thread = checkPlaybackThread_l(output);
548 if (thread == NULL) {
549 return 0.0f;
550 }
551 volume = thread->streamVolume(stream);
552 } else {
553 volume = mStreamTypes[stream].volume;
554 }
555
Eric Laurent4dd495b2009-04-21 07:56:33 -0700556 // remove correction applied by setStreamVolume()
Jean-Baptiste Queru732ca392009-03-18 11:33:14 -0700557 if (stream == AudioSystem::VOICE_CALL) {
Eric Laurent4dd495b2009-04-21 07:56:33 -0700558 volume = (volume - 0.01) / 0.99 ;
James E. Blair6015dfc2009-01-17 13:30:20 -0800559 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700560
Eric Laurent4dd495b2009-04-21 07:56:33 -0700561 return volume;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700562}
563
564bool AudioFlinger::streamMute(int stream) const
565{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700566 if (stream < 0 || stream >= (int)AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700567 return true;
568 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700569
570 return mStreamTypes[stream].mute;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700571}
572
573bool AudioFlinger::isMusicActive() const
574{
Eric Laurentb025ca02009-07-09 03:20:57 -0700575 Mutex::Autolock _l(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700576 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700577 if (mPlaybackThreads.valueAt(i)->isMusicActive()) {
Eric Laurent9d91ad52009-07-17 12:17:14 -0700578 return true;
579 }
580 }
581 return false;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700582}
583
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700584status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700585{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700586 status_t result;
587
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700588 LOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
Eric Laurent9d91ad52009-07-17 12:17:14 -0700589 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
590 // check calling permissions
591 if (!settingsAllowed()) {
592 return PERMISSION_DENIED;
The Android Open Source Project8a7a6752009-01-15 16:12:10 -0800593 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700594
595 // ioHandle == 0 means the parameters are global to the audio hardware interface
596 if (ioHandle == 0) {
597 AutoMutex lock(mHardwareLock);
598 mHardwareStatus = AUDIO_SET_PARAMETER;
599 result = mAudioHardware->setParameters(keyValuePairs);
600 mHardwareStatus = AUDIO_HW_IDLE;
601 return result;
602 }
603
604 // Check if parameters are for an output
605 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
606 if (playbackThread != NULL) {
607 return playbackThread->setParameters(keyValuePairs);
608 }
609
610 // Check if parameters are for an input
611 RecordThread *recordThread = checkRecordThread_l(ioHandle);
612 if (recordThread != NULL) {
613 return recordThread->setParameters(keyValuePairs);
614 }
615
616 return BAD_VALUE;
617}
618
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700619String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
Eric Laurent9d91ad52009-07-17 12:17:14 -0700620{
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700621// LOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
Eric Laurent9d91ad52009-07-17 12:17:14 -0700622// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
623
624 if (ioHandle == 0) {
625 return mAudioHardware->getParameters(keys);
626 }
627 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
628 if (playbackThread != NULL) {
629 return playbackThread->getParameters(keys);
630 }
631 RecordThread *recordThread = checkRecordThread_l(ioHandle);
632 if (recordThread != NULL) {
633 return recordThread->getParameters(keys);
634 }
635 return String8("");
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700636}
637
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800638size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
639{
640 return mAudioHardware->getInputBufferSize(sampleRate, format, channelCount);
641}
642
643void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
644{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700645
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800646 LOGV("registerClient() %p, tid %d, calling tid %d", client.get(), gettid(), IPCThreadState::self()->getCallingPid());
647 Mutex::Autolock _l(mLock);
648
649 sp<IBinder> binder = client->asBinder();
650 if (mNotificationClients.indexOf(binder) < 0) {
651 LOGV("Adding notification client %p", binder.get());
652 binder->linkToDeath(this);
653 mNotificationClients.add(binder);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700654 }
655
656 // the config change is always sent from playback or record threads to avoid deadlock
657 // with AudioSystem::gLock
658 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700659 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700660 }
661
662 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700663 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800664 }
665}
666
667void AudioFlinger::binderDied(const wp<IBinder>& who) {
Eric Laurent9d91ad52009-07-17 12:17:14 -0700668
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800669 LOGV("binderDied() %p, tid %d, calling tid %d", who.unsafe_get(), gettid(), IPCThreadState::self()->getCallingPid());
670 Mutex::Autolock _l(mLock);
671
672 IBinder *binder = who.unsafe_get();
673
674 if (binder != NULL) {
675 int index = mNotificationClients.indexOf(binder);
676 if (index >= 0) {
677 LOGV("Removing notification client %p", binder);
678 mNotificationClients.removeAt(index);
679 }
680 }
681}
682
Eric Laurentb3687ae2009-09-15 07:10:12 -0700683// audioConfigChanged_l() must be called with AudioFlinger::mLock held
684void AudioFlinger::audioConfigChanged_l(int event, const sp<ThreadBase>& thread, void *param2) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700685 int ioHandle = 0;
686
687 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
688 if (mPlaybackThreads.valueAt(i) == thread) {
689 ioHandle = mPlaybackThreads.keyAt(i);
690 break;
691 }
692 }
693 if (ioHandle == 0) {
694 for (size_t i = 0; i < mRecordThreads.size(); i++) {
695 if (mRecordThreads.valueAt(i) == thread) {
696 ioHandle = mRecordThreads.keyAt(i);
697 break;
698 }
699 }
700 }
701
702 if (ioHandle != 0) {
703 size_t size = mNotificationClients.size();
704 for (size_t i = 0; i < size; i++) {
705 sp<IBinder> binder = mNotificationClients.itemAt(i);
Eric Laurentb3687ae2009-09-15 07:10:12 -0700706 LOGV("audioConfigChanged_l() Notifying change to client %p", binder.get());
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700707 sp<IAudioFlingerClient> client = interface_cast<IAudioFlingerClient> (binder);
708 client->ioConfigChanged(event, ioHandle, param2);
709 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700710 }
711}
712
Eric Laurent0f8ab672009-09-17 05:12:56 -0700713// removeClient_l() must be called with AudioFlinger::mLock held
714void AudioFlinger::removeClient_l(pid_t pid)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700715{
Eric Laurent0f8ab672009-09-17 05:12:56 -0700716 LOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700717 mClients.removeItem(pid);
718}
719
Eric Laurent9d91ad52009-07-17 12:17:14 -0700720// ----------------------------------------------------------------------------
721
722AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger)
723 : Thread(false),
724 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
Eric Laurent3464c012009-08-04 09:45:33 -0700725 mFormat(0), mFrameSize(1), mStandby(false)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700726{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800727}
728
Eric Laurent9d91ad52009-07-17 12:17:14 -0700729AudioFlinger::ThreadBase::~ThreadBase()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800730{
Eric Laurent3464c012009-08-04 09:45:33 -0700731 mParamCond.broadcast();
732 mNewParameters.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800733}
734
Eric Laurent9d91ad52009-07-17 12:17:14 -0700735void AudioFlinger::ThreadBase::exit()
The Android Open Source Projectbcef13b2009-03-11 12:11:56 -0700736{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700737 // keep a strong ref on ourself so that we want get
738 // destroyed in the middle of requestExitAndWait()
739 sp <ThreadBase> strongMe = this;
740
741 LOGV("ThreadBase::exit");
742 {
743 AutoMutex lock(&mLock);
744 requestExit();
745 mWaitWorkCV.signal();
The Android Open Source Projectbcef13b2009-03-11 12:11:56 -0700746 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700747 requestExitAndWait();
The Android Open Source Projectbcef13b2009-03-11 12:11:56 -0700748}
Eric Laurent9d91ad52009-07-17 12:17:14 -0700749
750uint32_t AudioFlinger::ThreadBase::sampleRate() const
751{
752 return mSampleRate;
753}
754
755int AudioFlinger::ThreadBase::channelCount() const
756{
757 return mChannelCount;
758}
759
760int AudioFlinger::ThreadBase::format() const
761{
762 return mFormat;
763}
764
765size_t AudioFlinger::ThreadBase::frameCount() const
766{
767 return mFrameCount;
768}
769
770status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
771{
Eric Laurent3464c012009-08-04 09:45:33 -0700772 status_t status;
Eric Laurent9d91ad52009-07-17 12:17:14 -0700773
Eric Laurent3464c012009-08-04 09:45:33 -0700774 LOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Eric Laurent9d91ad52009-07-17 12:17:14 -0700775 Mutex::Autolock _l(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700776
Eric Laurent3464c012009-08-04 09:45:33 -0700777 mNewParameters.add(keyValuePairs);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700778 mWaitWorkCV.signal();
779 mParamCond.wait(mLock);
Eric Laurent3464c012009-08-04 09:45:33 -0700780 status = mParamStatus;
781 mWaitWorkCV.signal();
782 return status;
Eric Laurent9d91ad52009-07-17 12:17:14 -0700783}
784
785void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
786{
787 Mutex::Autolock _l(mLock);
Eric Laurent3464c012009-08-04 09:45:33 -0700788 sendConfigEvent_l(event, param);
789}
790
791// sendConfigEvent_l() must be called with ThreadBase::mLock held
792void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
793{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700794 ConfigEvent *configEvent = new ConfigEvent();
795 configEvent->mEvent = event;
796 configEvent->mParam = param;
797 mConfigEvents.add(configEvent);
798 LOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
799 mWaitWorkCV.signal();
800}
801
802void AudioFlinger::ThreadBase::processConfigEvents()
803{
804 mLock.lock();
805 while(!mConfigEvents.isEmpty()) {
806 LOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
807 ConfigEvent *configEvent = mConfigEvents[0];
808 mConfigEvents.removeAt(0);
Eric Laurentb3687ae2009-09-15 07:10:12 -0700809 // release mLock because audioConfigChanged() will lock AudioFlinger mLock
810 // before calling Audioflinger::audioConfigChanged_l() thus creating
Eric Laurent9d91ad52009-07-17 12:17:14 -0700811 // potential cross deadlock between AudioFlinger::mLock and mLock
812 mLock.unlock();
813 audioConfigChanged(configEvent->mEvent, configEvent->mParam);
814 delete configEvent;
815 mLock.lock();
816 }
817 mLock.unlock();
818}
819
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800820
821// ----------------------------------------------------------------------------
822
Eric Laurent9d91ad52009-07-17 12:17:14 -0700823AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output)
824 : ThreadBase(audioFlinger),
Eric Laurentf9df2492009-08-06 08:49:39 -0700825 mMixBuffer(0), mSuspended(0), mBytesWritten(0), mOutput(output),
Eric Laurent9395d9b2009-07-23 13:17:39 -0700826 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800827{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700828 readOutputParameters();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800829
Eric Laurent9d91ad52009-07-17 12:17:14 -0700830 mMasterVolume = mAudioFlinger->masterVolume();
831 mMasterMute = mAudioFlinger->masterMute();
832
833 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
834 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
835 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800836 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700837 // notify client processes that a new input has been opened
838 sendConfigEvent(AudioSystem::OUTPUT_OPENED);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800839}
840
Eric Laurent9d91ad52009-07-17 12:17:14 -0700841AudioFlinger::PlaybackThread::~PlaybackThread()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800842{
843 delete [] mMixBuffer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800844}
845
Eric Laurent9d91ad52009-07-17 12:17:14 -0700846status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800847{
848 dumpInternals(fd, args);
849 dumpTracks(fd, args);
850 return NO_ERROR;
851}
852
Eric Laurent9d91ad52009-07-17 12:17:14 -0700853status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800854{
855 const size_t SIZE = 256;
856 char buffer[SIZE];
857 String8 result;
858
Eric Laurent9d91ad52009-07-17 12:17:14 -0700859 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800860 result.append(buffer);
861 result.append(" Name Clien Typ Fmt Chn Buf S M F SRate LeftV RighV Serv User\n");
862 for (size_t i = 0; i < mTracks.size(); ++i) {
Eric Laurentc828f6a2009-03-31 14:34:35 -0700863 sp<Track> track = mTracks[i];
864 if (track != 0) {
865 track->dump(buffer, SIZE);
866 result.append(buffer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800867 }
868 }
869
Eric Laurent9d91ad52009-07-17 12:17:14 -0700870 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800871 result.append(buffer);
872 result.append(" Name Clien Typ Fmt Chn Buf S M F SRate LeftV RighV Serv User\n");
873 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Eric Laurentc828f6a2009-03-31 14:34:35 -0700874 wp<Track> wTrack = mActiveTracks[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800875 if (wTrack != 0) {
876 sp<Track> track = wTrack.promote();
877 if (track != 0) {
878 track->dump(buffer, SIZE);
879 result.append(buffer);
880 }
881 }
882 }
883 write(fd, result.string(), result.size());
884 return NO_ERROR;
885}
886
Eric Laurent9d91ad52009-07-17 12:17:14 -0700887status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800888{
889 const size_t SIZE = 256;
890 char buffer[SIZE];
891 String8 result;
892
Eric Laurent9d91ad52009-07-17 12:17:14 -0700893 snprintf(buffer, SIZE, "Output thread %p internals\n", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800894 result.append(buffer);
895 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
896 result.append(buffer);
897 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
898 result.append(buffer);
899 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
900 result.append(buffer);
901 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
902 result.append(buffer);
903 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
904 result.append(buffer);
905 write(fd, result.string(), result.size());
906 return NO_ERROR;
907}
908
909// Thread virtuals
Eric Laurent9d91ad52009-07-17 12:17:14 -0700910status_t AudioFlinger::PlaybackThread::readyToRun()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800911{
912 if (mSampleRate == 0) {
913 LOGE("No working audio driver found.");
914 return NO_INIT;
915 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700916 LOGI("AudioFlinger's thread %p ready to run", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800917 return NO_ERROR;
918}
919
Eric Laurent9d91ad52009-07-17 12:17:14 -0700920void AudioFlinger::PlaybackThread::onFirstRef()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800921{
922 const size_t SIZE = 256;
923 char buffer[SIZE];
924
Eric Laurent9d91ad52009-07-17 12:17:14 -0700925 snprintf(buffer, SIZE, "Playback Thread %p", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800926
927 run(buffer, ANDROID_PRIORITY_URGENT_AUDIO);
928}
929
Eric Laurent9d91ad52009-07-17 12:17:14 -0700930// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
931sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800932 const sp<AudioFlinger::Client>& client,
933 int streamType,
934 uint32_t sampleRate,
935 int format,
936 int channelCount,
937 int frameCount,
938 const sp<IMemory>& sharedBuffer,
939 status_t *status)
940{
941 sp<Track> track;
942 status_t lStatus;
Eric Laurent9d91ad52009-07-17 12:17:14 -0700943
944 if (mType == DIRECT) {
945 if (sampleRate != mSampleRate || format != mFormat || channelCount != mChannelCount) {
946 LOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelCount %d for output %p",
947 sampleRate, format, channelCount, mOutput);
948 lStatus = BAD_VALUE;
949 goto Exit;
950 }
951 } else {
952 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
953 if (sampleRate > mSampleRate*2) {
954 LOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
955 lStatus = BAD_VALUE;
956 goto Exit;
957 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800958 }
959
Eric Laurent9d91ad52009-07-17 12:17:14 -0700960 if (mOutput == 0) {
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700961 LOGE("Audio driver not initialized.");
962 lStatus = NO_INIT;
963 goto Exit;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800964 }
965
Eric Laurent9d91ad52009-07-17 12:17:14 -0700966 { // scope for mLock
967 Mutex::Autolock _l(mLock);
968 track = new Track(this, client, streamType, sampleRate, format,
969 channelCount, frameCount, sharedBuffer);
970 if (track->getCblk() == NULL) {
971 lStatus = NO_MEMORY;
972 goto Exit;
973 }
974 mTracks.add(track);
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700975 }
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700976 lStatus = NO_ERROR;
977
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800978Exit:
979 if(status) {
980 *status = lStatus;
981 }
982 return track;
983}
984
Eric Laurent9d91ad52009-07-17 12:17:14 -0700985uint32_t AudioFlinger::PlaybackThread::latency() const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800986{
987 if (mOutput) {
988 return mOutput->latency();
989 }
990 else {
991 return 0;
992 }
993}
994
Eric Laurent9d91ad52009-07-17 12:17:14 -0700995status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800996{
997 mMasterVolume = value;
998 return NO_ERROR;
999}
1000
Eric Laurent9d91ad52009-07-17 12:17:14 -07001001status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001002{
1003 mMasterMute = muted;
1004 return NO_ERROR;
1005}
1006
Eric Laurent9d91ad52009-07-17 12:17:14 -07001007float AudioFlinger::PlaybackThread::masterVolume() const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001008{
1009 return mMasterVolume;
1010}
1011
Eric Laurent9d91ad52009-07-17 12:17:14 -07001012bool AudioFlinger::PlaybackThread::masterMute() const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001013{
1014 return mMasterMute;
1015}
1016
Eric Laurent9d91ad52009-07-17 12:17:14 -07001017status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001018{
1019 mStreamTypes[stream].volume = value;
1020 return NO_ERROR;
1021}
1022
Eric Laurent9d91ad52009-07-17 12:17:14 -07001023status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001024{
1025 mStreamTypes[stream].mute = muted;
1026 return NO_ERROR;
1027}
1028
Eric Laurent9d91ad52009-07-17 12:17:14 -07001029float AudioFlinger::PlaybackThread::streamVolume(int stream) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001030{
1031 return mStreamTypes[stream].volume;
1032}
1033
Eric Laurent9d91ad52009-07-17 12:17:14 -07001034bool AudioFlinger::PlaybackThread::streamMute(int stream) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001035{
1036 return mStreamTypes[stream].mute;
1037}
1038
Eric Laurent9d91ad52009-07-17 12:17:14 -07001039bool AudioFlinger::PlaybackThread::isMusicActive() const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001040{
Eric Laurent9d91ad52009-07-17 12:17:14 -07001041 Mutex::Autolock _l(mLock);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001042 size_t count = mActiveTracks.size();
1043 for (size_t i = 0 ; i < count ; ++i) {
1044 sp<Track> t = mActiveTracks[i].promote();
1045 if (t == 0) continue;
1046 Track* const track = t.get();
Eric Laurent9395d9b2009-07-23 13:17:39 -07001047 if (t->type() == AudioSystem::MUSIC)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001048 return true;
1049 }
1050 return false;
1051}
1052
Eric Laurent9d91ad52009-07-17 12:17:14 -07001053// addTrack_l() must be called with ThreadBase::mLock held
1054status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001055{
1056 status_t status = ALREADY_EXISTS;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001057
1058 // here the track could be either new, or restarted
1059 // in both cases "unstop" the track
1060 if (track->isPaused()) {
1061 track->mState = TrackBase::RESUMING;
1062 LOGV("PAUSED => RESUMING (%d)", track->name());
1063 } else {
1064 track->mState = TrackBase::ACTIVE;
1065 LOGV("? => ACTIVE (%d)", track->name());
1066 }
1067 // set retry count for buffer fill
1068 track->mRetryCount = kMaxTrackStartupRetries;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001069 if (mActiveTracks.indexOf(track) < 0) {
1070 // the track is newly added, make sure it fills up all its
1071 // buffers before playing. This is to ensure the client will
1072 // effectively get the latency it requested.
1073 track->mFillingUpStatus = Track::FS_FILLING;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08001074 track->mResetDone = false;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001075 mActiveTracks.add(track);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001076 status = NO_ERROR;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001077 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07001078
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001079 LOGV("mWaitWorkCV.broadcast");
Eric Laurent9d91ad52009-07-17 12:17:14 -07001080 mWaitWorkCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001081
1082 return status;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001083}
1084
Eric Laurent9d91ad52009-07-17 12:17:14 -07001085// destroyTrack_l() must be called with ThreadBase::mLock held
1086void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001087{
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001088 track->mState = TrackBase::TERMINATED;
1089 if (mActiveTracks.indexOf(track) < 0) {
1090 LOGV("remove track (%d) and delete from mixer", track->name());
1091 mTracks.remove(track);
The Android Open Source Project22f8def2009-03-09 11:52:12 -07001092 deleteTrackName_l(track->name());
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001093 }
1094}
1095
Eric Laurent9d91ad52009-07-17 12:17:14 -07001096String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
The Android Open Source Projecte41dd752009-01-22 00:13:42 -08001097{
Eric Laurent9d91ad52009-07-17 12:17:14 -07001098 return mOutput->getParameters(keys);
1099}
The Android Open Source Projecte41dd752009-01-22 00:13:42 -08001100
Eric Laurent9d91ad52009-07-17 12:17:14 -07001101void AudioFlinger::PlaybackThread::audioConfigChanged(int event, int param) {
1102 AudioSystem::OutputDescriptor desc;
1103 void *param2 = 0;
1104
1105 LOGV("PlaybackThread::audioConfigChanged, thread %p, event %d, param %d", this, event, param);
1106
1107 switch (event) {
1108 case AudioSystem::OUTPUT_OPENED:
1109 case AudioSystem::OUTPUT_CONFIG_CHANGED:
1110 desc.channels = mChannelCount;
1111 desc.samplingRate = mSampleRate;
1112 desc.format = mFormat;
1113 desc.frameCount = mFrameCount;
1114 desc.latency = latency();
1115 param2 = &desc;
1116 break;
1117
1118 case AudioSystem::STREAM_CONFIG_CHANGED:
1119 param2 = &param;
1120 case AudioSystem::OUTPUT_CLOSED:
1121 default:
1122 break;
1123 }
Eric Laurentb3687ae2009-09-15 07:10:12 -07001124 Mutex::Autolock _l(mAudioFlinger->mLock);
1125 mAudioFlinger->audioConfigChanged_l(event, this, param2);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001126}
1127
1128void AudioFlinger::PlaybackThread::readOutputParameters()
1129{
1130 mSampleRate = mOutput->sampleRate();
1131 mChannelCount = AudioSystem::popCount(mOutput->channels());
1132
1133 mFormat = mOutput->format();
1134 mFrameSize = mOutput->frameSize();
1135 mFrameCount = mOutput->bufferSize() / mFrameSize;
1136
1137 mMinBytesToWrite = (mOutput->latency() * mSampleRate * mFrameSize) / 1000;
1138 // FIXME - Current mixer implementation only supports stereo output: Always
1139 // Allocate a stereo buffer even if HW output is mono.
1140 if (mMixBuffer != NULL) delete mMixBuffer;
1141 mMixBuffer = new int16_t[mFrameCount * 2];
1142 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1143}
1144
1145// ----------------------------------------------------------------------------
1146
1147AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output)
1148 : PlaybackThread(audioFlinger, output),
1149 mAudioMixer(0)
1150{
1151 mType = PlaybackThread::MIXER;
1152 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1153
1154 // FIXME - Current mixer implementation only supports stereo output
1155 if (mChannelCount == 1) {
1156 LOGE("Invalid audio hardware channel count");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001157 }
The Android Open Source Projecte41dd752009-01-22 00:13:42 -08001158}
1159
Eric Laurent9d91ad52009-07-17 12:17:14 -07001160AudioFlinger::MixerThread::~MixerThread()
The Android Open Source Projecte41dd752009-01-22 00:13:42 -08001161{
Eric Laurent9d91ad52009-07-17 12:17:14 -07001162 delete mAudioMixer;
1163}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001164
Eric Laurent9d91ad52009-07-17 12:17:14 -07001165bool AudioFlinger::MixerThread::threadLoop()
1166{
Eric Laurent3522c802009-09-07 08:38:38 -07001167 unsigned long sleepTime = 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001168 int16_t* curBuf = mMixBuffer;
1169 Vector< sp<Track> > tracksToRemove;
1170 size_t enabledTracks = 0;
1171 nsecs_t standbyTime = systemTime();
1172 size_t mixBufferSize = mFrameCount * mFrameSize;
1173 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 2;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001174
Eric Laurent9d91ad52009-07-17 12:17:14 -07001175 while (!exitPending())
1176 {
1177 processConfigEvents();
1178
1179 enabledTracks = 0;
1180 { // scope for mLock
1181
1182 Mutex::Autolock _l(mLock);
1183
1184 if (checkForNewParameters_l()) {
1185 mixBufferSize = mFrameCount * mFrameSize;
1186 maxPeriod = seconds(mFrameCount) / mSampleRate * 2;
1187 }
1188
1189 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1190
1191 // put audio hardware into standby after short delay
1192 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1193 mSuspended) {
1194 if (!mStandby) {
1195 LOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
1196 mOutput->standby();
1197 mStandby = true;
1198 mBytesWritten = 0;
1199 }
1200
1201 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1202 // we're about to wait, flush the binder command buffer
1203 IPCThreadState::self()->flushCommands();
1204
1205 if (exitPending()) break;
1206
1207 // wait until we have something to do...
1208 LOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
1209 mWaitWorkCV.wait(mLock);
1210 LOGV("MixerThread %p TID %d waking up\n", this, gettid());
1211
1212 if (mMasterMute == false) {
1213 char value[PROPERTY_VALUE_MAX];
1214 property_get("ro.audio.silent", value, "0");
1215 if (atoi(value)) {
1216 LOGD("Silence is golden");
1217 setMasterMute(true);
1218 }
1219 }
1220
1221 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent3522c802009-09-07 08:38:38 -07001222 sleepTime = 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001223 continue;
1224 }
1225 }
1226
1227 enabledTracks = prepareTracks_l(activeTracks, &tracksToRemove);
1228 }
1229
Eric Laurent9d91ad52009-07-17 12:17:14 -07001230
Eric Laurent3522c802009-09-07 08:38:38 -07001231 // output audio to hardware
1232 if (mSuspended) {
1233 usleep(kMaxBufferRecoveryInUsecs);
1234 } else {
1235 if (LIKELY(enabledTracks)) {
1236 // mix buffers...
1237 mAudioMixer->process(curBuf);
1238 sleepTime = 0;
1239 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001240 } else {
Eric Laurent3522c802009-09-07 08:38:38 -07001241 sleepTime += kBufferRecoveryInUsecs;
1242 // There was nothing to mix this round, which means all
1243 // active tracks were late. Sleep a little bit to give
1244 // them another chance. If we're too late, write 0s to audio
1245 // hardware to avoid underrun.
Eric Laurenta6e58fe2009-09-14 01:38:42 -07001246 if (mBytesWritten == 0 || sleepTime < kMaxBufferRecoveryInUsecs) {
Eric Laurent3522c802009-09-07 08:38:38 -07001247 usleep(kBufferRecoveryInUsecs);
1248 } else {
1249 memset (curBuf, 0, mixBufferSize);
1250 sleepTime = 0;
1251 }
1252 }
1253 // sleepTime == 0 means PCM data were written to mMixBuffer[]
1254 if (sleepTime == 0) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07001255 mLastWriteTime = systemTime();
1256 mInWrite = true;
1257 int bytesWritten = (int)mOutput->write(curBuf, mixBufferSize);
1258 if (bytesWritten > 0) mBytesWritten += bytesWritten;
1259 mNumWrites++;
1260 mInWrite = false;
1261 mStandby = false;
Eric Laurent3522c802009-09-07 08:38:38 -07001262 nsecs_t delta = systemTime() - mLastWriteTime;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001263 if (delta > maxPeriod) {
1264 LOGW("write blocked for %llu msecs", ns2ms(delta));
1265 mNumDelayedWrites++;
1266 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07001267 }
1268 }
1269
1270 // finally let go of all our tracks, without the lock held
1271 // since we can't guarantee the destructors won't acquire that
1272 // same lock.
1273 tracksToRemove.clear();
1274 }
1275
1276 if (!mStandby) {
1277 mOutput->standby();
1278 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07001279
1280 LOGV("MixerThread %p exiting", this);
1281 return false;
1282}
1283
1284// prepareTracks_l() must be called with ThreadBase::mLock held
1285size_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
1286{
1287
1288 size_t enabledTracks = 0;
1289 // find out which tracks need to be processed
1290 size_t count = activeTracks.size();
1291 for (size_t i=0 ; i<count ; i++) {
1292 sp<Track> t = activeTracks[i].promote();
1293 if (t == 0) continue;
1294
1295 Track* const track = t.get();
1296 audio_track_cblk_t* cblk = track->cblk();
1297
1298 // The first time a track is added we wait
1299 // for all its buffers to be filled before processing it
1300 mAudioMixer->setActiveTrack(track->name());
1301 if (cblk->framesReady() && (track->isReady() || track->isStopped()) &&
1302 !track->isPaused())
1303 {
1304 //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
1305
1306 // compute volume for this track
1307 int16_t left, right;
1308 if (track->isMuted() || mMasterMute || track->isPausing() ||
1309 mStreamTypes[track->type()].mute) {
1310 left = right = 0;
1311 if (track->isPausing()) {
1312 track->setPaused();
1313 }
1314 } else {
1315 float typeVolume = mStreamTypes[track->type()].volume;
1316 float v = mMasterVolume * typeVolume;
1317 float v_clamped = v * cblk->volume[0];
1318 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
1319 left = int16_t(v_clamped);
1320 v_clamped = v * cblk->volume[1];
1321 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
1322 right = int16_t(v_clamped);
1323 }
1324
1325 // XXX: these things DON'T need to be done each time
1326 mAudioMixer->setBufferProvider(track);
1327 mAudioMixer->enable(AudioMixer::MIXING);
1328
Eric Laurent08d3d1d2009-09-03 03:45:52 -07001329 int param = AudioMixer::VOLUME;
1330 if (track->mFillingUpStatus == Track::FS_FILLED) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07001331 // no ramp for the first volume setting
1332 track->mFillingUpStatus = Track::FS_ACTIVE;
1333 if (track->mState == TrackBase::RESUMING) {
1334 track->mState = TrackBase::ACTIVE;
1335 param = AudioMixer::RAMP_VOLUME;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001336 }
Eric Laurent08d3d1d2009-09-03 03:45:52 -07001337 } else if (cblk->server != 0) {
1338 // If the track is stopped before the first frame was mixed,
1339 // do not apply ramp
Eric Laurent9d91ad52009-07-17 12:17:14 -07001340 param = AudioMixer::RAMP_VOLUME;
1341 }
Eric Laurent08d3d1d2009-09-03 03:45:52 -07001342
Eric Laurent9d91ad52009-07-17 12:17:14 -07001343 mAudioMixer->setParameter(param, AudioMixer::VOLUME0, left);
1344 mAudioMixer->setParameter(param, AudioMixer::VOLUME1, right);
1345 mAudioMixer->setParameter(
1346 AudioMixer::TRACK,
1347 AudioMixer::FORMAT, track->format());
1348 mAudioMixer->setParameter(
1349 AudioMixer::TRACK,
1350 AudioMixer::CHANNEL_COUNT, track->channelCount());
1351 mAudioMixer->setParameter(
1352 AudioMixer::RESAMPLE,
1353 AudioMixer::SAMPLE_RATE,
1354 int(cblk->sampleRate));
1355
1356 // reset retry count
1357 track->mRetryCount = kMaxTrackRetries;
1358 enabledTracks++;
1359 } else {
1360 //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
1361 if (track->isStopped()) {
1362 track->reset();
1363 }
1364 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
1365 // We have consumed all the buffers of this track.
1366 // Remove it from the list of active tracks.
1367 tracksToRemove->add(track);
1368 mAudioMixer->disable(AudioMixer::MIXING);
1369 } else {
1370 // No buffers for this track. Give it a few chances to
1371 // fill a buffer, then remove it from active list.
1372 if (--(track->mRetryCount) <= 0) {
1373 LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
1374 tracksToRemove->add(track);
1375 }
Eric Laurent08d3d1d2009-09-03 03:45:52 -07001376 // For tracks using static shared memory buffer, make sure that we have
Eric Laurent9d91ad52009-07-17 12:17:14 -07001377 // written enough data to audio hardware before disabling the track
1378 // NOTE: this condition with arrive before track->mRetryCount <= 0 so we
1379 // don't care about code removing track from active list above.
1380 if ((track->mSharedBuffer == 0) || (mBytesWritten >= mMinBytesToWrite)) {
1381 mAudioMixer->disable(AudioMixer::MIXING);
1382 } else {
1383 enabledTracks++;
1384 }
1385 }
1386 }
1387 }
1388
1389 // remove all the tracks that need to be...
1390 count = tracksToRemove->size();
1391 if (UNLIKELY(count)) {
1392 for (size_t i=0 ; i<count ; i++) {
1393 const sp<Track>& track = tracksToRemove->itemAt(i);
1394 mActiveTracks.remove(track);
1395 if (track->isTerminated()) {
1396 mTracks.remove(track);
1397 deleteTrackName_l(track->mName);
1398 }
1399 }
1400 }
1401
1402 return enabledTracks;
1403}
1404
1405void AudioFlinger::MixerThread::getTracks(
1406 SortedVector < sp<Track> >& tracks,
1407 SortedVector < wp<Track> >& activeTracks,
1408 int streamType)
1409{
1410 LOGV ("MixerThread::getTracks() mixer %p, mTracks.size %d, mActiveTracks.size %d", this, mTracks.size(), mActiveTracks.size());
1411 Mutex::Autolock _l(mLock);
1412 size_t size = mTracks.size();
1413 for (size_t i = 0; i < size; i++) {
1414 sp<Track> t = mTracks[i];
1415 if (t->type() == streamType) {
1416 tracks.add(t);
1417 int j = mActiveTracks.indexOf(t);
1418 if (j >= 0) {
1419 t = mActiveTracks[j].promote();
1420 if (t != NULL) {
1421 activeTracks.add(t);
1422 }
1423 }
1424 }
1425 }
1426
1427 size = activeTracks.size();
1428 for (size_t i = 0; i < size; i++) {
1429 mActiveTracks.remove(activeTracks[i]);
1430 }
1431
1432 size = tracks.size();
1433 for (size_t i = 0; i < size; i++) {
1434 sp<Track> t = tracks[i];
1435 mTracks.remove(t);
1436 deleteTrackName_l(t->name());
1437 }
1438}
1439
1440void AudioFlinger::MixerThread::putTracks(
1441 SortedVector < sp<Track> >& tracks,
1442 SortedVector < wp<Track> >& activeTracks)
1443{
1444 LOGV ("MixerThread::putTracks() mixer %p, tracks.size %d, activeTracks.size %d", this, tracks.size(), activeTracks.size());
1445 Mutex::Autolock _l(mLock);
1446 size_t size = tracks.size();
1447 for (size_t i = 0; i < size ; i++) {
1448 sp<Track> t = tracks[i];
1449 int name = getTrackName_l();
1450
1451 if (name < 0) return;
1452
1453 t->mName = name;
1454 t->mThread = this;
1455 mTracks.add(t);
1456
1457 int j = activeTracks.indexOf(t);
1458 if (j >= 0) {
1459 mActiveTracks.add(t);
Eric Laurent06437712009-09-01 05:56:26 -07001460 // force buffer refilling and no ramp volume when the track is mixed for the first time
1461 t->mFillingUpStatus = Track::FS_FILLING;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001462 }
1463 }
1464}
1465
Eric Laurent9d91ad52009-07-17 12:17:14 -07001466// getTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Project22f8def2009-03-09 11:52:12 -07001467int AudioFlinger::MixerThread::getTrackName_l()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001468{
1469 return mAudioMixer->getTrackName();
1470}
1471
Eric Laurent9d91ad52009-07-17 12:17:14 -07001472// deleteTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Project22f8def2009-03-09 11:52:12 -07001473void AudioFlinger::MixerThread::deleteTrackName_l(int name)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001474{
1475 mAudioMixer->deleteTrackName(name);
1476}
1477
Eric Laurent9d91ad52009-07-17 12:17:14 -07001478// checkForNewParameters_l() must be called with ThreadBase::mLock held
1479bool AudioFlinger::MixerThread::checkForNewParameters_l()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001480{
Eric Laurent9d91ad52009-07-17 12:17:14 -07001481 bool reconfig = false;
1482
Eric Laurent3464c012009-08-04 09:45:33 -07001483 while (!mNewParameters.isEmpty()) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07001484 status_t status = NO_ERROR;
Eric Laurent3464c012009-08-04 09:45:33 -07001485 String8 keyValuePair = mNewParameters[0];
1486 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001487 int value;
Eric Laurent3464c012009-08-04 09:45:33 -07001488
1489 mNewParameters.removeAt(0);
1490
Eric Laurent9d91ad52009-07-17 12:17:14 -07001491 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
1492 reconfig = true;
1493 }
1494 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
1495 if (value != AudioSystem::PCM_16_BIT) {
1496 status = BAD_VALUE;
1497 } else {
1498 reconfig = true;
1499 }
1500 }
1501 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
1502 if (value != AudioSystem::CHANNEL_OUT_STEREO) {
1503 status = BAD_VALUE;
1504 } else {
1505 reconfig = true;
1506 }
1507 }
1508 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
1509 // do not accept frame count changes if tracks are open as the track buffer
1510 // size depends on frame count and correct behavior would not be garantied
1511 // if frame count is changed after track creation
1512 if (!mTracks.isEmpty()) {
1513 status = INVALID_OPERATION;
1514 } else {
1515 reconfig = true;
1516 }
1517 }
1518 if (status == NO_ERROR) {
Eric Laurent3464c012009-08-04 09:45:33 -07001519 status = mOutput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001520 if (!mStandby && status == INVALID_OPERATION) {
1521 mOutput->standby();
1522 mStandby = true;
1523 mBytesWritten = 0;
Eric Laurent3464c012009-08-04 09:45:33 -07001524 status = mOutput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001525 }
1526 if (status == NO_ERROR && reconfig) {
1527 delete mAudioMixer;
1528 readOutputParameters();
1529 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1530 for (size_t i = 0; i < mTracks.size() ; i++) {
1531 int name = getTrackName_l();
1532 if (name < 0) break;
1533 mTracks[i]->mName = name;
Eric Laurent878c0e12009-08-10 08:15:12 -07001534 // limit track sample rate to 2 x new output sample rate
1535 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
1536 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
1537 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07001538 }
Eric Laurent3464c012009-08-04 09:45:33 -07001539 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001540 }
1541 }
1542 mParamStatus = status;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001543 mParamCond.signal();
Eric Laurent3464c012009-08-04 09:45:33 -07001544 mWaitWorkCV.wait(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001545 }
1546 return reconfig;
1547}
1548
1549status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
1550{
1551 const size_t SIZE = 256;
1552 char buffer[SIZE];
1553 String8 result;
1554
1555 PlaybackThread::dumpInternals(fd, args);
1556
1557 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
1558 result.append(buffer);
1559 write(fd, result.string(), result.size());
1560 return NO_ERROR;
1561}
1562
1563// ----------------------------------------------------------------------------
1564AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output)
1565 : PlaybackThread(audioFlinger, output),
1566 mLeftVolume (1.0), mRightVolume(1.0)
1567{
1568 mType = PlaybackThread::DIRECT;
1569}
1570
1571AudioFlinger::DirectOutputThread::~DirectOutputThread()
1572{
1573}
1574
1575
1576bool AudioFlinger::DirectOutputThread::threadLoop()
1577{
Eric Laurent3522c802009-09-07 08:38:38 -07001578 unsigned long sleepTime = 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001579 sp<Track> trackToRemove;
1580 sp<Track> activeTrack;
1581 nsecs_t standbyTime = systemTime();
1582 int8_t *curBuf;
1583 size_t mixBufferSize = mFrameCount*mFrameSize;
1584
1585 while (!exitPending())
1586 {
1587 processConfigEvents();
1588
1589 { // scope for the mLock
1590
1591 Mutex::Autolock _l(mLock);
1592
1593 if (checkForNewParameters_l()) {
1594 mixBufferSize = mFrameCount*mFrameSize;
1595 }
1596
1597 // put audio hardware into standby after short delay
1598 if UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
1599 mSuspended) {
1600 // wait until we have something to do...
1601 if (!mStandby) {
1602 LOGV("Audio hardware entering standby, mixer %p\n", this);
1603 mOutput->standby();
1604 mStandby = true;
1605 mBytesWritten = 0;
1606 }
1607
1608 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
1609 // we're about to wait, flush the binder command buffer
1610 IPCThreadState::self()->flushCommands();
1611
1612 if (exitPending()) break;
1613
1614 LOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
1615 mWaitWorkCV.wait(mLock);
1616 LOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
1617
1618 if (mMasterMute == false) {
1619 char value[PROPERTY_VALUE_MAX];
1620 property_get("ro.audio.silent", value, "0");
1621 if (atoi(value)) {
1622 LOGD("Silence is golden");
1623 setMasterMute(true);
1624 }
1625 }
1626
1627 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent3522c802009-09-07 08:38:38 -07001628 sleepTime = 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001629 continue;
1630 }
1631 }
1632
1633 // find out which tracks need to be processed
1634 if (mActiveTracks.size() != 0) {
1635 sp<Track> t = mActiveTracks[0].promote();
1636 if (t == 0) continue;
1637
1638 Track* const track = t.get();
1639 audio_track_cblk_t* cblk = track->cblk();
1640
1641 // The first time a track is added we wait
1642 // for all its buffers to be filled before processing it
1643 if (cblk->framesReady() && (track->isReady() || track->isStopped()) &&
1644 !track->isPaused())
1645 {
1646 //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
1647
1648 // compute volume for this track
1649 float left, right;
1650 if (track->isMuted() || mMasterMute || track->isPausing() ||
1651 mStreamTypes[track->type()].mute) {
1652 left = right = 0;
1653 if (track->isPausing()) {
1654 track->setPaused();
1655 }
1656 } else {
1657 float typeVolume = mStreamTypes[track->type()].volume;
1658 float v = mMasterVolume * typeVolume;
1659 float v_clamped = v * cblk->volume[0];
1660 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
1661 left = v_clamped/MAX_GAIN;
1662 v_clamped = v * cblk->volume[1];
1663 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
1664 right = v_clamped/MAX_GAIN;
1665 }
1666
1667 if (left != mLeftVolume || right != mRightVolume) {
1668 mOutput->setVolume(left, right);
1669 left = mLeftVolume;
1670 right = mRightVolume;
1671 }
1672
1673 if (track->mFillingUpStatus == Track::FS_FILLED) {
1674 track->mFillingUpStatus = Track::FS_ACTIVE;
1675 if (track->mState == TrackBase::RESUMING) {
1676 track->mState = TrackBase::ACTIVE;
1677 }
1678 }
1679
1680 // reset retry count
1681 track->mRetryCount = kMaxTrackRetries;
1682 activeTrack = t;
1683 } else {
1684 //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
1685 if (track->isStopped()) {
1686 track->reset();
1687 }
1688 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
1689 // We have consumed all the buffers of this track.
1690 // Remove it from the list of active tracks.
1691 trackToRemove = track;
1692 } else {
1693 // No buffers for this track. Give it a few chances to
1694 // fill a buffer, then remove it from active list.
1695 if (--(track->mRetryCount) <= 0) {
1696 LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
1697 trackToRemove = track;
1698 }
1699
1700 // For tracks using static shared memry buffer, make sure that we have
1701 // written enough data to audio hardware before disabling the track
1702 // NOTE: this condition with arrive before track->mRetryCount <= 0 so we
1703 // don't care about code removing track from active list above.
1704 if ((track->mSharedBuffer != 0) && (mBytesWritten < mMinBytesToWrite)) {
1705 activeTrack = t;
1706 }
1707 }
1708 }
1709 }
1710
1711 // remove all the tracks that need to be...
1712 if (UNLIKELY(trackToRemove != 0)) {
1713 mActiveTracks.remove(trackToRemove);
1714 if (trackToRemove->isTerminated()) {
1715 mTracks.remove(trackToRemove);
1716 deleteTrackName_l(trackToRemove->mName);
1717 }
1718 }
1719 }
1720
Eric Laurent3522c802009-09-07 08:38:38 -07001721 // output audio to hardware
1722 if (mSuspended) {
1723 usleep(kMaxBufferRecoveryInUsecs);
1724 } else {
1725 if (activeTrack != 0) {
1726 AudioBufferProvider::Buffer buffer;
1727 size_t frameCount = mFrameCount;
1728 curBuf = (int8_t *)mMixBuffer;
1729 // output audio to hardware
1730 while(frameCount) {
1731 buffer.frameCount = frameCount;
1732 activeTrack->getNextBuffer(&buffer);
1733 if (UNLIKELY(buffer.raw == 0)) {
1734 memset(curBuf, 0, frameCount * mFrameSize);
1735 break;
1736 }
1737 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
1738 frameCount -= buffer.frameCount;
1739 curBuf += buffer.frameCount * mFrameSize;
1740 activeTrack->releaseBuffer(&buffer);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001741 }
Eric Laurent3522c802009-09-07 08:38:38 -07001742 sleepTime = 0;
1743 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001744 } else {
Eric Laurent3522c802009-09-07 08:38:38 -07001745 sleepTime += kBufferRecoveryInUsecs;
Eric Laurenta6e58fe2009-09-14 01:38:42 -07001746 if (mBytesWritten == 0 || !AudioSystem::isLinearPCM(mFormat) ||
1747 sleepTime < kMaxBufferRecoveryInUsecs) {
Eric Laurent3522c802009-09-07 08:38:38 -07001748 usleep(kBufferRecoveryInUsecs);
1749 } else {
1750 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
1751 sleepTime = 0;
1752 }
1753 }
1754
1755 // sleepTime == 0 means PCM data were written to mMixBuffer[]
1756 if (sleepTime == 0) {
1757 mLastWriteTime = systemTime();
1758 mInWrite = true;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001759 int bytesWritten = (int)mOutput->write(mMixBuffer, mixBufferSize);
1760 if (bytesWritten) mBytesWritten += bytesWritten;
1761 mNumWrites++;
1762 mInWrite = false;
1763 mStandby = false;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001764 }
1765 }
1766
1767 // finally let go of removed track, without the lock held
1768 // since we can't guarantee the destructors won't acquire that
1769 // same lock.
1770 trackToRemove.clear();
1771 activeTrack.clear();
1772 }
1773
1774 if (!mStandby) {
1775 mOutput->standby();
1776 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07001777
1778 LOGV("DirectOutputThread %p exiting", this);
1779 return false;
1780}
1781
1782// getTrackName_l() must be called with ThreadBase::mLock held
1783int AudioFlinger::DirectOutputThread::getTrackName_l()
1784{
1785 return 0;
1786}
1787
1788// deleteTrackName_l() must be called with ThreadBase::mLock held
1789void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
1790{
1791}
1792
1793// checkForNewParameters_l() must be called with ThreadBase::mLock held
1794bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
1795{
1796 bool reconfig = false;
1797
Eric Laurent3464c012009-08-04 09:45:33 -07001798 while (!mNewParameters.isEmpty()) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07001799 status_t status = NO_ERROR;
Eric Laurent3464c012009-08-04 09:45:33 -07001800 String8 keyValuePair = mNewParameters[0];
1801 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001802 int value;
Eric Laurent3464c012009-08-04 09:45:33 -07001803
1804 mNewParameters.removeAt(0);
1805
Eric Laurent9d91ad52009-07-17 12:17:14 -07001806 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
1807 // do not accept frame count changes if tracks are open as the track buffer
1808 // size depends on frame count and correct behavior would not be garantied
1809 // if frame count is changed after track creation
1810 if (!mTracks.isEmpty()) {
1811 status = INVALID_OPERATION;
1812 } else {
1813 reconfig = true;
1814 }
1815 }
1816 if (status == NO_ERROR) {
Eric Laurent3464c012009-08-04 09:45:33 -07001817 status = mOutput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001818 if (!mStandby && status == INVALID_OPERATION) {
1819 mOutput->standby();
1820 mStandby = true;
1821 mBytesWritten = 0;
Eric Laurent3464c012009-08-04 09:45:33 -07001822 status = mOutput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001823 }
1824 if (status == NO_ERROR && reconfig) {
1825 readOutputParameters();
Eric Laurent3464c012009-08-04 09:45:33 -07001826 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001827 }
1828 }
1829 mParamStatus = status;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001830 mParamCond.signal();
Eric Laurent3464c012009-08-04 09:45:33 -07001831 mWaitWorkCV.wait(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001832 }
1833 return reconfig;
The Android Open Source Projecte41dd752009-01-22 00:13:42 -08001834}
1835
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001836// ----------------------------------------------------------------------------
1837
Eric Laurent9d91ad52009-07-17 12:17:14 -07001838AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread)
1839 : MixerThread(audioFlinger, mainThread->getOutput())
1840{
1841 mType = PlaybackThread::DUPLICATING;
1842 addOutputTrack(mainThread);
1843}
1844
1845AudioFlinger::DuplicatingThread::~DuplicatingThread()
1846{
1847 mOutputTracks.clear();
1848}
1849
1850bool AudioFlinger::DuplicatingThread::threadLoop()
1851{
1852 unsigned long sleepTime = kBufferRecoveryInUsecs;
1853 int16_t* curBuf = mMixBuffer;
1854 Vector< sp<Track> > tracksToRemove;
1855 size_t enabledTracks = 0;
1856 nsecs_t standbyTime = systemTime();
1857 size_t mixBufferSize = mFrameCount*mFrameSize;
1858 SortedVector< sp<OutputTrack> > outputTracks;
1859
1860 while (!exitPending())
1861 {
1862 processConfigEvents();
1863
1864 enabledTracks = 0;
1865 { // scope for the mLock
1866
1867 Mutex::Autolock _l(mLock);
1868
1869 if (checkForNewParameters_l()) {
1870 mixBufferSize = mFrameCount*mFrameSize;
1871 }
1872
1873 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1874
1875 for (size_t i = 0; i < mOutputTracks.size(); i++) {
1876 outputTracks.add(mOutputTracks[i]);
1877 }
1878
1879 // put audio hardware into standby after short delay
1880 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1881 mSuspended) {
1882 if (!mStandby) {
1883 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07001884 outputTracks[i]->stop();
Eric Laurent9d91ad52009-07-17 12:17:14 -07001885 }
1886 mStandby = true;
1887 mBytesWritten = 0;
1888 }
1889
1890 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1891 // we're about to wait, flush the binder command buffer
1892 IPCThreadState::self()->flushCommands();
1893 outputTracks.clear();
1894
1895 if (exitPending()) break;
1896
1897 LOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
1898 mWaitWorkCV.wait(mLock);
1899 LOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
1900 if (mMasterMute == false) {
1901 char value[PROPERTY_VALUE_MAX];
1902 property_get("ro.audio.silent", value, "0");
1903 if (atoi(value)) {
1904 LOGD("Silence is golden");
1905 setMasterMute(true);
1906 }
1907 }
1908
1909 standbyTime = systemTime() + kStandbyTimeInNsecs;
1910 sleepTime = kBufferRecoveryInUsecs;
1911 continue;
1912 }
1913 }
1914
1915 enabledTracks = prepareTracks_l(activeTracks, &tracksToRemove);
1916 }
1917
1918 bool mustSleep = true;
1919 if (LIKELY(enabledTracks)) {
1920 // mix buffers...
1921 mAudioMixer->process(curBuf);
1922 if (!mSuspended) {
1923 for (size_t i = 0; i < outputTracks.size(); i++) {
1924 outputTracks[i]->write(curBuf, mFrameCount);
Eric Laurentf5aba822009-08-10 23:22:32 -07001925 mustSleep = false;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001926 }
1927 mStandby = false;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001928 mBytesWritten += mixBufferSize;
1929 }
1930 } else {
1931 // flush remaining overflow buffers in output tracks
1932 for (size_t i = 0; i < outputTracks.size(); i++) {
1933 if (outputTracks[i]->isActive()) {
1934 outputTracks[i]->write(curBuf, 0);
1935 standbyTime = systemTime() + kStandbyTimeInNsecs;
1936 mustSleep = false;
1937 }
1938 }
1939 }
1940 if (mustSleep) {
1941// LOGV("threadLoop() sleeping %d", sleepTime);
1942 usleep(sleepTime);
1943 if (sleepTime < kMaxBufferRecoveryInUsecs) {
1944 sleepTime += kBufferRecoveryInUsecs;
1945 }
1946 } else {
1947 sleepTime = kBufferRecoveryInUsecs;
1948 }
1949
1950 // finally let go of all our tracks, without the lock held
1951 // since we can't guarantee the destructors won't acquire that
1952 // same lock.
1953 tracksToRemove.clear();
1954 outputTracks.clear();
1955 }
1956
Eric Laurentf5aba822009-08-10 23:22:32 -07001957 { // scope for the mLock
1958
1959 Mutex::Autolock _l(mLock);
1960 if (!mStandby) {
1961 LOGV("DuplicatingThread() exiting out of standby");
1962 for (size_t i = 0; i < mOutputTracks.size(); i++) {
1963 mOutputTracks[i]->destroy();
1964 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07001965 }
1966 }
1967
Eric Laurent9d91ad52009-07-17 12:17:14 -07001968 return false;
1969}
1970
1971void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
1972{
1973 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
1974 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
1975 mSampleRate,
1976 mFormat,
1977 mChannelCount,
1978 frameCount);
Eric Laurentf5aba822009-08-10 23:22:32 -07001979 if (outputTrack->cblk() != NULL) {
1980 thread->setStreamVolume(AudioSystem::NUM_STREAM_TYPES, 1.0f);
1981 mOutputTracks.add(outputTrack);
1982 LOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
1983 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07001984}
1985
1986void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
1987{
1988 Mutex::Autolock _l(mLock);
1989 for (size_t i = 0; i < mOutputTracks.size(); i++) {
1990 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
Eric Laurentf5aba822009-08-10 23:22:32 -07001991 mOutputTracks[i]->destroy();
Eric Laurent9d91ad52009-07-17 12:17:14 -07001992 mOutputTracks.removeAt(i);
1993 return;
1994 }
1995 }
1996 LOGV("removeOutputTrack(): unkonwn thread: %p", thread);
1997}
1998
1999
2000// ----------------------------------------------------------------------------
2001
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002002// TrackBase constructor must be called with AudioFlinger::mLock held
Eric Laurent9d91ad52009-07-17 12:17:14 -07002003AudioFlinger::ThreadBase::TrackBase::TrackBase(
2004 const wp<ThreadBase>& thread,
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002005 const sp<Client>& client,
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002006 uint32_t sampleRate,
2007 int format,
2008 int channelCount,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002009 int frameCount,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002010 uint32_t flags,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002011 const sp<IMemory>& sharedBuffer)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002012 : RefBase(),
Eric Laurent9d91ad52009-07-17 12:17:14 -07002013 mThread(thread),
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002014 mClient(client),
Eric Laurent6ad8c642009-09-09 05:16:08 -07002015 mCblk(0),
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002016 mFrameCount(0),
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002017 mState(IDLE),
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002018 mClientTid(-1),
2019 mFormat(format),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002020 mFlags(flags & ~SYSTEM_FLAGS_MASK)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002021{
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002022 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
2023
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002024 // LOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002025 size_t size = sizeof(audio_track_cblk_t);
2026 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
2027 if (sharedBuffer == 0) {
2028 size += bufferSize;
2029 }
2030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002031 if (client != NULL) {
2032 mCblkMemory = client->heap()->allocate(size);
2033 if (mCblkMemory != 0) {
2034 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
2035 if (mCblk) { // construct the shared structure in-place.
2036 new(mCblk) audio_track_cblk_t();
2037 // clear all buffers
2038 mCblk->frameCount = frameCount;
Eric Laurent0bac5382009-07-07 07:10:45 -07002039 mCblk->sampleRate = sampleRate;
2040 mCblk->channels = (uint8_t)channelCount;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002041 if (sharedBuffer == 0) {
2042 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2043 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2044 // Force underrun condition to avoid false underrun callback until first data is
2045 // written to buffer
2046 mCblk->flowControlFlag = 1;
2047 } else {
2048 mBuffer = sharedBuffer->pointer();
2049 }
2050 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002051 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002052 } else {
2053 LOGE("not enough memory for AudioTrack size=%u", size);
2054 client->heap()->dump("AudioTrack");
2055 return;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002056 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002057 } else {
2058 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
2059 if (mCblk) { // construct the shared structure in-place.
2060 new(mCblk) audio_track_cblk_t();
2061 // clear all buffers
2062 mCblk->frameCount = frameCount;
Eric Laurent0bac5382009-07-07 07:10:45 -07002063 mCblk->sampleRate = sampleRate;
2064 mCblk->channels = (uint8_t)channelCount;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002065 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2066 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2067 // Force underrun condition to avoid false underrun callback until first data is
2068 // written to buffer
2069 mCblk->flowControlFlag = 1;
2070 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
2071 }
2072 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002073}
2074
Eric Laurentbdc0f842009-09-16 06:02:45 -07002075AudioFlinger::ThreadBase::TrackBase::~TrackBase()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002076{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002077 if (mCblk) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07002078 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
2079 if (mClient == NULL) {
2080 delete mCblk;
2081 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002082 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002083 mCblkMemory.clear(); // and free the shared memory
Eric Laurent0f8ab672009-09-17 05:12:56 -07002084 if (mClient != NULL) {
2085 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
2086 mClient.clear();
2087 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002088}
2089
Eric Laurentbdc0f842009-09-16 06:02:45 -07002090void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002091{
2092 buffer->raw = 0;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002093 mFrameCount = buffer->frameCount;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002094 step();
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002095 buffer->frameCount = 0;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002096}
2097
Eric Laurentbdc0f842009-09-16 06:02:45 -07002098bool AudioFlinger::ThreadBase::TrackBase::step() {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002099 bool result;
2100 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002101
2102 result = cblk->stepServer(mFrameCount);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002103 if (!result) {
2104 LOGV("stepServer failed acquiring cblk mutex");
2105 mFlags |= STEPSERVER_FAILED;
2106 }
2107 return result;
2108}
2109
Eric Laurentbdc0f842009-09-16 06:02:45 -07002110void AudioFlinger::ThreadBase::TrackBase::reset() {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002111 audio_track_cblk_t* cblk = this->cblk();
2112
2113 cblk->user = 0;
2114 cblk->server = 0;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002115 cblk->userBase = 0;
2116 cblk->serverBase = 0;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002117 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002118 LOGV("TrackBase::reset");
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002119}
2120
Eric Laurentbdc0f842009-09-16 06:02:45 -07002121sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002122{
2123 return mCblkMemory;
2124}
2125
Eric Laurentbdc0f842009-09-16 06:02:45 -07002126int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
The Android Open Source Project4f68be12009-03-18 17:39:46 -07002127 return (int)mCblk->sampleRate;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002128}
2129
Eric Laurentbdc0f842009-09-16 06:02:45 -07002130int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
Eric Laurent0bac5382009-07-07 07:10:45 -07002131 return (int)mCblk->channels;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002132}
2133
Eric Laurentbdc0f842009-09-16 06:02:45 -07002134void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002135 audio_track_cblk_t* cblk = this->cblk();
Eric Laurent9d91ad52009-07-17 12:17:14 -07002136 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
2137 int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002138
2139 // Check validity of returned pointer in case the track control block would have been corrupted.
Eric Laurent9d91ad52009-07-17 12:17:14 -07002140 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
2141 ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
The Android Open Source Project4f68be12009-03-18 17:39:46 -07002142 LOGE("TrackBase::getBuffer buffer out of range:\n start: %p, end %p , mBuffer %p mBufferEnd %p\n \
2143 server %d, serverBase %d, user %d, userBase %d, channels %d",
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002144 bufferStart, bufferEnd, mBuffer, mBufferEnd,
The Android Open Source Project4f68be12009-03-18 17:39:46 -07002145 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, cblk->channels);
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002146 return 0;
2147 }
2148
2149 return bufferStart;
2150}
2151
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002152// ----------------------------------------------------------------------------
2153
Eric Laurent9d91ad52009-07-17 12:17:14 -07002154// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
2155AudioFlinger::PlaybackThread::Track::Track(
2156 const wp<ThreadBase>& thread,
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002157 const sp<Client>& client,
2158 int streamType,
2159 uint32_t sampleRate,
2160 int format,
2161 int channelCount,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002162 int frameCount,
2163 const sp<IMemory>& sharedBuffer)
Eric Laurent9d91ad52009-07-17 12:17:14 -07002164 : TrackBase(thread, client, sampleRate, format, channelCount, frameCount, 0, sharedBuffer),
2165 mMute(false), mSharedBuffer(sharedBuffer), mName(-1)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002166{
Eric Laurent6ad8c642009-09-09 05:16:08 -07002167 if (mCblk != NULL) {
2168 sp<ThreadBase> baseThread = thread.promote();
2169 if (baseThread != 0) {
2170 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
2171 mName = playbackThread->getTrackName_l();
2172 }
2173 LOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2174 if (mName < 0) {
2175 LOGE("no more track names available");
2176 }
2177 mVolume[0] = 1.0f;
2178 mVolume[1] = 1.0f;
2179 mStreamType = streamType;
2180 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
2181 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
2182 mCblk->frameSize = AudioSystem::isLinearPCM(format) ? channelCount * sizeof(int16_t) : sizeof(int8_t);
Eric Laurent9d91ad52009-07-17 12:17:14 -07002183 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002184}
2185
Eric Laurent9d91ad52009-07-17 12:17:14 -07002186AudioFlinger::PlaybackThread::Track::~Track()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002187{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002188 LOGV("PlaybackThread::Track destructor");
2189 sp<ThreadBase> thread = mThread.promote();
2190 if (thread != 0) {
2191 Mutex::Autolock _l(thread->mLock);
2192 mState = TERMINATED;
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002193 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002194}
2195
Eric Laurent9d91ad52009-07-17 12:17:14 -07002196void AudioFlinger::PlaybackThread::Track::destroy()
2197{
2198 // NOTE: destroyTrack_l() can remove a strong reference to this Track
2199 // by removing it from mTracks vector, so there is a risk that this Tracks's
2200 // desctructor is called. As the destructor needs to lock mLock,
2201 // we must acquire a strong reference on this Track before locking mLock
2202 // here so that the destructor is called only when exiting this function.
2203 // On the other hand, as long as Track::destroy() is only called by
2204 // TrackHandle destructor, the TrackHandle still holds a strong ref on
2205 // this Track with its member mTrack.
2206 sp<Track> keep(this);
2207 { // scope for mLock
2208 sp<ThreadBase> thread = mThread.promote();
2209 if (thread != 0) {
2210 Mutex::Autolock _l(thread->mLock);
2211 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2212 playbackThread->destroyTrack_l(this);
2213 }
2214 }
2215}
2216
2217void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002218{
2219 snprintf(buffer, size, " %5d %5d %3u %3u %3u %3u %1d %1d %1d %5u %5u %5u %04x %04x\n",
2220 mName - AudioMixer::TRACK0,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002221 (mClient == NULL) ? getpid() : mClient->pid(),
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002222 mStreamType,
2223 mFormat,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002224 mCblk->channels,
2225 mFrameCount,
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002226 mState,
2227 mMute,
2228 mFillingUpStatus,
2229 mCblk->sampleRate,
2230 mCblk->volume[0],
2231 mCblk->volume[1],
2232 mCblk->server,
2233 mCblk->user);
2234}
2235
Eric Laurent9d91ad52009-07-17 12:17:14 -07002236status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002237{
2238 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002239 uint32_t framesReady;
2240 uint32_t framesReq = buffer->frameCount;
2241
2242 // Check if last stepServer failed, try to step now
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002243 if (mFlags & TrackBase::STEPSERVER_FAILED) {
2244 if (!step()) goto getNextBuffer_exit;
2245 LOGV("stepServer recovered");
2246 mFlags &= ~TrackBase::STEPSERVER_FAILED;
2247 }
2248
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002249 framesReady = cblk->framesReady();
2250
2251 if (LIKELY(framesReady)) {
2252 uint32_t s = cblk->server;
2253 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
2254
2255 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
2256 if (framesReq > framesReady) {
2257 framesReq = framesReady;
2258 }
2259 if (s + framesReq > bufferEnd) {
2260 framesReq = bufferEnd - s;
2261 }
2262
2263 buffer->raw = getBuffer(s, framesReq);
2264 if (buffer->raw == 0) goto getNextBuffer_exit;
2265
2266 buffer->frameCount = framesReq;
2267 return NO_ERROR;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002268 }
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002269
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002270getNextBuffer_exit:
2271 buffer->raw = 0;
2272 buffer->frameCount = 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002273 LOGV("getNextBuffer() no more data");
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002274 return NOT_ENOUGH_DATA;
2275}
2276
Eric Laurent9d91ad52009-07-17 12:17:14 -07002277bool AudioFlinger::PlaybackThread::Track::isReady() const {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002278 if (mFillingUpStatus != FS_FILLING) return true;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002279
2280 if (mCblk->framesReady() >= mCblk->frameCount ||
2281 mCblk->forceReady) {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002282 mFillingUpStatus = FS_FILLED;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002283 mCblk->forceReady = 0;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002284 return true;
2285 }
2286 return false;
2287}
2288
Eric Laurent9d91ad52009-07-17 12:17:14 -07002289status_t AudioFlinger::PlaybackThread::Track::start()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002290{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002291 LOGV("start(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2292 sp<ThreadBase> thread = mThread.promote();
2293 if (thread != 0) {
2294 Mutex::Autolock _l(thread->mLock);
2295 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2296 playbackThread->addTrack_l(this);
2297 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002298 return NO_ERROR;
2299}
2300
Eric Laurent9d91ad52009-07-17 12:17:14 -07002301void AudioFlinger::PlaybackThread::Track::stop()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002302{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002303 LOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2304 sp<ThreadBase> thread = mThread.promote();
2305 if (thread != 0) {
2306 Mutex::Autolock _l(thread->mLock);
2307 if (mState > STOPPED) {
2308 mState = STOPPED;
2309 // If the track is not active (PAUSED and buffers full), flush buffers
2310 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2311 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
2312 reset();
2313 }
2314 LOGV("(> STOPPED) => STOPPED (%d)", mName);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002315 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002316 }
2317}
2318
Eric Laurent9d91ad52009-07-17 12:17:14 -07002319void AudioFlinger::PlaybackThread::Track::pause()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002320{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002321 LOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
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 == ACTIVE || mState == RESUMING) {
2326 mState = PAUSING;
2327 LOGV("ACTIVE/RESUMING => PAUSING (%d)", mName);
2328 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002329 }
2330}
2331
Eric Laurent9d91ad52009-07-17 12:17:14 -07002332void AudioFlinger::PlaybackThread::Track::flush()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002333{
2334 LOGV("flush(%d)", mName);
Eric Laurent9d91ad52009-07-17 12:17:14 -07002335 sp<ThreadBase> thread = mThread.promote();
2336 if (thread != 0) {
2337 Mutex::Autolock _l(thread->mLock);
2338 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
2339 return;
2340 }
2341 // No point remaining in PAUSED state after a flush => go to
2342 // STOPPED state
2343 mState = STOPPED;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002344
Eric Laurent9d91ad52009-07-17 12:17:14 -07002345 mCblk->lock.lock();
2346 // NOTE: reset() will reset cblk->user and cblk->server with
2347 // the risk that at the same time, the AudioMixer is trying to read
2348 // data. In this case, getNextBuffer() would return a NULL pointer
2349 // as audio buffer => the AudioMixer code MUST always test that pointer
2350 // returned by getNextBuffer() is not NULL!
2351 reset();
2352 mCblk->lock.unlock();
2353 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002354}
2355
Eric Laurent9d91ad52009-07-17 12:17:14 -07002356void AudioFlinger::PlaybackThread::Track::reset()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002357{
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002358 // Do not reset twice to avoid discarding data written just after a flush and before
2359 // the audioflinger thread detects the track is stopped.
2360 if (!mResetDone) {
2361 TrackBase::reset();
2362 // Force underrun condition to avoid false underrun callback until first data is
2363 // written to buffer
2364 mCblk->flowControlFlag = 1;
2365 mCblk->forceReady = 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002366 mFillingUpStatus = FS_FILLING;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002367 mResetDone = true;
2368 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002369}
2370
Eric Laurent9d91ad52009-07-17 12:17:14 -07002371void AudioFlinger::PlaybackThread::Track::mute(bool muted)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002372{
2373 mMute = muted;
2374}
2375
Eric Laurent9d91ad52009-07-17 12:17:14 -07002376void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002377{
2378 mVolume[0] = left;
2379 mVolume[1] = right;
2380}
2381
2382// ----------------------------------------------------------------------------
2383
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002384// RecordTrack constructor must be called with AudioFlinger::mLock held
Eric Laurent9d91ad52009-07-17 12:17:14 -07002385AudioFlinger::RecordThread::RecordTrack::RecordTrack(
2386 const wp<ThreadBase>& thread,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002387 const sp<Client>& client,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002388 uint32_t sampleRate,
2389 int format,
2390 int channelCount,
2391 int frameCount,
2392 uint32_t flags)
Eric Laurent9d91ad52009-07-17 12:17:14 -07002393 : TrackBase(thread, client, sampleRate, format,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002394 channelCount, frameCount, flags, 0),
Eric Laurent9d91ad52009-07-17 12:17:14 -07002395 mOverflow(false)
2396{
Eric Laurent6ad8c642009-09-09 05:16:08 -07002397 if (mCblk != NULL) {
2398 LOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
2399 if (format == AudioSystem::PCM_16_BIT) {
2400 mCblk->frameSize = channelCount * sizeof(int16_t);
2401 } else if (format == AudioSystem::PCM_8_BIT) {
2402 mCblk->frameSize = channelCount * sizeof(int8_t);
2403 } else {
2404 mCblk->frameSize = sizeof(int8_t);
2405 }
2406 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002407}
2408
2409AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002410{
2411}
2412
Eric Laurent9d91ad52009-07-17 12:17:14 -07002413status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002414{
2415 audio_track_cblk_t* cblk = this->cblk();
2416 uint32_t framesAvail;
2417 uint32_t framesReq = buffer->frameCount;
2418
2419 // Check if last stepServer failed, try to step now
2420 if (mFlags & TrackBase::STEPSERVER_FAILED) {
2421 if (!step()) goto getNextBuffer_exit;
2422 LOGV("stepServer recovered");
2423 mFlags &= ~TrackBase::STEPSERVER_FAILED;
2424 }
2425
2426 framesAvail = cblk->framesAvailable_l();
2427
2428 if (LIKELY(framesAvail)) {
2429 uint32_t s = cblk->server;
2430 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
2431
2432 if (framesReq > framesAvail) {
2433 framesReq = framesAvail;
2434 }
2435 if (s + framesReq > bufferEnd) {
2436 framesReq = bufferEnd - s;
2437 }
2438
2439 buffer->raw = getBuffer(s, framesReq);
2440 if (buffer->raw == 0) goto getNextBuffer_exit;
2441
2442 buffer->frameCount = framesReq;
2443 return NO_ERROR;
2444 }
2445
2446getNextBuffer_exit:
2447 buffer->raw = 0;
2448 buffer->frameCount = 0;
2449 return NOT_ENOUGH_DATA;
2450}
2451
Eric Laurent9d91ad52009-07-17 12:17:14 -07002452status_t AudioFlinger::RecordThread::RecordTrack::start()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002453{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002454 sp<ThreadBase> thread = mThread.promote();
2455 if (thread != 0) {
2456 RecordThread *recordThread = (RecordThread *)thread.get();
2457 return recordThread->start(this);
2458 }
2459 return NO_INIT;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002460}
2461
Eric Laurent9d91ad52009-07-17 12:17:14 -07002462void AudioFlinger::RecordThread::RecordTrack::stop()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002463{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002464 sp<ThreadBase> thread = mThread.promote();
2465 if (thread != 0) {
2466 RecordThread *recordThread = (RecordThread *)thread.get();
2467 recordThread->stop(this);
2468 TrackBase::reset();
2469 // Force overerrun condition to avoid false overrun callback until first data is
2470 // read from buffer
2471 mCblk->flowControlFlag = 1;
2472 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002473}
2474
2475
2476// ----------------------------------------------------------------------------
2477
Eric Laurent9d91ad52009-07-17 12:17:14 -07002478AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
2479 const wp<ThreadBase>& thread,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002480 uint32_t sampleRate,
2481 int format,
2482 int channelCount,
2483 int frameCount)
Eric Laurent9d91ad52009-07-17 12:17:14 -07002484 : Track(thread, NULL, AudioSystem::NUM_STREAM_TYPES, sampleRate, format, channelCount, frameCount, NULL),
2485 mActive(false)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002486{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002487
2488 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
Eric Laurentf5aba822009-08-10 23:22:32 -07002489 if (mCblk != NULL) {
2490 mCblk->out = 1;
2491 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
2492 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
2493 mOutBuffer.frameCount = 0;
2494 mWaitTimeMs = (playbackThread->frameCount() * 2 * 1000) / playbackThread->sampleRate();
2495 playbackThread->mTracks.add(this);
2496 LOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, mCblk->frameCount %d, mCblk->sampleRate %d, mCblk->channels %d mBufferEnd %p mWaitTimeMs %d",
2497 mCblk, mBuffer, mCblk->buffers, mCblk->frameCount, mCblk->sampleRate, mCblk->channels, mBufferEnd, mWaitTimeMs);
2498 } else {
2499 LOGW("Error creating output track on thread %p", playbackThread);
2500 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002501}
2502
Eric Laurent9d91ad52009-07-17 12:17:14 -07002503AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002504{
Eric Laurentf5aba822009-08-10 23:22:32 -07002505 clearBufferQueue();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002506}
2507
Eric Laurent9d91ad52009-07-17 12:17:14 -07002508status_t AudioFlinger::PlaybackThread::OutputTrack::start()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002509{
2510 status_t status = Track::start();
Eric Laurent9d91ad52009-07-17 12:17:14 -07002511 if (status != NO_ERROR) {
2512 return status;
2513 }
2514
2515 mActive = true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002516 mRetryCount = 127;
2517 return status;
2518}
2519
Eric Laurent9d91ad52009-07-17 12:17:14 -07002520void AudioFlinger::PlaybackThread::OutputTrack::stop()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002521{
2522 Track::stop();
2523 clearBufferQueue();
2524 mOutBuffer.frameCount = 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002525 mActive = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002526}
2527
Eric Laurent9d91ad52009-07-17 12:17:14 -07002528bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002529{
2530 Buffer *pInBuffer;
2531 Buffer inBuffer;
2532 uint32_t channels = mCblk->channels;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002533 bool outputBufferFull = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002534 inBuffer.frameCount = frames;
2535 inBuffer.i16 = data;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002536
2537 uint32_t waitTimeLeftMs = mWaitTimeMs;
2538
2539 if (!mActive) {
2540 start();
2541 sp<ThreadBase> thread = mThread.promote();
2542 if (thread != 0) {
2543 MixerThread *mixerThread = (MixerThread *)thread.get();
2544 if (mCblk->frameCount > frames){
2545 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
2546 uint32_t startFrames = (mCblk->frameCount - frames);
2547 pInBuffer = new Buffer;
2548 pInBuffer->mBuffer = new int16_t[startFrames * channels];
2549 pInBuffer->frameCount = startFrames;
2550 pInBuffer->i16 = pInBuffer->mBuffer;
2551 memset(pInBuffer->raw, 0, startFrames * channels * sizeof(int16_t));
2552 mBufferQueue.add(pInBuffer);
2553 } else {
2554 LOGW ("OutputTrack::write() %p no more buffers in queue", this);
2555 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002556 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002557 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002558 }
2559
Eric Laurent9d91ad52009-07-17 12:17:14 -07002560 while (waitTimeLeftMs) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002561 // First write pending buffers, then new data
2562 if (mBufferQueue.size()) {
2563 pInBuffer = mBufferQueue.itemAt(0);
2564 } else {
2565 pInBuffer = &inBuffer;
2566 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002567
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002568 if (pInBuffer->frameCount == 0) {
2569 break;
2570 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002571
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002572 if (mOutBuffer.frameCount == 0) {
2573 mOutBuffer.frameCount = pInBuffer->frameCount;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002574 nsecs_t startTime = systemTime();
2575 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
2576 LOGV ("OutputTrack::write() %p no more output buffers", this);
2577 outputBufferFull = true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002578 break;
2579 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002580 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
2581// LOGV("OutputTrack::write() waitTimeMs %d waitTimeLeftMs %d", waitTimeMs, waitTimeLeftMs)
2582 if (waitTimeLeftMs >= waitTimeMs) {
2583 waitTimeLeftMs -= waitTimeMs;
2584 } else {
2585 waitTimeLeftMs = 0;
2586 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002587 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002588
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002589 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
2590 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channels * sizeof(int16_t));
2591 mCblk->stepUser(outFrames);
2592 pInBuffer->frameCount -= outFrames;
2593 pInBuffer->i16 += outFrames * channels;
2594 mOutBuffer.frameCount -= outFrames;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002595 mOutBuffer.i16 += outFrames * channels;
2596
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002597 if (pInBuffer->frameCount == 0) {
2598 if (mBufferQueue.size()) {
2599 mBufferQueue.removeAt(0);
2600 delete [] pInBuffer->mBuffer;
2601 delete pInBuffer;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002602 LOGV("OutputTrack::write() %p released overflow buffer %d", this, mBufferQueue.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002603 } else {
2604 break;
2605 }
2606 }
2607 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002608
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002609 // If we could not write all frames, allocate a buffer and queue it for next time.
2610 if (inBuffer.frameCount) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07002611 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002612 pInBuffer = new Buffer;
2613 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channels];
2614 pInBuffer->frameCount = inBuffer.frameCount;
2615 pInBuffer->i16 = pInBuffer->mBuffer;
2616 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channels * sizeof(int16_t));
2617 mBufferQueue.add(pInBuffer);
Eric Laurent9d91ad52009-07-17 12:17:14 -07002618 LOGV("OutputTrack::write() %p adding overflow buffer %d", this, mBufferQueue.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002619 } else {
Eric Laurent9d91ad52009-07-17 12:17:14 -07002620 LOGW("OutputTrack::write() %p no more overflow buffers", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002621 }
2622 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002623
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002624 // Calling write() with a 0 length buffer, means that no more data will be written:
Eric Laurent9d91ad52009-07-17 12:17:14 -07002625 // 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 -08002626 // by output mixer.
Eric Laurent9d91ad52009-07-17 12:17:14 -07002627 if (frames == 0 && mBufferQueue.size() == 0) {
2628 if (mCblk->user < mCblk->frameCount) {
2629 frames = mCblk->frameCount - mCblk->user;
2630 pInBuffer = new Buffer;
2631 pInBuffer->mBuffer = new int16_t[frames * channels];
2632 pInBuffer->frameCount = frames;
2633 pInBuffer->i16 = pInBuffer->mBuffer;
2634 memset(pInBuffer->raw, 0, frames * channels * sizeof(int16_t));
2635 mBufferQueue.add(pInBuffer);
2636 } else {
2637 stop();
2638 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002639 }
2640
Eric Laurent9d91ad52009-07-17 12:17:14 -07002641 return outputBufferFull;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002642}
2643
Eric Laurent9d91ad52009-07-17 12:17:14 -07002644status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002645{
2646 int active;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002647 status_t result;
2648 audio_track_cblk_t* cblk = mCblk;
2649 uint32_t framesReq = buffer->frameCount;
2650
Eric Laurent9d91ad52009-07-17 12:17:14 -07002651// LOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002652 buffer->frameCount = 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002653
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002654 uint32_t framesAvail = cblk->framesAvailable();
2655
Eric Laurent9d91ad52009-07-17 12:17:14 -07002656
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002657 if (framesAvail == 0) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07002658 Mutex::Autolock _l(cblk->lock);
2659 goto start_loop_here;
2660 while (framesAvail == 0) {
2661 active = mActive;
2662 if (UNLIKELY(!active)) {
2663 LOGV("Not active and NO_MORE_BUFFERS");
2664 return AudioTrack::NO_MORE_BUFFERS;
2665 }
2666 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
2667 if (result != NO_ERROR) {
2668 return AudioTrack::NO_MORE_BUFFERS;
2669 }
2670 // read the server count again
2671 start_loop_here:
2672 framesAvail = cblk->framesAvailable_l();
2673 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002674 }
2675
Eric Laurent9d91ad52009-07-17 12:17:14 -07002676// if (framesAvail < framesReq) {
2677// return AudioTrack::NO_MORE_BUFFERS;
2678// }
2679
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002680 if (framesReq > framesAvail) {
2681 framesReq = framesAvail;
2682 }
2683
2684 uint32_t u = cblk->user;
2685 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
2686
2687 if (u + framesReq > bufferEnd) {
2688 framesReq = bufferEnd - u;
2689 }
2690
2691 buffer->frameCount = framesReq;
2692 buffer->raw = (void *)cblk->buffer(u);
2693 return NO_ERROR;
2694}
2695
2696
Eric Laurent9d91ad52009-07-17 12:17:14 -07002697void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002698{
2699 size_t size = mBufferQueue.size();
2700 Buffer *pBuffer;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002701
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002702 for (size_t i = 0; i < size; i++) {
2703 pBuffer = mBufferQueue.itemAt(i);
2704 delete [] pBuffer->mBuffer;
2705 delete pBuffer;
2706 }
2707 mBufferQueue.clear();
2708}
2709
2710// ----------------------------------------------------------------------------
2711
2712AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
2713 : RefBase(),
2714 mAudioFlinger(audioFlinger),
2715 mMemoryDealer(new MemoryDealer(1024*1024)),
2716 mPid(pid)
2717{
2718 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
2719}
2720
Eric Laurent0f8ab672009-09-17 05:12:56 -07002721// Client destructor must be called with AudioFlinger::mLock held
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002722AudioFlinger::Client::~Client()
2723{
Eric Laurent0f8ab672009-09-17 05:12:56 -07002724 mAudioFlinger->removeClient_l(mPid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002725}
2726
2727const sp<MemoryDealer>& AudioFlinger::Client::heap() const
2728{
2729 return mMemoryDealer;
2730}
2731
2732// ----------------------------------------------------------------------------
2733
Eric Laurent9d91ad52009-07-17 12:17:14 -07002734AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002735 : BnAudioTrack(),
2736 mTrack(track)
2737{
2738}
2739
2740AudioFlinger::TrackHandle::~TrackHandle() {
2741 // just stop the track on deletion, associated resources
2742 // will be freed from the main thread once all pending buffers have
2743 // been played. Unless it's not in the active track list, in which
2744 // case we free everything now...
2745 mTrack->destroy();
2746}
2747
2748status_t AudioFlinger::TrackHandle::start() {
2749 return mTrack->start();
2750}
2751
2752void AudioFlinger::TrackHandle::stop() {
2753 mTrack->stop();
2754}
2755
2756void AudioFlinger::TrackHandle::flush() {
2757 mTrack->flush();
2758}
2759
2760void AudioFlinger::TrackHandle::mute(bool e) {
2761 mTrack->mute(e);
2762}
2763
2764void AudioFlinger::TrackHandle::pause() {
2765 mTrack->pause();
2766}
2767
2768void AudioFlinger::TrackHandle::setVolume(float left, float right) {
2769 mTrack->setVolume(left, right);
2770}
2771
2772sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
2773 return mTrack->getCblk();
2774}
2775
2776status_t AudioFlinger::TrackHandle::onTransact(
2777 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2778{
2779 return BnAudioTrack::onTransact(code, data, reply, flags);
2780}
2781
2782// ----------------------------------------------------------------------------
2783
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002784sp<IAudioRecord> AudioFlinger::openRecord(
2785 pid_t pid,
Eric Laurente0e9ecc2009-07-28 08:44:33 -07002786 int input,
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002787 uint32_t sampleRate,
2788 int format,
2789 int channelCount,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002790 int frameCount,
2791 uint32_t flags,
2792 status_t *status)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002793{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002794 sp<RecordThread::RecordTrack> recordTrack;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002795 sp<RecordHandle> recordHandle;
2796 sp<Client> client;
2797 wp<Client> wclient;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002798 status_t lStatus;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002799 RecordThread *thread;
2800 size_t inFrameCount;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002801
2802 // check calling permissions
2803 if (!recordingAllowed()) {
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002804 lStatus = PERMISSION_DENIED;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002805 goto Exit;
2806 }
2807
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002808 // add client to list
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002809 { // scope for mLock
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002810 Mutex::Autolock _l(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07002811 thread = checkRecordThread_l(input);
2812 if (thread == NULL) {
2813 lStatus = BAD_VALUE;
2814 goto Exit;
2815 }
2816
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002817 wclient = mClients.valueFor(pid);
2818 if (wclient != NULL) {
2819 client = wclient.promote();
2820 } else {
2821 client = new Client(this, pid);
2822 mClients.add(pid, client);
2823 }
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002824
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002825 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent9d91ad52009-07-17 12:17:14 -07002826 recordTrack = new RecordThread::RecordTrack(thread, client, sampleRate,
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002827 format, channelCount, frameCount, flags);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002828 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002829 if (recordTrack->getCblk() == NULL) {
Eric Laurent0f8ab672009-09-17 05:12:56 -07002830 // remove local strong reference to Client before deleting the RecordTrack so that the Client
2831 // destructor is called by the TrackBase destructor with mLock held
2832 client.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002833 recordTrack.clear();
2834 lStatus = NO_MEMORY;
2835 goto Exit;
2836 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002837
2838 // return to handle to client
2839 recordHandle = new RecordHandle(recordTrack);
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002840 lStatus = NO_ERROR;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002841
2842Exit:
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002843 if (status) {
2844 *status = lStatus;
2845 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002846 return recordHandle;
2847}
2848
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002849// ----------------------------------------------------------------------------
2850
Eric Laurent9d91ad52009-07-17 12:17:14 -07002851AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002852 : BnAudioRecord(),
2853 mRecordTrack(recordTrack)
2854{
2855}
2856
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002857AudioFlinger::RecordHandle::~RecordHandle() {
2858 stop();
2859}
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002860
2861status_t AudioFlinger::RecordHandle::start() {
2862 LOGV("RecordHandle::start()");
2863 return mRecordTrack->start();
2864}
2865
2866void AudioFlinger::RecordHandle::stop() {
2867 LOGV("RecordHandle::stop()");
2868 mRecordTrack->stop();
2869}
2870
2871sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
2872 return mRecordTrack->getCblk();
2873}
2874
2875status_t AudioFlinger::RecordHandle::onTransact(
2876 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2877{
2878 return BnAudioRecord::onTransact(code, data, reply, flags);
2879}
2880
2881// ----------------------------------------------------------------------------
2882
Eric Laurent9d91ad52009-07-17 12:17:14 -07002883AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger, AudioStreamIn *input, uint32_t sampleRate, uint32_t channels) :
2884 ThreadBase(audioFlinger),
2885 mInput(input), mResampler(0), mRsmpOutBuffer(0), mRsmpInBuffer(0)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002886{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002887 mReqChannelCount = AudioSystem::popCount(channels);
2888 mReqSampleRate = sampleRate;
2889 readInputParameters();
2890 sendConfigEvent(AudioSystem::INPUT_OPENED);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002891}
2892
Eric Laurent9d91ad52009-07-17 12:17:14 -07002893
2894AudioFlinger::RecordThread::~RecordThread()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002895{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002896 delete[] mRsmpInBuffer;
2897 if (mResampler != 0) {
2898 delete mResampler;
2899 delete[] mRsmpOutBuffer;
2900 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002901}
2902
Eric Laurent9d91ad52009-07-17 12:17:14 -07002903void AudioFlinger::RecordThread::onFirstRef()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002904{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002905 const size_t SIZE = 256;
2906 char buffer[SIZE];
2907
2908 snprintf(buffer, SIZE, "Record Thread %p", this);
2909
2910 run(buffer, PRIORITY_URGENT_AUDIO);
2911}
2912bool AudioFlinger::RecordThread::threadLoop()
2913{
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002914 AudioBufferProvider::Buffer buffer;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002915 sp<RecordTrack> activeTrack;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002916
2917 // start recording
2918 while (!exitPending()) {
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002919
Eric Laurent9d91ad52009-07-17 12:17:14 -07002920 processConfigEvents();
2921
2922 { // scope for mLock
2923 Mutex::Autolock _l(mLock);
2924 checkForNewParameters_l();
2925 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
2926 if (!mStandby) {
2927 mInput->standby();
2928 mStandby = true;
2929 }
2930
2931 if (exitPending()) break;
2932
2933 LOGV("RecordThread: loop stopping");
2934 // go to sleep
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002935 mWaitWorkCV.wait(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07002936 LOGV("RecordThread: loop starting");
2937 continue;
2938 }
2939 if (mActiveTrack != 0) {
2940 if (mActiveTrack->mState == TrackBase::PAUSING) {
2941 mActiveTrack.clear();
2942 mStartStopCond.broadcast();
2943 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
2944 mRsmpInIndex = mFrameCount;
2945 if (mReqChannelCount != mActiveTrack->channelCount()) {
2946 mActiveTrack.clear();
2947 } else {
Eric Laurent9e7b8192009-08-10 02:41:54 -07002948 mActiveTrack->mState = TrackBase::ACTIVE;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002949 }
2950 mStartStopCond.broadcast();
2951 }
2952 mStandby = false;
2953 }
2954 }
2955
2956 if (mActiveTrack != 0) {
2957 buffer.frameCount = mFrameCount;
2958 if (LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
2959 size_t framesOut = buffer.frameCount;
2960 if (mResampler == 0) {
2961 // no resampling
2962 while (framesOut) {
2963 size_t framesIn = mFrameCount - mRsmpInIndex;
2964 if (framesIn) {
2965 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
2966 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
2967 if (framesIn > framesOut)
2968 framesIn = framesOut;
2969 mRsmpInIndex += framesIn;
2970 framesOut -= framesIn;
2971 if (mChannelCount == mReqChannelCount ||
2972 mFormat != AudioSystem::PCM_16_BIT) {
2973 memcpy(dst, src, framesIn * mFrameSize);
2974 } else {
2975 int16_t *src16 = (int16_t *)src;
2976 int16_t *dst16 = (int16_t *)dst;
2977 if (mChannelCount == 1) {
2978 while (framesIn--) {
2979 *dst16++ = *src16;
2980 *dst16++ = *src16++;
2981 }
2982 } else {
2983 while (framesIn--) {
2984 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
2985 src16 += 2;
2986 }
2987 }
2988 }
2989 }
2990 if (framesOut && mFrameCount == mRsmpInIndex) {
2991 ssize_t bytesRead;
2992 if (framesOut == mFrameCount &&
2993 (mChannelCount == mReqChannelCount || mFormat != AudioSystem::PCM_16_BIT)) {
2994 bytesRead = mInput->read(buffer.raw, mInputBytes);
2995 framesOut = 0;
2996 } else {
2997 bytesRead = mInput->read(mRsmpInBuffer, mInputBytes);
2998 mRsmpInIndex = 0;
2999 }
3000 if (bytesRead < 0) {
3001 LOGE("Error reading audio input");
3002 sleep(1);
3003 mRsmpInIndex = mFrameCount;
3004 framesOut = 0;
3005 buffer.frameCount = 0;
3006 }
3007 }
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003008 }
3009 } else {
Eric Laurent9d91ad52009-07-17 12:17:14 -07003010 // resampling
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003011
Eric Laurent9d91ad52009-07-17 12:17:14 -07003012 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
3013 // alter output frame count as if we were expecting stereo samples
3014 if (mChannelCount == 1 && mReqChannelCount == 1) {
3015 framesOut >>= 1;
3016 }
3017 mResampler->resample(mRsmpOutBuffer, framesOut, this);
3018 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
3019 // are 32 bit aligned which should be always true.
3020 if (mChannelCount == 2 && mReqChannelCount == 1) {
3021 AudioMixer::ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
3022 // the resampler always outputs stereo samples: do post stereo to mono conversion
3023 int16_t *src = (int16_t *)mRsmpOutBuffer;
3024 int16_t *dst = buffer.i16;
3025 while (framesOut--) {
3026 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
3027 src += 2;
3028 }
3029 } else {
3030 AudioMixer::ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
3031 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003032
Eric Laurent9d91ad52009-07-17 12:17:14 -07003033 }
3034 mActiveTrack->releaseBuffer(&buffer);
3035 mActiveTrack->overflow();
3036 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003037 // client isn't retrieving buffers fast enough
3038 else {
Eric Laurent9d91ad52009-07-17 12:17:14 -07003039 if (!mActiveTrack->setOverflow())
3040 LOGW("RecordThread: buffer overflow");
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003041 // Release the processor for a while before asking for a new buffer.
3042 // This will give the application more chance to read from the buffer and
3043 // clear the overflow.
3044 usleep(5000);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003045 }
3046 }
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003047 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003048
Eric Laurent9d91ad52009-07-17 12:17:14 -07003049 if (!mStandby) {
3050 mInput->standby();
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003051 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003052 mActiveTrack.clear();
3053
Eric Laurent9d91ad52009-07-17 12:17:14 -07003054 LOGV("RecordThread %p exiting", this);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003055 return false;
3056}
3057
Eric Laurent9d91ad52009-07-17 12:17:14 -07003058status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003059{
Eric Laurent9d91ad52009-07-17 12:17:14 -07003060 LOGV("RecordThread::start");
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003061 AutoMutex lock(&mLock);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003062
Eric Laurent9d91ad52009-07-17 12:17:14 -07003063 if (mActiveTrack != 0) {
3064 if (recordTrack != mActiveTrack.get()) return -EBUSY;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003065
Eric Laurent9d91ad52009-07-17 12:17:14 -07003066 if (mActiveTrack->mState == TrackBase::PAUSING) mActiveTrack->mState = TrackBase::RESUMING;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003067
Eric Laurent9d91ad52009-07-17 12:17:14 -07003068 return NO_ERROR;
3069 }
3070
3071 mActiveTrack = recordTrack;
3072 mActiveTrack->mState = TrackBase::RESUMING;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003073 // signal thread to start
3074 LOGV("Signal record thread");
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003075 mWaitWorkCV.signal();
Eric Laurent9d91ad52009-07-17 12:17:14 -07003076 mStartStopCond.wait(mLock);
3077 if (mActiveTrack != 0) {
3078 LOGV("Record started OK");
3079 return NO_ERROR;
3080 } else {
3081 LOGV("Record failed to start");
3082 return BAD_VALUE;
3083 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003084}
3085
Eric Laurent9d91ad52009-07-17 12:17:14 -07003086void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
3087 LOGV("RecordThread::stop");
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003088 AutoMutex lock(&mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003089 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
3090 mActiveTrack->mState = TrackBase::PAUSING;
3091 mStartStopCond.wait(mLock);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003092 }
3093}
3094
Eric Laurent9d91ad52009-07-17 12:17:14 -07003095status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003096{
3097 const size_t SIZE = 256;
3098 char buffer[SIZE];
3099 String8 result;
3100 pid_t pid = 0;
3101
Eric Laurent9d91ad52009-07-17 12:17:14 -07003102 if (mActiveTrack != 0 && mActiveTrack->mClient != 0) {
3103 snprintf(buffer, SIZE, "Record client pid: %d\n", mActiveTrack->mClient->pid());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003104 result.append(buffer);
3105 } else {
3106 result.append("No record client\n");
3107 }
3108 write(fd, result.string(), result.size());
3109 return NO_ERROR;
3110}
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003111
Eric Laurent9d91ad52009-07-17 12:17:14 -07003112status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3113{
3114 size_t framesReq = buffer->frameCount;
3115 size_t framesReady = mFrameCount - mRsmpInIndex;
3116 int channelCount;
3117
3118 if (framesReady == 0) {
3119 ssize_t bytesRead = mInput->read(mRsmpInBuffer, mInputBytes);
3120 if (bytesRead < 0) {
3121 LOGE("RecordThread::getNextBuffer() Error reading audio input");
3122 sleep(1);
3123 buffer->raw = 0;
3124 buffer->frameCount = 0;
3125 return NOT_ENOUGH_DATA;
3126 }
3127 mRsmpInIndex = 0;
3128 framesReady = mFrameCount;
3129 }
3130
3131 if (framesReq > framesReady) {
3132 framesReq = framesReady;
3133 }
3134
3135 if (mChannelCount == 1 && mReqChannelCount == 2) {
3136 channelCount = 1;
3137 } else {
3138 channelCount = 2;
3139 }
3140 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
3141 buffer->frameCount = framesReq;
3142 return NO_ERROR;
3143}
3144
3145void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3146{
3147 mRsmpInIndex += buffer->frameCount;
3148 buffer->frameCount = 0;
3149}
3150
3151bool AudioFlinger::RecordThread::checkForNewParameters_l()
3152{
3153 bool reconfig = false;
3154
Eric Laurent3464c012009-08-04 09:45:33 -07003155 while (!mNewParameters.isEmpty()) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07003156 status_t status = NO_ERROR;
Eric Laurent3464c012009-08-04 09:45:33 -07003157 String8 keyValuePair = mNewParameters[0];
3158 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003159 int value;
3160 int reqFormat = mFormat;
3161 int reqSamplingRate = mReqSampleRate;
3162 int reqChannelCount = mReqChannelCount;
Eric Laurent3464c012009-08-04 09:45:33 -07003163
3164 mNewParameters.removeAt(0);
3165
Eric Laurent9d91ad52009-07-17 12:17:14 -07003166 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3167 reqSamplingRate = value;
3168 reconfig = true;
3169 }
3170 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
3171 reqFormat = value;
3172 reconfig = true;
3173 }
3174 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
3175 reqChannelCount = AudioSystem::popCount(value);
3176 reconfig = true;
3177 }
3178 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3179 // do not accept frame count changes if tracks are open as the track buffer
3180 // size depends on frame count and correct behavior would not be garantied
3181 // if frame count is changed after track creation
3182 if (mActiveTrack != 0) {
3183 status = INVALID_OPERATION;
3184 } else {
3185 reconfig = true;
3186 }
3187 }
3188 if (status == NO_ERROR) {
Eric Laurent3464c012009-08-04 09:45:33 -07003189 status = mInput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003190 if (status == INVALID_OPERATION) {
3191 mInput->standby();
Eric Laurent3464c012009-08-04 09:45:33 -07003192 status = mInput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003193 }
3194 if (reconfig) {
3195 if (status == BAD_VALUE &&
3196 reqFormat == mInput->format() && reqFormat == AudioSystem::PCM_16_BIT &&
3197 ((int)mInput->sampleRate() <= 2 * reqSamplingRate) &&
3198 (AudioSystem::popCount(mInput->channels()) < 3) && (reqChannelCount < 3)) {
3199 status = NO_ERROR;
3200 }
3201 if (status == NO_ERROR) {
3202 readInputParameters();
Eric Laurent3464c012009-08-04 09:45:33 -07003203 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003204 }
3205 }
3206 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003207 mParamStatus = status;
3208 mParamCond.signal();
Eric Laurent3464c012009-08-04 09:45:33 -07003209 mWaitWorkCV.wait(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003210 }
3211 return reconfig;
3212}
3213
3214String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
3215{
3216 return mInput->getParameters(keys);
3217}
3218
3219void AudioFlinger::RecordThread::audioConfigChanged(int event, int param) {
3220 AudioSystem::OutputDescriptor desc;
3221 void *param2 = 0;
3222
3223 switch (event) {
3224 case AudioSystem::INPUT_OPENED:
3225 case AudioSystem::INPUT_CONFIG_CHANGED:
3226 desc.channels = mChannelCount;
3227 desc.samplingRate = mSampleRate;
3228 desc.format = mFormat;
3229 desc.frameCount = mFrameCount;
3230 desc.latency = 0;
3231 param2 = &desc;
3232 break;
3233
3234 case AudioSystem::INPUT_CLOSED:
3235 default:
3236 break;
3237 }
Eric Laurentb3687ae2009-09-15 07:10:12 -07003238 Mutex::Autolock _l(mAudioFlinger->mLock);
3239 mAudioFlinger->audioConfigChanged_l(event, this, param2);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003240}
3241
3242void AudioFlinger::RecordThread::readInputParameters()
3243{
3244 if (mRsmpInBuffer) delete mRsmpInBuffer;
3245 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
3246 if (mResampler) delete mResampler;
3247 mResampler = 0;
3248
3249 mSampleRate = mInput->sampleRate();
3250 mChannelCount = AudioSystem::popCount(mInput->channels());
3251 mFormat = mInput->format();
3252 mFrameSize = mInput->frameSize();
3253 mInputBytes = mInput->bufferSize();
3254 mFrameCount = mInputBytes / mFrameSize;
3255 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
3256
3257 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
3258 {
3259 int channelCount;
3260 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
3261 // stereo to mono post process as the resampler always outputs stereo.
3262 if (mChannelCount == 1 && mReqChannelCount == 2) {
3263 channelCount = 1;
3264 } else {
3265 channelCount = 2;
3266 }
3267 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
3268 mResampler->setSampleRate(mSampleRate);
3269 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
3270 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
3271
3272 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
3273 if (mChannelCount == 1 && mReqChannelCount == 1) {
3274 mFrameCount >>= 1;
3275 }
3276
3277 }
3278 mRsmpInIndex = mFrameCount;
3279}
3280
3281// ----------------------------------------------------------------------------
3282
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003283int AudioFlinger::openOutput(uint32_t *pDevices,
Eric Laurent9d91ad52009-07-17 12:17:14 -07003284 uint32_t *pSamplingRate,
3285 uint32_t *pFormat,
3286 uint32_t *pChannels,
3287 uint32_t *pLatencyMs,
3288 uint32_t flags)
3289{
3290 status_t status;
3291 PlaybackThread *thread = NULL;
3292 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
3293 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
3294 uint32_t format = pFormat ? *pFormat : 0;
3295 uint32_t channels = pChannels ? *pChannels : 0;
3296 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
3297
3298 LOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
3299 pDevices ? *pDevices : 0,
3300 samplingRate,
3301 format,
3302 channels,
3303 flags);
3304
3305 if (pDevices == NULL || *pDevices == 0) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003306 return 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003307 }
3308 Mutex::Autolock _l(mLock);
3309
3310 AudioStreamOut *output = mAudioHardware->openOutputStream(*pDevices,
3311 (int *)&format,
3312 &channels,
3313 &samplingRate,
3314 &status);
3315 LOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
3316 output,
3317 samplingRate,
3318 format,
3319 channels,
3320 status);
3321
3322 mHardwareStatus = AUDIO_HW_IDLE;
3323 if (output != 0) {
3324 if ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) ||
3325 (format != AudioSystem::PCM_16_BIT) ||
3326 (channels != AudioSystem::CHANNEL_OUT_STEREO)) {
3327 thread = new DirectOutputThread(this, output);
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003328 LOGV("openOutput() created direct output: ID %d thread %p", (mNextThreadId + 1), thread);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003329 } else {
3330 thread = new MixerThread(this, output);
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003331 LOGV("openOutput() created mixer output: ID %d thread %p", (mNextThreadId + 1), thread);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003332 }
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003333 mPlaybackThreads.add(++mNextThreadId, thread);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003334
3335 if (pSamplingRate) *pSamplingRate = samplingRate;
3336 if (pFormat) *pFormat = format;
3337 if (pChannels) *pChannels = channels;
3338 if (pLatencyMs) *pLatencyMs = thread->latency();
3339 }
3340
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003341 return mNextThreadId;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003342}
3343
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003344int AudioFlinger::openDuplicateOutput(int output1, int output2)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003345{
3346 Mutex::Autolock _l(mLock);
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003347 MixerThread *thread1 = checkMixerThread_l(output1);
3348 MixerThread *thread2 = checkMixerThread_l(output2);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003349
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003350 if (thread1 == NULL || thread2 == NULL) {
3351 LOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
3352 return 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003353 }
3354
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003355
3356 DuplicatingThread *thread = new DuplicatingThread(this, thread1);
3357 thread->addOutputTrack(thread2);
3358 mPlaybackThreads.add(++mNextThreadId, thread);
3359 return mNextThreadId;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003360}
3361
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003362status_t AudioFlinger::closeOutput(int output)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003363{
Eric Laurentdae20d92009-08-04 08:37:05 -07003364 // keep strong reference on the playback thread so that
3365 // it is not destroyed while exit() is executed
3366 sp <PlaybackThread> thread;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003367 {
3368 Mutex::Autolock _l(mLock);
3369 thread = checkPlaybackThread_l(output);
3370 if (thread == NULL) {
3371 return BAD_VALUE;
3372 }
3373
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003374 LOGV("closeOutput() %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003375
3376 if (thread->type() == PlaybackThread::MIXER) {
3377 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003378 if (mPlaybackThreads.valueAt(i)->type() == PlaybackThread::DUPLICATING) {
3379 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Eric Laurentdae20d92009-08-04 08:37:05 -07003380 dupThread->removeOutputTrack((MixerThread *)thread.get());
Eric Laurent9d91ad52009-07-17 12:17:14 -07003381 }
3382 }
3383 }
Eric Laurentb3687ae2009-09-15 07:10:12 -07003384 void *param2 = 0;
3385 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, thread, param2);
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003386 mPlaybackThreads.removeItem(output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003387 }
3388 thread->exit();
3389
Eric Laurentdae20d92009-08-04 08:37:05 -07003390 if (thread->type() != PlaybackThread::DUPLICATING) {
3391 mAudioHardware->closeOutputStream(thread->getOutput());
3392 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003393 return NO_ERROR;
3394}
3395
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003396status_t AudioFlinger::suspendOutput(int output)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003397{
3398 Mutex::Autolock _l(mLock);
3399 PlaybackThread *thread = checkPlaybackThread_l(output);
3400
3401 if (thread == NULL) {
3402 return BAD_VALUE;
3403 }
3404
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003405 LOGV("suspendOutput() %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003406 thread->suspend();
3407
3408 return NO_ERROR;
3409}
3410
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003411status_t AudioFlinger::restoreOutput(int output)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003412{
3413 Mutex::Autolock _l(mLock);
3414 PlaybackThread *thread = checkPlaybackThread_l(output);
3415
3416 if (thread == NULL) {
3417 return BAD_VALUE;
3418 }
3419
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003420 LOGV("restoreOutput() %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003421
3422 thread->restore();
3423
3424 return NO_ERROR;
3425}
3426
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003427int AudioFlinger::openInput(uint32_t *pDevices,
Eric Laurent9d91ad52009-07-17 12:17:14 -07003428 uint32_t *pSamplingRate,
3429 uint32_t *pFormat,
3430 uint32_t *pChannels,
3431 uint32_t acoustics)
3432{
3433 status_t status;
3434 RecordThread *thread = NULL;
3435 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
3436 uint32_t format = pFormat ? *pFormat : 0;
3437 uint32_t channels = pChannels ? *pChannels : 0;
3438 uint32_t reqSamplingRate = samplingRate;
3439 uint32_t reqFormat = format;
3440 uint32_t reqChannels = channels;
3441
3442 if (pDevices == NULL || *pDevices == 0) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003443 return 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003444 }
3445 Mutex::Autolock _l(mLock);
3446
3447 AudioStreamIn *input = mAudioHardware->openInputStream(*pDevices,
3448 (int *)&format,
3449 &channels,
3450 &samplingRate,
3451 &status,
3452 (AudioSystem::audio_in_acoustics)acoustics);
3453 LOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
3454 input,
3455 samplingRate,
3456 format,
3457 channels,
3458 acoustics,
3459 status);
3460
3461 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
3462 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
3463 // or stereo to mono conversions on 16 bit PCM inputs.
3464 if (input == 0 && status == BAD_VALUE &&
3465 reqFormat == format && format == AudioSystem::PCM_16_BIT &&
3466 (samplingRate <= 2 * reqSamplingRate) &&
3467 (AudioSystem::popCount(channels) < 3) && (AudioSystem::popCount(reqChannels) < 3)) {
3468 LOGV("openInput() reopening with proposed sampling rate and channels");
3469 input = mAudioHardware->openInputStream(*pDevices,
3470 (int *)&format,
3471 &channels,
3472 &samplingRate,
3473 &status,
3474 (AudioSystem::audio_in_acoustics)acoustics);
3475 }
3476
3477 if (input != 0) {
3478 // Start record thread
3479 thread = new RecordThread(this, input, reqSamplingRate, reqChannels);
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003480 mRecordThreads.add(++mNextThreadId, thread);
3481 LOGV("openInput() created record thread: ID %d thread %p", mNextThreadId, thread);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003482 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
3483 if (pFormat) *pFormat = format;
3484 if (pChannels) *pChannels = reqChannels;
3485
3486 input->standby();
3487 }
3488
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003489 return mNextThreadId;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003490}
3491
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003492status_t AudioFlinger::closeInput(int input)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003493{
Eric Laurentdae20d92009-08-04 08:37:05 -07003494 // keep strong reference on the record thread so that
3495 // it is not destroyed while exit() is executed
3496 sp <RecordThread> thread;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003497 {
3498 Mutex::Autolock _l(mLock);
3499 thread = checkRecordThread_l(input);
3500 if (thread == NULL) {
3501 return BAD_VALUE;
3502 }
3503
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003504 LOGV("closeInput() %d", input);
Eric Laurentb3687ae2009-09-15 07:10:12 -07003505 void *param2 = 0;
3506 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, thread, param2);
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003507 mRecordThreads.removeItem(input);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003508 }
3509 thread->exit();
3510
Eric Laurentdae20d92009-08-04 08:37:05 -07003511 mAudioHardware->closeInputStream(thread->getInput());
3512
Eric Laurent9d91ad52009-07-17 12:17:14 -07003513 return NO_ERROR;
3514}
3515
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003516status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003517{
3518 Mutex::Autolock _l(mLock);
3519 MixerThread *dstThread = checkMixerThread_l(output);
3520 if (dstThread == NULL) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003521 LOGW("setStreamOutput() bad output id %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003522 return BAD_VALUE;
3523 }
3524
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003525 LOGV("setStreamOutput() stream %d to output %d", stream, output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003526
3527 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003528 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent9d91ad52009-07-17 12:17:14 -07003529 if (thread != dstThread &&
3530 thread->type() != PlaybackThread::DIRECT) {
3531 MixerThread *srcThread = (MixerThread *)thread;
3532 SortedVector < sp<MixerThread::Track> > tracks;
3533 SortedVector < wp<MixerThread::Track> > activeTracks;
3534 srcThread->getTracks(tracks, activeTracks, stream);
3535 if (tracks.size()) {
3536 dstThread->putTracks(tracks, activeTracks);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003537 }
3538 }
3539 }
3540
Eric Laurent06437712009-09-01 05:56:26 -07003541 dstThread->sendConfigEvent(AudioSystem::STREAM_CONFIG_CHANGED, stream);
3542
Eric Laurent9d91ad52009-07-17 12:17:14 -07003543 return NO_ERROR;
3544}
3545
3546// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003547AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
Eric Laurent9d91ad52009-07-17 12:17:14 -07003548{
3549 PlaybackThread *thread = NULL;
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003550 if (mPlaybackThreads.indexOfKey(output) >= 0) {
3551 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
Eric Laurent9d91ad52009-07-17 12:17:14 -07003552 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003553 return thread;
3554}
3555
3556// checkMixerThread_l() must be called with AudioFlinger::mLock held
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003557AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
Eric Laurent9d91ad52009-07-17 12:17:14 -07003558{
3559 PlaybackThread *thread = checkPlaybackThread_l(output);
3560 if (thread != NULL) {
3561 if (thread->type() == PlaybackThread::DIRECT) {
3562 thread = NULL;
3563 }
3564 }
3565 return (MixerThread *)thread;
3566}
3567
3568// checkRecordThread_l() must be called with AudioFlinger::mLock held
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003569AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
Eric Laurent9d91ad52009-07-17 12:17:14 -07003570{
3571 RecordThread *thread = NULL;
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003572 if (mRecordThreads.indexOfKey(input) >= 0) {
3573 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
Eric Laurent9d91ad52009-07-17 12:17:14 -07003574 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003575 return thread;
3576}
3577
3578// ----------------------------------------------------------------------------
3579
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003580status_t AudioFlinger::onTransact(
3581 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3582{
3583 return BnAudioFlinger::onTransact(code, data, reply, flags);
3584}
3585
3586// ----------------------------------------------------------------------------
Eric Laurent9d91ad52009-07-17 12:17:14 -07003587
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003588void AudioFlinger::instantiate() {
3589 defaultServiceManager()->addService(
3590 String16("media.audio_flinger"), new AudioFlinger());
3591}
3592
3593}; // namespace android