blob: 3276cdf76c6bedb511cb6d7046f2802dea3704aa [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 Laurent9d91ad52009-07-17 12:17:14 -0700139 mRecordThreads.clear();
140 mPlaybackThreads.clear();
The Android Open Source Project27629322009-01-09 17:51:23 -0800141}
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800142
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700143
The Android Open Source Projectbcef13b2009-03-11 12:11:56 -0700144
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700145status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
146{
147 const size_t SIZE = 256;
148 char buffer[SIZE];
149 String8 result;
150
151 result.append("Clients:\n");
152 for (size_t i = 0; i < mClients.size(); ++i) {
153 wp<Client> wClient = mClients.valueAt(i);
154 if (wClient != 0) {
155 sp<Client> client = wClient.promote();
156 if (client != 0) {
157 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
158 result.append(buffer);
159 }
160 }
161 }
162 write(fd, result.string(), result.size());
163 return NO_ERROR;
164}
165
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700166
167status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
168{
169 const size_t SIZE = 256;
170 char buffer[SIZE];
171 String8 result;
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700172 int hardwareStatus = mHardwareStatus;
Eric Laurent9d91ad52009-07-17 12:17:14 -0700173
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700174 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700175 result.append(buffer);
176 write(fd, result.string(), result.size());
177 return NO_ERROR;
178}
179
180status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
181{
182 const size_t SIZE = 256;
183 char buffer[SIZE];
184 String8 result;
185 snprintf(buffer, SIZE, "Permission Denial: "
186 "can't dump AudioFlinger from pid=%d, uid=%d\n",
187 IPCThreadState::self()->getCallingPid(),
188 IPCThreadState::self()->getCallingUid());
189 result.append(buffer);
190 write(fd, result.string(), result.size());
191 return NO_ERROR;
192}
193
The Android Open Source Project4f68be12009-03-18 17:39:46 -0700194static bool tryLock(Mutex& mutex)
195{
196 bool locked = false;
197 for (int i = 0; i < kDumpLockRetries; ++i) {
198 if (mutex.tryLock() == NO_ERROR) {
199 locked = true;
200 break;
201 }
202 usleep(kDumpLockSleep);
203 }
204 return locked;
205}
206
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700207status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
208{
209 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
210 dumpPermissionDenial(fd, args);
211 } else {
The Android Open Source Project4f68be12009-03-18 17:39:46 -0700212 // get state of hardware lock
213 bool hardwareLocked = tryLock(mHardwareLock);
214 if (!hardwareLocked) {
215 String8 result(kHardwareLockedString);
216 write(fd, result.string(), result.size());
217 } else {
218 mHardwareLock.unlock();
219 }
220
221 bool locked = tryLock(mLock);
222
223 // failed to lock - AudioFlinger is probably deadlocked
224 if (!locked) {
225 String8 result(kDeadlockedString);
226 write(fd, result.string(), result.size());
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700227 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700228
229 dumpClients(fd, args);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700230 dumpInternals(fd, args);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800231
Eric Laurent9d91ad52009-07-17 12:17:14 -0700232 // dump playback threads
233 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700234 mPlaybackThreads.valueAt(i)->dump(fd, args);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700235 }
236
237 // dump record threads
Eric Laurentfd558a92009-07-23 13:35:01 -0700238 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700239 mRecordThreads.valueAt(i)->dump(fd, args);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700240 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800241
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700242 if (mAudioHardware) {
243 mAudioHardware->dumpState(fd, args);
244 }
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700245 if (locked) mLock.unlock();
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700246 }
247 return NO_ERROR;
248}
249
Eric Laurent9d91ad52009-07-17 12:17:14 -0700250
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700251// IAudioFlinger interface
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800252
253
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700254sp<IAudioTrack> AudioFlinger::createTrack(
255 pid_t pid,
256 int streamType,
257 uint32_t sampleRate,
258 int format,
259 int channelCount,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800260 int frameCount,
261 uint32_t flags,
262 const sp<IMemory>& sharedBuffer,
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700263 int output,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800264 status_t *status)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700265{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700266 sp<PlaybackThread::Track> track;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700267 sp<TrackHandle> trackHandle;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700268 sp<Client> client;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800269 wp<Client> wclient;
270 status_t lStatus;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700271
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800272 if (streamType >= AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800273 LOGE("invalid stream type");
274 lStatus = BAD_VALUE;
275 goto Exit;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700276 }
277
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800278 {
279 Mutex::Autolock _l(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700280 PlaybackThread *thread = checkPlaybackThread_l(output);
281 if (thread == NULL) {
282 LOGE("unknown output thread");
283 lStatus = BAD_VALUE;
284 goto Exit;
285 }
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800286
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800287 wclient = mClients.valueFor(pid);
288
289 if (wclient != NULL) {
290 client = wclient.promote();
291 } else {
292 client = new Client(this, pid);
293 mClients.add(pid, client);
294 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700295 track = thread->createTrack_l(client, streamType, sampleRate, format,
296 channelCount, frameCount, sharedBuffer, &lStatus);
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700297 }
298 if (lStatus == NO_ERROR) {
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800299 trackHandle = new TrackHandle(track);
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700300 } else {
301 track.clear();
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800302 }
303
304Exit:
305 if(status) {
306 *status = lStatus;
307 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700308 return trackHandle;
309}
310
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700311uint32_t AudioFlinger::sampleRate(int output) const
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700312{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700313 Mutex::Autolock _l(mLock);
314 PlaybackThread *thread = checkPlaybackThread_l(output);
315 if (thread == NULL) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700316 LOGW("sampleRate() unknown thread %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700317 return 0;
318 }
319 return thread->sampleRate();
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700320}
321
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700322int AudioFlinger::channelCount(int output) const
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700323{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700324 Mutex::Autolock _l(mLock);
325 PlaybackThread *thread = checkPlaybackThread_l(output);
326 if (thread == NULL) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700327 LOGW("channelCount() unknown thread %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700328 return 0;
329 }
330 return thread->channelCount();
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700331}
332
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700333int AudioFlinger::format(int output) const
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700334{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700335 Mutex::Autolock _l(mLock);
336 PlaybackThread *thread = checkPlaybackThread_l(output);
337 if (thread == NULL) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700338 LOGW("format() unknown thread %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700339 return 0;
340 }
341 return thread->format();
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700342}
343
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700344size_t AudioFlinger::frameCount(int output) const
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700345{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700346 Mutex::Autolock _l(mLock);
347 PlaybackThread *thread = checkPlaybackThread_l(output);
348 if (thread == NULL) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700349 LOGW("frameCount() unknown thread %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700350 return 0;
351 }
352 return thread->frameCount();
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700353}
354
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700355uint32_t AudioFlinger::latency(int output) const
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800356{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700357 Mutex::Autolock _l(mLock);
358 PlaybackThread *thread = checkPlaybackThread_l(output);
359 if (thread == NULL) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700360 LOGW("latency() unknown thread %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700361 return 0;
362 }
363 return thread->latency();
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800364}
365
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700366status_t AudioFlinger::setMasterVolume(float value)
367{
368 // check calling permissions
369 if (!settingsAllowed()) {
370 return PERMISSION_DENIED;
371 }
372
373 // when hw supports master volume, don't scale in sw mixer
374 AutoMutex lock(mHardwareLock);
375 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
376 if (mAudioHardware->setMasterVolume(value) == NO_ERROR) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800377 value = 1.0f;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700378 }
379 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent9d91ad52009-07-17 12:17:14 -0700380
381 mMasterVolume = value;
382 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700383 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700384
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700385 return NO_ERROR;
386}
387
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700388status_t AudioFlinger::setMode(int mode)
389{
390 // check calling permissions
391 if (!settingsAllowed()) {
392 return PERMISSION_DENIED;
393 }
394 if ((mode < 0) || (mode >= AudioSystem::NUM_MODES)) {
395 LOGW("Illegal value: setMode(%d)", mode);
396 return BAD_VALUE;
397 }
398
399 AutoMutex lock(mHardwareLock);
400 mHardwareStatus = AUDIO_HW_SET_MODE;
401 status_t ret = mAudioHardware->setMode(mode);
402 mHardwareStatus = AUDIO_HW_IDLE;
403 return ret;
404}
405
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700406status_t AudioFlinger::setMicMute(bool state)
407{
408 // check calling permissions
409 if (!settingsAllowed()) {
410 return PERMISSION_DENIED;
411 }
412
413 AutoMutex lock(mHardwareLock);
414 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
415 status_t ret = mAudioHardware->setMicMute(state);
416 mHardwareStatus = AUDIO_HW_IDLE;
417 return ret;
418}
419
420bool AudioFlinger::getMicMute() const
421{
422 bool state = AudioSystem::MODE_INVALID;
423 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
424 mAudioHardware->getMicMute(&state);
425 mHardwareStatus = AUDIO_HW_IDLE;
426 return state;
427}
428
429status_t AudioFlinger::setMasterMute(bool muted)
430{
431 // check calling permissions
432 if (!settingsAllowed()) {
433 return PERMISSION_DENIED;
434 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700435
436 mMasterMute = muted;
437 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700438 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700439
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700440 return NO_ERROR;
441}
442
443float AudioFlinger::masterVolume() const
444{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700445 return mMasterVolume;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700446}
447
448bool AudioFlinger::masterMute() const
449{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700450 return mMasterMute;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700451}
452
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700453status_t AudioFlinger::setStreamVolume(int stream, float value, int output)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700454{
455 // check calling permissions
456 if (!settingsAllowed()) {
457 return PERMISSION_DENIED;
458 }
459
Eric Laurent9d91ad52009-07-17 12:17:14 -0700460 if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700461 return BAD_VALUE;
462 }
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800463
Eric Laurent9d91ad52009-07-17 12:17:14 -0700464 AutoMutex lock(mLock);
465 PlaybackThread *thread = NULL;
466 if (output) {
467 thread = checkPlaybackThread_l(output);
468 if (thread == NULL) {
469 return BAD_VALUE;
470 }
471 }
472
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700473 status_t ret = NO_ERROR;
Eric Laurent9d91ad52009-07-17 12:17:14 -0700474
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800475 if (stream == AudioSystem::VOICE_CALL ||
476 stream == AudioSystem::BLUETOOTH_SCO) {
Eric Laurent4dd495b2009-04-21 07:56:33 -0700477 float hwValue;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800478 if (stream == AudioSystem::VOICE_CALL) {
Jean-Baptiste Queru732ca392009-03-18 11:33:14 -0700479 hwValue = (float)AudioSystem::logToLinear(value)/100.0f;
Eric Laurent4dd495b2009-04-21 07:56:33 -0700480 // offset value to reflect actual hardware volume that never reaches 0
481 // 1% corresponds roughly to first step in VOICE_CALL stream volume setting (see AudioService.java)
482 value = 0.01 + 0.99 * value;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800483 } else { // (type == AudioSystem::BLUETOOTH_SCO)
Jean-Baptiste Queru732ca392009-03-18 11:33:14 -0700484 hwValue = 1.0f;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800485 }
486
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700487 AutoMutex lock(mHardwareLock);
488 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
Jean-Baptiste Queru732ca392009-03-18 11:33:14 -0700489 ret = mAudioHardware->setVoiceVolume(hwValue);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700490 mHardwareStatus = AUDIO_HW_IDLE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800491
Eric Laurent9d91ad52009-07-17 12:17:14 -0700492 }
493
494 mStreamTypes[stream].volume = value;
495
496 if (thread == NULL) {
497 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700498 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700499
500 } else {
501 thread->setStreamVolume(stream, value);
502 }
Eric Laurent4dd495b2009-04-21 07:56:33 -0700503
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700504 return ret;
505}
506
507status_t AudioFlinger::setStreamMute(int stream, bool muted)
508{
509 // check calling permissions
510 if (!settingsAllowed()) {
511 return PERMISSION_DENIED;
512 }
513
Eric Laurent9d91ad52009-07-17 12:17:14 -0700514 if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES ||
Eric Laurentb1596ee2009-03-26 01:57:59 -0700515 uint32_t(stream) == AudioSystem::ENFORCED_AUDIBLE) {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700516 return BAD_VALUE;
517 }
The Android Open Source Project4f68be12009-03-18 17:39:46 -0700518
Eric Laurent9d91ad52009-07-17 12:17:14 -0700519 mStreamTypes[stream].mute = muted;
520 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700521 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800522
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700523 return NO_ERROR;
524}
525
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700526float AudioFlinger::streamVolume(int stream, int output) const
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700527{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700528 if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700529 return 0.0f;
530 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700531
532 AutoMutex lock(mLock);
533 float volume;
534 if (output) {
535 PlaybackThread *thread = checkPlaybackThread_l(output);
536 if (thread == NULL) {
537 return 0.0f;
538 }
539 volume = thread->streamVolume(stream);
540 } else {
541 volume = mStreamTypes[stream].volume;
542 }
543
Eric Laurent4dd495b2009-04-21 07:56:33 -0700544 // remove correction applied by setStreamVolume()
Jean-Baptiste Queru732ca392009-03-18 11:33:14 -0700545 if (stream == AudioSystem::VOICE_CALL) {
Eric Laurent4dd495b2009-04-21 07:56:33 -0700546 volume = (volume - 0.01) / 0.99 ;
James E. Blair6015dfc2009-01-17 13:30:20 -0800547 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700548
Eric Laurent4dd495b2009-04-21 07:56:33 -0700549 return volume;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700550}
551
552bool AudioFlinger::streamMute(int stream) const
553{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700554 if (stream < 0 || stream >= (int)AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700555 return true;
556 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700557
558 return mStreamTypes[stream].mute;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700559}
560
561bool AudioFlinger::isMusicActive() const
562{
Eric Laurentb025ca02009-07-09 03:20:57 -0700563 Mutex::Autolock _l(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700564 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700565 if (mPlaybackThreads.valueAt(i)->isMusicActive()) {
Eric Laurent9d91ad52009-07-17 12:17:14 -0700566 return true;
567 }
568 }
569 return false;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700570}
571
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700572status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700573{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700574 status_t result;
575
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700576 LOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
Eric Laurent9d91ad52009-07-17 12:17:14 -0700577 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
578 // check calling permissions
579 if (!settingsAllowed()) {
580 return PERMISSION_DENIED;
The Android Open Source Project8a7a6752009-01-15 16:12:10 -0800581 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700582
583 // ioHandle == 0 means the parameters are global to the audio hardware interface
584 if (ioHandle == 0) {
585 AutoMutex lock(mHardwareLock);
586 mHardwareStatus = AUDIO_SET_PARAMETER;
587 result = mAudioHardware->setParameters(keyValuePairs);
588 mHardwareStatus = AUDIO_HW_IDLE;
589 return result;
590 }
591
592 // Check if parameters are for an output
593 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
594 if (playbackThread != NULL) {
595 return playbackThread->setParameters(keyValuePairs);
596 }
597
598 // Check if parameters are for an input
599 RecordThread *recordThread = checkRecordThread_l(ioHandle);
600 if (recordThread != NULL) {
601 return recordThread->setParameters(keyValuePairs);
602 }
603
604 return BAD_VALUE;
605}
606
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700607String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
Eric Laurent9d91ad52009-07-17 12:17:14 -0700608{
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700609// LOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
Eric Laurent9d91ad52009-07-17 12:17:14 -0700610// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
611
612 if (ioHandle == 0) {
613 return mAudioHardware->getParameters(keys);
614 }
615 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
616 if (playbackThread != NULL) {
617 return playbackThread->getParameters(keys);
618 }
619 RecordThread *recordThread = checkRecordThread_l(ioHandle);
620 if (recordThread != NULL) {
621 return recordThread->getParameters(keys);
622 }
623 return String8("");
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700624}
625
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800626size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
627{
628 return mAudioHardware->getInputBufferSize(sampleRate, format, channelCount);
629}
630
631void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
632{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700633
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800634 LOGV("registerClient() %p, tid %d, calling tid %d", client.get(), gettid(), IPCThreadState::self()->getCallingPid());
635 Mutex::Autolock _l(mLock);
636
637 sp<IBinder> binder = client->asBinder();
638 if (mNotificationClients.indexOf(binder) < 0) {
639 LOGV("Adding notification client %p", binder.get());
640 binder->linkToDeath(this);
641 mNotificationClients.add(binder);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700642 }
643
644 // the config change is always sent from playback or record threads to avoid deadlock
645 // with AudioSystem::gLock
646 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700647 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700648 }
649
650 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700651 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800652 }
653}
654
655void AudioFlinger::binderDied(const wp<IBinder>& who) {
Eric Laurent9d91ad52009-07-17 12:17:14 -0700656
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800657 LOGV("binderDied() %p, tid %d, calling tid %d", who.unsafe_get(), gettid(), IPCThreadState::self()->getCallingPid());
658 Mutex::Autolock _l(mLock);
659
660 IBinder *binder = who.unsafe_get();
661
662 if (binder != NULL) {
663 int index = mNotificationClients.indexOf(binder);
664 if (index >= 0) {
665 LOGV("Removing notification client %p", binder);
666 mNotificationClients.removeAt(index);
667 }
668 }
669}
670
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700671void AudioFlinger::audioConfigChanged(int event, const sp<ThreadBase>& thread, void *param2) {
Eric Laurent9d91ad52009-07-17 12:17:14 -0700672 Mutex::Autolock _l(mLock);
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700673 int ioHandle = 0;
674
675 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
676 if (mPlaybackThreads.valueAt(i) == thread) {
677 ioHandle = mPlaybackThreads.keyAt(i);
678 break;
679 }
680 }
681 if (ioHandle == 0) {
682 for (size_t i = 0; i < mRecordThreads.size(); i++) {
683 if (mRecordThreads.valueAt(i) == thread) {
684 ioHandle = mRecordThreads.keyAt(i);
685 break;
686 }
687 }
688 }
689
690 if (ioHandle != 0) {
691 size_t size = mNotificationClients.size();
692 for (size_t i = 0; i < size; i++) {
693 sp<IBinder> binder = mNotificationClients.itemAt(i);
694 LOGV("audioConfigChanged() Notifying change to client %p", binder.get());
695 sp<IAudioFlingerClient> client = interface_cast<IAudioFlingerClient> (binder);
696 client->ioConfigChanged(event, ioHandle, param2);
697 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700698 }
699}
700
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700701void AudioFlinger::removeClient(pid_t pid)
702{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800703 LOGV("removeClient() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700704 Mutex::Autolock _l(mLock);
705 mClients.removeItem(pid);
706}
707
Eric Laurent9d91ad52009-07-17 12:17:14 -0700708// ----------------------------------------------------------------------------
709
710AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger)
711 : Thread(false),
712 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
Eric Laurent3464c012009-08-04 09:45:33 -0700713 mFormat(0), mFrameSize(1), mStandby(false)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700714{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800715}
716
Eric Laurent9d91ad52009-07-17 12:17:14 -0700717AudioFlinger::ThreadBase::~ThreadBase()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800718{
Eric Laurent3464c012009-08-04 09:45:33 -0700719 mParamCond.broadcast();
720 mNewParameters.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800721}
722
Eric Laurent9d91ad52009-07-17 12:17:14 -0700723void AudioFlinger::ThreadBase::exit()
The Android Open Source Projectbcef13b2009-03-11 12:11:56 -0700724{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700725 // keep a strong ref on ourself so that we want get
726 // destroyed in the middle of requestExitAndWait()
727 sp <ThreadBase> strongMe = this;
728
729 LOGV("ThreadBase::exit");
730 {
731 AutoMutex lock(&mLock);
732 requestExit();
733 mWaitWorkCV.signal();
The Android Open Source Projectbcef13b2009-03-11 12:11:56 -0700734 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700735 requestExitAndWait();
The Android Open Source Projectbcef13b2009-03-11 12:11:56 -0700736}
Eric Laurent9d91ad52009-07-17 12:17:14 -0700737
738uint32_t AudioFlinger::ThreadBase::sampleRate() const
739{
740 return mSampleRate;
741}
742
743int AudioFlinger::ThreadBase::channelCount() const
744{
745 return mChannelCount;
746}
747
748int AudioFlinger::ThreadBase::format() const
749{
750 return mFormat;
751}
752
753size_t AudioFlinger::ThreadBase::frameCount() const
754{
755 return mFrameCount;
756}
757
758status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
759{
Eric Laurent3464c012009-08-04 09:45:33 -0700760 status_t status;
Eric Laurent9d91ad52009-07-17 12:17:14 -0700761
Eric Laurent3464c012009-08-04 09:45:33 -0700762 LOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Eric Laurent9d91ad52009-07-17 12:17:14 -0700763 Mutex::Autolock _l(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700764
Eric Laurent3464c012009-08-04 09:45:33 -0700765 mNewParameters.add(keyValuePairs);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700766 mWaitWorkCV.signal();
767 mParamCond.wait(mLock);
Eric Laurent3464c012009-08-04 09:45:33 -0700768 status = mParamStatus;
769 mWaitWorkCV.signal();
770 return status;
Eric Laurent9d91ad52009-07-17 12:17:14 -0700771}
772
773void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
774{
775 Mutex::Autolock _l(mLock);
Eric Laurent3464c012009-08-04 09:45:33 -0700776 sendConfigEvent_l(event, param);
777}
778
779// sendConfigEvent_l() must be called with ThreadBase::mLock held
780void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
781{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700782 ConfigEvent *configEvent = new ConfigEvent();
783 configEvent->mEvent = event;
784 configEvent->mParam = param;
785 mConfigEvents.add(configEvent);
786 LOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
787 mWaitWorkCV.signal();
788}
789
790void AudioFlinger::ThreadBase::processConfigEvents()
791{
792 mLock.lock();
793 while(!mConfigEvents.isEmpty()) {
794 LOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
795 ConfigEvent *configEvent = mConfigEvents[0];
796 mConfigEvents.removeAt(0);
797 // release mLock because audioConfigChanged() will call
798 // Audioflinger::audioConfigChanged() which locks AudioFlinger mLock thus creating
799 // potential cross deadlock between AudioFlinger::mLock and mLock
800 mLock.unlock();
801 audioConfigChanged(configEvent->mEvent, configEvent->mParam);
802 delete configEvent;
803 mLock.lock();
804 }
805 mLock.unlock();
806}
807
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800808
809// ----------------------------------------------------------------------------
810
Eric Laurent9d91ad52009-07-17 12:17:14 -0700811AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output)
812 : ThreadBase(audioFlinger),
Eric Laurent9395d9b2009-07-23 13:17:39 -0700813 mMixBuffer(0), mSuspended(false), mBytesWritten(0), mOutput(output),
814 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800815{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700816 readOutputParameters();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800817
Eric Laurent9d91ad52009-07-17 12:17:14 -0700818 mMasterVolume = mAudioFlinger->masterVolume();
819 mMasterMute = mAudioFlinger->masterMute();
820
821 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
822 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
823 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800824 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700825 // notify client processes that a new input has been opened
826 sendConfigEvent(AudioSystem::OUTPUT_OPENED);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800827}
828
Eric Laurent9d91ad52009-07-17 12:17:14 -0700829AudioFlinger::PlaybackThread::~PlaybackThread()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800830{
831 delete [] mMixBuffer;
Eric Laurent9d91ad52009-07-17 12:17:14 -0700832 if (mType != DUPLICATING) {
833 mAudioFlinger->mAudioHardware->closeOutputStream(mOutput);
834 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800835}
836
Eric Laurent9d91ad52009-07-17 12:17:14 -0700837status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800838{
839 dumpInternals(fd, args);
840 dumpTracks(fd, args);
841 return NO_ERROR;
842}
843
Eric Laurent9d91ad52009-07-17 12:17:14 -0700844status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800845{
846 const size_t SIZE = 256;
847 char buffer[SIZE];
848 String8 result;
849
Eric Laurent9d91ad52009-07-17 12:17:14 -0700850 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800851 result.append(buffer);
852 result.append(" Name Clien Typ Fmt Chn Buf S M F SRate LeftV RighV Serv User\n");
853 for (size_t i = 0; i < mTracks.size(); ++i) {
Eric Laurentc828f6a2009-03-31 14:34:35 -0700854 sp<Track> track = mTracks[i];
855 if (track != 0) {
856 track->dump(buffer, SIZE);
857 result.append(buffer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800858 }
859 }
860
Eric Laurent9d91ad52009-07-17 12:17:14 -0700861 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800862 result.append(buffer);
863 result.append(" Name Clien Typ Fmt Chn Buf S M F SRate LeftV RighV Serv User\n");
864 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Eric Laurentc828f6a2009-03-31 14:34:35 -0700865 wp<Track> wTrack = mActiveTracks[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800866 if (wTrack != 0) {
867 sp<Track> track = wTrack.promote();
868 if (track != 0) {
869 track->dump(buffer, SIZE);
870 result.append(buffer);
871 }
872 }
873 }
874 write(fd, result.string(), result.size());
875 return NO_ERROR;
876}
877
Eric Laurent9d91ad52009-07-17 12:17:14 -0700878status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800879{
880 const size_t SIZE = 256;
881 char buffer[SIZE];
882 String8 result;
883
Eric Laurent9d91ad52009-07-17 12:17:14 -0700884 snprintf(buffer, SIZE, "Output thread %p internals\n", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800885 result.append(buffer);
886 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
887 result.append(buffer);
888 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
889 result.append(buffer);
890 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
891 result.append(buffer);
892 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
893 result.append(buffer);
894 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
895 result.append(buffer);
896 write(fd, result.string(), result.size());
897 return NO_ERROR;
898}
899
900// Thread virtuals
Eric Laurent9d91ad52009-07-17 12:17:14 -0700901status_t AudioFlinger::PlaybackThread::readyToRun()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800902{
903 if (mSampleRate == 0) {
904 LOGE("No working audio driver found.");
905 return NO_INIT;
906 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700907 LOGI("AudioFlinger's thread %p ready to run", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800908 return NO_ERROR;
909}
910
Eric Laurent9d91ad52009-07-17 12:17:14 -0700911void AudioFlinger::PlaybackThread::onFirstRef()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800912{
913 const size_t SIZE = 256;
914 char buffer[SIZE];
915
Eric Laurent9d91ad52009-07-17 12:17:14 -0700916 snprintf(buffer, SIZE, "Playback Thread %p", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800917
918 run(buffer, ANDROID_PRIORITY_URGENT_AUDIO);
919}
920
Eric Laurent9d91ad52009-07-17 12:17:14 -0700921// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
922sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800923 const sp<AudioFlinger::Client>& client,
924 int streamType,
925 uint32_t sampleRate,
926 int format,
927 int channelCount,
928 int frameCount,
929 const sp<IMemory>& sharedBuffer,
930 status_t *status)
931{
932 sp<Track> track;
933 status_t lStatus;
Eric Laurent9d91ad52009-07-17 12:17:14 -0700934
935 if (mType == DIRECT) {
936 if (sampleRate != mSampleRate || format != mFormat || channelCount != mChannelCount) {
937 LOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelCount %d for output %p",
938 sampleRate, format, channelCount, mOutput);
939 lStatus = BAD_VALUE;
940 goto Exit;
941 }
942 } else {
943 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
944 if (sampleRate > mSampleRate*2) {
945 LOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
946 lStatus = BAD_VALUE;
947 goto Exit;
948 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800949 }
950
Eric Laurent9d91ad52009-07-17 12:17:14 -0700951 if (mOutput == 0) {
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700952 LOGE("Audio driver not initialized.");
953 lStatus = NO_INIT;
954 goto Exit;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800955 }
956
Eric Laurent9d91ad52009-07-17 12:17:14 -0700957 { // scope for mLock
958 Mutex::Autolock _l(mLock);
959 track = new Track(this, client, streamType, sampleRate, format,
960 channelCount, frameCount, sharedBuffer);
961 if (track->getCblk() == NULL) {
962 lStatus = NO_MEMORY;
963 goto Exit;
964 }
965 mTracks.add(track);
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700966 }
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700967 lStatus = NO_ERROR;
968
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800969Exit:
970 if(status) {
971 *status = lStatus;
972 }
973 return track;
974}
975
Eric Laurent9d91ad52009-07-17 12:17:14 -0700976uint32_t AudioFlinger::PlaybackThread::latency() const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800977{
978 if (mOutput) {
979 return mOutput->latency();
980 }
981 else {
982 return 0;
983 }
984}
985
Eric Laurent9d91ad52009-07-17 12:17:14 -0700986status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800987{
988 mMasterVolume = value;
989 return NO_ERROR;
990}
991
Eric Laurent9d91ad52009-07-17 12:17:14 -0700992status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800993{
994 mMasterMute = muted;
995 return NO_ERROR;
996}
997
Eric Laurent9d91ad52009-07-17 12:17:14 -0700998float AudioFlinger::PlaybackThread::masterVolume() const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800999{
1000 return mMasterVolume;
1001}
1002
Eric Laurent9d91ad52009-07-17 12:17:14 -07001003bool AudioFlinger::PlaybackThread::masterMute() const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001004{
1005 return mMasterMute;
1006}
1007
Eric Laurent9d91ad52009-07-17 12:17:14 -07001008status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001009{
1010 mStreamTypes[stream].volume = value;
1011 return NO_ERROR;
1012}
1013
Eric Laurent9d91ad52009-07-17 12:17:14 -07001014status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001015{
1016 mStreamTypes[stream].mute = muted;
1017 return NO_ERROR;
1018}
1019
Eric Laurent9d91ad52009-07-17 12:17:14 -07001020float AudioFlinger::PlaybackThread::streamVolume(int stream) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001021{
1022 return mStreamTypes[stream].volume;
1023}
1024
Eric Laurent9d91ad52009-07-17 12:17:14 -07001025bool AudioFlinger::PlaybackThread::streamMute(int stream) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001026{
1027 return mStreamTypes[stream].mute;
1028}
1029
Eric Laurent9d91ad52009-07-17 12:17:14 -07001030bool AudioFlinger::PlaybackThread::isMusicActive() const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001031{
Eric Laurent9d91ad52009-07-17 12:17:14 -07001032 Mutex::Autolock _l(mLock);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001033 size_t count = mActiveTracks.size();
1034 for (size_t i = 0 ; i < count ; ++i) {
1035 sp<Track> t = mActiveTracks[i].promote();
1036 if (t == 0) continue;
1037 Track* const track = t.get();
Eric Laurent9395d9b2009-07-23 13:17:39 -07001038 if (t->type() == AudioSystem::MUSIC)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001039 return true;
1040 }
1041 return false;
1042}
1043
Eric Laurent9d91ad52009-07-17 12:17:14 -07001044// addTrack_l() must be called with ThreadBase::mLock held
1045status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001046{
1047 status_t status = ALREADY_EXISTS;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001048
1049 // here the track could be either new, or restarted
1050 // in both cases "unstop" the track
1051 if (track->isPaused()) {
1052 track->mState = TrackBase::RESUMING;
1053 LOGV("PAUSED => RESUMING (%d)", track->name());
1054 } else {
1055 track->mState = TrackBase::ACTIVE;
1056 LOGV("? => ACTIVE (%d)", track->name());
1057 }
1058 // set retry count for buffer fill
1059 track->mRetryCount = kMaxTrackStartupRetries;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001060 if (mActiveTracks.indexOf(track) < 0) {
1061 // the track is newly added, make sure it fills up all its
1062 // buffers before playing. This is to ensure the client will
1063 // effectively get the latency it requested.
1064 track->mFillingUpStatus = Track::FS_FILLING;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08001065 track->mResetDone = false;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001066 mActiveTracks.add(track);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001067 status = NO_ERROR;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001068 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07001069
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001070 LOGV("mWaitWorkCV.broadcast");
Eric Laurent9d91ad52009-07-17 12:17:14 -07001071 mWaitWorkCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001072
1073 return status;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001074}
1075
Eric Laurent9d91ad52009-07-17 12:17:14 -07001076// destroyTrack_l() must be called with ThreadBase::mLock held
1077void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001078{
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001079 track->mState = TrackBase::TERMINATED;
1080 if (mActiveTracks.indexOf(track) < 0) {
1081 LOGV("remove track (%d) and delete from mixer", track->name());
1082 mTracks.remove(track);
The Android Open Source Project22f8def2009-03-09 11:52:12 -07001083 deleteTrackName_l(track->name());
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001084 }
1085}
1086
Eric Laurent9d91ad52009-07-17 12:17:14 -07001087String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
The Android Open Source Projecte41dd752009-01-22 00:13:42 -08001088{
Eric Laurent9d91ad52009-07-17 12:17:14 -07001089 return mOutput->getParameters(keys);
1090}
The Android Open Source Projecte41dd752009-01-22 00:13:42 -08001091
Eric Laurent9d91ad52009-07-17 12:17:14 -07001092void AudioFlinger::PlaybackThread::audioConfigChanged(int event, int param) {
1093 AudioSystem::OutputDescriptor desc;
1094 void *param2 = 0;
1095
1096 LOGV("PlaybackThread::audioConfigChanged, thread %p, event %d, param %d", this, event, param);
1097
1098 switch (event) {
1099 case AudioSystem::OUTPUT_OPENED:
1100 case AudioSystem::OUTPUT_CONFIG_CHANGED:
1101 desc.channels = mChannelCount;
1102 desc.samplingRate = mSampleRate;
1103 desc.format = mFormat;
1104 desc.frameCount = mFrameCount;
1105 desc.latency = latency();
1106 param2 = &desc;
1107 break;
1108
1109 case AudioSystem::STREAM_CONFIG_CHANGED:
1110 param2 = &param;
1111 case AudioSystem::OUTPUT_CLOSED:
1112 default:
1113 break;
1114 }
1115 mAudioFlinger->audioConfigChanged(event, this, param2);
1116}
1117
1118void AudioFlinger::PlaybackThread::readOutputParameters()
1119{
1120 mSampleRate = mOutput->sampleRate();
1121 mChannelCount = AudioSystem::popCount(mOutput->channels());
1122
1123 mFormat = mOutput->format();
1124 mFrameSize = mOutput->frameSize();
1125 mFrameCount = mOutput->bufferSize() / mFrameSize;
1126
1127 mMinBytesToWrite = (mOutput->latency() * mSampleRate * mFrameSize) / 1000;
1128 // FIXME - Current mixer implementation only supports stereo output: Always
1129 // Allocate a stereo buffer even if HW output is mono.
1130 if (mMixBuffer != NULL) delete mMixBuffer;
1131 mMixBuffer = new int16_t[mFrameCount * 2];
1132 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1133}
1134
1135// ----------------------------------------------------------------------------
1136
1137AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output)
1138 : PlaybackThread(audioFlinger, output),
1139 mAudioMixer(0)
1140{
1141 mType = PlaybackThread::MIXER;
1142 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1143
1144 // FIXME - Current mixer implementation only supports stereo output
1145 if (mChannelCount == 1) {
1146 LOGE("Invalid audio hardware channel count");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001147 }
The Android Open Source Projecte41dd752009-01-22 00:13:42 -08001148}
1149
Eric Laurent9d91ad52009-07-17 12:17:14 -07001150AudioFlinger::MixerThread::~MixerThread()
The Android Open Source Projecte41dd752009-01-22 00:13:42 -08001151{
Eric Laurent9d91ad52009-07-17 12:17:14 -07001152 delete mAudioMixer;
1153}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001154
Eric Laurent9d91ad52009-07-17 12:17:14 -07001155bool AudioFlinger::MixerThread::threadLoop()
1156{
1157 unsigned long sleepTime = kBufferRecoveryInUsecs;
1158 int16_t* curBuf = mMixBuffer;
1159 Vector< sp<Track> > tracksToRemove;
1160 size_t enabledTracks = 0;
1161 nsecs_t standbyTime = systemTime();
1162 size_t mixBufferSize = mFrameCount * mFrameSize;
1163 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 2;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001164
Eric Laurent9d91ad52009-07-17 12:17:14 -07001165 while (!exitPending())
1166 {
1167 processConfigEvents();
1168
1169 enabledTracks = 0;
1170 { // scope for mLock
1171
1172 Mutex::Autolock _l(mLock);
1173
1174 if (checkForNewParameters_l()) {
1175 mixBufferSize = mFrameCount * mFrameSize;
1176 maxPeriod = seconds(mFrameCount) / mSampleRate * 2;
1177 }
1178
1179 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1180
1181 // put audio hardware into standby after short delay
1182 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1183 mSuspended) {
1184 if (!mStandby) {
1185 LOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
1186 mOutput->standby();
1187 mStandby = true;
1188 mBytesWritten = 0;
1189 }
1190
1191 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1192 // we're about to wait, flush the binder command buffer
1193 IPCThreadState::self()->flushCommands();
1194
1195 if (exitPending()) break;
1196
1197 // wait until we have something to do...
1198 LOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
1199 mWaitWorkCV.wait(mLock);
1200 LOGV("MixerThread %p TID %d waking up\n", this, gettid());
1201
1202 if (mMasterMute == false) {
1203 char value[PROPERTY_VALUE_MAX];
1204 property_get("ro.audio.silent", value, "0");
1205 if (atoi(value)) {
1206 LOGD("Silence is golden");
1207 setMasterMute(true);
1208 }
1209 }
1210
1211 standbyTime = systemTime() + kStandbyTimeInNsecs;
1212 continue;
1213 }
1214 }
1215
1216 enabledTracks = prepareTracks_l(activeTracks, &tracksToRemove);
1217 }
1218
1219 if (LIKELY(enabledTracks)) {
1220 // mix buffers...
1221 mAudioMixer->process(curBuf);
1222
1223 // output audio to hardware
1224 if (mSuspended) {
1225 usleep(kMaxBufferRecoveryInUsecs);
1226 } else {
1227 mLastWriteTime = systemTime();
1228 mInWrite = true;
1229 int bytesWritten = (int)mOutput->write(curBuf, mixBufferSize);
1230 if (bytesWritten > 0) mBytesWritten += bytesWritten;
1231 mNumWrites++;
1232 mInWrite = false;
1233 mStandby = false;
1234 nsecs_t temp = systemTime();
1235 standbyTime = temp + kStandbyTimeInNsecs;
1236 nsecs_t delta = temp - mLastWriteTime;
1237 if (delta > maxPeriod) {
1238 LOGW("write blocked for %llu msecs", ns2ms(delta));
1239 mNumDelayedWrites++;
1240 }
1241 sleepTime = kBufferRecoveryInUsecs;
1242 }
1243 } else {
1244 // There was nothing to mix this round, which means all
1245 // active tracks were late. Sleep a little bit to give
1246 // them another chance. If we're too late, the audio
1247 // hardware will zero-fill for us.
1248 // LOGV("thread %p no buffers - usleep(%lu)", this, sleepTime);
1249 usleep(sleepTime);
1250 if (sleepTime < kMaxBufferRecoveryInUsecs) {
1251 sleepTime += kBufferRecoveryInUsecs;
1252 }
1253 }
1254
1255 // finally let go of all our tracks, without the lock held
1256 // since we can't guarantee the destructors won't acquire that
1257 // same lock.
1258 tracksToRemove.clear();
1259 }
1260
1261 if (!mStandby) {
1262 mOutput->standby();
1263 }
1264 sendConfigEvent(AudioSystem::OUTPUT_CLOSED);
1265 processConfigEvents();
1266
1267 LOGV("MixerThread %p exiting", this);
1268 return false;
1269}
1270
1271// prepareTracks_l() must be called with ThreadBase::mLock held
1272size_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
1273{
1274
1275 size_t enabledTracks = 0;
1276 // find out which tracks need to be processed
1277 size_t count = activeTracks.size();
1278 for (size_t i=0 ; i<count ; i++) {
1279 sp<Track> t = activeTracks[i].promote();
1280 if (t == 0) continue;
1281
1282 Track* const track = t.get();
1283 audio_track_cblk_t* cblk = track->cblk();
1284
1285 // The first time a track is added we wait
1286 // for all its buffers to be filled before processing it
1287 mAudioMixer->setActiveTrack(track->name());
1288 if (cblk->framesReady() && (track->isReady() || track->isStopped()) &&
1289 !track->isPaused())
1290 {
1291 //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
1292
1293 // compute volume for this track
1294 int16_t left, right;
1295 if (track->isMuted() || mMasterMute || track->isPausing() ||
1296 mStreamTypes[track->type()].mute) {
1297 left = right = 0;
1298 if (track->isPausing()) {
1299 track->setPaused();
1300 }
1301 } else {
1302 float typeVolume = mStreamTypes[track->type()].volume;
1303 float v = mMasterVolume * typeVolume;
1304 float v_clamped = v * cblk->volume[0];
1305 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
1306 left = int16_t(v_clamped);
1307 v_clamped = v * cblk->volume[1];
1308 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
1309 right = int16_t(v_clamped);
1310 }
1311
1312 // XXX: these things DON'T need to be done each time
1313 mAudioMixer->setBufferProvider(track);
1314 mAudioMixer->enable(AudioMixer::MIXING);
1315
1316 int param;
1317 if ( track->mFillingUpStatus == Track::FS_FILLED) {
1318 // no ramp for the first volume setting
1319 track->mFillingUpStatus = Track::FS_ACTIVE;
1320 if (track->mState == TrackBase::RESUMING) {
1321 track->mState = TrackBase::ACTIVE;
1322 param = AudioMixer::RAMP_VOLUME;
1323 } else {
1324 param = AudioMixer::VOLUME;
1325 }
1326 } else {
1327 param = AudioMixer::RAMP_VOLUME;
1328 }
1329 mAudioMixer->setParameter(param, AudioMixer::VOLUME0, left);
1330 mAudioMixer->setParameter(param, AudioMixer::VOLUME1, right);
1331 mAudioMixer->setParameter(
1332 AudioMixer::TRACK,
1333 AudioMixer::FORMAT, track->format());
1334 mAudioMixer->setParameter(
1335 AudioMixer::TRACK,
1336 AudioMixer::CHANNEL_COUNT, track->channelCount());
1337 mAudioMixer->setParameter(
1338 AudioMixer::RESAMPLE,
1339 AudioMixer::SAMPLE_RATE,
1340 int(cblk->sampleRate));
1341
1342 // reset retry count
1343 track->mRetryCount = kMaxTrackRetries;
1344 enabledTracks++;
1345 } else {
1346 //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
1347 if (track->isStopped()) {
1348 track->reset();
1349 }
1350 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
1351 // We have consumed all the buffers of this track.
1352 // Remove it from the list of active tracks.
1353 tracksToRemove->add(track);
1354 mAudioMixer->disable(AudioMixer::MIXING);
1355 } else {
1356 // No buffers for this track. Give it a few chances to
1357 // fill a buffer, then remove it from active list.
1358 if (--(track->mRetryCount) <= 0) {
1359 LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
1360 tracksToRemove->add(track);
1361 }
1362 // For tracks using static shared memry buffer, make sure that we have
1363 // written enough data to audio hardware before disabling the track
1364 // NOTE: this condition with arrive before track->mRetryCount <= 0 so we
1365 // don't care about code removing track from active list above.
1366 if ((track->mSharedBuffer == 0) || (mBytesWritten >= mMinBytesToWrite)) {
1367 mAudioMixer->disable(AudioMixer::MIXING);
1368 } else {
1369 enabledTracks++;
1370 }
1371 }
1372 }
1373 }
1374
1375 // remove all the tracks that need to be...
1376 count = tracksToRemove->size();
1377 if (UNLIKELY(count)) {
1378 for (size_t i=0 ; i<count ; i++) {
1379 const sp<Track>& track = tracksToRemove->itemAt(i);
1380 mActiveTracks.remove(track);
1381 if (track->isTerminated()) {
1382 mTracks.remove(track);
1383 deleteTrackName_l(track->mName);
1384 }
1385 }
1386 }
1387
1388 return enabledTracks;
1389}
1390
1391void AudioFlinger::MixerThread::getTracks(
1392 SortedVector < sp<Track> >& tracks,
1393 SortedVector < wp<Track> >& activeTracks,
1394 int streamType)
1395{
1396 LOGV ("MixerThread::getTracks() mixer %p, mTracks.size %d, mActiveTracks.size %d", this, mTracks.size(), mActiveTracks.size());
1397 Mutex::Autolock _l(mLock);
1398 size_t size = mTracks.size();
1399 for (size_t i = 0; i < size; i++) {
1400 sp<Track> t = mTracks[i];
1401 if (t->type() == streamType) {
1402 tracks.add(t);
1403 int j = mActiveTracks.indexOf(t);
1404 if (j >= 0) {
1405 t = mActiveTracks[j].promote();
1406 if (t != NULL) {
1407 activeTracks.add(t);
1408 }
1409 }
1410 }
1411 }
1412
1413 size = activeTracks.size();
1414 for (size_t i = 0; i < size; i++) {
1415 mActiveTracks.remove(activeTracks[i]);
1416 }
1417
1418 size = tracks.size();
1419 for (size_t i = 0; i < size; i++) {
1420 sp<Track> t = tracks[i];
1421 mTracks.remove(t);
1422 deleteTrackName_l(t->name());
1423 }
1424}
1425
1426void AudioFlinger::MixerThread::putTracks(
1427 SortedVector < sp<Track> >& tracks,
1428 SortedVector < wp<Track> >& activeTracks)
1429{
1430 LOGV ("MixerThread::putTracks() mixer %p, tracks.size %d, activeTracks.size %d", this, tracks.size(), activeTracks.size());
1431 Mutex::Autolock _l(mLock);
1432 size_t size = tracks.size();
1433 for (size_t i = 0; i < size ; i++) {
1434 sp<Track> t = tracks[i];
1435 int name = getTrackName_l();
1436
1437 if (name < 0) return;
1438
1439 t->mName = name;
1440 t->mThread = this;
1441 mTracks.add(t);
1442
1443 int j = activeTracks.indexOf(t);
1444 if (j >= 0) {
1445 mActiveTracks.add(t);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001446 }
1447 }
1448}
1449
Eric Laurent9d91ad52009-07-17 12:17:14 -07001450// getTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Project22f8def2009-03-09 11:52:12 -07001451int AudioFlinger::MixerThread::getTrackName_l()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001452{
1453 return mAudioMixer->getTrackName();
1454}
1455
Eric Laurent9d91ad52009-07-17 12:17:14 -07001456// deleteTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Project22f8def2009-03-09 11:52:12 -07001457void AudioFlinger::MixerThread::deleteTrackName_l(int name)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001458{
1459 mAudioMixer->deleteTrackName(name);
1460}
1461
Eric Laurent9d91ad52009-07-17 12:17:14 -07001462// checkForNewParameters_l() must be called with ThreadBase::mLock held
1463bool AudioFlinger::MixerThread::checkForNewParameters_l()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001464{
Eric Laurent9d91ad52009-07-17 12:17:14 -07001465 bool reconfig = false;
1466
Eric Laurent3464c012009-08-04 09:45:33 -07001467 while (!mNewParameters.isEmpty()) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07001468 status_t status = NO_ERROR;
Eric Laurent3464c012009-08-04 09:45:33 -07001469 String8 keyValuePair = mNewParameters[0];
1470 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001471 int value;
Eric Laurent3464c012009-08-04 09:45:33 -07001472
1473 mNewParameters.removeAt(0);
1474
Eric Laurent9d91ad52009-07-17 12:17:14 -07001475 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
1476 reconfig = true;
1477 }
1478 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
1479 if (value != AudioSystem::PCM_16_BIT) {
1480 status = BAD_VALUE;
1481 } else {
1482 reconfig = true;
1483 }
1484 }
1485 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
1486 if (value != AudioSystem::CHANNEL_OUT_STEREO) {
1487 status = BAD_VALUE;
1488 } else {
1489 reconfig = true;
1490 }
1491 }
1492 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
1493 // do not accept frame count changes if tracks are open as the track buffer
1494 // size depends on frame count and correct behavior would not be garantied
1495 // if frame count is changed after track creation
1496 if (!mTracks.isEmpty()) {
1497 status = INVALID_OPERATION;
1498 } else {
1499 reconfig = true;
1500 }
1501 }
1502 if (status == NO_ERROR) {
Eric Laurent3464c012009-08-04 09:45:33 -07001503 status = mOutput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001504 if (!mStandby && status == INVALID_OPERATION) {
1505 mOutput->standby();
1506 mStandby = true;
1507 mBytesWritten = 0;
Eric Laurent3464c012009-08-04 09:45:33 -07001508 status = mOutput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001509 }
1510 if (status == NO_ERROR && reconfig) {
1511 delete mAudioMixer;
1512 readOutputParameters();
1513 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1514 for (size_t i = 0; i < mTracks.size() ; i++) {
1515 int name = getTrackName_l();
1516 if (name < 0) break;
1517 mTracks[i]->mName = name;
1518 }
Eric Laurent3464c012009-08-04 09:45:33 -07001519 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001520 }
1521 }
1522 mParamStatus = status;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001523 mParamCond.signal();
Eric Laurent3464c012009-08-04 09:45:33 -07001524 mWaitWorkCV.wait(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001525 }
1526 return reconfig;
1527}
1528
1529status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
1530{
1531 const size_t SIZE = 256;
1532 char buffer[SIZE];
1533 String8 result;
1534
1535 PlaybackThread::dumpInternals(fd, args);
1536
1537 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
1538 result.append(buffer);
1539 write(fd, result.string(), result.size());
1540 return NO_ERROR;
1541}
1542
1543// ----------------------------------------------------------------------------
1544AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output)
1545 : PlaybackThread(audioFlinger, output),
1546 mLeftVolume (1.0), mRightVolume(1.0)
1547{
1548 mType = PlaybackThread::DIRECT;
1549}
1550
1551AudioFlinger::DirectOutputThread::~DirectOutputThread()
1552{
1553}
1554
1555
1556bool AudioFlinger::DirectOutputThread::threadLoop()
1557{
1558 unsigned long sleepTime = kBufferRecoveryInUsecs;
1559 sp<Track> trackToRemove;
1560 sp<Track> activeTrack;
1561 nsecs_t standbyTime = systemTime();
1562 int8_t *curBuf;
1563 size_t mixBufferSize = mFrameCount*mFrameSize;
1564
1565 while (!exitPending())
1566 {
1567 processConfigEvents();
1568
1569 { // scope for the mLock
1570
1571 Mutex::Autolock _l(mLock);
1572
1573 if (checkForNewParameters_l()) {
1574 mixBufferSize = mFrameCount*mFrameSize;
1575 }
1576
1577 // put audio hardware into standby after short delay
1578 if UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
1579 mSuspended) {
1580 // wait until we have something to do...
1581 if (!mStandby) {
1582 LOGV("Audio hardware entering standby, mixer %p\n", this);
1583 mOutput->standby();
1584 mStandby = true;
1585 mBytesWritten = 0;
1586 }
1587
1588 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
1589 // we're about to wait, flush the binder command buffer
1590 IPCThreadState::self()->flushCommands();
1591
1592 if (exitPending()) break;
1593
1594 LOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
1595 mWaitWorkCV.wait(mLock);
1596 LOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
1597
1598 if (mMasterMute == false) {
1599 char value[PROPERTY_VALUE_MAX];
1600 property_get("ro.audio.silent", value, "0");
1601 if (atoi(value)) {
1602 LOGD("Silence is golden");
1603 setMasterMute(true);
1604 }
1605 }
1606
1607 standbyTime = systemTime() + kStandbyTimeInNsecs;
1608 continue;
1609 }
1610 }
1611
1612 // find out which tracks need to be processed
1613 if (mActiveTracks.size() != 0) {
1614 sp<Track> t = mActiveTracks[0].promote();
1615 if (t == 0) continue;
1616
1617 Track* const track = t.get();
1618 audio_track_cblk_t* cblk = track->cblk();
1619
1620 // The first time a track is added we wait
1621 // for all its buffers to be filled before processing it
1622 if (cblk->framesReady() && (track->isReady() || track->isStopped()) &&
1623 !track->isPaused())
1624 {
1625 //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
1626
1627 // compute volume for this track
1628 float left, right;
1629 if (track->isMuted() || mMasterMute || track->isPausing() ||
1630 mStreamTypes[track->type()].mute) {
1631 left = right = 0;
1632 if (track->isPausing()) {
1633 track->setPaused();
1634 }
1635 } else {
1636 float typeVolume = mStreamTypes[track->type()].volume;
1637 float v = mMasterVolume * typeVolume;
1638 float v_clamped = v * cblk->volume[0];
1639 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
1640 left = v_clamped/MAX_GAIN;
1641 v_clamped = v * cblk->volume[1];
1642 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
1643 right = v_clamped/MAX_GAIN;
1644 }
1645
1646 if (left != mLeftVolume || right != mRightVolume) {
1647 mOutput->setVolume(left, right);
1648 left = mLeftVolume;
1649 right = mRightVolume;
1650 }
1651
1652 if (track->mFillingUpStatus == Track::FS_FILLED) {
1653 track->mFillingUpStatus = Track::FS_ACTIVE;
1654 if (track->mState == TrackBase::RESUMING) {
1655 track->mState = TrackBase::ACTIVE;
1656 }
1657 }
1658
1659 // reset retry count
1660 track->mRetryCount = kMaxTrackRetries;
1661 activeTrack = t;
1662 } else {
1663 //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
1664 if (track->isStopped()) {
1665 track->reset();
1666 }
1667 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
1668 // We have consumed all the buffers of this track.
1669 // Remove it from the list of active tracks.
1670 trackToRemove = track;
1671 } else {
1672 // No buffers for this track. Give it a few chances to
1673 // fill a buffer, then remove it from active list.
1674 if (--(track->mRetryCount) <= 0) {
1675 LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
1676 trackToRemove = track;
1677 }
1678
1679 // For tracks using static shared memry buffer, make sure that we have
1680 // written enough data to audio hardware before disabling the track
1681 // NOTE: this condition with arrive before track->mRetryCount <= 0 so we
1682 // don't care about code removing track from active list above.
1683 if ((track->mSharedBuffer != 0) && (mBytesWritten < mMinBytesToWrite)) {
1684 activeTrack = t;
1685 }
1686 }
1687 }
1688 }
1689
1690 // remove all the tracks that need to be...
1691 if (UNLIKELY(trackToRemove != 0)) {
1692 mActiveTracks.remove(trackToRemove);
1693 if (trackToRemove->isTerminated()) {
1694 mTracks.remove(trackToRemove);
1695 deleteTrackName_l(trackToRemove->mName);
1696 }
1697 }
1698 }
1699
1700 if (activeTrack != 0) {
1701 AudioBufferProvider::Buffer buffer;
1702 size_t frameCount = mFrameCount;
1703 curBuf = (int8_t *)mMixBuffer;
1704 // output audio to hardware
1705 mLastWriteTime = systemTime();
1706 mInWrite = true;
1707 while(frameCount) {
1708 buffer.frameCount = frameCount;
1709 activeTrack->getNextBuffer(&buffer);
1710 if (UNLIKELY(buffer.raw == 0)) {
1711 memset(curBuf, 0, frameCount * mFrameSize);
1712 break;
1713 }
1714 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
1715 frameCount -= buffer.frameCount;
1716 curBuf += buffer.frameCount * mFrameSize;
1717 activeTrack->releaseBuffer(&buffer);
1718 }
1719 if (mSuspended) {
1720 usleep(kMaxBufferRecoveryInUsecs);
1721 } else {
1722 int bytesWritten = (int)mOutput->write(mMixBuffer, mixBufferSize);
1723 if (bytesWritten) mBytesWritten += bytesWritten;
1724 mNumWrites++;
1725 mInWrite = false;
1726 mStandby = false;
1727 nsecs_t temp = systemTime();
1728 standbyTime = temp + kStandbyTimeInNsecs;
1729 sleepTime = kBufferRecoveryInUsecs;
1730 }
1731 } else {
1732 // There was nothing to mix this round, which means all
1733 // active tracks were late. Sleep a little bit to give
1734 // them another chance. If we're too late, the audio
1735 // hardware will zero-fill for us.
1736 //LOGV("no buffers - usleep(%lu)", sleepTime);
1737 usleep(sleepTime);
1738 if (sleepTime < kMaxBufferRecoveryInUsecs) {
1739 sleepTime += kBufferRecoveryInUsecs;
1740 }
1741 }
1742
1743 // finally let go of removed track, without the lock held
1744 // since we can't guarantee the destructors won't acquire that
1745 // same lock.
1746 trackToRemove.clear();
1747 activeTrack.clear();
1748 }
1749
1750 if (!mStandby) {
1751 mOutput->standby();
1752 }
1753 sendConfigEvent(AudioSystem::OUTPUT_CLOSED);
1754 processConfigEvents();
1755
1756 LOGV("DirectOutputThread %p exiting", this);
1757 return false;
1758}
1759
1760// getTrackName_l() must be called with ThreadBase::mLock held
1761int AudioFlinger::DirectOutputThread::getTrackName_l()
1762{
1763 return 0;
1764}
1765
1766// deleteTrackName_l() must be called with ThreadBase::mLock held
1767void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
1768{
1769}
1770
1771// checkForNewParameters_l() must be called with ThreadBase::mLock held
1772bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
1773{
1774 bool reconfig = false;
1775
Eric Laurent3464c012009-08-04 09:45:33 -07001776 while (!mNewParameters.isEmpty()) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07001777 status_t status = NO_ERROR;
Eric Laurent3464c012009-08-04 09:45:33 -07001778 String8 keyValuePair = mNewParameters[0];
1779 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001780 int value;
Eric Laurent3464c012009-08-04 09:45:33 -07001781
1782 mNewParameters.removeAt(0);
1783
Eric Laurent9d91ad52009-07-17 12:17:14 -07001784 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
1785 // do not accept frame count changes if tracks are open as the track buffer
1786 // size depends on frame count and correct behavior would not be garantied
1787 // if frame count is changed after track creation
1788 if (!mTracks.isEmpty()) {
1789 status = INVALID_OPERATION;
1790 } else {
1791 reconfig = true;
1792 }
1793 }
1794 if (status == NO_ERROR) {
Eric Laurent3464c012009-08-04 09:45:33 -07001795 status = mOutput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001796 if (!mStandby && status == INVALID_OPERATION) {
1797 mOutput->standby();
1798 mStandby = true;
1799 mBytesWritten = 0;
Eric Laurent3464c012009-08-04 09:45:33 -07001800 status = mOutput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001801 }
1802 if (status == NO_ERROR && reconfig) {
1803 readOutputParameters();
Eric Laurent3464c012009-08-04 09:45:33 -07001804 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001805 }
1806 }
1807 mParamStatus = status;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001808 mParamCond.signal();
Eric Laurent3464c012009-08-04 09:45:33 -07001809 mWaitWorkCV.wait(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001810 }
1811 return reconfig;
The Android Open Source Projecte41dd752009-01-22 00:13:42 -08001812}
1813
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001814// ----------------------------------------------------------------------------
1815
Eric Laurent9d91ad52009-07-17 12:17:14 -07001816AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread)
1817 : MixerThread(audioFlinger, mainThread->getOutput())
1818{
1819 mType = PlaybackThread::DUPLICATING;
1820 addOutputTrack(mainThread);
1821}
1822
1823AudioFlinger::DuplicatingThread::~DuplicatingThread()
1824{
1825 mOutputTracks.clear();
1826}
1827
1828bool AudioFlinger::DuplicatingThread::threadLoop()
1829{
1830 unsigned long sleepTime = kBufferRecoveryInUsecs;
1831 int16_t* curBuf = mMixBuffer;
1832 Vector< sp<Track> > tracksToRemove;
1833 size_t enabledTracks = 0;
1834 nsecs_t standbyTime = systemTime();
1835 size_t mixBufferSize = mFrameCount*mFrameSize;
1836 SortedVector< sp<OutputTrack> > outputTracks;
1837
1838 while (!exitPending())
1839 {
1840 processConfigEvents();
1841
1842 enabledTracks = 0;
1843 { // scope for the mLock
1844
1845 Mutex::Autolock _l(mLock);
1846
1847 if (checkForNewParameters_l()) {
1848 mixBufferSize = mFrameCount*mFrameSize;
1849 }
1850
1851 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1852
1853 for (size_t i = 0; i < mOutputTracks.size(); i++) {
1854 outputTracks.add(mOutputTracks[i]);
1855 }
1856
1857 // put audio hardware into standby after short delay
1858 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1859 mSuspended) {
1860 if (!mStandby) {
1861 for (size_t i = 0; i < outputTracks.size(); i++) {
1862 mLock.unlock();
1863 outputTracks[i]->stop();
1864 mLock.lock();
1865 }
1866 mStandby = true;
1867 mBytesWritten = 0;
1868 }
1869
1870 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1871 // we're about to wait, flush the binder command buffer
1872 IPCThreadState::self()->flushCommands();
1873 outputTracks.clear();
1874
1875 if (exitPending()) break;
1876
1877 LOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
1878 mWaitWorkCV.wait(mLock);
1879 LOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
1880 if (mMasterMute == false) {
1881 char value[PROPERTY_VALUE_MAX];
1882 property_get("ro.audio.silent", value, "0");
1883 if (atoi(value)) {
1884 LOGD("Silence is golden");
1885 setMasterMute(true);
1886 }
1887 }
1888
1889 standbyTime = systemTime() + kStandbyTimeInNsecs;
1890 sleepTime = kBufferRecoveryInUsecs;
1891 continue;
1892 }
1893 }
1894
1895 enabledTracks = prepareTracks_l(activeTracks, &tracksToRemove);
1896 }
1897
1898 bool mustSleep = true;
1899 if (LIKELY(enabledTracks)) {
1900 // mix buffers...
1901 mAudioMixer->process(curBuf);
1902 if (!mSuspended) {
1903 for (size_t i = 0; i < outputTracks.size(); i++) {
1904 outputTracks[i]->write(curBuf, mFrameCount);
1905 }
1906 mStandby = false;
1907 mustSleep = false;
1908 mBytesWritten += mixBufferSize;
1909 }
1910 } else {
1911 // flush remaining overflow buffers in output tracks
1912 for (size_t i = 0; i < outputTracks.size(); i++) {
1913 if (outputTracks[i]->isActive()) {
1914 outputTracks[i]->write(curBuf, 0);
1915 standbyTime = systemTime() + kStandbyTimeInNsecs;
1916 mustSleep = false;
1917 }
1918 }
1919 }
1920 if (mustSleep) {
1921// LOGV("threadLoop() sleeping %d", sleepTime);
1922 usleep(sleepTime);
1923 if (sleepTime < kMaxBufferRecoveryInUsecs) {
1924 sleepTime += kBufferRecoveryInUsecs;
1925 }
1926 } else {
1927 sleepTime = kBufferRecoveryInUsecs;
1928 }
1929
1930 // finally let go of all our tracks, without the lock held
1931 // since we can't guarantee the destructors won't acquire that
1932 // same lock.
1933 tracksToRemove.clear();
1934 outputTracks.clear();
1935 }
1936
1937 if (!mStandby) {
1938 for (size_t i = 0; i < outputTracks.size(); i++) {
1939 mLock.unlock();
1940 outputTracks[i]->stop();
1941 mLock.lock();
1942 }
1943 }
1944
1945 sendConfigEvent(AudioSystem::OUTPUT_CLOSED);
1946 processConfigEvents();
1947
1948 return false;
1949}
1950
1951void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
1952{
1953 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
1954 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
1955 mSampleRate,
1956 mFormat,
1957 mChannelCount,
1958 frameCount);
1959 thread->setStreamVolume(AudioSystem::NUM_STREAM_TYPES, 1.0f);
1960 mOutputTracks.add(outputTrack);
1961 LOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
1962}
1963
1964void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
1965{
1966 Mutex::Autolock _l(mLock);
1967 for (size_t i = 0; i < mOutputTracks.size(); i++) {
1968 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
1969 mOutputTracks.removeAt(i);
1970 return;
1971 }
1972 }
1973 LOGV("removeOutputTrack(): unkonwn thread: %p", thread);
1974}
1975
1976
1977// ----------------------------------------------------------------------------
1978
The Android Open Source Project22f8def2009-03-09 11:52:12 -07001979// TrackBase constructor must be called with AudioFlinger::mLock held
Eric Laurent9d91ad52009-07-17 12:17:14 -07001980AudioFlinger::ThreadBase::TrackBase::TrackBase(
1981 const wp<ThreadBase>& thread,
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001982 const sp<Client>& client,
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001983 uint32_t sampleRate,
1984 int format,
1985 int channelCount,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08001986 int frameCount,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001987 uint32_t flags,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08001988 const sp<IMemory>& sharedBuffer)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001989 : RefBase(),
Eric Laurent9d91ad52009-07-17 12:17:14 -07001990 mThread(thread),
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001991 mClient(client),
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08001992 mFrameCount(0),
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001993 mState(IDLE),
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08001994 mClientTid(-1),
1995 mFormat(format),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001996 mFlags(flags & ~SYSTEM_FLAGS_MASK)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001997{
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08001998 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
1999
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002000 // LOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002001 size_t size = sizeof(audio_track_cblk_t);
2002 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
2003 if (sharedBuffer == 0) {
2004 size += bufferSize;
2005 }
2006
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002007 if (client != NULL) {
2008 mCblkMemory = client->heap()->allocate(size);
2009 if (mCblkMemory != 0) {
2010 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
2011 if (mCblk) { // construct the shared structure in-place.
2012 new(mCblk) audio_track_cblk_t();
2013 // clear all buffers
2014 mCblk->frameCount = frameCount;
Eric Laurent0bac5382009-07-07 07:10:45 -07002015 mCblk->sampleRate = sampleRate;
2016 mCblk->channels = (uint8_t)channelCount;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002017 if (sharedBuffer == 0) {
2018 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2019 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2020 // Force underrun condition to avoid false underrun callback until first data is
2021 // written to buffer
2022 mCblk->flowControlFlag = 1;
2023 } else {
2024 mBuffer = sharedBuffer->pointer();
2025 }
2026 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002027 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002028 } else {
2029 LOGE("not enough memory for AudioTrack size=%u", size);
2030 client->heap()->dump("AudioTrack");
2031 return;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002032 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002033 } else {
2034 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
2035 if (mCblk) { // construct the shared structure in-place.
2036 new(mCblk) audio_track_cblk_t();
2037 // clear all buffers
2038 mCblk->frameCount = frameCount;
Eric Laurent0bac5382009-07-07 07:10:45 -07002039 mCblk->sampleRate = sampleRate;
2040 mCblk->channels = (uint8_t)channelCount;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002041 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2042 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2043 // Force underrun condition to avoid false underrun callback until first data is
2044 // written to buffer
2045 mCblk->flowControlFlag = 1;
2046 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
2047 }
2048 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002049}
2050
Eric Laurent9d91ad52009-07-17 12:17:14 -07002051AudioFlinger::PlaybackThread::TrackBase::~TrackBase()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002052{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002053 if (mCblk) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07002054 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
2055 if (mClient == NULL) {
2056 delete mCblk;
2057 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002058 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002059 mCblkMemory.clear(); // and free the shared memory
2060 mClient.clear();
2061}
2062
Eric Laurent9d91ad52009-07-17 12:17:14 -07002063void AudioFlinger::PlaybackThread::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002064{
2065 buffer->raw = 0;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002066 mFrameCount = buffer->frameCount;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002067 step();
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002068 buffer->frameCount = 0;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002069}
2070
Eric Laurent9d91ad52009-07-17 12:17:14 -07002071bool AudioFlinger::PlaybackThread::TrackBase::step() {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002072 bool result;
2073 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002074
2075 result = cblk->stepServer(mFrameCount);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002076 if (!result) {
2077 LOGV("stepServer failed acquiring cblk mutex");
2078 mFlags |= STEPSERVER_FAILED;
2079 }
2080 return result;
2081}
2082
Eric Laurent9d91ad52009-07-17 12:17:14 -07002083void AudioFlinger::PlaybackThread::TrackBase::reset() {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002084 audio_track_cblk_t* cblk = this->cblk();
2085
2086 cblk->user = 0;
2087 cblk->server = 0;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002088 cblk->userBase = 0;
2089 cblk->serverBase = 0;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002090 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002091 LOGV("TrackBase::reset");
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002092}
2093
Eric Laurent9d91ad52009-07-17 12:17:14 -07002094sp<IMemory> AudioFlinger::PlaybackThread::TrackBase::getCblk() const
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002095{
2096 return mCblkMemory;
2097}
2098
Eric Laurent9d91ad52009-07-17 12:17:14 -07002099int AudioFlinger::PlaybackThread::TrackBase::sampleRate() const {
The Android Open Source Project4f68be12009-03-18 17:39:46 -07002100 return (int)mCblk->sampleRate;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002101}
2102
Eric Laurent9d91ad52009-07-17 12:17:14 -07002103int AudioFlinger::PlaybackThread::TrackBase::channelCount() const {
Eric Laurent0bac5382009-07-07 07:10:45 -07002104 return (int)mCblk->channels;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002105}
2106
Eric Laurent9d91ad52009-07-17 12:17:14 -07002107void* AudioFlinger::PlaybackThread::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002108 audio_track_cblk_t* cblk = this->cblk();
Eric Laurent9d91ad52009-07-17 12:17:14 -07002109 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
2110 int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002111
2112 // Check validity of returned pointer in case the track control block would have been corrupted.
Eric Laurent9d91ad52009-07-17 12:17:14 -07002113 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
2114 ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
The Android Open Source Project4f68be12009-03-18 17:39:46 -07002115 LOGE("TrackBase::getBuffer buffer out of range:\n start: %p, end %p , mBuffer %p mBufferEnd %p\n \
2116 server %d, serverBase %d, user %d, userBase %d, channels %d",
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002117 bufferStart, bufferEnd, mBuffer, mBufferEnd,
The Android Open Source Project4f68be12009-03-18 17:39:46 -07002118 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, cblk->channels);
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002119 return 0;
2120 }
2121
2122 return bufferStart;
2123}
2124
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002125// ----------------------------------------------------------------------------
2126
Eric Laurent9d91ad52009-07-17 12:17:14 -07002127// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
2128AudioFlinger::PlaybackThread::Track::Track(
2129 const wp<ThreadBase>& thread,
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002130 const sp<Client>& client,
2131 int streamType,
2132 uint32_t sampleRate,
2133 int format,
2134 int channelCount,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002135 int frameCount,
2136 const sp<IMemory>& sharedBuffer)
Eric Laurent9d91ad52009-07-17 12:17:14 -07002137 : TrackBase(thread, client, sampleRate, format, channelCount, frameCount, 0, sharedBuffer),
2138 mMute(false), mSharedBuffer(sharedBuffer), mName(-1)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002139{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002140 sp<ThreadBase> baseThread = thread.promote();
2141 if (baseThread != 0) {
2142 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
2143 mName = playbackThread->getTrackName_l();
2144 }
2145 LOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2146 if (mName < 0) {
2147 LOGE("no more track names available");
2148 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002149 mVolume[0] = 1.0f;
2150 mVolume[1] = 1.0f;
Eric Laurent570dd0b2009-05-22 09:18:15 -07002151 mStreamType = streamType;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002152 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
2153 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
2154 mCblk->frameSize = AudioSystem::isLinearPCM(format) ? channelCount * sizeof(int16_t) : sizeof(int8_t);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002155}
2156
Eric Laurent9d91ad52009-07-17 12:17:14 -07002157AudioFlinger::PlaybackThread::Track::~Track()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002158{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002159 LOGV("PlaybackThread::Track destructor");
2160 sp<ThreadBase> thread = mThread.promote();
2161 if (thread != 0) {
2162 Mutex::Autolock _l(thread->mLock);
2163 mState = TERMINATED;
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002164 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002165}
2166
Eric Laurent9d91ad52009-07-17 12:17:14 -07002167void AudioFlinger::PlaybackThread::Track::destroy()
2168{
2169 // NOTE: destroyTrack_l() can remove a strong reference to this Track
2170 // by removing it from mTracks vector, so there is a risk that this Tracks's
2171 // desctructor is called. As the destructor needs to lock mLock,
2172 // we must acquire a strong reference on this Track before locking mLock
2173 // here so that the destructor is called only when exiting this function.
2174 // On the other hand, as long as Track::destroy() is only called by
2175 // TrackHandle destructor, the TrackHandle still holds a strong ref on
2176 // this Track with its member mTrack.
2177 sp<Track> keep(this);
2178 { // scope for mLock
2179 sp<ThreadBase> thread = mThread.promote();
2180 if (thread != 0) {
2181 Mutex::Autolock _l(thread->mLock);
2182 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2183 playbackThread->destroyTrack_l(this);
2184 }
2185 }
2186}
2187
2188void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002189{
2190 snprintf(buffer, size, " %5d %5d %3u %3u %3u %3u %1d %1d %1d %5u %5u %5u %04x %04x\n",
2191 mName - AudioMixer::TRACK0,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002192 (mClient == NULL) ? getpid() : mClient->pid(),
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002193 mStreamType,
2194 mFormat,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002195 mCblk->channels,
2196 mFrameCount,
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002197 mState,
2198 mMute,
2199 mFillingUpStatus,
2200 mCblk->sampleRate,
2201 mCblk->volume[0],
2202 mCblk->volume[1],
2203 mCblk->server,
2204 mCblk->user);
2205}
2206
Eric Laurent9d91ad52009-07-17 12:17:14 -07002207status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002208{
2209 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002210 uint32_t framesReady;
2211 uint32_t framesReq = buffer->frameCount;
2212
2213 // Check if last stepServer failed, try to step now
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002214 if (mFlags & TrackBase::STEPSERVER_FAILED) {
2215 if (!step()) goto getNextBuffer_exit;
2216 LOGV("stepServer recovered");
2217 mFlags &= ~TrackBase::STEPSERVER_FAILED;
2218 }
2219
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002220 framesReady = cblk->framesReady();
2221
2222 if (LIKELY(framesReady)) {
2223 uint32_t s = cblk->server;
2224 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
2225
2226 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
2227 if (framesReq > framesReady) {
2228 framesReq = framesReady;
2229 }
2230 if (s + framesReq > bufferEnd) {
2231 framesReq = bufferEnd - s;
2232 }
2233
2234 buffer->raw = getBuffer(s, framesReq);
2235 if (buffer->raw == 0) goto getNextBuffer_exit;
2236
2237 buffer->frameCount = framesReq;
2238 return NO_ERROR;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002239 }
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002240
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002241getNextBuffer_exit:
2242 buffer->raw = 0;
2243 buffer->frameCount = 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002244 LOGV("getNextBuffer() no more data");
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002245 return NOT_ENOUGH_DATA;
2246}
2247
Eric Laurent9d91ad52009-07-17 12:17:14 -07002248bool AudioFlinger::PlaybackThread::Track::isReady() const {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002249 if (mFillingUpStatus != FS_FILLING) return true;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002250
2251 if (mCblk->framesReady() >= mCblk->frameCount ||
2252 mCblk->forceReady) {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002253 mFillingUpStatus = FS_FILLED;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002254 mCblk->forceReady = 0;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002255 return true;
2256 }
2257 return false;
2258}
2259
Eric Laurent9d91ad52009-07-17 12:17:14 -07002260status_t AudioFlinger::PlaybackThread::Track::start()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002261{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002262 LOGV("start(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2263 sp<ThreadBase> thread = mThread.promote();
2264 if (thread != 0) {
2265 Mutex::Autolock _l(thread->mLock);
2266 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2267 playbackThread->addTrack_l(this);
2268 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002269 return NO_ERROR;
2270}
2271
Eric Laurent9d91ad52009-07-17 12:17:14 -07002272void AudioFlinger::PlaybackThread::Track::stop()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002273{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002274 LOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2275 sp<ThreadBase> thread = mThread.promote();
2276 if (thread != 0) {
2277 Mutex::Autolock _l(thread->mLock);
2278 if (mState > STOPPED) {
2279 mState = STOPPED;
2280 // If the track is not active (PAUSED and buffers full), flush buffers
2281 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2282 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
2283 reset();
2284 }
2285 LOGV("(> STOPPED) => STOPPED (%d)", mName);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002286 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002287 }
2288}
2289
Eric Laurent9d91ad52009-07-17 12:17:14 -07002290void AudioFlinger::PlaybackThread::Track::pause()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002291{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002292 LOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurent9d91ad52009-07-17 12:17:14 -07002293 sp<ThreadBase> thread = mThread.promote();
2294 if (thread != 0) {
2295 Mutex::Autolock _l(thread->mLock);
2296 if (mState == ACTIVE || mState == RESUMING) {
2297 mState = PAUSING;
2298 LOGV("ACTIVE/RESUMING => PAUSING (%d)", mName);
2299 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002300 }
2301}
2302
Eric Laurent9d91ad52009-07-17 12:17:14 -07002303void AudioFlinger::PlaybackThread::Track::flush()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002304{
2305 LOGV("flush(%d)", mName);
Eric Laurent9d91ad52009-07-17 12:17:14 -07002306 sp<ThreadBase> thread = mThread.promote();
2307 if (thread != 0) {
2308 Mutex::Autolock _l(thread->mLock);
2309 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
2310 return;
2311 }
2312 // No point remaining in PAUSED state after a flush => go to
2313 // STOPPED state
2314 mState = STOPPED;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002315
Eric Laurent9d91ad52009-07-17 12:17:14 -07002316 mCblk->lock.lock();
2317 // NOTE: reset() will reset cblk->user and cblk->server with
2318 // the risk that at the same time, the AudioMixer is trying to read
2319 // data. In this case, getNextBuffer() would return a NULL pointer
2320 // as audio buffer => the AudioMixer code MUST always test that pointer
2321 // returned by getNextBuffer() is not NULL!
2322 reset();
2323 mCblk->lock.unlock();
2324 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002325}
2326
Eric Laurent9d91ad52009-07-17 12:17:14 -07002327void AudioFlinger::PlaybackThread::Track::reset()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002328{
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002329 // Do not reset twice to avoid discarding data written just after a flush and before
2330 // the audioflinger thread detects the track is stopped.
2331 if (!mResetDone) {
2332 TrackBase::reset();
2333 // Force underrun condition to avoid false underrun callback until first data is
2334 // written to buffer
2335 mCblk->flowControlFlag = 1;
2336 mCblk->forceReady = 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002337 mFillingUpStatus = FS_FILLING;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002338 mResetDone = true;
2339 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002340}
2341
Eric Laurent9d91ad52009-07-17 12:17:14 -07002342void AudioFlinger::PlaybackThread::Track::mute(bool muted)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002343{
2344 mMute = muted;
2345}
2346
Eric Laurent9d91ad52009-07-17 12:17:14 -07002347void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002348{
2349 mVolume[0] = left;
2350 mVolume[1] = right;
2351}
2352
2353// ----------------------------------------------------------------------------
2354
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002355// RecordTrack constructor must be called with AudioFlinger::mLock held
Eric Laurent9d91ad52009-07-17 12:17:14 -07002356AudioFlinger::RecordThread::RecordTrack::RecordTrack(
2357 const wp<ThreadBase>& thread,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002358 const sp<Client>& client,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002359 uint32_t sampleRate,
2360 int format,
2361 int channelCount,
2362 int frameCount,
2363 uint32_t flags)
Eric Laurent9d91ad52009-07-17 12:17:14 -07002364 : TrackBase(thread, client, sampleRate, format,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002365 channelCount, frameCount, flags, 0),
Eric Laurent9d91ad52009-07-17 12:17:14 -07002366 mOverflow(false)
2367{
2368 LOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
2369 if (format == AudioSystem::PCM_16_BIT) {
2370 mCblk->frameSize = channelCount * sizeof(int16_t);
2371 } else if (format == AudioSystem::PCM_8_BIT) {
2372 mCblk->frameSize = channelCount * sizeof(int8_t);
2373 } else {
2374 mCblk->frameSize = sizeof(int8_t);
2375 }
2376}
2377
2378AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002379{
2380}
2381
Eric Laurent9d91ad52009-07-17 12:17:14 -07002382status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002383{
2384 audio_track_cblk_t* cblk = this->cblk();
2385 uint32_t framesAvail;
2386 uint32_t framesReq = buffer->frameCount;
2387
2388 // Check if last stepServer failed, try to step now
2389 if (mFlags & TrackBase::STEPSERVER_FAILED) {
2390 if (!step()) goto getNextBuffer_exit;
2391 LOGV("stepServer recovered");
2392 mFlags &= ~TrackBase::STEPSERVER_FAILED;
2393 }
2394
2395 framesAvail = cblk->framesAvailable_l();
2396
2397 if (LIKELY(framesAvail)) {
2398 uint32_t s = cblk->server;
2399 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
2400
2401 if (framesReq > framesAvail) {
2402 framesReq = framesAvail;
2403 }
2404 if (s + framesReq > bufferEnd) {
2405 framesReq = bufferEnd - s;
2406 }
2407
2408 buffer->raw = getBuffer(s, framesReq);
2409 if (buffer->raw == 0) goto getNextBuffer_exit;
2410
2411 buffer->frameCount = framesReq;
2412 return NO_ERROR;
2413 }
2414
2415getNextBuffer_exit:
2416 buffer->raw = 0;
2417 buffer->frameCount = 0;
2418 return NOT_ENOUGH_DATA;
2419}
2420
Eric Laurent9d91ad52009-07-17 12:17:14 -07002421status_t AudioFlinger::RecordThread::RecordTrack::start()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002422{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002423 sp<ThreadBase> thread = mThread.promote();
2424 if (thread != 0) {
2425 RecordThread *recordThread = (RecordThread *)thread.get();
2426 return recordThread->start(this);
2427 }
2428 return NO_INIT;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002429}
2430
Eric Laurent9d91ad52009-07-17 12:17:14 -07002431void AudioFlinger::RecordThread::RecordTrack::stop()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002432{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002433 sp<ThreadBase> thread = mThread.promote();
2434 if (thread != 0) {
2435 RecordThread *recordThread = (RecordThread *)thread.get();
2436 recordThread->stop(this);
2437 TrackBase::reset();
2438 // Force overerrun condition to avoid false overrun callback until first data is
2439 // read from buffer
2440 mCblk->flowControlFlag = 1;
2441 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002442}
2443
2444
2445// ----------------------------------------------------------------------------
2446
Eric Laurent9d91ad52009-07-17 12:17:14 -07002447AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
2448 const wp<ThreadBase>& thread,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002449 uint32_t sampleRate,
2450 int format,
2451 int channelCount,
2452 int frameCount)
Eric Laurent9d91ad52009-07-17 12:17:14 -07002453 : Track(thread, NULL, AudioSystem::NUM_STREAM_TYPES, sampleRate, format, channelCount, frameCount, NULL),
2454 mActive(false)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002455{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002456
2457 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002458 mCblk->out = 1;
2459 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
2460 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
2461 mOutBuffer.frameCount = 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002462 mWaitTimeMs = (playbackThread->frameCount() * 2 * 1000) / playbackThread->sampleRate();
2463
2464 LOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, mCblk->frameCount %d, mCblk->sampleRate %d, mCblk->channels %d mBufferEnd %p mWaitTimeMs %d",
2465 mCblk, mBuffer, mCblk->buffers, mCblk->frameCount, mCblk->sampleRate, mCblk->channels, mBufferEnd, mWaitTimeMs);
2466
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002467}
2468
Eric Laurent9d91ad52009-07-17 12:17:14 -07002469AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002470{
2471 stop();
2472}
2473
Eric Laurent9d91ad52009-07-17 12:17:14 -07002474status_t AudioFlinger::PlaybackThread::OutputTrack::start()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002475{
2476 status_t status = Track::start();
Eric Laurent9d91ad52009-07-17 12:17:14 -07002477 if (status != NO_ERROR) {
2478 return status;
2479 }
2480
2481 mActive = true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002482 mRetryCount = 127;
2483 return status;
2484}
2485
Eric Laurent9d91ad52009-07-17 12:17:14 -07002486void AudioFlinger::PlaybackThread::OutputTrack::stop()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002487{
2488 Track::stop();
2489 clearBufferQueue();
2490 mOutBuffer.frameCount = 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002491 mActive = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002492}
2493
Eric Laurent9d91ad52009-07-17 12:17:14 -07002494bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002495{
2496 Buffer *pInBuffer;
2497 Buffer inBuffer;
2498 uint32_t channels = mCblk->channels;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002499 bool outputBufferFull = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002500 inBuffer.frameCount = frames;
2501 inBuffer.i16 = data;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002502
2503 uint32_t waitTimeLeftMs = mWaitTimeMs;
2504
2505 if (!mActive) {
2506 start();
2507 sp<ThreadBase> thread = mThread.promote();
2508 if (thread != 0) {
2509 MixerThread *mixerThread = (MixerThread *)thread.get();
2510 if (mCblk->frameCount > frames){
2511 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
2512 uint32_t startFrames = (mCblk->frameCount - frames);
2513 pInBuffer = new Buffer;
2514 pInBuffer->mBuffer = new int16_t[startFrames * channels];
2515 pInBuffer->frameCount = startFrames;
2516 pInBuffer->i16 = pInBuffer->mBuffer;
2517 memset(pInBuffer->raw, 0, startFrames * channels * sizeof(int16_t));
2518 mBufferQueue.add(pInBuffer);
2519 } else {
2520 LOGW ("OutputTrack::write() %p no more buffers in queue", this);
2521 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002522 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002523 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002524 }
2525
Eric Laurent9d91ad52009-07-17 12:17:14 -07002526 while (waitTimeLeftMs) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002527 // First write pending buffers, then new data
2528 if (mBufferQueue.size()) {
2529 pInBuffer = mBufferQueue.itemAt(0);
2530 } else {
2531 pInBuffer = &inBuffer;
2532 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002533
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002534 if (pInBuffer->frameCount == 0) {
2535 break;
2536 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002537
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002538 if (mOutBuffer.frameCount == 0) {
2539 mOutBuffer.frameCount = pInBuffer->frameCount;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002540 nsecs_t startTime = systemTime();
2541 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
2542 LOGV ("OutputTrack::write() %p no more output buffers", this);
2543 outputBufferFull = true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002544 break;
2545 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002546 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
2547// LOGV("OutputTrack::write() waitTimeMs %d waitTimeLeftMs %d", waitTimeMs, waitTimeLeftMs)
2548 if (waitTimeLeftMs >= waitTimeMs) {
2549 waitTimeLeftMs -= waitTimeMs;
2550 } else {
2551 waitTimeLeftMs = 0;
2552 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002553 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002554
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002555 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
2556 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channels * sizeof(int16_t));
2557 mCblk->stepUser(outFrames);
2558 pInBuffer->frameCount -= outFrames;
2559 pInBuffer->i16 += outFrames * channels;
2560 mOutBuffer.frameCount -= outFrames;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002561 mOutBuffer.i16 += outFrames * channels;
2562
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002563 if (pInBuffer->frameCount == 0) {
2564 if (mBufferQueue.size()) {
2565 mBufferQueue.removeAt(0);
2566 delete [] pInBuffer->mBuffer;
2567 delete pInBuffer;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002568 LOGV("OutputTrack::write() %p released overflow buffer %d", this, mBufferQueue.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002569 } else {
2570 break;
2571 }
2572 }
2573 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002574
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002575 // If we could not write all frames, allocate a buffer and queue it for next time.
2576 if (inBuffer.frameCount) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07002577 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002578 pInBuffer = new Buffer;
2579 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channels];
2580 pInBuffer->frameCount = inBuffer.frameCount;
2581 pInBuffer->i16 = pInBuffer->mBuffer;
2582 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channels * sizeof(int16_t));
2583 mBufferQueue.add(pInBuffer);
Eric Laurent9d91ad52009-07-17 12:17:14 -07002584 LOGV("OutputTrack::write() %p adding overflow buffer %d", this, mBufferQueue.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002585 } else {
Eric Laurent9d91ad52009-07-17 12:17:14 -07002586 LOGW("OutputTrack::write() %p no more overflow buffers", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002587 }
2588 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002589
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002590 // Calling write() with a 0 length buffer, means that no more data will be written:
Eric Laurent9d91ad52009-07-17 12:17:14 -07002591 // 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 -08002592 // by output mixer.
Eric Laurent9d91ad52009-07-17 12:17:14 -07002593 if (frames == 0 && mBufferQueue.size() == 0) {
2594 if (mCblk->user < mCblk->frameCount) {
2595 frames = mCblk->frameCount - mCblk->user;
2596 pInBuffer = new Buffer;
2597 pInBuffer->mBuffer = new int16_t[frames * channels];
2598 pInBuffer->frameCount = frames;
2599 pInBuffer->i16 = pInBuffer->mBuffer;
2600 memset(pInBuffer->raw, 0, frames * channels * sizeof(int16_t));
2601 mBufferQueue.add(pInBuffer);
2602 } else {
2603 stop();
2604 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002605 }
2606
Eric Laurent9d91ad52009-07-17 12:17:14 -07002607 return outputBufferFull;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002608}
2609
Eric Laurent9d91ad52009-07-17 12:17:14 -07002610status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002611{
2612 int active;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002613 status_t result;
2614 audio_track_cblk_t* cblk = mCblk;
2615 uint32_t framesReq = buffer->frameCount;
2616
Eric Laurent9d91ad52009-07-17 12:17:14 -07002617// LOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002618 buffer->frameCount = 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002619
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002620 uint32_t framesAvail = cblk->framesAvailable();
2621
Eric Laurent9d91ad52009-07-17 12:17:14 -07002622
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002623 if (framesAvail == 0) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07002624 Mutex::Autolock _l(cblk->lock);
2625 goto start_loop_here;
2626 while (framesAvail == 0) {
2627 active = mActive;
2628 if (UNLIKELY(!active)) {
2629 LOGV("Not active and NO_MORE_BUFFERS");
2630 return AudioTrack::NO_MORE_BUFFERS;
2631 }
2632 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
2633 if (result != NO_ERROR) {
2634 return AudioTrack::NO_MORE_BUFFERS;
2635 }
2636 // read the server count again
2637 start_loop_here:
2638 framesAvail = cblk->framesAvailable_l();
2639 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002640 }
2641
Eric Laurent9d91ad52009-07-17 12:17:14 -07002642// if (framesAvail < framesReq) {
2643// return AudioTrack::NO_MORE_BUFFERS;
2644// }
2645
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002646 if (framesReq > framesAvail) {
2647 framesReq = framesAvail;
2648 }
2649
2650 uint32_t u = cblk->user;
2651 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
2652
2653 if (u + framesReq > bufferEnd) {
2654 framesReq = bufferEnd - u;
2655 }
2656
2657 buffer->frameCount = framesReq;
2658 buffer->raw = (void *)cblk->buffer(u);
2659 return NO_ERROR;
2660}
2661
2662
Eric Laurent9d91ad52009-07-17 12:17:14 -07002663void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002664{
2665 size_t size = mBufferQueue.size();
2666 Buffer *pBuffer;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002667
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002668 for (size_t i = 0; i < size; i++) {
2669 pBuffer = mBufferQueue.itemAt(i);
2670 delete [] pBuffer->mBuffer;
2671 delete pBuffer;
2672 }
2673 mBufferQueue.clear();
2674}
2675
2676// ----------------------------------------------------------------------------
2677
2678AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
2679 : RefBase(),
2680 mAudioFlinger(audioFlinger),
2681 mMemoryDealer(new MemoryDealer(1024*1024)),
2682 mPid(pid)
2683{
2684 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
2685}
2686
2687AudioFlinger::Client::~Client()
2688{
2689 mAudioFlinger->removeClient(mPid);
2690}
2691
2692const sp<MemoryDealer>& AudioFlinger::Client::heap() const
2693{
2694 return mMemoryDealer;
2695}
2696
2697// ----------------------------------------------------------------------------
2698
Eric Laurent9d91ad52009-07-17 12:17:14 -07002699AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002700 : BnAudioTrack(),
2701 mTrack(track)
2702{
2703}
2704
2705AudioFlinger::TrackHandle::~TrackHandle() {
2706 // just stop the track on deletion, associated resources
2707 // will be freed from the main thread once all pending buffers have
2708 // been played. Unless it's not in the active track list, in which
2709 // case we free everything now...
2710 mTrack->destroy();
2711}
2712
2713status_t AudioFlinger::TrackHandle::start() {
2714 return mTrack->start();
2715}
2716
2717void AudioFlinger::TrackHandle::stop() {
2718 mTrack->stop();
2719}
2720
2721void AudioFlinger::TrackHandle::flush() {
2722 mTrack->flush();
2723}
2724
2725void AudioFlinger::TrackHandle::mute(bool e) {
2726 mTrack->mute(e);
2727}
2728
2729void AudioFlinger::TrackHandle::pause() {
2730 mTrack->pause();
2731}
2732
2733void AudioFlinger::TrackHandle::setVolume(float left, float right) {
2734 mTrack->setVolume(left, right);
2735}
2736
2737sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
2738 return mTrack->getCblk();
2739}
2740
2741status_t AudioFlinger::TrackHandle::onTransact(
2742 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2743{
2744 return BnAudioTrack::onTransact(code, data, reply, flags);
2745}
2746
2747// ----------------------------------------------------------------------------
2748
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002749sp<IAudioRecord> AudioFlinger::openRecord(
2750 pid_t pid,
Eric Laurente0e9ecc2009-07-28 08:44:33 -07002751 int input,
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002752 uint32_t sampleRate,
2753 int format,
2754 int channelCount,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002755 int frameCount,
2756 uint32_t flags,
2757 status_t *status)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002758{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002759 sp<RecordThread::RecordTrack> recordTrack;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002760 sp<RecordHandle> recordHandle;
2761 sp<Client> client;
2762 wp<Client> wclient;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002763 status_t lStatus;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002764 RecordThread *thread;
2765 size_t inFrameCount;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002766
2767 // check calling permissions
2768 if (!recordingAllowed()) {
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002769 lStatus = PERMISSION_DENIED;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002770 goto Exit;
2771 }
2772
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002773 // add client to list
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002774 { // scope for mLock
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002775 Mutex::Autolock _l(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07002776 thread = checkRecordThread_l(input);
2777 if (thread == NULL) {
2778 lStatus = BAD_VALUE;
2779 goto Exit;
2780 }
2781
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002782 wclient = mClients.valueFor(pid);
2783 if (wclient != NULL) {
2784 client = wclient.promote();
2785 } else {
2786 client = new Client(this, pid);
2787 mClients.add(pid, client);
2788 }
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002789
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002790 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent9d91ad52009-07-17 12:17:14 -07002791 recordTrack = new RecordThread::RecordTrack(thread, client, sampleRate,
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002792 format, channelCount, frameCount, flags);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002793 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002794 if (recordTrack->getCblk() == NULL) {
2795 recordTrack.clear();
2796 lStatus = NO_MEMORY;
2797 goto Exit;
2798 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002799
2800 // return to handle to client
2801 recordHandle = new RecordHandle(recordTrack);
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002802 lStatus = NO_ERROR;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002803
2804Exit:
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002805 if (status) {
2806 *status = lStatus;
2807 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002808 return recordHandle;
2809}
2810
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002811// ----------------------------------------------------------------------------
2812
Eric Laurent9d91ad52009-07-17 12:17:14 -07002813AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002814 : BnAudioRecord(),
2815 mRecordTrack(recordTrack)
2816{
2817}
2818
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002819AudioFlinger::RecordHandle::~RecordHandle() {
2820 stop();
2821}
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002822
2823status_t AudioFlinger::RecordHandle::start() {
2824 LOGV("RecordHandle::start()");
2825 return mRecordTrack->start();
2826}
2827
2828void AudioFlinger::RecordHandle::stop() {
2829 LOGV("RecordHandle::stop()");
2830 mRecordTrack->stop();
2831}
2832
2833sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
2834 return mRecordTrack->getCblk();
2835}
2836
2837status_t AudioFlinger::RecordHandle::onTransact(
2838 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2839{
2840 return BnAudioRecord::onTransact(code, data, reply, flags);
2841}
2842
2843// ----------------------------------------------------------------------------
2844
Eric Laurent9d91ad52009-07-17 12:17:14 -07002845AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger, AudioStreamIn *input, uint32_t sampleRate, uint32_t channels) :
2846 ThreadBase(audioFlinger),
2847 mInput(input), mResampler(0), mRsmpOutBuffer(0), mRsmpInBuffer(0)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002848{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002849 mReqChannelCount = AudioSystem::popCount(channels);
2850 mReqSampleRate = sampleRate;
2851 readInputParameters();
2852 sendConfigEvent(AudioSystem::INPUT_OPENED);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002853}
2854
Eric Laurent9d91ad52009-07-17 12:17:14 -07002855
2856AudioFlinger::RecordThread::~RecordThread()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002857{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002858 mAudioFlinger->mAudioHardware->closeInputStream(mInput);
2859 delete[] mRsmpInBuffer;
2860 if (mResampler != 0) {
2861 delete mResampler;
2862 delete[] mRsmpOutBuffer;
2863 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002864}
2865
Eric Laurent9d91ad52009-07-17 12:17:14 -07002866void AudioFlinger::RecordThread::onFirstRef()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002867{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002868 const size_t SIZE = 256;
2869 char buffer[SIZE];
2870
2871 snprintf(buffer, SIZE, "Record Thread %p", this);
2872
2873 run(buffer, PRIORITY_URGENT_AUDIO);
2874}
2875bool AudioFlinger::RecordThread::threadLoop()
2876{
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002877 AudioBufferProvider::Buffer buffer;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002878 sp<RecordTrack> activeTrack;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002879
2880 // start recording
2881 while (!exitPending()) {
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002882
Eric Laurent9d91ad52009-07-17 12:17:14 -07002883 processConfigEvents();
2884
2885 { // scope for mLock
2886 Mutex::Autolock _l(mLock);
2887 checkForNewParameters_l();
2888 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
2889 if (!mStandby) {
2890 mInput->standby();
2891 mStandby = true;
2892 }
2893
2894 if (exitPending()) break;
2895
2896 LOGV("RecordThread: loop stopping");
2897 // go to sleep
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002898 mWaitWorkCV.wait(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07002899 LOGV("RecordThread: loop starting");
2900 continue;
2901 }
2902 if (mActiveTrack != 0) {
2903 if (mActiveTrack->mState == TrackBase::PAUSING) {
2904 mActiveTrack.clear();
2905 mStartStopCond.broadcast();
2906 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
2907 mRsmpInIndex = mFrameCount;
2908 if (mReqChannelCount != mActiveTrack->channelCount()) {
2909 mActiveTrack.clear();
2910 } else {
2911 mActiveTrack->mState == TrackBase::ACTIVE;
2912 }
2913 mStartStopCond.broadcast();
2914 }
2915 mStandby = false;
2916 }
2917 }
2918
2919 if (mActiveTrack != 0) {
2920 buffer.frameCount = mFrameCount;
2921 if (LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
2922 size_t framesOut = buffer.frameCount;
2923 if (mResampler == 0) {
2924 // no resampling
2925 while (framesOut) {
2926 size_t framesIn = mFrameCount - mRsmpInIndex;
2927 if (framesIn) {
2928 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
2929 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
2930 if (framesIn > framesOut)
2931 framesIn = framesOut;
2932 mRsmpInIndex += framesIn;
2933 framesOut -= framesIn;
2934 if (mChannelCount == mReqChannelCount ||
2935 mFormat != AudioSystem::PCM_16_BIT) {
2936 memcpy(dst, src, framesIn * mFrameSize);
2937 } else {
2938 int16_t *src16 = (int16_t *)src;
2939 int16_t *dst16 = (int16_t *)dst;
2940 if (mChannelCount == 1) {
2941 while (framesIn--) {
2942 *dst16++ = *src16;
2943 *dst16++ = *src16++;
2944 }
2945 } else {
2946 while (framesIn--) {
2947 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
2948 src16 += 2;
2949 }
2950 }
2951 }
2952 }
2953 if (framesOut && mFrameCount == mRsmpInIndex) {
2954 ssize_t bytesRead;
2955 if (framesOut == mFrameCount &&
2956 (mChannelCount == mReqChannelCount || mFormat != AudioSystem::PCM_16_BIT)) {
2957 bytesRead = mInput->read(buffer.raw, mInputBytes);
2958 framesOut = 0;
2959 } else {
2960 bytesRead = mInput->read(mRsmpInBuffer, mInputBytes);
2961 mRsmpInIndex = 0;
2962 }
2963 if (bytesRead < 0) {
2964 LOGE("Error reading audio input");
2965 sleep(1);
2966 mRsmpInIndex = mFrameCount;
2967 framesOut = 0;
2968 buffer.frameCount = 0;
2969 }
2970 }
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002971 }
2972 } else {
Eric Laurent9d91ad52009-07-17 12:17:14 -07002973 // resampling
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002974
Eric Laurent9d91ad52009-07-17 12:17:14 -07002975 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
2976 // alter output frame count as if we were expecting stereo samples
2977 if (mChannelCount == 1 && mReqChannelCount == 1) {
2978 framesOut >>= 1;
2979 }
2980 mResampler->resample(mRsmpOutBuffer, framesOut, this);
2981 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
2982 // are 32 bit aligned which should be always true.
2983 if (mChannelCount == 2 && mReqChannelCount == 1) {
2984 AudioMixer::ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
2985 // the resampler always outputs stereo samples: do post stereo to mono conversion
2986 int16_t *src = (int16_t *)mRsmpOutBuffer;
2987 int16_t *dst = buffer.i16;
2988 while (framesOut--) {
2989 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
2990 src += 2;
2991 }
2992 } else {
2993 AudioMixer::ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
2994 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002995
Eric Laurent9d91ad52009-07-17 12:17:14 -07002996 }
2997 mActiveTrack->releaseBuffer(&buffer);
2998 mActiveTrack->overflow();
2999 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003000 // client isn't retrieving buffers fast enough
3001 else {
Eric Laurent9d91ad52009-07-17 12:17:14 -07003002 if (!mActiveTrack->setOverflow())
3003 LOGW("RecordThread: buffer overflow");
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003004 // Release the processor for a while before asking for a new buffer.
3005 // This will give the application more chance to read from the buffer and
3006 // clear the overflow.
3007 usleep(5000);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003008 }
3009 }
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003010 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003011
Eric Laurent9d91ad52009-07-17 12:17:14 -07003012 if (!mStandby) {
3013 mInput->standby();
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003014 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003015 mActiveTrack.clear();
3016
3017 sendConfigEvent(AudioSystem::INPUT_CLOSED);
3018 processConfigEvents();
3019
3020 LOGV("RecordThread %p exiting", this);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003021 return false;
3022}
3023
Eric Laurent9d91ad52009-07-17 12:17:14 -07003024status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003025{
Eric Laurent9d91ad52009-07-17 12:17:14 -07003026 LOGV("RecordThread::start");
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003027 AutoMutex lock(&mLock);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003028
Eric Laurent9d91ad52009-07-17 12:17:14 -07003029 if (mActiveTrack != 0) {
3030 if (recordTrack != mActiveTrack.get()) return -EBUSY;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003031
Eric Laurent9d91ad52009-07-17 12:17:14 -07003032 if (mActiveTrack->mState == TrackBase::PAUSING) mActiveTrack->mState = TrackBase::RESUMING;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003033
Eric Laurent9d91ad52009-07-17 12:17:14 -07003034 return NO_ERROR;
3035 }
3036
3037 mActiveTrack = recordTrack;
3038 mActiveTrack->mState = TrackBase::RESUMING;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003039 // signal thread to start
3040 LOGV("Signal record thread");
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003041 mWaitWorkCV.signal();
Eric Laurent9d91ad52009-07-17 12:17:14 -07003042 mStartStopCond.wait(mLock);
3043 if (mActiveTrack != 0) {
3044 LOGV("Record started OK");
3045 return NO_ERROR;
3046 } else {
3047 LOGV("Record failed to start");
3048 return BAD_VALUE;
3049 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003050}
3051
Eric Laurent9d91ad52009-07-17 12:17:14 -07003052void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
3053 LOGV("RecordThread::stop");
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003054 AutoMutex lock(&mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003055 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
3056 mActiveTrack->mState = TrackBase::PAUSING;
3057 mStartStopCond.wait(mLock);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003058 }
3059}
3060
Eric Laurent9d91ad52009-07-17 12:17:14 -07003061status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003062{
3063 const size_t SIZE = 256;
3064 char buffer[SIZE];
3065 String8 result;
3066 pid_t pid = 0;
3067
Eric Laurent9d91ad52009-07-17 12:17:14 -07003068 if (mActiveTrack != 0 && mActiveTrack->mClient != 0) {
3069 snprintf(buffer, SIZE, "Record client pid: %d\n", mActiveTrack->mClient->pid());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003070 result.append(buffer);
3071 } else {
3072 result.append("No record client\n");
3073 }
3074 write(fd, result.string(), result.size());
3075 return NO_ERROR;
3076}
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003077
Eric Laurent9d91ad52009-07-17 12:17:14 -07003078status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3079{
3080 size_t framesReq = buffer->frameCount;
3081 size_t framesReady = mFrameCount - mRsmpInIndex;
3082 int channelCount;
3083
3084 if (framesReady == 0) {
3085 ssize_t bytesRead = mInput->read(mRsmpInBuffer, mInputBytes);
3086 if (bytesRead < 0) {
3087 LOGE("RecordThread::getNextBuffer() Error reading audio input");
3088 sleep(1);
3089 buffer->raw = 0;
3090 buffer->frameCount = 0;
3091 return NOT_ENOUGH_DATA;
3092 }
3093 mRsmpInIndex = 0;
3094 framesReady = mFrameCount;
3095 }
3096
3097 if (framesReq > framesReady) {
3098 framesReq = framesReady;
3099 }
3100
3101 if (mChannelCount == 1 && mReqChannelCount == 2) {
3102 channelCount = 1;
3103 } else {
3104 channelCount = 2;
3105 }
3106 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
3107 buffer->frameCount = framesReq;
3108 return NO_ERROR;
3109}
3110
3111void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3112{
3113 mRsmpInIndex += buffer->frameCount;
3114 buffer->frameCount = 0;
3115}
3116
3117bool AudioFlinger::RecordThread::checkForNewParameters_l()
3118{
3119 bool reconfig = false;
3120
Eric Laurent3464c012009-08-04 09:45:33 -07003121 while (!mNewParameters.isEmpty()) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07003122 status_t status = NO_ERROR;
Eric Laurent3464c012009-08-04 09:45:33 -07003123 String8 keyValuePair = mNewParameters[0];
3124 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003125 int value;
3126 int reqFormat = mFormat;
3127 int reqSamplingRate = mReqSampleRate;
3128 int reqChannelCount = mReqChannelCount;
Eric Laurent3464c012009-08-04 09:45:33 -07003129
3130 mNewParameters.removeAt(0);
3131
Eric Laurent9d91ad52009-07-17 12:17:14 -07003132 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3133 reqSamplingRate = value;
3134 reconfig = true;
3135 }
3136 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
3137 reqFormat = value;
3138 reconfig = true;
3139 }
3140 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
3141 reqChannelCount = AudioSystem::popCount(value);
3142 reconfig = true;
3143 }
3144 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3145 // do not accept frame count changes if tracks are open as the track buffer
3146 // size depends on frame count and correct behavior would not be garantied
3147 // if frame count is changed after track creation
3148 if (mActiveTrack != 0) {
3149 status = INVALID_OPERATION;
3150 } else {
3151 reconfig = true;
3152 }
3153 }
3154 if (status == NO_ERROR) {
Eric Laurent3464c012009-08-04 09:45:33 -07003155 status = mInput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003156 if (status == INVALID_OPERATION) {
3157 mInput->standby();
Eric Laurent3464c012009-08-04 09:45:33 -07003158 status = mInput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003159 }
3160 if (reconfig) {
3161 if (status == BAD_VALUE &&
3162 reqFormat == mInput->format() && reqFormat == AudioSystem::PCM_16_BIT &&
3163 ((int)mInput->sampleRate() <= 2 * reqSamplingRate) &&
3164 (AudioSystem::popCount(mInput->channels()) < 3) && (reqChannelCount < 3)) {
3165 status = NO_ERROR;
3166 }
3167 if (status == NO_ERROR) {
3168 readInputParameters();
Eric Laurent3464c012009-08-04 09:45:33 -07003169 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003170 }
3171 }
3172 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003173 mParamStatus = status;
3174 mParamCond.signal();
Eric Laurent3464c012009-08-04 09:45:33 -07003175 mWaitWorkCV.wait(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003176 }
3177 return reconfig;
3178}
3179
3180String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
3181{
3182 return mInput->getParameters(keys);
3183}
3184
3185void AudioFlinger::RecordThread::audioConfigChanged(int event, int param) {
3186 AudioSystem::OutputDescriptor desc;
3187 void *param2 = 0;
3188
3189 switch (event) {
3190 case AudioSystem::INPUT_OPENED:
3191 case AudioSystem::INPUT_CONFIG_CHANGED:
3192 desc.channels = mChannelCount;
3193 desc.samplingRate = mSampleRate;
3194 desc.format = mFormat;
3195 desc.frameCount = mFrameCount;
3196 desc.latency = 0;
3197 param2 = &desc;
3198 break;
3199
3200 case AudioSystem::INPUT_CLOSED:
3201 default:
3202 break;
3203 }
3204 mAudioFlinger->audioConfigChanged(event, this, param2);
3205}
3206
3207void AudioFlinger::RecordThread::readInputParameters()
3208{
3209 if (mRsmpInBuffer) delete mRsmpInBuffer;
3210 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
3211 if (mResampler) delete mResampler;
3212 mResampler = 0;
3213
3214 mSampleRate = mInput->sampleRate();
3215 mChannelCount = AudioSystem::popCount(mInput->channels());
3216 mFormat = mInput->format();
3217 mFrameSize = mInput->frameSize();
3218 mInputBytes = mInput->bufferSize();
3219 mFrameCount = mInputBytes / mFrameSize;
3220 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
3221
3222 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
3223 {
3224 int channelCount;
3225 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
3226 // stereo to mono post process as the resampler always outputs stereo.
3227 if (mChannelCount == 1 && mReqChannelCount == 2) {
3228 channelCount = 1;
3229 } else {
3230 channelCount = 2;
3231 }
3232 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
3233 mResampler->setSampleRate(mSampleRate);
3234 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
3235 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
3236
3237 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
3238 if (mChannelCount == 1 && mReqChannelCount == 1) {
3239 mFrameCount >>= 1;
3240 }
3241
3242 }
3243 mRsmpInIndex = mFrameCount;
3244}
3245
3246// ----------------------------------------------------------------------------
3247
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003248int AudioFlinger::openOutput(uint32_t *pDevices,
Eric Laurent9d91ad52009-07-17 12:17:14 -07003249 uint32_t *pSamplingRate,
3250 uint32_t *pFormat,
3251 uint32_t *pChannels,
3252 uint32_t *pLatencyMs,
3253 uint32_t flags)
3254{
3255 status_t status;
3256 PlaybackThread *thread = NULL;
3257 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
3258 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
3259 uint32_t format = pFormat ? *pFormat : 0;
3260 uint32_t channels = pChannels ? *pChannels : 0;
3261 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
3262
3263 LOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
3264 pDevices ? *pDevices : 0,
3265 samplingRate,
3266 format,
3267 channels,
3268 flags);
3269
3270 if (pDevices == NULL || *pDevices == 0) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003271 return 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003272 }
3273 Mutex::Autolock _l(mLock);
3274
3275 AudioStreamOut *output = mAudioHardware->openOutputStream(*pDevices,
3276 (int *)&format,
3277 &channels,
3278 &samplingRate,
3279 &status);
3280 LOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
3281 output,
3282 samplingRate,
3283 format,
3284 channels,
3285 status);
3286
3287 mHardwareStatus = AUDIO_HW_IDLE;
3288 if (output != 0) {
3289 if ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) ||
3290 (format != AudioSystem::PCM_16_BIT) ||
3291 (channels != AudioSystem::CHANNEL_OUT_STEREO)) {
3292 thread = new DirectOutputThread(this, output);
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003293 LOGV("openOutput() created direct output: ID %d thread %p", (mNextThreadId + 1), thread);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003294 } else {
3295 thread = new MixerThread(this, output);
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003296 LOGV("openOutput() created mixer output: ID %d thread %p", (mNextThreadId + 1), thread);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003297 }
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003298 mPlaybackThreads.add(++mNextThreadId, thread);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003299
3300 if (pSamplingRate) *pSamplingRate = samplingRate;
3301 if (pFormat) *pFormat = format;
3302 if (pChannels) *pChannels = channels;
3303 if (pLatencyMs) *pLatencyMs = thread->latency();
3304 }
3305
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003306 return mNextThreadId;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003307}
3308
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003309int AudioFlinger::openDuplicateOutput(int output1, int output2)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003310{
3311 Mutex::Autolock _l(mLock);
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003312 MixerThread *thread1 = checkMixerThread_l(output1);
3313 MixerThread *thread2 = checkMixerThread_l(output2);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003314
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003315 if (thread1 == NULL || thread2 == NULL) {
3316 LOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
3317 return 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003318 }
3319
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003320
3321 DuplicatingThread *thread = new DuplicatingThread(this, thread1);
3322 thread->addOutputTrack(thread2);
3323 mPlaybackThreads.add(++mNextThreadId, thread);
3324 return mNextThreadId;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003325}
3326
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003327status_t AudioFlinger::closeOutput(int output)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003328{
3329 PlaybackThread *thread;
3330 {
3331 Mutex::Autolock _l(mLock);
3332 thread = checkPlaybackThread_l(output);
3333 if (thread == NULL) {
3334 return BAD_VALUE;
3335 }
3336
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003337 LOGV("closeOutput() %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003338
3339 if (thread->type() == PlaybackThread::MIXER) {
3340 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003341 if (mPlaybackThreads.valueAt(i)->type() == PlaybackThread::DUPLICATING) {
3342 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Eric Laurent9d91ad52009-07-17 12:17:14 -07003343 dupThread->removeOutputTrack((MixerThread *)thread);
3344 }
3345 }
3346 }
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003347 mPlaybackThreads.removeItem(output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003348 }
3349 thread->exit();
3350
3351 return NO_ERROR;
3352}
3353
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003354status_t AudioFlinger::suspendOutput(int output)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003355{
3356 Mutex::Autolock _l(mLock);
3357 PlaybackThread *thread = checkPlaybackThread_l(output);
3358
3359 if (thread == NULL) {
3360 return BAD_VALUE;
3361 }
3362
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003363 LOGV("suspendOutput() %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003364 thread->suspend();
3365
3366 return NO_ERROR;
3367}
3368
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003369status_t AudioFlinger::restoreOutput(int output)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003370{
3371 Mutex::Autolock _l(mLock);
3372 PlaybackThread *thread = checkPlaybackThread_l(output);
3373
3374 if (thread == NULL) {
3375 return BAD_VALUE;
3376 }
3377
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003378 LOGV("restoreOutput() %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003379
3380 thread->restore();
3381
3382 return NO_ERROR;
3383}
3384
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003385int AudioFlinger::openInput(uint32_t *pDevices,
Eric Laurent9d91ad52009-07-17 12:17:14 -07003386 uint32_t *pSamplingRate,
3387 uint32_t *pFormat,
3388 uint32_t *pChannels,
3389 uint32_t acoustics)
3390{
3391 status_t status;
3392 RecordThread *thread = NULL;
3393 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
3394 uint32_t format = pFormat ? *pFormat : 0;
3395 uint32_t channels = pChannels ? *pChannels : 0;
3396 uint32_t reqSamplingRate = samplingRate;
3397 uint32_t reqFormat = format;
3398 uint32_t reqChannels = channels;
3399
3400 if (pDevices == NULL || *pDevices == 0) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003401 return 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003402 }
3403 Mutex::Autolock _l(mLock);
3404
3405 AudioStreamIn *input = mAudioHardware->openInputStream(*pDevices,
3406 (int *)&format,
3407 &channels,
3408 &samplingRate,
3409 &status,
3410 (AudioSystem::audio_in_acoustics)acoustics);
3411 LOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
3412 input,
3413 samplingRate,
3414 format,
3415 channels,
3416 acoustics,
3417 status);
3418
3419 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
3420 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
3421 // or stereo to mono conversions on 16 bit PCM inputs.
3422 if (input == 0 && status == BAD_VALUE &&
3423 reqFormat == format && format == AudioSystem::PCM_16_BIT &&
3424 (samplingRate <= 2 * reqSamplingRate) &&
3425 (AudioSystem::popCount(channels) < 3) && (AudioSystem::popCount(reqChannels) < 3)) {
3426 LOGV("openInput() reopening with proposed sampling rate and channels");
3427 input = mAudioHardware->openInputStream(*pDevices,
3428 (int *)&format,
3429 &channels,
3430 &samplingRate,
3431 &status,
3432 (AudioSystem::audio_in_acoustics)acoustics);
3433 }
3434
3435 if (input != 0) {
3436 // Start record thread
3437 thread = new RecordThread(this, input, reqSamplingRate, reqChannels);
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003438 mRecordThreads.add(++mNextThreadId, thread);
3439 LOGV("openInput() created record thread: ID %d thread %p", mNextThreadId, thread);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003440 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
3441 if (pFormat) *pFormat = format;
3442 if (pChannels) *pChannels = reqChannels;
3443
3444 input->standby();
3445 }
3446
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003447 return mNextThreadId;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003448}
3449
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003450status_t AudioFlinger::closeInput(int input)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003451{
3452 RecordThread *thread;
3453 {
3454 Mutex::Autolock _l(mLock);
3455 thread = checkRecordThread_l(input);
3456 if (thread == NULL) {
3457 return BAD_VALUE;
3458 }
3459
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003460 LOGV("closeInput() %d", input);
3461 mRecordThreads.removeItem(input);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003462 }
3463 thread->exit();
3464
3465 return NO_ERROR;
3466}
3467
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003468status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003469{
3470 Mutex::Autolock _l(mLock);
3471 MixerThread *dstThread = checkMixerThread_l(output);
3472 if (dstThread == NULL) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003473 LOGW("setStreamOutput() bad output id %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003474 return BAD_VALUE;
3475 }
3476
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003477 LOGV("setStreamOutput() stream %d to output %d", stream, output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003478
3479 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003480 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent9d91ad52009-07-17 12:17:14 -07003481 if (thread != dstThread &&
3482 thread->type() != PlaybackThread::DIRECT) {
3483 MixerThread *srcThread = (MixerThread *)thread;
3484 SortedVector < sp<MixerThread::Track> > tracks;
3485 SortedVector < wp<MixerThread::Track> > activeTracks;
3486 srcThread->getTracks(tracks, activeTracks, stream);
3487 if (tracks.size()) {
3488 dstThread->putTracks(tracks, activeTracks);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003489 }
Eric Laurentd55d1792009-07-28 06:11:55 -07003490 dstThread->sendConfigEvent(AudioSystem::STREAM_CONFIG_CHANGED, stream);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003491 }
3492 }
3493
3494 return NO_ERROR;
3495}
3496
3497// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003498AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
Eric Laurent9d91ad52009-07-17 12:17:14 -07003499{
3500 PlaybackThread *thread = NULL;
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003501 if (mPlaybackThreads.indexOfKey(output) >= 0) {
3502 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
Eric Laurent9d91ad52009-07-17 12:17:14 -07003503 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003504 return thread;
3505}
3506
3507// checkMixerThread_l() must be called with AudioFlinger::mLock held
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003508AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
Eric Laurent9d91ad52009-07-17 12:17:14 -07003509{
3510 PlaybackThread *thread = checkPlaybackThread_l(output);
3511 if (thread != NULL) {
3512 if (thread->type() == PlaybackThread::DIRECT) {
3513 thread = NULL;
3514 }
3515 }
3516 return (MixerThread *)thread;
3517}
3518
3519// checkRecordThread_l() must be called with AudioFlinger::mLock held
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003520AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
Eric Laurent9d91ad52009-07-17 12:17:14 -07003521{
3522 RecordThread *thread = NULL;
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003523 if (mRecordThreads.indexOfKey(input) >= 0) {
3524 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
Eric Laurent9d91ad52009-07-17 12:17:14 -07003525 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003526 return thread;
3527}
3528
3529// ----------------------------------------------------------------------------
3530
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003531status_t AudioFlinger::onTransact(
3532 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3533{
3534 return BnAudioFlinger::onTransact(code, data, reply, flags);
3535}
3536
3537// ----------------------------------------------------------------------------
Eric Laurent9d91ad52009-07-17 12:17:14 -07003538
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003539void AudioFlinger::instantiate() {
3540 defaultServiceManager()->addService(
3541 String16("media.audio_flinger"), new AudioFlinger());
3542}
3543
3544}; // namespace android