blob: 77a126c724091aa31997e820d1d51c0261a9e11b [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 Laurentf9df2492009-08-06 08:49:39 -0700813 mMixBuffer(0), mSuspended(0), mBytesWritten(0), mOutput(output),
Eric Laurent9395d9b2009-07-23 13:17:39 -0700814 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;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800832}
833
Eric Laurent9d91ad52009-07-17 12:17:14 -0700834status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800835{
836 dumpInternals(fd, args);
837 dumpTracks(fd, args);
838 return NO_ERROR;
839}
840
Eric Laurent9d91ad52009-07-17 12:17:14 -0700841status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800842{
843 const size_t SIZE = 256;
844 char buffer[SIZE];
845 String8 result;
846
Eric Laurent9d91ad52009-07-17 12:17:14 -0700847 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800848 result.append(buffer);
849 result.append(" Name Clien Typ Fmt Chn Buf S M F SRate LeftV RighV Serv User\n");
850 for (size_t i = 0; i < mTracks.size(); ++i) {
Eric Laurentc828f6a2009-03-31 14:34:35 -0700851 sp<Track> track = mTracks[i];
852 if (track != 0) {
853 track->dump(buffer, SIZE);
854 result.append(buffer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800855 }
856 }
857
Eric Laurent9d91ad52009-07-17 12:17:14 -0700858 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800859 result.append(buffer);
860 result.append(" Name Clien Typ Fmt Chn Buf S M F SRate LeftV RighV Serv User\n");
861 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Eric Laurentc828f6a2009-03-31 14:34:35 -0700862 wp<Track> wTrack = mActiveTracks[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800863 if (wTrack != 0) {
864 sp<Track> track = wTrack.promote();
865 if (track != 0) {
866 track->dump(buffer, SIZE);
867 result.append(buffer);
868 }
869 }
870 }
871 write(fd, result.string(), result.size());
872 return NO_ERROR;
873}
874
Eric Laurent9d91ad52009-07-17 12:17:14 -0700875status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800876{
877 const size_t SIZE = 256;
878 char buffer[SIZE];
879 String8 result;
880
Eric Laurent9d91ad52009-07-17 12:17:14 -0700881 snprintf(buffer, SIZE, "Output thread %p internals\n", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800882 result.append(buffer);
883 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
884 result.append(buffer);
885 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
886 result.append(buffer);
887 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
888 result.append(buffer);
889 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
890 result.append(buffer);
891 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
892 result.append(buffer);
893 write(fd, result.string(), result.size());
894 return NO_ERROR;
895}
896
897// Thread virtuals
Eric Laurent9d91ad52009-07-17 12:17:14 -0700898status_t AudioFlinger::PlaybackThread::readyToRun()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800899{
900 if (mSampleRate == 0) {
901 LOGE("No working audio driver found.");
902 return NO_INIT;
903 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700904 LOGI("AudioFlinger's thread %p ready to run", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800905 return NO_ERROR;
906}
907
Eric Laurent9d91ad52009-07-17 12:17:14 -0700908void AudioFlinger::PlaybackThread::onFirstRef()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800909{
910 const size_t SIZE = 256;
911 char buffer[SIZE];
912
Eric Laurent9d91ad52009-07-17 12:17:14 -0700913 snprintf(buffer, SIZE, "Playback Thread %p", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800914
915 run(buffer, ANDROID_PRIORITY_URGENT_AUDIO);
916}
917
Eric Laurent9d91ad52009-07-17 12:17:14 -0700918// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
919sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800920 const sp<AudioFlinger::Client>& client,
921 int streamType,
922 uint32_t sampleRate,
923 int format,
924 int channelCount,
925 int frameCount,
926 const sp<IMemory>& sharedBuffer,
927 status_t *status)
928{
929 sp<Track> track;
930 status_t lStatus;
Eric Laurent9d91ad52009-07-17 12:17:14 -0700931
932 if (mType == DIRECT) {
933 if (sampleRate != mSampleRate || format != mFormat || channelCount != mChannelCount) {
934 LOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelCount %d for output %p",
935 sampleRate, format, channelCount, mOutput);
936 lStatus = BAD_VALUE;
937 goto Exit;
938 }
939 } else {
940 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
941 if (sampleRate > mSampleRate*2) {
942 LOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
943 lStatus = BAD_VALUE;
944 goto Exit;
945 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800946 }
947
Eric Laurent9d91ad52009-07-17 12:17:14 -0700948 if (mOutput == 0) {
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700949 LOGE("Audio driver not initialized.");
950 lStatus = NO_INIT;
951 goto Exit;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800952 }
953
Eric Laurent9d91ad52009-07-17 12:17:14 -0700954 { // scope for mLock
955 Mutex::Autolock _l(mLock);
956 track = new Track(this, client, streamType, sampleRate, format,
957 channelCount, frameCount, sharedBuffer);
958 if (track->getCblk() == NULL) {
959 lStatus = NO_MEMORY;
960 goto Exit;
961 }
962 mTracks.add(track);
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700963 }
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700964 lStatus = NO_ERROR;
965
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800966Exit:
967 if(status) {
968 *status = lStatus;
969 }
970 return track;
971}
972
Eric Laurent9d91ad52009-07-17 12:17:14 -0700973uint32_t AudioFlinger::PlaybackThread::latency() const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800974{
975 if (mOutput) {
976 return mOutput->latency();
977 }
978 else {
979 return 0;
980 }
981}
982
Eric Laurent9d91ad52009-07-17 12:17:14 -0700983status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800984{
985 mMasterVolume = value;
986 return NO_ERROR;
987}
988
Eric Laurent9d91ad52009-07-17 12:17:14 -0700989status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800990{
991 mMasterMute = muted;
992 return NO_ERROR;
993}
994
Eric Laurent9d91ad52009-07-17 12:17:14 -0700995float AudioFlinger::PlaybackThread::masterVolume() const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800996{
997 return mMasterVolume;
998}
999
Eric Laurent9d91ad52009-07-17 12:17:14 -07001000bool AudioFlinger::PlaybackThread::masterMute() const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001001{
1002 return mMasterMute;
1003}
1004
Eric Laurent9d91ad52009-07-17 12:17:14 -07001005status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001006{
1007 mStreamTypes[stream].volume = value;
1008 return NO_ERROR;
1009}
1010
Eric Laurent9d91ad52009-07-17 12:17:14 -07001011status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001012{
1013 mStreamTypes[stream].mute = muted;
1014 return NO_ERROR;
1015}
1016
Eric Laurent9d91ad52009-07-17 12:17:14 -07001017float AudioFlinger::PlaybackThread::streamVolume(int stream) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001018{
1019 return mStreamTypes[stream].volume;
1020}
1021
Eric Laurent9d91ad52009-07-17 12:17:14 -07001022bool AudioFlinger::PlaybackThread::streamMute(int stream) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001023{
1024 return mStreamTypes[stream].mute;
1025}
1026
Eric Laurent9d91ad52009-07-17 12:17:14 -07001027bool AudioFlinger::PlaybackThread::isMusicActive() const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001028{
Eric Laurent9d91ad52009-07-17 12:17:14 -07001029 Mutex::Autolock _l(mLock);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001030 size_t count = mActiveTracks.size();
1031 for (size_t i = 0 ; i < count ; ++i) {
1032 sp<Track> t = mActiveTracks[i].promote();
1033 if (t == 0) continue;
1034 Track* const track = t.get();
Eric Laurent9395d9b2009-07-23 13:17:39 -07001035 if (t->type() == AudioSystem::MUSIC)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001036 return true;
1037 }
1038 return false;
1039}
1040
Eric Laurent9d91ad52009-07-17 12:17:14 -07001041// addTrack_l() must be called with ThreadBase::mLock held
1042status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001043{
1044 status_t status = ALREADY_EXISTS;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001045
1046 // here the track could be either new, or restarted
1047 // in both cases "unstop" the track
1048 if (track->isPaused()) {
1049 track->mState = TrackBase::RESUMING;
1050 LOGV("PAUSED => RESUMING (%d)", track->name());
1051 } else {
1052 track->mState = TrackBase::ACTIVE;
1053 LOGV("? => ACTIVE (%d)", track->name());
1054 }
1055 // set retry count for buffer fill
1056 track->mRetryCount = kMaxTrackStartupRetries;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001057 if (mActiveTracks.indexOf(track) < 0) {
1058 // the track is newly added, make sure it fills up all its
1059 // buffers before playing. This is to ensure the client will
1060 // effectively get the latency it requested.
1061 track->mFillingUpStatus = Track::FS_FILLING;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08001062 track->mResetDone = false;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001063 mActiveTracks.add(track);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001064 status = NO_ERROR;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001065 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07001066
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001067 LOGV("mWaitWorkCV.broadcast");
Eric Laurent9d91ad52009-07-17 12:17:14 -07001068 mWaitWorkCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001069
1070 return status;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001071}
1072
Eric Laurent9d91ad52009-07-17 12:17:14 -07001073// destroyTrack_l() must be called with ThreadBase::mLock held
1074void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001075{
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001076 track->mState = TrackBase::TERMINATED;
1077 if (mActiveTracks.indexOf(track) < 0) {
1078 LOGV("remove track (%d) and delete from mixer", track->name());
1079 mTracks.remove(track);
The Android Open Source Project22f8def2009-03-09 11:52:12 -07001080 deleteTrackName_l(track->name());
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001081 }
1082}
1083
Eric Laurent9d91ad52009-07-17 12:17:14 -07001084String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
The Android Open Source Projecte41dd752009-01-22 00:13:42 -08001085{
Eric Laurent9d91ad52009-07-17 12:17:14 -07001086 return mOutput->getParameters(keys);
1087}
The Android Open Source Projecte41dd752009-01-22 00:13:42 -08001088
Eric Laurent9d91ad52009-07-17 12:17:14 -07001089void AudioFlinger::PlaybackThread::audioConfigChanged(int event, int param) {
1090 AudioSystem::OutputDescriptor desc;
1091 void *param2 = 0;
1092
1093 LOGV("PlaybackThread::audioConfigChanged, thread %p, event %d, param %d", this, event, param);
1094
1095 switch (event) {
1096 case AudioSystem::OUTPUT_OPENED:
1097 case AudioSystem::OUTPUT_CONFIG_CHANGED:
1098 desc.channels = mChannelCount;
1099 desc.samplingRate = mSampleRate;
1100 desc.format = mFormat;
1101 desc.frameCount = mFrameCount;
1102 desc.latency = latency();
1103 param2 = &desc;
1104 break;
1105
1106 case AudioSystem::STREAM_CONFIG_CHANGED:
1107 param2 = &param;
1108 case AudioSystem::OUTPUT_CLOSED:
1109 default:
1110 break;
1111 }
1112 mAudioFlinger->audioConfigChanged(event, this, param2);
1113}
1114
1115void AudioFlinger::PlaybackThread::readOutputParameters()
1116{
1117 mSampleRate = mOutput->sampleRate();
1118 mChannelCount = AudioSystem::popCount(mOutput->channels());
1119
1120 mFormat = mOutput->format();
1121 mFrameSize = mOutput->frameSize();
1122 mFrameCount = mOutput->bufferSize() / mFrameSize;
1123
1124 mMinBytesToWrite = (mOutput->latency() * mSampleRate * mFrameSize) / 1000;
1125 // FIXME - Current mixer implementation only supports stereo output: Always
1126 // Allocate a stereo buffer even if HW output is mono.
1127 if (mMixBuffer != NULL) delete mMixBuffer;
1128 mMixBuffer = new int16_t[mFrameCount * 2];
1129 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1130}
1131
1132// ----------------------------------------------------------------------------
1133
1134AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output)
1135 : PlaybackThread(audioFlinger, output),
1136 mAudioMixer(0)
1137{
1138 mType = PlaybackThread::MIXER;
1139 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1140
1141 // FIXME - Current mixer implementation only supports stereo output
1142 if (mChannelCount == 1) {
1143 LOGE("Invalid audio hardware channel count");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001144 }
The Android Open Source Projecte41dd752009-01-22 00:13:42 -08001145}
1146
Eric Laurent9d91ad52009-07-17 12:17:14 -07001147AudioFlinger::MixerThread::~MixerThread()
The Android Open Source Projecte41dd752009-01-22 00:13:42 -08001148{
Eric Laurent9d91ad52009-07-17 12:17:14 -07001149 delete mAudioMixer;
1150}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001151
Eric Laurent9d91ad52009-07-17 12:17:14 -07001152bool AudioFlinger::MixerThread::threadLoop()
1153{
1154 unsigned long sleepTime = kBufferRecoveryInUsecs;
1155 int16_t* curBuf = mMixBuffer;
1156 Vector< sp<Track> > tracksToRemove;
1157 size_t enabledTracks = 0;
1158 nsecs_t standbyTime = systemTime();
1159 size_t mixBufferSize = mFrameCount * mFrameSize;
1160 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 2;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001161
Eric Laurent9d91ad52009-07-17 12:17:14 -07001162 while (!exitPending())
1163 {
1164 processConfigEvents();
1165
1166 enabledTracks = 0;
1167 { // scope for mLock
1168
1169 Mutex::Autolock _l(mLock);
1170
1171 if (checkForNewParameters_l()) {
1172 mixBufferSize = mFrameCount * mFrameSize;
1173 maxPeriod = seconds(mFrameCount) / mSampleRate * 2;
1174 }
1175
1176 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1177
1178 // put audio hardware into standby after short delay
1179 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1180 mSuspended) {
1181 if (!mStandby) {
1182 LOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
1183 mOutput->standby();
1184 mStandby = true;
1185 mBytesWritten = 0;
1186 }
1187
1188 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1189 // we're about to wait, flush the binder command buffer
1190 IPCThreadState::self()->flushCommands();
1191
1192 if (exitPending()) break;
1193
1194 // wait until we have something to do...
1195 LOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
1196 mWaitWorkCV.wait(mLock);
1197 LOGV("MixerThread %p TID %d waking up\n", this, gettid());
1198
1199 if (mMasterMute == false) {
1200 char value[PROPERTY_VALUE_MAX];
1201 property_get("ro.audio.silent", value, "0");
1202 if (atoi(value)) {
1203 LOGD("Silence is golden");
1204 setMasterMute(true);
1205 }
1206 }
1207
1208 standbyTime = systemTime() + kStandbyTimeInNsecs;
1209 continue;
1210 }
1211 }
1212
1213 enabledTracks = prepareTracks_l(activeTracks, &tracksToRemove);
1214 }
1215
1216 if (LIKELY(enabledTracks)) {
1217 // mix buffers...
1218 mAudioMixer->process(curBuf);
1219
1220 // output audio to hardware
1221 if (mSuspended) {
1222 usleep(kMaxBufferRecoveryInUsecs);
1223 } else {
1224 mLastWriteTime = systemTime();
1225 mInWrite = true;
1226 int bytesWritten = (int)mOutput->write(curBuf, mixBufferSize);
1227 if (bytesWritten > 0) mBytesWritten += bytesWritten;
1228 mNumWrites++;
1229 mInWrite = false;
1230 mStandby = false;
1231 nsecs_t temp = systemTime();
1232 standbyTime = temp + kStandbyTimeInNsecs;
1233 nsecs_t delta = temp - mLastWriteTime;
1234 if (delta > maxPeriod) {
1235 LOGW("write blocked for %llu msecs", ns2ms(delta));
1236 mNumDelayedWrites++;
1237 }
1238 sleepTime = kBufferRecoveryInUsecs;
1239 }
1240 } else {
1241 // There was nothing to mix this round, which means all
1242 // active tracks were late. Sleep a little bit to give
1243 // them another chance. If we're too late, the audio
1244 // hardware will zero-fill for us.
1245 // LOGV("thread %p no buffers - usleep(%lu)", this, sleepTime);
1246 usleep(sleepTime);
1247 if (sleepTime < kMaxBufferRecoveryInUsecs) {
1248 sleepTime += kBufferRecoveryInUsecs;
1249 }
1250 }
1251
1252 // finally let go of all our tracks, without the lock held
1253 // since we can't guarantee the destructors won't acquire that
1254 // same lock.
1255 tracksToRemove.clear();
1256 }
1257
1258 if (!mStandby) {
1259 mOutput->standby();
1260 }
1261 sendConfigEvent(AudioSystem::OUTPUT_CLOSED);
1262 processConfigEvents();
1263
1264 LOGV("MixerThread %p exiting", this);
1265 return false;
1266}
1267
1268// prepareTracks_l() must be called with ThreadBase::mLock held
1269size_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
1270{
1271
1272 size_t enabledTracks = 0;
1273 // find out which tracks need to be processed
1274 size_t count = activeTracks.size();
1275 for (size_t i=0 ; i<count ; i++) {
1276 sp<Track> t = activeTracks[i].promote();
1277 if (t == 0) continue;
1278
1279 Track* const track = t.get();
1280 audio_track_cblk_t* cblk = track->cblk();
1281
1282 // The first time a track is added we wait
1283 // for all its buffers to be filled before processing it
1284 mAudioMixer->setActiveTrack(track->name());
1285 if (cblk->framesReady() && (track->isReady() || track->isStopped()) &&
1286 !track->isPaused())
1287 {
1288 //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
1289
1290 // compute volume for this track
1291 int16_t left, right;
1292 if (track->isMuted() || mMasterMute || track->isPausing() ||
1293 mStreamTypes[track->type()].mute) {
1294 left = right = 0;
1295 if (track->isPausing()) {
1296 track->setPaused();
1297 }
1298 } else {
1299 float typeVolume = mStreamTypes[track->type()].volume;
1300 float v = mMasterVolume * typeVolume;
1301 float v_clamped = v * cblk->volume[0];
1302 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
1303 left = int16_t(v_clamped);
1304 v_clamped = v * cblk->volume[1];
1305 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
1306 right = int16_t(v_clamped);
1307 }
1308
1309 // XXX: these things DON'T need to be done each time
1310 mAudioMixer->setBufferProvider(track);
1311 mAudioMixer->enable(AudioMixer::MIXING);
1312
1313 int param;
1314 if ( track->mFillingUpStatus == Track::FS_FILLED) {
1315 // no ramp for the first volume setting
1316 track->mFillingUpStatus = Track::FS_ACTIVE;
1317 if (track->mState == TrackBase::RESUMING) {
1318 track->mState = TrackBase::ACTIVE;
1319 param = AudioMixer::RAMP_VOLUME;
1320 } else {
1321 param = AudioMixer::VOLUME;
1322 }
1323 } else {
1324 param = AudioMixer::RAMP_VOLUME;
1325 }
1326 mAudioMixer->setParameter(param, AudioMixer::VOLUME0, left);
1327 mAudioMixer->setParameter(param, AudioMixer::VOLUME1, right);
1328 mAudioMixer->setParameter(
1329 AudioMixer::TRACK,
1330 AudioMixer::FORMAT, track->format());
1331 mAudioMixer->setParameter(
1332 AudioMixer::TRACK,
1333 AudioMixer::CHANNEL_COUNT, track->channelCount());
1334 mAudioMixer->setParameter(
1335 AudioMixer::RESAMPLE,
1336 AudioMixer::SAMPLE_RATE,
1337 int(cblk->sampleRate));
1338
1339 // reset retry count
1340 track->mRetryCount = kMaxTrackRetries;
1341 enabledTracks++;
1342 } else {
1343 //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
1344 if (track->isStopped()) {
1345 track->reset();
1346 }
1347 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
1348 // We have consumed all the buffers of this track.
1349 // Remove it from the list of active tracks.
1350 tracksToRemove->add(track);
1351 mAudioMixer->disable(AudioMixer::MIXING);
1352 } else {
1353 // No buffers for this track. Give it a few chances to
1354 // fill a buffer, then remove it from active list.
1355 if (--(track->mRetryCount) <= 0) {
1356 LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
1357 tracksToRemove->add(track);
1358 }
1359 // For tracks using static shared memry buffer, make sure that we have
1360 // written enough data to audio hardware before disabling the track
1361 // NOTE: this condition with arrive before track->mRetryCount <= 0 so we
1362 // don't care about code removing track from active list above.
1363 if ((track->mSharedBuffer == 0) || (mBytesWritten >= mMinBytesToWrite)) {
1364 mAudioMixer->disable(AudioMixer::MIXING);
1365 } else {
1366 enabledTracks++;
1367 }
1368 }
1369 }
1370 }
1371
1372 // remove all the tracks that need to be...
1373 count = tracksToRemove->size();
1374 if (UNLIKELY(count)) {
1375 for (size_t i=0 ; i<count ; i++) {
1376 const sp<Track>& track = tracksToRemove->itemAt(i);
1377 mActiveTracks.remove(track);
1378 if (track->isTerminated()) {
1379 mTracks.remove(track);
1380 deleteTrackName_l(track->mName);
1381 }
1382 }
1383 }
1384
1385 return enabledTracks;
1386}
1387
1388void AudioFlinger::MixerThread::getTracks(
1389 SortedVector < sp<Track> >& tracks,
1390 SortedVector < wp<Track> >& activeTracks,
1391 int streamType)
1392{
1393 LOGV ("MixerThread::getTracks() mixer %p, mTracks.size %d, mActiveTracks.size %d", this, mTracks.size(), mActiveTracks.size());
1394 Mutex::Autolock _l(mLock);
1395 size_t size = mTracks.size();
1396 for (size_t i = 0; i < size; i++) {
1397 sp<Track> t = mTracks[i];
1398 if (t->type() == streamType) {
1399 tracks.add(t);
1400 int j = mActiveTracks.indexOf(t);
1401 if (j >= 0) {
1402 t = mActiveTracks[j].promote();
1403 if (t != NULL) {
1404 activeTracks.add(t);
1405 }
1406 }
1407 }
1408 }
1409
1410 size = activeTracks.size();
1411 for (size_t i = 0; i < size; i++) {
1412 mActiveTracks.remove(activeTracks[i]);
1413 }
1414
1415 size = tracks.size();
1416 for (size_t i = 0; i < size; i++) {
1417 sp<Track> t = tracks[i];
1418 mTracks.remove(t);
1419 deleteTrackName_l(t->name());
1420 }
1421}
1422
1423void AudioFlinger::MixerThread::putTracks(
1424 SortedVector < sp<Track> >& tracks,
1425 SortedVector < wp<Track> >& activeTracks)
1426{
1427 LOGV ("MixerThread::putTracks() mixer %p, tracks.size %d, activeTracks.size %d", this, tracks.size(), activeTracks.size());
1428 Mutex::Autolock _l(mLock);
1429 size_t size = tracks.size();
1430 for (size_t i = 0; i < size ; i++) {
1431 sp<Track> t = tracks[i];
1432 int name = getTrackName_l();
1433
1434 if (name < 0) return;
1435
1436 t->mName = name;
1437 t->mThread = this;
1438 mTracks.add(t);
1439
1440 int j = activeTracks.indexOf(t);
1441 if (j >= 0) {
1442 mActiveTracks.add(t);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001443 }
1444 }
1445}
1446
Eric Laurent9d91ad52009-07-17 12:17:14 -07001447// getTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Project22f8def2009-03-09 11:52:12 -07001448int AudioFlinger::MixerThread::getTrackName_l()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001449{
1450 return mAudioMixer->getTrackName();
1451}
1452
Eric Laurent9d91ad52009-07-17 12:17:14 -07001453// deleteTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Project22f8def2009-03-09 11:52:12 -07001454void AudioFlinger::MixerThread::deleteTrackName_l(int name)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001455{
1456 mAudioMixer->deleteTrackName(name);
1457}
1458
Eric Laurent9d91ad52009-07-17 12:17:14 -07001459// checkForNewParameters_l() must be called with ThreadBase::mLock held
1460bool AudioFlinger::MixerThread::checkForNewParameters_l()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001461{
Eric Laurent9d91ad52009-07-17 12:17:14 -07001462 bool reconfig = false;
1463
Eric Laurent3464c012009-08-04 09:45:33 -07001464 while (!mNewParameters.isEmpty()) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07001465 status_t status = NO_ERROR;
Eric Laurent3464c012009-08-04 09:45:33 -07001466 String8 keyValuePair = mNewParameters[0];
1467 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001468 int value;
Eric Laurent3464c012009-08-04 09:45:33 -07001469
1470 mNewParameters.removeAt(0);
1471
Eric Laurent9d91ad52009-07-17 12:17:14 -07001472 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
1473 reconfig = true;
1474 }
1475 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
1476 if (value != AudioSystem::PCM_16_BIT) {
1477 status = BAD_VALUE;
1478 } else {
1479 reconfig = true;
1480 }
1481 }
1482 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
1483 if (value != AudioSystem::CHANNEL_OUT_STEREO) {
1484 status = BAD_VALUE;
1485 } else {
1486 reconfig = true;
1487 }
1488 }
1489 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
1490 // do not accept frame count changes if tracks are open as the track buffer
1491 // size depends on frame count and correct behavior would not be garantied
1492 // if frame count is changed after track creation
1493 if (!mTracks.isEmpty()) {
1494 status = INVALID_OPERATION;
1495 } else {
1496 reconfig = true;
1497 }
1498 }
1499 if (status == NO_ERROR) {
Eric Laurent3464c012009-08-04 09:45:33 -07001500 status = mOutput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001501 if (!mStandby && status == INVALID_OPERATION) {
1502 mOutput->standby();
1503 mStandby = true;
1504 mBytesWritten = 0;
Eric Laurent3464c012009-08-04 09:45:33 -07001505 status = mOutput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001506 }
1507 if (status == NO_ERROR && reconfig) {
1508 delete mAudioMixer;
1509 readOutputParameters();
1510 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1511 for (size_t i = 0; i < mTracks.size() ; i++) {
1512 int name = getTrackName_l();
1513 if (name < 0) break;
1514 mTracks[i]->mName = name;
Eric Laurent878c0e12009-08-10 08:15:12 -07001515 // limit track sample rate to 2 x new output sample rate
1516 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
1517 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
1518 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07001519 }
Eric Laurent3464c012009-08-04 09:45:33 -07001520 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001521 }
1522 }
1523 mParamStatus = status;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001524 mParamCond.signal();
Eric Laurent3464c012009-08-04 09:45:33 -07001525 mWaitWorkCV.wait(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001526 }
1527 return reconfig;
1528}
1529
1530status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
1531{
1532 const size_t SIZE = 256;
1533 char buffer[SIZE];
1534 String8 result;
1535
1536 PlaybackThread::dumpInternals(fd, args);
1537
1538 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
1539 result.append(buffer);
1540 write(fd, result.string(), result.size());
1541 return NO_ERROR;
1542}
1543
1544// ----------------------------------------------------------------------------
1545AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output)
1546 : PlaybackThread(audioFlinger, output),
1547 mLeftVolume (1.0), mRightVolume(1.0)
1548{
1549 mType = PlaybackThread::DIRECT;
1550}
1551
1552AudioFlinger::DirectOutputThread::~DirectOutputThread()
1553{
1554}
1555
1556
1557bool AudioFlinger::DirectOutputThread::threadLoop()
1558{
1559 unsigned long sleepTime = kBufferRecoveryInUsecs;
1560 sp<Track> trackToRemove;
1561 sp<Track> activeTrack;
1562 nsecs_t standbyTime = systemTime();
1563 int8_t *curBuf;
1564 size_t mixBufferSize = mFrameCount*mFrameSize;
1565
1566 while (!exitPending())
1567 {
1568 processConfigEvents();
1569
1570 { // scope for the mLock
1571
1572 Mutex::Autolock _l(mLock);
1573
1574 if (checkForNewParameters_l()) {
1575 mixBufferSize = mFrameCount*mFrameSize;
1576 }
1577
1578 // put audio hardware into standby after short delay
1579 if UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
1580 mSuspended) {
1581 // wait until we have something to do...
1582 if (!mStandby) {
1583 LOGV("Audio hardware entering standby, mixer %p\n", this);
1584 mOutput->standby();
1585 mStandby = true;
1586 mBytesWritten = 0;
1587 }
1588
1589 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
1590 // we're about to wait, flush the binder command buffer
1591 IPCThreadState::self()->flushCommands();
1592
1593 if (exitPending()) break;
1594
1595 LOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
1596 mWaitWorkCV.wait(mLock);
1597 LOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
1598
1599 if (mMasterMute == false) {
1600 char value[PROPERTY_VALUE_MAX];
1601 property_get("ro.audio.silent", value, "0");
1602 if (atoi(value)) {
1603 LOGD("Silence is golden");
1604 setMasterMute(true);
1605 }
1606 }
1607
1608 standbyTime = systemTime() + kStandbyTimeInNsecs;
1609 continue;
1610 }
1611 }
1612
1613 // find out which tracks need to be processed
1614 if (mActiveTracks.size() != 0) {
1615 sp<Track> t = mActiveTracks[0].promote();
1616 if (t == 0) continue;
1617
1618 Track* const track = t.get();
1619 audio_track_cblk_t* cblk = track->cblk();
1620
1621 // The first time a track is added we wait
1622 // for all its buffers to be filled before processing it
1623 if (cblk->framesReady() && (track->isReady() || track->isStopped()) &&
1624 !track->isPaused())
1625 {
1626 //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
1627
1628 // compute volume for this track
1629 float left, right;
1630 if (track->isMuted() || mMasterMute || track->isPausing() ||
1631 mStreamTypes[track->type()].mute) {
1632 left = right = 0;
1633 if (track->isPausing()) {
1634 track->setPaused();
1635 }
1636 } else {
1637 float typeVolume = mStreamTypes[track->type()].volume;
1638 float v = mMasterVolume * typeVolume;
1639 float v_clamped = v * cblk->volume[0];
1640 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
1641 left = v_clamped/MAX_GAIN;
1642 v_clamped = v * cblk->volume[1];
1643 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
1644 right = v_clamped/MAX_GAIN;
1645 }
1646
1647 if (left != mLeftVolume || right != mRightVolume) {
1648 mOutput->setVolume(left, right);
1649 left = mLeftVolume;
1650 right = mRightVolume;
1651 }
1652
1653 if (track->mFillingUpStatus == Track::FS_FILLED) {
1654 track->mFillingUpStatus = Track::FS_ACTIVE;
1655 if (track->mState == TrackBase::RESUMING) {
1656 track->mState = TrackBase::ACTIVE;
1657 }
1658 }
1659
1660 // reset retry count
1661 track->mRetryCount = kMaxTrackRetries;
1662 activeTrack = t;
1663 } else {
1664 //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
1665 if (track->isStopped()) {
1666 track->reset();
1667 }
1668 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
1669 // We have consumed all the buffers of this track.
1670 // Remove it from the list of active tracks.
1671 trackToRemove = track;
1672 } else {
1673 // No buffers for this track. Give it a few chances to
1674 // fill a buffer, then remove it from active list.
1675 if (--(track->mRetryCount) <= 0) {
1676 LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
1677 trackToRemove = track;
1678 }
1679
1680 // For tracks using static shared memry buffer, make sure that we have
1681 // written enough data to audio hardware before disabling the track
1682 // NOTE: this condition with arrive before track->mRetryCount <= 0 so we
1683 // don't care about code removing track from active list above.
1684 if ((track->mSharedBuffer != 0) && (mBytesWritten < mMinBytesToWrite)) {
1685 activeTrack = t;
1686 }
1687 }
1688 }
1689 }
1690
1691 // remove all the tracks that need to be...
1692 if (UNLIKELY(trackToRemove != 0)) {
1693 mActiveTracks.remove(trackToRemove);
1694 if (trackToRemove->isTerminated()) {
1695 mTracks.remove(trackToRemove);
1696 deleteTrackName_l(trackToRemove->mName);
1697 }
1698 }
1699 }
1700
1701 if (activeTrack != 0) {
1702 AudioBufferProvider::Buffer buffer;
1703 size_t frameCount = mFrameCount;
1704 curBuf = (int8_t *)mMixBuffer;
1705 // output audio to hardware
1706 mLastWriteTime = systemTime();
1707 mInWrite = true;
1708 while(frameCount) {
1709 buffer.frameCount = frameCount;
1710 activeTrack->getNextBuffer(&buffer);
1711 if (UNLIKELY(buffer.raw == 0)) {
1712 memset(curBuf, 0, frameCount * mFrameSize);
1713 break;
1714 }
1715 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
1716 frameCount -= buffer.frameCount;
1717 curBuf += buffer.frameCount * mFrameSize;
1718 activeTrack->releaseBuffer(&buffer);
1719 }
1720 if (mSuspended) {
1721 usleep(kMaxBufferRecoveryInUsecs);
1722 } else {
1723 int bytesWritten = (int)mOutput->write(mMixBuffer, mixBufferSize);
1724 if (bytesWritten) mBytesWritten += bytesWritten;
1725 mNumWrites++;
1726 mInWrite = false;
1727 mStandby = false;
1728 nsecs_t temp = systemTime();
1729 standbyTime = temp + kStandbyTimeInNsecs;
1730 sleepTime = kBufferRecoveryInUsecs;
1731 }
1732 } else {
1733 // There was nothing to mix this round, which means all
1734 // active tracks were late. Sleep a little bit to give
1735 // them another chance. If we're too late, the audio
1736 // hardware will zero-fill for us.
1737 //LOGV("no buffers - usleep(%lu)", sleepTime);
1738 usleep(sleepTime);
1739 if (sleepTime < kMaxBufferRecoveryInUsecs) {
1740 sleepTime += kBufferRecoveryInUsecs;
1741 }
1742 }
1743
1744 // finally let go of removed track, without the lock held
1745 // since we can't guarantee the destructors won't acquire that
1746 // same lock.
1747 trackToRemove.clear();
1748 activeTrack.clear();
1749 }
1750
1751 if (!mStandby) {
1752 mOutput->standby();
1753 }
1754 sendConfigEvent(AudioSystem::OUTPUT_CLOSED);
1755 processConfigEvents();
1756
1757 LOGV("DirectOutputThread %p exiting", this);
1758 return false;
1759}
1760
1761// getTrackName_l() must be called with ThreadBase::mLock held
1762int AudioFlinger::DirectOutputThread::getTrackName_l()
1763{
1764 return 0;
1765}
1766
1767// deleteTrackName_l() must be called with ThreadBase::mLock held
1768void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
1769{
1770}
1771
1772// checkForNewParameters_l() must be called with ThreadBase::mLock held
1773bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
1774{
1775 bool reconfig = false;
1776
Eric Laurent3464c012009-08-04 09:45:33 -07001777 while (!mNewParameters.isEmpty()) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07001778 status_t status = NO_ERROR;
Eric Laurent3464c012009-08-04 09:45:33 -07001779 String8 keyValuePair = mNewParameters[0];
1780 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001781 int value;
Eric Laurent3464c012009-08-04 09:45:33 -07001782
1783 mNewParameters.removeAt(0);
1784
Eric Laurent9d91ad52009-07-17 12:17:14 -07001785 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
1786 // do not accept frame count changes if tracks are open as the track buffer
1787 // size depends on frame count and correct behavior would not be garantied
1788 // if frame count is changed after track creation
1789 if (!mTracks.isEmpty()) {
1790 status = INVALID_OPERATION;
1791 } else {
1792 reconfig = true;
1793 }
1794 }
1795 if (status == NO_ERROR) {
Eric Laurent3464c012009-08-04 09:45:33 -07001796 status = mOutput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001797 if (!mStandby && status == INVALID_OPERATION) {
1798 mOutput->standby();
1799 mStandby = true;
1800 mBytesWritten = 0;
Eric Laurent3464c012009-08-04 09:45:33 -07001801 status = mOutput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001802 }
1803 if (status == NO_ERROR && reconfig) {
1804 readOutputParameters();
Eric Laurent3464c012009-08-04 09:45:33 -07001805 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001806 }
1807 }
1808 mParamStatus = status;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001809 mParamCond.signal();
Eric Laurent3464c012009-08-04 09:45:33 -07001810 mWaitWorkCV.wait(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001811 }
1812 return reconfig;
The Android Open Source Projecte41dd752009-01-22 00:13:42 -08001813}
1814
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001815// ----------------------------------------------------------------------------
1816
Eric Laurent9d91ad52009-07-17 12:17:14 -07001817AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread)
1818 : MixerThread(audioFlinger, mainThread->getOutput())
1819{
1820 mType = PlaybackThread::DUPLICATING;
1821 addOutputTrack(mainThread);
1822}
1823
1824AudioFlinger::DuplicatingThread::~DuplicatingThread()
1825{
1826 mOutputTracks.clear();
1827}
1828
1829bool AudioFlinger::DuplicatingThread::threadLoop()
1830{
1831 unsigned long sleepTime = kBufferRecoveryInUsecs;
1832 int16_t* curBuf = mMixBuffer;
1833 Vector< sp<Track> > tracksToRemove;
1834 size_t enabledTracks = 0;
1835 nsecs_t standbyTime = systemTime();
1836 size_t mixBufferSize = mFrameCount*mFrameSize;
1837 SortedVector< sp<OutputTrack> > outputTracks;
1838
1839 while (!exitPending())
1840 {
1841 processConfigEvents();
1842
1843 enabledTracks = 0;
1844 { // scope for the mLock
1845
1846 Mutex::Autolock _l(mLock);
1847
1848 if (checkForNewParameters_l()) {
1849 mixBufferSize = mFrameCount*mFrameSize;
1850 }
1851
1852 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1853
1854 for (size_t i = 0; i < mOutputTracks.size(); i++) {
1855 outputTracks.add(mOutputTracks[i]);
1856 }
1857
1858 // put audio hardware into standby after short delay
1859 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1860 mSuspended) {
1861 if (!mStandby) {
1862 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07001863 outputTracks[i]->stop();
Eric Laurent9d91ad52009-07-17 12:17:14 -07001864 }
1865 mStandby = true;
1866 mBytesWritten = 0;
1867 }
1868
1869 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1870 // we're about to wait, flush the binder command buffer
1871 IPCThreadState::self()->flushCommands();
1872 outputTracks.clear();
1873
1874 if (exitPending()) break;
1875
1876 LOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
1877 mWaitWorkCV.wait(mLock);
1878 LOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
1879 if (mMasterMute == false) {
1880 char value[PROPERTY_VALUE_MAX];
1881 property_get("ro.audio.silent", value, "0");
1882 if (atoi(value)) {
1883 LOGD("Silence is golden");
1884 setMasterMute(true);
1885 }
1886 }
1887
1888 standbyTime = systemTime() + kStandbyTimeInNsecs;
1889 sleepTime = kBufferRecoveryInUsecs;
1890 continue;
1891 }
1892 }
1893
1894 enabledTracks = prepareTracks_l(activeTracks, &tracksToRemove);
1895 }
1896
1897 bool mustSleep = true;
1898 if (LIKELY(enabledTracks)) {
1899 // mix buffers...
1900 mAudioMixer->process(curBuf);
1901 if (!mSuspended) {
1902 for (size_t i = 0; i < outputTracks.size(); i++) {
1903 outputTracks[i]->write(curBuf, mFrameCount);
Eric Laurentf5aba822009-08-10 23:22:32 -07001904 mustSleep = false;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001905 }
1906 mStandby = false;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001907 mBytesWritten += mixBufferSize;
1908 }
1909 } else {
1910 // flush remaining overflow buffers in output tracks
1911 for (size_t i = 0; i < outputTracks.size(); i++) {
1912 if (outputTracks[i]->isActive()) {
1913 outputTracks[i]->write(curBuf, 0);
1914 standbyTime = systemTime() + kStandbyTimeInNsecs;
1915 mustSleep = false;
1916 }
1917 }
1918 }
1919 if (mustSleep) {
1920// LOGV("threadLoop() sleeping %d", sleepTime);
1921 usleep(sleepTime);
1922 if (sleepTime < kMaxBufferRecoveryInUsecs) {
1923 sleepTime += kBufferRecoveryInUsecs;
1924 }
1925 } else {
1926 sleepTime = kBufferRecoveryInUsecs;
1927 }
1928
1929 // finally let go of all our tracks, without the lock held
1930 // since we can't guarantee the destructors won't acquire that
1931 // same lock.
1932 tracksToRemove.clear();
1933 outputTracks.clear();
1934 }
1935
Eric Laurentf5aba822009-08-10 23:22:32 -07001936 { // scope for the mLock
1937
1938 Mutex::Autolock _l(mLock);
1939 if (!mStandby) {
1940 LOGV("DuplicatingThread() exiting out of standby");
1941 for (size_t i = 0; i < mOutputTracks.size(); i++) {
1942 mOutputTracks[i]->destroy();
1943 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07001944 }
1945 }
1946
1947 sendConfigEvent(AudioSystem::OUTPUT_CLOSED);
1948 processConfigEvents();
1949
1950 return false;
1951}
1952
1953void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
1954{
1955 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
1956 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
1957 mSampleRate,
1958 mFormat,
1959 mChannelCount,
1960 frameCount);
Eric Laurentf5aba822009-08-10 23:22:32 -07001961 if (outputTrack->cblk() != NULL) {
1962 thread->setStreamVolume(AudioSystem::NUM_STREAM_TYPES, 1.0f);
1963 mOutputTracks.add(outputTrack);
1964 LOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
1965 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07001966}
1967
1968void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
1969{
1970 Mutex::Autolock _l(mLock);
1971 for (size_t i = 0; i < mOutputTracks.size(); i++) {
1972 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
Eric Laurentf5aba822009-08-10 23:22:32 -07001973 mOutputTracks[i]->destroy();
Eric Laurent9d91ad52009-07-17 12:17:14 -07001974 mOutputTracks.removeAt(i);
1975 return;
1976 }
1977 }
1978 LOGV("removeOutputTrack(): unkonwn thread: %p", thread);
1979}
1980
1981
1982// ----------------------------------------------------------------------------
1983
The Android Open Source Project22f8def2009-03-09 11:52:12 -07001984// TrackBase constructor must be called with AudioFlinger::mLock held
Eric Laurent9d91ad52009-07-17 12:17:14 -07001985AudioFlinger::ThreadBase::TrackBase::TrackBase(
1986 const wp<ThreadBase>& thread,
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001987 const sp<Client>& client,
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001988 uint32_t sampleRate,
1989 int format,
1990 int channelCount,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08001991 int frameCount,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001992 uint32_t flags,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08001993 const sp<IMemory>& sharedBuffer)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001994 : RefBase(),
Eric Laurent9d91ad52009-07-17 12:17:14 -07001995 mThread(thread),
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001996 mClient(client),
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08001997 mFrameCount(0),
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001998 mState(IDLE),
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08001999 mClientTid(-1),
2000 mFormat(format),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002001 mFlags(flags & ~SYSTEM_FLAGS_MASK)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002002{
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002003 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
2004
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002005 // LOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002006 size_t size = sizeof(audio_track_cblk_t);
2007 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
2008 if (sharedBuffer == 0) {
2009 size += bufferSize;
2010 }
2011
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002012 if (client != NULL) {
2013 mCblkMemory = client->heap()->allocate(size);
2014 if (mCblkMemory != 0) {
2015 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
2016 if (mCblk) { // construct the shared structure in-place.
2017 new(mCblk) audio_track_cblk_t();
2018 // clear all buffers
2019 mCblk->frameCount = frameCount;
Eric Laurent0bac5382009-07-07 07:10:45 -07002020 mCblk->sampleRate = sampleRate;
2021 mCblk->channels = (uint8_t)channelCount;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002022 if (sharedBuffer == 0) {
2023 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2024 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2025 // Force underrun condition to avoid false underrun callback until first data is
2026 // written to buffer
2027 mCblk->flowControlFlag = 1;
2028 } else {
2029 mBuffer = sharedBuffer->pointer();
2030 }
2031 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002032 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002033 } else {
2034 LOGE("not enough memory for AudioTrack size=%u", size);
2035 client->heap()->dump("AudioTrack");
2036 return;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002037 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002038 } else {
2039 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
2040 if (mCblk) { // construct the shared structure in-place.
2041 new(mCblk) audio_track_cblk_t();
2042 // clear all buffers
2043 mCblk->frameCount = frameCount;
Eric Laurent0bac5382009-07-07 07:10:45 -07002044 mCblk->sampleRate = sampleRate;
2045 mCblk->channels = (uint8_t)channelCount;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002046 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2047 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2048 // Force underrun condition to avoid false underrun callback until first data is
2049 // written to buffer
2050 mCblk->flowControlFlag = 1;
2051 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
2052 }
2053 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002054}
2055
Eric Laurent9d91ad52009-07-17 12:17:14 -07002056AudioFlinger::PlaybackThread::TrackBase::~TrackBase()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002057{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002058 if (mCblk) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07002059 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
2060 if (mClient == NULL) {
2061 delete mCblk;
2062 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002063 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002064 mCblkMemory.clear(); // and free the shared memory
2065 mClient.clear();
2066}
2067
Eric Laurent9d91ad52009-07-17 12:17:14 -07002068void AudioFlinger::PlaybackThread::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002069{
2070 buffer->raw = 0;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002071 mFrameCount = buffer->frameCount;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002072 step();
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002073 buffer->frameCount = 0;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002074}
2075
Eric Laurent9d91ad52009-07-17 12:17:14 -07002076bool AudioFlinger::PlaybackThread::TrackBase::step() {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002077 bool result;
2078 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002079
2080 result = cblk->stepServer(mFrameCount);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002081 if (!result) {
2082 LOGV("stepServer failed acquiring cblk mutex");
2083 mFlags |= STEPSERVER_FAILED;
2084 }
2085 return result;
2086}
2087
Eric Laurent9d91ad52009-07-17 12:17:14 -07002088void AudioFlinger::PlaybackThread::TrackBase::reset() {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002089 audio_track_cblk_t* cblk = this->cblk();
2090
2091 cblk->user = 0;
2092 cblk->server = 0;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002093 cblk->userBase = 0;
2094 cblk->serverBase = 0;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002095 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002096 LOGV("TrackBase::reset");
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002097}
2098
Eric Laurent9d91ad52009-07-17 12:17:14 -07002099sp<IMemory> AudioFlinger::PlaybackThread::TrackBase::getCblk() const
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002100{
2101 return mCblkMemory;
2102}
2103
Eric Laurent9d91ad52009-07-17 12:17:14 -07002104int AudioFlinger::PlaybackThread::TrackBase::sampleRate() const {
The Android Open Source Project4f68be12009-03-18 17:39:46 -07002105 return (int)mCblk->sampleRate;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002106}
2107
Eric Laurent9d91ad52009-07-17 12:17:14 -07002108int AudioFlinger::PlaybackThread::TrackBase::channelCount() const {
Eric Laurent0bac5382009-07-07 07:10:45 -07002109 return (int)mCblk->channels;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002110}
2111
Eric Laurent9d91ad52009-07-17 12:17:14 -07002112void* AudioFlinger::PlaybackThread::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002113 audio_track_cblk_t* cblk = this->cblk();
Eric Laurent9d91ad52009-07-17 12:17:14 -07002114 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
2115 int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002116
2117 // Check validity of returned pointer in case the track control block would have been corrupted.
Eric Laurent9d91ad52009-07-17 12:17:14 -07002118 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
2119 ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
The Android Open Source Project4f68be12009-03-18 17:39:46 -07002120 LOGE("TrackBase::getBuffer buffer out of range:\n start: %p, end %p , mBuffer %p mBufferEnd %p\n \
2121 server %d, serverBase %d, user %d, userBase %d, channels %d",
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002122 bufferStart, bufferEnd, mBuffer, mBufferEnd,
The Android Open Source Project4f68be12009-03-18 17:39:46 -07002123 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, cblk->channels);
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002124 return 0;
2125 }
2126
2127 return bufferStart;
2128}
2129
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002130// ----------------------------------------------------------------------------
2131
Eric Laurent9d91ad52009-07-17 12:17:14 -07002132// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
2133AudioFlinger::PlaybackThread::Track::Track(
2134 const wp<ThreadBase>& thread,
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002135 const sp<Client>& client,
2136 int streamType,
2137 uint32_t sampleRate,
2138 int format,
2139 int channelCount,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002140 int frameCount,
2141 const sp<IMemory>& sharedBuffer)
Eric Laurent9d91ad52009-07-17 12:17:14 -07002142 : TrackBase(thread, client, sampleRate, format, channelCount, frameCount, 0, sharedBuffer),
2143 mMute(false), mSharedBuffer(sharedBuffer), mName(-1)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002144{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002145 sp<ThreadBase> baseThread = thread.promote();
2146 if (baseThread != 0) {
2147 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
2148 mName = playbackThread->getTrackName_l();
2149 }
2150 LOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2151 if (mName < 0) {
2152 LOGE("no more track names available");
2153 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002154 mVolume[0] = 1.0f;
2155 mVolume[1] = 1.0f;
Eric Laurent570dd0b2009-05-22 09:18:15 -07002156 mStreamType = streamType;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002157 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
2158 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
2159 mCblk->frameSize = AudioSystem::isLinearPCM(format) ? channelCount * sizeof(int16_t) : sizeof(int8_t);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002160}
2161
Eric Laurent9d91ad52009-07-17 12:17:14 -07002162AudioFlinger::PlaybackThread::Track::~Track()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002163{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002164 LOGV("PlaybackThread::Track destructor");
2165 sp<ThreadBase> thread = mThread.promote();
2166 if (thread != 0) {
2167 Mutex::Autolock _l(thread->mLock);
2168 mState = TERMINATED;
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002169 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002170}
2171
Eric Laurent9d91ad52009-07-17 12:17:14 -07002172void AudioFlinger::PlaybackThread::Track::destroy()
2173{
2174 // NOTE: destroyTrack_l() can remove a strong reference to this Track
2175 // by removing it from mTracks vector, so there is a risk that this Tracks's
2176 // desctructor is called. As the destructor needs to lock mLock,
2177 // we must acquire a strong reference on this Track before locking mLock
2178 // here so that the destructor is called only when exiting this function.
2179 // On the other hand, as long as Track::destroy() is only called by
2180 // TrackHandle destructor, the TrackHandle still holds a strong ref on
2181 // this Track with its member mTrack.
2182 sp<Track> keep(this);
2183 { // scope for mLock
2184 sp<ThreadBase> thread = mThread.promote();
2185 if (thread != 0) {
2186 Mutex::Autolock _l(thread->mLock);
2187 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2188 playbackThread->destroyTrack_l(this);
2189 }
2190 }
2191}
2192
2193void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002194{
2195 snprintf(buffer, size, " %5d %5d %3u %3u %3u %3u %1d %1d %1d %5u %5u %5u %04x %04x\n",
2196 mName - AudioMixer::TRACK0,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002197 (mClient == NULL) ? getpid() : mClient->pid(),
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002198 mStreamType,
2199 mFormat,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002200 mCblk->channels,
2201 mFrameCount,
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002202 mState,
2203 mMute,
2204 mFillingUpStatus,
2205 mCblk->sampleRate,
2206 mCblk->volume[0],
2207 mCblk->volume[1],
2208 mCblk->server,
2209 mCblk->user);
2210}
2211
Eric Laurent9d91ad52009-07-17 12:17:14 -07002212status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002213{
2214 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002215 uint32_t framesReady;
2216 uint32_t framesReq = buffer->frameCount;
2217
2218 // Check if last stepServer failed, try to step now
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002219 if (mFlags & TrackBase::STEPSERVER_FAILED) {
2220 if (!step()) goto getNextBuffer_exit;
2221 LOGV("stepServer recovered");
2222 mFlags &= ~TrackBase::STEPSERVER_FAILED;
2223 }
2224
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002225 framesReady = cblk->framesReady();
2226
2227 if (LIKELY(framesReady)) {
2228 uint32_t s = cblk->server;
2229 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
2230
2231 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
2232 if (framesReq > framesReady) {
2233 framesReq = framesReady;
2234 }
2235 if (s + framesReq > bufferEnd) {
2236 framesReq = bufferEnd - s;
2237 }
2238
2239 buffer->raw = getBuffer(s, framesReq);
2240 if (buffer->raw == 0) goto getNextBuffer_exit;
2241
2242 buffer->frameCount = framesReq;
2243 return NO_ERROR;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002244 }
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002245
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002246getNextBuffer_exit:
2247 buffer->raw = 0;
2248 buffer->frameCount = 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002249 LOGV("getNextBuffer() no more data");
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002250 return NOT_ENOUGH_DATA;
2251}
2252
Eric Laurent9d91ad52009-07-17 12:17:14 -07002253bool AudioFlinger::PlaybackThread::Track::isReady() const {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002254 if (mFillingUpStatus != FS_FILLING) return true;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002255
2256 if (mCblk->framesReady() >= mCblk->frameCount ||
2257 mCblk->forceReady) {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002258 mFillingUpStatus = FS_FILLED;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002259 mCblk->forceReady = 0;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002260 return true;
2261 }
2262 return false;
2263}
2264
Eric Laurent9d91ad52009-07-17 12:17:14 -07002265status_t AudioFlinger::PlaybackThread::Track::start()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002266{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002267 LOGV("start(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2268 sp<ThreadBase> thread = mThread.promote();
2269 if (thread != 0) {
2270 Mutex::Autolock _l(thread->mLock);
2271 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2272 playbackThread->addTrack_l(this);
2273 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002274 return NO_ERROR;
2275}
2276
Eric Laurent9d91ad52009-07-17 12:17:14 -07002277void AudioFlinger::PlaybackThread::Track::stop()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002278{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002279 LOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2280 sp<ThreadBase> thread = mThread.promote();
2281 if (thread != 0) {
2282 Mutex::Autolock _l(thread->mLock);
2283 if (mState > STOPPED) {
2284 mState = STOPPED;
2285 // If the track is not active (PAUSED and buffers full), flush buffers
2286 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2287 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
2288 reset();
2289 }
2290 LOGV("(> STOPPED) => STOPPED (%d)", mName);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002291 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002292 }
2293}
2294
Eric Laurent9d91ad52009-07-17 12:17:14 -07002295void AudioFlinger::PlaybackThread::Track::pause()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002296{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002297 LOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurent9d91ad52009-07-17 12:17:14 -07002298 sp<ThreadBase> thread = mThread.promote();
2299 if (thread != 0) {
2300 Mutex::Autolock _l(thread->mLock);
2301 if (mState == ACTIVE || mState == RESUMING) {
2302 mState = PAUSING;
2303 LOGV("ACTIVE/RESUMING => PAUSING (%d)", mName);
2304 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002305 }
2306}
2307
Eric Laurent9d91ad52009-07-17 12:17:14 -07002308void AudioFlinger::PlaybackThread::Track::flush()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002309{
2310 LOGV("flush(%d)", mName);
Eric Laurent9d91ad52009-07-17 12:17:14 -07002311 sp<ThreadBase> thread = mThread.promote();
2312 if (thread != 0) {
2313 Mutex::Autolock _l(thread->mLock);
2314 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
2315 return;
2316 }
2317 // No point remaining in PAUSED state after a flush => go to
2318 // STOPPED state
2319 mState = STOPPED;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002320
Eric Laurent9d91ad52009-07-17 12:17:14 -07002321 mCblk->lock.lock();
2322 // NOTE: reset() will reset cblk->user and cblk->server with
2323 // the risk that at the same time, the AudioMixer is trying to read
2324 // data. In this case, getNextBuffer() would return a NULL pointer
2325 // as audio buffer => the AudioMixer code MUST always test that pointer
2326 // returned by getNextBuffer() is not NULL!
2327 reset();
2328 mCblk->lock.unlock();
2329 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002330}
2331
Eric Laurent9d91ad52009-07-17 12:17:14 -07002332void AudioFlinger::PlaybackThread::Track::reset()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002333{
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002334 // Do not reset twice to avoid discarding data written just after a flush and before
2335 // the audioflinger thread detects the track is stopped.
2336 if (!mResetDone) {
2337 TrackBase::reset();
2338 // Force underrun condition to avoid false underrun callback until first data is
2339 // written to buffer
2340 mCblk->flowControlFlag = 1;
2341 mCblk->forceReady = 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002342 mFillingUpStatus = FS_FILLING;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002343 mResetDone = true;
2344 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002345}
2346
Eric Laurent9d91ad52009-07-17 12:17:14 -07002347void AudioFlinger::PlaybackThread::Track::mute(bool muted)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002348{
2349 mMute = muted;
2350}
2351
Eric Laurent9d91ad52009-07-17 12:17:14 -07002352void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002353{
2354 mVolume[0] = left;
2355 mVolume[1] = right;
2356}
2357
2358// ----------------------------------------------------------------------------
2359
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002360// RecordTrack constructor must be called with AudioFlinger::mLock held
Eric Laurent9d91ad52009-07-17 12:17:14 -07002361AudioFlinger::RecordThread::RecordTrack::RecordTrack(
2362 const wp<ThreadBase>& thread,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002363 const sp<Client>& client,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002364 uint32_t sampleRate,
2365 int format,
2366 int channelCount,
2367 int frameCount,
2368 uint32_t flags)
Eric Laurent9d91ad52009-07-17 12:17:14 -07002369 : TrackBase(thread, client, sampleRate, format,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002370 channelCount, frameCount, flags, 0),
Eric Laurent9d91ad52009-07-17 12:17:14 -07002371 mOverflow(false)
2372{
2373 LOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
2374 if (format == AudioSystem::PCM_16_BIT) {
2375 mCblk->frameSize = channelCount * sizeof(int16_t);
2376 } else if (format == AudioSystem::PCM_8_BIT) {
2377 mCblk->frameSize = channelCount * sizeof(int8_t);
2378 } else {
2379 mCblk->frameSize = sizeof(int8_t);
2380 }
2381}
2382
2383AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002384{
2385}
2386
Eric Laurent9d91ad52009-07-17 12:17:14 -07002387status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002388{
2389 audio_track_cblk_t* cblk = this->cblk();
2390 uint32_t framesAvail;
2391 uint32_t framesReq = buffer->frameCount;
2392
2393 // Check if last stepServer failed, try to step now
2394 if (mFlags & TrackBase::STEPSERVER_FAILED) {
2395 if (!step()) goto getNextBuffer_exit;
2396 LOGV("stepServer recovered");
2397 mFlags &= ~TrackBase::STEPSERVER_FAILED;
2398 }
2399
2400 framesAvail = cblk->framesAvailable_l();
2401
2402 if (LIKELY(framesAvail)) {
2403 uint32_t s = cblk->server;
2404 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
2405
2406 if (framesReq > framesAvail) {
2407 framesReq = framesAvail;
2408 }
2409 if (s + framesReq > bufferEnd) {
2410 framesReq = bufferEnd - s;
2411 }
2412
2413 buffer->raw = getBuffer(s, framesReq);
2414 if (buffer->raw == 0) goto getNextBuffer_exit;
2415
2416 buffer->frameCount = framesReq;
2417 return NO_ERROR;
2418 }
2419
2420getNextBuffer_exit:
2421 buffer->raw = 0;
2422 buffer->frameCount = 0;
2423 return NOT_ENOUGH_DATA;
2424}
2425
Eric Laurent9d91ad52009-07-17 12:17:14 -07002426status_t AudioFlinger::RecordThread::RecordTrack::start()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002427{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002428 sp<ThreadBase> thread = mThread.promote();
2429 if (thread != 0) {
2430 RecordThread *recordThread = (RecordThread *)thread.get();
2431 return recordThread->start(this);
2432 }
2433 return NO_INIT;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002434}
2435
Eric Laurent9d91ad52009-07-17 12:17:14 -07002436void AudioFlinger::RecordThread::RecordTrack::stop()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002437{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002438 sp<ThreadBase> thread = mThread.promote();
2439 if (thread != 0) {
2440 RecordThread *recordThread = (RecordThread *)thread.get();
2441 recordThread->stop(this);
2442 TrackBase::reset();
2443 // Force overerrun condition to avoid false overrun callback until first data is
2444 // read from buffer
2445 mCblk->flowControlFlag = 1;
2446 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002447}
2448
2449
2450// ----------------------------------------------------------------------------
2451
Eric Laurent9d91ad52009-07-17 12:17:14 -07002452AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
2453 const wp<ThreadBase>& thread,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002454 uint32_t sampleRate,
2455 int format,
2456 int channelCount,
2457 int frameCount)
Eric Laurent9d91ad52009-07-17 12:17:14 -07002458 : Track(thread, NULL, AudioSystem::NUM_STREAM_TYPES, sampleRate, format, channelCount, frameCount, NULL),
2459 mActive(false)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002460{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002461
2462 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
Eric Laurentf5aba822009-08-10 23:22:32 -07002463 if (mCblk != NULL) {
2464 mCblk->out = 1;
2465 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
2466 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
2467 mOutBuffer.frameCount = 0;
2468 mWaitTimeMs = (playbackThread->frameCount() * 2 * 1000) / playbackThread->sampleRate();
2469 playbackThread->mTracks.add(this);
2470 LOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, mCblk->frameCount %d, mCblk->sampleRate %d, mCblk->channels %d mBufferEnd %p mWaitTimeMs %d",
2471 mCblk, mBuffer, mCblk->buffers, mCblk->frameCount, mCblk->sampleRate, mCblk->channels, mBufferEnd, mWaitTimeMs);
2472 } else {
2473 LOGW("Error creating output track on thread %p", playbackThread);
2474 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002475}
2476
Eric Laurent9d91ad52009-07-17 12:17:14 -07002477AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002478{
Eric Laurentf5aba822009-08-10 23:22:32 -07002479 clearBufferQueue();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002480}
2481
Eric Laurent9d91ad52009-07-17 12:17:14 -07002482status_t AudioFlinger::PlaybackThread::OutputTrack::start()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002483{
2484 status_t status = Track::start();
Eric Laurent9d91ad52009-07-17 12:17:14 -07002485 if (status != NO_ERROR) {
2486 return status;
2487 }
2488
2489 mActive = true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002490 mRetryCount = 127;
2491 return status;
2492}
2493
Eric Laurent9d91ad52009-07-17 12:17:14 -07002494void AudioFlinger::PlaybackThread::OutputTrack::stop()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002495{
2496 Track::stop();
2497 clearBufferQueue();
2498 mOutBuffer.frameCount = 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002499 mActive = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002500}
2501
Eric Laurent9d91ad52009-07-17 12:17:14 -07002502bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002503{
2504 Buffer *pInBuffer;
2505 Buffer inBuffer;
2506 uint32_t channels = mCblk->channels;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002507 bool outputBufferFull = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002508 inBuffer.frameCount = frames;
2509 inBuffer.i16 = data;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002510
2511 uint32_t waitTimeLeftMs = mWaitTimeMs;
2512
2513 if (!mActive) {
2514 start();
2515 sp<ThreadBase> thread = mThread.promote();
2516 if (thread != 0) {
2517 MixerThread *mixerThread = (MixerThread *)thread.get();
2518 if (mCblk->frameCount > frames){
2519 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
2520 uint32_t startFrames = (mCblk->frameCount - frames);
2521 pInBuffer = new Buffer;
2522 pInBuffer->mBuffer = new int16_t[startFrames * channels];
2523 pInBuffer->frameCount = startFrames;
2524 pInBuffer->i16 = pInBuffer->mBuffer;
2525 memset(pInBuffer->raw, 0, startFrames * channels * sizeof(int16_t));
2526 mBufferQueue.add(pInBuffer);
2527 } else {
2528 LOGW ("OutputTrack::write() %p no more buffers in queue", this);
2529 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002530 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002531 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002532 }
2533
Eric Laurent9d91ad52009-07-17 12:17:14 -07002534 while (waitTimeLeftMs) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002535 // First write pending buffers, then new data
2536 if (mBufferQueue.size()) {
2537 pInBuffer = mBufferQueue.itemAt(0);
2538 } else {
2539 pInBuffer = &inBuffer;
2540 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002541
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002542 if (pInBuffer->frameCount == 0) {
2543 break;
2544 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002545
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002546 if (mOutBuffer.frameCount == 0) {
2547 mOutBuffer.frameCount = pInBuffer->frameCount;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002548 nsecs_t startTime = systemTime();
2549 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
2550 LOGV ("OutputTrack::write() %p no more output buffers", this);
2551 outputBufferFull = true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002552 break;
2553 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002554 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
2555// LOGV("OutputTrack::write() waitTimeMs %d waitTimeLeftMs %d", waitTimeMs, waitTimeLeftMs)
2556 if (waitTimeLeftMs >= waitTimeMs) {
2557 waitTimeLeftMs -= waitTimeMs;
2558 } else {
2559 waitTimeLeftMs = 0;
2560 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002561 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002562
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002563 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
2564 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channels * sizeof(int16_t));
2565 mCblk->stepUser(outFrames);
2566 pInBuffer->frameCount -= outFrames;
2567 pInBuffer->i16 += outFrames * channels;
2568 mOutBuffer.frameCount -= outFrames;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002569 mOutBuffer.i16 += outFrames * channels;
2570
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002571 if (pInBuffer->frameCount == 0) {
2572 if (mBufferQueue.size()) {
2573 mBufferQueue.removeAt(0);
2574 delete [] pInBuffer->mBuffer;
2575 delete pInBuffer;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002576 LOGV("OutputTrack::write() %p released overflow buffer %d", this, mBufferQueue.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002577 } else {
2578 break;
2579 }
2580 }
2581 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002582
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002583 // If we could not write all frames, allocate a buffer and queue it for next time.
2584 if (inBuffer.frameCount) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07002585 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002586 pInBuffer = new Buffer;
2587 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channels];
2588 pInBuffer->frameCount = inBuffer.frameCount;
2589 pInBuffer->i16 = pInBuffer->mBuffer;
2590 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channels * sizeof(int16_t));
2591 mBufferQueue.add(pInBuffer);
Eric Laurent9d91ad52009-07-17 12:17:14 -07002592 LOGV("OutputTrack::write() %p adding overflow buffer %d", this, mBufferQueue.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002593 } else {
Eric Laurent9d91ad52009-07-17 12:17:14 -07002594 LOGW("OutputTrack::write() %p no more overflow buffers", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002595 }
2596 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002597
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002598 // Calling write() with a 0 length buffer, means that no more data will be written:
Eric Laurent9d91ad52009-07-17 12:17:14 -07002599 // 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 -08002600 // by output mixer.
Eric Laurent9d91ad52009-07-17 12:17:14 -07002601 if (frames == 0 && mBufferQueue.size() == 0) {
2602 if (mCblk->user < mCblk->frameCount) {
2603 frames = mCblk->frameCount - mCblk->user;
2604 pInBuffer = new Buffer;
2605 pInBuffer->mBuffer = new int16_t[frames * channels];
2606 pInBuffer->frameCount = frames;
2607 pInBuffer->i16 = pInBuffer->mBuffer;
2608 memset(pInBuffer->raw, 0, frames * channels * sizeof(int16_t));
2609 mBufferQueue.add(pInBuffer);
2610 } else {
2611 stop();
2612 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002613 }
2614
Eric Laurent9d91ad52009-07-17 12:17:14 -07002615 return outputBufferFull;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002616}
2617
Eric Laurent9d91ad52009-07-17 12:17:14 -07002618status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002619{
2620 int active;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002621 status_t result;
2622 audio_track_cblk_t* cblk = mCblk;
2623 uint32_t framesReq = buffer->frameCount;
2624
Eric Laurent9d91ad52009-07-17 12:17:14 -07002625// LOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002626 buffer->frameCount = 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002627
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002628 uint32_t framesAvail = cblk->framesAvailable();
2629
Eric Laurent9d91ad52009-07-17 12:17:14 -07002630
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002631 if (framesAvail == 0) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07002632 Mutex::Autolock _l(cblk->lock);
2633 goto start_loop_here;
2634 while (framesAvail == 0) {
2635 active = mActive;
2636 if (UNLIKELY(!active)) {
2637 LOGV("Not active and NO_MORE_BUFFERS");
2638 return AudioTrack::NO_MORE_BUFFERS;
2639 }
2640 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
2641 if (result != NO_ERROR) {
2642 return AudioTrack::NO_MORE_BUFFERS;
2643 }
2644 // read the server count again
2645 start_loop_here:
2646 framesAvail = cblk->framesAvailable_l();
2647 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002648 }
2649
Eric Laurent9d91ad52009-07-17 12:17:14 -07002650// if (framesAvail < framesReq) {
2651// return AudioTrack::NO_MORE_BUFFERS;
2652// }
2653
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002654 if (framesReq > framesAvail) {
2655 framesReq = framesAvail;
2656 }
2657
2658 uint32_t u = cblk->user;
2659 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
2660
2661 if (u + framesReq > bufferEnd) {
2662 framesReq = bufferEnd - u;
2663 }
2664
2665 buffer->frameCount = framesReq;
2666 buffer->raw = (void *)cblk->buffer(u);
2667 return NO_ERROR;
2668}
2669
2670
Eric Laurent9d91ad52009-07-17 12:17:14 -07002671void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002672{
2673 size_t size = mBufferQueue.size();
2674 Buffer *pBuffer;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002675
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002676 for (size_t i = 0; i < size; i++) {
2677 pBuffer = mBufferQueue.itemAt(i);
2678 delete [] pBuffer->mBuffer;
2679 delete pBuffer;
2680 }
2681 mBufferQueue.clear();
2682}
2683
2684// ----------------------------------------------------------------------------
2685
2686AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
2687 : RefBase(),
2688 mAudioFlinger(audioFlinger),
2689 mMemoryDealer(new MemoryDealer(1024*1024)),
2690 mPid(pid)
2691{
2692 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
2693}
2694
2695AudioFlinger::Client::~Client()
2696{
2697 mAudioFlinger->removeClient(mPid);
2698}
2699
2700const sp<MemoryDealer>& AudioFlinger::Client::heap() const
2701{
2702 return mMemoryDealer;
2703}
2704
2705// ----------------------------------------------------------------------------
2706
Eric Laurent9d91ad52009-07-17 12:17:14 -07002707AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002708 : BnAudioTrack(),
2709 mTrack(track)
2710{
2711}
2712
2713AudioFlinger::TrackHandle::~TrackHandle() {
2714 // just stop the track on deletion, associated resources
2715 // will be freed from the main thread once all pending buffers have
2716 // been played. Unless it's not in the active track list, in which
2717 // case we free everything now...
2718 mTrack->destroy();
2719}
2720
2721status_t AudioFlinger::TrackHandle::start() {
2722 return mTrack->start();
2723}
2724
2725void AudioFlinger::TrackHandle::stop() {
2726 mTrack->stop();
2727}
2728
2729void AudioFlinger::TrackHandle::flush() {
2730 mTrack->flush();
2731}
2732
2733void AudioFlinger::TrackHandle::mute(bool e) {
2734 mTrack->mute(e);
2735}
2736
2737void AudioFlinger::TrackHandle::pause() {
2738 mTrack->pause();
2739}
2740
2741void AudioFlinger::TrackHandle::setVolume(float left, float right) {
2742 mTrack->setVolume(left, right);
2743}
2744
2745sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
2746 return mTrack->getCblk();
2747}
2748
2749status_t AudioFlinger::TrackHandle::onTransact(
2750 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2751{
2752 return BnAudioTrack::onTransact(code, data, reply, flags);
2753}
2754
2755// ----------------------------------------------------------------------------
2756
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002757sp<IAudioRecord> AudioFlinger::openRecord(
2758 pid_t pid,
Eric Laurente0e9ecc2009-07-28 08:44:33 -07002759 int input,
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002760 uint32_t sampleRate,
2761 int format,
2762 int channelCount,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002763 int frameCount,
2764 uint32_t flags,
2765 status_t *status)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002766{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002767 sp<RecordThread::RecordTrack> recordTrack;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002768 sp<RecordHandle> recordHandle;
2769 sp<Client> client;
2770 wp<Client> wclient;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002771 status_t lStatus;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002772 RecordThread *thread;
2773 size_t inFrameCount;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002774
2775 // check calling permissions
2776 if (!recordingAllowed()) {
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002777 lStatus = PERMISSION_DENIED;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002778 goto Exit;
2779 }
2780
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002781 // add client to list
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002782 { // scope for mLock
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002783 Mutex::Autolock _l(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07002784 thread = checkRecordThread_l(input);
2785 if (thread == NULL) {
2786 lStatus = BAD_VALUE;
2787 goto Exit;
2788 }
2789
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002790 wclient = mClients.valueFor(pid);
2791 if (wclient != NULL) {
2792 client = wclient.promote();
2793 } else {
2794 client = new Client(this, pid);
2795 mClients.add(pid, client);
2796 }
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002797
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002798 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent9d91ad52009-07-17 12:17:14 -07002799 recordTrack = new RecordThread::RecordTrack(thread, client, sampleRate,
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002800 format, channelCount, frameCount, flags);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002801 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002802 if (recordTrack->getCblk() == NULL) {
2803 recordTrack.clear();
2804 lStatus = NO_MEMORY;
2805 goto Exit;
2806 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002807
2808 // return to handle to client
2809 recordHandle = new RecordHandle(recordTrack);
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002810 lStatus = NO_ERROR;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002811
2812Exit:
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002813 if (status) {
2814 *status = lStatus;
2815 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002816 return recordHandle;
2817}
2818
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002819// ----------------------------------------------------------------------------
2820
Eric Laurent9d91ad52009-07-17 12:17:14 -07002821AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002822 : BnAudioRecord(),
2823 mRecordTrack(recordTrack)
2824{
2825}
2826
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002827AudioFlinger::RecordHandle::~RecordHandle() {
2828 stop();
2829}
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002830
2831status_t AudioFlinger::RecordHandle::start() {
2832 LOGV("RecordHandle::start()");
2833 return mRecordTrack->start();
2834}
2835
2836void AudioFlinger::RecordHandle::stop() {
2837 LOGV("RecordHandle::stop()");
2838 mRecordTrack->stop();
2839}
2840
2841sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
2842 return mRecordTrack->getCblk();
2843}
2844
2845status_t AudioFlinger::RecordHandle::onTransact(
2846 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2847{
2848 return BnAudioRecord::onTransact(code, data, reply, flags);
2849}
2850
2851// ----------------------------------------------------------------------------
2852
Eric Laurent9d91ad52009-07-17 12:17:14 -07002853AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger, AudioStreamIn *input, uint32_t sampleRate, uint32_t channels) :
2854 ThreadBase(audioFlinger),
2855 mInput(input), mResampler(0), mRsmpOutBuffer(0), mRsmpInBuffer(0)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002856{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002857 mReqChannelCount = AudioSystem::popCount(channels);
2858 mReqSampleRate = sampleRate;
2859 readInputParameters();
2860 sendConfigEvent(AudioSystem::INPUT_OPENED);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002861}
2862
Eric Laurent9d91ad52009-07-17 12:17:14 -07002863
2864AudioFlinger::RecordThread::~RecordThread()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002865{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002866 delete[] mRsmpInBuffer;
2867 if (mResampler != 0) {
2868 delete mResampler;
2869 delete[] mRsmpOutBuffer;
2870 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002871}
2872
Eric Laurent9d91ad52009-07-17 12:17:14 -07002873void AudioFlinger::RecordThread::onFirstRef()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002874{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002875 const size_t SIZE = 256;
2876 char buffer[SIZE];
2877
2878 snprintf(buffer, SIZE, "Record Thread %p", this);
2879
2880 run(buffer, PRIORITY_URGENT_AUDIO);
2881}
2882bool AudioFlinger::RecordThread::threadLoop()
2883{
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002884 AudioBufferProvider::Buffer buffer;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002885 sp<RecordTrack> activeTrack;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002886
2887 // start recording
2888 while (!exitPending()) {
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002889
Eric Laurent9d91ad52009-07-17 12:17:14 -07002890 processConfigEvents();
2891
2892 { // scope for mLock
2893 Mutex::Autolock _l(mLock);
2894 checkForNewParameters_l();
2895 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
2896 if (!mStandby) {
2897 mInput->standby();
2898 mStandby = true;
2899 }
2900
2901 if (exitPending()) break;
2902
2903 LOGV("RecordThread: loop stopping");
2904 // go to sleep
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002905 mWaitWorkCV.wait(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07002906 LOGV("RecordThread: loop starting");
2907 continue;
2908 }
2909 if (mActiveTrack != 0) {
2910 if (mActiveTrack->mState == TrackBase::PAUSING) {
2911 mActiveTrack.clear();
2912 mStartStopCond.broadcast();
2913 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
2914 mRsmpInIndex = mFrameCount;
2915 if (mReqChannelCount != mActiveTrack->channelCount()) {
2916 mActiveTrack.clear();
2917 } else {
Eric Laurent9e7b8192009-08-10 02:41:54 -07002918 mActiveTrack->mState = TrackBase::ACTIVE;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002919 }
2920 mStartStopCond.broadcast();
2921 }
2922 mStandby = false;
2923 }
2924 }
2925
2926 if (mActiveTrack != 0) {
2927 buffer.frameCount = mFrameCount;
2928 if (LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
2929 size_t framesOut = buffer.frameCount;
2930 if (mResampler == 0) {
2931 // no resampling
2932 while (framesOut) {
2933 size_t framesIn = mFrameCount - mRsmpInIndex;
2934 if (framesIn) {
2935 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
2936 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
2937 if (framesIn > framesOut)
2938 framesIn = framesOut;
2939 mRsmpInIndex += framesIn;
2940 framesOut -= framesIn;
2941 if (mChannelCount == mReqChannelCount ||
2942 mFormat != AudioSystem::PCM_16_BIT) {
2943 memcpy(dst, src, framesIn * mFrameSize);
2944 } else {
2945 int16_t *src16 = (int16_t *)src;
2946 int16_t *dst16 = (int16_t *)dst;
2947 if (mChannelCount == 1) {
2948 while (framesIn--) {
2949 *dst16++ = *src16;
2950 *dst16++ = *src16++;
2951 }
2952 } else {
2953 while (framesIn--) {
2954 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
2955 src16 += 2;
2956 }
2957 }
2958 }
2959 }
2960 if (framesOut && mFrameCount == mRsmpInIndex) {
2961 ssize_t bytesRead;
2962 if (framesOut == mFrameCount &&
2963 (mChannelCount == mReqChannelCount || mFormat != AudioSystem::PCM_16_BIT)) {
2964 bytesRead = mInput->read(buffer.raw, mInputBytes);
2965 framesOut = 0;
2966 } else {
2967 bytesRead = mInput->read(mRsmpInBuffer, mInputBytes);
2968 mRsmpInIndex = 0;
2969 }
2970 if (bytesRead < 0) {
2971 LOGE("Error reading audio input");
2972 sleep(1);
2973 mRsmpInIndex = mFrameCount;
2974 framesOut = 0;
2975 buffer.frameCount = 0;
2976 }
2977 }
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002978 }
2979 } else {
Eric Laurent9d91ad52009-07-17 12:17:14 -07002980 // resampling
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002981
Eric Laurent9d91ad52009-07-17 12:17:14 -07002982 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
2983 // alter output frame count as if we were expecting stereo samples
2984 if (mChannelCount == 1 && mReqChannelCount == 1) {
2985 framesOut >>= 1;
2986 }
2987 mResampler->resample(mRsmpOutBuffer, framesOut, this);
2988 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
2989 // are 32 bit aligned which should be always true.
2990 if (mChannelCount == 2 && mReqChannelCount == 1) {
2991 AudioMixer::ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
2992 // the resampler always outputs stereo samples: do post stereo to mono conversion
2993 int16_t *src = (int16_t *)mRsmpOutBuffer;
2994 int16_t *dst = buffer.i16;
2995 while (framesOut--) {
2996 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
2997 src += 2;
2998 }
2999 } else {
3000 AudioMixer::ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
3001 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003002
Eric Laurent9d91ad52009-07-17 12:17:14 -07003003 }
3004 mActiveTrack->releaseBuffer(&buffer);
3005 mActiveTrack->overflow();
3006 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003007 // client isn't retrieving buffers fast enough
3008 else {
Eric Laurent9d91ad52009-07-17 12:17:14 -07003009 if (!mActiveTrack->setOverflow())
3010 LOGW("RecordThread: buffer overflow");
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003011 // Release the processor for a while before asking for a new buffer.
3012 // This will give the application more chance to read from the buffer and
3013 // clear the overflow.
3014 usleep(5000);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003015 }
3016 }
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003017 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003018
Eric Laurent9d91ad52009-07-17 12:17:14 -07003019 if (!mStandby) {
3020 mInput->standby();
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003021 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003022 mActiveTrack.clear();
3023
3024 sendConfigEvent(AudioSystem::INPUT_CLOSED);
3025 processConfigEvents();
3026
3027 LOGV("RecordThread %p exiting", this);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003028 return false;
3029}
3030
Eric Laurent9d91ad52009-07-17 12:17:14 -07003031status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003032{
Eric Laurent9d91ad52009-07-17 12:17:14 -07003033 LOGV("RecordThread::start");
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003034 AutoMutex lock(&mLock);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003035
Eric Laurent9d91ad52009-07-17 12:17:14 -07003036 if (mActiveTrack != 0) {
3037 if (recordTrack != mActiveTrack.get()) return -EBUSY;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003038
Eric Laurent9d91ad52009-07-17 12:17:14 -07003039 if (mActiveTrack->mState == TrackBase::PAUSING) mActiveTrack->mState = TrackBase::RESUMING;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003040
Eric Laurent9d91ad52009-07-17 12:17:14 -07003041 return NO_ERROR;
3042 }
3043
3044 mActiveTrack = recordTrack;
3045 mActiveTrack->mState = TrackBase::RESUMING;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003046 // signal thread to start
3047 LOGV("Signal record thread");
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003048 mWaitWorkCV.signal();
Eric Laurent9d91ad52009-07-17 12:17:14 -07003049 mStartStopCond.wait(mLock);
3050 if (mActiveTrack != 0) {
3051 LOGV("Record started OK");
3052 return NO_ERROR;
3053 } else {
3054 LOGV("Record failed to start");
3055 return BAD_VALUE;
3056 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003057}
3058
Eric Laurent9d91ad52009-07-17 12:17:14 -07003059void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
3060 LOGV("RecordThread::stop");
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003061 AutoMutex lock(&mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003062 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
3063 mActiveTrack->mState = TrackBase::PAUSING;
3064 mStartStopCond.wait(mLock);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003065 }
3066}
3067
Eric Laurent9d91ad52009-07-17 12:17:14 -07003068status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003069{
3070 const size_t SIZE = 256;
3071 char buffer[SIZE];
3072 String8 result;
3073 pid_t pid = 0;
3074
Eric Laurent9d91ad52009-07-17 12:17:14 -07003075 if (mActiveTrack != 0 && mActiveTrack->mClient != 0) {
3076 snprintf(buffer, SIZE, "Record client pid: %d\n", mActiveTrack->mClient->pid());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003077 result.append(buffer);
3078 } else {
3079 result.append("No record client\n");
3080 }
3081 write(fd, result.string(), result.size());
3082 return NO_ERROR;
3083}
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003084
Eric Laurent9d91ad52009-07-17 12:17:14 -07003085status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3086{
3087 size_t framesReq = buffer->frameCount;
3088 size_t framesReady = mFrameCount - mRsmpInIndex;
3089 int channelCount;
3090
3091 if (framesReady == 0) {
3092 ssize_t bytesRead = mInput->read(mRsmpInBuffer, mInputBytes);
3093 if (bytesRead < 0) {
3094 LOGE("RecordThread::getNextBuffer() Error reading audio input");
3095 sleep(1);
3096 buffer->raw = 0;
3097 buffer->frameCount = 0;
3098 return NOT_ENOUGH_DATA;
3099 }
3100 mRsmpInIndex = 0;
3101 framesReady = mFrameCount;
3102 }
3103
3104 if (framesReq > framesReady) {
3105 framesReq = framesReady;
3106 }
3107
3108 if (mChannelCount == 1 && mReqChannelCount == 2) {
3109 channelCount = 1;
3110 } else {
3111 channelCount = 2;
3112 }
3113 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
3114 buffer->frameCount = framesReq;
3115 return NO_ERROR;
3116}
3117
3118void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3119{
3120 mRsmpInIndex += buffer->frameCount;
3121 buffer->frameCount = 0;
3122}
3123
3124bool AudioFlinger::RecordThread::checkForNewParameters_l()
3125{
3126 bool reconfig = false;
3127
Eric Laurent3464c012009-08-04 09:45:33 -07003128 while (!mNewParameters.isEmpty()) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07003129 status_t status = NO_ERROR;
Eric Laurent3464c012009-08-04 09:45:33 -07003130 String8 keyValuePair = mNewParameters[0];
3131 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003132 int value;
3133 int reqFormat = mFormat;
3134 int reqSamplingRate = mReqSampleRate;
3135 int reqChannelCount = mReqChannelCount;
Eric Laurent3464c012009-08-04 09:45:33 -07003136
3137 mNewParameters.removeAt(0);
3138
Eric Laurent9d91ad52009-07-17 12:17:14 -07003139 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3140 reqSamplingRate = value;
3141 reconfig = true;
3142 }
3143 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
3144 reqFormat = value;
3145 reconfig = true;
3146 }
3147 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
3148 reqChannelCount = AudioSystem::popCount(value);
3149 reconfig = true;
3150 }
3151 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3152 // do not accept frame count changes if tracks are open as the track buffer
3153 // size depends on frame count and correct behavior would not be garantied
3154 // if frame count is changed after track creation
3155 if (mActiveTrack != 0) {
3156 status = INVALID_OPERATION;
3157 } else {
3158 reconfig = true;
3159 }
3160 }
3161 if (status == NO_ERROR) {
Eric Laurent3464c012009-08-04 09:45:33 -07003162 status = mInput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003163 if (status == INVALID_OPERATION) {
3164 mInput->standby();
Eric Laurent3464c012009-08-04 09:45:33 -07003165 status = mInput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003166 }
3167 if (reconfig) {
3168 if (status == BAD_VALUE &&
3169 reqFormat == mInput->format() && reqFormat == AudioSystem::PCM_16_BIT &&
3170 ((int)mInput->sampleRate() <= 2 * reqSamplingRate) &&
3171 (AudioSystem::popCount(mInput->channels()) < 3) && (reqChannelCount < 3)) {
3172 status = NO_ERROR;
3173 }
3174 if (status == NO_ERROR) {
3175 readInputParameters();
Eric Laurent3464c012009-08-04 09:45:33 -07003176 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003177 }
3178 }
3179 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003180 mParamStatus = status;
3181 mParamCond.signal();
Eric Laurent3464c012009-08-04 09:45:33 -07003182 mWaitWorkCV.wait(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003183 }
3184 return reconfig;
3185}
3186
3187String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
3188{
3189 return mInput->getParameters(keys);
3190}
3191
3192void AudioFlinger::RecordThread::audioConfigChanged(int event, int param) {
3193 AudioSystem::OutputDescriptor desc;
3194 void *param2 = 0;
3195
3196 switch (event) {
3197 case AudioSystem::INPUT_OPENED:
3198 case AudioSystem::INPUT_CONFIG_CHANGED:
3199 desc.channels = mChannelCount;
3200 desc.samplingRate = mSampleRate;
3201 desc.format = mFormat;
3202 desc.frameCount = mFrameCount;
3203 desc.latency = 0;
3204 param2 = &desc;
3205 break;
3206
3207 case AudioSystem::INPUT_CLOSED:
3208 default:
3209 break;
3210 }
3211 mAudioFlinger->audioConfigChanged(event, this, param2);
3212}
3213
3214void AudioFlinger::RecordThread::readInputParameters()
3215{
3216 if (mRsmpInBuffer) delete mRsmpInBuffer;
3217 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
3218 if (mResampler) delete mResampler;
3219 mResampler = 0;
3220
3221 mSampleRate = mInput->sampleRate();
3222 mChannelCount = AudioSystem::popCount(mInput->channels());
3223 mFormat = mInput->format();
3224 mFrameSize = mInput->frameSize();
3225 mInputBytes = mInput->bufferSize();
3226 mFrameCount = mInputBytes / mFrameSize;
3227 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
3228
3229 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
3230 {
3231 int channelCount;
3232 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
3233 // stereo to mono post process as the resampler always outputs stereo.
3234 if (mChannelCount == 1 && mReqChannelCount == 2) {
3235 channelCount = 1;
3236 } else {
3237 channelCount = 2;
3238 }
3239 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
3240 mResampler->setSampleRate(mSampleRate);
3241 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
3242 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
3243
3244 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
3245 if (mChannelCount == 1 && mReqChannelCount == 1) {
3246 mFrameCount >>= 1;
3247 }
3248
3249 }
3250 mRsmpInIndex = mFrameCount;
3251}
3252
3253// ----------------------------------------------------------------------------
3254
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003255int AudioFlinger::openOutput(uint32_t *pDevices,
Eric Laurent9d91ad52009-07-17 12:17:14 -07003256 uint32_t *pSamplingRate,
3257 uint32_t *pFormat,
3258 uint32_t *pChannels,
3259 uint32_t *pLatencyMs,
3260 uint32_t flags)
3261{
3262 status_t status;
3263 PlaybackThread *thread = NULL;
3264 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
3265 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
3266 uint32_t format = pFormat ? *pFormat : 0;
3267 uint32_t channels = pChannels ? *pChannels : 0;
3268 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
3269
3270 LOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
3271 pDevices ? *pDevices : 0,
3272 samplingRate,
3273 format,
3274 channels,
3275 flags);
3276
3277 if (pDevices == NULL || *pDevices == 0) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003278 return 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003279 }
3280 Mutex::Autolock _l(mLock);
3281
3282 AudioStreamOut *output = mAudioHardware->openOutputStream(*pDevices,
3283 (int *)&format,
3284 &channels,
3285 &samplingRate,
3286 &status);
3287 LOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
3288 output,
3289 samplingRate,
3290 format,
3291 channels,
3292 status);
3293
3294 mHardwareStatus = AUDIO_HW_IDLE;
3295 if (output != 0) {
3296 if ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) ||
3297 (format != AudioSystem::PCM_16_BIT) ||
3298 (channels != AudioSystem::CHANNEL_OUT_STEREO)) {
3299 thread = new DirectOutputThread(this, output);
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003300 LOGV("openOutput() created direct output: ID %d thread %p", (mNextThreadId + 1), thread);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003301 } else {
3302 thread = new MixerThread(this, output);
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003303 LOGV("openOutput() created mixer output: ID %d thread %p", (mNextThreadId + 1), thread);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003304 }
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003305 mPlaybackThreads.add(++mNextThreadId, thread);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003306
3307 if (pSamplingRate) *pSamplingRate = samplingRate;
3308 if (pFormat) *pFormat = format;
3309 if (pChannels) *pChannels = channels;
3310 if (pLatencyMs) *pLatencyMs = thread->latency();
3311 }
3312
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003313 return mNextThreadId;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003314}
3315
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003316int AudioFlinger::openDuplicateOutput(int output1, int output2)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003317{
3318 Mutex::Autolock _l(mLock);
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003319 MixerThread *thread1 = checkMixerThread_l(output1);
3320 MixerThread *thread2 = checkMixerThread_l(output2);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003321
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003322 if (thread1 == NULL || thread2 == NULL) {
3323 LOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
3324 return 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003325 }
3326
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003327
3328 DuplicatingThread *thread = new DuplicatingThread(this, thread1);
3329 thread->addOutputTrack(thread2);
3330 mPlaybackThreads.add(++mNextThreadId, thread);
3331 return mNextThreadId;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003332}
3333
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003334status_t AudioFlinger::closeOutput(int output)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003335{
Eric Laurentdae20d92009-08-04 08:37:05 -07003336 // keep strong reference on the playback thread so that
3337 // it is not destroyed while exit() is executed
3338 sp <PlaybackThread> thread;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003339 {
3340 Mutex::Autolock _l(mLock);
3341 thread = checkPlaybackThread_l(output);
3342 if (thread == NULL) {
3343 return BAD_VALUE;
3344 }
3345
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003346 LOGV("closeOutput() %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003347
3348 if (thread->type() == PlaybackThread::MIXER) {
3349 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003350 if (mPlaybackThreads.valueAt(i)->type() == PlaybackThread::DUPLICATING) {
3351 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Eric Laurentdae20d92009-08-04 08:37:05 -07003352 dupThread->removeOutputTrack((MixerThread *)thread.get());
Eric Laurent9d91ad52009-07-17 12:17:14 -07003353 }
3354 }
3355 }
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003356 mPlaybackThreads.removeItem(output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003357 }
3358 thread->exit();
3359
Eric Laurentdae20d92009-08-04 08:37:05 -07003360 if (thread->type() != PlaybackThread::DUPLICATING) {
3361 mAudioHardware->closeOutputStream(thread->getOutput());
3362 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003363 return NO_ERROR;
3364}
3365
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003366status_t AudioFlinger::suspendOutput(int output)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003367{
3368 Mutex::Autolock _l(mLock);
3369 PlaybackThread *thread = checkPlaybackThread_l(output);
3370
3371 if (thread == NULL) {
3372 return BAD_VALUE;
3373 }
3374
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003375 LOGV("suspendOutput() %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003376 thread->suspend();
3377
3378 return NO_ERROR;
3379}
3380
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003381status_t AudioFlinger::restoreOutput(int output)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003382{
3383 Mutex::Autolock _l(mLock);
3384 PlaybackThread *thread = checkPlaybackThread_l(output);
3385
3386 if (thread == NULL) {
3387 return BAD_VALUE;
3388 }
3389
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003390 LOGV("restoreOutput() %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003391
3392 thread->restore();
3393
3394 return NO_ERROR;
3395}
3396
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003397int AudioFlinger::openInput(uint32_t *pDevices,
Eric Laurent9d91ad52009-07-17 12:17:14 -07003398 uint32_t *pSamplingRate,
3399 uint32_t *pFormat,
3400 uint32_t *pChannels,
3401 uint32_t acoustics)
3402{
3403 status_t status;
3404 RecordThread *thread = NULL;
3405 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
3406 uint32_t format = pFormat ? *pFormat : 0;
3407 uint32_t channels = pChannels ? *pChannels : 0;
3408 uint32_t reqSamplingRate = samplingRate;
3409 uint32_t reqFormat = format;
3410 uint32_t reqChannels = channels;
3411
3412 if (pDevices == NULL || *pDevices == 0) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003413 return 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003414 }
3415 Mutex::Autolock _l(mLock);
3416
3417 AudioStreamIn *input = mAudioHardware->openInputStream(*pDevices,
3418 (int *)&format,
3419 &channels,
3420 &samplingRate,
3421 &status,
3422 (AudioSystem::audio_in_acoustics)acoustics);
3423 LOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
3424 input,
3425 samplingRate,
3426 format,
3427 channels,
3428 acoustics,
3429 status);
3430
3431 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
3432 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
3433 // or stereo to mono conversions on 16 bit PCM inputs.
3434 if (input == 0 && status == BAD_VALUE &&
3435 reqFormat == format && format == AudioSystem::PCM_16_BIT &&
3436 (samplingRate <= 2 * reqSamplingRate) &&
3437 (AudioSystem::popCount(channels) < 3) && (AudioSystem::popCount(reqChannels) < 3)) {
3438 LOGV("openInput() reopening with proposed sampling rate and channels");
3439 input = mAudioHardware->openInputStream(*pDevices,
3440 (int *)&format,
3441 &channels,
3442 &samplingRate,
3443 &status,
3444 (AudioSystem::audio_in_acoustics)acoustics);
3445 }
3446
3447 if (input != 0) {
3448 // Start record thread
3449 thread = new RecordThread(this, input, reqSamplingRate, reqChannels);
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003450 mRecordThreads.add(++mNextThreadId, thread);
3451 LOGV("openInput() created record thread: ID %d thread %p", mNextThreadId, thread);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003452 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
3453 if (pFormat) *pFormat = format;
3454 if (pChannels) *pChannels = reqChannels;
3455
3456 input->standby();
3457 }
3458
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003459 return mNextThreadId;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003460}
3461
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003462status_t AudioFlinger::closeInput(int input)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003463{
Eric Laurentdae20d92009-08-04 08:37:05 -07003464 // keep strong reference on the record thread so that
3465 // it is not destroyed while exit() is executed
3466 sp <RecordThread> thread;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003467 {
3468 Mutex::Autolock _l(mLock);
3469 thread = checkRecordThread_l(input);
3470 if (thread == NULL) {
3471 return BAD_VALUE;
3472 }
3473
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003474 LOGV("closeInput() %d", input);
3475 mRecordThreads.removeItem(input);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003476 }
3477 thread->exit();
3478
Eric Laurentdae20d92009-08-04 08:37:05 -07003479 mAudioHardware->closeInputStream(thread->getInput());
3480
Eric Laurent9d91ad52009-07-17 12:17:14 -07003481 return NO_ERROR;
3482}
3483
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003484status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003485{
3486 Mutex::Autolock _l(mLock);
3487 MixerThread *dstThread = checkMixerThread_l(output);
3488 if (dstThread == NULL) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003489 LOGW("setStreamOutput() bad output id %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003490 return BAD_VALUE;
3491 }
3492
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003493 LOGV("setStreamOutput() stream %d to output %d", stream, output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003494
3495 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003496 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent9d91ad52009-07-17 12:17:14 -07003497 if (thread != dstThread &&
3498 thread->type() != PlaybackThread::DIRECT) {
3499 MixerThread *srcThread = (MixerThread *)thread;
3500 SortedVector < sp<MixerThread::Track> > tracks;
3501 SortedVector < wp<MixerThread::Track> > activeTracks;
3502 srcThread->getTracks(tracks, activeTracks, stream);
3503 if (tracks.size()) {
3504 dstThread->putTracks(tracks, activeTracks);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003505 }
Eric Laurentd55d1792009-07-28 06:11:55 -07003506 dstThread->sendConfigEvent(AudioSystem::STREAM_CONFIG_CHANGED, stream);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003507 }
3508 }
3509
3510 return NO_ERROR;
3511}
3512
3513// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003514AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
Eric Laurent9d91ad52009-07-17 12:17:14 -07003515{
3516 PlaybackThread *thread = NULL;
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003517 if (mPlaybackThreads.indexOfKey(output) >= 0) {
3518 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
Eric Laurent9d91ad52009-07-17 12:17:14 -07003519 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003520 return thread;
3521}
3522
3523// checkMixerThread_l() must be called with AudioFlinger::mLock held
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003524AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
Eric Laurent9d91ad52009-07-17 12:17:14 -07003525{
3526 PlaybackThread *thread = checkPlaybackThread_l(output);
3527 if (thread != NULL) {
3528 if (thread->type() == PlaybackThread::DIRECT) {
3529 thread = NULL;
3530 }
3531 }
3532 return (MixerThread *)thread;
3533}
3534
3535// checkRecordThread_l() must be called with AudioFlinger::mLock held
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003536AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
Eric Laurent9d91ad52009-07-17 12:17:14 -07003537{
3538 RecordThread *thread = NULL;
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003539 if (mRecordThreads.indexOfKey(input) >= 0) {
3540 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
Eric Laurent9d91ad52009-07-17 12:17:14 -07003541 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003542 return thread;
3543}
3544
3545// ----------------------------------------------------------------------------
3546
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003547status_t AudioFlinger::onTransact(
3548 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3549{
3550 return BnAudioFlinger::onTransact(code, data, reply, flags);
3551}
3552
3553// ----------------------------------------------------------------------------
Eric Laurent9d91ad52009-07-17 12:17:14 -07003554
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003555void AudioFlinger::instantiate() {
3556 defaultServiceManager()->addService(
3557 String16("media.audio_flinger"), new AudioFlinger());
3558}
3559
3560}; // namespace android