AudioTrack.cpp revision c08d20b6a37122ebf116262c9372509ed060d4c1
146b20e7f41ded340596b732aaf08cc2d05a8e842Ying Wang/* 246b20e7f41ded340596b732aaf08cc2d05a8e842Ying Wang** 346b20e7f41ded340596b732aaf08cc2d05a8e842Ying Wang** Copyright 2007, The Android Open Source Project 446b20e7f41ded340596b732aaf08cc2d05a8e842Ying Wang** 546b20e7f41ded340596b732aaf08cc2d05a8e842Ying Wang** Licensed under the Apache License, Version 2.0 (the "License"); 646b20e7f41ded340596b732aaf08cc2d05a8e842Ying Wang** you may not use this file except in compliance with the License. 746b20e7f41ded340596b732aaf08cc2d05a8e842Ying Wang** You may obtain a copy of the License at 846b20e7f41ded340596b732aaf08cc2d05a8e842Ying Wang** 946b20e7f41ded340596b732aaf08cc2d05a8e842Ying Wang** http://www.apache.org/licenses/LICENSE-2.0 1046b20e7f41ded340596b732aaf08cc2d05a8e842Ying Wang** 1146b20e7f41ded340596b732aaf08cc2d05a8e842Ying Wang** Unless required by applicable law or agreed to in writing, software 1246b20e7f41ded340596b732aaf08cc2d05a8e842Ying Wang** distributed under the License is distributed on an "AS IS" BASIS, 1346b20e7f41ded340596b732aaf08cc2d05a8e842Ying Wang** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1446b20e7f41ded340596b732aaf08cc2d05a8e842Ying Wang** See the License for the specific language governing permissions and 1546b20e7f41ded340596b732aaf08cc2d05a8e842Ying Wang** limitations under the License. 1646b20e7f41ded340596b732aaf08cc2d05a8e842Ying Wang*/ 1746b20e7f41ded340596b732aaf08cc2d05a8e842Ying Wang 1846b20e7f41ded340596b732aaf08cc2d05a8e842Ying Wang 1946b20e7f41ded340596b732aaf08cc2d05a8e842Ying Wang//#define LOG_NDEBUG 0 208e359817da14f6a4ffcf3bf4f7a59bc4fef8c211Ying Wang#define LOG_TAG "AudioTrack" 21087610198e82bc5537b2a8e9c07ed6a20829a16dKeun young Park 22087610198e82bc5537b2a8e9c07ed6a20829a16dKeun young Park#include <sys/resource.h> 23087610198e82bc5537b2a8e9c07ed6a20829a16dKeun young Park#include <audio_utils/primitives.h> 24087610198e82bc5537b2a8e9c07ed6a20829a16dKeun young Park#include <binder/IPCThreadState.h> 25087610198e82bc5537b2a8e9c07ed6a20829a16dKeun young Park#include <media/AudioTrack.h> 26087610198e82bc5537b2a8e9c07ed6a20829a16dKeun young Park#include <utils/Log.h> 27087610198e82bc5537b2a8e9c07ed6a20829a16dKeun young Park#include <private/media/AudioTrackShared.h> 28087610198e82bc5537b2a8e9c07ed6a20829a16dKeun young Park#include <media/IAudioFlinger.h> 29087610198e82bc5537b2a8e9c07ed6a20829a16dKeun young Park 308e359817da14f6a4ffcf3bf4f7a59bc4fef8c211Ying Wang#define WAIT_PERIOD_MS 10 31087610198e82bc5537b2a8e9c07ed6a20829a16dKeun young Park#define WAIT_STREAM_END_TIMEOUT_SEC 120 32087610198e82bc5537b2a8e9c07ed6a20829a16dKeun young Park 33087610198e82bc5537b2a8e9c07ed6a20829a16dKeun young Park 348e359817da14f6a4ffcf3bf4f7a59bc4fef8c211Ying Wangnamespace android { 35087610198e82bc5537b2a8e9c07ed6a20829a16dKeun young Park// --------------------------------------------------------------------------- 36087610198e82bc5537b2a8e9c07ed6a20829a16dKeun young Park 37087610198e82bc5537b2a8e9c07ed6a20829a16dKeun young Park// static 38087610198e82bc5537b2a8e9c07ed6a20829a16dKeun young Parkstatus_t AudioTrack::getMinFrameCount( 39087610198e82bc5537b2a8e9c07ed6a20829a16dKeun young Park size_t* frameCount, 4046b20e7f41ded340596b732aaf08cc2d05a8e842Ying Wang audio_stream_type_t streamType, 418e359817da14f6a4ffcf3bf4f7a59bc4fef8c211Ying Wang uint32_t sampleRate) 42193ec66214ecf4cdb43702655a4a571ae0c7e6ceYing Wang{ 43193ec66214ecf4cdb43702655a4a571ae0c7e6ceYing Wang if (frameCount == NULL) { 44193ec66214ecf4cdb43702655a4a571ae0c7e6ceYing Wang return BAD_VALUE; 451c097a9c21096a0d677f336081bfdeb4cfc96063Russell Brenner } 46193ec66214ecf4cdb43702655a4a571ae0c7e6ceYing Wang 4746b20e7f41ded340596b732aaf08cc2d05a8e842Ying Wang // FIXME merge with similar code in createTrack_l(), except we're missing 488e359817da14f6a4ffcf3bf4f7a59bc4fef8c211Ying Wang // some information here that is available in createTrack_l(): 4946b20e7f41ded340596b732aaf08cc2d05a8e842Ying Wang // audio_io_handle_t output 5046b20e7f41ded340596b732aaf08cc2d05a8e842Ying Wang // audio_format_t format 5146b20e7f41ded340596b732aaf08cc2d05a8e842Ying Wang // audio_channel_mask_t channelMask 5246b20e7f41ded340596b732aaf08cc2d05a8e842Ying Wang // audio_output_flags_t flags 5346b20e7f41ded340596b732aaf08cc2d05a8e842Ying Wang uint32_t afSampleRate; 5446b20e7f41ded340596b732aaf08cc2d05a8e842Ying Wang status_t status; 551c097a9c21096a0d677f336081bfdeb4cfc96063Russell Brenner status = AudioSystem::getOutputSamplingRate(&afSampleRate, streamType); 561c097a9c21096a0d677f336081bfdeb4cfc96063Russell Brenner if (status != NO_ERROR) { 571c097a9c21096a0d677f336081bfdeb4cfc96063Russell Brenner ALOGE("Unable to query output sample rate for stream type %d; status %d", 581c097a9c21096a0d677f336081bfdeb4cfc96063Russell Brenner streamType, status); 591c097a9c21096a0d677f336081bfdeb4cfc96063Russell Brenner return status; 601c097a9c21096a0d677f336081bfdeb4cfc96063Russell Brenner } 611c097a9c21096a0d677f336081bfdeb4cfc96063Russell Brenner size_t afFrameCount; 621c097a9c21096a0d677f336081bfdeb4cfc96063Russell Brenner status = AudioSystem::getOutputFrameCount(&afFrameCount, streamType); 638e359817da14f6a4ffcf3bf4f7a59bc4fef8c211Ying Wang if (status != NO_ERROR) { 641c097a9c21096a0d677f336081bfdeb4cfc96063Russell Brenner ALOGE("Unable to query output frame count for stream type %d; status %d", 651c097a9c21096a0d677f336081bfdeb4cfc96063Russell Brenner streamType, status); 661c097a9c21096a0d677f336081bfdeb4cfc96063Russell Brenner return status; 671c097a9c21096a0d677f336081bfdeb4cfc96063Russell Brenner } 68ac1cbaf2e5575ac75a0160e13089d51a0bb232faBilly Hewlett uint32_t afLatency; 698e359817da14f6a4ffcf3bf4f7a59bc4fef8c211Ying Wang status = AudioSystem::getOutputLatency(&afLatency, streamType); 708e359817da14f6a4ffcf3bf4f7a59bc4fef8c211Ying Wang if (status != NO_ERROR) { 71193ec66214ecf4cdb43702655a4a571ae0c7e6ceYing Wang ALOGE("Unable to query output latency for stream type %d; status %d", 7246b20e7f41ded340596b732aaf08cc2d05a8e842Ying Wang streamType, status); 738e359817da14f6a4ffcf3bf4f7a59bc4fef8c211Ying Wang return status; 748e359817da14f6a4ffcf3bf4f7a59bc4fef8c211Ying Wang } 7546b20e7f41ded340596b732aaf08cc2d05a8e842Ying Wang 7646b20e7f41ded340596b732aaf08cc2d05a8e842Ying Wang // Ensure that buffer depth covers at least audio hardware latency 7746b20e7f41ded340596b732aaf08cc2d05a8e842Ying Wang uint32_t minBufCount = afLatency / ((1000 * afFrameCount) / afSampleRate); 781c097a9c21096a0d677f336081bfdeb4cfc96063Russell Brenner if (minBufCount < 2) { 7946b20e7f41ded340596b732aaf08cc2d05a8e842Ying Wang minBufCount = 2; 808e359817da14f6a4ffcf3bf4f7a59bc4fef8c211Ying Wang } 818e359817da14f6a4ffcf3bf4f7a59bc4fef8c211Ying Wang 828e359817da14f6a4ffcf3bf4f7a59bc4fef8c211Ying Wang *frameCount = (sampleRate == 0) ? afFrameCount * minBufCount : 838e359817da14f6a4ffcf3bf4f7a59bc4fef8c211Ying Wang afFrameCount * minBufCount * sampleRate / afSampleRate; 841c097a9c21096a0d677f336081bfdeb4cfc96063Russell Brenner // The formula above should always produce a non-zero value, but return an error 85193ec66214ecf4cdb43702655a4a571ae0c7e6ceYing Wang // in the unlikely event that it does not, as that's part of the API contract. 86193ec66214ecf4cdb43702655a4a571ae0c7e6ceYing Wang if (*frameCount == 0) { 87193ec66214ecf4cdb43702655a4a571ae0c7e6ceYing Wang ALOGE("AudioTrack::getMinFrameCount failed for streamType %d, sampleRate %d", 88193ec66214ecf4cdb43702655a4a571ae0c7e6ceYing Wang streamType, sampleRate); 89193ec66214ecf4cdb43702655a4a571ae0c7e6ceYing Wang return BAD_VALUE; 90193ec66214ecf4cdb43702655a4a571ae0c7e6ceYing Wang } 91193ec66214ecf4cdb43702655a4a571ae0c7e6ceYing Wang ALOGV("getMinFrameCount=%d: afFrameCount=%d, minBufCount=%d, afSampleRate=%d, afLatency=%d", 92193ec66214ecf4cdb43702655a4a571ae0c7e6ceYing Wang *frameCount, afFrameCount, minBufCount, afSampleRate, afLatency); 93193ec66214ecf4cdb43702655a4a571ae0c7e6ceYing Wang return NO_ERROR; 94193ec66214ecf4cdb43702655a4a571ae0c7e6ceYing Wang} 95193ec66214ecf4cdb43702655a4a571ae0c7e6ceYing Wang 96193ec66214ecf4cdb43702655a4a571ae0c7e6ceYing Wang// --------------------------------------------------------------------------- 97193ec66214ecf4cdb43702655a4a571ae0c7e6ceYing Wang 98193ec66214ecf4cdb43702655a4a571ae0c7e6ceYing WangAudioTrack::AudioTrack() 99193ec66214ecf4cdb43702655a4a571ae0c7e6ceYing Wang : mStatus(NO_INIT), 100193ec66214ecf4cdb43702655a4a571ae0c7e6ceYing Wang mIsTimed(false), 101193ec66214ecf4cdb43702655a4a571ae0c7e6ceYing Wang mPreviousPriority(ANDROID_PRIORITY_NORMAL), 102193ec66214ecf4cdb43702655a4a571ae0c7e6ceYing Wang mPreviousSchedulingGroup(SP_DEFAULT) 103193ec66214ecf4cdb43702655a4a571ae0c7e6ceYing Wang{ 104193ec66214ecf4cdb43702655a4a571ae0c7e6ceYing Wang} 105087610198e82bc5537b2a8e9c07ed6a20829a16dKeun young Park 106087610198e82bc5537b2a8e9c07ed6a20829a16dKeun young ParkAudioTrack::AudioTrack( 107087610198e82bc5537b2a8e9c07ed6a20829a16dKeun young Park audio_stream_type_t streamType, 108087610198e82bc5537b2a8e9c07ed6a20829a16dKeun young Park uint32_t sampleRate, 109087610198e82bc5537b2a8e9c07ed6a20829a16dKeun young Park audio_format_t format, 110087610198e82bc5537b2a8e9c07ed6a20829a16dKeun young Park audio_channel_mask_t channelMask, 111087610198e82bc5537b2a8e9c07ed6a20829a16dKeun young Park int frameCount, 112087610198e82bc5537b2a8e9c07ed6a20829a16dKeun young Park audio_output_flags_t flags, 113087610198e82bc5537b2a8e9c07ed6a20829a16dKeun young Park callback_t cbf, 114087610198e82bc5537b2a8e9c07ed6a20829a16dKeun young Park void* user, 115087610198e82bc5537b2a8e9c07ed6a20829a16dKeun young Park int notificationFrames, 116087610198e82bc5537b2a8e9c07ed6a20829a16dKeun young Park int sessionId, 117087610198e82bc5537b2a8e9c07ed6a20829a16dKeun young Park transfer_type transferType, 118087610198e82bc5537b2a8e9c07ed6a20829a16dKeun young Park const audio_offload_info_t *offloadInfo, 119be456f2e81ac9c205178883b6cbf880304665319Raph Levien int uid, 120be456f2e81ac9c205178883b6cbf880304665319Raph Levien pid_t pid) 121087610198e82bc5537b2a8e9c07ed6a20829a16dKeun young Park : mStatus(NO_INIT), 122087610198e82bc5537b2a8e9c07ed6a20829a16dKeun young Park mIsTimed(false), 123087610198e82bc5537b2a8e9c07ed6a20829a16dKeun young Park mPreviousPriority(ANDROID_PRIORITY_NORMAL), 124087610198e82bc5537b2a8e9c07ed6a20829a16dKeun young Park mPreviousSchedulingGroup(SP_DEFAULT) 125087610198e82bc5537b2a8e9c07ed6a20829a16dKeun young Park{ 126087610198e82bc5537b2a8e9c07ed6a20829a16dKeun young Park mStatus = set(streamType, sampleRate, format, channelMask, 127087610198e82bc5537b2a8e9c07ed6a20829a16dKeun young Park frameCount, flags, cbf, user, notificationFrames, 128289c09aae5879936bdeeabdc8047fcf2c7d28c6eRaph Levien 0 /*sharedBuffer*/, false /*threadCanCallJava*/, sessionId, transferType, 129289c09aae5879936bdeeabdc8047fcf2c7d28c6eRaph Levien offloadInfo, uid, pid); 130be456f2e81ac9c205178883b6cbf880304665319Raph Levien} 131be456f2e81ac9c205178883b6cbf880304665319Raph Levien 132467ea516175f5dfa52c4b9900d24e6b0062721d1Raph LevienAudioTrack::AudioTrack( 133467ea516175f5dfa52c4b9900d24e6b0062721d1Raph Levien audio_stream_type_t streamType, 134467ea516175f5dfa52c4b9900d24e6b0062721d1Raph Levien uint32_t sampleRate, 135467ea516175f5dfa52c4b9900d24e6b0062721d1Raph Levien audio_format_t format, 136f1596064d38b4e9f6cacd6703f282d376f32b5b3Justin Koh audio_channel_mask_t channelMask, 137f1596064d38b4e9f6cacd6703f282d376f32b5b3Justin Koh const sp<IMemory>& sharedBuffer, 138193ec66214ecf4cdb43702655a4a571ae0c7e6ceYing Wang audio_output_flags_t flags, 13915b8c185037410dfd15b65b2246500e0a2545c5dRaph Levien callback_t cbf, 140193ec66214ecf4cdb43702655a4a571ae0c7e6ceYing Wang void* user, 141193ec66214ecf4cdb43702655a4a571ae0c7e6ceYing Wang int notificationFrames, 142193ec66214ecf4cdb43702655a4a571ae0c7e6ceYing Wang int sessionId, 1434ce0931ffd78c0cfe1de37c291f96b5275ae53a4Victoria Lease transfer_type transferType, 1444ce0931ffd78c0cfe1de37c291f96b5275ae53a4Victoria Lease const audio_offload_info_t *offloadInfo, 145087610198e82bc5537b2a8e9c07ed6a20829a16dKeun young Park int uid, 146087610198e82bc5537b2a8e9c07ed6a20829a16dKeun young Park pid_t pid) 147193ec66214ecf4cdb43702655a4a571ae0c7e6ceYing Wang : mStatus(NO_INIT), 148193ec66214ecf4cdb43702655a4a571ae0c7e6ceYing Wang mIsTimed(false), 149193ec66214ecf4cdb43702655a4a571ae0c7e6ceYing Wang mPreviousPriority(ANDROID_PRIORITY_NORMAL), 150193ec66214ecf4cdb43702655a4a571ae0c7e6ceYing Wang mPreviousSchedulingGroup(SP_DEFAULT) 151193ec66214ecf4cdb43702655a4a571ae0c7e6ceYing Wang{ 152 mStatus = set(streamType, sampleRate, format, channelMask, 153 0 /*frameCount*/, flags, cbf, user, notificationFrames, 154 sharedBuffer, false /*threadCanCallJava*/, sessionId, transferType, offloadInfo, 155 uid, pid); 156} 157 158AudioTrack::~AudioTrack() 159{ 160 if (mStatus == NO_ERROR) { 161 // Make sure that callback function exits in the case where 162 // it is looping on buffer full condition in obtainBuffer(). 163 // Otherwise the callback thread will never exit. 164 stop(); 165 if (mAudioTrackThread != 0) { 166 mProxy->interrupt(); 167 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h 168 mAudioTrackThread->requestExitAndWait(); 169 mAudioTrackThread.clear(); 170 } 171 mAudioTrack->asBinder()->unlinkToDeath(mDeathNotifier, this); 172 mAudioTrack.clear(); 173 IPCThreadState::self()->flushCommands(); 174 ALOGV("~AudioTrack, releasing session id from %d on behalf of %d", 175 IPCThreadState::self()->getCallingPid(), mClientPid); 176 AudioSystem::releaseAudioSessionId(mSessionId, mClientPid); 177 } 178} 179 180status_t AudioTrack::set( 181 audio_stream_type_t streamType, 182 uint32_t sampleRate, 183 audio_format_t format, 184 audio_channel_mask_t channelMask, 185 int frameCountInt, 186 audio_output_flags_t flags, 187 callback_t cbf, 188 void* user, 189 int notificationFrames, 190 const sp<IMemory>& sharedBuffer, 191 bool threadCanCallJava, 192 int sessionId, 193 transfer_type transferType, 194 const audio_offload_info_t *offloadInfo, 195 int uid, 196 pid_t pid) 197{ 198 ALOGV("set(): streamType %d, sampleRate %u, format %#x, channelMask %#x, frameCount %d, " 199 "flags #%x, notificationFrames %d, sessionId %d, transferType %d", 200 streamType, sampleRate, format, channelMask, frameCountInt, flags, notificationFrames, 201 sessionId, transferType); 202 203 switch (transferType) { 204 case TRANSFER_DEFAULT: 205 if (sharedBuffer != 0) { 206 transferType = TRANSFER_SHARED; 207 } else if (cbf == NULL || threadCanCallJava) { 208 transferType = TRANSFER_SYNC; 209 } else { 210 transferType = TRANSFER_CALLBACK; 211 } 212 break; 213 case TRANSFER_CALLBACK: 214 if (cbf == NULL || sharedBuffer != 0) { 215 ALOGE("Transfer type TRANSFER_CALLBACK but cbf == NULL || sharedBuffer != 0"); 216 return BAD_VALUE; 217 } 218 break; 219 case TRANSFER_OBTAIN: 220 case TRANSFER_SYNC: 221 if (sharedBuffer != 0) { 222 ALOGE("Transfer type TRANSFER_OBTAIN but sharedBuffer != 0"); 223 return BAD_VALUE; 224 } 225 break; 226 case TRANSFER_SHARED: 227 if (sharedBuffer == 0) { 228 ALOGE("Transfer type TRANSFER_SHARED but sharedBuffer == 0"); 229 return BAD_VALUE; 230 } 231 break; 232 default: 233 ALOGE("Invalid transfer type %d", transferType); 234 return BAD_VALUE; 235 } 236 mSharedBuffer = sharedBuffer; 237 mTransfer = transferType; 238 239 // FIXME "int" here is legacy and will be replaced by size_t later 240 if (frameCountInt < 0) { 241 ALOGE("Invalid frame count %d", frameCountInt); 242 return BAD_VALUE; 243 } 244 size_t frameCount = frameCountInt; 245 246 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), 247 sharedBuffer->size()); 248 249 ALOGV("set() streamType %d frameCount %u flags %04x", streamType, frameCount, flags); 250 251 AutoMutex lock(mLock); 252 253 // invariant that mAudioTrack != 0 is true only after set() returns successfully 254 if (mAudioTrack != 0) { 255 ALOGE("Track already in use"); 256 return INVALID_OPERATION; 257 } 258 259 // handle default values first. 260 if (streamType == AUDIO_STREAM_DEFAULT) { 261 streamType = AUDIO_STREAM_MUSIC; 262 } 263 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) { 264 ALOGE("Invalid stream type %d", streamType); 265 return BAD_VALUE; 266 } 267 mStreamType = streamType; 268 269 status_t status; 270 if (sampleRate == 0) { 271 status = AudioSystem::getOutputSamplingRate(&sampleRate, streamType); 272 if (status != NO_ERROR) { 273 ALOGE("Could not get output sample rate for stream type %d; status %d", 274 streamType, status); 275 return status; 276 } 277 } 278 mSampleRate = sampleRate; 279 280 // these below should probably come from the audioFlinger too... 281 if (format == AUDIO_FORMAT_DEFAULT) { 282 format = AUDIO_FORMAT_PCM_16_BIT; 283 } 284 285 // validate parameters 286 if (!audio_is_valid_format(format)) { 287 ALOGE("Invalid format %#x", format); 288 return BAD_VALUE; 289 } 290 mFormat = format; 291 292 if (!audio_is_output_channel(channelMask)) { 293 ALOGE("Invalid channel mask %#x", channelMask); 294 return BAD_VALUE; 295 } 296 mChannelMask = channelMask; 297 uint32_t channelCount = popcount(channelMask); 298 mChannelCount = channelCount; 299 300 // AudioFlinger does not currently support 8-bit data in shared memory 301 if (format == AUDIO_FORMAT_PCM_8_BIT && sharedBuffer != 0) { 302 ALOGE("8-bit data in shared memory is not supported"); 303 return BAD_VALUE; 304 } 305 306 // force direct flag if format is not linear PCM 307 // or offload was requested 308 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) 309 || !audio_is_linear_pcm(format)) { 310 ALOGV( (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) 311 ? "Offload request, forcing to Direct Output" 312 : "Not linear PCM, forcing to Direct Output"); 313 flags = (audio_output_flags_t) 314 // FIXME why can't we allow direct AND fast? 315 ((flags | AUDIO_OUTPUT_FLAG_DIRECT) & ~AUDIO_OUTPUT_FLAG_FAST); 316 } 317 // only allow deep buffering for music stream type 318 if (streamType != AUDIO_STREAM_MUSIC) { 319 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER); 320 } 321 322 if (audio_is_linear_pcm(format)) { 323 mFrameSize = channelCount * audio_bytes_per_sample(format); 324 mFrameSizeAF = channelCount * sizeof(int16_t); 325 } else { 326 mFrameSize = sizeof(uint8_t); 327 mFrameSizeAF = sizeof(uint8_t); 328 } 329 330 // Make copy of input parameter offloadInfo so that in the future: 331 // (a) createTrack_l doesn't need it as an input parameter 332 // (b) we can support re-creation of offloaded tracks 333 if (offloadInfo != NULL) { 334 mOffloadInfoCopy = *offloadInfo; 335 mOffloadInfo = &mOffloadInfoCopy; 336 } else { 337 mOffloadInfo = NULL; 338 } 339 340 mVolume[LEFT] = 1.0f; 341 mVolume[RIGHT] = 1.0f; 342 mSendLevel = 0.0f; 343 // mFrameCount is initialized in createTrack_l 344 mReqFrameCount = frameCount; 345 mNotificationFramesReq = notificationFrames; 346 mNotificationFramesAct = 0; 347 mSessionId = sessionId; 348 int callingpid = IPCThreadState::self()->getCallingPid(); 349 int mypid = getpid(); 350 if (uid == -1 || (callingpid != mypid)) { 351 mClientUid = IPCThreadState::self()->getCallingUid(); 352 } else { 353 mClientUid = uid; 354 } 355 if (pid == -1 || (callingpid != mypid)) { 356 mClientPid = callingpid; 357 } else { 358 mClientPid = pid; 359 } 360 mAuxEffectId = 0; 361 mFlags = flags; 362 mCbf = cbf; 363 364 if (cbf != NULL) { 365 mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava); 366 mAudioTrackThread->run("AudioTrack", ANDROID_PRIORITY_AUDIO, 0 /*stack*/); 367 } 368 369 // create the IAudioTrack 370 status = createTrack_l(0 /*epoch*/); 371 372 if (status != NO_ERROR) { 373 if (mAudioTrackThread != 0) { 374 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h 375 mAudioTrackThread->requestExitAndWait(); 376 mAudioTrackThread.clear(); 377 } 378 // Use of direct and offloaded output streams is ref counted by audio policy manager. 379#if 0 // FIXME This should no longer be needed 380 //Use of direct and offloaded output streams is ref counted by audio policy manager. 381 // As getOutput was called above and resulted in an output stream to be opened, 382 // we need to release it. 383 if (mOutput != 0) { 384 AudioSystem::releaseOutput(mOutput); 385 mOutput = 0; 386 } 387#endif 388 return status; 389 } 390 391 mStatus = NO_ERROR; 392 mState = STATE_STOPPED; 393 mUserData = user; 394 mLoopPeriod = 0; 395 mMarkerPosition = 0; 396 mMarkerReached = false; 397 mNewPosition = 0; 398 mUpdatePeriod = 0; 399 AudioSystem::acquireAudioSessionId(mSessionId, mClientPid); 400 mSequence = 1; 401 mObservedSequence = mSequence; 402 mInUnderrun = false; 403 404 return NO_ERROR; 405} 406 407// ------------------------------------------------------------------------- 408 409status_t AudioTrack::start() 410{ 411 AutoMutex lock(mLock); 412 413 if (mState == STATE_ACTIVE) { 414 return INVALID_OPERATION; 415 } 416 417 mInUnderrun = true; 418 419 State previousState = mState; 420 if (previousState == STATE_PAUSED_STOPPING) { 421 mState = STATE_STOPPING; 422 } else { 423 mState = STATE_ACTIVE; 424 } 425 if (previousState == STATE_STOPPED || previousState == STATE_FLUSHED) { 426 // reset current position as seen by client to 0 427 mProxy->setEpoch(mProxy->getEpoch() - mProxy->getPosition()); 428 // force refresh of remaining frames by processAudioBuffer() as last 429 // write before stop could be partial. 430 mRefreshRemaining = true; 431 } 432 mNewPosition = mProxy->getPosition() + mUpdatePeriod; 433 int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags); 434 435 sp<AudioTrackThread> t = mAudioTrackThread; 436 if (t != 0) { 437 if (previousState == STATE_STOPPING) { 438 mProxy->interrupt(); 439 } else { 440 t->resume(); 441 } 442 } else { 443 mPreviousPriority = getpriority(PRIO_PROCESS, 0); 444 get_sched_policy(0, &mPreviousSchedulingGroup); 445 androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO); 446 } 447 448 status_t status = NO_ERROR; 449 if (!(flags & CBLK_INVALID)) { 450 status = mAudioTrack->start(); 451 if (status == DEAD_OBJECT) { 452 flags |= CBLK_INVALID; 453 } 454 } 455 if (flags & CBLK_INVALID) { 456 status = restoreTrack_l("start"); 457 } 458 459 if (status != NO_ERROR) { 460 ALOGE("start() status %d", status); 461 mState = previousState; 462 if (t != 0) { 463 if (previousState != STATE_STOPPING) { 464 t->pause(); 465 } 466 } else { 467 setpriority(PRIO_PROCESS, 0, mPreviousPriority); 468 set_sched_policy(0, mPreviousSchedulingGroup); 469 } 470 } 471 472 return status; 473} 474 475void AudioTrack::stop() 476{ 477 AutoMutex lock(mLock); 478 if (mState != STATE_ACTIVE && mState != STATE_PAUSED) { 479 return; 480 } 481 482 if (isOffloaded_l()) { 483 mState = STATE_STOPPING; 484 } else { 485 mState = STATE_STOPPED; 486 } 487 488 mProxy->interrupt(); 489 mAudioTrack->stop(); 490 // the playback head position will reset to 0, so if a marker is set, we need 491 // to activate it again 492 mMarkerReached = false; 493#if 0 494 // Force flush if a shared buffer is used otherwise audioflinger 495 // will not stop before end of buffer is reached. 496 // It may be needed to make sure that we stop playback, likely in case looping is on. 497 if (mSharedBuffer != 0) { 498 flush_l(); 499 } 500#endif 501 502 sp<AudioTrackThread> t = mAudioTrackThread; 503 if (t != 0) { 504 if (!isOffloaded_l()) { 505 t->pause(); 506 } 507 } else { 508 setpriority(PRIO_PROCESS, 0, mPreviousPriority); 509 set_sched_policy(0, mPreviousSchedulingGroup); 510 } 511} 512 513bool AudioTrack::stopped() const 514{ 515 AutoMutex lock(mLock); 516 return mState != STATE_ACTIVE; 517} 518 519void AudioTrack::flush() 520{ 521 if (mSharedBuffer != 0) { 522 return; 523 } 524 AutoMutex lock(mLock); 525 if (mState == STATE_ACTIVE || mState == STATE_FLUSHED) { 526 return; 527 } 528 flush_l(); 529} 530 531void AudioTrack::flush_l() 532{ 533 ALOG_ASSERT(mState != STATE_ACTIVE); 534 535 // clear playback marker and periodic update counter 536 mMarkerPosition = 0; 537 mMarkerReached = false; 538 mUpdatePeriod = 0; 539 mRefreshRemaining = true; 540 541 mState = STATE_FLUSHED; 542 if (isOffloaded_l()) { 543 mProxy->interrupt(); 544 } 545 mProxy->flush(); 546 mAudioTrack->flush(); 547} 548 549void AudioTrack::pause() 550{ 551 AutoMutex lock(mLock); 552 if (mState == STATE_ACTIVE) { 553 mState = STATE_PAUSED; 554 } else if (mState == STATE_STOPPING) { 555 mState = STATE_PAUSED_STOPPING; 556 } else { 557 return; 558 } 559 mProxy->interrupt(); 560 mAudioTrack->pause(); 561} 562 563status_t AudioTrack::setVolume(float left, float right) 564{ 565 if (left < 0.0f || left > 1.0f || right < 0.0f || right > 1.0f) { 566 return BAD_VALUE; 567 } 568 569 AutoMutex lock(mLock); 570 mVolume[LEFT] = left; 571 mVolume[RIGHT] = right; 572 573 mProxy->setVolumeLR((uint32_t(uint16_t(right * 0x1000)) << 16) | uint16_t(left * 0x1000)); 574 575 if (isOffloaded_l()) { 576 mAudioTrack->signal(); 577 } 578 return NO_ERROR; 579} 580 581status_t AudioTrack::setVolume(float volume) 582{ 583 return setVolume(volume, volume); 584} 585 586status_t AudioTrack::setAuxEffectSendLevel(float level) 587{ 588 if (level < 0.0f || level > 1.0f) { 589 return BAD_VALUE; 590 } 591 592 AutoMutex lock(mLock); 593 mSendLevel = level; 594 mProxy->setSendLevel(level); 595 596 return NO_ERROR; 597} 598 599void AudioTrack::getAuxEffectSendLevel(float* level) const 600{ 601 if (level != NULL) { 602 *level = mSendLevel; 603 } 604} 605 606status_t AudioTrack::setSampleRate(uint32_t rate) 607{ 608 if (mIsTimed || isOffloaded()) { 609 return INVALID_OPERATION; 610 } 611 612 uint32_t afSamplingRate; 613 if (AudioSystem::getOutputSamplingRate(&afSamplingRate, mStreamType) != NO_ERROR) { 614 return NO_INIT; 615 } 616 // Resampler implementation limits input sampling rate to 2 x output sampling rate. 617 if (rate == 0 || rate > afSamplingRate*2 ) { 618 return BAD_VALUE; 619 } 620 621 AutoMutex lock(mLock); 622 mSampleRate = rate; 623 mProxy->setSampleRate(rate); 624 625 return NO_ERROR; 626} 627 628uint32_t AudioTrack::getSampleRate() const 629{ 630 if (mIsTimed) { 631 return 0; 632 } 633 634 AutoMutex lock(mLock); 635 636 // sample rate can be updated during playback by the offloaded decoder so we need to 637 // query the HAL and update if needed. 638// FIXME use Proxy return channel to update the rate from server and avoid polling here 639 if (isOffloaded_l()) { 640 if (mOutput != 0) { 641 uint32_t sampleRate = 0; 642 status_t status = AudioSystem::getSamplingRate(mOutput, mStreamType, &sampleRate); 643 if (status == NO_ERROR) { 644 mSampleRate = sampleRate; 645 } 646 } 647 } 648 return mSampleRate; 649} 650 651status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount) 652{ 653 if (mSharedBuffer == 0 || mIsTimed || isOffloaded()) { 654 return INVALID_OPERATION; 655 } 656 657 if (loopCount == 0) { 658 ; 659 } else if (loopCount >= -1 && loopStart < loopEnd && loopEnd <= mFrameCount && 660 loopEnd - loopStart >= MIN_LOOP) { 661 ; 662 } else { 663 return BAD_VALUE; 664 } 665 666 AutoMutex lock(mLock); 667 // See setPosition() regarding setting parameters such as loop points or position while active 668 if (mState == STATE_ACTIVE) { 669 return INVALID_OPERATION; 670 } 671 setLoop_l(loopStart, loopEnd, loopCount); 672 return NO_ERROR; 673} 674 675void AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount) 676{ 677 // FIXME If setting a loop also sets position to start of loop, then 678 // this is correct. Otherwise it should be removed. 679 mNewPosition = mProxy->getPosition() + mUpdatePeriod; 680 mLoopPeriod = loopCount != 0 ? loopEnd - loopStart : 0; 681 mStaticProxy->setLoop(loopStart, loopEnd, loopCount); 682} 683 684status_t AudioTrack::setMarkerPosition(uint32_t marker) 685{ 686 // The only purpose of setting marker position is to get a callback 687 if (mCbf == NULL || isOffloaded()) { 688 return INVALID_OPERATION; 689 } 690 691 AutoMutex lock(mLock); 692 mMarkerPosition = marker; 693 mMarkerReached = false; 694 695 return NO_ERROR; 696} 697 698status_t AudioTrack::getMarkerPosition(uint32_t *marker) const 699{ 700 if (isOffloaded()) { 701 return INVALID_OPERATION; 702 } 703 if (marker == NULL) { 704 return BAD_VALUE; 705 } 706 707 AutoMutex lock(mLock); 708 *marker = mMarkerPosition; 709 710 return NO_ERROR; 711} 712 713status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod) 714{ 715 // The only purpose of setting position update period is to get a callback 716 if (mCbf == NULL || isOffloaded()) { 717 return INVALID_OPERATION; 718 } 719 720 AutoMutex lock(mLock); 721 mNewPosition = mProxy->getPosition() + updatePeriod; 722 mUpdatePeriod = updatePeriod; 723 724 return NO_ERROR; 725} 726 727status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod) const 728{ 729 if (isOffloaded()) { 730 return INVALID_OPERATION; 731 } 732 if (updatePeriod == NULL) { 733 return BAD_VALUE; 734 } 735 736 AutoMutex lock(mLock); 737 *updatePeriod = mUpdatePeriod; 738 739 return NO_ERROR; 740} 741 742status_t AudioTrack::setPosition(uint32_t position) 743{ 744 if (mSharedBuffer == 0 || mIsTimed || isOffloaded()) { 745 return INVALID_OPERATION; 746 } 747 if (position > mFrameCount) { 748 return BAD_VALUE; 749 } 750 751 AutoMutex lock(mLock); 752 // Currently we require that the player is inactive before setting parameters such as position 753 // or loop points. Otherwise, there could be a race condition: the application could read the 754 // current position, compute a new position or loop parameters, and then set that position or 755 // loop parameters but it would do the "wrong" thing since the position has continued to advance 756 // in the mean time. If we ever provide a sequencer in server, we could allow a way for the app 757 // to specify how it wants to handle such scenarios. 758 if (mState == STATE_ACTIVE) { 759 return INVALID_OPERATION; 760 } 761 mNewPosition = mProxy->getPosition() + mUpdatePeriod; 762 mLoopPeriod = 0; 763 // FIXME Check whether loops and setting position are incompatible in old code. 764 // If we use setLoop for both purposes we lose the capability to set the position while looping. 765 mStaticProxy->setLoop(position, mFrameCount, 0); 766 767 return NO_ERROR; 768} 769 770status_t AudioTrack::getPosition(uint32_t *position) const 771{ 772 if (position == NULL) { 773 return BAD_VALUE; 774 } 775 776 AutoMutex lock(mLock); 777 if (isOffloaded_l()) { 778 uint32_t dspFrames = 0; 779 780 if (mOutput != 0) { 781 uint32_t halFrames; 782 AudioSystem::getRenderPosition(mOutput, &halFrames, &dspFrames); 783 } 784 *position = dspFrames; 785 } else { 786 // IAudioTrack::stop() isn't synchronous; we don't know when presentation completes 787 *position = (mState == STATE_STOPPED || mState == STATE_FLUSHED) ? 0 : 788 mProxy->getPosition(); 789 } 790 return NO_ERROR; 791} 792 793status_t AudioTrack::getBufferPosition(uint32_t *position) 794{ 795 if (mSharedBuffer == 0 || mIsTimed) { 796 return INVALID_OPERATION; 797 } 798 if (position == NULL) { 799 return BAD_VALUE; 800 } 801 802 AutoMutex lock(mLock); 803 *position = mStaticProxy->getBufferPosition(); 804 return NO_ERROR; 805} 806 807status_t AudioTrack::reload() 808{ 809 if (mSharedBuffer == 0 || mIsTimed || isOffloaded()) { 810 return INVALID_OPERATION; 811 } 812 813 AutoMutex lock(mLock); 814 // See setPosition() regarding setting parameters such as loop points or position while active 815 if (mState == STATE_ACTIVE) { 816 return INVALID_OPERATION; 817 } 818 mNewPosition = mUpdatePeriod; 819 mLoopPeriod = 0; 820 // FIXME The new code cannot reload while keeping a loop specified. 821 // Need to check how the old code handled this, and whether it's a significant change. 822 mStaticProxy->setLoop(0, mFrameCount, 0); 823 return NO_ERROR; 824} 825 826audio_io_handle_t AudioTrack::getOutput() const 827{ 828 AutoMutex lock(mLock); 829 return mOutput; 830} 831 832status_t AudioTrack::attachAuxEffect(int effectId) 833{ 834 AutoMutex lock(mLock); 835 status_t status = mAudioTrack->attachAuxEffect(effectId); 836 if (status == NO_ERROR) { 837 mAuxEffectId = effectId; 838 } 839 return status; 840} 841 842// ------------------------------------------------------------------------- 843 844// must be called with mLock held 845status_t AudioTrack::createTrack_l(size_t epoch) 846{ 847 status_t status; 848 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger(); 849 if (audioFlinger == 0) { 850 ALOGE("Could not get audioflinger"); 851 return NO_INIT; 852 } 853 854 audio_io_handle_t output = AudioSystem::getOutput(mStreamType, mSampleRate, mFormat, 855 mChannelMask, mFlags, mOffloadInfo); 856 if (output == 0) { 857 ALOGE("Could not get audio output for stream type %d, sample rate %u, format %#x, " 858 "channel mask %#x, flags %#x", 859 mStreamType, mSampleRate, mFormat, mChannelMask, mFlags); 860 return BAD_VALUE; 861 } 862 { 863 // Now that we have a reference to an I/O handle and have not yet handed it off to AudioFlinger, 864 // we must release it ourselves if anything goes wrong. 865 866 // Not all of these values are needed under all conditions, but it is easier to get them all 867 868 uint32_t afLatency; 869 status = AudioSystem::getLatency(output, mStreamType, &afLatency); 870 if (status != NO_ERROR) { 871 ALOGE("getLatency(%d) failed status %d", output, status); 872 goto release; 873 } 874 875 size_t afFrameCount; 876 status = AudioSystem::getFrameCount(output, mStreamType, &afFrameCount); 877 if (status != NO_ERROR) { 878 ALOGE("getFrameCount(output=%d, streamType=%d) status %d", output, mStreamType, status); 879 goto release; 880 } 881 882 uint32_t afSampleRate; 883 status = AudioSystem::getSamplingRate(output, mStreamType, &afSampleRate); 884 if (status != NO_ERROR) { 885 ALOGE("getSamplingRate(output=%d, streamType=%d) status %d", output, mStreamType, status); 886 goto release; 887 } 888 889 // Client decides whether the track is TIMED (see below), but can only express a preference 890 // for FAST. Server will perform additional tests. 891 if ((mFlags & AUDIO_OUTPUT_FLAG_FAST) && !(( 892 // either of these use cases: 893 // use case 1: shared buffer 894 (mSharedBuffer != 0) || 895 // use case 2: callback handler 896 (mCbf != NULL)) && 897 // matching sample rate 898 (mSampleRate == afSampleRate))) { 899 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied by client"); 900 // once denied, do not request again if IAudioTrack is re-created 901 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST); 902 } 903 ALOGV("createTrack_l() output %d afLatency %d", output, afLatency); 904 905 // The client's AudioTrack buffer is divided into n parts for purpose of wakeup by server, where 906 // n = 1 fast track with single buffering; nBuffering is ignored 907 // n = 2 fast track with double buffering 908 // n = 2 normal track, no sample rate conversion 909 // n = 3 normal track, with sample rate conversion 910 // (pessimistic; some non-1:1 conversion ratios don't actually need triple-buffering) 911 // n > 3 very high latency or very small notification interval; nBuffering is ignored 912 const uint32_t nBuffering = (mSampleRate == afSampleRate) ? 2 : 3; 913 914 mNotificationFramesAct = mNotificationFramesReq; 915 916 size_t frameCount = mReqFrameCount; 917 if (!audio_is_linear_pcm(mFormat)) { 918 919 if (mSharedBuffer != 0) { 920 // Same comment as below about ignoring frameCount parameter for set() 921 frameCount = mSharedBuffer->size(); 922 } else if (frameCount == 0) { 923 frameCount = afFrameCount; 924 } 925 if (mNotificationFramesAct != frameCount) { 926 mNotificationFramesAct = frameCount; 927 } 928 } else if (mSharedBuffer != 0) { 929 930 // Ensure that buffer alignment matches channel count 931 // 8-bit data in shared memory is not currently supported by AudioFlinger 932 size_t alignment = /* mFormat == AUDIO_FORMAT_PCM_8_BIT ? 1 : */ 2; 933 if (mChannelCount > 1) { 934 // More than 2 channels does not require stronger alignment than stereo 935 alignment <<= 1; 936 } 937 if (((uintptr_t)mSharedBuffer->pointer() & (alignment - 1)) != 0) { 938 ALOGE("Invalid buffer alignment: address %p, channel count %u", 939 mSharedBuffer->pointer(), mChannelCount); 940 status = BAD_VALUE; 941 goto release; 942 } 943 944 // When initializing a shared buffer AudioTrack via constructors, 945 // there's no frameCount parameter. 946 // But when initializing a shared buffer AudioTrack via set(), 947 // there _is_ a frameCount parameter. We silently ignore it. 948 frameCount = mSharedBuffer->size()/mChannelCount/sizeof(int16_t); 949 950 } else if (!(mFlags & AUDIO_OUTPUT_FLAG_FAST)) { 951 952 // FIXME move these calculations and associated checks to server 953 954 // Ensure that buffer depth covers at least audio hardware latency 955 uint32_t minBufCount = afLatency / ((1000 * afFrameCount)/afSampleRate); 956 ALOGV("afFrameCount=%d, minBufCount=%d, afSampleRate=%u, afLatency=%d", 957 afFrameCount, minBufCount, afSampleRate, afLatency); 958 if (minBufCount <= nBuffering) { 959 minBufCount = nBuffering; 960 } 961 962 size_t minFrameCount = (afFrameCount*mSampleRate*minBufCount)/afSampleRate; 963 ALOGV("minFrameCount: %u, afFrameCount=%d, minBufCount=%d, sampleRate=%u, afSampleRate=%u" 964 ", afLatency=%d", 965 minFrameCount, afFrameCount, minBufCount, mSampleRate, afSampleRate, afLatency); 966 967 if (frameCount == 0) { 968 frameCount = minFrameCount; 969 } else if (frameCount < minFrameCount) { 970 // not ALOGW because it happens all the time when playing key clicks over A2DP 971 ALOGV("Minimum buffer size corrected from %d to %d", 972 frameCount, minFrameCount); 973 frameCount = minFrameCount; 974 } 975 // Make sure that application is notified with sufficient margin before underrun 976 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) { 977 mNotificationFramesAct = frameCount/nBuffering; 978 } 979 980 } else { 981 // For fast tracks, the frame count calculations and checks are done by server 982 } 983 984 IAudioFlinger::track_flags_t trackFlags = IAudioFlinger::TRACK_DEFAULT; 985 if (mIsTimed) { 986 trackFlags |= IAudioFlinger::TRACK_TIMED; 987 } 988 989 pid_t tid = -1; 990 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) { 991 trackFlags |= IAudioFlinger::TRACK_FAST; 992 if (mAudioTrackThread != 0) { 993 tid = mAudioTrackThread->getTid(); 994 } 995 } 996 997 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) { 998 trackFlags |= IAudioFlinger::TRACK_OFFLOAD; 999 } 1000 1001 size_t temp = frameCount; // temp may be replaced by a revised value of frameCount, 1002 // but we will still need the original value also 1003 sp<IAudioTrack> track = audioFlinger->createTrack(mStreamType, 1004 mSampleRate, 1005 // AudioFlinger only sees 16-bit PCM 1006 mFormat == AUDIO_FORMAT_PCM_8_BIT ? 1007 AUDIO_FORMAT_PCM_16_BIT : mFormat, 1008 mChannelMask, 1009 &temp, 1010 &trackFlags, 1011 mSharedBuffer, 1012 output, 1013 tid, 1014 &mSessionId, 1015 mName, 1016 mClientUid, 1017 &status); 1018 1019 if (status != NO_ERROR) { 1020 ALOGE("AudioFlinger could not create track, status: %d", status); 1021 goto release; 1022 } 1023 ALOG_ASSERT(track != 0); 1024 1025 // AudioFlinger now owns the reference to the I/O handle, 1026 // so we are no longer responsible for releasing it. 1027 1028 sp<IMemory> iMem = track->getCblk(); 1029 if (iMem == 0) { 1030 ALOGE("Could not get control block"); 1031 return NO_INIT; 1032 } 1033 void *iMemPointer = iMem->pointer(); 1034 if (iMemPointer == NULL) { 1035 ALOGE("Could not get control block pointer"); 1036 return NO_INIT; 1037 } 1038 // invariant that mAudioTrack != 0 is true only after set() returns successfully 1039 if (mAudioTrack != 0) { 1040 mAudioTrack->asBinder()->unlinkToDeath(mDeathNotifier, this); 1041 mDeathNotifier.clear(); 1042 } 1043 mAudioTrack = track; 1044 1045 mCblkMemory = iMem; 1046 audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMemPointer); 1047 mCblk = cblk; 1048 // note that temp is the (possibly revised) value of frameCount 1049 if (temp < frameCount || (frameCount == 0 && temp == 0)) { 1050 // In current design, AudioTrack client checks and ensures frame count validity before 1051 // passing it to AudioFlinger so AudioFlinger should not return a different value except 1052 // for fast track as it uses a special method of assigning frame count. 1053 ALOGW("Requested frameCount %u but received frameCount %u", frameCount, temp); 1054 } 1055 frameCount = temp; 1056 1057 mAwaitBoost = false; 1058 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) { 1059 if (trackFlags & IAudioFlinger::TRACK_FAST) { 1060 ALOGV("AUDIO_OUTPUT_FLAG_FAST successful; frameCount %u", frameCount); 1061 mAwaitBoost = true; 1062 if (mSharedBuffer == 0) { 1063 // Theoretically double-buffering is not required for fast tracks, 1064 // due to tighter scheduling. But in practice, to accommodate kernels with 1065 // scheduling jitter, and apps with computation jitter, we use double-buffering. 1066 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) { 1067 mNotificationFramesAct = frameCount/nBuffering; 1068 } 1069 } 1070 } else { 1071 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied by server; frameCount %u", frameCount); 1072 // once denied, do not request again if IAudioTrack is re-created 1073 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST); 1074 if (mSharedBuffer == 0) { 1075 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) { 1076 mNotificationFramesAct = frameCount/nBuffering; 1077 } 1078 } 1079 } 1080 } 1081 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) { 1082 if (trackFlags & IAudioFlinger::TRACK_OFFLOAD) { 1083 ALOGV("AUDIO_OUTPUT_FLAG_OFFLOAD successful"); 1084 } else { 1085 ALOGW("AUDIO_OUTPUT_FLAG_OFFLOAD denied by server"); 1086 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD); 1087 // FIXME This is a warning, not an error, so don't return error status 1088 //return NO_INIT; 1089 } 1090 } 1091 1092 // We retain a copy of the I/O handle, but don't own the reference 1093 mOutput = output; 1094 mRefreshRemaining = true; 1095 1096 // Starting address of buffers in shared memory. If there is a shared buffer, buffers 1097 // is the value of pointer() for the shared buffer, otherwise buffers points 1098 // immediately after the control block. This address is for the mapping within client 1099 // address space. AudioFlinger::TrackBase::mBuffer is for the server address space. 1100 void* buffers; 1101 if (mSharedBuffer == 0) { 1102 buffers = (char*)cblk + sizeof(audio_track_cblk_t); 1103 } else { 1104 buffers = mSharedBuffer->pointer(); 1105 } 1106 1107 mAudioTrack->attachAuxEffect(mAuxEffectId); 1108 // FIXME don't believe this lie 1109 mLatency = afLatency + (1000*frameCount) / mSampleRate; 1110 1111 mFrameCount = frameCount; 1112 // If IAudioTrack is re-created, don't let the requested frameCount 1113 // decrease. This can confuse clients that cache frameCount(). 1114 if (frameCount > mReqFrameCount) { 1115 mReqFrameCount = frameCount; 1116 } 1117 1118 // update proxy 1119 if (mSharedBuffer == 0) { 1120 mStaticProxy.clear(); 1121 mProxy = new AudioTrackClientProxy(cblk, buffers, frameCount, mFrameSizeAF); 1122 } else { 1123 mStaticProxy = new StaticAudioTrackClientProxy(cblk, buffers, frameCount, mFrameSizeAF); 1124 mProxy = mStaticProxy; 1125 } 1126 mProxy->setVolumeLR((uint32_t(uint16_t(mVolume[RIGHT] * 0x1000)) << 16) | 1127 uint16_t(mVolume[LEFT] * 0x1000)); 1128 mProxy->setSendLevel(mSendLevel); 1129 mProxy->setSampleRate(mSampleRate); 1130 mProxy->setEpoch(epoch); 1131 mProxy->setMinimum(mNotificationFramesAct); 1132 1133 mDeathNotifier = new DeathNotifier(this); 1134 mAudioTrack->asBinder()->linkToDeath(mDeathNotifier, this); 1135 1136 return NO_ERROR; 1137 } 1138 1139release: 1140 AudioSystem::releaseOutput(output); 1141 if (status == NO_ERROR) { 1142 status = NO_INIT; 1143 } 1144 return status; 1145} 1146 1147status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount) 1148{ 1149 if (audioBuffer == NULL) { 1150 return BAD_VALUE; 1151 } 1152 if (mTransfer != TRANSFER_OBTAIN) { 1153 audioBuffer->frameCount = 0; 1154 audioBuffer->size = 0; 1155 audioBuffer->raw = NULL; 1156 return INVALID_OPERATION; 1157 } 1158 1159 const struct timespec *requested; 1160 struct timespec timeout; 1161 if (waitCount == -1) { 1162 requested = &ClientProxy::kForever; 1163 } else if (waitCount == 0) { 1164 requested = &ClientProxy::kNonBlocking; 1165 } else if (waitCount > 0) { 1166 long long ms = WAIT_PERIOD_MS * (long long) waitCount; 1167 timeout.tv_sec = ms / 1000; 1168 timeout.tv_nsec = (int) (ms % 1000) * 1000000; 1169 requested = &timeout; 1170 } else { 1171 ALOGE("%s invalid waitCount %d", __func__, waitCount); 1172 requested = NULL; 1173 } 1174 return obtainBuffer(audioBuffer, requested); 1175} 1176 1177status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested, 1178 struct timespec *elapsed, size_t *nonContig) 1179{ 1180 // previous and new IAudioTrack sequence numbers are used to detect track re-creation 1181 uint32_t oldSequence = 0; 1182 uint32_t newSequence; 1183 1184 Proxy::Buffer buffer; 1185 status_t status = NO_ERROR; 1186 1187 static const int32_t kMaxTries = 5; 1188 int32_t tryCounter = kMaxTries; 1189 1190 do { 1191 // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to 1192 // keep them from going away if another thread re-creates the track during obtainBuffer() 1193 sp<AudioTrackClientProxy> proxy; 1194 sp<IMemory> iMem; 1195 1196 { // start of lock scope 1197 AutoMutex lock(mLock); 1198 1199 newSequence = mSequence; 1200 // did previous obtainBuffer() fail due to media server death or voluntary invalidation? 1201 if (status == DEAD_OBJECT) { 1202 // re-create track, unless someone else has already done so 1203 if (newSequence == oldSequence) { 1204 status = restoreTrack_l("obtainBuffer"); 1205 if (status != NO_ERROR) { 1206 buffer.mFrameCount = 0; 1207 buffer.mRaw = NULL; 1208 buffer.mNonContig = 0; 1209 break; 1210 } 1211 } 1212 } 1213 oldSequence = newSequence; 1214 1215 // Keep the extra references 1216 proxy = mProxy; 1217 iMem = mCblkMemory; 1218 1219 if (mState == STATE_STOPPING) { 1220 status = -EINTR; 1221 buffer.mFrameCount = 0; 1222 buffer.mRaw = NULL; 1223 buffer.mNonContig = 0; 1224 break; 1225 } 1226 1227 // Non-blocking if track is stopped or paused 1228 if (mState != STATE_ACTIVE) { 1229 requested = &ClientProxy::kNonBlocking; 1230 } 1231 1232 } // end of lock scope 1233 1234 buffer.mFrameCount = audioBuffer->frameCount; 1235 // FIXME starts the requested timeout and elapsed over from scratch 1236 status = proxy->obtainBuffer(&buffer, requested, elapsed); 1237 1238 } while ((status == DEAD_OBJECT) && (tryCounter-- > 0)); 1239 1240 audioBuffer->frameCount = buffer.mFrameCount; 1241 audioBuffer->size = buffer.mFrameCount * mFrameSizeAF; 1242 audioBuffer->raw = buffer.mRaw; 1243 if (nonContig != NULL) { 1244 *nonContig = buffer.mNonContig; 1245 } 1246 return status; 1247} 1248 1249void AudioTrack::releaseBuffer(Buffer* audioBuffer) 1250{ 1251 if (mTransfer == TRANSFER_SHARED) { 1252 return; 1253 } 1254 1255 size_t stepCount = audioBuffer->size / mFrameSizeAF; 1256 if (stepCount == 0) { 1257 return; 1258 } 1259 1260 Proxy::Buffer buffer; 1261 buffer.mFrameCount = stepCount; 1262 buffer.mRaw = audioBuffer->raw; 1263 1264 AutoMutex lock(mLock); 1265 mInUnderrun = false; 1266 mProxy->releaseBuffer(&buffer); 1267 1268 // restart track if it was disabled by audioflinger due to previous underrun 1269 if (mState == STATE_ACTIVE) { 1270 audio_track_cblk_t* cblk = mCblk; 1271 if (android_atomic_and(~CBLK_DISABLED, &cblk->mFlags) & CBLK_DISABLED) { 1272 ALOGW("releaseBuffer() track %p name=%s disabled due to previous underrun, restarting", 1273 this, mName.string()); 1274 // FIXME ignoring status 1275 mAudioTrack->start(); 1276 } 1277 } 1278} 1279 1280// ------------------------------------------------------------------------- 1281 1282ssize_t AudioTrack::write(const void* buffer, size_t userSize) 1283{ 1284 if (mTransfer != TRANSFER_SYNC || mIsTimed) { 1285 return INVALID_OPERATION; 1286 } 1287 1288 if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) { 1289 // Sanity-check: user is most-likely passing an error code, and it would 1290 // make the return value ambiguous (actualSize vs error). 1291 ALOGE("AudioTrack::write(buffer=%p, size=%zu (%zd)", buffer, userSize, userSize); 1292 return BAD_VALUE; 1293 } 1294 1295 size_t written = 0; 1296 Buffer audioBuffer; 1297 1298 while (userSize >= mFrameSize) { 1299 audioBuffer.frameCount = userSize / mFrameSize; 1300 1301 status_t err = obtainBuffer(&audioBuffer, &ClientProxy::kForever); 1302 if (err < 0) { 1303 if (written > 0) { 1304 break; 1305 } 1306 return ssize_t(err); 1307 } 1308 1309 size_t toWrite; 1310 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) { 1311 // Divide capacity by 2 to take expansion into account 1312 toWrite = audioBuffer.size >> 1; 1313 memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) buffer, toWrite); 1314 } else { 1315 toWrite = audioBuffer.size; 1316 memcpy(audioBuffer.i8, buffer, toWrite); 1317 } 1318 buffer = ((const char *) buffer) + toWrite; 1319 userSize -= toWrite; 1320 written += toWrite; 1321 1322 releaseBuffer(&audioBuffer); 1323 } 1324 1325 return written; 1326} 1327 1328// ------------------------------------------------------------------------- 1329 1330TimedAudioTrack::TimedAudioTrack() { 1331 mIsTimed = true; 1332} 1333 1334status_t TimedAudioTrack::allocateTimedBuffer(size_t size, sp<IMemory>* buffer) 1335{ 1336 AutoMutex lock(mLock); 1337 status_t result = UNKNOWN_ERROR; 1338 1339#if 1 1340 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed 1341 // while we are accessing the cblk 1342 sp<IAudioTrack> audioTrack = mAudioTrack; 1343 sp<IMemory> iMem = mCblkMemory; 1344#endif 1345 1346 // If the track is not invalid already, try to allocate a buffer. alloc 1347 // fails indicating that the server is dead, flag the track as invalid so 1348 // we can attempt to restore in just a bit. 1349 audio_track_cblk_t* cblk = mCblk; 1350 if (!(cblk->mFlags & CBLK_INVALID)) { 1351 result = mAudioTrack->allocateTimedBuffer(size, buffer); 1352 if (result == DEAD_OBJECT) { 1353 android_atomic_or(CBLK_INVALID, &cblk->mFlags); 1354 } 1355 } 1356 1357 // If the track is invalid at this point, attempt to restore it. and try the 1358 // allocation one more time. 1359 if (cblk->mFlags & CBLK_INVALID) { 1360 result = restoreTrack_l("allocateTimedBuffer"); 1361 1362 if (result == NO_ERROR) { 1363 result = mAudioTrack->allocateTimedBuffer(size, buffer); 1364 } 1365 } 1366 1367 return result; 1368} 1369 1370status_t TimedAudioTrack::queueTimedBuffer(const sp<IMemory>& buffer, 1371 int64_t pts) 1372{ 1373 status_t status = mAudioTrack->queueTimedBuffer(buffer, pts); 1374 { 1375 AutoMutex lock(mLock); 1376 audio_track_cblk_t* cblk = mCblk; 1377 // restart track if it was disabled by audioflinger due to previous underrun 1378 if (buffer->size() != 0 && status == NO_ERROR && 1379 (mState == STATE_ACTIVE) && (cblk->mFlags & CBLK_DISABLED)) { 1380 android_atomic_and(~CBLK_DISABLED, &cblk->mFlags); 1381 ALOGW("queueTimedBuffer() track %p disabled, restarting", this); 1382 // FIXME ignoring status 1383 mAudioTrack->start(); 1384 } 1385 } 1386 return status; 1387} 1388 1389status_t TimedAudioTrack::setMediaTimeTransform(const LinearTransform& xform, 1390 TargetTimeline target) 1391{ 1392 return mAudioTrack->setMediaTimeTransform(xform, target); 1393} 1394 1395// ------------------------------------------------------------------------- 1396 1397nsecs_t AudioTrack::processAudioBuffer() 1398{ 1399 // Currently the AudioTrack thread is not created if there are no callbacks. 1400 // Would it ever make sense to run the thread, even without callbacks? 1401 // If so, then replace this by checks at each use for mCbf != NULL. 1402 LOG_ALWAYS_FATAL_IF(mCblk == NULL); 1403 1404 mLock.lock(); 1405 if (mAwaitBoost) { 1406 mAwaitBoost = false; 1407 mLock.unlock(); 1408 static const int32_t kMaxTries = 5; 1409 int32_t tryCounter = kMaxTries; 1410 uint32_t pollUs = 10000; 1411 do { 1412 int policy = sched_getscheduler(0); 1413 if (policy == SCHED_FIFO || policy == SCHED_RR) { 1414 break; 1415 } 1416 usleep(pollUs); 1417 pollUs <<= 1; 1418 } while (tryCounter-- > 0); 1419 if (tryCounter < 0) { 1420 ALOGE("did not receive expected priority boost on time"); 1421 } 1422 // Run again immediately 1423 return 0; 1424 } 1425 1426 // Can only reference mCblk while locked 1427 int32_t flags = android_atomic_and( 1428 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END), &mCblk->mFlags); 1429 1430 // Check for track invalidation 1431 if (flags & CBLK_INVALID) { 1432 // for offloaded tracks restoreTrack_l() will just update the sequence and clear 1433 // AudioSystem cache. We should not exit here but after calling the callback so 1434 // that the upper layers can recreate the track 1435 if (!isOffloaded_l() || (mSequence == mObservedSequence)) { 1436 status_t status = restoreTrack_l("processAudioBuffer"); 1437 mLock.unlock(); 1438 // Run again immediately, but with a new IAudioTrack 1439 return 0; 1440 } 1441 } 1442 1443 bool waitStreamEnd = mState == STATE_STOPPING; 1444 bool active = mState == STATE_ACTIVE; 1445 1446 // Manage underrun callback, must be done under lock to avoid race with releaseBuffer() 1447 bool newUnderrun = false; 1448 if (flags & CBLK_UNDERRUN) { 1449#if 0 1450 // Currently in shared buffer mode, when the server reaches the end of buffer, 1451 // the track stays active in continuous underrun state. It's up to the application 1452 // to pause or stop the track, or set the position to a new offset within buffer. 1453 // This was some experimental code to auto-pause on underrun. Keeping it here 1454 // in "if 0" so we can re-visit this if we add a real sequencer for shared memory content. 1455 if (mTransfer == TRANSFER_SHARED) { 1456 mState = STATE_PAUSED; 1457 active = false; 1458 } 1459#endif 1460 if (!mInUnderrun) { 1461 mInUnderrun = true; 1462 newUnderrun = true; 1463 } 1464 } 1465 1466 // Get current position of server 1467 size_t position = mProxy->getPosition(); 1468 1469 // Manage marker callback 1470 bool markerReached = false; 1471 size_t markerPosition = mMarkerPosition; 1472 // FIXME fails for wraparound, need 64 bits 1473 if (!mMarkerReached && (markerPosition > 0) && (position >= markerPosition)) { 1474 mMarkerReached = markerReached = true; 1475 } 1476 1477 // Determine number of new position callback(s) that will be needed, while locked 1478 size_t newPosCount = 0; 1479 size_t newPosition = mNewPosition; 1480 size_t updatePeriod = mUpdatePeriod; 1481 // FIXME fails for wraparound, need 64 bits 1482 if (updatePeriod > 0 && position >= newPosition) { 1483 newPosCount = ((position - newPosition) / updatePeriod) + 1; 1484 mNewPosition += updatePeriod * newPosCount; 1485 } 1486 1487 // Cache other fields that will be needed soon 1488 uint32_t loopPeriod = mLoopPeriod; 1489 uint32_t sampleRate = mSampleRate; 1490 size_t notificationFrames = mNotificationFramesAct; 1491 if (mRefreshRemaining) { 1492 mRefreshRemaining = false; 1493 mRemainingFrames = notificationFrames; 1494 mRetryOnPartialBuffer = false; 1495 } 1496 size_t misalignment = mProxy->getMisalignment(); 1497 uint32_t sequence = mSequence; 1498 1499 // These fields don't need to be cached, because they are assigned only by set(): 1500 // mTransfer, mCbf, mUserData, mFormat, mFrameSize, mFrameSizeAF, mFlags 1501 // mFlags is also assigned by createTrack_l(), but not the bit we care about. 1502 1503 mLock.unlock(); 1504 1505 if (waitStreamEnd) { 1506 AutoMutex lock(mLock); 1507 1508 sp<AudioTrackClientProxy> proxy = mProxy; 1509 sp<IMemory> iMem = mCblkMemory; 1510 1511 struct timespec timeout; 1512 timeout.tv_sec = WAIT_STREAM_END_TIMEOUT_SEC; 1513 timeout.tv_nsec = 0; 1514 1515 mLock.unlock(); 1516 status_t status = mProxy->waitStreamEndDone(&timeout); 1517 mLock.lock(); 1518 switch (status) { 1519 case NO_ERROR: 1520 case DEAD_OBJECT: 1521 case TIMED_OUT: 1522 mLock.unlock(); 1523 mCbf(EVENT_STREAM_END, mUserData, NULL); 1524 mLock.lock(); 1525 if (mState == STATE_STOPPING) { 1526 mState = STATE_STOPPED; 1527 if (status != DEAD_OBJECT) { 1528 return NS_INACTIVE; 1529 } 1530 } 1531 return 0; 1532 default: 1533 return 0; 1534 } 1535 } 1536 1537 // perform callbacks while unlocked 1538 if (newUnderrun) { 1539 mCbf(EVENT_UNDERRUN, mUserData, NULL); 1540 } 1541 // FIXME we will miss loops if loop cycle was signaled several times since last call 1542 // to processAudioBuffer() 1543 if (flags & (CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL)) { 1544 mCbf(EVENT_LOOP_END, mUserData, NULL); 1545 } 1546 if (flags & CBLK_BUFFER_END) { 1547 mCbf(EVENT_BUFFER_END, mUserData, NULL); 1548 } 1549 if (markerReached) { 1550 mCbf(EVENT_MARKER, mUserData, &markerPosition); 1551 } 1552 while (newPosCount > 0) { 1553 size_t temp = newPosition; 1554 mCbf(EVENT_NEW_POS, mUserData, &temp); 1555 newPosition += updatePeriod; 1556 newPosCount--; 1557 } 1558 1559 if (mObservedSequence != sequence) { 1560 mObservedSequence = sequence; 1561 mCbf(EVENT_NEW_IAUDIOTRACK, mUserData, NULL); 1562 // for offloaded tracks, just wait for the upper layers to recreate the track 1563 if (isOffloaded()) { 1564 return NS_INACTIVE; 1565 } 1566 } 1567 1568 // if inactive, then don't run me again until re-started 1569 if (!active) { 1570 return NS_INACTIVE; 1571 } 1572 1573 // Compute the estimated time until the next timed event (position, markers, loops) 1574 // FIXME only for non-compressed audio 1575 uint32_t minFrames = ~0; 1576 if (!markerReached && position < markerPosition) { 1577 minFrames = markerPosition - position; 1578 } 1579 if (loopPeriod > 0 && loopPeriod < minFrames) { 1580 minFrames = loopPeriod; 1581 } 1582 if (updatePeriod > 0 && updatePeriod < minFrames) { 1583 minFrames = updatePeriod; 1584 } 1585 1586 // If > 0, poll periodically to recover from a stuck server. A good value is 2. 1587 static const uint32_t kPoll = 0; 1588 if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) { 1589 minFrames = kPoll * notificationFrames; 1590 } 1591 1592 // Convert frame units to time units 1593 nsecs_t ns = NS_WHENEVER; 1594 if (minFrames != (uint32_t) ~0) { 1595 // This "fudge factor" avoids soaking CPU, and compensates for late progress by server 1596 static const nsecs_t kFudgeNs = 10000000LL; // 10 ms 1597 ns = ((minFrames * 1000000000LL) / sampleRate) + kFudgeNs; 1598 } 1599 1600 // If not supplying data by EVENT_MORE_DATA, then we're done 1601 if (mTransfer != TRANSFER_CALLBACK) { 1602 return ns; 1603 } 1604 1605 struct timespec timeout; 1606 const struct timespec *requested = &ClientProxy::kForever; 1607 if (ns != NS_WHENEVER) { 1608 timeout.tv_sec = ns / 1000000000LL; 1609 timeout.tv_nsec = ns % 1000000000LL; 1610 ALOGV("timeout %ld.%03d", timeout.tv_sec, (int) timeout.tv_nsec / 1000000); 1611 requested = &timeout; 1612 } 1613 1614 while (mRemainingFrames > 0) { 1615 1616 Buffer audioBuffer; 1617 audioBuffer.frameCount = mRemainingFrames; 1618 size_t nonContig; 1619 status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig); 1620 LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0), 1621 "obtainBuffer() err=%d frameCount=%u", err, audioBuffer.frameCount); 1622 requested = &ClientProxy::kNonBlocking; 1623 size_t avail = audioBuffer.frameCount + nonContig; 1624 ALOGV("obtainBuffer(%u) returned %u = %u + %u err %d", 1625 mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err); 1626 if (err != NO_ERROR) { 1627 if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR || 1628 (isOffloaded() && (err == DEAD_OBJECT))) { 1629 return 0; 1630 } 1631 ALOGE("Error %d obtaining an audio buffer, giving up.", err); 1632 return NS_NEVER; 1633 } 1634 1635 if (mRetryOnPartialBuffer && !isOffloaded()) { 1636 mRetryOnPartialBuffer = false; 1637 if (avail < mRemainingFrames) { 1638 int64_t myns = ((mRemainingFrames - avail) * 1100000000LL) / sampleRate; 1639 if (ns < 0 || myns < ns) { 1640 ns = myns; 1641 } 1642 return ns; 1643 } 1644 } 1645 1646 // Divide buffer size by 2 to take into account the expansion 1647 // due to 8 to 16 bit conversion: the callback must fill only half 1648 // of the destination buffer 1649 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) { 1650 audioBuffer.size >>= 1; 1651 } 1652 1653 size_t reqSize = audioBuffer.size; 1654 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer); 1655 size_t writtenSize = audioBuffer.size; 1656 1657 // Sanity check on returned size 1658 if (ssize_t(writtenSize) < 0 || writtenSize > reqSize) { 1659 ALOGE("EVENT_MORE_DATA requested %u bytes but callback returned %d bytes", 1660 reqSize, (int) writtenSize); 1661 return NS_NEVER; 1662 } 1663 1664 if (writtenSize == 0) { 1665 // The callback is done filling buffers 1666 // Keep this thread going to handle timed events and 1667 // still try to get more data in intervals of WAIT_PERIOD_MS 1668 // but don't just loop and block the CPU, so wait 1669 return WAIT_PERIOD_MS * 1000000LL; 1670 } 1671 1672 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) { 1673 // 8 to 16 bit conversion, note that source and destination are the same address 1674 memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) audioBuffer.i8, writtenSize); 1675 audioBuffer.size <<= 1; 1676 } 1677 1678 size_t releasedFrames = audioBuffer.size / mFrameSizeAF; 1679 audioBuffer.frameCount = releasedFrames; 1680 mRemainingFrames -= releasedFrames; 1681 if (misalignment >= releasedFrames) { 1682 misalignment -= releasedFrames; 1683 } else { 1684 misalignment = 0; 1685 } 1686 1687 releaseBuffer(&audioBuffer); 1688 1689 // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer 1690 // if callback doesn't like to accept the full chunk 1691 if (writtenSize < reqSize) { 1692 continue; 1693 } 1694 1695 // There could be enough non-contiguous frames available to satisfy the remaining request 1696 if (mRemainingFrames <= nonContig) { 1697 continue; 1698 } 1699 1700#if 0 1701 // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a 1702 // sum <= notificationFrames. It replaces that series by at most two EVENT_MORE_DATA 1703 // that total to a sum == notificationFrames. 1704 if (0 < misalignment && misalignment <= mRemainingFrames) { 1705 mRemainingFrames = misalignment; 1706 return (mRemainingFrames * 1100000000LL) / sampleRate; 1707 } 1708#endif 1709 1710 } 1711 mRemainingFrames = notificationFrames; 1712 mRetryOnPartialBuffer = true; 1713 1714 // A lot has transpired since ns was calculated, so run again immediately and re-calculate 1715 return 0; 1716} 1717 1718status_t AudioTrack::restoreTrack_l(const char *from) 1719{ 1720 ALOGW("dead IAudioTrack, %s, creating a new one from %s()", 1721 isOffloaded_l() ? "Offloaded" : "PCM", from); 1722 ++mSequence; 1723 status_t result; 1724 1725 // refresh the audio configuration cache in this process to make sure we get new 1726 // output parameters in createTrack_l() 1727 AudioSystem::clearAudioConfigCache(); 1728 1729 if (isOffloaded_l()) { 1730 // FIXME re-creation of offloaded tracks is not yet implemented 1731 return DEAD_OBJECT; 1732 } 1733 1734 // if the new IAudioTrack is created, createTrack_l() will modify the 1735 // following member variables: mAudioTrack, mCblkMemory and mCblk. 1736 // It will also delete the strong references on previous IAudioTrack and IMemory 1737 1738 // take the frames that will be lost by track recreation into account in saved position 1739 size_t position = mProxy->getPosition() + mProxy->getFramesFilled(); 1740 size_t bufferPosition = mStaticProxy != NULL ? mStaticProxy->getBufferPosition() : 0; 1741 result = createTrack_l(position /*epoch*/); 1742 1743 if (result == NO_ERROR) { 1744 // continue playback from last known position, but 1745 // don't attempt to restore loop after invalidation; it's difficult and not worthwhile 1746 if (mStaticProxy != NULL) { 1747 mLoopPeriod = 0; 1748 mStaticProxy->setLoop(bufferPosition, mFrameCount, 0); 1749 } 1750 // FIXME How do we simulate the fact that all frames present in the buffer at the time of 1751 // track destruction have been played? This is critical for SoundPool implementation 1752 // This must be broken, and needs to be tested/debugged. 1753#if 0 1754 // restore write index and set other indexes to reflect empty buffer status 1755 if (!strcmp(from, "start")) { 1756 // Make sure that a client relying on callback events indicating underrun or 1757 // the actual amount of audio frames played (e.g SoundPool) receives them. 1758 if (mSharedBuffer == 0) { 1759 // restart playback even if buffer is not completely filled. 1760 android_atomic_or(CBLK_FORCEREADY, &mCblk->mFlags); 1761 } 1762 } 1763#endif 1764 if (mState == STATE_ACTIVE) { 1765 result = mAudioTrack->start(); 1766 } 1767 } 1768 if (result != NO_ERROR) { 1769 // Use of direct and offloaded output streams is ref counted by audio policy manager. 1770#if 0 // FIXME This should no longer be needed 1771 //Use of direct and offloaded output streams is ref counted by audio policy manager. 1772 // As getOutput was called above and resulted in an output stream to be opened, 1773 // we need to release it. 1774 if (mOutput != 0) { 1775 AudioSystem::releaseOutput(mOutput); 1776 mOutput = 0; 1777 } 1778#endif 1779 ALOGW("restoreTrack_l() failed status %d", result); 1780 mState = STATE_STOPPED; 1781 } 1782 1783 return result; 1784} 1785 1786status_t AudioTrack::setParameters(const String8& keyValuePairs) 1787{ 1788 AutoMutex lock(mLock); 1789 return mAudioTrack->setParameters(keyValuePairs); 1790} 1791 1792status_t AudioTrack::getTimestamp(AudioTimestamp& timestamp) 1793{ 1794 AutoMutex lock(mLock); 1795 // FIXME not implemented for fast tracks; should use proxy and SSQ 1796 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) { 1797 return INVALID_OPERATION; 1798 } 1799 if (mState != STATE_ACTIVE && mState != STATE_PAUSED) { 1800 return INVALID_OPERATION; 1801 } 1802 status_t status = mAudioTrack->getTimestamp(timestamp); 1803 if (status == NO_ERROR) { 1804 timestamp.mPosition += mProxy->getEpoch(); 1805 } 1806 return status; 1807} 1808 1809String8 AudioTrack::getParameters(const String8& keys) 1810{ 1811 audio_io_handle_t output = getOutput(); 1812 if (output != 0) { 1813 return AudioSystem::getParameters(output, keys); 1814 } else { 1815 return String8::empty(); 1816 } 1817} 1818 1819bool AudioTrack::isOffloaded() const 1820{ 1821 AutoMutex lock(mLock); 1822 return isOffloaded_l(); 1823} 1824 1825status_t AudioTrack::dump(int fd, const Vector<String16>& args __unused) const 1826{ 1827 1828 const size_t SIZE = 256; 1829 char buffer[SIZE]; 1830 String8 result; 1831 1832 result.append(" AudioTrack::dump\n"); 1833 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType, 1834 mVolume[0], mVolume[1]); 1835 result.append(buffer); 1836 snprintf(buffer, 255, " format(%d), channel count(%d), frame count(%zu)\n", mFormat, 1837 mChannelCount, mFrameCount); 1838 result.append(buffer); 1839 snprintf(buffer, 255, " sample rate(%u), status(%d)\n", mSampleRate, mStatus); 1840 result.append(buffer); 1841 snprintf(buffer, 255, " state(%d), latency (%d)\n", mState, mLatency); 1842 result.append(buffer); 1843 ::write(fd, result.string(), result.size()); 1844 return NO_ERROR; 1845} 1846 1847uint32_t AudioTrack::getUnderrunFrames() const 1848{ 1849 AutoMutex lock(mLock); 1850 return mProxy->getUnderrunFrames(); 1851} 1852 1853// ========================================================================= 1854 1855void AudioTrack::DeathNotifier::binderDied(const wp<IBinder>& who __unused) 1856{ 1857 sp<AudioTrack> audioTrack = mAudioTrack.promote(); 1858 if (audioTrack != 0) { 1859 AutoMutex lock(audioTrack->mLock); 1860 audioTrack->mProxy->binderDied(); 1861 } 1862} 1863 1864// ========================================================================= 1865 1866AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava) 1867 : Thread(bCanCallJava), mReceiver(receiver), mPaused(true), mPausedInt(false), mPausedNs(0LL), 1868 mIgnoreNextPausedInt(false) 1869{ 1870} 1871 1872AudioTrack::AudioTrackThread::~AudioTrackThread() 1873{ 1874} 1875 1876bool AudioTrack::AudioTrackThread::threadLoop() 1877{ 1878 { 1879 AutoMutex _l(mMyLock); 1880 if (mPaused) { 1881 mMyCond.wait(mMyLock); 1882 // caller will check for exitPending() 1883 return true; 1884 } 1885 if (mIgnoreNextPausedInt) { 1886 mIgnoreNextPausedInt = false; 1887 mPausedInt = false; 1888 } 1889 if (mPausedInt) { 1890 if (mPausedNs > 0) { 1891 (void) mMyCond.waitRelative(mMyLock, mPausedNs); 1892 } else { 1893 mMyCond.wait(mMyLock); 1894 } 1895 mPausedInt = false; 1896 return true; 1897 } 1898 } 1899 nsecs_t ns = mReceiver.processAudioBuffer(); 1900 switch (ns) { 1901 case 0: 1902 return true; 1903 case NS_INACTIVE: 1904 pauseInternal(); 1905 return true; 1906 case NS_NEVER: 1907 return false; 1908 case NS_WHENEVER: 1909 // FIXME increase poll interval, or make event-driven 1910 ns = 1000000000LL; 1911 // fall through 1912 default: 1913 LOG_ALWAYS_FATAL_IF(ns < 0, "processAudioBuffer() returned %lld", ns); 1914 pauseInternal(ns); 1915 return true; 1916 } 1917} 1918 1919void AudioTrack::AudioTrackThread::requestExit() 1920{ 1921 // must be in this order to avoid a race condition 1922 Thread::requestExit(); 1923 resume(); 1924} 1925 1926void AudioTrack::AudioTrackThread::pause() 1927{ 1928 AutoMutex _l(mMyLock); 1929 mPaused = true; 1930} 1931 1932void AudioTrack::AudioTrackThread::resume() 1933{ 1934 AutoMutex _l(mMyLock); 1935 mIgnoreNextPausedInt = true; 1936 if (mPaused || mPausedInt) { 1937 mPaused = false; 1938 mPausedInt = false; 1939 mMyCond.signal(); 1940 } 1941} 1942 1943void AudioTrack::AudioTrackThread::pauseInternal(nsecs_t ns) 1944{ 1945 AutoMutex _l(mMyLock); 1946 mPausedInt = true; 1947 mPausedNs = ns; 1948} 1949 1950}; // namespace android 1951