blob: d019097c5c9d90ebe0e9062564a6e5c7ba2f2718 [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;
1515 }
Eric Laurent3464c012009-08-04 09:45:33 -07001516 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001517 }
1518 }
1519 mParamStatus = status;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001520 mParamCond.signal();
Eric Laurent3464c012009-08-04 09:45:33 -07001521 mWaitWorkCV.wait(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001522 }
1523 return reconfig;
1524}
1525
1526status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
1527{
1528 const size_t SIZE = 256;
1529 char buffer[SIZE];
1530 String8 result;
1531
1532 PlaybackThread::dumpInternals(fd, args);
1533
1534 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
1535 result.append(buffer);
1536 write(fd, result.string(), result.size());
1537 return NO_ERROR;
1538}
1539
1540// ----------------------------------------------------------------------------
1541AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output)
1542 : PlaybackThread(audioFlinger, output),
1543 mLeftVolume (1.0), mRightVolume(1.0)
1544{
1545 mType = PlaybackThread::DIRECT;
1546}
1547
1548AudioFlinger::DirectOutputThread::~DirectOutputThread()
1549{
1550}
1551
1552
1553bool AudioFlinger::DirectOutputThread::threadLoop()
1554{
1555 unsigned long sleepTime = kBufferRecoveryInUsecs;
1556 sp<Track> trackToRemove;
1557 sp<Track> activeTrack;
1558 nsecs_t standbyTime = systemTime();
1559 int8_t *curBuf;
1560 size_t mixBufferSize = mFrameCount*mFrameSize;
1561
1562 while (!exitPending())
1563 {
1564 processConfigEvents();
1565
1566 { // scope for the mLock
1567
1568 Mutex::Autolock _l(mLock);
1569
1570 if (checkForNewParameters_l()) {
1571 mixBufferSize = mFrameCount*mFrameSize;
1572 }
1573
1574 // put audio hardware into standby after short delay
1575 if UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
1576 mSuspended) {
1577 // wait until we have something to do...
1578 if (!mStandby) {
1579 LOGV("Audio hardware entering standby, mixer %p\n", this);
1580 mOutput->standby();
1581 mStandby = true;
1582 mBytesWritten = 0;
1583 }
1584
1585 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
1586 // we're about to wait, flush the binder command buffer
1587 IPCThreadState::self()->flushCommands();
1588
1589 if (exitPending()) break;
1590
1591 LOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
1592 mWaitWorkCV.wait(mLock);
1593 LOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
1594
1595 if (mMasterMute == false) {
1596 char value[PROPERTY_VALUE_MAX];
1597 property_get("ro.audio.silent", value, "0");
1598 if (atoi(value)) {
1599 LOGD("Silence is golden");
1600 setMasterMute(true);
1601 }
1602 }
1603
1604 standbyTime = systemTime() + kStandbyTimeInNsecs;
1605 continue;
1606 }
1607 }
1608
1609 // find out which tracks need to be processed
1610 if (mActiveTracks.size() != 0) {
1611 sp<Track> t = mActiveTracks[0].promote();
1612 if (t == 0) continue;
1613
1614 Track* const track = t.get();
1615 audio_track_cblk_t* cblk = track->cblk();
1616
1617 // The first time a track is added we wait
1618 // for all its buffers to be filled before processing it
1619 if (cblk->framesReady() && (track->isReady() || track->isStopped()) &&
1620 !track->isPaused())
1621 {
1622 //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
1623
1624 // compute volume for this track
1625 float left, right;
1626 if (track->isMuted() || mMasterMute || track->isPausing() ||
1627 mStreamTypes[track->type()].mute) {
1628 left = right = 0;
1629 if (track->isPausing()) {
1630 track->setPaused();
1631 }
1632 } else {
1633 float typeVolume = mStreamTypes[track->type()].volume;
1634 float v = mMasterVolume * typeVolume;
1635 float v_clamped = v * cblk->volume[0];
1636 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
1637 left = v_clamped/MAX_GAIN;
1638 v_clamped = v * cblk->volume[1];
1639 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
1640 right = v_clamped/MAX_GAIN;
1641 }
1642
1643 if (left != mLeftVolume || right != mRightVolume) {
1644 mOutput->setVolume(left, right);
1645 left = mLeftVolume;
1646 right = mRightVolume;
1647 }
1648
1649 if (track->mFillingUpStatus == Track::FS_FILLED) {
1650 track->mFillingUpStatus = Track::FS_ACTIVE;
1651 if (track->mState == TrackBase::RESUMING) {
1652 track->mState = TrackBase::ACTIVE;
1653 }
1654 }
1655
1656 // reset retry count
1657 track->mRetryCount = kMaxTrackRetries;
1658 activeTrack = t;
1659 } else {
1660 //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
1661 if (track->isStopped()) {
1662 track->reset();
1663 }
1664 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
1665 // We have consumed all the buffers of this track.
1666 // Remove it from the list of active tracks.
1667 trackToRemove = track;
1668 } else {
1669 // No buffers for this track. Give it a few chances to
1670 // fill a buffer, then remove it from active list.
1671 if (--(track->mRetryCount) <= 0) {
1672 LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
1673 trackToRemove = track;
1674 }
1675
1676 // For tracks using static shared memry buffer, make sure that we have
1677 // written enough data to audio hardware before disabling the track
1678 // NOTE: this condition with arrive before track->mRetryCount <= 0 so we
1679 // don't care about code removing track from active list above.
1680 if ((track->mSharedBuffer != 0) && (mBytesWritten < mMinBytesToWrite)) {
1681 activeTrack = t;
1682 }
1683 }
1684 }
1685 }
1686
1687 // remove all the tracks that need to be...
1688 if (UNLIKELY(trackToRemove != 0)) {
1689 mActiveTracks.remove(trackToRemove);
1690 if (trackToRemove->isTerminated()) {
1691 mTracks.remove(trackToRemove);
1692 deleteTrackName_l(trackToRemove->mName);
1693 }
1694 }
1695 }
1696
1697 if (activeTrack != 0) {
1698 AudioBufferProvider::Buffer buffer;
1699 size_t frameCount = mFrameCount;
1700 curBuf = (int8_t *)mMixBuffer;
1701 // output audio to hardware
1702 mLastWriteTime = systemTime();
1703 mInWrite = true;
1704 while(frameCount) {
1705 buffer.frameCount = frameCount;
1706 activeTrack->getNextBuffer(&buffer);
1707 if (UNLIKELY(buffer.raw == 0)) {
1708 memset(curBuf, 0, frameCount * mFrameSize);
1709 break;
1710 }
1711 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
1712 frameCount -= buffer.frameCount;
1713 curBuf += buffer.frameCount * mFrameSize;
1714 activeTrack->releaseBuffer(&buffer);
1715 }
1716 if (mSuspended) {
1717 usleep(kMaxBufferRecoveryInUsecs);
1718 } else {
1719 int bytesWritten = (int)mOutput->write(mMixBuffer, mixBufferSize);
1720 if (bytesWritten) mBytesWritten += bytesWritten;
1721 mNumWrites++;
1722 mInWrite = false;
1723 mStandby = false;
1724 nsecs_t temp = systemTime();
1725 standbyTime = temp + kStandbyTimeInNsecs;
1726 sleepTime = kBufferRecoveryInUsecs;
1727 }
1728 } else {
1729 // There was nothing to mix this round, which means all
1730 // active tracks were late. Sleep a little bit to give
1731 // them another chance. If we're too late, the audio
1732 // hardware will zero-fill for us.
1733 //LOGV("no buffers - usleep(%lu)", sleepTime);
1734 usleep(sleepTime);
1735 if (sleepTime < kMaxBufferRecoveryInUsecs) {
1736 sleepTime += kBufferRecoveryInUsecs;
1737 }
1738 }
1739
1740 // finally let go of removed track, without the lock held
1741 // since we can't guarantee the destructors won't acquire that
1742 // same lock.
1743 trackToRemove.clear();
1744 activeTrack.clear();
1745 }
1746
1747 if (!mStandby) {
1748 mOutput->standby();
1749 }
1750 sendConfigEvent(AudioSystem::OUTPUT_CLOSED);
1751 processConfigEvents();
1752
1753 LOGV("DirectOutputThread %p exiting", this);
1754 return false;
1755}
1756
1757// getTrackName_l() must be called with ThreadBase::mLock held
1758int AudioFlinger::DirectOutputThread::getTrackName_l()
1759{
1760 return 0;
1761}
1762
1763// deleteTrackName_l() must be called with ThreadBase::mLock held
1764void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
1765{
1766}
1767
1768// checkForNewParameters_l() must be called with ThreadBase::mLock held
1769bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
1770{
1771 bool reconfig = false;
1772
Eric Laurent3464c012009-08-04 09:45:33 -07001773 while (!mNewParameters.isEmpty()) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07001774 status_t status = NO_ERROR;
Eric Laurent3464c012009-08-04 09:45:33 -07001775 String8 keyValuePair = mNewParameters[0];
1776 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001777 int value;
Eric Laurent3464c012009-08-04 09:45:33 -07001778
1779 mNewParameters.removeAt(0);
1780
Eric Laurent9d91ad52009-07-17 12:17:14 -07001781 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
1782 // do not accept frame count changes if tracks are open as the track buffer
1783 // size depends on frame count and correct behavior would not be garantied
1784 // if frame count is changed after track creation
1785 if (!mTracks.isEmpty()) {
1786 status = INVALID_OPERATION;
1787 } else {
1788 reconfig = true;
1789 }
1790 }
1791 if (status == NO_ERROR) {
Eric Laurent3464c012009-08-04 09:45:33 -07001792 status = mOutput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001793 if (!mStandby && status == INVALID_OPERATION) {
1794 mOutput->standby();
1795 mStandby = true;
1796 mBytesWritten = 0;
Eric Laurent3464c012009-08-04 09:45:33 -07001797 status = mOutput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001798 }
1799 if (status == NO_ERROR && reconfig) {
1800 readOutputParameters();
Eric Laurent3464c012009-08-04 09:45:33 -07001801 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001802 }
1803 }
1804 mParamStatus = status;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001805 mParamCond.signal();
Eric Laurent3464c012009-08-04 09:45:33 -07001806 mWaitWorkCV.wait(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001807 }
1808 return reconfig;
The Android Open Source Projecte41dd752009-01-22 00:13:42 -08001809}
1810
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001811// ----------------------------------------------------------------------------
1812
Eric Laurent9d91ad52009-07-17 12:17:14 -07001813AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread)
1814 : MixerThread(audioFlinger, mainThread->getOutput())
1815{
1816 mType = PlaybackThread::DUPLICATING;
1817 addOutputTrack(mainThread);
1818}
1819
1820AudioFlinger::DuplicatingThread::~DuplicatingThread()
1821{
1822 mOutputTracks.clear();
1823}
1824
1825bool AudioFlinger::DuplicatingThread::threadLoop()
1826{
1827 unsigned long sleepTime = kBufferRecoveryInUsecs;
1828 int16_t* curBuf = mMixBuffer;
1829 Vector< sp<Track> > tracksToRemove;
1830 size_t enabledTracks = 0;
1831 nsecs_t standbyTime = systemTime();
1832 size_t mixBufferSize = mFrameCount*mFrameSize;
1833 SortedVector< sp<OutputTrack> > outputTracks;
1834
1835 while (!exitPending())
1836 {
1837 processConfigEvents();
1838
1839 enabledTracks = 0;
1840 { // scope for the mLock
1841
1842 Mutex::Autolock _l(mLock);
1843
1844 if (checkForNewParameters_l()) {
1845 mixBufferSize = mFrameCount*mFrameSize;
1846 }
1847
1848 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1849
1850 for (size_t i = 0; i < mOutputTracks.size(); i++) {
1851 outputTracks.add(mOutputTracks[i]);
1852 }
1853
1854 // put audio hardware into standby after short delay
1855 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1856 mSuspended) {
1857 if (!mStandby) {
1858 for (size_t i = 0; i < outputTracks.size(); i++) {
1859 mLock.unlock();
1860 outputTracks[i]->stop();
1861 mLock.lock();
1862 }
1863 mStandby = true;
1864 mBytesWritten = 0;
1865 }
1866
1867 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1868 // we're about to wait, flush the binder command buffer
1869 IPCThreadState::self()->flushCommands();
1870 outputTracks.clear();
1871
1872 if (exitPending()) break;
1873
1874 LOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
1875 mWaitWorkCV.wait(mLock);
1876 LOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
1877 if (mMasterMute == false) {
1878 char value[PROPERTY_VALUE_MAX];
1879 property_get("ro.audio.silent", value, "0");
1880 if (atoi(value)) {
1881 LOGD("Silence is golden");
1882 setMasterMute(true);
1883 }
1884 }
1885
1886 standbyTime = systemTime() + kStandbyTimeInNsecs;
1887 sleepTime = kBufferRecoveryInUsecs;
1888 continue;
1889 }
1890 }
1891
1892 enabledTracks = prepareTracks_l(activeTracks, &tracksToRemove);
1893 }
1894
1895 bool mustSleep = true;
1896 if (LIKELY(enabledTracks)) {
1897 // mix buffers...
1898 mAudioMixer->process(curBuf);
1899 if (!mSuspended) {
1900 for (size_t i = 0; i < outputTracks.size(); i++) {
1901 outputTracks[i]->write(curBuf, mFrameCount);
1902 }
1903 mStandby = false;
1904 mustSleep = false;
1905 mBytesWritten += mixBufferSize;
1906 }
1907 } else {
1908 // flush remaining overflow buffers in output tracks
1909 for (size_t i = 0; i < outputTracks.size(); i++) {
1910 if (outputTracks[i]->isActive()) {
1911 outputTracks[i]->write(curBuf, 0);
1912 standbyTime = systemTime() + kStandbyTimeInNsecs;
1913 mustSleep = false;
1914 }
1915 }
1916 }
1917 if (mustSleep) {
1918// LOGV("threadLoop() sleeping %d", sleepTime);
1919 usleep(sleepTime);
1920 if (sleepTime < kMaxBufferRecoveryInUsecs) {
1921 sleepTime += kBufferRecoveryInUsecs;
1922 }
1923 } else {
1924 sleepTime = kBufferRecoveryInUsecs;
1925 }
1926
1927 // finally let go of all our tracks, without the lock held
1928 // since we can't guarantee the destructors won't acquire that
1929 // same lock.
1930 tracksToRemove.clear();
1931 outputTracks.clear();
1932 }
1933
1934 if (!mStandby) {
1935 for (size_t i = 0; i < outputTracks.size(); i++) {
1936 mLock.unlock();
1937 outputTracks[i]->stop();
1938 mLock.lock();
1939 }
1940 }
1941
1942 sendConfigEvent(AudioSystem::OUTPUT_CLOSED);
1943 processConfigEvents();
1944
1945 return false;
1946}
1947
1948void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
1949{
1950 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
1951 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
1952 mSampleRate,
1953 mFormat,
1954 mChannelCount,
1955 frameCount);
1956 thread->setStreamVolume(AudioSystem::NUM_STREAM_TYPES, 1.0f);
1957 mOutputTracks.add(outputTrack);
1958 LOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
1959}
1960
1961void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
1962{
1963 Mutex::Autolock _l(mLock);
1964 for (size_t i = 0; i < mOutputTracks.size(); i++) {
1965 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
1966 mOutputTracks.removeAt(i);
1967 return;
1968 }
1969 }
1970 LOGV("removeOutputTrack(): unkonwn thread: %p", thread);
1971}
1972
1973
1974// ----------------------------------------------------------------------------
1975
The Android Open Source Project22f8def2009-03-09 11:52:12 -07001976// TrackBase constructor must be called with AudioFlinger::mLock held
Eric Laurent9d91ad52009-07-17 12:17:14 -07001977AudioFlinger::ThreadBase::TrackBase::TrackBase(
1978 const wp<ThreadBase>& thread,
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001979 const sp<Client>& client,
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001980 uint32_t sampleRate,
1981 int format,
1982 int channelCount,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08001983 int frameCount,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001984 uint32_t flags,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08001985 const sp<IMemory>& sharedBuffer)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001986 : RefBase(),
Eric Laurent9d91ad52009-07-17 12:17:14 -07001987 mThread(thread),
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001988 mClient(client),
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08001989 mFrameCount(0),
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001990 mState(IDLE),
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08001991 mClientTid(-1),
1992 mFormat(format),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001993 mFlags(flags & ~SYSTEM_FLAGS_MASK)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001994{
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08001995 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
1996
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001997 // LOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08001998 size_t size = sizeof(audio_track_cblk_t);
1999 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
2000 if (sharedBuffer == 0) {
2001 size += bufferSize;
2002 }
2003
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002004 if (client != NULL) {
2005 mCblkMemory = client->heap()->allocate(size);
2006 if (mCblkMemory != 0) {
2007 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
2008 if (mCblk) { // construct the shared structure in-place.
2009 new(mCblk) audio_track_cblk_t();
2010 // clear all buffers
2011 mCblk->frameCount = frameCount;
Eric Laurent0bac5382009-07-07 07:10:45 -07002012 mCblk->sampleRate = sampleRate;
2013 mCblk->channels = (uint8_t)channelCount;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002014 if (sharedBuffer == 0) {
2015 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2016 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2017 // Force underrun condition to avoid false underrun callback until first data is
2018 // written to buffer
2019 mCblk->flowControlFlag = 1;
2020 } else {
2021 mBuffer = sharedBuffer->pointer();
2022 }
2023 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002024 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002025 } else {
2026 LOGE("not enough memory for AudioTrack size=%u", size);
2027 client->heap()->dump("AudioTrack");
2028 return;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002029 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002030 } else {
2031 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
2032 if (mCblk) { // construct the shared structure in-place.
2033 new(mCblk) audio_track_cblk_t();
2034 // clear all buffers
2035 mCblk->frameCount = frameCount;
Eric Laurent0bac5382009-07-07 07:10:45 -07002036 mCblk->sampleRate = sampleRate;
2037 mCblk->channels = (uint8_t)channelCount;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002038 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2039 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2040 // Force underrun condition to avoid false underrun callback until first data is
2041 // written to buffer
2042 mCblk->flowControlFlag = 1;
2043 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
2044 }
2045 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002046}
2047
Eric Laurent9d91ad52009-07-17 12:17:14 -07002048AudioFlinger::PlaybackThread::TrackBase::~TrackBase()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002049{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002050 if (mCblk) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07002051 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
2052 if (mClient == NULL) {
2053 delete mCblk;
2054 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002055 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002056 mCblkMemory.clear(); // and free the shared memory
2057 mClient.clear();
2058}
2059
Eric Laurent9d91ad52009-07-17 12:17:14 -07002060void AudioFlinger::PlaybackThread::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002061{
2062 buffer->raw = 0;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002063 mFrameCount = buffer->frameCount;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002064 step();
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002065 buffer->frameCount = 0;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002066}
2067
Eric Laurent9d91ad52009-07-17 12:17:14 -07002068bool AudioFlinger::PlaybackThread::TrackBase::step() {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002069 bool result;
2070 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002071
2072 result = cblk->stepServer(mFrameCount);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002073 if (!result) {
2074 LOGV("stepServer failed acquiring cblk mutex");
2075 mFlags |= STEPSERVER_FAILED;
2076 }
2077 return result;
2078}
2079
Eric Laurent9d91ad52009-07-17 12:17:14 -07002080void AudioFlinger::PlaybackThread::TrackBase::reset() {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002081 audio_track_cblk_t* cblk = this->cblk();
2082
2083 cblk->user = 0;
2084 cblk->server = 0;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002085 cblk->userBase = 0;
2086 cblk->serverBase = 0;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002087 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002088 LOGV("TrackBase::reset");
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002089}
2090
Eric Laurent9d91ad52009-07-17 12:17:14 -07002091sp<IMemory> AudioFlinger::PlaybackThread::TrackBase::getCblk() const
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002092{
2093 return mCblkMemory;
2094}
2095
Eric Laurent9d91ad52009-07-17 12:17:14 -07002096int AudioFlinger::PlaybackThread::TrackBase::sampleRate() const {
The Android Open Source Project4f68be12009-03-18 17:39:46 -07002097 return (int)mCblk->sampleRate;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002098}
2099
Eric Laurent9d91ad52009-07-17 12:17:14 -07002100int AudioFlinger::PlaybackThread::TrackBase::channelCount() const {
Eric Laurent0bac5382009-07-07 07:10:45 -07002101 return (int)mCblk->channels;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002102}
2103
Eric Laurent9d91ad52009-07-17 12:17:14 -07002104void* AudioFlinger::PlaybackThread::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002105 audio_track_cblk_t* cblk = this->cblk();
Eric Laurent9d91ad52009-07-17 12:17:14 -07002106 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
2107 int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002108
2109 // Check validity of returned pointer in case the track control block would have been corrupted.
Eric Laurent9d91ad52009-07-17 12:17:14 -07002110 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
2111 ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
The Android Open Source Project4f68be12009-03-18 17:39:46 -07002112 LOGE("TrackBase::getBuffer buffer out of range:\n start: %p, end %p , mBuffer %p mBufferEnd %p\n \
2113 server %d, serverBase %d, user %d, userBase %d, channels %d",
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002114 bufferStart, bufferEnd, mBuffer, mBufferEnd,
The Android Open Source Project4f68be12009-03-18 17:39:46 -07002115 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, cblk->channels);
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002116 return 0;
2117 }
2118
2119 return bufferStart;
2120}
2121
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002122// ----------------------------------------------------------------------------
2123
Eric Laurent9d91ad52009-07-17 12:17:14 -07002124// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
2125AudioFlinger::PlaybackThread::Track::Track(
2126 const wp<ThreadBase>& thread,
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002127 const sp<Client>& client,
2128 int streamType,
2129 uint32_t sampleRate,
2130 int format,
2131 int channelCount,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002132 int frameCount,
2133 const sp<IMemory>& sharedBuffer)
Eric Laurent9d91ad52009-07-17 12:17:14 -07002134 : TrackBase(thread, client, sampleRate, format, channelCount, frameCount, 0, sharedBuffer),
2135 mMute(false), mSharedBuffer(sharedBuffer), mName(-1)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002136{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002137 sp<ThreadBase> baseThread = thread.promote();
2138 if (baseThread != 0) {
2139 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
2140 mName = playbackThread->getTrackName_l();
2141 }
2142 LOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2143 if (mName < 0) {
2144 LOGE("no more track names available");
2145 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002146 mVolume[0] = 1.0f;
2147 mVolume[1] = 1.0f;
Eric Laurent570dd0b2009-05-22 09:18:15 -07002148 mStreamType = streamType;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002149 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
2150 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
2151 mCblk->frameSize = AudioSystem::isLinearPCM(format) ? channelCount * sizeof(int16_t) : sizeof(int8_t);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002152}
2153
Eric Laurent9d91ad52009-07-17 12:17:14 -07002154AudioFlinger::PlaybackThread::Track::~Track()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002155{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002156 LOGV("PlaybackThread::Track destructor");
2157 sp<ThreadBase> thread = mThread.promote();
2158 if (thread != 0) {
2159 Mutex::Autolock _l(thread->mLock);
2160 mState = TERMINATED;
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002161 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002162}
2163
Eric Laurent9d91ad52009-07-17 12:17:14 -07002164void AudioFlinger::PlaybackThread::Track::destroy()
2165{
2166 // NOTE: destroyTrack_l() can remove a strong reference to this Track
2167 // by removing it from mTracks vector, so there is a risk that this Tracks's
2168 // desctructor is called. As the destructor needs to lock mLock,
2169 // we must acquire a strong reference on this Track before locking mLock
2170 // here so that the destructor is called only when exiting this function.
2171 // On the other hand, as long as Track::destroy() is only called by
2172 // TrackHandle destructor, the TrackHandle still holds a strong ref on
2173 // this Track with its member mTrack.
2174 sp<Track> keep(this);
2175 { // scope for mLock
2176 sp<ThreadBase> thread = mThread.promote();
2177 if (thread != 0) {
2178 Mutex::Autolock _l(thread->mLock);
2179 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2180 playbackThread->destroyTrack_l(this);
2181 }
2182 }
2183}
2184
2185void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002186{
2187 snprintf(buffer, size, " %5d %5d %3u %3u %3u %3u %1d %1d %1d %5u %5u %5u %04x %04x\n",
2188 mName - AudioMixer::TRACK0,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002189 (mClient == NULL) ? getpid() : mClient->pid(),
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002190 mStreamType,
2191 mFormat,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002192 mCblk->channels,
2193 mFrameCount,
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002194 mState,
2195 mMute,
2196 mFillingUpStatus,
2197 mCblk->sampleRate,
2198 mCblk->volume[0],
2199 mCblk->volume[1],
2200 mCblk->server,
2201 mCblk->user);
2202}
2203
Eric Laurent9d91ad52009-07-17 12:17:14 -07002204status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002205{
2206 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002207 uint32_t framesReady;
2208 uint32_t framesReq = buffer->frameCount;
2209
2210 // Check if last stepServer failed, try to step now
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002211 if (mFlags & TrackBase::STEPSERVER_FAILED) {
2212 if (!step()) goto getNextBuffer_exit;
2213 LOGV("stepServer recovered");
2214 mFlags &= ~TrackBase::STEPSERVER_FAILED;
2215 }
2216
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002217 framesReady = cblk->framesReady();
2218
2219 if (LIKELY(framesReady)) {
2220 uint32_t s = cblk->server;
2221 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
2222
2223 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
2224 if (framesReq > framesReady) {
2225 framesReq = framesReady;
2226 }
2227 if (s + framesReq > bufferEnd) {
2228 framesReq = bufferEnd - s;
2229 }
2230
2231 buffer->raw = getBuffer(s, framesReq);
2232 if (buffer->raw == 0) goto getNextBuffer_exit;
2233
2234 buffer->frameCount = framesReq;
2235 return NO_ERROR;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002236 }
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002237
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002238getNextBuffer_exit:
2239 buffer->raw = 0;
2240 buffer->frameCount = 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002241 LOGV("getNextBuffer() no more data");
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002242 return NOT_ENOUGH_DATA;
2243}
2244
Eric Laurent9d91ad52009-07-17 12:17:14 -07002245bool AudioFlinger::PlaybackThread::Track::isReady() const {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002246 if (mFillingUpStatus != FS_FILLING) return true;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002247
2248 if (mCblk->framesReady() >= mCblk->frameCount ||
2249 mCblk->forceReady) {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002250 mFillingUpStatus = FS_FILLED;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002251 mCblk->forceReady = 0;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002252 return true;
2253 }
2254 return false;
2255}
2256
Eric Laurent9d91ad52009-07-17 12:17:14 -07002257status_t AudioFlinger::PlaybackThread::Track::start()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002258{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002259 LOGV("start(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2260 sp<ThreadBase> thread = mThread.promote();
2261 if (thread != 0) {
2262 Mutex::Autolock _l(thread->mLock);
2263 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2264 playbackThread->addTrack_l(this);
2265 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002266 return NO_ERROR;
2267}
2268
Eric Laurent9d91ad52009-07-17 12:17:14 -07002269void AudioFlinger::PlaybackThread::Track::stop()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002270{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002271 LOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2272 sp<ThreadBase> thread = mThread.promote();
2273 if (thread != 0) {
2274 Mutex::Autolock _l(thread->mLock);
2275 if (mState > STOPPED) {
2276 mState = STOPPED;
2277 // If the track is not active (PAUSED and buffers full), flush buffers
2278 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2279 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
2280 reset();
2281 }
2282 LOGV("(> STOPPED) => STOPPED (%d)", mName);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002283 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002284 }
2285}
2286
Eric Laurent9d91ad52009-07-17 12:17:14 -07002287void AudioFlinger::PlaybackThread::Track::pause()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002288{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002289 LOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurent9d91ad52009-07-17 12:17:14 -07002290 sp<ThreadBase> thread = mThread.promote();
2291 if (thread != 0) {
2292 Mutex::Autolock _l(thread->mLock);
2293 if (mState == ACTIVE || mState == RESUMING) {
2294 mState = PAUSING;
2295 LOGV("ACTIVE/RESUMING => PAUSING (%d)", mName);
2296 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002297 }
2298}
2299
Eric Laurent9d91ad52009-07-17 12:17:14 -07002300void AudioFlinger::PlaybackThread::Track::flush()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002301{
2302 LOGV("flush(%d)", mName);
Eric Laurent9d91ad52009-07-17 12:17:14 -07002303 sp<ThreadBase> thread = mThread.promote();
2304 if (thread != 0) {
2305 Mutex::Autolock _l(thread->mLock);
2306 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
2307 return;
2308 }
2309 // No point remaining in PAUSED state after a flush => go to
2310 // STOPPED state
2311 mState = STOPPED;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002312
Eric Laurent9d91ad52009-07-17 12:17:14 -07002313 mCblk->lock.lock();
2314 // NOTE: reset() will reset cblk->user and cblk->server with
2315 // the risk that at the same time, the AudioMixer is trying to read
2316 // data. In this case, getNextBuffer() would return a NULL pointer
2317 // as audio buffer => the AudioMixer code MUST always test that pointer
2318 // returned by getNextBuffer() is not NULL!
2319 reset();
2320 mCblk->lock.unlock();
2321 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002322}
2323
Eric Laurent9d91ad52009-07-17 12:17:14 -07002324void AudioFlinger::PlaybackThread::Track::reset()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002325{
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002326 // Do not reset twice to avoid discarding data written just after a flush and before
2327 // the audioflinger thread detects the track is stopped.
2328 if (!mResetDone) {
2329 TrackBase::reset();
2330 // Force underrun condition to avoid false underrun callback until first data is
2331 // written to buffer
2332 mCblk->flowControlFlag = 1;
2333 mCblk->forceReady = 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002334 mFillingUpStatus = FS_FILLING;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002335 mResetDone = true;
2336 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002337}
2338
Eric Laurent9d91ad52009-07-17 12:17:14 -07002339void AudioFlinger::PlaybackThread::Track::mute(bool muted)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002340{
2341 mMute = muted;
2342}
2343
Eric Laurent9d91ad52009-07-17 12:17:14 -07002344void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002345{
2346 mVolume[0] = left;
2347 mVolume[1] = right;
2348}
2349
2350// ----------------------------------------------------------------------------
2351
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002352// RecordTrack constructor must be called with AudioFlinger::mLock held
Eric Laurent9d91ad52009-07-17 12:17:14 -07002353AudioFlinger::RecordThread::RecordTrack::RecordTrack(
2354 const wp<ThreadBase>& thread,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002355 const sp<Client>& client,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002356 uint32_t sampleRate,
2357 int format,
2358 int channelCount,
2359 int frameCount,
2360 uint32_t flags)
Eric Laurent9d91ad52009-07-17 12:17:14 -07002361 : TrackBase(thread, client, sampleRate, format,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002362 channelCount, frameCount, flags, 0),
Eric Laurent9d91ad52009-07-17 12:17:14 -07002363 mOverflow(false)
2364{
2365 LOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
2366 if (format == AudioSystem::PCM_16_BIT) {
2367 mCblk->frameSize = channelCount * sizeof(int16_t);
2368 } else if (format == AudioSystem::PCM_8_BIT) {
2369 mCblk->frameSize = channelCount * sizeof(int8_t);
2370 } else {
2371 mCblk->frameSize = sizeof(int8_t);
2372 }
2373}
2374
2375AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002376{
2377}
2378
Eric Laurent9d91ad52009-07-17 12:17:14 -07002379status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002380{
2381 audio_track_cblk_t* cblk = this->cblk();
2382 uint32_t framesAvail;
2383 uint32_t framesReq = buffer->frameCount;
2384
2385 // Check if last stepServer failed, try to step now
2386 if (mFlags & TrackBase::STEPSERVER_FAILED) {
2387 if (!step()) goto getNextBuffer_exit;
2388 LOGV("stepServer recovered");
2389 mFlags &= ~TrackBase::STEPSERVER_FAILED;
2390 }
2391
2392 framesAvail = cblk->framesAvailable_l();
2393
2394 if (LIKELY(framesAvail)) {
2395 uint32_t s = cblk->server;
2396 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
2397
2398 if (framesReq > framesAvail) {
2399 framesReq = framesAvail;
2400 }
2401 if (s + framesReq > bufferEnd) {
2402 framesReq = bufferEnd - s;
2403 }
2404
2405 buffer->raw = getBuffer(s, framesReq);
2406 if (buffer->raw == 0) goto getNextBuffer_exit;
2407
2408 buffer->frameCount = framesReq;
2409 return NO_ERROR;
2410 }
2411
2412getNextBuffer_exit:
2413 buffer->raw = 0;
2414 buffer->frameCount = 0;
2415 return NOT_ENOUGH_DATA;
2416}
2417
Eric Laurent9d91ad52009-07-17 12:17:14 -07002418status_t AudioFlinger::RecordThread::RecordTrack::start()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002419{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002420 sp<ThreadBase> thread = mThread.promote();
2421 if (thread != 0) {
2422 RecordThread *recordThread = (RecordThread *)thread.get();
2423 return recordThread->start(this);
2424 }
2425 return NO_INIT;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002426}
2427
Eric Laurent9d91ad52009-07-17 12:17:14 -07002428void AudioFlinger::RecordThread::RecordTrack::stop()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002429{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002430 sp<ThreadBase> thread = mThread.promote();
2431 if (thread != 0) {
2432 RecordThread *recordThread = (RecordThread *)thread.get();
2433 recordThread->stop(this);
2434 TrackBase::reset();
2435 // Force overerrun condition to avoid false overrun callback until first data is
2436 // read from buffer
2437 mCblk->flowControlFlag = 1;
2438 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002439}
2440
2441
2442// ----------------------------------------------------------------------------
2443
Eric Laurent9d91ad52009-07-17 12:17:14 -07002444AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
2445 const wp<ThreadBase>& thread,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002446 uint32_t sampleRate,
2447 int format,
2448 int channelCount,
2449 int frameCount)
Eric Laurent9d91ad52009-07-17 12:17:14 -07002450 : Track(thread, NULL, AudioSystem::NUM_STREAM_TYPES, sampleRate, format, channelCount, frameCount, NULL),
2451 mActive(false)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002452{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002453
2454 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002455 mCblk->out = 1;
2456 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
2457 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
2458 mOutBuffer.frameCount = 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002459 mWaitTimeMs = (playbackThread->frameCount() * 2 * 1000) / playbackThread->sampleRate();
2460
2461 LOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, mCblk->frameCount %d, mCblk->sampleRate %d, mCblk->channels %d mBufferEnd %p mWaitTimeMs %d",
2462 mCblk, mBuffer, mCblk->buffers, mCblk->frameCount, mCblk->sampleRate, mCblk->channels, mBufferEnd, mWaitTimeMs);
2463
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002464}
2465
Eric Laurent9d91ad52009-07-17 12:17:14 -07002466AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002467{
2468 stop();
2469}
2470
Eric Laurent9d91ad52009-07-17 12:17:14 -07002471status_t AudioFlinger::PlaybackThread::OutputTrack::start()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002472{
2473 status_t status = Track::start();
Eric Laurent9d91ad52009-07-17 12:17:14 -07002474 if (status != NO_ERROR) {
2475 return status;
2476 }
2477
2478 mActive = true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002479 mRetryCount = 127;
2480 return status;
2481}
2482
Eric Laurent9d91ad52009-07-17 12:17:14 -07002483void AudioFlinger::PlaybackThread::OutputTrack::stop()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002484{
2485 Track::stop();
2486 clearBufferQueue();
2487 mOutBuffer.frameCount = 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002488 mActive = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002489}
2490
Eric Laurent9d91ad52009-07-17 12:17:14 -07002491bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002492{
2493 Buffer *pInBuffer;
2494 Buffer inBuffer;
2495 uint32_t channels = mCblk->channels;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002496 bool outputBufferFull = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002497 inBuffer.frameCount = frames;
2498 inBuffer.i16 = data;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002499
2500 uint32_t waitTimeLeftMs = mWaitTimeMs;
2501
2502 if (!mActive) {
2503 start();
2504 sp<ThreadBase> thread = mThread.promote();
2505 if (thread != 0) {
2506 MixerThread *mixerThread = (MixerThread *)thread.get();
2507 if (mCblk->frameCount > frames){
2508 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
2509 uint32_t startFrames = (mCblk->frameCount - frames);
2510 pInBuffer = new Buffer;
2511 pInBuffer->mBuffer = new int16_t[startFrames * channels];
2512 pInBuffer->frameCount = startFrames;
2513 pInBuffer->i16 = pInBuffer->mBuffer;
2514 memset(pInBuffer->raw, 0, startFrames * channels * sizeof(int16_t));
2515 mBufferQueue.add(pInBuffer);
2516 } else {
2517 LOGW ("OutputTrack::write() %p no more buffers in queue", this);
2518 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002519 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002520 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002521 }
2522
Eric Laurent9d91ad52009-07-17 12:17:14 -07002523 while (waitTimeLeftMs) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002524 // First write pending buffers, then new data
2525 if (mBufferQueue.size()) {
2526 pInBuffer = mBufferQueue.itemAt(0);
2527 } else {
2528 pInBuffer = &inBuffer;
2529 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002530
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002531 if (pInBuffer->frameCount == 0) {
2532 break;
2533 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002534
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002535 if (mOutBuffer.frameCount == 0) {
2536 mOutBuffer.frameCount = pInBuffer->frameCount;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002537 nsecs_t startTime = systemTime();
2538 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
2539 LOGV ("OutputTrack::write() %p no more output buffers", this);
2540 outputBufferFull = true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002541 break;
2542 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002543 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
2544// LOGV("OutputTrack::write() waitTimeMs %d waitTimeLeftMs %d", waitTimeMs, waitTimeLeftMs)
2545 if (waitTimeLeftMs >= waitTimeMs) {
2546 waitTimeLeftMs -= waitTimeMs;
2547 } else {
2548 waitTimeLeftMs = 0;
2549 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002550 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002551
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002552 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
2553 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channels * sizeof(int16_t));
2554 mCblk->stepUser(outFrames);
2555 pInBuffer->frameCount -= outFrames;
2556 pInBuffer->i16 += outFrames * channels;
2557 mOutBuffer.frameCount -= outFrames;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002558 mOutBuffer.i16 += outFrames * channels;
2559
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002560 if (pInBuffer->frameCount == 0) {
2561 if (mBufferQueue.size()) {
2562 mBufferQueue.removeAt(0);
2563 delete [] pInBuffer->mBuffer;
2564 delete pInBuffer;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002565 LOGV("OutputTrack::write() %p released overflow buffer %d", this, mBufferQueue.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002566 } else {
2567 break;
2568 }
2569 }
2570 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002571
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002572 // If we could not write all frames, allocate a buffer and queue it for next time.
2573 if (inBuffer.frameCount) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07002574 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002575 pInBuffer = new Buffer;
2576 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channels];
2577 pInBuffer->frameCount = inBuffer.frameCount;
2578 pInBuffer->i16 = pInBuffer->mBuffer;
2579 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channels * sizeof(int16_t));
2580 mBufferQueue.add(pInBuffer);
Eric Laurent9d91ad52009-07-17 12:17:14 -07002581 LOGV("OutputTrack::write() %p adding overflow buffer %d", this, mBufferQueue.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002582 } else {
Eric Laurent9d91ad52009-07-17 12:17:14 -07002583 LOGW("OutputTrack::write() %p no more overflow buffers", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002584 }
2585 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002586
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002587 // Calling write() with a 0 length buffer, means that no more data will be written:
Eric Laurent9d91ad52009-07-17 12:17:14 -07002588 // 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 -08002589 // by output mixer.
Eric Laurent9d91ad52009-07-17 12:17:14 -07002590 if (frames == 0 && mBufferQueue.size() == 0) {
2591 if (mCblk->user < mCblk->frameCount) {
2592 frames = mCblk->frameCount - mCblk->user;
2593 pInBuffer = new Buffer;
2594 pInBuffer->mBuffer = new int16_t[frames * channels];
2595 pInBuffer->frameCount = frames;
2596 pInBuffer->i16 = pInBuffer->mBuffer;
2597 memset(pInBuffer->raw, 0, frames * channels * sizeof(int16_t));
2598 mBufferQueue.add(pInBuffer);
2599 } else {
2600 stop();
2601 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002602 }
2603
Eric Laurent9d91ad52009-07-17 12:17:14 -07002604 return outputBufferFull;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002605}
2606
Eric Laurent9d91ad52009-07-17 12:17:14 -07002607status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002608{
2609 int active;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002610 status_t result;
2611 audio_track_cblk_t* cblk = mCblk;
2612 uint32_t framesReq = buffer->frameCount;
2613
Eric Laurent9d91ad52009-07-17 12:17:14 -07002614// LOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002615 buffer->frameCount = 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002616
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002617 uint32_t framesAvail = cblk->framesAvailable();
2618
Eric Laurent9d91ad52009-07-17 12:17:14 -07002619
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002620 if (framesAvail == 0) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07002621 Mutex::Autolock _l(cblk->lock);
2622 goto start_loop_here;
2623 while (framesAvail == 0) {
2624 active = mActive;
2625 if (UNLIKELY(!active)) {
2626 LOGV("Not active and NO_MORE_BUFFERS");
2627 return AudioTrack::NO_MORE_BUFFERS;
2628 }
2629 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
2630 if (result != NO_ERROR) {
2631 return AudioTrack::NO_MORE_BUFFERS;
2632 }
2633 // read the server count again
2634 start_loop_here:
2635 framesAvail = cblk->framesAvailable_l();
2636 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002637 }
2638
Eric Laurent9d91ad52009-07-17 12:17:14 -07002639// if (framesAvail < framesReq) {
2640// return AudioTrack::NO_MORE_BUFFERS;
2641// }
2642
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002643 if (framesReq > framesAvail) {
2644 framesReq = framesAvail;
2645 }
2646
2647 uint32_t u = cblk->user;
2648 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
2649
2650 if (u + framesReq > bufferEnd) {
2651 framesReq = bufferEnd - u;
2652 }
2653
2654 buffer->frameCount = framesReq;
2655 buffer->raw = (void *)cblk->buffer(u);
2656 return NO_ERROR;
2657}
2658
2659
Eric Laurent9d91ad52009-07-17 12:17:14 -07002660void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002661{
2662 size_t size = mBufferQueue.size();
2663 Buffer *pBuffer;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002664
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002665 for (size_t i = 0; i < size; i++) {
2666 pBuffer = mBufferQueue.itemAt(i);
2667 delete [] pBuffer->mBuffer;
2668 delete pBuffer;
2669 }
2670 mBufferQueue.clear();
2671}
2672
2673// ----------------------------------------------------------------------------
2674
2675AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
2676 : RefBase(),
2677 mAudioFlinger(audioFlinger),
2678 mMemoryDealer(new MemoryDealer(1024*1024)),
2679 mPid(pid)
2680{
2681 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
2682}
2683
2684AudioFlinger::Client::~Client()
2685{
2686 mAudioFlinger->removeClient(mPid);
2687}
2688
2689const sp<MemoryDealer>& AudioFlinger::Client::heap() const
2690{
2691 return mMemoryDealer;
2692}
2693
2694// ----------------------------------------------------------------------------
2695
Eric Laurent9d91ad52009-07-17 12:17:14 -07002696AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002697 : BnAudioTrack(),
2698 mTrack(track)
2699{
2700}
2701
2702AudioFlinger::TrackHandle::~TrackHandle() {
2703 // just stop the track on deletion, associated resources
2704 // will be freed from the main thread once all pending buffers have
2705 // been played. Unless it's not in the active track list, in which
2706 // case we free everything now...
2707 mTrack->destroy();
2708}
2709
2710status_t AudioFlinger::TrackHandle::start() {
2711 return mTrack->start();
2712}
2713
2714void AudioFlinger::TrackHandle::stop() {
2715 mTrack->stop();
2716}
2717
2718void AudioFlinger::TrackHandle::flush() {
2719 mTrack->flush();
2720}
2721
2722void AudioFlinger::TrackHandle::mute(bool e) {
2723 mTrack->mute(e);
2724}
2725
2726void AudioFlinger::TrackHandle::pause() {
2727 mTrack->pause();
2728}
2729
2730void AudioFlinger::TrackHandle::setVolume(float left, float right) {
2731 mTrack->setVolume(left, right);
2732}
2733
2734sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
2735 return mTrack->getCblk();
2736}
2737
2738status_t AudioFlinger::TrackHandle::onTransact(
2739 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2740{
2741 return BnAudioTrack::onTransact(code, data, reply, flags);
2742}
2743
2744// ----------------------------------------------------------------------------
2745
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002746sp<IAudioRecord> AudioFlinger::openRecord(
2747 pid_t pid,
Eric Laurente0e9ecc2009-07-28 08:44:33 -07002748 int input,
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002749 uint32_t sampleRate,
2750 int format,
2751 int channelCount,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002752 int frameCount,
2753 uint32_t flags,
2754 status_t *status)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002755{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002756 sp<RecordThread::RecordTrack> recordTrack;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002757 sp<RecordHandle> recordHandle;
2758 sp<Client> client;
2759 wp<Client> wclient;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002760 status_t lStatus;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002761 RecordThread *thread;
2762 size_t inFrameCount;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002763
2764 // check calling permissions
2765 if (!recordingAllowed()) {
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002766 lStatus = PERMISSION_DENIED;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002767 goto Exit;
2768 }
2769
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002770 // add client to list
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002771 { // scope for mLock
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002772 Mutex::Autolock _l(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07002773 thread = checkRecordThread_l(input);
2774 if (thread == NULL) {
2775 lStatus = BAD_VALUE;
2776 goto Exit;
2777 }
2778
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002779 wclient = mClients.valueFor(pid);
2780 if (wclient != NULL) {
2781 client = wclient.promote();
2782 } else {
2783 client = new Client(this, pid);
2784 mClients.add(pid, client);
2785 }
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002786
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002787 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent9d91ad52009-07-17 12:17:14 -07002788 recordTrack = new RecordThread::RecordTrack(thread, client, sampleRate,
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002789 format, channelCount, frameCount, flags);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002790 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002791 if (recordTrack->getCblk() == NULL) {
2792 recordTrack.clear();
2793 lStatus = NO_MEMORY;
2794 goto Exit;
2795 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002796
2797 // return to handle to client
2798 recordHandle = new RecordHandle(recordTrack);
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002799 lStatus = NO_ERROR;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002800
2801Exit:
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002802 if (status) {
2803 *status = lStatus;
2804 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002805 return recordHandle;
2806}
2807
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002808// ----------------------------------------------------------------------------
2809
Eric Laurent9d91ad52009-07-17 12:17:14 -07002810AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002811 : BnAudioRecord(),
2812 mRecordTrack(recordTrack)
2813{
2814}
2815
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002816AudioFlinger::RecordHandle::~RecordHandle() {
2817 stop();
2818}
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002819
2820status_t AudioFlinger::RecordHandle::start() {
2821 LOGV("RecordHandle::start()");
2822 return mRecordTrack->start();
2823}
2824
2825void AudioFlinger::RecordHandle::stop() {
2826 LOGV("RecordHandle::stop()");
2827 mRecordTrack->stop();
2828}
2829
2830sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
2831 return mRecordTrack->getCblk();
2832}
2833
2834status_t AudioFlinger::RecordHandle::onTransact(
2835 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2836{
2837 return BnAudioRecord::onTransact(code, data, reply, flags);
2838}
2839
2840// ----------------------------------------------------------------------------
2841
Eric Laurent9d91ad52009-07-17 12:17:14 -07002842AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger, AudioStreamIn *input, uint32_t sampleRate, uint32_t channels) :
2843 ThreadBase(audioFlinger),
2844 mInput(input), mResampler(0), mRsmpOutBuffer(0), mRsmpInBuffer(0)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002845{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002846 mReqChannelCount = AudioSystem::popCount(channels);
2847 mReqSampleRate = sampleRate;
2848 readInputParameters();
2849 sendConfigEvent(AudioSystem::INPUT_OPENED);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002850}
2851
Eric Laurent9d91ad52009-07-17 12:17:14 -07002852
2853AudioFlinger::RecordThread::~RecordThread()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002854{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002855 delete[] mRsmpInBuffer;
2856 if (mResampler != 0) {
2857 delete mResampler;
2858 delete[] mRsmpOutBuffer;
2859 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002860}
2861
Eric Laurent9d91ad52009-07-17 12:17:14 -07002862void AudioFlinger::RecordThread::onFirstRef()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002863{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002864 const size_t SIZE = 256;
2865 char buffer[SIZE];
2866
2867 snprintf(buffer, SIZE, "Record Thread %p", this);
2868
2869 run(buffer, PRIORITY_URGENT_AUDIO);
2870}
2871bool AudioFlinger::RecordThread::threadLoop()
2872{
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002873 AudioBufferProvider::Buffer buffer;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002874 sp<RecordTrack> activeTrack;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002875
2876 // start recording
2877 while (!exitPending()) {
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002878
Eric Laurent9d91ad52009-07-17 12:17:14 -07002879 processConfigEvents();
2880
2881 { // scope for mLock
2882 Mutex::Autolock _l(mLock);
2883 checkForNewParameters_l();
2884 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
2885 if (!mStandby) {
2886 mInput->standby();
2887 mStandby = true;
2888 }
2889
2890 if (exitPending()) break;
2891
2892 LOGV("RecordThread: loop stopping");
2893 // go to sleep
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002894 mWaitWorkCV.wait(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07002895 LOGV("RecordThread: loop starting");
2896 continue;
2897 }
2898 if (mActiveTrack != 0) {
2899 if (mActiveTrack->mState == TrackBase::PAUSING) {
2900 mActiveTrack.clear();
2901 mStartStopCond.broadcast();
2902 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
2903 mRsmpInIndex = mFrameCount;
2904 if (mReqChannelCount != mActiveTrack->channelCount()) {
2905 mActiveTrack.clear();
2906 } else {
2907 mActiveTrack->mState == TrackBase::ACTIVE;
2908 }
2909 mStartStopCond.broadcast();
2910 }
2911 mStandby = false;
2912 }
2913 }
2914
2915 if (mActiveTrack != 0) {
2916 buffer.frameCount = mFrameCount;
2917 if (LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
2918 size_t framesOut = buffer.frameCount;
2919 if (mResampler == 0) {
2920 // no resampling
2921 while (framesOut) {
2922 size_t framesIn = mFrameCount - mRsmpInIndex;
2923 if (framesIn) {
2924 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
2925 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
2926 if (framesIn > framesOut)
2927 framesIn = framesOut;
2928 mRsmpInIndex += framesIn;
2929 framesOut -= framesIn;
2930 if (mChannelCount == mReqChannelCount ||
2931 mFormat != AudioSystem::PCM_16_BIT) {
2932 memcpy(dst, src, framesIn * mFrameSize);
2933 } else {
2934 int16_t *src16 = (int16_t *)src;
2935 int16_t *dst16 = (int16_t *)dst;
2936 if (mChannelCount == 1) {
2937 while (framesIn--) {
2938 *dst16++ = *src16;
2939 *dst16++ = *src16++;
2940 }
2941 } else {
2942 while (framesIn--) {
2943 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
2944 src16 += 2;
2945 }
2946 }
2947 }
2948 }
2949 if (framesOut && mFrameCount == mRsmpInIndex) {
2950 ssize_t bytesRead;
2951 if (framesOut == mFrameCount &&
2952 (mChannelCount == mReqChannelCount || mFormat != AudioSystem::PCM_16_BIT)) {
2953 bytesRead = mInput->read(buffer.raw, mInputBytes);
2954 framesOut = 0;
2955 } else {
2956 bytesRead = mInput->read(mRsmpInBuffer, mInputBytes);
2957 mRsmpInIndex = 0;
2958 }
2959 if (bytesRead < 0) {
2960 LOGE("Error reading audio input");
2961 sleep(1);
2962 mRsmpInIndex = mFrameCount;
2963 framesOut = 0;
2964 buffer.frameCount = 0;
2965 }
2966 }
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002967 }
2968 } else {
Eric Laurent9d91ad52009-07-17 12:17:14 -07002969 // resampling
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002970
Eric Laurent9d91ad52009-07-17 12:17:14 -07002971 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
2972 // alter output frame count as if we were expecting stereo samples
2973 if (mChannelCount == 1 && mReqChannelCount == 1) {
2974 framesOut >>= 1;
2975 }
2976 mResampler->resample(mRsmpOutBuffer, framesOut, this);
2977 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
2978 // are 32 bit aligned which should be always true.
2979 if (mChannelCount == 2 && mReqChannelCount == 1) {
2980 AudioMixer::ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
2981 // the resampler always outputs stereo samples: do post stereo to mono conversion
2982 int16_t *src = (int16_t *)mRsmpOutBuffer;
2983 int16_t *dst = buffer.i16;
2984 while (framesOut--) {
2985 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
2986 src += 2;
2987 }
2988 } else {
2989 AudioMixer::ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
2990 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002991
Eric Laurent9d91ad52009-07-17 12:17:14 -07002992 }
2993 mActiveTrack->releaseBuffer(&buffer);
2994 mActiveTrack->overflow();
2995 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002996 // client isn't retrieving buffers fast enough
2997 else {
Eric Laurent9d91ad52009-07-17 12:17:14 -07002998 if (!mActiveTrack->setOverflow())
2999 LOGW("RecordThread: buffer overflow");
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003000 // Release the processor for a while before asking for a new buffer.
3001 // This will give the application more chance to read from the buffer and
3002 // clear the overflow.
3003 usleep(5000);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003004 }
3005 }
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003006 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003007
Eric Laurent9d91ad52009-07-17 12:17:14 -07003008 if (!mStandby) {
3009 mInput->standby();
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003010 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003011 mActiveTrack.clear();
3012
3013 sendConfigEvent(AudioSystem::INPUT_CLOSED);
3014 processConfigEvents();
3015
3016 LOGV("RecordThread %p exiting", this);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003017 return false;
3018}
3019
Eric Laurent9d91ad52009-07-17 12:17:14 -07003020status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003021{
Eric Laurent9d91ad52009-07-17 12:17:14 -07003022 LOGV("RecordThread::start");
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003023 AutoMutex lock(&mLock);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003024
Eric Laurent9d91ad52009-07-17 12:17:14 -07003025 if (mActiveTrack != 0) {
3026 if (recordTrack != mActiveTrack.get()) return -EBUSY;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003027
Eric Laurent9d91ad52009-07-17 12:17:14 -07003028 if (mActiveTrack->mState == TrackBase::PAUSING) mActiveTrack->mState = TrackBase::RESUMING;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003029
Eric Laurent9d91ad52009-07-17 12:17:14 -07003030 return NO_ERROR;
3031 }
3032
3033 mActiveTrack = recordTrack;
3034 mActiveTrack->mState = TrackBase::RESUMING;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003035 // signal thread to start
3036 LOGV("Signal record thread");
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003037 mWaitWorkCV.signal();
Eric Laurent9d91ad52009-07-17 12:17:14 -07003038 mStartStopCond.wait(mLock);
3039 if (mActiveTrack != 0) {
3040 LOGV("Record started OK");
3041 return NO_ERROR;
3042 } else {
3043 LOGV("Record failed to start");
3044 return BAD_VALUE;
3045 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003046}
3047
Eric Laurent9d91ad52009-07-17 12:17:14 -07003048void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
3049 LOGV("RecordThread::stop");
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003050 AutoMutex lock(&mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003051 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
3052 mActiveTrack->mState = TrackBase::PAUSING;
3053 mStartStopCond.wait(mLock);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003054 }
3055}
3056
Eric Laurent9d91ad52009-07-17 12:17:14 -07003057status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003058{
3059 const size_t SIZE = 256;
3060 char buffer[SIZE];
3061 String8 result;
3062 pid_t pid = 0;
3063
Eric Laurent9d91ad52009-07-17 12:17:14 -07003064 if (mActiveTrack != 0 && mActiveTrack->mClient != 0) {
3065 snprintf(buffer, SIZE, "Record client pid: %d\n", mActiveTrack->mClient->pid());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003066 result.append(buffer);
3067 } else {
3068 result.append("No record client\n");
3069 }
3070 write(fd, result.string(), result.size());
3071 return NO_ERROR;
3072}
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003073
Eric Laurent9d91ad52009-07-17 12:17:14 -07003074status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3075{
3076 size_t framesReq = buffer->frameCount;
3077 size_t framesReady = mFrameCount - mRsmpInIndex;
3078 int channelCount;
3079
3080 if (framesReady == 0) {
3081 ssize_t bytesRead = mInput->read(mRsmpInBuffer, mInputBytes);
3082 if (bytesRead < 0) {
3083 LOGE("RecordThread::getNextBuffer() Error reading audio input");
3084 sleep(1);
3085 buffer->raw = 0;
3086 buffer->frameCount = 0;
3087 return NOT_ENOUGH_DATA;
3088 }
3089 mRsmpInIndex = 0;
3090 framesReady = mFrameCount;
3091 }
3092
3093 if (framesReq > framesReady) {
3094 framesReq = framesReady;
3095 }
3096
3097 if (mChannelCount == 1 && mReqChannelCount == 2) {
3098 channelCount = 1;
3099 } else {
3100 channelCount = 2;
3101 }
3102 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
3103 buffer->frameCount = framesReq;
3104 return NO_ERROR;
3105}
3106
3107void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3108{
3109 mRsmpInIndex += buffer->frameCount;
3110 buffer->frameCount = 0;
3111}
3112
3113bool AudioFlinger::RecordThread::checkForNewParameters_l()
3114{
3115 bool reconfig = false;
3116
Eric Laurent3464c012009-08-04 09:45:33 -07003117 while (!mNewParameters.isEmpty()) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07003118 status_t status = NO_ERROR;
Eric Laurent3464c012009-08-04 09:45:33 -07003119 String8 keyValuePair = mNewParameters[0];
3120 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003121 int value;
3122 int reqFormat = mFormat;
3123 int reqSamplingRate = mReqSampleRate;
3124 int reqChannelCount = mReqChannelCount;
Eric Laurent3464c012009-08-04 09:45:33 -07003125
3126 mNewParameters.removeAt(0);
3127
Eric Laurent9d91ad52009-07-17 12:17:14 -07003128 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3129 reqSamplingRate = value;
3130 reconfig = true;
3131 }
3132 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
3133 reqFormat = value;
3134 reconfig = true;
3135 }
3136 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
3137 reqChannelCount = AudioSystem::popCount(value);
3138 reconfig = true;
3139 }
3140 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3141 // do not accept frame count changes if tracks are open as the track buffer
3142 // size depends on frame count and correct behavior would not be garantied
3143 // if frame count is changed after track creation
3144 if (mActiveTrack != 0) {
3145 status = INVALID_OPERATION;
3146 } else {
3147 reconfig = true;
3148 }
3149 }
3150 if (status == NO_ERROR) {
Eric Laurent3464c012009-08-04 09:45:33 -07003151 status = mInput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003152 if (status == INVALID_OPERATION) {
3153 mInput->standby();
Eric Laurent3464c012009-08-04 09:45:33 -07003154 status = mInput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003155 }
3156 if (reconfig) {
3157 if (status == BAD_VALUE &&
3158 reqFormat == mInput->format() && reqFormat == AudioSystem::PCM_16_BIT &&
3159 ((int)mInput->sampleRate() <= 2 * reqSamplingRate) &&
3160 (AudioSystem::popCount(mInput->channels()) < 3) && (reqChannelCount < 3)) {
3161 status = NO_ERROR;
3162 }
3163 if (status == NO_ERROR) {
3164 readInputParameters();
Eric Laurent3464c012009-08-04 09:45:33 -07003165 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003166 }
3167 }
3168 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003169 mParamStatus = status;
3170 mParamCond.signal();
Eric Laurent3464c012009-08-04 09:45:33 -07003171 mWaitWorkCV.wait(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003172 }
3173 return reconfig;
3174}
3175
3176String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
3177{
3178 return mInput->getParameters(keys);
3179}
3180
3181void AudioFlinger::RecordThread::audioConfigChanged(int event, int param) {
3182 AudioSystem::OutputDescriptor desc;
3183 void *param2 = 0;
3184
3185 switch (event) {
3186 case AudioSystem::INPUT_OPENED:
3187 case AudioSystem::INPUT_CONFIG_CHANGED:
3188 desc.channels = mChannelCount;
3189 desc.samplingRate = mSampleRate;
3190 desc.format = mFormat;
3191 desc.frameCount = mFrameCount;
3192 desc.latency = 0;
3193 param2 = &desc;
3194 break;
3195
3196 case AudioSystem::INPUT_CLOSED:
3197 default:
3198 break;
3199 }
3200 mAudioFlinger->audioConfigChanged(event, this, param2);
3201}
3202
3203void AudioFlinger::RecordThread::readInputParameters()
3204{
3205 if (mRsmpInBuffer) delete mRsmpInBuffer;
3206 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
3207 if (mResampler) delete mResampler;
3208 mResampler = 0;
3209
3210 mSampleRate = mInput->sampleRate();
3211 mChannelCount = AudioSystem::popCount(mInput->channels());
3212 mFormat = mInput->format();
3213 mFrameSize = mInput->frameSize();
3214 mInputBytes = mInput->bufferSize();
3215 mFrameCount = mInputBytes / mFrameSize;
3216 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
3217
3218 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
3219 {
3220 int channelCount;
3221 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
3222 // stereo to mono post process as the resampler always outputs stereo.
3223 if (mChannelCount == 1 && mReqChannelCount == 2) {
3224 channelCount = 1;
3225 } else {
3226 channelCount = 2;
3227 }
3228 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
3229 mResampler->setSampleRate(mSampleRate);
3230 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
3231 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
3232
3233 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
3234 if (mChannelCount == 1 && mReqChannelCount == 1) {
3235 mFrameCount >>= 1;
3236 }
3237
3238 }
3239 mRsmpInIndex = mFrameCount;
3240}
3241
3242// ----------------------------------------------------------------------------
3243
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003244int AudioFlinger::openOutput(uint32_t *pDevices,
Eric Laurent9d91ad52009-07-17 12:17:14 -07003245 uint32_t *pSamplingRate,
3246 uint32_t *pFormat,
3247 uint32_t *pChannels,
3248 uint32_t *pLatencyMs,
3249 uint32_t flags)
3250{
3251 status_t status;
3252 PlaybackThread *thread = NULL;
3253 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
3254 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
3255 uint32_t format = pFormat ? *pFormat : 0;
3256 uint32_t channels = pChannels ? *pChannels : 0;
3257 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
3258
3259 LOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
3260 pDevices ? *pDevices : 0,
3261 samplingRate,
3262 format,
3263 channels,
3264 flags);
3265
3266 if (pDevices == NULL || *pDevices == 0) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003267 return 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003268 }
3269 Mutex::Autolock _l(mLock);
3270
3271 AudioStreamOut *output = mAudioHardware->openOutputStream(*pDevices,
3272 (int *)&format,
3273 &channels,
3274 &samplingRate,
3275 &status);
3276 LOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
3277 output,
3278 samplingRate,
3279 format,
3280 channels,
3281 status);
3282
3283 mHardwareStatus = AUDIO_HW_IDLE;
3284 if (output != 0) {
3285 if ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) ||
3286 (format != AudioSystem::PCM_16_BIT) ||
3287 (channels != AudioSystem::CHANNEL_OUT_STEREO)) {
3288 thread = new DirectOutputThread(this, output);
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003289 LOGV("openOutput() created direct output: ID %d thread %p", (mNextThreadId + 1), thread);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003290 } else {
3291 thread = new MixerThread(this, output);
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003292 LOGV("openOutput() created mixer output: ID %d thread %p", (mNextThreadId + 1), thread);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003293 }
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003294 mPlaybackThreads.add(++mNextThreadId, thread);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003295
3296 if (pSamplingRate) *pSamplingRate = samplingRate;
3297 if (pFormat) *pFormat = format;
3298 if (pChannels) *pChannels = channels;
3299 if (pLatencyMs) *pLatencyMs = thread->latency();
3300 }
3301
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003302 return mNextThreadId;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003303}
3304
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003305int AudioFlinger::openDuplicateOutput(int output1, int output2)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003306{
3307 Mutex::Autolock _l(mLock);
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003308 MixerThread *thread1 = checkMixerThread_l(output1);
3309 MixerThread *thread2 = checkMixerThread_l(output2);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003310
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003311 if (thread1 == NULL || thread2 == NULL) {
3312 LOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
3313 return 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003314 }
3315
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003316
3317 DuplicatingThread *thread = new DuplicatingThread(this, thread1);
3318 thread->addOutputTrack(thread2);
3319 mPlaybackThreads.add(++mNextThreadId, thread);
3320 return mNextThreadId;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003321}
3322
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003323status_t AudioFlinger::closeOutput(int output)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003324{
Eric Laurentdae20d92009-08-04 08:37:05 -07003325 // keep strong reference on the playback thread so that
3326 // it is not destroyed while exit() is executed
3327 sp <PlaybackThread> thread;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003328 {
3329 Mutex::Autolock _l(mLock);
3330 thread = checkPlaybackThread_l(output);
3331 if (thread == NULL) {
3332 return BAD_VALUE;
3333 }
3334
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003335 LOGV("closeOutput() %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003336
3337 if (thread->type() == PlaybackThread::MIXER) {
3338 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003339 if (mPlaybackThreads.valueAt(i)->type() == PlaybackThread::DUPLICATING) {
3340 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Eric Laurentdae20d92009-08-04 08:37:05 -07003341 dupThread->removeOutputTrack((MixerThread *)thread.get());
Eric Laurent9d91ad52009-07-17 12:17:14 -07003342 }
3343 }
3344 }
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003345 mPlaybackThreads.removeItem(output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003346 }
3347 thread->exit();
3348
Eric Laurentdae20d92009-08-04 08:37:05 -07003349 if (thread->type() != PlaybackThread::DUPLICATING) {
3350 mAudioHardware->closeOutputStream(thread->getOutput());
3351 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003352 return NO_ERROR;
3353}
3354
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003355status_t AudioFlinger::suspendOutput(int output)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003356{
3357 Mutex::Autolock _l(mLock);
3358 PlaybackThread *thread = checkPlaybackThread_l(output);
3359
3360 if (thread == NULL) {
3361 return BAD_VALUE;
3362 }
3363
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003364 LOGV("suspendOutput() %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003365 thread->suspend();
3366
3367 return NO_ERROR;
3368}
3369
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003370status_t AudioFlinger::restoreOutput(int output)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003371{
3372 Mutex::Autolock _l(mLock);
3373 PlaybackThread *thread = checkPlaybackThread_l(output);
3374
3375 if (thread == NULL) {
3376 return BAD_VALUE;
3377 }
3378
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003379 LOGV("restoreOutput() %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003380
3381 thread->restore();
3382
3383 return NO_ERROR;
3384}
3385
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003386int AudioFlinger::openInput(uint32_t *pDevices,
Eric Laurent9d91ad52009-07-17 12:17:14 -07003387 uint32_t *pSamplingRate,
3388 uint32_t *pFormat,
3389 uint32_t *pChannels,
3390 uint32_t acoustics)
3391{
3392 status_t status;
3393 RecordThread *thread = NULL;
3394 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
3395 uint32_t format = pFormat ? *pFormat : 0;
3396 uint32_t channels = pChannels ? *pChannels : 0;
3397 uint32_t reqSamplingRate = samplingRate;
3398 uint32_t reqFormat = format;
3399 uint32_t reqChannels = channels;
3400
3401 if (pDevices == NULL || *pDevices == 0) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003402 return 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003403 }
3404 Mutex::Autolock _l(mLock);
3405
3406 AudioStreamIn *input = mAudioHardware->openInputStream(*pDevices,
3407 (int *)&format,
3408 &channels,
3409 &samplingRate,
3410 &status,
3411 (AudioSystem::audio_in_acoustics)acoustics);
3412 LOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
3413 input,
3414 samplingRate,
3415 format,
3416 channels,
3417 acoustics,
3418 status);
3419
3420 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
3421 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
3422 // or stereo to mono conversions on 16 bit PCM inputs.
3423 if (input == 0 && status == BAD_VALUE &&
3424 reqFormat == format && format == AudioSystem::PCM_16_BIT &&
3425 (samplingRate <= 2 * reqSamplingRate) &&
3426 (AudioSystem::popCount(channels) < 3) && (AudioSystem::popCount(reqChannels) < 3)) {
3427 LOGV("openInput() reopening with proposed sampling rate and channels");
3428 input = mAudioHardware->openInputStream(*pDevices,
3429 (int *)&format,
3430 &channels,
3431 &samplingRate,
3432 &status,
3433 (AudioSystem::audio_in_acoustics)acoustics);
3434 }
3435
3436 if (input != 0) {
3437 // Start record thread
3438 thread = new RecordThread(this, input, reqSamplingRate, reqChannels);
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003439 mRecordThreads.add(++mNextThreadId, thread);
3440 LOGV("openInput() created record thread: ID %d thread %p", mNextThreadId, thread);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003441 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
3442 if (pFormat) *pFormat = format;
3443 if (pChannels) *pChannels = reqChannels;
3444
3445 input->standby();
3446 }
3447
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003448 return mNextThreadId;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003449}
3450
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003451status_t AudioFlinger::closeInput(int input)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003452{
Eric Laurentdae20d92009-08-04 08:37:05 -07003453 // keep strong reference on the record thread so that
3454 // it is not destroyed while exit() is executed
3455 sp <RecordThread> thread;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003456 {
3457 Mutex::Autolock _l(mLock);
3458 thread = checkRecordThread_l(input);
3459 if (thread == NULL) {
3460 return BAD_VALUE;
3461 }
3462
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003463 LOGV("closeInput() %d", input);
3464 mRecordThreads.removeItem(input);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003465 }
3466 thread->exit();
3467
Eric Laurentdae20d92009-08-04 08:37:05 -07003468 mAudioHardware->closeInputStream(thread->getInput());
3469
Eric Laurent9d91ad52009-07-17 12:17:14 -07003470 return NO_ERROR;
3471}
3472
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003473status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003474{
3475 Mutex::Autolock _l(mLock);
3476 MixerThread *dstThread = checkMixerThread_l(output);
3477 if (dstThread == NULL) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003478 LOGW("setStreamOutput() bad output id %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003479 return BAD_VALUE;
3480 }
3481
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003482 LOGV("setStreamOutput() stream %d to output %d", stream, output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003483
3484 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003485 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent9d91ad52009-07-17 12:17:14 -07003486 if (thread != dstThread &&
3487 thread->type() != PlaybackThread::DIRECT) {
3488 MixerThread *srcThread = (MixerThread *)thread;
3489 SortedVector < sp<MixerThread::Track> > tracks;
3490 SortedVector < wp<MixerThread::Track> > activeTracks;
3491 srcThread->getTracks(tracks, activeTracks, stream);
3492 if (tracks.size()) {
3493 dstThread->putTracks(tracks, activeTracks);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003494 }
Eric Laurentd55d1792009-07-28 06:11:55 -07003495 dstThread->sendConfigEvent(AudioSystem::STREAM_CONFIG_CHANGED, stream);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003496 }
3497 }
3498
3499 return NO_ERROR;
3500}
3501
3502// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003503AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
Eric Laurent9d91ad52009-07-17 12:17:14 -07003504{
3505 PlaybackThread *thread = NULL;
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003506 if (mPlaybackThreads.indexOfKey(output) >= 0) {
3507 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
Eric Laurent9d91ad52009-07-17 12:17:14 -07003508 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003509 return thread;
3510}
3511
3512// checkMixerThread_l() must be called with AudioFlinger::mLock held
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003513AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
Eric Laurent9d91ad52009-07-17 12:17:14 -07003514{
3515 PlaybackThread *thread = checkPlaybackThread_l(output);
3516 if (thread != NULL) {
3517 if (thread->type() == PlaybackThread::DIRECT) {
3518 thread = NULL;
3519 }
3520 }
3521 return (MixerThread *)thread;
3522}
3523
3524// checkRecordThread_l() must be called with AudioFlinger::mLock held
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003525AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
Eric Laurent9d91ad52009-07-17 12:17:14 -07003526{
3527 RecordThread *thread = NULL;
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003528 if (mRecordThreads.indexOfKey(input) >= 0) {
3529 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
Eric Laurent9d91ad52009-07-17 12:17:14 -07003530 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003531 return thread;
3532}
3533
3534// ----------------------------------------------------------------------------
3535
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003536status_t AudioFlinger::onTransact(
3537 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3538{
3539 return BnAudioFlinger::onTransact(code, data, reply, flags);
3540}
3541
3542// ----------------------------------------------------------------------------
Eric Laurent9d91ad52009-07-17 12:17:14 -07003543
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003544void AudioFlinger::instantiate() {
3545 defaultServiceManager()->addService(
3546 String16("media.audio_flinger"), new AudioFlinger());
3547}
3548
3549}; // namespace android