blob: 3a419b579b89bd3c8b6fcc2120fb3ba2d93ab096 [file] [log] [blame]
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001/* //device/include/server/AudioFlinger/AudioFlinger.cpp
2**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
22#include <math.h>
23#include <signal.h>
24#include <sys/time.h>
25#include <sys/resource.h>
26
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070027#include <binder/IServiceManager.h>
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -070028#include <utils/Log.h>
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070029#include <binder/Parcel.h>
30#include <binder/IPCThreadState.h>
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -070031#include <utils/String16.h>
32#include <utils/threads.h>
33
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -080034#include <cutils/properties.h>
35
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -070036#include <media/AudioTrack.h>
37#include <media/AudioRecord.h>
38
39#include <private/media/AudioTrackShared.h>
40
The Android Open Source Project8a7a6752009-01-15 16:12:10 -080041#include <hardware_legacy/AudioHardwareInterface.h>
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -070042
43#include "AudioMixer.h"
44#include "AudioFlinger.h"
45
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -080046#ifdef WITH_A2DP
47#include "A2dpAudioInterface.h"
48#endif
49
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080050// ----------------------------------------------------------------------------
51// the sim build doesn't have gettid
52
53#ifndef HAVE_GETTID
54# define gettid getpid
55#endif
56
57// ----------------------------------------------------------------------------
58
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -070059namespace android {
60
The Android Open Source Project4f68be12009-03-18 17:39:46 -070061static const char* kDeadlockedString = "AudioFlinger may be deadlocked\n";
62static const char* kHardwareLockedString = "Hardware lock is taken\n";
63
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -080064//static const nsecs_t kStandbyTimeInNsecs = seconds(3);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -070065static const unsigned long kBufferRecoveryInUsecs = 2000;
66static const unsigned long kMaxBufferRecoveryInUsecs = 20000;
67static const float MAX_GAIN = 4096.0f;
68
69// retry counts for buffer fill timeout
70// 50 * ~20msecs = 1 second
71static const int8_t kMaxTrackRetries = 50;
72static const int8_t kMaxTrackStartupRetries = 50;
73
The Android Open Source Project22f8def2009-03-09 11:52:12 -070074static const int kDumpLockRetries = 50;
75static const int kDumpLockSleep = 20000;
76
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -070078#define AUDIOFLINGER_SECURITY_ENABLED 1
79
80// ----------------------------------------------------------------------------
81
82static bool recordingAllowed() {
83#ifndef HAVE_ANDROID_OS
84 return true;
85#endif
86#if AUDIOFLINGER_SECURITY_ENABLED
87 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
88 bool ok = checkCallingPermission(String16("android.permission.RECORD_AUDIO"));
89 if (!ok) LOGE("Request requires android.permission.RECORD_AUDIO");
90 return ok;
91#else
92 if (!checkCallingPermission(String16("android.permission.RECORD_AUDIO")))
93 LOGW("WARNING: Need to add android.permission.RECORD_AUDIO to manifest");
94 return true;
95#endif
96}
97
98static bool settingsAllowed() {
99#ifndef HAVE_ANDROID_OS
100 return true;
101#endif
102#if AUDIOFLINGER_SECURITY_ENABLED
103 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
104 bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
105 if (!ok) LOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
106 return ok;
107#else
108 if (!checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS")))
109 LOGW("WARNING: Need to add android.permission.MODIFY_AUDIO_SETTINGS to manifest");
110 return true;
111#endif
112}
113
114// ----------------------------------------------------------------------------
115
116AudioFlinger::AudioFlinger()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800117 : BnAudioFlinger(),
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700118 mAudioHardware(0), mMasterVolume(1.0f), mMasterMute(false), mNextThreadId(0)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700119{
120 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent9d91ad52009-07-17 12:17:14 -0700121
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700122 mAudioHardware = AudioHardwareInterface::create();
Eric Laurent9d91ad52009-07-17 12:17:14 -0700123
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700124 mHardwareStatus = AUDIO_HW_INIT;
125 if (mAudioHardware->initCheck() == NO_ERROR) {
126 // open 16-bit output stream for s/w mixer
Eric Laurent9d91ad52009-07-17 12:17:14 -0700127
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800128 setMode(AudioSystem::MODE_NORMAL);
129
130 setMasterVolume(1.0f);
131 setMasterMute(false);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700132 } else {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700133 LOGE("Couldn't even initialize the stubbed audio hardware!");
134 }
135}
136
137AudioFlinger::~AudioFlinger()
138{
Eric Laurentc80b1a02009-08-28 10:39:03 -0700139 while (!mRecordThreads.isEmpty()) {
140 // closeInput() will remove first entry from mRecordThreads
141 closeInput(mRecordThreads.keyAt(0));
142 }
143 while (!mPlaybackThreads.isEmpty()) {
144 // closeOutput() will remove first entry from mPlaybackThreads
145 closeOutput(mPlaybackThreads.keyAt(0));
146 }
147 if (mAudioHardware) {
148 delete mAudioHardware;
149 }
The Android Open Source Project27629322009-01-09 17:51:23 -0800150}
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800151
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700152
The Android Open Source Projectbcef13b2009-03-11 12:11:56 -0700153
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700154status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
155{
156 const size_t SIZE = 256;
157 char buffer[SIZE];
158 String8 result;
159
160 result.append("Clients:\n");
161 for (size_t i = 0; i < mClients.size(); ++i) {
162 wp<Client> wClient = mClients.valueAt(i);
163 if (wClient != 0) {
164 sp<Client> client = wClient.promote();
165 if (client != 0) {
166 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
167 result.append(buffer);
168 }
169 }
170 }
171 write(fd, result.string(), result.size());
172 return NO_ERROR;
173}
174
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700175
176status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
177{
178 const size_t SIZE = 256;
179 char buffer[SIZE];
180 String8 result;
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700181 int hardwareStatus = mHardwareStatus;
Eric Laurent9d91ad52009-07-17 12:17:14 -0700182
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700183 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700184 result.append(buffer);
185 write(fd, result.string(), result.size());
186 return NO_ERROR;
187}
188
189status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
190{
191 const size_t SIZE = 256;
192 char buffer[SIZE];
193 String8 result;
194 snprintf(buffer, SIZE, "Permission Denial: "
195 "can't dump AudioFlinger from pid=%d, uid=%d\n",
196 IPCThreadState::self()->getCallingPid(),
197 IPCThreadState::self()->getCallingUid());
198 result.append(buffer);
199 write(fd, result.string(), result.size());
200 return NO_ERROR;
201}
202
The Android Open Source Project4f68be12009-03-18 17:39:46 -0700203static bool tryLock(Mutex& mutex)
204{
205 bool locked = false;
206 for (int i = 0; i < kDumpLockRetries; ++i) {
207 if (mutex.tryLock() == NO_ERROR) {
208 locked = true;
209 break;
210 }
211 usleep(kDumpLockSleep);
212 }
213 return locked;
214}
215
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700216status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
217{
218 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
219 dumpPermissionDenial(fd, args);
220 } else {
The Android Open Source Project4f68be12009-03-18 17:39:46 -0700221 // get state of hardware lock
222 bool hardwareLocked = tryLock(mHardwareLock);
223 if (!hardwareLocked) {
224 String8 result(kHardwareLockedString);
225 write(fd, result.string(), result.size());
226 } else {
227 mHardwareLock.unlock();
228 }
229
230 bool locked = tryLock(mLock);
231
232 // failed to lock - AudioFlinger is probably deadlocked
233 if (!locked) {
234 String8 result(kDeadlockedString);
235 write(fd, result.string(), result.size());
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700236 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700237
238 dumpClients(fd, args);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700239 dumpInternals(fd, args);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800240
Eric Laurent9d91ad52009-07-17 12:17:14 -0700241 // dump playback threads
242 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700243 mPlaybackThreads.valueAt(i)->dump(fd, args);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700244 }
245
246 // dump record threads
Eric Laurentfd558a92009-07-23 13:35:01 -0700247 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700248 mRecordThreads.valueAt(i)->dump(fd, args);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700249 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800250
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700251 if (mAudioHardware) {
252 mAudioHardware->dumpState(fd, args);
253 }
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700254 if (locked) mLock.unlock();
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700255 }
256 return NO_ERROR;
257}
258
Eric Laurent9d91ad52009-07-17 12:17:14 -0700259
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700260// IAudioFlinger interface
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800261
262
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700263sp<IAudioTrack> AudioFlinger::createTrack(
264 pid_t pid,
265 int streamType,
266 uint32_t sampleRate,
267 int format,
268 int channelCount,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800269 int frameCount,
270 uint32_t flags,
271 const sp<IMemory>& sharedBuffer,
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700272 int output,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800273 status_t *status)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700274{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700275 sp<PlaybackThread::Track> track;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700276 sp<TrackHandle> trackHandle;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700277 sp<Client> client;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800278 wp<Client> wclient;
279 status_t lStatus;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700280
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800281 if (streamType >= AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800282 LOGE("invalid stream type");
283 lStatus = BAD_VALUE;
284 goto Exit;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700285 }
286
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800287 {
288 Mutex::Autolock _l(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700289 PlaybackThread *thread = checkPlaybackThread_l(output);
290 if (thread == NULL) {
291 LOGE("unknown output thread");
292 lStatus = BAD_VALUE;
293 goto Exit;
294 }
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800295
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800296 wclient = mClients.valueFor(pid);
297
298 if (wclient != NULL) {
299 client = wclient.promote();
300 } else {
301 client = new Client(this, pid);
302 mClients.add(pid, client);
303 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700304 track = thread->createTrack_l(client, streamType, sampleRate, format,
305 channelCount, frameCount, sharedBuffer, &lStatus);
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700306 }
307 if (lStatus == NO_ERROR) {
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800308 trackHandle = new TrackHandle(track);
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700309 } else {
310 track.clear();
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800311 }
312
313Exit:
314 if(status) {
315 *status = lStatus;
316 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700317 return trackHandle;
318}
319
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700320uint32_t AudioFlinger::sampleRate(int output) const
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700321{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700322 Mutex::Autolock _l(mLock);
323 PlaybackThread *thread = checkPlaybackThread_l(output);
324 if (thread == NULL) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700325 LOGW("sampleRate() unknown thread %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700326 return 0;
327 }
328 return thread->sampleRate();
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700329}
330
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700331int AudioFlinger::channelCount(int output) const
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700332{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700333 Mutex::Autolock _l(mLock);
334 PlaybackThread *thread = checkPlaybackThread_l(output);
335 if (thread == NULL) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700336 LOGW("channelCount() unknown thread %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700337 return 0;
338 }
339 return thread->channelCount();
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700340}
341
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700342int AudioFlinger::format(int output) const
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700343{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700344 Mutex::Autolock _l(mLock);
345 PlaybackThread *thread = checkPlaybackThread_l(output);
346 if (thread == NULL) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700347 LOGW("format() unknown thread %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700348 return 0;
349 }
350 return thread->format();
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700351}
352
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700353size_t AudioFlinger::frameCount(int output) const
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700354{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700355 Mutex::Autolock _l(mLock);
356 PlaybackThread *thread = checkPlaybackThread_l(output);
357 if (thread == NULL) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700358 LOGW("frameCount() unknown thread %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700359 return 0;
360 }
361 return thread->frameCount();
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700362}
363
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700364uint32_t AudioFlinger::latency(int output) const
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800365{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700366 Mutex::Autolock _l(mLock);
367 PlaybackThread *thread = checkPlaybackThread_l(output);
368 if (thread == NULL) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700369 LOGW("latency() unknown thread %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700370 return 0;
371 }
372 return thread->latency();
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800373}
374
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700375status_t AudioFlinger::setMasterVolume(float value)
376{
377 // check calling permissions
378 if (!settingsAllowed()) {
379 return PERMISSION_DENIED;
380 }
381
382 // when hw supports master volume, don't scale in sw mixer
383 AutoMutex lock(mHardwareLock);
384 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
385 if (mAudioHardware->setMasterVolume(value) == NO_ERROR) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800386 value = 1.0f;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700387 }
388 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent9d91ad52009-07-17 12:17:14 -0700389
390 mMasterVolume = value;
391 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700392 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700393
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700394 return NO_ERROR;
395}
396
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700397status_t AudioFlinger::setMode(int mode)
398{
399 // check calling permissions
400 if (!settingsAllowed()) {
401 return PERMISSION_DENIED;
402 }
403 if ((mode < 0) || (mode >= AudioSystem::NUM_MODES)) {
404 LOGW("Illegal value: setMode(%d)", mode);
405 return BAD_VALUE;
406 }
407
408 AutoMutex lock(mHardwareLock);
409 mHardwareStatus = AUDIO_HW_SET_MODE;
410 status_t ret = mAudioHardware->setMode(mode);
411 mHardwareStatus = AUDIO_HW_IDLE;
412 return ret;
413}
414
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700415status_t AudioFlinger::setMicMute(bool state)
416{
417 // check calling permissions
418 if (!settingsAllowed()) {
419 return PERMISSION_DENIED;
420 }
421
422 AutoMutex lock(mHardwareLock);
423 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
424 status_t ret = mAudioHardware->setMicMute(state);
425 mHardwareStatus = AUDIO_HW_IDLE;
426 return ret;
427}
428
429bool AudioFlinger::getMicMute() const
430{
431 bool state = AudioSystem::MODE_INVALID;
432 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
433 mAudioHardware->getMicMute(&state);
434 mHardwareStatus = AUDIO_HW_IDLE;
435 return state;
436}
437
438status_t AudioFlinger::setMasterMute(bool muted)
439{
440 // check calling permissions
441 if (!settingsAllowed()) {
442 return PERMISSION_DENIED;
443 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700444
445 mMasterMute = muted;
446 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700447 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700448
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700449 return NO_ERROR;
450}
451
452float AudioFlinger::masterVolume() const
453{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700454 return mMasterVolume;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700455}
456
457bool AudioFlinger::masterMute() const
458{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700459 return mMasterMute;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700460}
461
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700462status_t AudioFlinger::setStreamVolume(int stream, float value, int output)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700463{
464 // check calling permissions
465 if (!settingsAllowed()) {
466 return PERMISSION_DENIED;
467 }
468
Eric Laurent9d91ad52009-07-17 12:17:14 -0700469 if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700470 return BAD_VALUE;
471 }
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800472
Eric Laurent9d91ad52009-07-17 12:17:14 -0700473 AutoMutex lock(mLock);
474 PlaybackThread *thread = NULL;
475 if (output) {
476 thread = checkPlaybackThread_l(output);
477 if (thread == NULL) {
478 return BAD_VALUE;
479 }
480 }
481
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700482 status_t ret = NO_ERROR;
Eric Laurent9d91ad52009-07-17 12:17:14 -0700483
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800484 if (stream == AudioSystem::VOICE_CALL ||
485 stream == AudioSystem::BLUETOOTH_SCO) {
Eric Laurent4dd495b2009-04-21 07:56:33 -0700486 float hwValue;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800487 if (stream == AudioSystem::VOICE_CALL) {
Jean-Baptiste Queru732ca392009-03-18 11:33:14 -0700488 hwValue = (float)AudioSystem::logToLinear(value)/100.0f;
Eric Laurent4dd495b2009-04-21 07:56:33 -0700489 // offset value to reflect actual hardware volume that never reaches 0
490 // 1% corresponds roughly to first step in VOICE_CALL stream volume setting (see AudioService.java)
491 value = 0.01 + 0.99 * value;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800492 } else { // (type == AudioSystem::BLUETOOTH_SCO)
Jean-Baptiste Queru732ca392009-03-18 11:33:14 -0700493 hwValue = 1.0f;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800494 }
495
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700496 AutoMutex lock(mHardwareLock);
497 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
Jean-Baptiste Queru732ca392009-03-18 11:33:14 -0700498 ret = mAudioHardware->setVoiceVolume(hwValue);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700499 mHardwareStatus = AUDIO_HW_IDLE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800500
Eric Laurent9d91ad52009-07-17 12:17:14 -0700501 }
502
503 mStreamTypes[stream].volume = value;
504
505 if (thread == NULL) {
506 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700507 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700508
509 } else {
510 thread->setStreamVolume(stream, value);
511 }
Eric Laurent4dd495b2009-04-21 07:56:33 -0700512
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700513 return ret;
514}
515
516status_t AudioFlinger::setStreamMute(int stream, bool muted)
517{
518 // check calling permissions
519 if (!settingsAllowed()) {
520 return PERMISSION_DENIED;
521 }
522
Eric Laurent9d91ad52009-07-17 12:17:14 -0700523 if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES ||
Eric Laurentb1596ee2009-03-26 01:57:59 -0700524 uint32_t(stream) == AudioSystem::ENFORCED_AUDIBLE) {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700525 return BAD_VALUE;
526 }
The Android Open Source Project4f68be12009-03-18 17:39:46 -0700527
Eric Laurent9d91ad52009-07-17 12:17:14 -0700528 mStreamTypes[stream].mute = muted;
529 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700530 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800531
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700532 return NO_ERROR;
533}
534
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700535float AudioFlinger::streamVolume(int stream, int output) const
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700536{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700537 if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700538 return 0.0f;
539 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700540
541 AutoMutex lock(mLock);
542 float volume;
543 if (output) {
544 PlaybackThread *thread = checkPlaybackThread_l(output);
545 if (thread == NULL) {
546 return 0.0f;
547 }
548 volume = thread->streamVolume(stream);
549 } else {
550 volume = mStreamTypes[stream].volume;
551 }
552
Eric Laurent4dd495b2009-04-21 07:56:33 -0700553 // remove correction applied by setStreamVolume()
Jean-Baptiste Queru732ca392009-03-18 11:33:14 -0700554 if (stream == AudioSystem::VOICE_CALL) {
Eric Laurent4dd495b2009-04-21 07:56:33 -0700555 volume = (volume - 0.01) / 0.99 ;
James E. Blair6015dfc2009-01-17 13:30:20 -0800556 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700557
Eric Laurent4dd495b2009-04-21 07:56:33 -0700558 return volume;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700559}
560
561bool AudioFlinger::streamMute(int stream) const
562{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700563 if (stream < 0 || stream >= (int)AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700564 return true;
565 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700566
567 return mStreamTypes[stream].mute;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700568}
569
570bool AudioFlinger::isMusicActive() const
571{
Eric Laurentb025ca02009-07-09 03:20:57 -0700572 Mutex::Autolock _l(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700573 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700574 if (mPlaybackThreads.valueAt(i)->isMusicActive()) {
Eric Laurent9d91ad52009-07-17 12:17:14 -0700575 return true;
576 }
577 }
578 return false;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700579}
580
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700581status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700582{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700583 status_t result;
584
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700585 LOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
Eric Laurent9d91ad52009-07-17 12:17:14 -0700586 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
587 // check calling permissions
588 if (!settingsAllowed()) {
589 return PERMISSION_DENIED;
The Android Open Source Project8a7a6752009-01-15 16:12:10 -0800590 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700591
592 // ioHandle == 0 means the parameters are global to the audio hardware interface
593 if (ioHandle == 0) {
594 AutoMutex lock(mHardwareLock);
595 mHardwareStatus = AUDIO_SET_PARAMETER;
596 result = mAudioHardware->setParameters(keyValuePairs);
597 mHardwareStatus = AUDIO_HW_IDLE;
598 return result;
599 }
600
601 // Check if parameters are for an output
602 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
603 if (playbackThread != NULL) {
604 return playbackThread->setParameters(keyValuePairs);
605 }
606
607 // Check if parameters are for an input
608 RecordThread *recordThread = checkRecordThread_l(ioHandle);
609 if (recordThread != NULL) {
610 return recordThread->setParameters(keyValuePairs);
611 }
612
613 return BAD_VALUE;
614}
615
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700616String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
Eric Laurent9d91ad52009-07-17 12:17:14 -0700617{
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700618// LOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
Eric Laurent9d91ad52009-07-17 12:17:14 -0700619// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
620
621 if (ioHandle == 0) {
622 return mAudioHardware->getParameters(keys);
623 }
624 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
625 if (playbackThread != NULL) {
626 return playbackThread->getParameters(keys);
627 }
628 RecordThread *recordThread = checkRecordThread_l(ioHandle);
629 if (recordThread != NULL) {
630 return recordThread->getParameters(keys);
631 }
632 return String8("");
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700633}
634
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800635size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
636{
637 return mAudioHardware->getInputBufferSize(sampleRate, format, channelCount);
638}
639
640void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
641{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700642
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800643 LOGV("registerClient() %p, tid %d, calling tid %d", client.get(), gettid(), IPCThreadState::self()->getCallingPid());
644 Mutex::Autolock _l(mLock);
645
646 sp<IBinder> binder = client->asBinder();
647 if (mNotificationClients.indexOf(binder) < 0) {
648 LOGV("Adding notification client %p", binder.get());
649 binder->linkToDeath(this);
650 mNotificationClients.add(binder);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700651 }
652
653 // the config change is always sent from playback or record threads to avoid deadlock
654 // with AudioSystem::gLock
655 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700656 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700657 }
658
659 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700660 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800661 }
662}
663
664void AudioFlinger::binderDied(const wp<IBinder>& who) {
Eric Laurent9d91ad52009-07-17 12:17:14 -0700665
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800666 LOGV("binderDied() %p, tid %d, calling tid %d", who.unsafe_get(), gettid(), IPCThreadState::self()->getCallingPid());
667 Mutex::Autolock _l(mLock);
668
669 IBinder *binder = who.unsafe_get();
670
671 if (binder != NULL) {
672 int index = mNotificationClients.indexOf(binder);
673 if (index >= 0) {
674 LOGV("Removing notification client %p", binder);
675 mNotificationClients.removeAt(index);
676 }
677 }
678}
679
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700680void AudioFlinger::audioConfigChanged(int event, const sp<ThreadBase>& thread, void *param2) {
Eric Laurent9d91ad52009-07-17 12:17:14 -0700681 Mutex::Autolock _l(mLock);
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700682 int ioHandle = 0;
683
684 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
685 if (mPlaybackThreads.valueAt(i) == thread) {
686 ioHandle = mPlaybackThreads.keyAt(i);
687 break;
688 }
689 }
690 if (ioHandle == 0) {
691 for (size_t i = 0; i < mRecordThreads.size(); i++) {
692 if (mRecordThreads.valueAt(i) == thread) {
693 ioHandle = mRecordThreads.keyAt(i);
694 break;
695 }
696 }
697 }
698
699 if (ioHandle != 0) {
700 size_t size = mNotificationClients.size();
701 for (size_t i = 0; i < size; i++) {
702 sp<IBinder> binder = mNotificationClients.itemAt(i);
703 LOGV("audioConfigChanged() Notifying change to client %p", binder.get());
704 sp<IAudioFlingerClient> client = interface_cast<IAudioFlingerClient> (binder);
705 client->ioConfigChanged(event, ioHandle, param2);
706 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700707 }
708}
709
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700710void AudioFlinger::removeClient(pid_t pid)
711{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800712 LOGV("removeClient() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700713 Mutex::Autolock _l(mLock);
714 mClients.removeItem(pid);
715}
716
Eric Laurent9d91ad52009-07-17 12:17:14 -0700717// ----------------------------------------------------------------------------
718
719AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger)
720 : Thread(false),
721 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
Eric Laurent3464c012009-08-04 09:45:33 -0700722 mFormat(0), mFrameSize(1), mStandby(false)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700723{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800724}
725
Eric Laurent9d91ad52009-07-17 12:17:14 -0700726AudioFlinger::ThreadBase::~ThreadBase()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800727{
Eric Laurent3464c012009-08-04 09:45:33 -0700728 mParamCond.broadcast();
729 mNewParameters.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800730}
731
Eric Laurent9d91ad52009-07-17 12:17:14 -0700732void AudioFlinger::ThreadBase::exit()
The Android Open Source Projectbcef13b2009-03-11 12:11:56 -0700733{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700734 // keep a strong ref on ourself so that we want get
735 // destroyed in the middle of requestExitAndWait()
736 sp <ThreadBase> strongMe = this;
737
738 LOGV("ThreadBase::exit");
739 {
740 AutoMutex lock(&mLock);
741 requestExit();
742 mWaitWorkCV.signal();
The Android Open Source Projectbcef13b2009-03-11 12:11:56 -0700743 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700744 requestExitAndWait();
The Android Open Source Projectbcef13b2009-03-11 12:11:56 -0700745}
Eric Laurent9d91ad52009-07-17 12:17:14 -0700746
747uint32_t AudioFlinger::ThreadBase::sampleRate() const
748{
749 return mSampleRate;
750}
751
752int AudioFlinger::ThreadBase::channelCount() const
753{
754 return mChannelCount;
755}
756
757int AudioFlinger::ThreadBase::format() const
758{
759 return mFormat;
760}
761
762size_t AudioFlinger::ThreadBase::frameCount() const
763{
764 return mFrameCount;
765}
766
767status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
768{
Eric Laurent3464c012009-08-04 09:45:33 -0700769 status_t status;
Eric Laurent9d91ad52009-07-17 12:17:14 -0700770
Eric Laurent3464c012009-08-04 09:45:33 -0700771 LOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Eric Laurent9d91ad52009-07-17 12:17:14 -0700772 Mutex::Autolock _l(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700773
Eric Laurent3464c012009-08-04 09:45:33 -0700774 mNewParameters.add(keyValuePairs);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700775 mWaitWorkCV.signal();
776 mParamCond.wait(mLock);
Eric Laurent3464c012009-08-04 09:45:33 -0700777 status = mParamStatus;
778 mWaitWorkCV.signal();
779 return status;
Eric Laurent9d91ad52009-07-17 12:17:14 -0700780}
781
782void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
783{
784 Mutex::Autolock _l(mLock);
Eric Laurent3464c012009-08-04 09:45:33 -0700785 sendConfigEvent_l(event, param);
786}
787
788// sendConfigEvent_l() must be called with ThreadBase::mLock held
789void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
790{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700791 ConfigEvent *configEvent = new ConfigEvent();
792 configEvent->mEvent = event;
793 configEvent->mParam = param;
794 mConfigEvents.add(configEvent);
795 LOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
796 mWaitWorkCV.signal();
797}
798
799void AudioFlinger::ThreadBase::processConfigEvents()
800{
801 mLock.lock();
802 while(!mConfigEvents.isEmpty()) {
803 LOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
804 ConfigEvent *configEvent = mConfigEvents[0];
805 mConfigEvents.removeAt(0);
806 // release mLock because audioConfigChanged() will call
807 // Audioflinger::audioConfigChanged() which locks AudioFlinger mLock thus creating
808 // potential cross deadlock between AudioFlinger::mLock and mLock
809 mLock.unlock();
810 audioConfigChanged(configEvent->mEvent, configEvent->mParam);
811 delete configEvent;
812 mLock.lock();
813 }
814 mLock.unlock();
815}
816
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800817
818// ----------------------------------------------------------------------------
819
Eric Laurent9d91ad52009-07-17 12:17:14 -0700820AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output)
821 : ThreadBase(audioFlinger),
Eric Laurentf9df2492009-08-06 08:49:39 -0700822 mMixBuffer(0), mSuspended(0), mBytesWritten(0), mOutput(output),
Eric Laurent9395d9b2009-07-23 13:17:39 -0700823 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800824{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700825 readOutputParameters();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800826
Eric Laurent9d91ad52009-07-17 12:17:14 -0700827 mMasterVolume = mAudioFlinger->masterVolume();
828 mMasterMute = mAudioFlinger->masterMute();
829
830 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
831 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
832 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800833 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700834 // notify client processes that a new input has been opened
835 sendConfigEvent(AudioSystem::OUTPUT_OPENED);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800836}
837
Eric Laurent9d91ad52009-07-17 12:17:14 -0700838AudioFlinger::PlaybackThread::~PlaybackThread()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800839{
840 delete [] mMixBuffer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800841}
842
Eric Laurent9d91ad52009-07-17 12:17:14 -0700843status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800844{
845 dumpInternals(fd, args);
846 dumpTracks(fd, args);
847 return NO_ERROR;
848}
849
Eric Laurent9d91ad52009-07-17 12:17:14 -0700850status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800851{
852 const size_t SIZE = 256;
853 char buffer[SIZE];
854 String8 result;
855
Eric Laurent9d91ad52009-07-17 12:17:14 -0700856 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800857 result.append(buffer);
858 result.append(" Name Clien Typ Fmt Chn Buf S M F SRate LeftV RighV Serv User\n");
859 for (size_t i = 0; i < mTracks.size(); ++i) {
Eric Laurentc828f6a2009-03-31 14:34:35 -0700860 sp<Track> track = mTracks[i];
861 if (track != 0) {
862 track->dump(buffer, SIZE);
863 result.append(buffer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800864 }
865 }
866
Eric Laurent9d91ad52009-07-17 12:17:14 -0700867 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800868 result.append(buffer);
869 result.append(" Name Clien Typ Fmt Chn Buf S M F SRate LeftV RighV Serv User\n");
870 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Eric Laurentc828f6a2009-03-31 14:34:35 -0700871 wp<Track> wTrack = mActiveTracks[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800872 if (wTrack != 0) {
873 sp<Track> track = wTrack.promote();
874 if (track != 0) {
875 track->dump(buffer, SIZE);
876 result.append(buffer);
877 }
878 }
879 }
880 write(fd, result.string(), result.size());
881 return NO_ERROR;
882}
883
Eric Laurent9d91ad52009-07-17 12:17:14 -0700884status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800885{
886 const size_t SIZE = 256;
887 char buffer[SIZE];
888 String8 result;
889
Eric Laurent9d91ad52009-07-17 12:17:14 -0700890 snprintf(buffer, SIZE, "Output thread %p internals\n", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800891 result.append(buffer);
892 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
893 result.append(buffer);
894 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
895 result.append(buffer);
896 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
897 result.append(buffer);
898 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
899 result.append(buffer);
900 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
901 result.append(buffer);
902 write(fd, result.string(), result.size());
903 return NO_ERROR;
904}
905
906// Thread virtuals
Eric Laurent9d91ad52009-07-17 12:17:14 -0700907status_t AudioFlinger::PlaybackThread::readyToRun()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800908{
909 if (mSampleRate == 0) {
910 LOGE("No working audio driver found.");
911 return NO_INIT;
912 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700913 LOGI("AudioFlinger's thread %p ready to run", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800914 return NO_ERROR;
915}
916
Eric Laurent9d91ad52009-07-17 12:17:14 -0700917void AudioFlinger::PlaybackThread::onFirstRef()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800918{
919 const size_t SIZE = 256;
920 char buffer[SIZE];
921
Eric Laurent9d91ad52009-07-17 12:17:14 -0700922 snprintf(buffer, SIZE, "Playback Thread %p", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800923
924 run(buffer, ANDROID_PRIORITY_URGENT_AUDIO);
925}
926
Eric Laurent9d91ad52009-07-17 12:17:14 -0700927// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
928sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800929 const sp<AudioFlinger::Client>& client,
930 int streamType,
931 uint32_t sampleRate,
932 int format,
933 int channelCount,
934 int frameCount,
935 const sp<IMemory>& sharedBuffer,
936 status_t *status)
937{
938 sp<Track> track;
939 status_t lStatus;
Eric Laurent9d91ad52009-07-17 12:17:14 -0700940
941 if (mType == DIRECT) {
942 if (sampleRate != mSampleRate || format != mFormat || channelCount != mChannelCount) {
943 LOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelCount %d for output %p",
944 sampleRate, format, channelCount, mOutput);
945 lStatus = BAD_VALUE;
946 goto Exit;
947 }
948 } else {
949 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
950 if (sampleRate > mSampleRate*2) {
951 LOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
952 lStatus = BAD_VALUE;
953 goto Exit;
954 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800955 }
956
Eric Laurent9d91ad52009-07-17 12:17:14 -0700957 if (mOutput == 0) {
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700958 LOGE("Audio driver not initialized.");
959 lStatus = NO_INIT;
960 goto Exit;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800961 }
962
Eric Laurent9d91ad52009-07-17 12:17:14 -0700963 { // scope for mLock
964 Mutex::Autolock _l(mLock);
965 track = new Track(this, client, streamType, sampleRate, format,
966 channelCount, frameCount, sharedBuffer);
967 if (track->getCblk() == NULL) {
968 lStatus = NO_MEMORY;
969 goto Exit;
970 }
971 mTracks.add(track);
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700972 }
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700973 lStatus = NO_ERROR;
974
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800975Exit:
976 if(status) {
977 *status = lStatus;
978 }
979 return track;
980}
981
Eric Laurent9d91ad52009-07-17 12:17:14 -0700982uint32_t AudioFlinger::PlaybackThread::latency() const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800983{
984 if (mOutput) {
985 return mOutput->latency();
986 }
987 else {
988 return 0;
989 }
990}
991
Eric Laurent9d91ad52009-07-17 12:17:14 -0700992status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800993{
994 mMasterVolume = value;
995 return NO_ERROR;
996}
997
Eric Laurent9d91ad52009-07-17 12:17:14 -0700998status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800999{
1000 mMasterMute = muted;
1001 return NO_ERROR;
1002}
1003
Eric Laurent9d91ad52009-07-17 12:17:14 -07001004float AudioFlinger::PlaybackThread::masterVolume() const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001005{
1006 return mMasterVolume;
1007}
1008
Eric Laurent9d91ad52009-07-17 12:17:14 -07001009bool AudioFlinger::PlaybackThread::masterMute() const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001010{
1011 return mMasterMute;
1012}
1013
Eric Laurent9d91ad52009-07-17 12:17:14 -07001014status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001015{
1016 mStreamTypes[stream].volume = value;
1017 return NO_ERROR;
1018}
1019
Eric Laurent9d91ad52009-07-17 12:17:14 -07001020status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001021{
1022 mStreamTypes[stream].mute = muted;
1023 return NO_ERROR;
1024}
1025
Eric Laurent9d91ad52009-07-17 12:17:14 -07001026float AudioFlinger::PlaybackThread::streamVolume(int stream) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001027{
1028 return mStreamTypes[stream].volume;
1029}
1030
Eric Laurent9d91ad52009-07-17 12:17:14 -07001031bool AudioFlinger::PlaybackThread::streamMute(int stream) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001032{
1033 return mStreamTypes[stream].mute;
1034}
1035
Eric Laurent9d91ad52009-07-17 12:17:14 -07001036bool AudioFlinger::PlaybackThread::isMusicActive() const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001037{
Eric Laurent9d91ad52009-07-17 12:17:14 -07001038 Mutex::Autolock _l(mLock);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001039 size_t count = mActiveTracks.size();
1040 for (size_t i = 0 ; i < count ; ++i) {
1041 sp<Track> t = mActiveTracks[i].promote();
1042 if (t == 0) continue;
1043 Track* const track = t.get();
Eric Laurent9395d9b2009-07-23 13:17:39 -07001044 if (t->type() == AudioSystem::MUSIC)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001045 return true;
1046 }
1047 return false;
1048}
1049
Eric Laurent9d91ad52009-07-17 12:17:14 -07001050// addTrack_l() must be called with ThreadBase::mLock held
1051status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001052{
1053 status_t status = ALREADY_EXISTS;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001054
1055 // here the track could be either new, or restarted
1056 // in both cases "unstop" the track
1057 if (track->isPaused()) {
1058 track->mState = TrackBase::RESUMING;
1059 LOGV("PAUSED => RESUMING (%d)", track->name());
1060 } else {
1061 track->mState = TrackBase::ACTIVE;
1062 LOGV("? => ACTIVE (%d)", track->name());
1063 }
1064 // set retry count for buffer fill
1065 track->mRetryCount = kMaxTrackStartupRetries;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001066 if (mActiveTracks.indexOf(track) < 0) {
1067 // the track is newly added, make sure it fills up all its
1068 // buffers before playing. This is to ensure the client will
1069 // effectively get the latency it requested.
1070 track->mFillingUpStatus = Track::FS_FILLING;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08001071 track->mResetDone = false;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001072 mActiveTracks.add(track);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001073 status = NO_ERROR;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001074 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07001075
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001076 LOGV("mWaitWorkCV.broadcast");
Eric Laurent9d91ad52009-07-17 12:17:14 -07001077 mWaitWorkCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001078
1079 return status;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001080}
1081
Eric Laurent9d91ad52009-07-17 12:17:14 -07001082// destroyTrack_l() must be called with ThreadBase::mLock held
1083void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001084{
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001085 track->mState = TrackBase::TERMINATED;
1086 if (mActiveTracks.indexOf(track) < 0) {
1087 LOGV("remove track (%d) and delete from mixer", track->name());
1088 mTracks.remove(track);
The Android Open Source Project22f8def2009-03-09 11:52:12 -07001089 deleteTrackName_l(track->name());
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001090 }
1091}
1092
Eric Laurent9d91ad52009-07-17 12:17:14 -07001093String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
The Android Open Source Projecte41dd752009-01-22 00:13:42 -08001094{
Eric Laurent9d91ad52009-07-17 12:17:14 -07001095 return mOutput->getParameters(keys);
1096}
The Android Open Source Projecte41dd752009-01-22 00:13:42 -08001097
Eric Laurent9d91ad52009-07-17 12:17:14 -07001098void AudioFlinger::PlaybackThread::audioConfigChanged(int event, int param) {
1099 AudioSystem::OutputDescriptor desc;
1100 void *param2 = 0;
1101
1102 LOGV("PlaybackThread::audioConfigChanged, thread %p, event %d, param %d", this, event, param);
1103
1104 switch (event) {
1105 case AudioSystem::OUTPUT_OPENED:
1106 case AudioSystem::OUTPUT_CONFIG_CHANGED:
1107 desc.channels = mChannelCount;
1108 desc.samplingRate = mSampleRate;
1109 desc.format = mFormat;
1110 desc.frameCount = mFrameCount;
1111 desc.latency = latency();
1112 param2 = &desc;
1113 break;
1114
1115 case AudioSystem::STREAM_CONFIG_CHANGED:
1116 param2 = &param;
1117 case AudioSystem::OUTPUT_CLOSED:
1118 default:
1119 break;
1120 }
1121 mAudioFlinger->audioConfigChanged(event, this, param2);
1122}
1123
1124void AudioFlinger::PlaybackThread::readOutputParameters()
1125{
1126 mSampleRate = mOutput->sampleRate();
1127 mChannelCount = AudioSystem::popCount(mOutput->channels());
1128
1129 mFormat = mOutput->format();
1130 mFrameSize = mOutput->frameSize();
1131 mFrameCount = mOutput->bufferSize() / mFrameSize;
1132
1133 mMinBytesToWrite = (mOutput->latency() * mSampleRate * mFrameSize) / 1000;
1134 // FIXME - Current mixer implementation only supports stereo output: Always
1135 // Allocate a stereo buffer even if HW output is mono.
1136 if (mMixBuffer != NULL) delete mMixBuffer;
1137 mMixBuffer = new int16_t[mFrameCount * 2];
1138 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1139}
1140
1141// ----------------------------------------------------------------------------
1142
1143AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output)
1144 : PlaybackThread(audioFlinger, output),
1145 mAudioMixer(0)
1146{
1147 mType = PlaybackThread::MIXER;
1148 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1149
1150 // FIXME - Current mixer implementation only supports stereo output
1151 if (mChannelCount == 1) {
1152 LOGE("Invalid audio hardware channel count");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001153 }
The Android Open Source Projecte41dd752009-01-22 00:13:42 -08001154}
1155
Eric Laurent9d91ad52009-07-17 12:17:14 -07001156AudioFlinger::MixerThread::~MixerThread()
The Android Open Source Projecte41dd752009-01-22 00:13:42 -08001157{
Eric Laurent9d91ad52009-07-17 12:17:14 -07001158 delete mAudioMixer;
1159}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001160
Eric Laurent9d91ad52009-07-17 12:17:14 -07001161bool AudioFlinger::MixerThread::threadLoop()
1162{
1163 unsigned long sleepTime = kBufferRecoveryInUsecs;
1164 int16_t* curBuf = mMixBuffer;
1165 Vector< sp<Track> > tracksToRemove;
1166 size_t enabledTracks = 0;
1167 nsecs_t standbyTime = systemTime();
1168 size_t mixBufferSize = mFrameCount * mFrameSize;
1169 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 2;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001170
Eric Laurent9d91ad52009-07-17 12:17:14 -07001171 while (!exitPending())
1172 {
1173 processConfigEvents();
1174
1175 enabledTracks = 0;
1176 { // scope for mLock
1177
1178 Mutex::Autolock _l(mLock);
1179
1180 if (checkForNewParameters_l()) {
1181 mixBufferSize = mFrameCount * mFrameSize;
1182 maxPeriod = seconds(mFrameCount) / mSampleRate * 2;
1183 }
1184
1185 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1186
1187 // put audio hardware into standby after short delay
1188 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1189 mSuspended) {
1190 if (!mStandby) {
1191 LOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
1192 mOutput->standby();
1193 mStandby = true;
1194 mBytesWritten = 0;
1195 }
1196
1197 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1198 // we're about to wait, flush the binder command buffer
1199 IPCThreadState::self()->flushCommands();
1200
1201 if (exitPending()) break;
1202
1203 // wait until we have something to do...
1204 LOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
1205 mWaitWorkCV.wait(mLock);
1206 LOGV("MixerThread %p TID %d waking up\n", this, gettid());
1207
1208 if (mMasterMute == false) {
1209 char value[PROPERTY_VALUE_MAX];
1210 property_get("ro.audio.silent", value, "0");
1211 if (atoi(value)) {
1212 LOGD("Silence is golden");
1213 setMasterMute(true);
1214 }
1215 }
1216
1217 standbyTime = systemTime() + kStandbyTimeInNsecs;
1218 continue;
1219 }
1220 }
1221
1222 enabledTracks = prepareTracks_l(activeTracks, &tracksToRemove);
1223 }
1224
1225 if (LIKELY(enabledTracks)) {
1226 // mix buffers...
1227 mAudioMixer->process(curBuf);
1228
1229 // output audio to hardware
1230 if (mSuspended) {
1231 usleep(kMaxBufferRecoveryInUsecs);
1232 } else {
1233 mLastWriteTime = systemTime();
1234 mInWrite = true;
1235 int bytesWritten = (int)mOutput->write(curBuf, mixBufferSize);
1236 if (bytesWritten > 0) mBytesWritten += bytesWritten;
1237 mNumWrites++;
1238 mInWrite = false;
1239 mStandby = false;
1240 nsecs_t temp = systemTime();
1241 standbyTime = temp + kStandbyTimeInNsecs;
1242 nsecs_t delta = temp - mLastWriteTime;
1243 if (delta > maxPeriod) {
1244 LOGW("write blocked for %llu msecs", ns2ms(delta));
1245 mNumDelayedWrites++;
1246 }
1247 sleepTime = kBufferRecoveryInUsecs;
1248 }
1249 } else {
1250 // There was nothing to mix this round, which means all
1251 // active tracks were late. Sleep a little bit to give
1252 // them another chance. If we're too late, the audio
1253 // hardware will zero-fill for us.
1254 // LOGV("thread %p no buffers - usleep(%lu)", this, sleepTime);
1255 usleep(sleepTime);
1256 if (sleepTime < kMaxBufferRecoveryInUsecs) {
1257 sleepTime += kBufferRecoveryInUsecs;
1258 }
1259 }
1260
1261 // finally let go of all our tracks, without the lock held
1262 // since we can't guarantee the destructors won't acquire that
1263 // same lock.
1264 tracksToRemove.clear();
1265 }
1266
1267 if (!mStandby) {
1268 mOutput->standby();
1269 }
1270 sendConfigEvent(AudioSystem::OUTPUT_CLOSED);
1271 processConfigEvents();
1272
1273 LOGV("MixerThread %p exiting", this);
1274 return false;
1275}
1276
1277// prepareTracks_l() must be called with ThreadBase::mLock held
1278size_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
1279{
1280
1281 size_t enabledTracks = 0;
1282 // find out which tracks need to be processed
1283 size_t count = activeTracks.size();
1284 for (size_t i=0 ; i<count ; i++) {
1285 sp<Track> t = activeTracks[i].promote();
1286 if (t == 0) continue;
1287
1288 Track* const track = t.get();
1289 audio_track_cblk_t* cblk = track->cblk();
1290
1291 // The first time a track is added we wait
1292 // for all its buffers to be filled before processing it
1293 mAudioMixer->setActiveTrack(track->name());
1294 if (cblk->framesReady() && (track->isReady() || track->isStopped()) &&
1295 !track->isPaused())
1296 {
1297 //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
1298
1299 // compute volume for this track
1300 int16_t left, right;
1301 if (track->isMuted() || mMasterMute || track->isPausing() ||
1302 mStreamTypes[track->type()].mute) {
1303 left = right = 0;
1304 if (track->isPausing()) {
1305 track->setPaused();
1306 }
1307 } else {
1308 float typeVolume = mStreamTypes[track->type()].volume;
1309 float v = mMasterVolume * typeVolume;
1310 float v_clamped = v * cblk->volume[0];
1311 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
1312 left = int16_t(v_clamped);
1313 v_clamped = v * cblk->volume[1];
1314 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
1315 right = int16_t(v_clamped);
1316 }
1317
1318 // XXX: these things DON'T need to be done each time
1319 mAudioMixer->setBufferProvider(track);
1320 mAudioMixer->enable(AudioMixer::MIXING);
1321
1322 int param;
1323 if ( track->mFillingUpStatus == Track::FS_FILLED) {
1324 // no ramp for the first volume setting
1325 track->mFillingUpStatus = Track::FS_ACTIVE;
1326 if (track->mState == TrackBase::RESUMING) {
1327 track->mState = TrackBase::ACTIVE;
1328 param = AudioMixer::RAMP_VOLUME;
1329 } else {
1330 param = AudioMixer::VOLUME;
1331 }
1332 } else {
1333 param = AudioMixer::RAMP_VOLUME;
1334 }
1335 mAudioMixer->setParameter(param, AudioMixer::VOLUME0, left);
1336 mAudioMixer->setParameter(param, AudioMixer::VOLUME1, right);
1337 mAudioMixer->setParameter(
1338 AudioMixer::TRACK,
1339 AudioMixer::FORMAT, track->format());
1340 mAudioMixer->setParameter(
1341 AudioMixer::TRACK,
1342 AudioMixer::CHANNEL_COUNT, track->channelCount());
1343 mAudioMixer->setParameter(
1344 AudioMixer::RESAMPLE,
1345 AudioMixer::SAMPLE_RATE,
1346 int(cblk->sampleRate));
1347
1348 // reset retry count
1349 track->mRetryCount = kMaxTrackRetries;
1350 enabledTracks++;
1351 } else {
1352 //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
1353 if (track->isStopped()) {
1354 track->reset();
1355 }
1356 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
1357 // We have consumed all the buffers of this track.
1358 // Remove it from the list of active tracks.
1359 tracksToRemove->add(track);
1360 mAudioMixer->disable(AudioMixer::MIXING);
1361 } else {
1362 // No buffers for this track. Give it a few chances to
1363 // fill a buffer, then remove it from active list.
1364 if (--(track->mRetryCount) <= 0) {
1365 LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
1366 tracksToRemove->add(track);
1367 }
1368 // For tracks using static shared memry buffer, make sure that we have
1369 // written enough data to audio hardware before disabling the track
1370 // NOTE: this condition with arrive before track->mRetryCount <= 0 so we
1371 // don't care about code removing track from active list above.
1372 if ((track->mSharedBuffer == 0) || (mBytesWritten >= mMinBytesToWrite)) {
1373 mAudioMixer->disable(AudioMixer::MIXING);
1374 } else {
1375 enabledTracks++;
1376 }
1377 }
1378 }
1379 }
1380
1381 // remove all the tracks that need to be...
1382 count = tracksToRemove->size();
1383 if (UNLIKELY(count)) {
1384 for (size_t i=0 ; i<count ; i++) {
1385 const sp<Track>& track = tracksToRemove->itemAt(i);
1386 mActiveTracks.remove(track);
1387 if (track->isTerminated()) {
1388 mTracks.remove(track);
1389 deleteTrackName_l(track->mName);
1390 }
1391 }
1392 }
1393
1394 return enabledTracks;
1395}
1396
1397void AudioFlinger::MixerThread::getTracks(
1398 SortedVector < sp<Track> >& tracks,
1399 SortedVector < wp<Track> >& activeTracks,
1400 int streamType)
1401{
1402 LOGV ("MixerThread::getTracks() mixer %p, mTracks.size %d, mActiveTracks.size %d", this, mTracks.size(), mActiveTracks.size());
1403 Mutex::Autolock _l(mLock);
1404 size_t size = mTracks.size();
1405 for (size_t i = 0; i < size; i++) {
1406 sp<Track> t = mTracks[i];
1407 if (t->type() == streamType) {
1408 tracks.add(t);
1409 int j = mActiveTracks.indexOf(t);
1410 if (j >= 0) {
1411 t = mActiveTracks[j].promote();
1412 if (t != NULL) {
1413 activeTracks.add(t);
1414 }
1415 }
1416 }
1417 }
1418
1419 size = activeTracks.size();
1420 for (size_t i = 0; i < size; i++) {
1421 mActiveTracks.remove(activeTracks[i]);
1422 }
1423
1424 size = tracks.size();
1425 for (size_t i = 0; i < size; i++) {
1426 sp<Track> t = tracks[i];
1427 mTracks.remove(t);
1428 deleteTrackName_l(t->name());
1429 }
1430}
1431
1432void AudioFlinger::MixerThread::putTracks(
1433 SortedVector < sp<Track> >& tracks,
1434 SortedVector < wp<Track> >& activeTracks)
1435{
1436 LOGV ("MixerThread::putTracks() mixer %p, tracks.size %d, activeTracks.size %d", this, tracks.size(), activeTracks.size());
1437 Mutex::Autolock _l(mLock);
1438 size_t size = tracks.size();
1439 for (size_t i = 0; i < size ; i++) {
1440 sp<Track> t = tracks[i];
1441 int name = getTrackName_l();
1442
1443 if (name < 0) return;
1444
1445 t->mName = name;
1446 t->mThread = this;
1447 mTracks.add(t);
1448
1449 int j = activeTracks.indexOf(t);
1450 if (j >= 0) {
1451 mActiveTracks.add(t);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001452 }
1453 }
1454}
1455
Eric Laurent9d91ad52009-07-17 12:17:14 -07001456// getTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Project22f8def2009-03-09 11:52:12 -07001457int AudioFlinger::MixerThread::getTrackName_l()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001458{
1459 return mAudioMixer->getTrackName();
1460}
1461
Eric Laurent9d91ad52009-07-17 12:17:14 -07001462// deleteTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Project22f8def2009-03-09 11:52:12 -07001463void AudioFlinger::MixerThread::deleteTrackName_l(int name)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001464{
1465 mAudioMixer->deleteTrackName(name);
1466}
1467
Eric Laurent9d91ad52009-07-17 12:17:14 -07001468// checkForNewParameters_l() must be called with ThreadBase::mLock held
1469bool AudioFlinger::MixerThread::checkForNewParameters_l()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001470{
Eric Laurent9d91ad52009-07-17 12:17:14 -07001471 bool reconfig = false;
1472
Eric Laurent3464c012009-08-04 09:45:33 -07001473 while (!mNewParameters.isEmpty()) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07001474 status_t status = NO_ERROR;
Eric Laurent3464c012009-08-04 09:45:33 -07001475 String8 keyValuePair = mNewParameters[0];
1476 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001477 int value;
Eric Laurent3464c012009-08-04 09:45:33 -07001478
1479 mNewParameters.removeAt(0);
1480
Eric Laurent9d91ad52009-07-17 12:17:14 -07001481 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
1482 reconfig = true;
1483 }
1484 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
1485 if (value != AudioSystem::PCM_16_BIT) {
1486 status = BAD_VALUE;
1487 } else {
1488 reconfig = true;
1489 }
1490 }
1491 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
1492 if (value != AudioSystem::CHANNEL_OUT_STEREO) {
1493 status = BAD_VALUE;
1494 } else {
1495 reconfig = true;
1496 }
1497 }
1498 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
1499 // do not accept frame count changes if tracks are open as the track buffer
1500 // size depends on frame count and correct behavior would not be garantied
1501 // if frame count is changed after track creation
1502 if (!mTracks.isEmpty()) {
1503 status = INVALID_OPERATION;
1504 } else {
1505 reconfig = true;
1506 }
1507 }
1508 if (status == NO_ERROR) {
Eric Laurent3464c012009-08-04 09:45:33 -07001509 status = mOutput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001510 if (!mStandby && status == INVALID_OPERATION) {
1511 mOutput->standby();
1512 mStandby = true;
1513 mBytesWritten = 0;
Eric Laurent3464c012009-08-04 09:45:33 -07001514 status = mOutput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001515 }
1516 if (status == NO_ERROR && reconfig) {
1517 delete mAudioMixer;
1518 readOutputParameters();
1519 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1520 for (size_t i = 0; i < mTracks.size() ; i++) {
1521 int name = getTrackName_l();
1522 if (name < 0) break;
1523 mTracks[i]->mName = name;
Eric Laurent878c0e12009-08-10 08:15:12 -07001524 // limit track sample rate to 2 x new output sample rate
1525 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
1526 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
1527 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07001528 }
Eric Laurent3464c012009-08-04 09:45:33 -07001529 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001530 }
1531 }
1532 mParamStatus = status;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001533 mParamCond.signal();
Eric Laurent3464c012009-08-04 09:45:33 -07001534 mWaitWorkCV.wait(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001535 }
1536 return reconfig;
1537}
1538
1539status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
1540{
1541 const size_t SIZE = 256;
1542 char buffer[SIZE];
1543 String8 result;
1544
1545 PlaybackThread::dumpInternals(fd, args);
1546
1547 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
1548 result.append(buffer);
1549 write(fd, result.string(), result.size());
1550 return NO_ERROR;
1551}
1552
1553// ----------------------------------------------------------------------------
1554AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output)
1555 : PlaybackThread(audioFlinger, output),
1556 mLeftVolume (1.0), mRightVolume(1.0)
1557{
1558 mType = PlaybackThread::DIRECT;
1559}
1560
1561AudioFlinger::DirectOutputThread::~DirectOutputThread()
1562{
1563}
1564
1565
1566bool AudioFlinger::DirectOutputThread::threadLoop()
1567{
1568 unsigned long sleepTime = kBufferRecoveryInUsecs;
1569 sp<Track> trackToRemove;
1570 sp<Track> activeTrack;
1571 nsecs_t standbyTime = systemTime();
1572 int8_t *curBuf;
1573 size_t mixBufferSize = mFrameCount*mFrameSize;
1574
1575 while (!exitPending())
1576 {
1577 processConfigEvents();
1578
1579 { // scope for the mLock
1580
1581 Mutex::Autolock _l(mLock);
1582
1583 if (checkForNewParameters_l()) {
1584 mixBufferSize = mFrameCount*mFrameSize;
1585 }
1586
1587 // put audio hardware into standby after short delay
1588 if UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
1589 mSuspended) {
1590 // wait until we have something to do...
1591 if (!mStandby) {
1592 LOGV("Audio hardware entering standby, mixer %p\n", this);
1593 mOutput->standby();
1594 mStandby = true;
1595 mBytesWritten = 0;
1596 }
1597
1598 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
1599 // we're about to wait, flush the binder command buffer
1600 IPCThreadState::self()->flushCommands();
1601
1602 if (exitPending()) break;
1603
1604 LOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
1605 mWaitWorkCV.wait(mLock);
1606 LOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
1607
1608 if (mMasterMute == false) {
1609 char value[PROPERTY_VALUE_MAX];
1610 property_get("ro.audio.silent", value, "0");
1611 if (atoi(value)) {
1612 LOGD("Silence is golden");
1613 setMasterMute(true);
1614 }
1615 }
1616
1617 standbyTime = systemTime() + kStandbyTimeInNsecs;
1618 continue;
1619 }
1620 }
1621
1622 // find out which tracks need to be processed
1623 if (mActiveTracks.size() != 0) {
1624 sp<Track> t = mActiveTracks[0].promote();
1625 if (t == 0) continue;
1626
1627 Track* const track = t.get();
1628 audio_track_cblk_t* cblk = track->cblk();
1629
1630 // The first time a track is added we wait
1631 // for all its buffers to be filled before processing it
1632 if (cblk->framesReady() && (track->isReady() || track->isStopped()) &&
1633 !track->isPaused())
1634 {
1635 //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
1636
1637 // compute volume for this track
1638 float left, right;
1639 if (track->isMuted() || mMasterMute || track->isPausing() ||
1640 mStreamTypes[track->type()].mute) {
1641 left = right = 0;
1642 if (track->isPausing()) {
1643 track->setPaused();
1644 }
1645 } else {
1646 float typeVolume = mStreamTypes[track->type()].volume;
1647 float v = mMasterVolume * typeVolume;
1648 float v_clamped = v * cblk->volume[0];
1649 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
1650 left = v_clamped/MAX_GAIN;
1651 v_clamped = v * cblk->volume[1];
1652 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
1653 right = v_clamped/MAX_GAIN;
1654 }
1655
1656 if (left != mLeftVolume || right != mRightVolume) {
1657 mOutput->setVolume(left, right);
1658 left = mLeftVolume;
1659 right = mRightVolume;
1660 }
1661
1662 if (track->mFillingUpStatus == Track::FS_FILLED) {
1663 track->mFillingUpStatus = Track::FS_ACTIVE;
1664 if (track->mState == TrackBase::RESUMING) {
1665 track->mState = TrackBase::ACTIVE;
1666 }
1667 }
1668
1669 // reset retry count
1670 track->mRetryCount = kMaxTrackRetries;
1671 activeTrack = t;
1672 } else {
1673 //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
1674 if (track->isStopped()) {
1675 track->reset();
1676 }
1677 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
1678 // We have consumed all the buffers of this track.
1679 // Remove it from the list of active tracks.
1680 trackToRemove = track;
1681 } else {
1682 // No buffers for this track. Give it a few chances to
1683 // fill a buffer, then remove it from active list.
1684 if (--(track->mRetryCount) <= 0) {
1685 LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
1686 trackToRemove = track;
1687 }
1688
1689 // For tracks using static shared memry buffer, make sure that we have
1690 // written enough data to audio hardware before disabling the track
1691 // NOTE: this condition with arrive before track->mRetryCount <= 0 so we
1692 // don't care about code removing track from active list above.
1693 if ((track->mSharedBuffer != 0) && (mBytesWritten < mMinBytesToWrite)) {
1694 activeTrack = t;
1695 }
1696 }
1697 }
1698 }
1699
1700 // remove all the tracks that need to be...
1701 if (UNLIKELY(trackToRemove != 0)) {
1702 mActiveTracks.remove(trackToRemove);
1703 if (trackToRemove->isTerminated()) {
1704 mTracks.remove(trackToRemove);
1705 deleteTrackName_l(trackToRemove->mName);
1706 }
1707 }
1708 }
1709
1710 if (activeTrack != 0) {
1711 AudioBufferProvider::Buffer buffer;
1712 size_t frameCount = mFrameCount;
1713 curBuf = (int8_t *)mMixBuffer;
1714 // output audio to hardware
1715 mLastWriteTime = systemTime();
1716 mInWrite = true;
1717 while(frameCount) {
1718 buffer.frameCount = frameCount;
1719 activeTrack->getNextBuffer(&buffer);
1720 if (UNLIKELY(buffer.raw == 0)) {
1721 memset(curBuf, 0, frameCount * mFrameSize);
1722 break;
1723 }
1724 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
1725 frameCount -= buffer.frameCount;
1726 curBuf += buffer.frameCount * mFrameSize;
1727 activeTrack->releaseBuffer(&buffer);
1728 }
1729 if (mSuspended) {
1730 usleep(kMaxBufferRecoveryInUsecs);
1731 } else {
1732 int bytesWritten = (int)mOutput->write(mMixBuffer, mixBufferSize);
1733 if (bytesWritten) mBytesWritten += bytesWritten;
1734 mNumWrites++;
1735 mInWrite = false;
1736 mStandby = false;
1737 nsecs_t temp = systemTime();
1738 standbyTime = temp + kStandbyTimeInNsecs;
1739 sleepTime = kBufferRecoveryInUsecs;
1740 }
1741 } else {
1742 // There was nothing to mix this round, which means all
1743 // active tracks were late. Sleep a little bit to give
1744 // them another chance. If we're too late, the audio
1745 // hardware will zero-fill for us.
1746 //LOGV("no buffers - usleep(%lu)", sleepTime);
1747 usleep(sleepTime);
1748 if (sleepTime < kMaxBufferRecoveryInUsecs) {
1749 sleepTime += kBufferRecoveryInUsecs;
1750 }
1751 }
1752
1753 // finally let go of removed track, without the lock held
1754 // since we can't guarantee the destructors won't acquire that
1755 // same lock.
1756 trackToRemove.clear();
1757 activeTrack.clear();
1758 }
1759
1760 if (!mStandby) {
1761 mOutput->standby();
1762 }
1763 sendConfigEvent(AudioSystem::OUTPUT_CLOSED);
1764 processConfigEvents();
1765
1766 LOGV("DirectOutputThread %p exiting", this);
1767 return false;
1768}
1769
1770// getTrackName_l() must be called with ThreadBase::mLock held
1771int AudioFlinger::DirectOutputThread::getTrackName_l()
1772{
1773 return 0;
1774}
1775
1776// deleteTrackName_l() must be called with ThreadBase::mLock held
1777void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
1778{
1779}
1780
1781// checkForNewParameters_l() must be called with ThreadBase::mLock held
1782bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
1783{
1784 bool reconfig = false;
1785
Eric Laurent3464c012009-08-04 09:45:33 -07001786 while (!mNewParameters.isEmpty()) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07001787 status_t status = NO_ERROR;
Eric Laurent3464c012009-08-04 09:45:33 -07001788 String8 keyValuePair = mNewParameters[0];
1789 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001790 int value;
Eric Laurent3464c012009-08-04 09:45:33 -07001791
1792 mNewParameters.removeAt(0);
1793
Eric Laurent9d91ad52009-07-17 12:17:14 -07001794 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
1795 // do not accept frame count changes if tracks are open as the track buffer
1796 // size depends on frame count and correct behavior would not be garantied
1797 // if frame count is changed after track creation
1798 if (!mTracks.isEmpty()) {
1799 status = INVALID_OPERATION;
1800 } else {
1801 reconfig = true;
1802 }
1803 }
1804 if (status == NO_ERROR) {
Eric Laurent3464c012009-08-04 09:45:33 -07001805 status = mOutput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001806 if (!mStandby && status == INVALID_OPERATION) {
1807 mOutput->standby();
1808 mStandby = true;
1809 mBytesWritten = 0;
Eric Laurent3464c012009-08-04 09:45:33 -07001810 status = mOutput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001811 }
1812 if (status == NO_ERROR && reconfig) {
1813 readOutputParameters();
Eric Laurent3464c012009-08-04 09:45:33 -07001814 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001815 }
1816 }
1817 mParamStatus = status;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001818 mParamCond.signal();
Eric Laurent3464c012009-08-04 09:45:33 -07001819 mWaitWorkCV.wait(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001820 }
1821 return reconfig;
The Android Open Source Projecte41dd752009-01-22 00:13:42 -08001822}
1823
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001824// ----------------------------------------------------------------------------
1825
Eric Laurent9d91ad52009-07-17 12:17:14 -07001826AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread)
1827 : MixerThread(audioFlinger, mainThread->getOutput())
1828{
1829 mType = PlaybackThread::DUPLICATING;
1830 addOutputTrack(mainThread);
1831}
1832
1833AudioFlinger::DuplicatingThread::~DuplicatingThread()
1834{
1835 mOutputTracks.clear();
1836}
1837
1838bool AudioFlinger::DuplicatingThread::threadLoop()
1839{
1840 unsigned long sleepTime = kBufferRecoveryInUsecs;
1841 int16_t* curBuf = mMixBuffer;
1842 Vector< sp<Track> > tracksToRemove;
1843 size_t enabledTracks = 0;
1844 nsecs_t standbyTime = systemTime();
1845 size_t mixBufferSize = mFrameCount*mFrameSize;
1846 SortedVector< sp<OutputTrack> > outputTracks;
1847
1848 while (!exitPending())
1849 {
1850 processConfigEvents();
1851
1852 enabledTracks = 0;
1853 { // scope for the mLock
1854
1855 Mutex::Autolock _l(mLock);
1856
1857 if (checkForNewParameters_l()) {
1858 mixBufferSize = mFrameCount*mFrameSize;
1859 }
1860
1861 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1862
1863 for (size_t i = 0; i < mOutputTracks.size(); i++) {
1864 outputTracks.add(mOutputTracks[i]);
1865 }
1866
1867 // put audio hardware into standby after short delay
1868 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1869 mSuspended) {
1870 if (!mStandby) {
1871 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07001872 outputTracks[i]->stop();
Eric Laurent9d91ad52009-07-17 12:17:14 -07001873 }
1874 mStandby = true;
1875 mBytesWritten = 0;
1876 }
1877
1878 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1879 // we're about to wait, flush the binder command buffer
1880 IPCThreadState::self()->flushCommands();
1881 outputTracks.clear();
1882
1883 if (exitPending()) break;
1884
1885 LOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
1886 mWaitWorkCV.wait(mLock);
1887 LOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
1888 if (mMasterMute == false) {
1889 char value[PROPERTY_VALUE_MAX];
1890 property_get("ro.audio.silent", value, "0");
1891 if (atoi(value)) {
1892 LOGD("Silence is golden");
1893 setMasterMute(true);
1894 }
1895 }
1896
1897 standbyTime = systemTime() + kStandbyTimeInNsecs;
1898 sleepTime = kBufferRecoveryInUsecs;
1899 continue;
1900 }
1901 }
1902
1903 enabledTracks = prepareTracks_l(activeTracks, &tracksToRemove);
1904 }
1905
1906 bool mustSleep = true;
1907 if (LIKELY(enabledTracks)) {
1908 // mix buffers...
1909 mAudioMixer->process(curBuf);
1910 if (!mSuspended) {
1911 for (size_t i = 0; i < outputTracks.size(); i++) {
1912 outputTracks[i]->write(curBuf, mFrameCount);
Eric Laurentf5aba822009-08-10 23:22:32 -07001913 mustSleep = false;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001914 }
1915 mStandby = false;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001916 mBytesWritten += mixBufferSize;
1917 }
1918 } else {
1919 // flush remaining overflow buffers in output tracks
1920 for (size_t i = 0; i < outputTracks.size(); i++) {
1921 if (outputTracks[i]->isActive()) {
1922 outputTracks[i]->write(curBuf, 0);
1923 standbyTime = systemTime() + kStandbyTimeInNsecs;
1924 mustSleep = false;
1925 }
1926 }
1927 }
1928 if (mustSleep) {
1929// LOGV("threadLoop() sleeping %d", sleepTime);
1930 usleep(sleepTime);
1931 if (sleepTime < kMaxBufferRecoveryInUsecs) {
1932 sleepTime += kBufferRecoveryInUsecs;
1933 }
1934 } else {
1935 sleepTime = kBufferRecoveryInUsecs;
1936 }
1937
1938 // finally let go of all our tracks, without the lock held
1939 // since we can't guarantee the destructors won't acquire that
1940 // same lock.
1941 tracksToRemove.clear();
1942 outputTracks.clear();
1943 }
1944
Eric Laurentf5aba822009-08-10 23:22:32 -07001945 { // scope for the mLock
1946
1947 Mutex::Autolock _l(mLock);
1948 if (!mStandby) {
1949 LOGV("DuplicatingThread() exiting out of standby");
1950 for (size_t i = 0; i < mOutputTracks.size(); i++) {
1951 mOutputTracks[i]->destroy();
1952 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07001953 }
1954 }
1955
1956 sendConfigEvent(AudioSystem::OUTPUT_CLOSED);
1957 processConfigEvents();
1958
1959 return false;
1960}
1961
1962void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
1963{
1964 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
1965 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
1966 mSampleRate,
1967 mFormat,
1968 mChannelCount,
1969 frameCount);
Eric Laurentf5aba822009-08-10 23:22:32 -07001970 if (outputTrack->cblk() != NULL) {
1971 thread->setStreamVolume(AudioSystem::NUM_STREAM_TYPES, 1.0f);
1972 mOutputTracks.add(outputTrack);
1973 LOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
1974 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07001975}
1976
1977void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
1978{
1979 Mutex::Autolock _l(mLock);
1980 for (size_t i = 0; i < mOutputTracks.size(); i++) {
1981 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
Eric Laurentf5aba822009-08-10 23:22:32 -07001982 mOutputTracks[i]->destroy();
Eric Laurent9d91ad52009-07-17 12:17:14 -07001983 mOutputTracks.removeAt(i);
1984 return;
1985 }
1986 }
1987 LOGV("removeOutputTrack(): unkonwn thread: %p", thread);
1988}
1989
1990
1991// ----------------------------------------------------------------------------
1992
The Android Open Source Project22f8def2009-03-09 11:52:12 -07001993// TrackBase constructor must be called with AudioFlinger::mLock held
Eric Laurent9d91ad52009-07-17 12:17:14 -07001994AudioFlinger::ThreadBase::TrackBase::TrackBase(
1995 const wp<ThreadBase>& thread,
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001996 const sp<Client>& client,
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001997 uint32_t sampleRate,
1998 int format,
1999 int channelCount,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002000 int frameCount,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002001 uint32_t flags,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002002 const sp<IMemory>& sharedBuffer)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002003 : RefBase(),
Eric Laurent9d91ad52009-07-17 12:17:14 -07002004 mThread(thread),
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002005 mClient(client),
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002006 mFrameCount(0),
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002007 mState(IDLE),
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002008 mClientTid(-1),
2009 mFormat(format),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002010 mFlags(flags & ~SYSTEM_FLAGS_MASK)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002011{
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002012 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
2013
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002014 // LOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002015 size_t size = sizeof(audio_track_cblk_t);
2016 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
2017 if (sharedBuffer == 0) {
2018 size += bufferSize;
2019 }
2020
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002021 if (client != NULL) {
2022 mCblkMemory = client->heap()->allocate(size);
2023 if (mCblkMemory != 0) {
2024 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
2025 if (mCblk) { // construct the shared structure in-place.
2026 new(mCblk) audio_track_cblk_t();
2027 // clear all buffers
2028 mCblk->frameCount = frameCount;
Eric Laurent0bac5382009-07-07 07:10:45 -07002029 mCblk->sampleRate = sampleRate;
2030 mCblk->channels = (uint8_t)channelCount;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002031 if (sharedBuffer == 0) {
2032 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2033 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2034 // Force underrun condition to avoid false underrun callback until first data is
2035 // written to buffer
2036 mCblk->flowControlFlag = 1;
2037 } else {
2038 mBuffer = sharedBuffer->pointer();
2039 }
2040 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002041 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002042 } else {
2043 LOGE("not enough memory for AudioTrack size=%u", size);
2044 client->heap()->dump("AudioTrack");
2045 return;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002046 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002047 } else {
2048 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
2049 if (mCblk) { // construct the shared structure in-place.
2050 new(mCblk) audio_track_cblk_t();
2051 // clear all buffers
2052 mCblk->frameCount = frameCount;
Eric Laurent0bac5382009-07-07 07:10:45 -07002053 mCblk->sampleRate = sampleRate;
2054 mCblk->channels = (uint8_t)channelCount;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002055 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2056 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2057 // Force underrun condition to avoid false underrun callback until first data is
2058 // written to buffer
2059 mCblk->flowControlFlag = 1;
2060 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
2061 }
2062 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002063}
2064
Eric Laurent9d91ad52009-07-17 12:17:14 -07002065AudioFlinger::PlaybackThread::TrackBase::~TrackBase()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002066{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002067 if (mCblk) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07002068 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
2069 if (mClient == NULL) {
2070 delete mCblk;
2071 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002072 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002073 mCblkMemory.clear(); // and free the shared memory
2074 mClient.clear();
2075}
2076
Eric Laurent9d91ad52009-07-17 12:17:14 -07002077void AudioFlinger::PlaybackThread::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002078{
2079 buffer->raw = 0;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002080 mFrameCount = buffer->frameCount;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002081 step();
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002082 buffer->frameCount = 0;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002083}
2084
Eric Laurent9d91ad52009-07-17 12:17:14 -07002085bool AudioFlinger::PlaybackThread::TrackBase::step() {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002086 bool result;
2087 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002088
2089 result = cblk->stepServer(mFrameCount);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002090 if (!result) {
2091 LOGV("stepServer failed acquiring cblk mutex");
2092 mFlags |= STEPSERVER_FAILED;
2093 }
2094 return result;
2095}
2096
Eric Laurent9d91ad52009-07-17 12:17:14 -07002097void AudioFlinger::PlaybackThread::TrackBase::reset() {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002098 audio_track_cblk_t* cblk = this->cblk();
2099
2100 cblk->user = 0;
2101 cblk->server = 0;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002102 cblk->userBase = 0;
2103 cblk->serverBase = 0;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002104 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002105 LOGV("TrackBase::reset");
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002106}
2107
Eric Laurent9d91ad52009-07-17 12:17:14 -07002108sp<IMemory> AudioFlinger::PlaybackThread::TrackBase::getCblk() const
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002109{
2110 return mCblkMemory;
2111}
2112
Eric Laurent9d91ad52009-07-17 12:17:14 -07002113int AudioFlinger::PlaybackThread::TrackBase::sampleRate() const {
The Android Open Source Project4f68be12009-03-18 17:39:46 -07002114 return (int)mCblk->sampleRate;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002115}
2116
Eric Laurent9d91ad52009-07-17 12:17:14 -07002117int AudioFlinger::PlaybackThread::TrackBase::channelCount() const {
Eric Laurent0bac5382009-07-07 07:10:45 -07002118 return (int)mCblk->channels;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002119}
2120
Eric Laurent9d91ad52009-07-17 12:17:14 -07002121void* AudioFlinger::PlaybackThread::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002122 audio_track_cblk_t* cblk = this->cblk();
Eric Laurent9d91ad52009-07-17 12:17:14 -07002123 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
2124 int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002125
2126 // Check validity of returned pointer in case the track control block would have been corrupted.
Eric Laurent9d91ad52009-07-17 12:17:14 -07002127 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
2128 ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
The Android Open Source Project4f68be12009-03-18 17:39:46 -07002129 LOGE("TrackBase::getBuffer buffer out of range:\n start: %p, end %p , mBuffer %p mBufferEnd %p\n \
2130 server %d, serverBase %d, user %d, userBase %d, channels %d",
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002131 bufferStart, bufferEnd, mBuffer, mBufferEnd,
The Android Open Source Project4f68be12009-03-18 17:39:46 -07002132 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, cblk->channels);
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002133 return 0;
2134 }
2135
2136 return bufferStart;
2137}
2138
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002139// ----------------------------------------------------------------------------
2140
Eric Laurent9d91ad52009-07-17 12:17:14 -07002141// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
2142AudioFlinger::PlaybackThread::Track::Track(
2143 const wp<ThreadBase>& thread,
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002144 const sp<Client>& client,
2145 int streamType,
2146 uint32_t sampleRate,
2147 int format,
2148 int channelCount,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002149 int frameCount,
2150 const sp<IMemory>& sharedBuffer)
Eric Laurent9d91ad52009-07-17 12:17:14 -07002151 : TrackBase(thread, client, sampleRate, format, channelCount, frameCount, 0, sharedBuffer),
2152 mMute(false), mSharedBuffer(sharedBuffer), mName(-1)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002153{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002154 sp<ThreadBase> baseThread = thread.promote();
2155 if (baseThread != 0) {
2156 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
2157 mName = playbackThread->getTrackName_l();
2158 }
2159 LOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2160 if (mName < 0) {
2161 LOGE("no more track names available");
2162 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002163 mVolume[0] = 1.0f;
2164 mVolume[1] = 1.0f;
Eric Laurent570dd0b2009-05-22 09:18:15 -07002165 mStreamType = streamType;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002166 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
2167 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
2168 mCblk->frameSize = AudioSystem::isLinearPCM(format) ? channelCount * sizeof(int16_t) : sizeof(int8_t);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002169}
2170
Eric Laurent9d91ad52009-07-17 12:17:14 -07002171AudioFlinger::PlaybackThread::Track::~Track()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002172{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002173 LOGV("PlaybackThread::Track destructor");
2174 sp<ThreadBase> thread = mThread.promote();
2175 if (thread != 0) {
2176 Mutex::Autolock _l(thread->mLock);
2177 mState = TERMINATED;
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002178 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002179}
2180
Eric Laurent9d91ad52009-07-17 12:17:14 -07002181void AudioFlinger::PlaybackThread::Track::destroy()
2182{
2183 // NOTE: destroyTrack_l() can remove a strong reference to this Track
2184 // by removing it from mTracks vector, so there is a risk that this Tracks's
2185 // desctructor is called. As the destructor needs to lock mLock,
2186 // we must acquire a strong reference on this Track before locking mLock
2187 // here so that the destructor is called only when exiting this function.
2188 // On the other hand, as long as Track::destroy() is only called by
2189 // TrackHandle destructor, the TrackHandle still holds a strong ref on
2190 // this Track with its member mTrack.
2191 sp<Track> keep(this);
2192 { // scope for mLock
2193 sp<ThreadBase> thread = mThread.promote();
2194 if (thread != 0) {
2195 Mutex::Autolock _l(thread->mLock);
2196 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2197 playbackThread->destroyTrack_l(this);
2198 }
2199 }
2200}
2201
2202void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002203{
2204 snprintf(buffer, size, " %5d %5d %3u %3u %3u %3u %1d %1d %1d %5u %5u %5u %04x %04x\n",
2205 mName - AudioMixer::TRACK0,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002206 (mClient == NULL) ? getpid() : mClient->pid(),
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002207 mStreamType,
2208 mFormat,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002209 mCblk->channels,
2210 mFrameCount,
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002211 mState,
2212 mMute,
2213 mFillingUpStatus,
2214 mCblk->sampleRate,
2215 mCblk->volume[0],
2216 mCblk->volume[1],
2217 mCblk->server,
2218 mCblk->user);
2219}
2220
Eric Laurent9d91ad52009-07-17 12:17:14 -07002221status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002222{
2223 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002224 uint32_t framesReady;
2225 uint32_t framesReq = buffer->frameCount;
2226
2227 // Check if last stepServer failed, try to step now
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002228 if (mFlags & TrackBase::STEPSERVER_FAILED) {
2229 if (!step()) goto getNextBuffer_exit;
2230 LOGV("stepServer recovered");
2231 mFlags &= ~TrackBase::STEPSERVER_FAILED;
2232 }
2233
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002234 framesReady = cblk->framesReady();
2235
2236 if (LIKELY(framesReady)) {
2237 uint32_t s = cblk->server;
2238 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
2239
2240 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
2241 if (framesReq > framesReady) {
2242 framesReq = framesReady;
2243 }
2244 if (s + framesReq > bufferEnd) {
2245 framesReq = bufferEnd - s;
2246 }
2247
2248 buffer->raw = getBuffer(s, framesReq);
2249 if (buffer->raw == 0) goto getNextBuffer_exit;
2250
2251 buffer->frameCount = framesReq;
2252 return NO_ERROR;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002253 }
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002254
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002255getNextBuffer_exit:
2256 buffer->raw = 0;
2257 buffer->frameCount = 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002258 LOGV("getNextBuffer() no more data");
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002259 return NOT_ENOUGH_DATA;
2260}
2261
Eric Laurent9d91ad52009-07-17 12:17:14 -07002262bool AudioFlinger::PlaybackThread::Track::isReady() const {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002263 if (mFillingUpStatus != FS_FILLING) return true;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002264
2265 if (mCblk->framesReady() >= mCblk->frameCount ||
2266 mCblk->forceReady) {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002267 mFillingUpStatus = FS_FILLED;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002268 mCblk->forceReady = 0;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002269 return true;
2270 }
2271 return false;
2272}
2273
Eric Laurent9d91ad52009-07-17 12:17:14 -07002274status_t AudioFlinger::PlaybackThread::Track::start()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002275{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002276 LOGV("start(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2277 sp<ThreadBase> thread = mThread.promote();
2278 if (thread != 0) {
2279 Mutex::Autolock _l(thread->mLock);
2280 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2281 playbackThread->addTrack_l(this);
2282 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002283 return NO_ERROR;
2284}
2285
Eric Laurent9d91ad52009-07-17 12:17:14 -07002286void AudioFlinger::PlaybackThread::Track::stop()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002287{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002288 LOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2289 sp<ThreadBase> thread = mThread.promote();
2290 if (thread != 0) {
2291 Mutex::Autolock _l(thread->mLock);
2292 if (mState > STOPPED) {
2293 mState = STOPPED;
2294 // If the track is not active (PAUSED and buffers full), flush buffers
2295 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2296 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
2297 reset();
2298 }
2299 LOGV("(> STOPPED) => STOPPED (%d)", mName);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002300 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002301 }
2302}
2303
Eric Laurent9d91ad52009-07-17 12:17:14 -07002304void AudioFlinger::PlaybackThread::Track::pause()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002305{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002306 LOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurent9d91ad52009-07-17 12:17:14 -07002307 sp<ThreadBase> thread = mThread.promote();
2308 if (thread != 0) {
2309 Mutex::Autolock _l(thread->mLock);
2310 if (mState == ACTIVE || mState == RESUMING) {
2311 mState = PAUSING;
2312 LOGV("ACTIVE/RESUMING => PAUSING (%d)", mName);
2313 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002314 }
2315}
2316
Eric Laurent9d91ad52009-07-17 12:17:14 -07002317void AudioFlinger::PlaybackThread::Track::flush()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002318{
2319 LOGV("flush(%d)", mName);
Eric Laurent9d91ad52009-07-17 12:17:14 -07002320 sp<ThreadBase> thread = mThread.promote();
2321 if (thread != 0) {
2322 Mutex::Autolock _l(thread->mLock);
2323 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
2324 return;
2325 }
2326 // No point remaining in PAUSED state after a flush => go to
2327 // STOPPED state
2328 mState = STOPPED;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002329
Eric Laurent9d91ad52009-07-17 12:17:14 -07002330 mCblk->lock.lock();
2331 // NOTE: reset() will reset cblk->user and cblk->server with
2332 // the risk that at the same time, the AudioMixer is trying to read
2333 // data. In this case, getNextBuffer() would return a NULL pointer
2334 // as audio buffer => the AudioMixer code MUST always test that pointer
2335 // returned by getNextBuffer() is not NULL!
2336 reset();
2337 mCblk->lock.unlock();
2338 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002339}
2340
Eric Laurent9d91ad52009-07-17 12:17:14 -07002341void AudioFlinger::PlaybackThread::Track::reset()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002342{
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002343 // Do not reset twice to avoid discarding data written just after a flush and before
2344 // the audioflinger thread detects the track is stopped.
2345 if (!mResetDone) {
2346 TrackBase::reset();
2347 // Force underrun condition to avoid false underrun callback until first data is
2348 // written to buffer
2349 mCblk->flowControlFlag = 1;
2350 mCblk->forceReady = 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002351 mFillingUpStatus = FS_FILLING;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002352 mResetDone = true;
2353 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002354}
2355
Eric Laurent9d91ad52009-07-17 12:17:14 -07002356void AudioFlinger::PlaybackThread::Track::mute(bool muted)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002357{
2358 mMute = muted;
2359}
2360
Eric Laurent9d91ad52009-07-17 12:17:14 -07002361void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002362{
2363 mVolume[0] = left;
2364 mVolume[1] = right;
2365}
2366
2367// ----------------------------------------------------------------------------
2368
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002369// RecordTrack constructor must be called with AudioFlinger::mLock held
Eric Laurent9d91ad52009-07-17 12:17:14 -07002370AudioFlinger::RecordThread::RecordTrack::RecordTrack(
2371 const wp<ThreadBase>& thread,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002372 const sp<Client>& client,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002373 uint32_t sampleRate,
2374 int format,
2375 int channelCount,
2376 int frameCount,
2377 uint32_t flags)
Eric Laurent9d91ad52009-07-17 12:17:14 -07002378 : TrackBase(thread, client, sampleRate, format,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002379 channelCount, frameCount, flags, 0),
Eric Laurent9d91ad52009-07-17 12:17:14 -07002380 mOverflow(false)
2381{
2382 LOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
2383 if (format == AudioSystem::PCM_16_BIT) {
2384 mCblk->frameSize = channelCount * sizeof(int16_t);
2385 } else if (format == AudioSystem::PCM_8_BIT) {
2386 mCblk->frameSize = channelCount * sizeof(int8_t);
2387 } else {
2388 mCblk->frameSize = sizeof(int8_t);
2389 }
2390}
2391
2392AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002393{
2394}
2395
Eric Laurent9d91ad52009-07-17 12:17:14 -07002396status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002397{
2398 audio_track_cblk_t* cblk = this->cblk();
2399 uint32_t framesAvail;
2400 uint32_t framesReq = buffer->frameCount;
2401
2402 // Check if last stepServer failed, try to step now
2403 if (mFlags & TrackBase::STEPSERVER_FAILED) {
2404 if (!step()) goto getNextBuffer_exit;
2405 LOGV("stepServer recovered");
2406 mFlags &= ~TrackBase::STEPSERVER_FAILED;
2407 }
2408
2409 framesAvail = cblk->framesAvailable_l();
2410
2411 if (LIKELY(framesAvail)) {
2412 uint32_t s = cblk->server;
2413 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
2414
2415 if (framesReq > framesAvail) {
2416 framesReq = framesAvail;
2417 }
2418 if (s + framesReq > bufferEnd) {
2419 framesReq = bufferEnd - s;
2420 }
2421
2422 buffer->raw = getBuffer(s, framesReq);
2423 if (buffer->raw == 0) goto getNextBuffer_exit;
2424
2425 buffer->frameCount = framesReq;
2426 return NO_ERROR;
2427 }
2428
2429getNextBuffer_exit:
2430 buffer->raw = 0;
2431 buffer->frameCount = 0;
2432 return NOT_ENOUGH_DATA;
2433}
2434
Eric Laurent9d91ad52009-07-17 12:17:14 -07002435status_t AudioFlinger::RecordThread::RecordTrack::start()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002436{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002437 sp<ThreadBase> thread = mThread.promote();
2438 if (thread != 0) {
2439 RecordThread *recordThread = (RecordThread *)thread.get();
2440 return recordThread->start(this);
2441 }
2442 return NO_INIT;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002443}
2444
Eric Laurent9d91ad52009-07-17 12:17:14 -07002445void AudioFlinger::RecordThread::RecordTrack::stop()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002446{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002447 sp<ThreadBase> thread = mThread.promote();
2448 if (thread != 0) {
2449 RecordThread *recordThread = (RecordThread *)thread.get();
2450 recordThread->stop(this);
2451 TrackBase::reset();
2452 // Force overerrun condition to avoid false overrun callback until first data is
2453 // read from buffer
2454 mCblk->flowControlFlag = 1;
2455 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002456}
2457
2458
2459// ----------------------------------------------------------------------------
2460
Eric Laurent9d91ad52009-07-17 12:17:14 -07002461AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
2462 const wp<ThreadBase>& thread,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002463 uint32_t sampleRate,
2464 int format,
2465 int channelCount,
2466 int frameCount)
Eric Laurent9d91ad52009-07-17 12:17:14 -07002467 : Track(thread, NULL, AudioSystem::NUM_STREAM_TYPES, sampleRate, format, channelCount, frameCount, NULL),
2468 mActive(false)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002469{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002470
2471 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
Eric Laurentf5aba822009-08-10 23:22:32 -07002472 if (mCblk != NULL) {
2473 mCblk->out = 1;
2474 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
2475 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
2476 mOutBuffer.frameCount = 0;
2477 mWaitTimeMs = (playbackThread->frameCount() * 2 * 1000) / playbackThread->sampleRate();
2478 playbackThread->mTracks.add(this);
2479 LOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, mCblk->frameCount %d, mCblk->sampleRate %d, mCblk->channels %d mBufferEnd %p mWaitTimeMs %d",
2480 mCblk, mBuffer, mCblk->buffers, mCblk->frameCount, mCblk->sampleRate, mCblk->channels, mBufferEnd, mWaitTimeMs);
2481 } else {
2482 LOGW("Error creating output track on thread %p", playbackThread);
2483 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002484}
2485
Eric Laurent9d91ad52009-07-17 12:17:14 -07002486AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002487{
Eric Laurentf5aba822009-08-10 23:22:32 -07002488 clearBufferQueue();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002489}
2490
Eric Laurent9d91ad52009-07-17 12:17:14 -07002491status_t AudioFlinger::PlaybackThread::OutputTrack::start()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002492{
2493 status_t status = Track::start();
Eric Laurent9d91ad52009-07-17 12:17:14 -07002494 if (status != NO_ERROR) {
2495 return status;
2496 }
2497
2498 mActive = true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002499 mRetryCount = 127;
2500 return status;
2501}
2502
Eric Laurent9d91ad52009-07-17 12:17:14 -07002503void AudioFlinger::PlaybackThread::OutputTrack::stop()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002504{
2505 Track::stop();
2506 clearBufferQueue();
2507 mOutBuffer.frameCount = 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002508 mActive = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002509}
2510
Eric Laurent9d91ad52009-07-17 12:17:14 -07002511bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002512{
2513 Buffer *pInBuffer;
2514 Buffer inBuffer;
2515 uint32_t channels = mCblk->channels;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002516 bool outputBufferFull = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002517 inBuffer.frameCount = frames;
2518 inBuffer.i16 = data;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002519
2520 uint32_t waitTimeLeftMs = mWaitTimeMs;
2521
2522 if (!mActive) {
2523 start();
2524 sp<ThreadBase> thread = mThread.promote();
2525 if (thread != 0) {
2526 MixerThread *mixerThread = (MixerThread *)thread.get();
2527 if (mCblk->frameCount > frames){
2528 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
2529 uint32_t startFrames = (mCblk->frameCount - frames);
2530 pInBuffer = new Buffer;
2531 pInBuffer->mBuffer = new int16_t[startFrames * channels];
2532 pInBuffer->frameCount = startFrames;
2533 pInBuffer->i16 = pInBuffer->mBuffer;
2534 memset(pInBuffer->raw, 0, startFrames * channels * sizeof(int16_t));
2535 mBufferQueue.add(pInBuffer);
2536 } else {
2537 LOGW ("OutputTrack::write() %p no more buffers in queue", this);
2538 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002539 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002540 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002541 }
2542
Eric Laurent9d91ad52009-07-17 12:17:14 -07002543 while (waitTimeLeftMs) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002544 // First write pending buffers, then new data
2545 if (mBufferQueue.size()) {
2546 pInBuffer = mBufferQueue.itemAt(0);
2547 } else {
2548 pInBuffer = &inBuffer;
2549 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002550
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002551 if (pInBuffer->frameCount == 0) {
2552 break;
2553 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002554
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002555 if (mOutBuffer.frameCount == 0) {
2556 mOutBuffer.frameCount = pInBuffer->frameCount;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002557 nsecs_t startTime = systemTime();
2558 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
2559 LOGV ("OutputTrack::write() %p no more output buffers", this);
2560 outputBufferFull = true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002561 break;
2562 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002563 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
2564// LOGV("OutputTrack::write() waitTimeMs %d waitTimeLeftMs %d", waitTimeMs, waitTimeLeftMs)
2565 if (waitTimeLeftMs >= waitTimeMs) {
2566 waitTimeLeftMs -= waitTimeMs;
2567 } else {
2568 waitTimeLeftMs = 0;
2569 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002570 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002571
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002572 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
2573 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channels * sizeof(int16_t));
2574 mCblk->stepUser(outFrames);
2575 pInBuffer->frameCount -= outFrames;
2576 pInBuffer->i16 += outFrames * channels;
2577 mOutBuffer.frameCount -= outFrames;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002578 mOutBuffer.i16 += outFrames * channels;
2579
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002580 if (pInBuffer->frameCount == 0) {
2581 if (mBufferQueue.size()) {
2582 mBufferQueue.removeAt(0);
2583 delete [] pInBuffer->mBuffer;
2584 delete pInBuffer;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002585 LOGV("OutputTrack::write() %p released overflow buffer %d", this, mBufferQueue.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002586 } else {
2587 break;
2588 }
2589 }
2590 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002591
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002592 // If we could not write all frames, allocate a buffer and queue it for next time.
2593 if (inBuffer.frameCount) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07002594 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002595 pInBuffer = new Buffer;
2596 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channels];
2597 pInBuffer->frameCount = inBuffer.frameCount;
2598 pInBuffer->i16 = pInBuffer->mBuffer;
2599 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channels * sizeof(int16_t));
2600 mBufferQueue.add(pInBuffer);
Eric Laurent9d91ad52009-07-17 12:17:14 -07002601 LOGV("OutputTrack::write() %p adding overflow buffer %d", this, mBufferQueue.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002602 } else {
Eric Laurent9d91ad52009-07-17 12:17:14 -07002603 LOGW("OutputTrack::write() %p no more overflow buffers", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002604 }
2605 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002606
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002607 // Calling write() with a 0 length buffer, means that no more data will be written:
Eric Laurent9d91ad52009-07-17 12:17:14 -07002608 // 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 -08002609 // by output mixer.
Eric Laurent9d91ad52009-07-17 12:17:14 -07002610 if (frames == 0 && mBufferQueue.size() == 0) {
2611 if (mCblk->user < mCblk->frameCount) {
2612 frames = mCblk->frameCount - mCblk->user;
2613 pInBuffer = new Buffer;
2614 pInBuffer->mBuffer = new int16_t[frames * channels];
2615 pInBuffer->frameCount = frames;
2616 pInBuffer->i16 = pInBuffer->mBuffer;
2617 memset(pInBuffer->raw, 0, frames * channels * sizeof(int16_t));
2618 mBufferQueue.add(pInBuffer);
2619 } else {
2620 stop();
2621 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002622 }
2623
Eric Laurent9d91ad52009-07-17 12:17:14 -07002624 return outputBufferFull;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002625}
2626
Eric Laurent9d91ad52009-07-17 12:17:14 -07002627status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002628{
2629 int active;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002630 status_t result;
2631 audio_track_cblk_t* cblk = mCblk;
2632 uint32_t framesReq = buffer->frameCount;
2633
Eric Laurent9d91ad52009-07-17 12:17:14 -07002634// LOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002635 buffer->frameCount = 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002636
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002637 uint32_t framesAvail = cblk->framesAvailable();
2638
Eric Laurent9d91ad52009-07-17 12:17:14 -07002639
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002640 if (framesAvail == 0) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07002641 Mutex::Autolock _l(cblk->lock);
2642 goto start_loop_here;
2643 while (framesAvail == 0) {
2644 active = mActive;
2645 if (UNLIKELY(!active)) {
2646 LOGV("Not active and NO_MORE_BUFFERS");
2647 return AudioTrack::NO_MORE_BUFFERS;
2648 }
2649 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
2650 if (result != NO_ERROR) {
2651 return AudioTrack::NO_MORE_BUFFERS;
2652 }
2653 // read the server count again
2654 start_loop_here:
2655 framesAvail = cblk->framesAvailable_l();
2656 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002657 }
2658
Eric Laurent9d91ad52009-07-17 12:17:14 -07002659// if (framesAvail < framesReq) {
2660// return AudioTrack::NO_MORE_BUFFERS;
2661// }
2662
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002663 if (framesReq > framesAvail) {
2664 framesReq = framesAvail;
2665 }
2666
2667 uint32_t u = cblk->user;
2668 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
2669
2670 if (u + framesReq > bufferEnd) {
2671 framesReq = bufferEnd - u;
2672 }
2673
2674 buffer->frameCount = framesReq;
2675 buffer->raw = (void *)cblk->buffer(u);
2676 return NO_ERROR;
2677}
2678
2679
Eric Laurent9d91ad52009-07-17 12:17:14 -07002680void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002681{
2682 size_t size = mBufferQueue.size();
2683 Buffer *pBuffer;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002684
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002685 for (size_t i = 0; i < size; i++) {
2686 pBuffer = mBufferQueue.itemAt(i);
2687 delete [] pBuffer->mBuffer;
2688 delete pBuffer;
2689 }
2690 mBufferQueue.clear();
2691}
2692
2693// ----------------------------------------------------------------------------
2694
2695AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
2696 : RefBase(),
2697 mAudioFlinger(audioFlinger),
2698 mMemoryDealer(new MemoryDealer(1024*1024)),
2699 mPid(pid)
2700{
2701 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
2702}
2703
2704AudioFlinger::Client::~Client()
2705{
2706 mAudioFlinger->removeClient(mPid);
2707}
2708
2709const sp<MemoryDealer>& AudioFlinger::Client::heap() const
2710{
2711 return mMemoryDealer;
2712}
2713
2714// ----------------------------------------------------------------------------
2715
Eric Laurent9d91ad52009-07-17 12:17:14 -07002716AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002717 : BnAudioTrack(),
2718 mTrack(track)
2719{
2720}
2721
2722AudioFlinger::TrackHandle::~TrackHandle() {
2723 // just stop the track on deletion, associated resources
2724 // will be freed from the main thread once all pending buffers have
2725 // been played. Unless it's not in the active track list, in which
2726 // case we free everything now...
2727 mTrack->destroy();
2728}
2729
2730status_t AudioFlinger::TrackHandle::start() {
2731 return mTrack->start();
2732}
2733
2734void AudioFlinger::TrackHandle::stop() {
2735 mTrack->stop();
2736}
2737
2738void AudioFlinger::TrackHandle::flush() {
2739 mTrack->flush();
2740}
2741
2742void AudioFlinger::TrackHandle::mute(bool e) {
2743 mTrack->mute(e);
2744}
2745
2746void AudioFlinger::TrackHandle::pause() {
2747 mTrack->pause();
2748}
2749
2750void AudioFlinger::TrackHandle::setVolume(float left, float right) {
2751 mTrack->setVolume(left, right);
2752}
2753
2754sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
2755 return mTrack->getCblk();
2756}
2757
2758status_t AudioFlinger::TrackHandle::onTransact(
2759 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2760{
2761 return BnAudioTrack::onTransact(code, data, reply, flags);
2762}
2763
2764// ----------------------------------------------------------------------------
2765
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002766sp<IAudioRecord> AudioFlinger::openRecord(
2767 pid_t pid,
Eric Laurente0e9ecc2009-07-28 08:44:33 -07002768 int input,
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002769 uint32_t sampleRate,
2770 int format,
2771 int channelCount,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002772 int frameCount,
2773 uint32_t flags,
2774 status_t *status)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002775{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002776 sp<RecordThread::RecordTrack> recordTrack;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002777 sp<RecordHandle> recordHandle;
2778 sp<Client> client;
2779 wp<Client> wclient;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002780 status_t lStatus;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002781 RecordThread *thread;
2782 size_t inFrameCount;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002783
2784 // check calling permissions
2785 if (!recordingAllowed()) {
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002786 lStatus = PERMISSION_DENIED;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002787 goto Exit;
2788 }
2789
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002790 // add client to list
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002791 { // scope for mLock
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002792 Mutex::Autolock _l(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07002793 thread = checkRecordThread_l(input);
2794 if (thread == NULL) {
2795 lStatus = BAD_VALUE;
2796 goto Exit;
2797 }
2798
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002799 wclient = mClients.valueFor(pid);
2800 if (wclient != NULL) {
2801 client = wclient.promote();
2802 } else {
2803 client = new Client(this, pid);
2804 mClients.add(pid, client);
2805 }
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002806
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002807 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent9d91ad52009-07-17 12:17:14 -07002808 recordTrack = new RecordThread::RecordTrack(thread, client, sampleRate,
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002809 format, channelCount, frameCount, flags);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002810 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002811 if (recordTrack->getCblk() == NULL) {
2812 recordTrack.clear();
2813 lStatus = NO_MEMORY;
2814 goto Exit;
2815 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002816
2817 // return to handle to client
2818 recordHandle = new RecordHandle(recordTrack);
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002819 lStatus = NO_ERROR;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002820
2821Exit:
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002822 if (status) {
2823 *status = lStatus;
2824 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002825 return recordHandle;
2826}
2827
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002828// ----------------------------------------------------------------------------
2829
Eric Laurent9d91ad52009-07-17 12:17:14 -07002830AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002831 : BnAudioRecord(),
2832 mRecordTrack(recordTrack)
2833{
2834}
2835
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002836AudioFlinger::RecordHandle::~RecordHandle() {
2837 stop();
2838}
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002839
2840status_t AudioFlinger::RecordHandle::start() {
2841 LOGV("RecordHandle::start()");
2842 return mRecordTrack->start();
2843}
2844
2845void AudioFlinger::RecordHandle::stop() {
2846 LOGV("RecordHandle::stop()");
2847 mRecordTrack->stop();
2848}
2849
2850sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
2851 return mRecordTrack->getCblk();
2852}
2853
2854status_t AudioFlinger::RecordHandle::onTransact(
2855 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2856{
2857 return BnAudioRecord::onTransact(code, data, reply, flags);
2858}
2859
2860// ----------------------------------------------------------------------------
2861
Eric Laurent9d91ad52009-07-17 12:17:14 -07002862AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger, AudioStreamIn *input, uint32_t sampleRate, uint32_t channels) :
2863 ThreadBase(audioFlinger),
2864 mInput(input), mResampler(0), mRsmpOutBuffer(0), mRsmpInBuffer(0)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002865{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002866 mReqChannelCount = AudioSystem::popCount(channels);
2867 mReqSampleRate = sampleRate;
2868 readInputParameters();
2869 sendConfigEvent(AudioSystem::INPUT_OPENED);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002870}
2871
Eric Laurent9d91ad52009-07-17 12:17:14 -07002872
2873AudioFlinger::RecordThread::~RecordThread()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002874{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002875 delete[] mRsmpInBuffer;
2876 if (mResampler != 0) {
2877 delete mResampler;
2878 delete[] mRsmpOutBuffer;
2879 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002880}
2881
Eric Laurent9d91ad52009-07-17 12:17:14 -07002882void AudioFlinger::RecordThread::onFirstRef()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002883{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002884 const size_t SIZE = 256;
2885 char buffer[SIZE];
2886
2887 snprintf(buffer, SIZE, "Record Thread %p", this);
2888
2889 run(buffer, PRIORITY_URGENT_AUDIO);
2890}
2891bool AudioFlinger::RecordThread::threadLoop()
2892{
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002893 AudioBufferProvider::Buffer buffer;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002894 sp<RecordTrack> activeTrack;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002895
2896 // start recording
2897 while (!exitPending()) {
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002898
Eric Laurent9d91ad52009-07-17 12:17:14 -07002899 processConfigEvents();
2900
2901 { // scope for mLock
2902 Mutex::Autolock _l(mLock);
2903 checkForNewParameters_l();
2904 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
2905 if (!mStandby) {
2906 mInput->standby();
2907 mStandby = true;
2908 }
2909
2910 if (exitPending()) break;
2911
2912 LOGV("RecordThread: loop stopping");
2913 // go to sleep
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002914 mWaitWorkCV.wait(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07002915 LOGV("RecordThread: loop starting");
2916 continue;
2917 }
2918 if (mActiveTrack != 0) {
2919 if (mActiveTrack->mState == TrackBase::PAUSING) {
2920 mActiveTrack.clear();
2921 mStartStopCond.broadcast();
2922 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
2923 mRsmpInIndex = mFrameCount;
2924 if (mReqChannelCount != mActiveTrack->channelCount()) {
2925 mActiveTrack.clear();
2926 } else {
Eric Laurent9e7b8192009-08-10 02:41:54 -07002927 mActiveTrack->mState = TrackBase::ACTIVE;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002928 }
2929 mStartStopCond.broadcast();
2930 }
2931 mStandby = false;
2932 }
2933 }
2934
2935 if (mActiveTrack != 0) {
2936 buffer.frameCount = mFrameCount;
2937 if (LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
2938 size_t framesOut = buffer.frameCount;
2939 if (mResampler == 0) {
2940 // no resampling
2941 while (framesOut) {
2942 size_t framesIn = mFrameCount - mRsmpInIndex;
2943 if (framesIn) {
2944 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
2945 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
2946 if (framesIn > framesOut)
2947 framesIn = framesOut;
2948 mRsmpInIndex += framesIn;
2949 framesOut -= framesIn;
2950 if (mChannelCount == mReqChannelCount ||
2951 mFormat != AudioSystem::PCM_16_BIT) {
2952 memcpy(dst, src, framesIn * mFrameSize);
2953 } else {
2954 int16_t *src16 = (int16_t *)src;
2955 int16_t *dst16 = (int16_t *)dst;
2956 if (mChannelCount == 1) {
2957 while (framesIn--) {
2958 *dst16++ = *src16;
2959 *dst16++ = *src16++;
2960 }
2961 } else {
2962 while (framesIn--) {
2963 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
2964 src16 += 2;
2965 }
2966 }
2967 }
2968 }
2969 if (framesOut && mFrameCount == mRsmpInIndex) {
2970 ssize_t bytesRead;
2971 if (framesOut == mFrameCount &&
2972 (mChannelCount == mReqChannelCount || mFormat != AudioSystem::PCM_16_BIT)) {
2973 bytesRead = mInput->read(buffer.raw, mInputBytes);
2974 framesOut = 0;
2975 } else {
2976 bytesRead = mInput->read(mRsmpInBuffer, mInputBytes);
2977 mRsmpInIndex = 0;
2978 }
2979 if (bytesRead < 0) {
2980 LOGE("Error reading audio input");
2981 sleep(1);
2982 mRsmpInIndex = mFrameCount;
2983 framesOut = 0;
2984 buffer.frameCount = 0;
2985 }
2986 }
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002987 }
2988 } else {
Eric Laurent9d91ad52009-07-17 12:17:14 -07002989 // resampling
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002990
Eric Laurent9d91ad52009-07-17 12:17:14 -07002991 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
2992 // alter output frame count as if we were expecting stereo samples
2993 if (mChannelCount == 1 && mReqChannelCount == 1) {
2994 framesOut >>= 1;
2995 }
2996 mResampler->resample(mRsmpOutBuffer, framesOut, this);
2997 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
2998 // are 32 bit aligned which should be always true.
2999 if (mChannelCount == 2 && mReqChannelCount == 1) {
3000 AudioMixer::ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
3001 // the resampler always outputs stereo samples: do post stereo to mono conversion
3002 int16_t *src = (int16_t *)mRsmpOutBuffer;
3003 int16_t *dst = buffer.i16;
3004 while (framesOut--) {
3005 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
3006 src += 2;
3007 }
3008 } else {
3009 AudioMixer::ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
3010 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003011
Eric Laurent9d91ad52009-07-17 12:17:14 -07003012 }
3013 mActiveTrack->releaseBuffer(&buffer);
3014 mActiveTrack->overflow();
3015 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003016 // client isn't retrieving buffers fast enough
3017 else {
Eric Laurent9d91ad52009-07-17 12:17:14 -07003018 if (!mActiveTrack->setOverflow())
3019 LOGW("RecordThread: buffer overflow");
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003020 // Release the processor for a while before asking for a new buffer.
3021 // This will give the application more chance to read from the buffer and
3022 // clear the overflow.
3023 usleep(5000);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003024 }
3025 }
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003026 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003027
Eric Laurent9d91ad52009-07-17 12:17:14 -07003028 if (!mStandby) {
3029 mInput->standby();
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003030 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003031 mActiveTrack.clear();
3032
3033 sendConfigEvent(AudioSystem::INPUT_CLOSED);
3034 processConfigEvents();
3035
3036 LOGV("RecordThread %p exiting", this);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003037 return false;
3038}
3039
Eric Laurent9d91ad52009-07-17 12:17:14 -07003040status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003041{
Eric Laurent9d91ad52009-07-17 12:17:14 -07003042 LOGV("RecordThread::start");
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003043 AutoMutex lock(&mLock);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003044
Eric Laurent9d91ad52009-07-17 12:17:14 -07003045 if (mActiveTrack != 0) {
3046 if (recordTrack != mActiveTrack.get()) return -EBUSY;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003047
Eric Laurent9d91ad52009-07-17 12:17:14 -07003048 if (mActiveTrack->mState == TrackBase::PAUSING) mActiveTrack->mState = TrackBase::RESUMING;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003049
Eric Laurent9d91ad52009-07-17 12:17:14 -07003050 return NO_ERROR;
3051 }
3052
3053 mActiveTrack = recordTrack;
3054 mActiveTrack->mState = TrackBase::RESUMING;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003055 // signal thread to start
3056 LOGV("Signal record thread");
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003057 mWaitWorkCV.signal();
Eric Laurent9d91ad52009-07-17 12:17:14 -07003058 mStartStopCond.wait(mLock);
3059 if (mActiveTrack != 0) {
3060 LOGV("Record started OK");
3061 return NO_ERROR;
3062 } else {
3063 LOGV("Record failed to start");
3064 return BAD_VALUE;
3065 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003066}
3067
Eric Laurent9d91ad52009-07-17 12:17:14 -07003068void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
3069 LOGV("RecordThread::stop");
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003070 AutoMutex lock(&mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003071 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
3072 mActiveTrack->mState = TrackBase::PAUSING;
3073 mStartStopCond.wait(mLock);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003074 }
3075}
3076
Eric Laurent9d91ad52009-07-17 12:17:14 -07003077status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003078{
3079 const size_t SIZE = 256;
3080 char buffer[SIZE];
3081 String8 result;
3082 pid_t pid = 0;
3083
Eric Laurent9d91ad52009-07-17 12:17:14 -07003084 if (mActiveTrack != 0 && mActiveTrack->mClient != 0) {
3085 snprintf(buffer, SIZE, "Record client pid: %d\n", mActiveTrack->mClient->pid());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003086 result.append(buffer);
3087 } else {
3088 result.append("No record client\n");
3089 }
3090 write(fd, result.string(), result.size());
3091 return NO_ERROR;
3092}
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003093
Eric Laurent9d91ad52009-07-17 12:17:14 -07003094status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3095{
3096 size_t framesReq = buffer->frameCount;
3097 size_t framesReady = mFrameCount - mRsmpInIndex;
3098 int channelCount;
3099
3100 if (framesReady == 0) {
3101 ssize_t bytesRead = mInput->read(mRsmpInBuffer, mInputBytes);
3102 if (bytesRead < 0) {
3103 LOGE("RecordThread::getNextBuffer() Error reading audio input");
3104 sleep(1);
3105 buffer->raw = 0;
3106 buffer->frameCount = 0;
3107 return NOT_ENOUGH_DATA;
3108 }
3109 mRsmpInIndex = 0;
3110 framesReady = mFrameCount;
3111 }
3112
3113 if (framesReq > framesReady) {
3114 framesReq = framesReady;
3115 }
3116
3117 if (mChannelCount == 1 && mReqChannelCount == 2) {
3118 channelCount = 1;
3119 } else {
3120 channelCount = 2;
3121 }
3122 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
3123 buffer->frameCount = framesReq;
3124 return NO_ERROR;
3125}
3126
3127void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3128{
3129 mRsmpInIndex += buffer->frameCount;
3130 buffer->frameCount = 0;
3131}
3132
3133bool AudioFlinger::RecordThread::checkForNewParameters_l()
3134{
3135 bool reconfig = false;
3136
Eric Laurent3464c012009-08-04 09:45:33 -07003137 while (!mNewParameters.isEmpty()) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07003138 status_t status = NO_ERROR;
Eric Laurent3464c012009-08-04 09:45:33 -07003139 String8 keyValuePair = mNewParameters[0];
3140 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003141 int value;
3142 int reqFormat = mFormat;
3143 int reqSamplingRate = mReqSampleRate;
3144 int reqChannelCount = mReqChannelCount;
Eric Laurent3464c012009-08-04 09:45:33 -07003145
3146 mNewParameters.removeAt(0);
3147
Eric Laurent9d91ad52009-07-17 12:17:14 -07003148 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3149 reqSamplingRate = value;
3150 reconfig = true;
3151 }
3152 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
3153 reqFormat = value;
3154 reconfig = true;
3155 }
3156 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
3157 reqChannelCount = AudioSystem::popCount(value);
3158 reconfig = true;
3159 }
3160 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3161 // do not accept frame count changes if tracks are open as the track buffer
3162 // size depends on frame count and correct behavior would not be garantied
3163 // if frame count is changed after track creation
3164 if (mActiveTrack != 0) {
3165 status = INVALID_OPERATION;
3166 } else {
3167 reconfig = true;
3168 }
3169 }
3170 if (status == NO_ERROR) {
Eric Laurent3464c012009-08-04 09:45:33 -07003171 status = mInput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003172 if (status == INVALID_OPERATION) {
3173 mInput->standby();
Eric Laurent3464c012009-08-04 09:45:33 -07003174 status = mInput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003175 }
3176 if (reconfig) {
3177 if (status == BAD_VALUE &&
3178 reqFormat == mInput->format() && reqFormat == AudioSystem::PCM_16_BIT &&
3179 ((int)mInput->sampleRate() <= 2 * reqSamplingRate) &&
3180 (AudioSystem::popCount(mInput->channels()) < 3) && (reqChannelCount < 3)) {
3181 status = NO_ERROR;
3182 }
3183 if (status == NO_ERROR) {
3184 readInputParameters();
Eric Laurent3464c012009-08-04 09:45:33 -07003185 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003186 }
3187 }
3188 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003189 mParamStatus = status;
3190 mParamCond.signal();
Eric Laurent3464c012009-08-04 09:45:33 -07003191 mWaitWorkCV.wait(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003192 }
3193 return reconfig;
3194}
3195
3196String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
3197{
3198 return mInput->getParameters(keys);
3199}
3200
3201void AudioFlinger::RecordThread::audioConfigChanged(int event, int param) {
3202 AudioSystem::OutputDescriptor desc;
3203 void *param2 = 0;
3204
3205 switch (event) {
3206 case AudioSystem::INPUT_OPENED:
3207 case AudioSystem::INPUT_CONFIG_CHANGED:
3208 desc.channels = mChannelCount;
3209 desc.samplingRate = mSampleRate;
3210 desc.format = mFormat;
3211 desc.frameCount = mFrameCount;
3212 desc.latency = 0;
3213 param2 = &desc;
3214 break;
3215
3216 case AudioSystem::INPUT_CLOSED:
3217 default:
3218 break;
3219 }
3220 mAudioFlinger->audioConfigChanged(event, this, param2);
3221}
3222
3223void AudioFlinger::RecordThread::readInputParameters()
3224{
3225 if (mRsmpInBuffer) delete mRsmpInBuffer;
3226 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
3227 if (mResampler) delete mResampler;
3228 mResampler = 0;
3229
3230 mSampleRate = mInput->sampleRate();
3231 mChannelCount = AudioSystem::popCount(mInput->channels());
3232 mFormat = mInput->format();
3233 mFrameSize = mInput->frameSize();
3234 mInputBytes = mInput->bufferSize();
3235 mFrameCount = mInputBytes / mFrameSize;
3236 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
3237
3238 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
3239 {
3240 int channelCount;
3241 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
3242 // stereo to mono post process as the resampler always outputs stereo.
3243 if (mChannelCount == 1 && mReqChannelCount == 2) {
3244 channelCount = 1;
3245 } else {
3246 channelCount = 2;
3247 }
3248 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
3249 mResampler->setSampleRate(mSampleRate);
3250 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
3251 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
3252
3253 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
3254 if (mChannelCount == 1 && mReqChannelCount == 1) {
3255 mFrameCount >>= 1;
3256 }
3257
3258 }
3259 mRsmpInIndex = mFrameCount;
3260}
3261
3262// ----------------------------------------------------------------------------
3263
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003264int AudioFlinger::openOutput(uint32_t *pDevices,
Eric Laurent9d91ad52009-07-17 12:17:14 -07003265 uint32_t *pSamplingRate,
3266 uint32_t *pFormat,
3267 uint32_t *pChannels,
3268 uint32_t *pLatencyMs,
3269 uint32_t flags)
3270{
3271 status_t status;
3272 PlaybackThread *thread = NULL;
3273 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
3274 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
3275 uint32_t format = pFormat ? *pFormat : 0;
3276 uint32_t channels = pChannels ? *pChannels : 0;
3277 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
3278
3279 LOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
3280 pDevices ? *pDevices : 0,
3281 samplingRate,
3282 format,
3283 channels,
3284 flags);
3285
3286 if (pDevices == NULL || *pDevices == 0) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003287 return 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003288 }
3289 Mutex::Autolock _l(mLock);
3290
3291 AudioStreamOut *output = mAudioHardware->openOutputStream(*pDevices,
3292 (int *)&format,
3293 &channels,
3294 &samplingRate,
3295 &status);
3296 LOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
3297 output,
3298 samplingRate,
3299 format,
3300 channels,
3301 status);
3302
3303 mHardwareStatus = AUDIO_HW_IDLE;
3304 if (output != 0) {
3305 if ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) ||
3306 (format != AudioSystem::PCM_16_BIT) ||
3307 (channels != AudioSystem::CHANNEL_OUT_STEREO)) {
3308 thread = new DirectOutputThread(this, output);
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003309 LOGV("openOutput() created direct output: ID %d thread %p", (mNextThreadId + 1), thread);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003310 } else {
3311 thread = new MixerThread(this, output);
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003312 LOGV("openOutput() created mixer output: ID %d thread %p", (mNextThreadId + 1), thread);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003313 }
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003314 mPlaybackThreads.add(++mNextThreadId, thread);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003315
3316 if (pSamplingRate) *pSamplingRate = samplingRate;
3317 if (pFormat) *pFormat = format;
3318 if (pChannels) *pChannels = channels;
3319 if (pLatencyMs) *pLatencyMs = thread->latency();
3320 }
3321
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003322 return mNextThreadId;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003323}
3324
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003325int AudioFlinger::openDuplicateOutput(int output1, int output2)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003326{
3327 Mutex::Autolock _l(mLock);
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003328 MixerThread *thread1 = checkMixerThread_l(output1);
3329 MixerThread *thread2 = checkMixerThread_l(output2);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003330
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003331 if (thread1 == NULL || thread2 == NULL) {
3332 LOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
3333 return 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003334 }
3335
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003336
3337 DuplicatingThread *thread = new DuplicatingThread(this, thread1);
3338 thread->addOutputTrack(thread2);
3339 mPlaybackThreads.add(++mNextThreadId, thread);
3340 return mNextThreadId;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003341}
3342
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003343status_t AudioFlinger::closeOutput(int output)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003344{
Eric Laurentdae20d92009-08-04 08:37:05 -07003345 // keep strong reference on the playback thread so that
3346 // it is not destroyed while exit() is executed
3347 sp <PlaybackThread> thread;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003348 {
3349 Mutex::Autolock _l(mLock);
3350 thread = checkPlaybackThread_l(output);
3351 if (thread == NULL) {
3352 return BAD_VALUE;
3353 }
3354
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003355 LOGV("closeOutput() %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003356
3357 if (thread->type() == PlaybackThread::MIXER) {
3358 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003359 if (mPlaybackThreads.valueAt(i)->type() == PlaybackThread::DUPLICATING) {
3360 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Eric Laurentdae20d92009-08-04 08:37:05 -07003361 dupThread->removeOutputTrack((MixerThread *)thread.get());
Eric Laurent9d91ad52009-07-17 12:17:14 -07003362 }
3363 }
3364 }
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003365 mPlaybackThreads.removeItem(output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003366 }
3367 thread->exit();
3368
Eric Laurentdae20d92009-08-04 08:37:05 -07003369 if (thread->type() != PlaybackThread::DUPLICATING) {
3370 mAudioHardware->closeOutputStream(thread->getOutput());
3371 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003372 return NO_ERROR;
3373}
3374
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003375status_t AudioFlinger::suspendOutput(int output)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003376{
3377 Mutex::Autolock _l(mLock);
3378 PlaybackThread *thread = checkPlaybackThread_l(output);
3379
3380 if (thread == NULL) {
3381 return BAD_VALUE;
3382 }
3383
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003384 LOGV("suspendOutput() %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003385 thread->suspend();
3386
3387 return NO_ERROR;
3388}
3389
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003390status_t AudioFlinger::restoreOutput(int output)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003391{
3392 Mutex::Autolock _l(mLock);
3393 PlaybackThread *thread = checkPlaybackThread_l(output);
3394
3395 if (thread == NULL) {
3396 return BAD_VALUE;
3397 }
3398
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003399 LOGV("restoreOutput() %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003400
3401 thread->restore();
3402
3403 return NO_ERROR;
3404}
3405
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003406int AudioFlinger::openInput(uint32_t *pDevices,
Eric Laurent9d91ad52009-07-17 12:17:14 -07003407 uint32_t *pSamplingRate,
3408 uint32_t *pFormat,
3409 uint32_t *pChannels,
3410 uint32_t acoustics)
3411{
3412 status_t status;
3413 RecordThread *thread = NULL;
3414 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
3415 uint32_t format = pFormat ? *pFormat : 0;
3416 uint32_t channels = pChannels ? *pChannels : 0;
3417 uint32_t reqSamplingRate = samplingRate;
3418 uint32_t reqFormat = format;
3419 uint32_t reqChannels = channels;
3420
3421 if (pDevices == NULL || *pDevices == 0) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003422 return 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003423 }
3424 Mutex::Autolock _l(mLock);
3425
3426 AudioStreamIn *input = mAudioHardware->openInputStream(*pDevices,
3427 (int *)&format,
3428 &channels,
3429 &samplingRate,
3430 &status,
3431 (AudioSystem::audio_in_acoustics)acoustics);
3432 LOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
3433 input,
3434 samplingRate,
3435 format,
3436 channels,
3437 acoustics,
3438 status);
3439
3440 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
3441 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
3442 // or stereo to mono conversions on 16 bit PCM inputs.
3443 if (input == 0 && status == BAD_VALUE &&
3444 reqFormat == format && format == AudioSystem::PCM_16_BIT &&
3445 (samplingRate <= 2 * reqSamplingRate) &&
3446 (AudioSystem::popCount(channels) < 3) && (AudioSystem::popCount(reqChannels) < 3)) {
3447 LOGV("openInput() reopening with proposed sampling rate and channels");
3448 input = mAudioHardware->openInputStream(*pDevices,
3449 (int *)&format,
3450 &channels,
3451 &samplingRate,
3452 &status,
3453 (AudioSystem::audio_in_acoustics)acoustics);
3454 }
3455
3456 if (input != 0) {
3457 // Start record thread
3458 thread = new RecordThread(this, input, reqSamplingRate, reqChannels);
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003459 mRecordThreads.add(++mNextThreadId, thread);
3460 LOGV("openInput() created record thread: ID %d thread %p", mNextThreadId, thread);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003461 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
3462 if (pFormat) *pFormat = format;
3463 if (pChannels) *pChannels = reqChannels;
3464
3465 input->standby();
3466 }
3467
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003468 return mNextThreadId;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003469}
3470
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003471status_t AudioFlinger::closeInput(int input)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003472{
Eric Laurentdae20d92009-08-04 08:37:05 -07003473 // keep strong reference on the record thread so that
3474 // it is not destroyed while exit() is executed
3475 sp <RecordThread> thread;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003476 {
3477 Mutex::Autolock _l(mLock);
3478 thread = checkRecordThread_l(input);
3479 if (thread == NULL) {
3480 return BAD_VALUE;
3481 }
3482
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003483 LOGV("closeInput() %d", input);
3484 mRecordThreads.removeItem(input);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003485 }
3486 thread->exit();
3487
Eric Laurentdae20d92009-08-04 08:37:05 -07003488 mAudioHardware->closeInputStream(thread->getInput());
3489
Eric Laurent9d91ad52009-07-17 12:17:14 -07003490 return NO_ERROR;
3491}
3492
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003493status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003494{
3495 Mutex::Autolock _l(mLock);
3496 MixerThread *dstThread = checkMixerThread_l(output);
3497 if (dstThread == NULL) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003498 LOGW("setStreamOutput() bad output id %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003499 return BAD_VALUE;
3500 }
3501
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003502 LOGV("setStreamOutput() stream %d to output %d", stream, output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003503
3504 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003505 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent9d91ad52009-07-17 12:17:14 -07003506 if (thread != dstThread &&
3507 thread->type() != PlaybackThread::DIRECT) {
3508 MixerThread *srcThread = (MixerThread *)thread;
3509 SortedVector < sp<MixerThread::Track> > tracks;
3510 SortedVector < wp<MixerThread::Track> > activeTracks;
3511 srcThread->getTracks(tracks, activeTracks, stream);
3512 if (tracks.size()) {
3513 dstThread->putTracks(tracks, activeTracks);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003514 }
Eric Laurentd55d1792009-07-28 06:11:55 -07003515 dstThread->sendConfigEvent(AudioSystem::STREAM_CONFIG_CHANGED, stream);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003516 }
3517 }
3518
3519 return NO_ERROR;
3520}
3521
3522// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003523AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
Eric Laurent9d91ad52009-07-17 12:17:14 -07003524{
3525 PlaybackThread *thread = NULL;
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003526 if (mPlaybackThreads.indexOfKey(output) >= 0) {
3527 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
Eric Laurent9d91ad52009-07-17 12:17:14 -07003528 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003529 return thread;
3530}
3531
3532// checkMixerThread_l() must be called with AudioFlinger::mLock held
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003533AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
Eric Laurent9d91ad52009-07-17 12:17:14 -07003534{
3535 PlaybackThread *thread = checkPlaybackThread_l(output);
3536 if (thread != NULL) {
3537 if (thread->type() == PlaybackThread::DIRECT) {
3538 thread = NULL;
3539 }
3540 }
3541 return (MixerThread *)thread;
3542}
3543
3544// checkRecordThread_l() must be called with AudioFlinger::mLock held
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003545AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
Eric Laurent9d91ad52009-07-17 12:17:14 -07003546{
3547 RecordThread *thread = NULL;
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003548 if (mRecordThreads.indexOfKey(input) >= 0) {
3549 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
Eric Laurent9d91ad52009-07-17 12:17:14 -07003550 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003551 return thread;
3552}
3553
3554// ----------------------------------------------------------------------------
3555
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003556status_t AudioFlinger::onTransact(
3557 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3558{
3559 return BnAudioFlinger::onTransact(code, data, reply, flags);
3560}
3561
3562// ----------------------------------------------------------------------------
Eric Laurent9d91ad52009-07-17 12:17:14 -07003563
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003564void AudioFlinger::instantiate() {
3565 defaultServiceManager()->addService(
3566 String16("media.audio_flinger"), new AudioFlinger());
3567}
3568
3569}; // namespace android