AudioTrack.cpp revision 4ef88d7106c01f81109ee163cb6789073d80c6ae
199e53b86eebb605b70dd7591b89bf61a9414ed0eGlenn Kasten/*
289fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project**
389fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project** Copyright 2007, The Android Open Source Project
489fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project**
589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project** Licensed under the Apache License, Version 2.0 (the "License");
689fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project** you may not use this file except in compliance with the License.
789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project** You may obtain a copy of the License at
889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project**
989fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project**     http://www.apache.org/licenses/LICENSE-2.0
1089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project**
1189fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project** Unless required by applicable law or agreed to in writing, software
1289fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project** distributed under the License is distributed on an "AS IS" BASIS,
1389fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1489fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project** See the License for the specific language governing permissions and
1589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project** limitations under the License.
1689fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project*/
1789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
1889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project//#define LOG_NDEBUG 0
1989fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project#define LOG_TAG "AudioTrack"
2089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
2134fb29696b0f3abf61b10f8d053b1f33d501de0aMark Salyzyn#include <inttypes.h>
22c56f3426099a3cf2d07ccff8886050c7fbce140fGlenn Kasten#include <math.h>
2389fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project#include <sys/resource.h>
2434fb29696b0f3abf61b10f8d053b1f33d501de0aMark Salyzyn
259f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten#include <audio_utils/primitives.h>
269f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten#include <binder/IPCThreadState.h>
2789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project#include <media/AudioTrack.h>
2889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project#include <utils/Log.h>
299f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten#include <private/media/AudioTrackShared.h>
301ab85ec401801ef9a9184650d0f5a1639b45eeb9Glenn Kasten#include <media/IAudioFlinger.h>
31e83b55dc29ca16092ba02f36f55fa6e0e37fd78cEric Laurent#include <media/AudioPolicyHelper.h>
32cd04484f4837b8ca0041d118286ab6a98e84fc75Andy Hung#include <media/AudioResamplerPublic.h>
33fce7a473248381cc83a01855f92581077d3c9ee2Dima Zavin
34b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald#define WAIT_PERIOD_MS                  10
35b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald#define WAIT_STREAM_END_TIMEOUT_SEC     120
3653c3b5fc1afe162a8669cb3d27d6bb14e1847e39Andy Hungstatic const int kMaxLoopCountNotifications = 32;
37511754b5839fd9b09fc56b89ae007fbc39084a33Glenn Kasten
3889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectnamespace android {
3933005a932c60a0780fe9b7307d5988df3d9f6c26Chia-chi Yeh// ---------------------------------------------------------------------------
4033005a932c60a0780fe9b7307d5988df3d9f6c26Chia-chi Yeh
41a7f03353d5f172016f324e2a01f301cca6794152Andy Hung// TODO: Move to a separate .h
42a7f03353d5f172016f324e2a01f301cca6794152Andy Hung
434ede21d9c1f957baf5e561849ff9bbe4bcbefc20Andy Hungtemplate <typename T>
44a7f03353d5f172016f324e2a01f301cca6794152Andy Hungstatic inline const T &min(const T &x, const T &y) {
454ede21d9c1f957baf5e561849ff9bbe4bcbefc20Andy Hung    return x < y ? x : y;
464ede21d9c1f957baf5e561849ff9bbe4bcbefc20Andy Hung}
474ede21d9c1f957baf5e561849ff9bbe4bcbefc20Andy Hung
48a7f03353d5f172016f324e2a01f301cca6794152Andy Hungtemplate <typename T>
49a7f03353d5f172016f324e2a01f301cca6794152Andy Hungstatic inline const T &max(const T &x, const T &y) {
50a7f03353d5f172016f324e2a01f301cca6794152Andy Hung    return x > y ? x : y;
51a7f03353d5f172016f324e2a01f301cca6794152Andy Hung}
52a7f03353d5f172016f324e2a01f301cca6794152Andy Hung
535d313803bdd61d59f28e518e7a793f33832f1901Andy Hungstatic const int32_t NANOS_PER_SECOND = 1000000000;
545d313803bdd61d59f28e518e7a793f33832f1901Andy Hung
55a7f03353d5f172016f324e2a01f301cca6794152Andy Hungstatic inline nsecs_t framesToNanoseconds(ssize_t frames, uint32_t sampleRate, float speed)
56a7f03353d5f172016f324e2a01f301cca6794152Andy Hung{
57a7f03353d5f172016f324e2a01f301cca6794152Andy Hung    return ((double)frames * 1000000000) / ((double)sampleRate * speed);
58a7f03353d5f172016f324e2a01f301cca6794152Andy Hung}
59a7f03353d5f172016f324e2a01f301cca6794152Andy Hung
607f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hungstatic int64_t convertTimespecToUs(const struct timespec &tv)
617f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung{
627f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung    return tv.tv_sec * 1000000ll + tv.tv_nsec / 1000;
637f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung}
647f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung
655d313803bdd61d59f28e518e7a793f33832f1901Andy Hungstatic inline nsecs_t convertTimespecToNs(const struct timespec &tv)
665d313803bdd61d59f28e518e7a793f33832f1901Andy Hung{
675d313803bdd61d59f28e518e7a793f33832f1901Andy Hung    return tv.tv_sec * (long long)NANOS_PER_SECOND + tv.tv_nsec;
685d313803bdd61d59f28e518e7a793f33832f1901Andy Hung}
695d313803bdd61d59f28e518e7a793f33832f1901Andy Hung
707f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung// current monotonic time in microseconds.
717f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hungstatic int64_t getNowUs()
727f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung{
737f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung    struct timespec tv;
747f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung    (void) clock_gettime(CLOCK_MONOTONIC, &tv);
757f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung    return convertTimespecToUs(tv);
767f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung}
777f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung
7826145643ce22d797b3b1675c82c47a2d8c79ecaaAndy Hung// FIXME: we don't use the pitch setting in the time stretcher (not working);
7926145643ce22d797b3b1675c82c47a2d8c79ecaaAndy Hung// instead we emulate it using our sample rate converter.
8026145643ce22d797b3b1675c82c47a2d8c79ecaaAndy Hungstatic const bool kFixPitch = true; // enable pitch fix
8126145643ce22d797b3b1675c82c47a2d8c79ecaaAndy Hungstatic inline uint32_t adjustSampleRate(uint32_t sampleRate, float pitch)
8226145643ce22d797b3b1675c82c47a2d8c79ecaaAndy Hung{
8326145643ce22d797b3b1675c82c47a2d8c79ecaaAndy Hung    return kFixPitch ? (sampleRate * pitch + 0.5) : sampleRate;
8426145643ce22d797b3b1675c82c47a2d8c79ecaaAndy Hung}
8526145643ce22d797b3b1675c82c47a2d8c79ecaaAndy Hung
8626145643ce22d797b3b1675c82c47a2d8c79ecaaAndy Hungstatic inline float adjustSpeed(float speed, float pitch)
8726145643ce22d797b3b1675c82c47a2d8c79ecaaAndy Hung{
886c7f062d3149d6890daaee64828959ad6f61ea54Ricardo Garcia    return kFixPitch ? speed / max(pitch, AUDIO_TIMESTRETCH_PITCH_MIN_DELTA) : speed;
8926145643ce22d797b3b1675c82c47a2d8c79ecaaAndy Hung}
9026145643ce22d797b3b1675c82c47a2d8c79ecaaAndy Hung
9126145643ce22d797b3b1675c82c47a2d8c79ecaaAndy Hungstatic inline float adjustPitch(float pitch)
9226145643ce22d797b3b1675c82c47a2d8c79ecaaAndy Hung{
9326145643ce22d797b3b1675c82c47a2d8c79ecaaAndy Hung    return kFixPitch ? AUDIO_TIMESTRETCH_PITCH_NORMAL : pitch;
9426145643ce22d797b3b1675c82c47a2d8c79ecaaAndy Hung}
9526145643ce22d797b3b1675c82c47a2d8c79ecaaAndy Hung
968edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung// Must match similar computation in createTrack_l in Threads.cpp.
978edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung// TODO: Move to a common library
988edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hungstatic size_t calculateMinFrameCount(
998edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung        uint32_t afLatencyMs, uint32_t afFrameCount, uint32_t afSampleRate,
100ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten        uint32_t sampleRate, float speed /*, uint32_t notificationsPerBufferReq*/)
1018edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung{
1028edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung    // Ensure that buffer depth covers at least audio hardware latency
1038edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung    uint32_t minBufCount = afLatencyMs / ((1000 * afFrameCount) / afSampleRate);
1048edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung    if (minBufCount < 2) {
1058edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung        minBufCount = 2;
1068edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung    }
107ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten#if 0
108ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten    // The notificationsPerBufferReq parameter is not yet used for non-fast tracks,
109ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten    // but keeping the code here to make it easier to add later.
110ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten    if (minBufCount < notificationsPerBufferReq) {
111ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten        minBufCount = notificationsPerBufferReq;
112ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten    }
113ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten#endif
1148edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung    ALOGV("calculateMinFrameCount afLatency %u  afFrameCount %u  afSampleRate %u  "
115ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten            "sampleRate %u  speed %f  minBufCount: %u" /*"  notificationsPerBufferReq %u"*/,
116ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten            afLatencyMs, afFrameCount, afSampleRate, sampleRate, speed, minBufCount
117ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten            /*, notificationsPerBufferReq*/);
1188edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung    return minBufCount * sourceFramesNeededWithTimestretch(
1198edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung            sampleRate, afFrameCount, afSampleRate, speed);
1208edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung}
1218edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung
12233005a932c60a0780fe9b7307d5988df3d9f6c26Chia-chi Yeh// static
12333005a932c60a0780fe9b7307d5988df3d9f6c26Chia-chi Yehstatus_t AudioTrack::getMinFrameCount(
124e33054eb968cbf8ccaee1b0ff0301403902deed6Glenn Kasten        size_t* frameCount,
125fff6d715a8db0daf08a50634f242c40268de3d49Glenn Kasten        audio_stream_type_t streamType,
12633005a932c60a0780fe9b7307d5988df3d9f6c26Chia-chi Yeh        uint32_t sampleRate)
12733005a932c60a0780fe9b7307d5988df3d9f6c26Chia-chi Yeh{
128d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kasten    if (frameCount == NULL) {
129d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kasten        return BAD_VALUE;
130d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kasten    }
13104cd0186305e2b59d23c9147787046c6662029ccGlenn Kasten
1320e48d25606c82def035ad10a5b3923767a765cddAndy Hung    // FIXME handle in server, like createTrack_l(), possible missing info:
133e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten    //          audio_io_handle_t output
134e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten    //          audio_format_t format
135e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten    //          audio_channel_mask_t channelMask
1360e48d25606c82def035ad10a5b3923767a765cddAndy Hung    //          audio_output_flags_t flags (FAST)
1373b16c766d1ae2cfd8487e8ffb2b23936fc0a8e17Glenn Kasten    uint32_t afSampleRate;
13866a0467fdddada4caabd0f0a999fbb367fea7beeGlenn Kasten    status_t status;
13966a0467fdddada4caabd0f0a999fbb367fea7beeGlenn Kasten    status = AudioSystem::getOutputSamplingRate(&afSampleRate, streamType);
14066a0467fdddada4caabd0f0a999fbb367fea7beeGlenn Kasten    if (status != NO_ERROR) {
14170c0bfbe5ec88dcc3efa2bd8df26f36cff1cf03aGlenn Kasten        ALOGE("Unable to query output sample rate for stream type %d; status %d",
14270c0bfbe5ec88dcc3efa2bd8df26f36cff1cf03aGlenn Kasten                streamType, status);
14366a0467fdddada4caabd0f0a999fbb367fea7beeGlenn Kasten        return status;
14433005a932c60a0780fe9b7307d5988df3d9f6c26Chia-chi Yeh    }
145e33054eb968cbf8ccaee1b0ff0301403902deed6Glenn Kasten    size_t afFrameCount;
14666a0467fdddada4caabd0f0a999fbb367fea7beeGlenn Kasten    status = AudioSystem::getOutputFrameCount(&afFrameCount, streamType);
14766a0467fdddada4caabd0f0a999fbb367fea7beeGlenn Kasten    if (status != NO_ERROR) {
14870c0bfbe5ec88dcc3efa2bd8df26f36cff1cf03aGlenn Kasten        ALOGE("Unable to query output frame count for stream type %d; status %d",
14970c0bfbe5ec88dcc3efa2bd8df26f36cff1cf03aGlenn Kasten                streamType, status);
15066a0467fdddada4caabd0f0a999fbb367fea7beeGlenn Kasten        return status;
15133005a932c60a0780fe9b7307d5988df3d9f6c26Chia-chi Yeh    }
15233005a932c60a0780fe9b7307d5988df3d9f6c26Chia-chi Yeh    uint32_t afLatency;
15366a0467fdddada4caabd0f0a999fbb367fea7beeGlenn Kasten    status = AudioSystem::getOutputLatency(&afLatency, streamType);
15466a0467fdddada4caabd0f0a999fbb367fea7beeGlenn Kasten    if (status != NO_ERROR) {
15570c0bfbe5ec88dcc3efa2bd8df26f36cff1cf03aGlenn Kasten        ALOGE("Unable to query output latency for stream type %d; status %d",
15670c0bfbe5ec88dcc3efa2bd8df26f36cff1cf03aGlenn Kasten                streamType, status);
15766a0467fdddada4caabd0f0a999fbb367fea7beeGlenn Kasten        return status;
15833005a932c60a0780fe9b7307d5988df3d9f6c26Chia-chi Yeh    }
15933005a932c60a0780fe9b7307d5988df3d9f6c26Chia-chi Yeh
1608edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung    // When called from createTrack, speed is 1.0f (normal speed).
1618edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung    // This is rechecked again on setting playback rate (TODO: on setting sample rate, too).
162ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten    *frameCount = calculateMinFrameCount(afLatency, afFrameCount, afSampleRate, sampleRate, 1.0f
163ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten            /*, 0 notificationsPerBufferReq*/);
16433005a932c60a0780fe9b7307d5988df3d9f6c26Chia-chi Yeh
1650e48d25606c82def035ad10a5b3923767a765cddAndy Hung    // The formula above should always produce a non-zero value under normal circumstances:
1660e48d25606c82def035ad10a5b3923767a765cddAndy Hung    // AudioTrack.SAMPLE_RATE_HZ_MIN <= sampleRate <= AudioTrack.SAMPLE_RATE_HZ_MAX.
1670e48d25606c82def035ad10a5b3923767a765cddAndy Hung    // Return error in the unlikely event that it does not, as that's part of the API contract.
16866a0467fdddada4caabd0f0a999fbb367fea7beeGlenn Kasten    if (*frameCount == 0) {
1690e48d25606c82def035ad10a5b3923767a765cddAndy Hung        ALOGE("AudioTrack::getMinFrameCount failed for streamType %d, sampleRate %u",
17066a0467fdddada4caabd0f0a999fbb367fea7beeGlenn Kasten                streamType, sampleRate);
17166a0467fdddada4caabd0f0a999fbb367fea7beeGlenn Kasten        return BAD_VALUE;
17266a0467fdddada4caabd0f0a999fbb367fea7beeGlenn Kasten    }
1738edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung    ALOGV("getMinFrameCount=%zu: afFrameCount=%zu, afSampleRate=%u, afLatency=%u",
1748edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung            *frameCount, afFrameCount, afSampleRate, afLatency);
17533005a932c60a0780fe9b7307d5988df3d9f6c26Chia-chi Yeh    return NO_ERROR;
17633005a932c60a0780fe9b7307d5988df3d9f6c26Chia-chi Yeh}
17789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
17889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project// ---------------------------------------------------------------------------
17989fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
18089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source ProjectAudioTrack::AudioTrack()
181879135196fd1c97deefc538c888037c56c2879a7Glenn Kasten    : mStatus(NO_INIT),
1829b3359feabbf138bb965da5173434da78bfe0929Haynes Mathew George      mState(STATE_STOPPED),
1834ff14bae91075eb274eb1c2975982358946e7e63John Grossman      mPreviousPriority(ANDROID_PRIORITY_NORMAL),
1847064fd2dcdfeafea53cd5a992bb78c413542f29fHaynes Mathew George      mPreviousSchedulingGroup(SP_DEFAULT),
185aa9811945f575614b3482d09e4d969792701cebbPaul McLean      mPausedPosition(0),
18620b9ef0b55c9150ae11057ab997ae61be2d496efEric Laurent      mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE),
18720b9ef0b55c9150ae11057ab997ae61be2d496efEric Laurent      mPortId(AUDIO_PORT_HANDLE_NONE)
18889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project{
189faabb51ceef13bf1e3f692219ac410c1cd75d0deJean-Michel Trivi    mAttributes.content_type = AUDIO_CONTENT_TYPE_UNKNOWN;
190faabb51ceef13bf1e3f692219ac410c1cd75d0deJean-Michel Trivi    mAttributes.usage = AUDIO_USAGE_UNKNOWN;
191faabb51ceef13bf1e3f692219ac410c1cd75d0deJean-Michel Trivi    mAttributes.flags = 0x0;
192faabb51ceef13bf1e3f692219ac410c1cd75d0deJean-Michel Trivi    strcpy(mAttributes.tags, "");
19389fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project}
19489fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
19589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source ProjectAudioTrack::AudioTrack(
196fff6d715a8db0daf08a50634f242c40268de3d49Glenn Kasten        audio_stream_type_t streamType,
19789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        uint32_t sampleRate,
198e1c3962e268ffc12bfd1bd9ea84da1f135f36960Glenn Kasten        audio_format_t format,
19928b76b334f92a15a2be3cc9e2f7d229a3275d1acGlenn Kasten        audio_channel_mask_t channelMask,
200bce50bfc3846ab008bafa75c5d3f29fd7b5395f7Glenn Kasten        size_t frameCount,
2010ca3cf94c0dfc173ad7886ae162c4b67067539f6Eric Laurent        audio_output_flags_t flags,
20289fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        callback_t cbf,
20389fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        void* user,
204ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten        int32_t notificationFrames,
205d848eb48c121c119e8ba7583efc75415fe102570Glenn Kasten        audio_session_t sessionId,
206ad3af3305f024bcbbd55c894a4995e449498e1baRichard Fitzgerald        transfer_type transferType,
207462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen        const audio_offload_info_t *offloadInfo,
2081f12a8ad958344c50733b948628ffa06db9c5bc6Andy Hung        uid_t uid,
209d9d7fa0873796ac661c44a7fcd6ad5ff697ff01fJean-Michel Trivi        pid_t pid,
210faeb0f291330134dc4468359a36e099aae508449Ronghua Wu        const audio_attributes_t* pAttributes,
211ff874dc957f9ea70d87f4d627bf903e1fc86d58bAndy Hung        bool doNotReconnect,
212ff874dc957f9ea70d87f4d627bf903e1fc86d58bAndy Hung        float maxRequiredSpeed)
213879135196fd1c97deefc538c888037c56c2879a7Glenn Kasten    : mStatus(NO_INIT),
2149b3359feabbf138bb965da5173434da78bfe0929Haynes Mathew George      mState(STATE_STOPPED),
2154ff14bae91075eb274eb1c2975982358946e7e63John Grossman      mPreviousPriority(ANDROID_PRIORITY_NORMAL),
2167064fd2dcdfeafea53cd5a992bb78c413542f29fHaynes Mathew George      mPreviousSchedulingGroup(SP_DEFAULT),
217aa9811945f575614b3482d09e4d969792701cebbPaul McLean      mPausedPosition(0),
21820b9ef0b55c9150ae11057ab997ae61be2d496efEric Laurent      mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE),
21920b9ef0b55c9150ae11057ab997ae61be2d496efEric Laurent      mPortId(AUDIO_PORT_HANDLE_NONE)
22089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project{
2210d255b2d9061ba31f13ada3fc0f7e51916407176Jean-Michel Trivi    mStatus = set(streamType, sampleRate, format, channelMask,
222a514bdb58b5de4986679f72b7204b4764f7a2778Eric Laurent            frameCount, flags, cbf, user, notificationFrames,
223462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen            0 /*sharedBuffer*/, false /*threadCanCallJava*/, sessionId, transferType,
224ff874dc957f9ea70d87f4d627bf903e1fc86d58bAndy Hung            offloadInfo, uid, pid, pAttributes, doNotReconnect, maxRequiredSpeed);
22589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project}
22689fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
227c813985abd8ba61e999b3505f6a332574f87a1beAndreas HuberAudioTrack::AudioTrack(
228fff6d715a8db0daf08a50634f242c40268de3d49Glenn Kasten        audio_stream_type_t streamType,
22989fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        uint32_t sampleRate,
230e1c3962e268ffc12bfd1bd9ea84da1f135f36960Glenn Kasten        audio_format_t format,
23128b76b334f92a15a2be3cc9e2f7d229a3275d1acGlenn Kasten        audio_channel_mask_t channelMask,
23289fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        const sp<IMemory>& sharedBuffer,
2330ca3cf94c0dfc173ad7886ae162c4b67067539f6Eric Laurent        audio_output_flags_t flags,
23489fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        callback_t cbf,
23589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        void* user,
236ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten        int32_t notificationFrames,
237d848eb48c121c119e8ba7583efc75415fe102570Glenn Kasten        audio_session_t sessionId,
238ad3af3305f024bcbbd55c894a4995e449498e1baRichard Fitzgerald        transfer_type transferType,
239462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen        const audio_offload_info_t *offloadInfo,
2401f12a8ad958344c50733b948628ffa06db9c5bc6Andy Hung        uid_t uid,
241d9d7fa0873796ac661c44a7fcd6ad5ff697ff01fJean-Michel Trivi        pid_t pid,
242faeb0f291330134dc4468359a36e099aae508449Ronghua Wu        const audio_attributes_t* pAttributes,
243ff874dc957f9ea70d87f4d627bf903e1fc86d58bAndy Hung        bool doNotReconnect,
244ff874dc957f9ea70d87f4d627bf903e1fc86d58bAndy Hung        float maxRequiredSpeed)
245879135196fd1c97deefc538c888037c56c2879a7Glenn Kasten    : mStatus(NO_INIT),
2469b3359feabbf138bb965da5173434da78bfe0929Haynes Mathew George      mState(STATE_STOPPED),
2474ff14bae91075eb274eb1c2975982358946e7e63John Grossman      mPreviousPriority(ANDROID_PRIORITY_NORMAL),
2487064fd2dcdfeafea53cd5a992bb78c413542f29fHaynes Mathew George      mPreviousSchedulingGroup(SP_DEFAULT),
249aa9811945f575614b3482d09e4d969792701cebbPaul McLean      mPausedPosition(0),
25020b9ef0b55c9150ae11057ab997ae61be2d496efEric Laurent      mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE),
25120b9ef0b55c9150ae11057ab997ae61be2d496efEric Laurent      mPortId(AUDIO_PORT_HANDLE_NONE)
25289fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project{
2530d255b2d9061ba31f13ada3fc0f7e51916407176Jean-Michel Trivi    mStatus = set(streamType, sampleRate, format, channelMask,
25417a736c3e1d062d7fc916329eb32aef8935614afGlenn Kasten            0 /*frameCount*/, flags, cbf, user, notificationFrames,
255d457c970c8d08519cd77280a90b61ae1e342cfe3Marco Nelissen            sharedBuffer, false /*threadCanCallJava*/, sessionId, transferType, offloadInfo,
256ff874dc957f9ea70d87f4d627bf903e1fc86d58bAndy Hung            uid, pid, pAttributes, doNotReconnect, maxRequiredSpeed);
25789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project}
25889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
25989fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source ProjectAudioTrack::~AudioTrack()
26089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project{
26189fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    if (mStatus == NO_ERROR) {
26289fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        // Make sure that callback function exits in the case where
26389fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        // it is looping on buffer full condition in obtainBuffer().
26489fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        // Otherwise the callback thread will never exit.
26589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        stop();
26689fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        if (mAudioTrackThread != 0) {
267b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald            mProxy->interrupt();
2683acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten            mAudioTrackThread->requestExit();   // see comment in AudioTrack.h
26989fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project            mAudioTrackThread->requestExitAndWait();
27089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project            mAudioTrackThread.clear();
27189fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        }
272296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent        // No lock here: worst case we remove a NULL callback which will be a nop
273296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent        if (mDeviceCallback != 0 && mOutput != AUDIO_IO_HANDLE_NONE) {
274296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent            AudioSystem::removeAudioDeviceCallback(mDeviceCallback, mOutput);
275296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent        }
276f888020c6e2735624f2b2a30e72aca24e17b8b4dMarco Nelissen        IInterface::asBinder(mAudioTrack)->unlinkToDeath(mDeathNotifier, this);
27753cec22821072719ee02c856e9ac2dda2496c570Glenn Kasten        mAudioTrack.clear();
2783bcffa136909c1fb6e88ee4efd12ccac18360a85Eric Laurent        mCblkMemory.clear();
2793bcffa136909c1fb6e88ee4efd12ccac18360a85Eric Laurent        mSharedBuffer.clear();
28089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        IPCThreadState::self()->flushCommands();
2814c36d6f48f4eecacc148317f775f65961a4f03d2Glenn Kasten        ALOGV("~AudioTrack, releasing session id %d from %d on behalf of %d",
2824c36d6f48f4eecacc148317f775f65961a4f03d2Glenn Kasten                mSessionId, IPCThreadState::self()->getCallingPid(), mClientPid);
283d457c970c8d08519cd77280a90b61ae1e342cfe3Marco Nelissen        AudioSystem::releaseAudioSessionId(mSessionId, mClientPid);
28489fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    }
28589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project}
28689fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
28789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectstatus_t AudioTrack::set(
288fff6d715a8db0daf08a50634f242c40268de3d49Glenn Kasten        audio_stream_type_t streamType,
28989fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        uint32_t sampleRate,
290e1c3962e268ffc12bfd1bd9ea84da1f135f36960Glenn Kasten        audio_format_t format,
29128b76b334f92a15a2be3cc9e2f7d229a3275d1acGlenn Kasten        audio_channel_mask_t channelMask,
292bce50bfc3846ab008bafa75c5d3f29fd7b5395f7Glenn Kasten        size_t frameCount,
2930ca3cf94c0dfc173ad7886ae162c4b67067539f6Eric Laurent        audio_output_flags_t flags,
29489fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        callback_t cbf,
29589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        void* user,
296ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten        int32_t notificationFrames,
29789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        const sp<IMemory>& sharedBuffer,
298be916aa1267e2e6b1c148f51d11bcbbc79cb864cEric Laurent        bool threadCanCallJava,
299d848eb48c121c119e8ba7583efc75415fe102570Glenn Kasten        audio_session_t sessionId,
300ad3af3305f024bcbbd55c894a4995e449498e1baRichard Fitzgerald        transfer_type transferType,
301462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen        const audio_offload_info_t *offloadInfo,
3021f12a8ad958344c50733b948628ffa06db9c5bc6Andy Hung        uid_t uid,
303faabb51ceef13bf1e3f692219ac410c1cd75d0deJean-Michel Trivi        pid_t pid,
304faeb0f291330134dc4468359a36e099aae508449Ronghua Wu        const audio_attributes_t* pAttributes,
305ff874dc957f9ea70d87f4d627bf903e1fc86d58bAndy Hung        bool doNotReconnect,
306ff874dc957f9ea70d87f4d627bf903e1fc86d58bAndy Hung        float maxRequiredSpeed)
30789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project{
308bce50bfc3846ab008bafa75c5d3f29fd7b5395f7Glenn Kasten    ALOGV("set(): streamType %d, sampleRate %u, format %#x, channelMask %#x, frameCount %zu, "
309ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten          "flags #%x, notificationFrames %d, sessionId %d, transferType %d, uid %d, pid %d",
310bce50bfc3846ab008bafa75c5d3f29fd7b5395f7Glenn Kasten          streamType, sampleRate, format, channelMask, frameCount, flags, notificationFrames,
3114c36d6f48f4eecacc148317f775f65961a4f03d2Glenn Kasten          sessionId, transferType, uid, pid);
31286f04663032ddaa25110149d709bbf896ad83b02Glenn Kasten
31333ff89ba94a527e4293ee5349da01483252d5c83Phil Burk    mThreadCanCallJava = threadCanCallJava;
31433ff89ba94a527e4293ee5349da01483252d5c83Phil Burk
3159f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    switch (transferType) {
3169f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    case TRANSFER_DEFAULT:
3179f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        if (sharedBuffer != 0) {
3189f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            transferType = TRANSFER_SHARED;
3199f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        } else if (cbf == NULL || threadCanCallJava) {
3209f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            transferType = TRANSFER_SYNC;
3219f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        } else {
3229f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            transferType = TRANSFER_CALLBACK;
3239f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
3249f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        break;
3259f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    case TRANSFER_CALLBACK:
3269f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        if (cbf == NULL || sharedBuffer != 0) {
3279f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            ALOGE("Transfer type TRANSFER_CALLBACK but cbf == NULL || sharedBuffer != 0");
3289f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            return BAD_VALUE;
3299f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
3309f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        break;
3319f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    case TRANSFER_OBTAIN:
3329f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    case TRANSFER_SYNC:
3339f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        if (sharedBuffer != 0) {
3349f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            ALOGE("Transfer type TRANSFER_OBTAIN but sharedBuffer != 0");
3359f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            return BAD_VALUE;
3369f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
3379f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        break;
3389f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    case TRANSFER_SHARED:
3399f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        if (sharedBuffer == 0) {
3409f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            ALOGE("Transfer type TRANSFER_SHARED but sharedBuffer == 0");
3419f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            return BAD_VALUE;
3429f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
3439f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        break;
3449f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    default:
3459f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        ALOGE("Invalid transfer type %d", transferType);
3469f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        return BAD_VALUE;
3479f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    }
348dd5f4c8c4059f890e81b28b026a688febb4e1dd9Glenn Kasten    mSharedBuffer = sharedBuffer;
3499f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    mTransfer = transferType;
350faeb0f291330134dc4468359a36e099aae508449Ronghua Wu    mDoNotReconnect = doNotReconnect;
3519f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
35297c9f4fd7bc31e2968d816402659ba1c64f10b42Eric Laurent    ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %zu", sharedBuffer->pointer(),
35385ab62c4b433df3f1a9826bed1c9bec07a86c750Glenn Kasten            sharedBuffer->size());
35489fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
35534fb29696b0f3abf61b10f8d053b1f33d501de0aMark Salyzyn    ALOGV("set() streamType %d frameCount %zu flags %04x", streamType, frameCount, flags);
3561a9ed11a472493cac7f6dfcbfac2064526a493edEric Laurent
35753cec22821072719ee02c856e9ac2dda2496c570Glenn Kasten    // invariant that mAudioTrack != 0 is true only after set() returns successfully
3581dd70b9f04961a06fcb73a97fca10a53b3245d3cEric Laurent    if (mAudioTrack != 0) {
35929357bc2c0dd7c43ad3bd0c8e3efa4e6fd9bfd47Steve Block        ALOGE("Track already in use");
36089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        return INVALID_OPERATION;
36189fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    }
36289fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
36389fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    // handle default values first.
364e83b55dc29ca16092ba02f36f55fa6e0e37fd78cEric Laurent    if (streamType == AUDIO_STREAM_DEFAULT) {
365fce7a473248381cc83a01855f92581077d3c9ee2Dima Zavin        streamType = AUDIO_STREAM_MUSIC;
36689fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    }
367faabb51ceef13bf1e3f692219ac410c1cd75d0deJean-Michel Trivi    if (pAttributes == NULL) {
368223fd5c9738e9665e495904d37d4632414b68c1eEric Laurent        if (uint32_t(streamType) >= AUDIO_STREAM_PUBLIC_CNT) {
369faabb51ceef13bf1e3f692219ac410c1cd75d0deJean-Michel Trivi            ALOGE("Invalid stream type %d", streamType);
370faabb51ceef13bf1e3f692219ac410c1cd75d0deJean-Michel Trivi            return BAD_VALUE;
371faabb51ceef13bf1e3f692219ac410c1cd75d0deJean-Michel Trivi        }
372faabb51ceef13bf1e3f692219ac410c1cd75d0deJean-Michel Trivi        mStreamType = streamType;
373e83b55dc29ca16092ba02f36f55fa6e0e37fd78cEric Laurent
374faabb51ceef13bf1e3f692219ac410c1cd75d0deJean-Michel Trivi    } else {
375faabb51ceef13bf1e3f692219ac410c1cd75d0deJean-Michel Trivi        // stream type shouldn't be looked at, this track has audio attributes
376faabb51ceef13bf1e3f692219ac410c1cd75d0deJean-Michel Trivi        memcpy(&mAttributes, pAttributes, sizeof(audio_attributes_t));
377faabb51ceef13bf1e3f692219ac410c1cd75d0deJean-Michel Trivi        ALOGV("Building AudioTrack with attributes: usage=%d content=%d flags=0x%x tags=[%s]",
378faabb51ceef13bf1e3f692219ac410c1cd75d0deJean-Michel Trivi                mAttributes.usage, mAttributes.content_type, mAttributes.flags, mAttributes.tags);
379e83b55dc29ca16092ba02f36f55fa6e0e37fd78cEric Laurent        mStreamType = AUDIO_STREAM_DEFAULT;
380c6bd5db9d9cf4bba1649b5b7ddea2d23f5de23a9Eric Laurent        if ((mAttributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
381c6bd5db9d9cf4bba1649b5b7ddea2d23f5de23a9Eric Laurent            flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
382c6bd5db9d9cf4bba1649b5b7ddea2d23f5de23a9Eric Laurent        }
38333ff89ba94a527e4293ee5349da01483252d5c83Phil Burk        if ((mAttributes.flags & AUDIO_FLAG_LOW_LATENCY) != 0) {
38433ff89ba94a527e4293ee5349da01483252d5c83Phil Burk            flags = (audio_output_flags_t) (flags | AUDIO_OUTPUT_FLAG_FAST);
38533ff89ba94a527e4293ee5349da01483252d5c83Phil Burk        }
386fff204c192f7e16c635a79f6a85786afb8522a3dAndy Hung        // check deep buffer after flags have been modified above
387fff204c192f7e16c635a79f6a85786afb8522a3dAndy Hung        if (flags == AUDIO_OUTPUT_FLAG_NONE && (mAttributes.flags & AUDIO_FLAG_DEEP_BUFFER) != 0) {
388fff204c192f7e16c635a79f6a85786afb8522a3dAndy Hung            flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
389fff204c192f7e16c635a79f6a85786afb8522a3dAndy Hung        }
390dd5f4c8c4059f890e81b28b026a688febb4e1dd9Glenn Kasten    }
391ea7939a079b3600cab955760839b021326f8cfc3Glenn Kasten
39289fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    // these below should probably come from the audioFlinger too...
393e1c3962e268ffc12bfd1bd9ea84da1f135f36960Glenn Kasten    if (format == AUDIO_FORMAT_DEFAULT) {
394fce7a473248381cc83a01855f92581077d3c9ee2Dima Zavin        format = AUDIO_FORMAT_PCM_16_BIT;
395fdb3c07db5d44535eb8c3ec46dc78ad8446c01ebPhil Burk    } else if (format == AUDIO_FORMAT_IEC61937) { // HDMI pass-through?
396fdb3c07db5d44535eb8c3ec46dc78ad8446c01ebPhil Burk        mAttributes.flags |= AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO;
39789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    }
39889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
39989fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    // validate parameters
400fce7a473248381cc83a01855f92581077d3c9ee2Dima Zavin    if (!audio_is_valid_format(format)) {
401cac3daa6332bf6d1f7d26adc4a9915f3d7992dd9Glenn Kasten        ALOGE("Invalid format %#x", format);
40289fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        return BAD_VALUE;
40389fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    }
404dd5f4c8c4059f890e81b28b026a688febb4e1dd9Glenn Kasten    mFormat = format;
405c2f1f07084818942352c6bbfb36af9b6b330eb4eEric Laurent
4068ba90326d683b035d99e24db669093e4602a7149Glenn Kasten    if (!audio_is_output_channel(channelMask)) {
4078ba90326d683b035d99e24db669093e4602a7149Glenn Kasten        ALOGE("Invalid channel mask %#x", channelMask);
4088ba90326d683b035d99e24db669093e4602a7149Glenn Kasten        return BAD_VALUE;
4098ba90326d683b035d99e24db669093e4602a7149Glenn Kasten    }
410e3247bf8dd4f8fa8dfa3a108260241ae4a967569Glenn Kasten    mChannelMask = channelMask;
411e541269be94f3a1072932d51537905b120ef4733Andy Hung    uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
412e3247bf8dd4f8fa8dfa3a108260241ae4a967569Glenn Kasten    mChannelCount = channelCount;
4138ba90326d683b035d99e24db669093e4602a7149Glenn Kasten
414c2f1f07084818942352c6bbfb36af9b6b330eb4eEric Laurent    // force direct flag if format is not linear PCM
415b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald    // or offload was requested
416b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald    if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
417b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald            || !audio_is_linear_pcm(format)) {
418b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        ALOGV( (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
419b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald                    ? "Offload request, forcing to Direct Output"
420b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald                    : "Not linear PCM, forcing to Direct Output");
4210ca3cf94c0dfc173ad7886ae162c4b67067539f6Eric Laurent        flags = (audio_output_flags_t)
4223acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten                // FIXME why can't we allow direct AND fast?
4230ca3cf94c0dfc173ad7886ae162c4b67067539f6Eric Laurent                ((flags | AUDIO_OUTPUT_FLAG_DIRECT) & ~AUDIO_OUTPUT_FLAG_FAST);
424c2f1f07084818942352c6bbfb36af9b6b330eb4eEric Laurent    }
425c2f1f07084818942352c6bbfb36af9b6b330eb4eEric Laurent
426d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    // force direct flag if HW A/V sync requested
427d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
428d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent        flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
429d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent    }
430d1f69b0b17acbd96987ecb2f3378abd394d05903Eric Laurent
431b773038277ba328696832b690b91ce6e95bd1a6cGlenn Kasten    if (flags & AUDIO_OUTPUT_FLAG_DIRECT) {
432fdb3c07db5d44535eb8c3ec46dc78ad8446c01ebPhil Burk        if (audio_has_proportional_frames(format)) {
433b773038277ba328696832b690b91ce6e95bd1a6cGlenn Kasten            mFrameSize = channelCount * audio_bytes_per_sample(format);
434b773038277ba328696832b690b91ce6e95bd1a6cGlenn Kasten        } else {
435b773038277ba328696832b690b91ce6e95bd1a6cGlenn Kasten            mFrameSize = sizeof(uint8_t);
436b773038277ba328696832b690b91ce6e95bd1a6cGlenn Kasten        }
437e3aa659e9cee7df5c12a80d285cc29ab3b2cbb39Glenn Kasten    } else {
438fdb3c07db5d44535eb8c3ec46dc78ad8446c01ebPhil Burk        ALOG_ASSERT(audio_has_proportional_frames(format));
439b773038277ba328696832b690b91ce6e95bd1a6cGlenn Kasten        mFrameSize = channelCount * audio_bytes_per_sample(format);
440b773038277ba328696832b690b91ce6e95bd1a6cGlenn Kasten        // createTrack will return an error if PCM format is not supported by server,
441b773038277ba328696832b690b91ce6e95bd1a6cGlenn Kasten        // so no need to check for specific PCM formats here
442e3aa659e9cee7df5c12a80d285cc29ab3b2cbb39Glenn Kasten    }
443e3aa659e9cee7df5c12a80d285cc29ab3b2cbb39Glenn Kasten
4440d6db582f2ccc9f8943c5f3965e2994b7d137158Eric Laurent    // sampling rate must be specified for direct outputs
4450d6db582f2ccc9f8943c5f3965e2994b7d137158Eric Laurent    if (sampleRate == 0 && (flags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
4460d6db582f2ccc9f8943c5f3965e2994b7d137158Eric Laurent        return BAD_VALUE;
4470d6db582f2ccc9f8943c5f3965e2994b7d137158Eric Laurent    }
4480d6db582f2ccc9f8943c5f3965e2994b7d137158Eric Laurent    mSampleRate = sampleRate;
4493a474aa67fc31505740526dd249d96204c08bf79Lajos Molnar    mOriginalSampleRate = sampleRate;
4505a8a95de6dad1a3bcf3da5a37b35766e89086e13Ricardo Garcia    mPlaybackRate = AUDIO_PLAYBACK_RATE_DEFAULT;
451ff874dc957f9ea70d87f4d627bf903e1fc86d58bAndy Hung    // 1.0 <= mMaxRequiredSpeed <= AUDIO_TIMESTRETCH_SPEED_MAX
452ff874dc957f9ea70d87f4d627bf903e1fc86d58bAndy Hung    mMaxRequiredSpeed = min(max(maxRequiredSpeed, 1.0f), AUDIO_TIMESTRETCH_SPEED_MAX);
4530d6db582f2ccc9f8943c5f3965e2994b7d137158Eric Laurent
454b5ccb2d99b2af400c70777a6452f090ac14f5a96Glenn Kasten    // Make copy of input parameter offloadInfo so that in the future:
455b5ccb2d99b2af400c70777a6452f090ac14f5a96Glenn Kasten    //  (a) createTrack_l doesn't need it as an input parameter
456b5ccb2d99b2af400c70777a6452f090ac14f5a96Glenn Kasten    //  (b) we can support re-creation of offloaded tracks
457b5ccb2d99b2af400c70777a6452f090ac14f5a96Glenn Kasten    if (offloadInfo != NULL) {
458b5ccb2d99b2af400c70777a6452f090ac14f5a96Glenn Kasten        mOffloadInfoCopy = *offloadInfo;
459b5ccb2d99b2af400c70777a6452f090ac14f5a96Glenn Kasten        mOffloadInfo = &mOffloadInfoCopy;
460b5ccb2d99b2af400c70777a6452f090ac14f5a96Glenn Kasten    } else {
461b5ccb2d99b2af400c70777a6452f090ac14f5a96Glenn Kasten        mOffloadInfo = NULL;
46220b9ef0b55c9150ae11057ab997ae61be2d496efEric Laurent        memset(&mOffloadInfoCopy, 0, sizeof(audio_offload_info_t));
463b5ccb2d99b2af400c70777a6452f090ac14f5a96Glenn Kasten    }
464b5ccb2d99b2af400c70777a6452f090ac14f5a96Glenn Kasten
46566e4635cb09fadcaccf912f37c387396c428378aGlenn Kasten    mVolume[AUDIO_INTERLEAVE_LEFT] = 1.0f;
46666e4635cb09fadcaccf912f37c387396c428378aGlenn Kasten    mVolume[AUDIO_INTERLEAVE_RIGHT] = 1.0f;
46705632a5fa4b88ca474294887fc92a9fcdf0e2352Glenn Kasten    mSendLevel = 0.0f;
468396fabdb6efcdac5aea3d9f559d1beedf6a4cedcGlenn Kasten    // mFrameCount is initialized in createTrack_l
469b603744e96b07b1d5bf745bde593fb2c025cefcfGlenn Kasten    mReqFrameCount = frameCount;
470ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten    if (notificationFrames >= 0) {
471ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten        mNotificationFramesReq = notificationFrames;
472ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten        mNotificationsPerBufferReq = 0;
473ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten    } else {
474ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten        if (!(flags & AUDIO_OUTPUT_FLAG_FAST)) {
475ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten            ALOGE("notificationFrames=%d not permitted for non-fast track",
476ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten                    notificationFrames);
477ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten            return BAD_VALUE;
478ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten        }
479ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten        if (frameCount > 0) {
480ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten            ALOGE("notificationFrames=%d not permitted with non-zero frameCount=%zu",
481ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten                    notificationFrames, frameCount);
482ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten            return BAD_VALUE;
483ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten        }
484ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten        mNotificationFramesReq = 0;
485ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten        const uint32_t minNotificationsPerBuffer = 1;
486ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten        const uint32_t maxNotificationsPerBuffer = 8;
487ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten        mNotificationsPerBufferReq = min(maxNotificationsPerBuffer,
488ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten                max((uint32_t) -notificationFrames, minNotificationsPerBuffer));
489ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten        ALOGW_IF(mNotificationsPerBufferReq != (uint32_t) -notificationFrames,
490ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten                "notificationFrames=%d clamped to the range -%u to -%u",
491ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten                notificationFrames, minNotificationsPerBuffer, maxNotificationsPerBuffer);
492ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten    }
4939f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    mNotificationFramesAct = 0;
494caf7f48a0ef558689d39aafd187c1571ff4128b4Eric Laurent    if (sessionId == AUDIO_SESSION_ALLOCATE) {
495d848eb48c121c119e8ba7583efc75415fe102570Glenn Kasten        mSessionId = (audio_session_t) AudioSystem::newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
496caf7f48a0ef558689d39aafd187c1571ff4128b4Eric Laurent    } else {
497caf7f48a0ef558689d39aafd187c1571ff4128b4Eric Laurent        mSessionId = sessionId;
498caf7f48a0ef558689d39aafd187c1571ff4128b4Eric Laurent    }
499d457c970c8d08519cd77280a90b61ae1e342cfe3Marco Nelissen    int callingpid = IPCThreadState::self()->getCallingPid();
500d457c970c8d08519cd77280a90b61ae1e342cfe3Marco Nelissen    int mypid = getpid();
5011f12a8ad958344c50733b948628ffa06db9c5bc6Andy Hung    if (uid == AUDIO_UID_INVALID || (callingpid != mypid)) {
502462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen        mClientUid = IPCThreadState::self()->getCallingUid();
503462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen    } else {
504462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen        mClientUid = uid;
505462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen    }
506d457c970c8d08519cd77280a90b61ae1e342cfe3Marco Nelissen    if (pid == -1 || (callingpid != mypid)) {
507d457c970c8d08519cd77280a90b61ae1e342cfe3Marco Nelissen        mClientPid = callingpid;
508d457c970c8d08519cd77280a90b61ae1e342cfe3Marco Nelissen    } else {
509d457c970c8d08519cd77280a90b61ae1e342cfe3Marco Nelissen        mClientPid = pid;
510d457c970c8d08519cd77280a90b61ae1e342cfe3Marco Nelissen    }
5112beeb50b1bba9e92f6cacfeca37fe9fa9d36ead1Eric Laurent    mAuxEffectId = 0;
512ae34ed2bcc9fa49a22fe7497327adb689ef27e8dHaynes Mathew George    mOrigFlags = mFlags = flags;
5134a4a0959bca78e03e3c3f486ba17829c28314d8cGlenn Kasten    mCbf = cbf;
514be916aa1267e2e6b1c148f51d11bcbbc79cb864cEric Laurent
515a997e7a7c5aa2fc7e95316218316f8b7b98786baGlenn Kasten    if (cbf != NULL) {
516896adcd3ae6a1c7010e526327eff54e16179987bEric Laurent        mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava);
517a997e7a7c5aa2fc7e95316218316f8b7b98786baGlenn Kasten        mAudioTrackThread->run("AudioTrack", ANDROID_PRIORITY_AUDIO, 0 /*stack*/);
518bfd318402924414fbde4d31c9d23cc423f10b630Glenn Kasten        // thread begins in paused state, and will not reference us until start()
519a997e7a7c5aa2fc7e95316218316f8b7b98786baGlenn Kasten    }
520a997e7a7c5aa2fc7e95316218316f8b7b98786baGlenn Kasten
52134f1d8ecd23169a5f299937e3aaf1bd7937578a0Eric Laurent    // create the IAudioTrack
5220d6db582f2ccc9f8943c5f3965e2994b7d137158Eric Laurent    status_t status = createTrack_l();
523a997e7a7c5aa2fc7e95316218316f8b7b98786baGlenn Kasten
52434f1d8ecd23169a5f299937e3aaf1bd7937578a0Eric Laurent    if (status != NO_ERROR) {
525a997e7a7c5aa2fc7e95316218316f8b7b98786baGlenn Kasten        if (mAudioTrackThread != 0) {
526b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald            mAudioTrackThread->requestExit();   // see comment in AudioTrack.h
527b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald            mAudioTrackThread->requestExitAndWait();
528a997e7a7c5aa2fc7e95316218316f8b7b98786baGlenn Kasten            mAudioTrackThread.clear();
529a997e7a7c5aa2fc7e95316218316f8b7b98786baGlenn Kasten        }
53089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        return status;
53189fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    }
53234f1d8ecd23169a5f299937e3aaf1bd7937578a0Eric Laurent
53389fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    mStatus = NO_ERROR;
53489fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    mUserData = user;
5354ede21d9c1f957baf5e561849ff9bbe4bcbefc20Andy Hung    mLoopCount = 0;
5364ede21d9c1f957baf5e561849ff9bbe4bcbefc20Andy Hung    mLoopStart = 0;
5374ede21d9c1f957baf5e561849ff9bbe4bcbefc20Andy Hung    mLoopEnd = 0;
53853c3b5fc1afe162a8669cb3d27d6bb14e1847e39Andy Hung    mLoopCountNotified = 0;
53989fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    mMarkerPosition = 0;
5402c22aeb65e801f663a754d043062f85e49f77739Jean-Michel Trivi    mMarkerReached = false;
54189fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    mNewPosition = 0;
54289fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    mUpdatePeriod = 0;
543200092b7f21d2b98f30b800e79d152636f9ba225Glenn Kasten    mPosition = 0;
544200092b7f21d2b98f30b800e79d152636f9ba225Glenn Kasten    mReleased = 0;
5457f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung    mStartUs = 0;
546d457c970c8d08519cd77280a90b61ae1e342cfe3Marco Nelissen    AudioSystem::acquireAudioSessionId(mSessionId, mClientPid);
5479f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    mSequence = 1;
5489f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    mObservedSequence = mSequence;
5499f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    mInUnderrun = false;
5501b42097f38e72574ed853a35f4e8a66e4739c421Phil Burk    mPreviousTimestampValid = false;
551c8e09c610fabc7390297ecb48e939acbdfe27325Andy Hung    mTimestampStartupGlitchReported = false;
552c8e09c610fabc7390297ecb48e939acbdfe27325Andy Hung    mRetrogradeMotionReported = false;
553b01faa31462e19957ae3c0c3ada07c9576a9494fAndy Hung    mPreviousLocation = ExtendedTimestamp::LOCATION_INVALID;
55465ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung    mStartTs.mPosition = 0;
5552812d9ea3a3a33142dd8e23c9d949c498d6f7a12Phil Burk    mUnderrunCountOffset = 0;
556ea2b9c07b34079f0dbd8610a511e006e69a15adcAndy Hung    mFramesWritten = 0;
557ea2b9c07b34079f0dbd8610a511e006e69a15adcAndy Hung    mFramesWrittenServerOffset = 0;
558f20a4e9f84bbb8748f28ca326caeba7a9947a369Andy Hung    mFramesWrittenAtRestore = -1; // -1 is a unique initializer.
5594ef88d7106c01f81109ee163cb6789073d80c6aeAndy Hung    mVolumeHandler = new VolumeHandler();
56089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    return NO_ERROR;
56189fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project}
56289fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
56389fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project// -------------------------------------------------------------------------
56489fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
565b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgeraldstatus_t AudioTrack::start()
56689fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project{
567f5aafb209d01ba2ab6cb55d1a12cfc653e2b4be0Eric Laurent    AutoMutex lock(mLock);
568b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald
5699f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    if (mState == STATE_ACTIVE) {
570b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        return INVALID_OPERATION;
5719f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    }
5721703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent
5739f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    mInUnderrun = true;
5742b584244930c9de0e3bc46898a801e9ccb731900Eric Laurent
5759f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    State previousState = mState;
576b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald    if (previousState == STATE_PAUSED_STOPPING) {
577b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        mState = STATE_STOPPING;
578b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald    } else {
579b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        mState = STATE_ACTIVE;
580b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald    }
581200092b7f21d2b98f30b800e79d152636f9ba225Glenn Kasten    (void) updateAndGetPosition_l();
58265ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung
58365ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung    // save start timestamp
58465ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung    if (isOffloadedOrDirect_l()) {
58565ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung        if (getTimestamp_l(mStartTs) != OK) {
58665ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung            mStartTs.mPosition = 0;
58765ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung        }
58865ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung    } else {
58965ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung        if (getTimestamp_l(&mStartEts) != OK) {
59065ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung            mStartEts.clear();
59165ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung        }
59265ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung    }
5939f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    if (previousState == STATE_STOPPED || previousState == STATE_FLUSHED) {
5949f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        // reset current position as seen by client to 0
595200092b7f21d2b98f30b800e79d152636f9ba225Glenn Kasten        mPosition = 0;
5961b42097f38e72574ed853a35f4e8a66e4739c421Phil Burk        mPreviousTimestampValid = false;
597c8e09c610fabc7390297ecb48e939acbdfe27325Andy Hung        mTimestampStartupGlitchReported = false;
598c8e09c610fabc7390297ecb48e939acbdfe27325Andy Hung        mRetrogradeMotionReported = false;
599b01faa31462e19957ae3c0c3ada07c9576a9494fAndy Hung        mPreviousLocation = ExtendedTimestamp::LOCATION_INVALID;
6001b42097f38e72574ed853a35f4e8a66e4739c421Phil Burk
60165ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung        if (!isOffloadedOrDirect_l()
60265ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung                && mStartEts.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] > 0) {
603e1e9846a786a0d77a13b44f8e798e03b4cba9d77Andy Hung            // Server side has consumed something, but is it finished consuming?
604e1e9846a786a0d77a13b44f8e798e03b4cba9d77Andy Hung            // It is possible since flush and stop are asynchronous that the server
605e1e9846a786a0d77a13b44f8e798e03b4cba9d77Andy Hung            // is still active at this point.
606e1e9846a786a0d77a13b44f8e798e03b4cba9d77Andy Hung            ALOGV("start: server read:%lld  cumulative flushed:%lld  client written:%lld",
607e1e9846a786a0d77a13b44f8e798e03b4cba9d77Andy Hung                    (long long)(mFramesWrittenServerOffset
60865ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung                            + mStartEts.mPosition[ExtendedTimestamp::LOCATION_SERVER]),
60965ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung                    (long long)mStartEts.mFlushed,
610e1e9846a786a0d77a13b44f8e798e03b4cba9d77Andy Hung                    (long long)mFramesWritten);
61165ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung            mFramesWrittenServerOffset = -mStartEts.mPosition[ExtendedTimestamp::LOCATION_SERVER];
61261be84167c1a11c8a030e00a2b79b2bc4fdf617fAndy Hung        }
613e1e9846a786a0d77a13b44f8e798e03b4cba9d77Andy Hung        mFramesWritten = 0;
614e1e9846a786a0d77a13b44f8e798e03b4cba9d77Andy Hung        mProxy->clearTimestamp(); // need new server push for valid timestamp
615e1e9846a786a0d77a13b44f8e798e03b4cba9d77Andy Hung        mMarkerReached = false;
61661be84167c1a11c8a030e00a2b79b2bc4fdf617fAndy Hung
6177f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung        // For offloaded tracks, we don't know if the hardware counters are really zero here,
6187f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung        // since the flush is asynchronous and stop may not fully drain.
6197f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung        // We save the time when the track is started to later verify whether
6207f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung        // the counters are realistic (i.e. start from zero after this time).
6217f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung        mStartUs = getNowUs();
6227f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung
623ec9a032c2e104ab1e3b5bf73e69dab1408ced0adEric Laurent        // force refresh of remaining frames by processAudioBuffer() as last
624ec9a032c2e104ab1e3b5bf73e69dab1408ced0adEric Laurent        // write before stop could be partial.
625ec9a032c2e104ab1e3b5bf73e69dab1408ced0adEric Laurent        mRefreshRemaining = true;
62689fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    }
627200092b7f21d2b98f30b800e79d152636f9ba225Glenn Kasten    mNewPosition = mPosition + mUpdatePeriod;
6284be3b831904640ca853845b3ea31f985774047deAndy Hung    int32_t flags = android_atomic_and(~(CBLK_STREAM_END_DONE | CBLK_DISABLED), &mCblk->mFlags);
62989fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
6309f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    status_t status = NO_ERROR;
6319f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    if (!(flags & CBLK_INVALID)) {
6329f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        status = mAudioTrack->start();
6339f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        if (status == DEAD_OBJECT) {
6349f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            flags |= CBLK_INVALID;
63589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        }
6369f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    }
6379f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    if (flags & CBLK_INVALID) {
6389f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        status = restoreTrack_l("start");
6399f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    }
6409f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
64179629f0716f04e79064256362be56730077b8c50Andy Hung    // resume or pause the callback thread as needed.
64279629f0716f04e79064256362be56730077b8c50Andy Hung    sp<AudioTrackThread> t = mAudioTrackThread;
64379629f0716f04e79064256362be56730077b8c50Andy Hung    if (status == NO_ERROR) {
64479629f0716f04e79064256362be56730077b8c50Andy Hung        if (t != 0) {
64579629f0716f04e79064256362be56730077b8c50Andy Hung            if (previousState == STATE_STOPPING) {
64679629f0716f04e79064256362be56730077b8c50Andy Hung                mProxy->interrupt();
64779629f0716f04e79064256362be56730077b8c50Andy Hung            } else {
64879629f0716f04e79064256362be56730077b8c50Andy Hung                t->resume();
64979629f0716f04e79064256362be56730077b8c50Andy Hung            }
65079629f0716f04e79064256362be56730077b8c50Andy Hung        } else {
65179629f0716f04e79064256362be56730077b8c50Andy Hung            mPreviousPriority = getpriority(PRIO_PROCESS, 0);
65279629f0716f04e79064256362be56730077b8c50Andy Hung            get_sched_policy(0, &mPreviousSchedulingGroup);
65379629f0716f04e79064256362be56730077b8c50Andy Hung            androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO);
65479629f0716f04e79064256362be56730077b8c50Andy Hung        }
65579629f0716f04e79064256362be56730077b8c50Andy Hung    } else {
6569f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        ALOGE("start() status %d", status);
6579f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        mState = previousState;
65889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        if (t != 0) {
659b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald            if (previousState != STATE_STOPPING) {
660b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald                t->pause();
661b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald            }
66289fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        } else {
663879135196fd1c97deefc538c888037c56c2879a7Glenn Kasten            setpriority(PRIO_PROCESS, 0, mPreviousPriority);
664a636433cbd09c0708b85f337ef45c0cdef3bcb4dGlenn Kasten            set_sched_policy(0, mPreviousSchedulingGroup);
66589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        }
66689fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    }
66789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
668b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald    return status;
6699f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten}
6709f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
6719f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kastenvoid AudioTrack::stop()
6729f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten{
6739f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    AutoMutex lock(mLock);
674397edb3377e5775f4df60afb8bf6d4711e5adc0eGlenn Kasten    if (mState != STATE_ACTIVE && mState != STATE_PAUSED) {
6759f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        return;
6769f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    }
6779f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
67823a7545c4de71e989c2d8ebf1d5b9dcf463c36a9Glenn Kasten    if (isOffloaded_l()) {
679b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        mState = STATE_STOPPING;
680b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald    } else {
681b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        mState = STATE_STOPPED;
6822148bf0e79c436b8764b9edc4c8f2730cce98a32Andy Hung        ALOGD_IF(mSharedBuffer == nullptr,
6832148bf0e79c436b8764b9edc4c8f2730cce98a32Andy Hung                "stop() called with %u frames delivered", mReleased.value());
684c2813e568aa476e03d159529c0af28c99536db8dAndy Hung        mReleased = 0;
685b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald    }
686b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald
6879f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    mProxy->interrupt();
6889f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    mAudioTrack->stop();
68961be84167c1a11c8a030e00a2b79b2bc4fdf617fAndy Hung
69061be84167c1a11c8a030e00a2b79b2bc4fdf617fAndy Hung    // Note: legacy handling - stop does not clear playback marker
69161be84167c1a11c8a030e00a2b79b2bc4fdf617fAndy Hung    // and periodic update counter, but flush does for streaming tracks.
6929b4615887c23548438fd0d8e3d8f04ac21912850Andy Hung
6939f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    if (mSharedBuffer != 0) {
6949b4615887c23548438fd0d8e3d8f04ac21912850Andy Hung        // clear buffer position and loop count.
6959b4615887c23548438fd0d8e3d8f04ac21912850Andy Hung        mStaticProxy->setBufferPositionAndLoop(0 /* position */,
6969b4615887c23548438fd0d8e3d8f04ac21912850Andy Hung                0 /* loopStart */, 0 /* loopEnd */, 0 /* loopCount */);
6979f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    }
698b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald
6999f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    sp<AudioTrackThread> t = mAudioTrackThread;
7009f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    if (t != 0) {
70123a7545c4de71e989c2d8ebf1d5b9dcf463c36a9Glenn Kasten        if (!isOffloaded_l()) {
702b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald            t->pause();
703b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        }
7049f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    } else {
7059f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        setpriority(PRIO_PROCESS, 0, mPreviousPriority);
7069f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        set_sched_policy(0, mPreviousSchedulingGroup);
7079f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    }
70889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project}
70989fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
71089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectbool AudioTrack::stopped() const
71189fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project{
7129a2aaf927e56a4b4acab23ef16b3f133a9f48a63Glenn Kasten    AutoMutex lock(mLock);
7139f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    return mState != STATE_ACTIVE;
71489fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project}
71589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
71689fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectvoid AudioTrack::flush()
71789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project{
7189f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    if (mSharedBuffer != 0) {
7199f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        return;
7209f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    }
7211703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent    AutoMutex lock(mLock);
7229f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    if (mState == STATE_ACTIVE || mState == STATE_FLUSHED) {
7239f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        return;
7244bae3649d504d590a546717a8e49f96a30d9a745Glenn Kasten    }
7259f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    flush_l();
7261703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent}
7271703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent
7281703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurentvoid AudioTrack::flush_l()
7291703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent{
7309f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    ALOG_ASSERT(mState != STATE_ACTIVE);
731c2f1f07084818942352c6bbfb36af9b6b330eb4eEric Laurent
7322c22aeb65e801f663a754d043062f85e49f77739Jean-Michel Trivi    // clear playback marker and periodic update counter
7332c22aeb65e801f663a754d043062f85e49f77739Jean-Michel Trivi    mMarkerPosition = 0;
7342c22aeb65e801f663a754d043062f85e49f77739Jean-Michel Trivi    mMarkerReached = false;
7352c22aeb65e801f663a754d043062f85e49f77739Jean-Michel Trivi    mUpdatePeriod = 0;
736b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald    mRefreshRemaining = true;
737c2f1f07084818942352c6bbfb36af9b6b330eb4eEric Laurent
7389f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    mState = STATE_FLUSHED;
739c2813e568aa476e03d159529c0af28c99536db8dAndy Hung    mReleased = 0;
74023a7545c4de71e989c2d8ebf1d5b9dcf463c36a9Glenn Kasten    if (isOffloaded_l()) {
741b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        mProxy->interrupt();
742b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald    }
7439f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    mProxy->flush();
7444bae3649d504d590a546717a8e49f96a30d9a745Glenn Kasten    mAudioTrack->flush();
74589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project}
74689fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
74789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectvoid AudioTrack::pause()
74889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project{
749f5aafb209d01ba2ab6cb55d1a12cfc653e2b4be0Eric Laurent    AutoMutex lock(mLock);
750b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald    if (mState == STATE_ACTIVE) {
751b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        mState = STATE_PAUSED;
752b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald    } else if (mState == STATE_STOPPING) {
753b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        mState = STATE_PAUSED_STOPPING;
754b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald    } else {
7559f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        return;
75689fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    }
7579f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    mProxy->interrupt();
7589f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    mAudioTrack->pause();
7597064fd2dcdfeafea53cd5a992bb78c413542f29fHaynes Mathew George
7603a90f2849d49bf65f2d6257fd6da30ae46d745faMarco Nelissen    if (isOffloaded_l()) {
761142f519aa1acd5804d111e60d100f170fed28405Glenn Kasten        if (mOutput != AUDIO_IO_HANDLE_NONE) {
7627f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung            // An offload output can be re-used between two audio tracks having
7637f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung            // the same configuration. A timestamp query for a paused track
7647f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung            // while the other is running would return an incorrect time.
7657f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung            // To fix this, cache the playback position on a pause() and return
7667f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung            // this time when requested until the track is resumed.
7677f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung
7687f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung            // OffloadThread sends HAL pause in its threadLoop. Time saved
7697f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung            // here can be slightly off.
7707f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung
7717f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung            // TODO: check return code for getRenderPosition.
7727f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung
7737064fd2dcdfeafea53cd5a992bb78c413542f29fHaynes Mathew George            uint32_t halFrames;
7747064fd2dcdfeafea53cd5a992bb78c413542f29fHaynes Mathew George            AudioSystem::getRenderPosition(mOutput, &halFrames, &mPausedPosition);
7757064fd2dcdfeafea53cd5a992bb78c413542f29fHaynes Mathew George            ALOGV("AudioTrack::pause for offload, cache current position %u", mPausedPosition);
7767064fd2dcdfeafea53cd5a992bb78c413542f29fHaynes Mathew George        }
7777064fd2dcdfeafea53cd5a992bb78c413542f29fHaynes Mathew George    }
77889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project}
77989fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
780be916aa1267e2e6b1c148f51d11bcbbc79cb864cEric Laurentstatus_t AudioTrack::setVolume(float left, float right)
78189fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project{
782c56f3426099a3cf2d07ccff8886050c7fbce140fGlenn Kasten    // This duplicates a test by AudioTrack JNI, but that is not the only caller
783c56f3426099a3cf2d07ccff8886050c7fbce140fGlenn Kasten    if (isnanf(left) || left < GAIN_FLOAT_ZERO || left > GAIN_FLOAT_UNITY ||
784c56f3426099a3cf2d07ccff8886050c7fbce140fGlenn Kasten            isnanf(right) || right < GAIN_FLOAT_ZERO || right > GAIN_FLOAT_UNITY) {
785be916aa1267e2e6b1c148f51d11bcbbc79cb864cEric Laurent        return BAD_VALUE;
786be916aa1267e2e6b1c148f51d11bcbbc79cb864cEric Laurent    }
787be916aa1267e2e6b1c148f51d11bcbbc79cb864cEric Laurent
7881703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent    AutoMutex lock(mLock);
78966e4635cb09fadcaccf912f37c387396c428378aGlenn Kasten    mVolume[AUDIO_INTERLEAVE_LEFT] = left;
79066e4635cb09fadcaccf912f37c387396c428378aGlenn Kasten    mVolume[AUDIO_INTERLEAVE_RIGHT] = right;
79189fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
792c56f3426099a3cf2d07ccff8886050c7fbce140fGlenn Kasten    mProxy->setVolumeLR(gain_minifloat_pack(gain_from_float(left), gain_from_float(right)));
793be916aa1267e2e6b1c148f51d11bcbbc79cb864cEric Laurent
79423a7545c4de71e989c2d8ebf1d5b9dcf463c36a9Glenn Kasten    if (isOffloaded_l()) {
79559fe010bcc072597852454a2ec53d7b0a2002a3bEric Laurent        mAudioTrack->signal();
79659fe010bcc072597852454a2ec53d7b0a2002a3bEric Laurent    }
797be916aa1267e2e6b1c148f51d11bcbbc79cb864cEric Laurent    return NO_ERROR;
79889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project}
79989fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
800b1c0993b215c5c3eebd1c6bafc22bba23d57a70bGlenn Kastenstatus_t AudioTrack::setVolume(float volume)
80189fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project{
802b1c0993b215c5c3eebd1c6bafc22bba23d57a70bGlenn Kasten    return setVolume(volume, volume);
803be916aa1267e2e6b1c148f51d11bcbbc79cb864cEric Laurent}
804be916aa1267e2e6b1c148f51d11bcbbc79cb864cEric Laurent
8052beeb50b1bba9e92f6cacfeca37fe9fa9d36ead1Eric Laurentstatus_t AudioTrack::setAuxEffectSendLevel(float level)
806be916aa1267e2e6b1c148f51d11bcbbc79cb864cEric Laurent{
807c56f3426099a3cf2d07ccff8886050c7fbce140fGlenn Kasten    // This duplicates a test by AudioTrack JNI, but that is not the only caller
808c56f3426099a3cf2d07ccff8886050c7fbce140fGlenn Kasten    if (isnanf(level) || level < GAIN_FLOAT_ZERO || level > GAIN_FLOAT_UNITY) {
809be916aa1267e2e6b1c148f51d11bcbbc79cb864cEric Laurent        return BAD_VALUE;
810be916aa1267e2e6b1c148f51d11bcbbc79cb864cEric Laurent    }
811be916aa1267e2e6b1c148f51d11bcbbc79cb864cEric Laurent
8129f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    AutoMutex lock(mLock);
813be916aa1267e2e6b1c148f51d11bcbbc79cb864cEric Laurent    mSendLevel = level;
814e3aa659e9cee7df5c12a80d285cc29ab3b2cbb39Glenn Kasten    mProxy->setSendLevel(level);
815be916aa1267e2e6b1c148f51d11bcbbc79cb864cEric Laurent
816be916aa1267e2e6b1c148f51d11bcbbc79cb864cEric Laurent    return NO_ERROR;
817be916aa1267e2e6b1c148f51d11bcbbc79cb864cEric Laurent}
818be916aa1267e2e6b1c148f51d11bcbbc79cb864cEric Laurent
819a5224f319e2ba4b51ddb4287705ccf8d4b8ecc51Glenn Kastenvoid AudioTrack::getAuxEffectSendLevel(float* level) const
820be916aa1267e2e6b1c148f51d11bcbbc79cb864cEric Laurent{
821be916aa1267e2e6b1c148f51d11bcbbc79cb864cEric Laurent    if (level != NULL) {
8229f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        *level = mSendLevel;
823be916aa1267e2e6b1c148f51d11bcbbc79cb864cEric Laurent    }
82489fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project}
82589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
8263b16c766d1ae2cfd8487e8ffb2b23936fc0a8e17Glenn Kastenstatus_t AudioTrack::setSampleRate(uint32_t rate)
82789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project{
8285cbb5785a58655e21f5f7805274b8c78b986216bAndy Hung    AutoMutex lock(mLock);
8295cbb5785a58655e21f5f7805274b8c78b986216bAndy Hung    if (rate == mSampleRate) {
8305cbb5785a58655e21f5f7805274b8c78b986216bAndy Hung        return NO_ERROR;
8315cbb5785a58655e21f5f7805274b8c78b986216bAndy Hung    }
832d79072e9dff59f767cce2cda1caab80ce5a0815bGlenn Kasten    if (isOffloadedOrDirect_l() || (mFlags & AUDIO_OUTPUT_FLAG_FAST)) {
8334ff14bae91075eb274eb1c2975982358946e7e63John Grossman        return INVALID_OPERATION;
8344ff14bae91075eb274eb1c2975982358946e7e63John Grossman    }
8350d6db582f2ccc9f8943c5f3965e2994b7d137158Eric Laurent    if (mOutput == AUDIO_IO_HANDLE_NONE) {
8360d6db582f2ccc9f8943c5f3965e2994b7d137158Eric Laurent        return NO_INIT;
8370d6db582f2ccc9f8943c5f3965e2994b7d137158Eric Laurent    }
8385cbb5785a58655e21f5f7805274b8c78b986216bAndy Hung    // NOTE: it is theoretically possible, but highly unlikely, that a device change
8395cbb5785a58655e21f5f7805274b8c78b986216bAndy Hung    // could mean a previously allowed sampling rate is no longer allowed.
8409f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    uint32_t afSamplingRate;
8410d6db582f2ccc9f8943c5f3965e2994b7d137158Eric Laurent    if (AudioSystem::getSamplingRate(mOutput, &afSamplingRate) != NO_ERROR) {
842573266210fb2b2e7d86fbd46d0dfe16763611d91Eric Laurent        return NO_INIT;
84389fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    }
84426145643ce22d797b3b1675c82c47a2d8c79ecaaAndy Hung    // pitch is emulated by adjusting speed and sampleRate
8455a8a95de6dad1a3bcf3da5a37b35766e89086e13Ricardo Garcia    const uint32_t effectiveSampleRate = adjustSampleRate(rate, mPlaybackRate.mPitch);
84626145643ce22d797b3b1675c82c47a2d8c79ecaaAndy Hung    if (rate == 0 || effectiveSampleRate > afSamplingRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
847d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kasten        return BAD_VALUE;
848d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kasten    }
8498edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung    // TODO: Should we also check if the buffer size is compatible?
85089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
851e3aa659e9cee7df5c12a80d285cc29ab3b2cbb39Glenn Kasten    mSampleRate = rate;
85226145643ce22d797b3b1675c82c47a2d8c79ecaaAndy Hung    mProxy->setSampleRate(effectiveSampleRate);
853e3aa659e9cee7df5c12a80d285cc29ab3b2cbb39Glenn Kasten
854573266210fb2b2e7d86fbd46d0dfe16763611d91Eric Laurent    return NO_ERROR;
85589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project}
85689fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
857a5224f319e2ba4b51ddb4287705ccf8d4b8ecc51Glenn Kastenuint32_t AudioTrack::getSampleRate() const
85889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project{
8591703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent    AutoMutex lock(mLock);
8606f59db12a64f4496866952a251122ccb77a36c6bEric Laurent
8616f59db12a64f4496866952a251122ccb77a36c6bEric Laurent    // sample rate can be updated during playback by the offloaded decoder so we need to
8626f59db12a64f4496866952a251122ccb77a36c6bEric Laurent    // query the HAL and update if needed.
8636f59db12a64f4496866952a251122ccb77a36c6bEric Laurent// FIXME use Proxy return channel to update the rate from server and avoid polling here
864ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent    if (isOffloadedOrDirect_l()) {
865142f519aa1acd5804d111e60d100f170fed28405Glenn Kasten        if (mOutput != AUDIO_IO_HANDLE_NONE) {
8666f59db12a64f4496866952a251122ccb77a36c6bEric Laurent            uint32_t sampleRate = 0;
867b7f24b101d43139b4c747129bfbc4ecf5c468b86Jean-Michel Trivi            status_t status = AudioSystem::getSamplingRate(mOutput, &sampleRate);
8686f59db12a64f4496866952a251122ccb77a36c6bEric Laurent            if (status == NO_ERROR) {
8696f59db12a64f4496866952a251122ccb77a36c6bEric Laurent                mSampleRate = sampleRate;
8706f59db12a64f4496866952a251122ccb77a36c6bEric Laurent            }
8716f59db12a64f4496866952a251122ccb77a36c6bEric Laurent        }
8726f59db12a64f4496866952a251122ccb77a36c6bEric Laurent    }
873e3aa659e9cee7df5c12a80d285cc29ab3b2cbb39Glenn Kasten    return mSampleRate;
87489fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project}
87589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
8763a474aa67fc31505740526dd249d96204c08bf79Lajos Molnaruint32_t AudioTrack::getOriginalSampleRate() const
8773a474aa67fc31505740526dd249d96204c08bf79Lajos Molnar{
8783a474aa67fc31505740526dd249d96204c08bf79Lajos Molnar    return mOriginalSampleRate;
8793a474aa67fc31505740526dd249d96204c08bf79Lajos Molnar}
8803a474aa67fc31505740526dd249d96204c08bf79Lajos Molnar
8815a8a95de6dad1a3bcf3da5a37b35766e89086e13Ricardo Garciastatus_t AudioTrack::setPlaybackRate(const AudioPlaybackRate &playbackRate)
8828edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung{
8838edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung    AutoMutex lock(mLock);
8845a8a95de6dad1a3bcf3da5a37b35766e89086e13Ricardo Garcia    if (isAudioPlaybackRateEqual(playbackRate, mPlaybackRate)) {
8858edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung        return NO_ERROR;
8868edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung    }
887d79072e9dff59f767cce2cda1caab80ce5a0815bGlenn Kasten    if (isOffloadedOrDirect_l()) {
8888edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung        return INVALID_OPERATION;
8898edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung    }
8908edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung    if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
8918edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung        return INVALID_OPERATION;
8928edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung    }
893ff874dc957f9ea70d87f4d627bf903e1fc86d58bAndy Hung
894ff874dc957f9ea70d87f4d627bf903e1fc86d58bAndy Hung    ALOGV("setPlaybackRate (input): mSampleRate:%u  mSpeed:%f  mPitch:%f",
895ff874dc957f9ea70d87f4d627bf903e1fc86d58bAndy Hung            mSampleRate, playbackRate.mSpeed, playbackRate.mPitch);
89626145643ce22d797b3b1675c82c47a2d8c79ecaaAndy Hung    // pitch is emulated by adjusting speed and sampleRate
8975a8a95de6dad1a3bcf3da5a37b35766e89086e13Ricardo Garcia    const uint32_t effectiveRate = adjustSampleRate(mSampleRate, playbackRate.mPitch);
8985a8a95de6dad1a3bcf3da5a37b35766e89086e13Ricardo Garcia    const float effectiveSpeed = adjustSpeed(playbackRate.mSpeed, playbackRate.mPitch);
8995a8a95de6dad1a3bcf3da5a37b35766e89086e13Ricardo Garcia    const float effectivePitch = adjustPitch(playbackRate.mPitch);
9006c7f062d3149d6890daaee64828959ad6f61ea54Ricardo Garcia    AudioPlaybackRate playbackRateTemp = playbackRate;
9016c7f062d3149d6890daaee64828959ad6f61ea54Ricardo Garcia    playbackRateTemp.mSpeed = effectiveSpeed;
9026c7f062d3149d6890daaee64828959ad6f61ea54Ricardo Garcia    playbackRateTemp.mPitch = effectivePitch;
9036c7f062d3149d6890daaee64828959ad6f61ea54Ricardo Garcia
904ff874dc957f9ea70d87f4d627bf903e1fc86d58bAndy Hung    ALOGV("setPlaybackRate (effective): mSampleRate:%u  mSpeed:%f  mPitch:%f",
905ff874dc957f9ea70d87f4d627bf903e1fc86d58bAndy Hung            effectiveRate, effectiveSpeed, effectivePitch);
906ff874dc957f9ea70d87f4d627bf903e1fc86d58bAndy Hung
9076c7f062d3149d6890daaee64828959ad6f61ea54Ricardo Garcia    if (!isAudioPlaybackRateValid(playbackRateTemp)) {
908ff874dc957f9ea70d87f4d627bf903e1fc86d58bAndy Hung        ALOGV("setPlaybackRate(%f, %f) failed (effective rate out of bounds)",
909ff874dc957f9ea70d87f4d627bf903e1fc86d58bAndy Hung                playbackRate.mSpeed, playbackRate.mPitch);
91026145643ce22d797b3b1675c82c47a2d8c79ecaaAndy Hung        return BAD_VALUE;
91126145643ce22d797b3b1675c82c47a2d8c79ecaaAndy Hung    }
9128edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung    // Check if the buffer size is compatible.
91326145643ce22d797b3b1675c82c47a2d8c79ecaaAndy Hung    if (!isSampleRateSpeedAllowed_l(effectiveRate, effectiveSpeed)) {
914ff874dc957f9ea70d87f4d627bf903e1fc86d58bAndy Hung        ALOGV("setPlaybackRate(%f, %f) failed (buffer size)",
915ff874dc957f9ea70d87f4d627bf903e1fc86d58bAndy Hung                playbackRate.mSpeed, playbackRate.mPitch);
9168edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung        return BAD_VALUE;
9178edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung    }
9185a8a95de6dad1a3bcf3da5a37b35766e89086e13Ricardo Garcia
9196c7f062d3149d6890daaee64828959ad6f61ea54Ricardo Garcia    // Check resampler ratios are within bounds
920e34eae2de7bd6dcba5dea132dabb09f63ac46adcDan Austin    if ((uint64_t)effectiveRate > (uint64_t)mSampleRate * (uint64_t)AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
9216c7f062d3149d6890daaee64828959ad6f61ea54Ricardo Garcia        ALOGV("setPlaybackRate(%f, %f) failed. Resample rate exceeds max accepted value",
9226c7f062d3149d6890daaee64828959ad6f61ea54Ricardo Garcia                playbackRate.mSpeed, playbackRate.mPitch);
9236c7f062d3149d6890daaee64828959ad6f61ea54Ricardo Garcia        return BAD_VALUE;
9246c7f062d3149d6890daaee64828959ad6f61ea54Ricardo Garcia    }
9256c7f062d3149d6890daaee64828959ad6f61ea54Ricardo Garcia
926e34eae2de7bd6dcba5dea132dabb09f63ac46adcDan Austin    if ((uint64_t)effectiveRate * (uint64_t)AUDIO_RESAMPLER_UP_RATIO_MAX < (uint64_t)mSampleRate) {
9276c7f062d3149d6890daaee64828959ad6f61ea54Ricardo Garcia        ALOGV("setPlaybackRate(%f, %f) failed. Resample rate below min accepted value",
9286c7f062d3149d6890daaee64828959ad6f61ea54Ricardo Garcia                        playbackRate.mSpeed, playbackRate.mPitch);
9296c7f062d3149d6890daaee64828959ad6f61ea54Ricardo Garcia        return BAD_VALUE;
9306c7f062d3149d6890daaee64828959ad6f61ea54Ricardo Garcia    }
9316c7f062d3149d6890daaee64828959ad6f61ea54Ricardo Garcia    mPlaybackRate = playbackRate;
9326c7f062d3149d6890daaee64828959ad6f61ea54Ricardo Garcia    //set effective rates
9335a8a95de6dad1a3bcf3da5a37b35766e89086e13Ricardo Garcia    mProxy->setPlaybackRate(playbackRateTemp);
93426145643ce22d797b3b1675c82c47a2d8c79ecaaAndy Hung    mProxy->setSampleRate(effectiveRate); // FIXME: not quite "atomic" with setPlaybackRate
9358edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung    return NO_ERROR;
9368edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung}
9378edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung
9385a8a95de6dad1a3bcf3da5a37b35766e89086e13Ricardo Garciaconst AudioPlaybackRate& AudioTrack::getPlaybackRate() const
9398edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung{
9408edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung    AutoMutex lock(mLock);
9415a8a95de6dad1a3bcf3da5a37b35766e89086e13Ricardo Garcia    return mPlaybackRate;
9428edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung}
9438edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung
944c0adecb800b197cb8c028513130ebabf2d0f37baPhil Burkssize_t AudioTrack::getBufferSizeInFrames()
945c0adecb800b197cb8c028513130ebabf2d0f37baPhil Burk{
946c0adecb800b197cb8c028513130ebabf2d0f37baPhil Burk    AutoMutex lock(mLock);
947c0adecb800b197cb8c028513130ebabf2d0f37baPhil Burk    if (mOutput == AUDIO_IO_HANDLE_NONE || mProxy.get() == 0) {
948c0adecb800b197cb8c028513130ebabf2d0f37baPhil Burk        return NO_INIT;
949c0adecb800b197cb8c028513130ebabf2d0f37baPhil Burk    }
950e8972b0a27fac327c997fceb20d9abae1dc1d899Phil Burk    return (ssize_t) mProxy->getBufferSizeInFrames();
951c0adecb800b197cb8c028513130ebabf2d0f37baPhil Burk}
952c0adecb800b197cb8c028513130ebabf2d0f37baPhil Burk
953f2c87b3f88d987d2af6322e9763eb8224a2bae48Andy Hungstatus_t AudioTrack::getBufferDurationInUs(int64_t *duration)
954f2c87b3f88d987d2af6322e9763eb8224a2bae48Andy Hung{
955f2c87b3f88d987d2af6322e9763eb8224a2bae48Andy Hung    if (duration == nullptr) {
956f2c87b3f88d987d2af6322e9763eb8224a2bae48Andy Hung        return BAD_VALUE;
957f2c87b3f88d987d2af6322e9763eb8224a2bae48Andy Hung    }
958f2c87b3f88d987d2af6322e9763eb8224a2bae48Andy Hung    AutoMutex lock(mLock);
959f2c87b3f88d987d2af6322e9763eb8224a2bae48Andy Hung    if (mOutput == AUDIO_IO_HANDLE_NONE || mProxy.get() == 0) {
960f2c87b3f88d987d2af6322e9763eb8224a2bae48Andy Hung        return NO_INIT;
961f2c87b3f88d987d2af6322e9763eb8224a2bae48Andy Hung    }
962f2c87b3f88d987d2af6322e9763eb8224a2bae48Andy Hung    ssize_t bufferSizeInFrames = (ssize_t) mProxy->getBufferSizeInFrames();
963f2c87b3f88d987d2af6322e9763eb8224a2bae48Andy Hung    if (bufferSizeInFrames < 0) {
964f2c87b3f88d987d2af6322e9763eb8224a2bae48Andy Hung        return (status_t)bufferSizeInFrames;
965f2c87b3f88d987d2af6322e9763eb8224a2bae48Andy Hung    }
966f2c87b3f88d987d2af6322e9763eb8224a2bae48Andy Hung    *duration = (int64_t)((double)bufferSizeInFrames * 1000000
967f2c87b3f88d987d2af6322e9763eb8224a2bae48Andy Hung            / ((double)mSampleRate * mPlaybackRate.mSpeed));
968f2c87b3f88d987d2af6322e9763eb8224a2bae48Andy Hung    return NO_ERROR;
969f2c87b3f88d987d2af6322e9763eb8224a2bae48Andy Hung}
970f2c87b3f88d987d2af6322e9763eb8224a2bae48Andy Hung
971c0adecb800b197cb8c028513130ebabf2d0f37baPhil Burkssize_t AudioTrack::setBufferSizeInFrames(size_t bufferSizeInFrames)
972c0adecb800b197cb8c028513130ebabf2d0f37baPhil Burk{
973c0adecb800b197cb8c028513130ebabf2d0f37baPhil Burk    AutoMutex lock(mLock);
974c0adecb800b197cb8c028513130ebabf2d0f37baPhil Burk    if (mOutput == AUDIO_IO_HANDLE_NONE || mProxy.get() == 0) {
975c0adecb800b197cb8c028513130ebabf2d0f37baPhil Burk        return NO_INIT;
976c0adecb800b197cb8c028513130ebabf2d0f37baPhil Burk    }
977c0adecb800b197cb8c028513130ebabf2d0f37baPhil Burk    // Reject if timed track or compressed audio.
978d79072e9dff59f767cce2cda1caab80ce5a0815bGlenn Kasten    if (!audio_is_linear_pcm(mFormat)) {
979c0adecb800b197cb8c028513130ebabf2d0f37baPhil Burk        return INVALID_OPERATION;
980c0adecb800b197cb8c028513130ebabf2d0f37baPhil Burk    }
981e8972b0a27fac327c997fceb20d9abae1dc1d899Phil Burk    return (ssize_t) mProxy->setBufferSizeInFrames((uint32_t) bufferSizeInFrames);
982c0adecb800b197cb8c028513130ebabf2d0f37baPhil Burk}
983c0adecb800b197cb8c028513130ebabf2d0f37baPhil Burk
98489fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectstatus_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
98589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project{
986d79072e9dff59f767cce2cda1caab80ce5a0815bGlenn Kasten    if (mSharedBuffer == 0 || isOffloadedOrDirect()) {
987083d1c1492d496960d5b28f4664ff02101736677Glenn Kasten        return INVALID_OPERATION;
988083d1c1492d496960d5b28f4664ff02101736677Glenn Kasten    }
989083d1c1492d496960d5b28f4664ff02101736677Glenn Kasten
99089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    if (loopCount == 0) {
9919f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        ;
9929f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    } else if (loopCount >= -1 && loopStart < loopEnd && loopEnd <= mFrameCount &&
9939f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            loopEnd - loopStart >= MIN_LOOP) {
9949f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        ;
9959f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    } else {
99689fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        return BAD_VALUE;
99789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    }
99889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
9999f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    AutoMutex lock(mLock);
10009f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    // See setPosition() regarding setting parameters such as loop points or position while active
10019f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    if (mState == STATE_ACTIVE) {
10029f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        return INVALID_OPERATION;
1003c2f1f07084818942352c6bbfb36af9b6b330eb4eEric Laurent    }
10049f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    setLoop_l(loopStart, loopEnd, loopCount);
100589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    return NO_ERROR;
100689fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project}
100789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
10089f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kastenvoid AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount)
10099f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten{
10104ede21d9c1f957baf5e561849ff9bbe4bcbefc20Andy Hung    // We do not update the periodic notification point.
10114ede21d9c1f957baf5e561849ff9bbe4bcbefc20Andy Hung    // mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
10124ede21d9c1f957baf5e561849ff9bbe4bcbefc20Andy Hung    mLoopCount = loopCount;
10134ede21d9c1f957baf5e561849ff9bbe4bcbefc20Andy Hung    mLoopEnd = loopEnd;
10144ede21d9c1f957baf5e561849ff9bbe4bcbefc20Andy Hung    mLoopStart = loopStart;
101553c3b5fc1afe162a8669cb3d27d6bb14e1847e39Andy Hung    mLoopCountNotified = loopCount;
10169f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    mStaticProxy->setLoop(loopStart, loopEnd, loopCount);
10173c09c78aabcb9d314dfb400258fb99a37c7b50c9Andy Hung
10183c09c78aabcb9d314dfb400258fb99a37c7b50c9Andy Hung    // Waking the AudioTrackThread is not needed as this cannot be called when active.
10199f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten}
10209f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
102189fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectstatus_t AudioTrack::setMarkerPosition(uint32_t marker)
102289fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project{
1023fb1fdc9d6603aa228362e7349451f6455c9849c2Glenn Kasten    // The only purpose of setting marker position is to get a callback
1024ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent    if (mCbf == NULL || isOffloadedOrDirect()) {
1025d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kasten        return INVALID_OPERATION;
1026d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kasten    }
102789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
10289f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    AutoMutex lock(mLock);
102989fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    mMarkerPosition = marker;
10302c22aeb65e801f663a754d043062f85e49f77739Jean-Michel Trivi    mMarkerReached = false;
103189fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
10323c09c78aabcb9d314dfb400258fb99a37c7b50c9Andy Hung    sp<AudioTrackThread> t = mAudioTrackThread;
10333c09c78aabcb9d314dfb400258fb99a37c7b50c9Andy Hung    if (t != 0) {
10343c09c78aabcb9d314dfb400258fb99a37c7b50c9Andy Hung        t->wake();
10353c09c78aabcb9d314dfb400258fb99a37c7b50c9Andy Hung    }
103689fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    return NO_ERROR;
103789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project}
103889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
1039a5224f319e2ba4b51ddb4287705ccf8d4b8ecc51Glenn Kastenstatus_t AudioTrack::getMarkerPosition(uint32_t *marker) const
104089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project{
1041ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent    if (isOffloadedOrDirect()) {
1042b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        return INVALID_OPERATION;
1043b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald    }
1044d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kasten    if (marker == NULL) {
1045d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kasten        return BAD_VALUE;
1046d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kasten    }
104789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
10489f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    AutoMutex lock(mLock);
104990e8a97dd5c9d391d7a2ea6a2290ed976f928379Andy Hung    mMarkerPosition.getValue(marker);
105089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
105189fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    return NO_ERROR;
105289fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project}
105389fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
105489fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectstatus_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
105589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project{
1056fb1fdc9d6603aa228362e7349451f6455c9849c2Glenn Kasten    // The only purpose of setting position update period is to get a callback
1057ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent    if (mCbf == NULL || isOffloadedOrDirect()) {
1058d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kasten        return INVALID_OPERATION;
1059d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kasten    }
106089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
10619f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    AutoMutex lock(mLock);
1062200092b7f21d2b98f30b800e79d152636f9ba225Glenn Kasten    mNewPosition = updateAndGetPosition_l() + updatePeriod;
106389fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    mUpdatePeriod = updatePeriod;
10642b2165c75790050810460c8de3f414876bce4c0eGlenn Kasten
10653c09c78aabcb9d314dfb400258fb99a37c7b50c9Andy Hung    sp<AudioTrackThread> t = mAudioTrackThread;
10663c09c78aabcb9d314dfb400258fb99a37c7b50c9Andy Hung    if (t != 0) {
10673c09c78aabcb9d314dfb400258fb99a37c7b50c9Andy Hung        t->wake();
10683c09c78aabcb9d314dfb400258fb99a37c7b50c9Andy Hung    }
106989fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    return NO_ERROR;
107089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project}
107189fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
1072a5224f319e2ba4b51ddb4287705ccf8d4b8ecc51Glenn Kastenstatus_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod) const
107389fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project{
1074ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent    if (isOffloadedOrDirect()) {
1075b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        return INVALID_OPERATION;
1076b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald    }
1077d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kasten    if (updatePeriod == NULL) {
1078d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kasten        return BAD_VALUE;
1079d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kasten    }
108089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
10819f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    AutoMutex lock(mLock);
108289fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    *updatePeriod = mUpdatePeriod;
108389fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
108489fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    return NO_ERROR;
108589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project}
108689fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
108789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectstatus_t AudioTrack::setPosition(uint32_t position)
108889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project{
1089d79072e9dff59f767cce2cda1caab80ce5a0815bGlenn Kasten    if (mSharedBuffer == 0 || isOffloadedOrDirect()) {
1090d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kasten        return INVALID_OPERATION;
1091d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kasten    }
10929f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    if (position > mFrameCount) {
10939c6745f128648f6e0144b74ee593911a9fa10d51Glenn Kasten        return BAD_VALUE;
10949c6745f128648f6e0144b74ee593911a9fa10d51Glenn Kasten    }
10959c6745f128648f6e0144b74ee593911a9fa10d51Glenn Kasten
10969f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    AutoMutex lock(mLock);
10979f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    // Currently we require that the player is inactive before setting parameters such as position
10989f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    // or loop points.  Otherwise, there could be a race condition: the application could read the
10999f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    // current position, compute a new position or loop parameters, and then set that position or
11009f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    // loop parameters but it would do the "wrong" thing since the position has continued to advance
11019f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    // in the mean time.  If we ever provide a sequencer in server, we could allow a way for the app
11029f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    // to specify how it wants to handle such scenarios.
11039f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    if (mState == STATE_ACTIVE) {
11049f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        return INVALID_OPERATION;
1105d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kasten    }
11069b4615887c23548438fd0d8e3d8f04ac21912850Andy Hung    // After setting the position, use full update period before notification.
1107200092b7f21d2b98f30b800e79d152636f9ba225Glenn Kasten    mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
11089b4615887c23548438fd0d8e3d8f04ac21912850Andy Hung    mStaticProxy->setBufferPosition(position);
11093c09c78aabcb9d314dfb400258fb99a37c7b50c9Andy Hung
11103c09c78aabcb9d314dfb400258fb99a37c7b50c9Andy Hung    // Waking the AudioTrackThread is not needed as this cannot be called when active.
111189fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    return NO_ERROR;
111289fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project}
111389fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
1114200092b7f21d2b98f30b800e79d152636f9ba225Glenn Kastenstatus_t AudioTrack::getPosition(uint32_t *position)
111589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project{
1116d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kasten    if (position == NULL) {
1117d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kasten        return BAD_VALUE;
1118d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kasten    }
11199f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
11201703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent    AutoMutex lock(mLock);
11217a490e7ab39ef0b22baf24b03f2463c46dc068edAndy Hung    // FIXME: offloaded and direct tracks call into the HAL for render positions
11227a490e7ab39ef0b22baf24b03f2463c46dc068edAndy Hung    // for compressed/synced data; however, we use proxy position for pure linear pcm data
11237a490e7ab39ef0b22baf24b03f2463c46dc068edAndy Hung    // as we do not know the capability of the HAL for pcm position support and standby.
11247a490e7ab39ef0b22baf24b03f2463c46dc068edAndy Hung    // There may be some latency differences between the HAL position and the proxy position.
11257a490e7ab39ef0b22baf24b03f2463c46dc068edAndy Hung    if (isOffloadedOrDirect_l() && !isPurePcmData_l()) {
1126b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        uint32_t dspFrames = 0;
112789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
1128ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent        if (isOffloaded_l() && ((mState == STATE_PAUSED) || (mState == STATE_PAUSED_STOPPING))) {
11297064fd2dcdfeafea53cd5a992bb78c413542f29fHaynes Mathew George            ALOGV("getPosition called in paused state, return cached position %u", mPausedPosition);
11307064fd2dcdfeafea53cd5a992bb78c413542f29fHaynes Mathew George            *position = mPausedPosition;
11317064fd2dcdfeafea53cd5a992bb78c413542f29fHaynes Mathew George            return NO_ERROR;
11327064fd2dcdfeafea53cd5a992bb78c413542f29fHaynes Mathew George        }
11337064fd2dcdfeafea53cd5a992bb78c413542f29fHaynes Mathew George
1134142f519aa1acd5804d111e60d100f170fed28405Glenn Kasten        if (mOutput != AUDIO_IO_HANDLE_NONE) {
11351f1db8356b599bc40703c907fb69e6e539343532Andy Hung            uint32_t halFrames; // actually unused
11361f1db8356b599bc40703c907fb69e6e539343532Andy Hung            (void) AudioSystem::getRenderPosition(mOutput, &halFrames, &dspFrames);
11371f1db8356b599bc40703c907fb69e6e539343532Andy Hung            // FIXME: on getRenderPosition() error, we return OK with frame position 0.
1138b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        }
11397f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung        // FIXME: dspFrames may not be zero in (mState == STATE_STOPPED || mState == STATE_FLUSHED)
11407f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung        // due to hardware latency. We leave this behavior for now.
1141b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        *position = dspFrames;
1142b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald    } else {
1143275e8e9de2e11b4b344f5a201f1f0e51fda02d9cEric Laurent        if (mCblk->mFlags & CBLK_INVALID) {
11441f1db8356b599bc40703c907fb69e6e539343532Andy Hung            (void) restoreTrack_l("getPosition");
11451f1db8356b599bc40703c907fb69e6e539343532Andy Hung            // FIXME: for compatibility with the Java API we ignore the restoreTrack_l()
11461f1db8356b599bc40703c907fb69e6e539343532Andy Hung            // error here (e.g. DEAD_OBJECT) and return OK with the last recorded server position.
1147275e8e9de2e11b4b344f5a201f1f0e51fda02d9cEric Laurent        }
1148275e8e9de2e11b4b344f5a201f1f0e51fda02d9cEric Laurent
1149b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        // IAudioTrack::stop() isn't synchronous; we don't know when presentation completes
1150200092b7f21d2b98f30b800e79d152636f9ba225Glenn Kasten        *position = (mState == STATE_STOPPED || mState == STATE_FLUSHED) ?
115190e8a97dd5c9d391d7a2ea6a2290ed976f928379Andy Hung                0 : updateAndGetPosition_l().value();
1152b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald    }
115389fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    return NO_ERROR;
115489fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project}
115589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
1156377b2ec9a2885f9b6405b07ba900a9e3f4349c38Kévin PETITstatus_t AudioTrack::getBufferPosition(uint32_t *position)
11579c6745f128648f6e0144b74ee593911a9fa10d51Glenn Kasten{
1158d79072e9dff59f767cce2cda1caab80ce5a0815bGlenn Kasten    if (mSharedBuffer == 0) {
11599c6745f128648f6e0144b74ee593911a9fa10d51Glenn Kasten        return INVALID_OPERATION;
11609c6745f128648f6e0144b74ee593911a9fa10d51Glenn Kasten    }
11619c6745f128648f6e0144b74ee593911a9fa10d51Glenn Kasten    if (position == NULL) {
11629c6745f128648f6e0144b74ee593911a9fa10d51Glenn Kasten        return BAD_VALUE;
11639c6745f128648f6e0144b74ee593911a9fa10d51Glenn Kasten    }
11649c6745f128648f6e0144b74ee593911a9fa10d51Glenn Kasten
11659f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    AutoMutex lock(mLock);
11669f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    *position = mStaticProxy->getBufferPosition();
11679c6745f128648f6e0144b74ee593911a9fa10d51Glenn Kasten    return NO_ERROR;
11689c6745f128648f6e0144b74ee593911a9fa10d51Glenn Kasten}
11699c6745f128648f6e0144b74ee593911a9fa10d51Glenn Kasten
117089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectstatus_t AudioTrack::reload()
117189fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project{
1172d79072e9dff59f767cce2cda1caab80ce5a0815bGlenn Kasten    if (mSharedBuffer == 0 || isOffloadedOrDirect()) {
1173083d1c1492d496960d5b28f4664ff02101736677Glenn Kasten        return INVALID_OPERATION;
1174083d1c1492d496960d5b28f4664ff02101736677Glenn Kasten    }
1175083d1c1492d496960d5b28f4664ff02101736677Glenn Kasten
11761703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent    AutoMutex lock(mLock);
11779f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    // See setPosition() regarding setting parameters such as loop points or position while active
11789f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    if (mState == STATE_ACTIVE) {
1179d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kasten        return INVALID_OPERATION;
1180d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kasten    }
11819f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    mNewPosition = mUpdatePeriod;
11829b4615887c23548438fd0d8e3d8f04ac21912850Andy Hung    (void) updateAndGetPosition_l();
11839b4615887c23548438fd0d8e3d8f04ac21912850Andy Hung    mPosition = 0;
11841b42097f38e72574ed853a35f4e8a66e4739c421Phil Burk    mPreviousTimestampValid = false;
118553c3b5fc1afe162a8669cb3d27d6bb14e1847e39Andy Hung#if 0
11869b4615887c23548438fd0d8e3d8f04ac21912850Andy Hung    // The documentation is not clear on the behavior of reload() and the restoration
118753c3b5fc1afe162a8669cb3d27d6bb14e1847e39Andy Hung    // of loop count. Historically we have not restored loop count, start, end,
118853c3b5fc1afe162a8669cb3d27d6bb14e1847e39Andy Hung    // but it makes sense if one desires to repeat playing a particular sound.
118953c3b5fc1afe162a8669cb3d27d6bb14e1847e39Andy Hung    if (mLoopCount != 0) {
119053c3b5fc1afe162a8669cb3d27d6bb14e1847e39Andy Hung        mLoopCountNotified = mLoopCount;
119153c3b5fc1afe162a8669cb3d27d6bb14e1847e39Andy Hung        mStaticProxy->setLoop(mLoopStart, mLoopEnd, mLoopCount);
119253c3b5fc1afe162a8669cb3d27d6bb14e1847e39Andy Hung    }
119353c3b5fc1afe162a8669cb3d27d6bb14e1847e39Andy Hung#endif
11949b4615887c23548438fd0d8e3d8f04ac21912850Andy Hung    mStaticProxy->setBufferPosition(0);
119589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    return NO_ERROR;
119689fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project}
119789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
119838e905b3cbba4da443d799b16999989781afc6d8Glenn Kastenaudio_io_handle_t AudioTrack::getOutput() const
1199c2f1f07084818942352c6bbfb36af9b6b330eb4eEric Laurent{
12001703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent    AutoMutex lock(mLock);
1201b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald    return mOutput;
12021703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent}
12031703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent
1204aa9811945f575614b3482d09e4d969792701cebbPaul McLeanstatus_t AudioTrack::setOutputDevice(audio_port_handle_t deviceId) {
1205aa9811945f575614b3482d09e4d969792701cebbPaul McLean    AutoMutex lock(mLock);
1206aa9811945f575614b3482d09e4d969792701cebbPaul McLean    if (mSelectedDeviceId != deviceId) {
1207aa9811945f575614b3482d09e4d969792701cebbPaul McLean        mSelectedDeviceId = deviceId;
1208493404d8c396e15ed73455acd39aa0f1940996e2Eric Laurent        android_atomic_or(CBLK_INVALID, &mCblk->mFlags);
1209aa9811945f575614b3482d09e4d969792701cebbPaul McLean    }
1210493404d8c396e15ed73455acd39aa0f1940996e2Eric Laurent    return NO_ERROR;
1211aa9811945f575614b3482d09e4d969792701cebbPaul McLean}
1212aa9811945f575614b3482d09e4d969792701cebbPaul McLean
1213aa9811945f575614b3482d09e4d969792701cebbPaul McLeanaudio_port_handle_t AudioTrack::getOutputDevice() {
1214aa9811945f575614b3482d09e4d969792701cebbPaul McLean    AutoMutex lock(mLock);
1215aa9811945f575614b3482d09e4d969792701cebbPaul McLean    return mSelectedDeviceId;
1216aa9811945f575614b3482d09e4d969792701cebbPaul McLean}
1217aa9811945f575614b3482d09e4d969792701cebbPaul McLean
1218296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurentaudio_port_handle_t AudioTrack::getRoutedDeviceId() {
1219296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent    AutoMutex lock(mLock);
1220296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent    if (mOutput == AUDIO_IO_HANDLE_NONE) {
1221296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent        return AUDIO_PORT_HANDLE_NONE;
1222296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent    }
1223296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent    return AudioSystem::getDeviceIdForIo(mOutput);
1224296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent}
1225296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent
1226be916aa1267e2e6b1c148f51d11bcbbc79cb864cEric Laurentstatus_t AudioTrack::attachAuxEffect(int effectId)
1227be916aa1267e2e6b1c148f51d11bcbbc79cb864cEric Laurent{
12289f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    AutoMutex lock(mLock);
12292beeb50b1bba9e92f6cacfeca37fe9fa9d36ead1Eric Laurent    status_t status = mAudioTrack->attachAuxEffect(effectId);
12302beeb50b1bba9e92f6cacfeca37fe9fa9d36ead1Eric Laurent    if (status == NO_ERROR) {
12312beeb50b1bba9e92f6cacfeca37fe9fa9d36ead1Eric Laurent        mAuxEffectId = effectId;
12322beeb50b1bba9e92f6cacfeca37fe9fa9d36ead1Eric Laurent    }
12332beeb50b1bba9e92f6cacfeca37fe9fa9d36ead1Eric Laurent    return status;
1234be916aa1267e2e6b1c148f51d11bcbbc79cb864cEric Laurent}
1235be916aa1267e2e6b1c148f51d11bcbbc79cb864cEric Laurent
1236e83b55dc29ca16092ba02f36f55fa6e0e37fd78cEric Laurentaudio_stream_type_t AudioTrack::streamType() const
1237e83b55dc29ca16092ba02f36f55fa6e0e37fd78cEric Laurent{
1238e83b55dc29ca16092ba02f36f55fa6e0e37fd78cEric Laurent    if (mStreamType == AUDIO_STREAM_DEFAULT) {
1239e83b55dc29ca16092ba02f36f55fa6e0e37fd78cEric Laurent        return audio_attributes_to_stream_type(&mAttributes);
1240e83b55dc29ca16092ba02f36f55fa6e0e37fd78cEric Laurent    }
1241e83b55dc29ca16092ba02f36f55fa6e0e37fd78cEric Laurent    return mStreamType;
1242e83b55dc29ca16092ba02f36f55fa6e0e37fd78cEric Laurent}
1243e83b55dc29ca16092ba02f36f55fa6e0e37fd78cEric Laurent
124489fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project// -------------------------------------------------------------------------
124589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
12461703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent// must be called with mLock held
1247200092b7f21d2b98f30b800e79d152636f9ba225Glenn Kastenstatus_t AudioTrack::createTrack_l()
124834f1d8ecd23169a5f299937e3aaf1bd7937578a0Eric Laurent{
124934f1d8ecd23169a5f299937e3aaf1bd7937578a0Eric Laurent    const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
125034f1d8ecd23169a5f299937e3aaf1bd7937578a0Eric Laurent    if (audioFlinger == 0) {
1251e53b9ead781c36e96d6b6f012ddffc93a3d80f0dGlenn Kasten        ALOGE("Could not get audioflinger");
1252e53b9ead781c36e96d6b6f012ddffc93a3d80f0dGlenn Kasten        return NO_INIT;
125334f1d8ecd23169a5f299937e3aaf1bd7937578a0Eric Laurent    }
125434f1d8ecd23169a5f299937e3aaf1bd7937578a0Eric Laurent
1255296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent    if (mDeviceCallback != 0 && mOutput != AUDIO_IO_HANDLE_NONE) {
1256296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent        AudioSystem::removeAudioDeviceCallback(mDeviceCallback, mOutput);
1257296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent    }
1258e83b55dc29ca16092ba02f36f55fa6e0e37fd78cEric Laurent    audio_io_handle_t output;
1259e83b55dc29ca16092ba02f36f55fa6e0e37fd78cEric Laurent    audio_stream_type_t streamType = mStreamType;
1260e83b55dc29ca16092ba02f36f55fa6e0e37fd78cEric Laurent    audio_attributes_t *attr = (mStreamType == AUDIO_STREAM_DEFAULT) ? &mAttributes : NULL;
1261e83b55dc29ca16092ba02f36f55fa6e0e37fd78cEric Laurent
1262ae34ed2bcc9fa49a22fe7497327adb689ef27e8dHaynes Mathew George    // mFlags (not mOrigFlags) is modified depending on whether fast request is accepted.
1263ae34ed2bcc9fa49a22fe7497327adb689ef27e8dHaynes Mathew George    // After fast request is denied, we will request again if IAudioTrack is re-created.
1264ae34ed2bcc9fa49a22fe7497327adb689ef27e8dHaynes Mathew George
1265aa9811945f575614b3482d09e4d969792701cebbPaul McLean    status_t status;
126620b9ef0b55c9150ae11057ab997ae61be2d496efEric Laurent    audio_config_t config = AUDIO_CONFIG_INITIALIZER;
126720b9ef0b55c9150ae11057ab997ae61be2d496efEric Laurent    config.sample_rate = mSampleRate;
126820b9ef0b55c9150ae11057ab997ae61be2d496efEric Laurent    config.channel_mask = mChannelMask;
126920b9ef0b55c9150ae11057ab997ae61be2d496efEric Laurent    config.format = mFormat;
127020b9ef0b55c9150ae11057ab997ae61be2d496efEric Laurent    config.offload_info = mOffloadInfoCopy;
1271aa9811945f575614b3482d09e4d969792701cebbPaul McLean    status = AudioSystem::getOutputForAttr(attr, &output,
1272d848eb48c121c119e8ba7583efc75415fe102570Glenn Kasten                                           mSessionId, &streamType, mClientUid,
127320b9ef0b55c9150ae11057ab997ae61be2d496efEric Laurent                                           &config,
127420b9ef0b55c9150ae11057ab997ae61be2d496efEric Laurent                                           mFlags, mSelectedDeviceId, &mPortId);
1275e83b55dc29ca16092ba02f36f55fa6e0e37fd78cEric Laurent
1276e83b55dc29ca16092ba02f36f55fa6e0e37fd78cEric Laurent    if (status != NO_ERROR || output == AUDIO_IO_HANDLE_NONE) {
12774c36d6f48f4eecacc148317f775f65961a4f03d2Glenn Kasten        ALOGE("Could not get audio output for session %d, stream type %d, usage %d, sample rate %u, format %#x,"
12785bd3f38638acab633d181359cc9ec27b80f84d43Jean-Michel Trivi              " channel mask %#x, flags %#x",
12794c36d6f48f4eecacc148317f775f65961a4f03d2Glenn Kasten              mSessionId, streamType, mAttributes.usage, mSampleRate, mFormat, mChannelMask, mFlags);
128038e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten        return BAD_VALUE;
128138e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten    }
128238e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten    {
128338e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten    // Now that we have a reference to an I/O handle and have not yet handed it off to AudioFlinger,
128438e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten    // we must release it ourselves if anything goes wrong.
128538e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten
1286ce8828a016b082f730152af2204b8ea3610dc1ecGlenn Kasten    // Not all of these values are needed under all conditions, but it is easier to get them all
12879f9e21ed9a342e0ca945818bdc6c0c4fb3bfb9bdAndy Hung    status = AudioSystem::getLatency(output, &mAfLatency);
1288ce8828a016b082f730152af2204b8ea3610dc1ecGlenn Kasten    if (status != NO_ERROR) {
12899f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        ALOGE("getLatency(%d) failed status %d", output, status);
129038e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten        goto release;
1291d1b449aad6c087a69f5ec66b7facb2845b73f1cbEric Laurent    }
12929f9e21ed9a342e0ca945818bdc6c0c4fb3bfb9bdAndy Hung    ALOGV("createTrack_l() output %d afLatency %u", output, mAfLatency);
1293d1b449aad6c087a69f5ec66b7facb2845b73f1cbEric Laurent
12949f9e21ed9a342e0ca945818bdc6c0c4fb3bfb9bdAndy Hung    status = AudioSystem::getFrameCount(output, &mAfFrameCount);
1295ce8828a016b082f730152af2204b8ea3610dc1ecGlenn Kasten    if (status != NO_ERROR) {
1296b7f24b101d43139b4c747129bfbc4ecf5c468b86Jean-Michel Trivi        ALOGE("getFrameCount(output=%d) status %d", output, status);
129738e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten        goto release;
1298ce8828a016b082f730152af2204b8ea3610dc1ecGlenn Kasten    }
1299ce8828a016b082f730152af2204b8ea3610dc1ecGlenn Kasten
1300ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten    // TODO consider making this a member variable if there are other uses for it later
1301ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten    size_t afFrameCountHAL;
1302ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten    status = AudioSystem::getFrameCountHAL(output, &afFrameCountHAL);
1303ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten    if (status != NO_ERROR) {
1304ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten        ALOGE("getFrameCountHAL(output=%d) status %d", output, status);
1305ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten        goto release;
1306ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten    }
1307ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten    ALOG_ASSERT(afFrameCountHAL > 0);
1308ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten
13099f9e21ed9a342e0ca945818bdc6c0c4fb3bfb9bdAndy Hung    status = AudioSystem::getSamplingRate(output, &mAfSampleRate);
1310ce8828a016b082f730152af2204b8ea3610dc1ecGlenn Kasten    if (status != NO_ERROR) {
1311b7f24b101d43139b4c747129bfbc4ecf5c468b86Jean-Michel Trivi        ALOGE("getSamplingRate(output=%d) status %d", output, status);
131238e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten        goto release;
1313ce8828a016b082f730152af2204b8ea3610dc1ecGlenn Kasten    }
13140d6db582f2ccc9f8943c5f3965e2994b7d137158Eric Laurent    if (mSampleRate == 0) {
13159f9e21ed9a342e0ca945818bdc6c0c4fb3bfb9bdAndy Hung        mSampleRate = mAfSampleRate;
13169f9e21ed9a342e0ca945818bdc6c0c4fb3bfb9bdAndy Hung        mOriginalSampleRate = mAfSampleRate;
13170d6db582f2ccc9f8943c5f3965e2994b7d137158Eric Laurent    }
13187fd0422fbd17af3b24eb04421d37fce50f3826e2Glenn Kasten
1319d79072e9dff59f767cce2cda1caab80ce5a0815bGlenn Kasten    // Client can only express a preference for FAST.  Server will perform additional tests.
132033ff89ba94a527e4293ee5349da01483252d5c83Phil Burk    if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
132133ff89ba94a527e4293ee5349da01483252d5c83Phil Burk        bool useCaseAllowed =
13224a4a0959bca78e03e3c3f486ba17829c28314d8cGlenn Kasten            // either of these use cases:
13234a4a0959bca78e03e3c3f486ba17829c28314d8cGlenn Kasten            // use case 1: shared buffer
1324363fb75db26698cbb50065506e0c80b61d1fbf92Glenn Kasten            (mSharedBuffer != 0) ||
1325c6ba823a397abf865b02f4f48fe18231f94d8e87Glenn Kasten            // use case 2: callback transfer mode
13261dfe2f9c2d03fc8d0ed0cdfe0b9fb894bc0bcc11Glenn Kasten            (mTransfer == TRANSFER_CALLBACK) ||
13271dfe2f9c2d03fc8d0ed0cdfe0b9fb894bc0bcc11Glenn Kasten            // use case 3: obtain/release mode
132833ff89ba94a527e4293ee5349da01483252d5c83Phil Burk            (mTransfer == TRANSFER_OBTAIN) ||
132933ff89ba94a527e4293ee5349da01483252d5c83Phil Burk            // use case 4: synchronous write
133033ff89ba94a527e4293ee5349da01483252d5c83Phil Burk            ((mTransfer == TRANSFER_SYNC) && mThreadCanCallJava);
133133ff89ba94a527e4293ee5349da01483252d5c83Phil Burk        // sample rates must also match
133233ff89ba94a527e4293ee5349da01483252d5c83Phil Burk        bool fastAllowed = useCaseAllowed && (mSampleRate == mAfSampleRate);
133333ff89ba94a527e4293ee5349da01483252d5c83Phil Burk        if (!fastAllowed) {
13347fd0422fbd17af3b24eb04421d37fce50f3826e2Glenn Kasten            ALOGW("AUDIO_OUTPUT_FLAG_FAST denied by client; transfer %d, "
133533ff89ba94a527e4293ee5349da01483252d5c83Phil Burk                "track %u Hz, output %u Hz",
13369f9e21ed9a342e0ca945818bdc6c0c4fb3bfb9bdAndy Hung                mTransfer, mSampleRate, mAfSampleRate);
133733ff89ba94a527e4293ee5349da01483252d5c83Phil Burk            mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
133833ff89ba94a527e4293ee5349da01483252d5c83Phil Burk        }
13394a4a0959bca78e03e3c3f486ba17829c28314d8cGlenn Kasten    }
13404a4a0959bca78e03e3c3f486ba17829c28314d8cGlenn Kasten
1341d1b449aad6c087a69f5ec66b7facb2845b73f1cbEric Laurent    mNotificationFramesAct = mNotificationFramesReq;
1342e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten
1343363fb75db26698cbb50065506e0c80b61d1fbf92Glenn Kasten    size_t frameCount = mReqFrameCount;
1344fdb3c07db5d44535eb8c3ec46dc78ad8446c01ebPhil Burk    if (!audio_has_proportional_frames(mFormat)) {
1345e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten
1346363fb75db26698cbb50065506e0c80b61d1fbf92Glenn Kasten        if (mSharedBuffer != 0) {
1347e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten            // Same comment as below about ignoring frameCount parameter for set()
1348363fb75db26698cbb50065506e0c80b61d1fbf92Glenn Kasten            frameCount = mSharedBuffer->size();
1349e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten        } else if (frameCount == 0) {
13509f9e21ed9a342e0ca945818bdc6c0c4fb3bfb9bdAndy Hung            frameCount = mAfFrameCount;
1351d1b449aad6c087a69f5ec66b7facb2845b73f1cbEric Laurent        }
1352b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        if (mNotificationFramesAct != frameCount) {
1353b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald            mNotificationFramesAct = frameCount;
1354b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        }
1355363fb75db26698cbb50065506e0c80b61d1fbf92Glenn Kasten    } else if (mSharedBuffer != 0) {
1356abdb990953ffe94a9dc544aea0bed17ef7d5f484Andy Hung        // FIXME: Ensure client side memory buffers need
1357abdb990953ffe94a9dc544aea0bed17ef7d5f484Andy Hung        // not have additional alignment beyond sample
1358abdb990953ffe94a9dc544aea0bed17ef7d5f484Andy Hung        // (e.g. 16 bit stereo accessed as 32 bit frame).
1359abdb990953ffe94a9dc544aea0bed17ef7d5f484Andy Hung        size_t alignment = audio_bytes_per_sample(mFormat);
1360b773038277ba328696832b690b91ce6e95bd1a6cGlenn Kasten        if (alignment & 1) {
1361abdb990953ffe94a9dc544aea0bed17ef7d5f484Andy Hung            // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
1362b773038277ba328696832b690b91ce6e95bd1a6cGlenn Kasten            alignment = 1;
1363b773038277ba328696832b690b91ce6e95bd1a6cGlenn Kasten        }
1364a42ff007a17d63df22c60dd5e5fd811ee45ca1b3Glenn Kasten        if (mChannelCount > 1) {
1365e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten            // More than 2 channels does not require stronger alignment than stereo
1366e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten            alignment <<= 1;
1367e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten        }
13681d6fa7af1288b550faabe4ec2cf98684236723dbNarayan Kamath        if (((uintptr_t)mSharedBuffer->pointer() & (alignment - 1)) != 0) {
1369a42ff007a17d63df22c60dd5e5fd811ee45ca1b3Glenn Kasten            ALOGE("Invalid buffer alignment: address %p, channel count %u",
1370363fb75db26698cbb50065506e0c80b61d1fbf92Glenn Kasten                    mSharedBuffer->pointer(), mChannelCount);
137138e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten            status = BAD_VALUE;
137238e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten            goto release;
1373e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten        }
1374e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten
1375e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten        // When initializing a shared buffer AudioTrack via constructors,
1376e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten        // there's no frameCount parameter.
1377e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten        // But when initializing a shared buffer AudioTrack via set(),
1378e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten        // there _is_ a frameCount parameter.  We silently ignore it.
1379abdb990953ffe94a9dc544aea0bed17ef7d5f484Andy Hung        frameCount = mSharedBuffer->size() / mFrameSize;
1380e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten    } else {
1381ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten        size_t minFrameCount = 0;
1382ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten        // For fast tracks the frame count calculations and checks are mostly done by server,
1383ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten        // but we try to respect the application's request for notifications per buffer.
1384ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten        if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
1385ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten            if (mNotificationsPerBufferReq > 0) {
1386ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten                // Avoid possible arithmetic overflow during multiplication.
1387ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten                // mNotificationsPerBuffer is clamped to a small integer earlier, so it is unlikely.
1388ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten                if (mNotificationsPerBufferReq > SIZE_MAX / afFrameCountHAL) {
1389ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten                    ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
1390ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten                            mNotificationsPerBufferReq, afFrameCountHAL);
1391ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten                } else {
1392ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten                    minFrameCount = afFrameCountHAL * mNotificationsPerBufferReq;
1393ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten                }
1394ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten            }
1395ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten        } else {
13968edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung            // for normal tracks precompute the frame count based on speed.
1397ff874dc957f9ea70d87f4d627bf903e1fc86d58bAndy Hung            const float speed = !isPurePcmData_l() || isOffloadedOrDirect_l() ? 1.0f :
1398ff874dc957f9ea70d87f4d627bf903e1fc86d58bAndy Hung                            max(mMaxRequiredSpeed, mPlaybackRate.mSpeed);
1399ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten            minFrameCount = calculateMinFrameCount(
14009f9e21ed9a342e0ca945818bdc6c0c4fb3bfb9bdAndy Hung                    mAfLatency, mAfFrameCount, mAfSampleRate, mSampleRate,
1401ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten                    speed /*, 0 mNotificationsPerBufferReq*/);
1402ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten        }
1403ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten        if (frameCount < minFrameCount) {
1404ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten            frameCount = minFrameCount;
14058edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung        }
1406d1b449aad6c087a69f5ec66b7facb2845b73f1cbEric Laurent    }
1407d1b449aad6c087a69f5ec66b7facb2845b73f1cbEric Laurent
1408050677873c10d4da308ac222f8533c96cca3207eEric Laurent    audio_output_flags_t flags = mFlags;
14093acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten
14103acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten    pid_t tid = -1;
1411363fb75db26698cbb50065506e0c80b61d1fbf92Glenn Kasten    if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
141233ff89ba94a527e4293ee5349da01483252d5c83Phil Burk        if (mAudioTrackThread != 0 && !mThreadCanCallJava) {
14133acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten            tid = mAudioTrackThread->getTid();
14143acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten        }
14154a4a0959bca78e03e3c3f486ba17829c28314d8cGlenn Kasten    }
14164a4a0959bca78e03e3c3f486ba17829c28314d8cGlenn Kasten
141774935e44734c1ec235c2b6677db3e0dbefa5ddb8Glenn Kasten    size_t temp = frameCount;   // temp may be replaced by a revised value of frameCount,
141874935e44734c1ec235c2b6677db3e0dbefa5ddb8Glenn Kasten                                // but we will still need the original value also
1419d848eb48c121c119e8ba7583efc75415fe102570Glenn Kasten    audio_session_t originalSessionId = mSessionId;
1420e83b55dc29ca16092ba02f36f55fa6e0e37fd78cEric Laurent    sp<IAudioTrack> track = audioFlinger->createTrack(streamType,
1421363fb75db26698cbb50065506e0c80b61d1fbf92Glenn Kasten                                                      mSampleRate,
1422abdb990953ffe94a9dc544aea0bed17ef7d5f484Andy Hung                                                      mFormat,
1423a42ff007a17d63df22c60dd5e5fd811ee45ca1b3Glenn Kasten                                                      mChannelMask,
142474935e44734c1ec235c2b6677db3e0dbefa5ddb8Glenn Kasten                                                      &temp,
1425050677873c10d4da308ac222f8533c96cca3207eEric Laurent                                                      &flags,
1426363fb75db26698cbb50065506e0c80b61d1fbf92Glenn Kasten                                                      mSharedBuffer,
142734f1d8ecd23169a5f299937e3aaf1bd7937578a0Eric Laurent                                                      output,
14289ea77cdba8c422940adb57a790b44ac04fe0353fHaynes Mathew George                                                      mClientPid,
14293acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten                                                      tid,
1430be916aa1267e2e6b1c148f51d11bcbbc79cb864cEric Laurent                                                      &mSessionId,
1431462fd2fa9eef642b0574aa7409de0bde3fec8d43Marco Nelissen                                                      mClientUid,
143220b9ef0b55c9150ae11057ab997ae61be2d496efEric Laurent                                                      &status,
143320b9ef0b55c9150ae11057ab997ae61be2d496efEric Laurent                                                      mPortId);
1434138d6f9b0b77d94773a8a29d3c5bdb78f38ee142Glenn Kasten    ALOGE_IF(originalSessionId != AUDIO_SESSION_ALLOCATE && mSessionId != originalSessionId,
1435138d6f9b0b77d94773a8a29d3c5bdb78f38ee142Glenn Kasten            "session ID changed from %d to %d", originalSessionId, mSessionId);
143634f1d8ecd23169a5f299937e3aaf1bd7937578a0Eric Laurent
1437c08d20b6a37122ebf116262c9372509ed060d4c1Glenn Kasten    if (status != NO_ERROR) {
143829357bc2c0dd7c43ad3bd0c8e3efa4e6fd9bfd47Steve Block        ALOGE("AudioFlinger could not create track, status: %d", status);
143938e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten        goto release;
144034f1d8ecd23169a5f299937e3aaf1bd7937578a0Eric Laurent    }
1441c08d20b6a37122ebf116262c9372509ed060d4c1Glenn Kasten    ALOG_ASSERT(track != 0);
1442c08d20b6a37122ebf116262c9372509ed060d4c1Glenn Kasten
144338e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten    // AudioFlinger now owns the reference to the I/O handle,
144438e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten    // so we are no longer responsible for releasing it.
144538e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten
14467fd0422fbd17af3b24eb04421d37fce50f3826e2Glenn Kasten    // FIXME compare to AudioRecord
1447d2c38fc4d5dc742d7441444316849510dd2b7363Glenn Kasten    sp<IMemory> iMem = track->getCblk();
1448d2c38fc4d5dc742d7441444316849510dd2b7363Glenn Kasten    if (iMem == 0) {
144929357bc2c0dd7c43ad3bd0c8e3efa4e6fd9bfd47Steve Block        ALOGE("Could not get control block");
145034f1d8ecd23169a5f299937e3aaf1bd7937578a0Eric Laurent        return NO_INIT;
145134f1d8ecd23169a5f299937e3aaf1bd7937578a0Eric Laurent    }
14520cde076ddb283c84c3801a2df4cc3df99bd1577fGlenn Kasten    void *iMemPointer = iMem->pointer();
14530cde076ddb283c84c3801a2df4cc3df99bd1577fGlenn Kasten    if (iMemPointer == NULL) {
14540cde076ddb283c84c3801a2df4cc3df99bd1577fGlenn Kasten        ALOGE("Could not get control block pointer");
14550cde076ddb283c84c3801a2df4cc3df99bd1577fGlenn Kasten        return NO_INIT;
14560cde076ddb283c84c3801a2df4cc3df99bd1577fGlenn Kasten    }
145753cec22821072719ee02c856e9ac2dda2496c570Glenn Kasten    // invariant that mAudioTrack != 0 is true only after set() returns successfully
14589f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    if (mAudioTrack != 0) {
1459f888020c6e2735624f2b2a30e72aca24e17b8b4dMarco Nelissen        IInterface::asBinder(mAudioTrack)->unlinkToDeath(mDeathNotifier, this);
14609f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        mDeathNotifier.clear();
14619f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    }
146234f1d8ecd23169a5f299937e3aaf1bd7937578a0Eric Laurent    mAudioTrack = track;
1463d2c38fc4d5dc742d7441444316849510dd2b7363Glenn Kasten    mCblkMemory = iMem;
14643bcffa136909c1fb6e88ee4efd12ccac18360a85Eric Laurent    IPCThreadState::self()->flushCommands();
14653bcffa136909c1fb6e88ee4efd12ccac18360a85Eric Laurent
14660cde076ddb283c84c3801a2df4cc3df99bd1577fGlenn Kasten    audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMemPointer);
1467d2c38fc4d5dc742d7441444316849510dd2b7363Glenn Kasten    mCblk = cblk;
146874935e44734c1ec235c2b6677db3e0dbefa5ddb8Glenn Kasten    // note that temp is the (possibly revised) value of frameCount
1469b603744e96b07b1d5bf745bde593fb2c025cefcfGlenn Kasten    if (temp < frameCount || (frameCount == 0 && temp == 0)) {
1470b603744e96b07b1d5bf745bde593fb2c025cefcfGlenn Kasten        // In current design, AudioTrack client checks and ensures frame count validity before
1471b603744e96b07b1d5bf745bde593fb2c025cefcfGlenn Kasten        // passing it to AudioFlinger so AudioFlinger should not return a different value except
1472b603744e96b07b1d5bf745bde593fb2c025cefcfGlenn Kasten        // for fast track as it uses a special method of assigning frame count.
147334fb29696b0f3abf61b10f8d053b1f33d501de0aMark Salyzyn        ALOGW("Requested frameCount %zu but received frameCount %zu", frameCount, temp);
1474b603744e96b07b1d5bf745bde593fb2c025cefcfGlenn Kasten    }
1475b603744e96b07b1d5bf745bde593fb2c025cefcfGlenn Kasten    frameCount = temp;
14765f631515d098c29603cda88f7a7e7580a2d55b57Glenn Kasten
1477a07f17ca46db04c9d5d9e7d6b2878db59ca2b9eaGlenn Kasten    mAwaitBoost = false;
1478363fb75db26698cbb50065506e0c80b61d1fbf92Glenn Kasten    if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
1479050677873c10d4da308ac222f8533c96cca3207eEric Laurent        if (flags & AUDIO_OUTPUT_FLAG_FAST) {
148034fb29696b0f3abf61b10f8d053b1f33d501de0aMark Salyzyn            ALOGV("AUDIO_OUTPUT_FLAG_FAST successful; frameCount %zu", frameCount);
148133ff89ba94a527e4293ee5349da01483252d5c83Phil Burk            if (!mThreadCanCallJava) {
148233ff89ba94a527e4293ee5349da01483252d5c83Phil Burk                mAwaitBoost = true;
148333ff89ba94a527e4293ee5349da01483252d5c83Phil Burk            }
14843acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten        } else {
1485ae34ed2bcc9fa49a22fe7497327adb689ef27e8dHaynes Mathew George            ALOGW("AUDIO_OUTPUT_FLAG_FAST denied by server; frameCount %zu", frameCount);
1486e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten        }
14873acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten    }
1488050677873c10d4da308ac222f8533c96cca3207eEric Laurent    mFlags = flags;
14897fd0422fbd17af3b24eb04421d37fce50f3826e2Glenn Kasten
14907fd0422fbd17af3b24eb04421d37fce50f3826e2Glenn Kasten    // Make sure that application is notified with sufficient margin before underrun.
1491ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten    // The client can divide the AudioTrack buffer into sub-buffers,
1492ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten    // and expresses its desire to server as the notification frame count.
14930e48d25606c82def035ad10a5b3923767a765cddAndy Hung    if (mSharedBuffer == 0 && audio_is_linear_pcm(mFormat)) {
1494ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten        size_t maxNotificationFrames;
1495050677873c10d4da308ac222f8533c96cca3207eEric Laurent        if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
1496ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten            // notify every HAL buffer, regardless of the size of the track buffer
1497ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten            maxNotificationFrames = afFrameCountHAL;
1498ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten        } else {
1499aebe9dc29988c94a774208ba659c4f156d274d79Glenn Kasten            // For normal tracks, use at least double-buffering if no sample rate conversion,
1500aebe9dc29988c94a774208ba659c4f156d274d79Glenn Kasten            // or at least triple-buffering if there is sample rate conversion
1501aebe9dc29988c94a774208ba659c4f156d274d79Glenn Kasten            const int nBuffering = mOriginalSampleRate == mAfSampleRate ? 2 : 3;
1502ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten            maxNotificationFrames = frameCount / nBuffering;
15037fd0422fbd17af3b24eb04421d37fce50f3826e2Glenn Kasten        }
15047fd0422fbd17af3b24eb04421d37fce50f3826e2Glenn Kasten        if (mNotificationFramesAct == 0 || mNotificationFramesAct > maxNotificationFrames) {
1505ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten            if (mNotificationFramesAct == 0) {
1506ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten                ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
1507ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten                    maxNotificationFrames, frameCount);
1508ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten            } else {
1509ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten                ALOGW("Client adjusted notificationFrames from %u to %zu for frameCount %zu",
15107fd0422fbd17af3b24eb04421d37fce50f3826e2Glenn Kasten                    mNotificationFramesAct, maxNotificationFrames, frameCount);
1511ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten            }
15127fd0422fbd17af3b24eb04421d37fce50f3826e2Glenn Kasten            mNotificationFramesAct = (uint32_t) maxNotificationFrames;
15130e48d25606c82def035ad10a5b3923767a765cddAndy Hung        }
15140e48d25606c82def035ad10a5b3923767a765cddAndy Hung    }
1515b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald
151638e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten    // We retain a copy of the I/O handle, but don't own the reference
151738e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten    mOutput = output;
15189f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    mRefreshRemaining = true;
15199f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
15209f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    // Starting address of buffers in shared memory.  If there is a shared buffer, buffers
15219f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    // is the value of pointer() for the shared buffer, otherwise buffers points
15229f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    // immediately after the control block.  This address is for the mapping within client
15239f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    // address space.  AudioFlinger::TrackBase::mBuffer is for the server address space.
15249f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    void* buffers;
1525363fb75db26698cbb50065506e0c80b61d1fbf92Glenn Kasten    if (mSharedBuffer == 0) {
1526138d6f9b0b77d94773a8a29d3c5bdb78f38ee142Glenn Kasten        buffers = cblk + 1;
152734f1d8ecd23169a5f299937e3aaf1bd7937578a0Eric Laurent    } else {
1528363fb75db26698cbb50065506e0c80b61d1fbf92Glenn Kasten        buffers = mSharedBuffer->pointer();
1529138d6f9b0b77d94773a8a29d3c5bdb78f38ee142Glenn Kasten        if (buffers == NULL) {
1530138d6f9b0b77d94773a8a29d3c5bdb78f38ee142Glenn Kasten            ALOGE("Could not get buffer pointer");
1531138d6f9b0b77d94773a8a29d3c5bdb78f38ee142Glenn Kasten            return NO_INIT;
1532138d6f9b0b77d94773a8a29d3c5bdb78f38ee142Glenn Kasten        }
153334f1d8ecd23169a5f299937e3aaf1bd7937578a0Eric Laurent    }
153434f1d8ecd23169a5f299937e3aaf1bd7937578a0Eric Laurent
15352beeb50b1bba9e92f6cacfeca37fe9fa9d36ead1Eric Laurent    mAudioTrack->attachAuxEffect(mAuxEffectId);
15368edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung    // FIXME doesn't take into account speed or future sample rate changes (until restoreTrack)
1537e0fa467e1150c65a7b1b1ed904c579b40f97c9dfGlenn Kasten    // FIXME don't believe this lie
15389f9e21ed9a342e0ca945818bdc6c0c4fb3bfb9bdAndy Hung    mLatency = mAfLatency + (1000*frameCount) / mSampleRate;
15395f631515d098c29603cda88f7a7e7580a2d55b57Glenn Kasten
1540b603744e96b07b1d5bf745bde593fb2c025cefcfGlenn Kasten    mFrameCount = frameCount;
1541093000f7d11839b920e8dfaa42ed1d09f48e24b8Glenn Kasten    // If IAudioTrack is re-created, don't let the requested frameCount
1542093000f7d11839b920e8dfaa42ed1d09f48e24b8Glenn Kasten    // decrease.  This can confuse clients that cache frameCount().
1543b603744e96b07b1d5bf745bde593fb2c025cefcfGlenn Kasten    if (frameCount > mReqFrameCount) {
1544b603744e96b07b1d5bf745bde593fb2c025cefcfGlenn Kasten        mReqFrameCount = frameCount;
1545093000f7d11839b920e8dfaa42ed1d09f48e24b8Glenn Kasten    }
1546e3aa659e9cee7df5c12a80d285cc29ab3b2cbb39Glenn Kasten
1547d7bd69e4d1e74f25413721804d5290c53ea87f2bAndy Hung    // reset server position to 0 as we have new cblk.
1548d7bd69e4d1e74f25413721804d5290c53ea87f2bAndy Hung    mServer = 0;
1549d7bd69e4d1e74f25413721804d5290c53ea87f2bAndy Hung
1550e3aa659e9cee7df5c12a80d285cc29ab3b2cbb39Glenn Kasten    // update proxy
1551363fb75db26698cbb50065506e0c80b61d1fbf92Glenn Kasten    if (mSharedBuffer == 0) {
15529f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        mStaticProxy.clear();
1553abdb990953ffe94a9dc544aea0bed17ef7d5f484Andy Hung        mProxy = new AudioTrackClientProxy(cblk, buffers, frameCount, mFrameSize);
15549f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    } else {
1555abdb990953ffe94a9dc544aea0bed17ef7d5f484Andy Hung        mStaticProxy = new StaticAudioTrackClientProxy(cblk, buffers, frameCount, mFrameSize);
15569f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        mProxy = mStaticProxy;
15579f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    }
1558e6a9d65845032644b0865b6e3d0b5a820f35d9e4seunghak.han
1559e6a9d65845032644b0865b6e3d0b5a820f35d9e4seunghak.han    mProxy->setVolumeLR(gain_minifloat_pack(
1560e6a9d65845032644b0865b6e3d0b5a820f35d9e4seunghak.han            gain_from_float(mVolume[AUDIO_INTERLEAVE_LEFT]),
1561e6a9d65845032644b0865b6e3d0b5a820f35d9e4seunghak.han            gain_from_float(mVolume[AUDIO_INTERLEAVE_RIGHT])));
1562e6a9d65845032644b0865b6e3d0b5a820f35d9e4seunghak.han
1563e3aa659e9cee7df5c12a80d285cc29ab3b2cbb39Glenn Kasten    mProxy->setSendLevel(mSendLevel);
15645a8a95de6dad1a3bcf3da5a37b35766e89086e13Ricardo Garcia    const uint32_t effectiveSampleRate = adjustSampleRate(mSampleRate, mPlaybackRate.mPitch);
15655a8a95de6dad1a3bcf3da5a37b35766e89086e13Ricardo Garcia    const float effectiveSpeed = adjustSpeed(mPlaybackRate.mSpeed, mPlaybackRate.mPitch);
15665a8a95de6dad1a3bcf3da5a37b35766e89086e13Ricardo Garcia    const float effectivePitch = adjustPitch(mPlaybackRate.mPitch);
156726145643ce22d797b3b1675c82c47a2d8c79ecaaAndy Hung    mProxy->setSampleRate(effectiveSampleRate);
15685a8a95de6dad1a3bcf3da5a37b35766e89086e13Ricardo Garcia
15695a8a95de6dad1a3bcf3da5a37b35766e89086e13Ricardo Garcia    AudioPlaybackRate playbackRateTemp = mPlaybackRate;
15705a8a95de6dad1a3bcf3da5a37b35766e89086e13Ricardo Garcia    playbackRateTemp.mSpeed = effectiveSpeed;
15715a8a95de6dad1a3bcf3da5a37b35766e89086e13Ricardo Garcia    playbackRateTemp.mPitch = effectivePitch;
15725a8a95de6dad1a3bcf3da5a37b35766e89086e13Ricardo Garcia    mProxy->setPlaybackRate(playbackRateTemp);
15739f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    mProxy->setMinimum(mNotificationFramesAct);
15749f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
15759f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    mDeathNotifier = new DeathNotifier(this);
1576f888020c6e2735624f2b2a30e72aca24e17b8b4dMarco Nelissen    IInterface::asBinder(mAudioTrack)->linkToDeath(mDeathNotifier, this);
1577e3aa659e9cee7df5c12a80d285cc29ab3b2cbb39Glenn Kasten
1578296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent    if (mDeviceCallback != 0) {
1579296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent        AudioSystem::addAudioDeviceCallback(mDeviceCallback, mOutput);
1580296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent    }
1581296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent
158234f1d8ecd23169a5f299937e3aaf1bd7937578a0Eric Laurent    return NO_ERROR;
158338e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten    }
158438e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten
158538e905b3cbba4da443d799b16999989781afc6d8Glenn Kastenrelease:
1586d848eb48c121c119e8ba7583efc75415fe102570Glenn Kasten    AudioSystem::releaseOutput(output, streamType, mSessionId);
158738e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten    if (status == NO_ERROR) {
158838e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten        status = NO_INIT;
158938e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten    }
159038e905b3cbba4da443d799b16999989781afc6d8Glenn Kasten    return status;
159134f1d8ecd23169a5f299937e3aaf1bd7937578a0Eric Laurent}
159234f1d8ecd23169a5f299937e3aaf1bd7937578a0Eric Laurent
1593b46f394a85d704dd05287cf9bb77cf86e3c02a38Glenn Kastenstatus_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount, size_t *nonContig)
159489fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project{
15959f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    if (audioBuffer == NULL) {
1596551b5355d34aa42890811fc3606d3b63429296cdGlenn Kasten        if (nonContig != NULL) {
1597551b5355d34aa42890811fc3606d3b63429296cdGlenn Kasten            *nonContig = 0;
1598551b5355d34aa42890811fc3606d3b63429296cdGlenn Kasten        }
15999f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        return BAD_VALUE;
16009f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    }
16019f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    if (mTransfer != TRANSFER_OBTAIN) {
16029f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        audioBuffer->frameCount = 0;
16039f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        audioBuffer->size = 0;
16049f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        audioBuffer->raw = NULL;
1605551b5355d34aa42890811fc3606d3b63429296cdGlenn Kasten        if (nonContig != NULL) {
1606551b5355d34aa42890811fc3606d3b63429296cdGlenn Kasten            *nonContig = 0;
1607551b5355d34aa42890811fc3606d3b63429296cdGlenn Kasten        }
16089f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        return INVALID_OPERATION;
16099f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    }
16109f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
16119f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    const struct timespec *requested;
1612df576995a5aad3428aeeef765387d650945c161dEric Laurent    struct timespec timeout;
16139f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    if (waitCount == -1) {
16149f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        requested = &ClientProxy::kForever;
16159f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    } else if (waitCount == 0) {
16169f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        requested = &ClientProxy::kNonBlocking;
16179f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    } else if (waitCount > 0) {
16189f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        long long ms = WAIT_PERIOD_MS * (long long) waitCount;
16199f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        timeout.tv_sec = ms / 1000;
16209f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        timeout.tv_nsec = (int) (ms % 1000) * 1000000;
16219f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        requested = &timeout;
16229f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    } else {
16239f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        ALOGE("%s invalid waitCount %d", __func__, waitCount);
16249f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        requested = NULL;
16259f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    }
1626b46f394a85d704dd05287cf9bb77cf86e3c02a38Glenn Kasten    return obtainBuffer(audioBuffer, requested, NULL /*elapsed*/, nonContig);
16279f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten}
16289f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
16299f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kastenstatus_t AudioTrack::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
16309f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        struct timespec *elapsed, size_t *nonContig)
16319f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten{
16329f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    // previous and new IAudioTrack sequence numbers are used to detect track re-creation
16339f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    uint32_t oldSequence = 0;
16349f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    uint32_t newSequence;
1635e3aa659e9cee7df5c12a80d285cc29ab3b2cbb39Glenn Kasten
16369f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    Proxy::Buffer buffer;
16379f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    status_t status = NO_ERROR;
163889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
16399f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    static const int32_t kMaxTries = 5;
16409f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    int32_t tryCounter = kMaxTries;
164189fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
16429f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    do {
16439f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to
16449f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        // keep them from going away if another thread re-creates the track during obtainBuffer()
16459f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        sp<AudioTrackClientProxy> proxy;
16469f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        sp<IMemory> iMem;
164789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
16489f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        {   // start of lock scope
16499f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            AutoMutex lock(mLock);
16501703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent
16519f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            newSequence = mSequence;
16529f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            // did previous obtainBuffer() fail due to media server death or voluntary invalidation?
16539f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            if (status == DEAD_OBJECT) {
16549f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                // re-create track, unless someone else has already done so
16559f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                if (newSequence == oldSequence) {
16569f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    status = restoreTrack_l("obtainBuffer");
16579f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    if (status != NO_ERROR) {
1658b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald                        buffer.mFrameCount = 0;
1659b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald                        buffer.mRaw = NULL;
1660b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald                        buffer.mNonContig = 0;
16619f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                        break;
166289fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                    }
166389fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                }
16649f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            }
16659f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            oldSequence = newSequence;
1666c2f1f07084818942352c6bbfb36af9b6b330eb4eEric Laurent
16674d231dc0ee34380956c71cbe18a750e487a69601Eric Laurent            if (status == NOT_ENOUGH_DATA) {
16684d231dc0ee34380956c71cbe18a750e487a69601Eric Laurent                restartIfDisabled();
16694d231dc0ee34380956c71cbe18a750e487a69601Eric Laurent            }
16704d231dc0ee34380956c71cbe18a750e487a69601Eric Laurent
16719f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            // Keep the extra references
16729f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            proxy = mProxy;
16739f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            iMem = mCblkMemory;
16749f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
1675b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald            if (mState == STATE_STOPPING) {
1676b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald                status = -EINTR;
1677b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald                buffer.mFrameCount = 0;
1678b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald                buffer.mRaw = NULL;
1679b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald                buffer.mNonContig = 0;
1680b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald                break;
1681b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald            }
1682b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald
16839f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            // Non-blocking if track is stopped or paused
16849f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            if (mState != STATE_ACTIVE) {
16859f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                requested = &ClientProxy::kNonBlocking;
168689fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project            }
168789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
16889f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }   // end of lock scope
1689c2f1f07084818942352c6bbfb36af9b6b330eb4eEric Laurent
16909f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        buffer.mFrameCount = audioBuffer->frameCount;
16919f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        // FIXME starts the requested timeout and elapsed over from scratch
16929f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        status = proxy->obtainBuffer(&buffer, requested, elapsed);
16934d231dc0ee34380956c71cbe18a750e487a69601Eric Laurent    } while (((status == DEAD_OBJECT) || (status == NOT_ENOUGH_DATA)) && (tryCounter-- > 0));
169489fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
16959f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    audioBuffer->frameCount = buffer.mFrameCount;
1696abdb990953ffe94a9dc544aea0bed17ef7d5f484Andy Hung    audioBuffer->size = buffer.mFrameCount * mFrameSize;
16979f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    audioBuffer->raw = buffer.mRaw;
16989f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    if (nonContig != NULL) {
16999f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        *nonContig = buffer.mNonContig;
170089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    }
17019f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    return status;
170289fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project}
170389fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
170454a8a456c2b4b382b3ffe3d99e40703df79c0717Glenn Kastenvoid AudioTrack::releaseBuffer(const Buffer* audioBuffer)
170589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project{
17063f02be2ceeaa4b67dc0b1a81aebcfa049276fad8Glenn Kasten    // FIXME add error checking on mode, by adding an internal version
17079f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    if (mTransfer == TRANSFER_SHARED) {
17089f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        return;
17099f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    }
17109f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
1711abdb990953ffe94a9dc544aea0bed17ef7d5f484Andy Hung    size_t stepCount = audioBuffer->size / mFrameSize;
17129f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    if (stepCount == 0) {
17139f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        return;
17149f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    }
17159f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
17169f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    Proxy::Buffer buffer;
17179f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    buffer.mFrameCount = stepCount;
17189f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    buffer.mRaw = audioBuffer->raw;
1719e3aa659e9cee7df5c12a80d285cc29ab3b2cbb39Glenn Kasten
17201703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent    AutoMutex lock(mLock);
1721200092b7f21d2b98f30b800e79d152636f9ba225Glenn Kasten    mReleased += stepCount;
17229f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    mInUnderrun = false;
17239f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    mProxy->releaseBuffer(&buffer);
17249f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
17259f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    // restart track if it was disabled by audioflinger due to previous underrun
17264d231dc0ee34380956c71cbe18a750e487a69601Eric Laurent    restartIfDisabled();
17274d231dc0ee34380956c71cbe18a750e487a69601Eric Laurent}
17284d231dc0ee34380956c71cbe18a750e487a69601Eric Laurent
17294d231dc0ee34380956c71cbe18a750e487a69601Eric Laurentvoid AudioTrack::restartIfDisabled()
17304d231dc0ee34380956c71cbe18a750e487a69601Eric Laurent{
17314d231dc0ee34380956c71cbe18a750e487a69601Eric Laurent    int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
17324d231dc0ee34380956c71cbe18a750e487a69601Eric Laurent    if ((mState == STATE_ACTIVE) && (flags & CBLK_DISABLED)) {
17334d231dc0ee34380956c71cbe18a750e487a69601Eric Laurent        ALOGW("releaseBuffer() track %p disabled due to previous underrun, restarting", this);
17344d231dc0ee34380956c71cbe18a750e487a69601Eric Laurent        // FIXME ignoring status
17354d231dc0ee34380956c71cbe18a750e487a69601Eric Laurent        mAudioTrack->start();
1736df839841d2db4cb8e2acb10205b3942622b3e7a2Eric Laurent    }
173789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project}
173889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
173989fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project// -------------------------------------------------------------------------
174089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
1741720ad9ddb2ac6b55b0dfbfcd2d8360151d8ac427Jean-Michel Trivissize_t AudioTrack::write(const void* buffer, size_t userSize, bool blocking)
174289fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project{
1743d79072e9dff59f767cce2cda1caab80ce5a0815bGlenn Kasten    if (mTransfer != TRANSFER_SYNC) {
1744d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kasten        return INVALID_OPERATION;
1745d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kasten    }
174689fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
1747ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent    if (isDirect()) {
1748ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent        AutoMutex lock(mLock);
1749ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent        int32_t flags = android_atomic_and(
1750ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent                            ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END),
1751ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent                            &mCblk->mFlags);
1752ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent        if (flags & CBLK_INVALID) {
1753ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent            return DEAD_OBJECT;
1754ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent        }
1755ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent    }
1756ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent
17579f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
175899e53b86eebb605b70dd7591b89bf61a9414ed0eGlenn Kasten        // Sanity-check: user is most-likely passing an error code, and it would
175999e53b86eebb605b70dd7591b89bf61a9414ed0eGlenn Kasten        // make the return value ambiguous (actualSize vs error).
1760377b2ec9a2885f9b6405b07ba900a9e3f4349c38Kévin PETIT        ALOGE("AudioTrack::write(buffer=%p, size=%zu (%zd)", buffer, userSize, userSize);
176189fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        return BAD_VALUE;
176289fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    }
176389fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
17649f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    size_t written = 0;
176589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    Buffer audioBuffer;
176689fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
17679f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    while (userSize >= mFrameSize) {
17689f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        audioBuffer.frameCount = userSize / mFrameSize;
1769c2f1f07084818942352c6bbfb36af9b6b330eb4eEric Laurent
1770720ad9ddb2ac6b55b0dfbfcd2d8360151d8ac427Jean-Michel Trivi        status_t err = obtainBuffer(&audioBuffer,
1771720ad9ddb2ac6b55b0dfbfcd2d8360151d8ac427Jean-Michel Trivi                blocking ? &ClientProxy::kForever : &ClientProxy::kNonBlocking);
177289fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        if (err < 0) {
17739f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            if (written > 0) {
177489fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project                break;
1775d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kasten            }
17760a2f151f37c715078351ae0be99b0c4dbabc2a23Glenn Kasten            if (err == TIMED_OUT || err == -EINTR) {
17770a2f151f37c715078351ae0be99b0c4dbabc2a23Glenn Kasten                err = WOULD_BLOCK;
17780a2f151f37c715078351ae0be99b0c4dbabc2a23Glenn Kasten            }
177989fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project            return ssize_t(err);
178089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        }
178189fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
1782ae4b879d04c4b07c62241a8f507c8dce11e628e4Glenn Kasten        size_t toWrite = audioBuffer.size;
1783abdb990953ffe94a9dc544aea0bed17ef7d5f484Andy Hung        memcpy(audioBuffer.i8, buffer, toWrite);
17849f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        buffer = ((const char *) buffer) + toWrite;
178589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        userSize -= toWrite;
178689fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        written += toWrite;
178789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
178889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        releaseBuffer(&audioBuffer);
17899f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    }
179089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
1791ea2b9c07b34079f0dbd8610a511e006e69a15adcAndy Hung    if (written > 0) {
1792ea2b9c07b34079f0dbd8610a511e006e69a15adcAndy Hung        mFramesWritten += written / mFrameSize;
1793ea2b9c07b34079f0dbd8610a511e006e69a15adcAndy Hung    }
179489fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    return written;
179589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project}
179689fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
179789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project// -------------------------------------------------------------------------
179889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
17997c7be1e05634d96d08210efb4bdeb012ffba440dGlenn Kastennsecs_t AudioTrack::processAudioBuffer()
180089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project{
1801fb1fdc9d6603aa228362e7349451f6455c9849c2Glenn Kasten    // Currently the AudioTrack thread is not created if there are no callbacks.
1802fb1fdc9d6603aa228362e7349451f6455c9849c2Glenn Kasten    // Would it ever make sense to run the thread, even without callbacks?
1803fb1fdc9d6603aa228362e7349451f6455c9849c2Glenn Kasten    // If so, then replace this by checks at each use for mCbf != NULL.
1804fb1fdc9d6603aa228362e7349451f6455c9849c2Glenn Kasten    LOG_ALWAYS_FATAL_IF(mCblk == NULL);
1805fb1fdc9d6603aa228362e7349451f6455c9849c2Glenn Kasten
18061703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent    mLock.lock();
1807a07f17ca46db04c9d5d9e7d6b2878db59ca2b9eaGlenn Kasten    if (mAwaitBoost) {
1808a07f17ca46db04c9d5d9e7d6b2878db59ca2b9eaGlenn Kasten        mAwaitBoost = false;
1809a07f17ca46db04c9d5d9e7d6b2878db59ca2b9eaGlenn Kasten        mLock.unlock();
1810a07f17ca46db04c9d5d9e7d6b2878db59ca2b9eaGlenn Kasten        static const int32_t kMaxTries = 5;
1811a07f17ca46db04c9d5d9e7d6b2878db59ca2b9eaGlenn Kasten        int32_t tryCounter = kMaxTries;
1812a07f17ca46db04c9d5d9e7d6b2878db59ca2b9eaGlenn Kasten        uint32_t pollUs = 10000;
1813a07f17ca46db04c9d5d9e7d6b2878db59ca2b9eaGlenn Kasten        do {
18148255ba7b40774b2b8868482f1a302db3ae98e905Glenn Kasten            int policy = sched_getscheduler(0) & ~SCHED_RESET_ON_FORK;
1815a07f17ca46db04c9d5d9e7d6b2878db59ca2b9eaGlenn Kasten            if (policy == SCHED_FIFO || policy == SCHED_RR) {
1816a07f17ca46db04c9d5d9e7d6b2878db59ca2b9eaGlenn Kasten                break;
1817a07f17ca46db04c9d5d9e7d6b2878db59ca2b9eaGlenn Kasten            }
1818a07f17ca46db04c9d5d9e7d6b2878db59ca2b9eaGlenn Kasten            usleep(pollUs);
1819a07f17ca46db04c9d5d9e7d6b2878db59ca2b9eaGlenn Kasten            pollUs <<= 1;
1820a07f17ca46db04c9d5d9e7d6b2878db59ca2b9eaGlenn Kasten        } while (tryCounter-- > 0);
1821a07f17ca46db04c9d5d9e7d6b2878db59ca2b9eaGlenn Kasten        if (tryCounter < 0) {
1822a07f17ca46db04c9d5d9e7d6b2878db59ca2b9eaGlenn Kasten            ALOGE("did not receive expected priority boost on time");
1823a07f17ca46db04c9d5d9e7d6b2878db59ca2b9eaGlenn Kasten        }
1824b0dfd4613225a3b2a17bdf8d85e89a4b04d65ef3Glenn Kasten        // Run again immediately
1825b0dfd4613225a3b2a17bdf8d85e89a4b04d65ef3Glenn Kasten        return 0;
1826a07f17ca46db04c9d5d9e7d6b2878db59ca2b9eaGlenn Kasten    }
18271703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent
18289f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    // Can only reference mCblk while locked
18299f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    int32_t flags = android_atomic_and(
183096f60d8f04432a1ed503b3e24d5736d28c63c9a2Glenn Kasten        ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END), &mCblk->mFlags);
1831a47f3165f53c8e8fb8907a94de7417e2c3047eebGlenn Kasten
18329f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    // Check for track invalidation
18339f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    if (flags & CBLK_INVALID) {
1834b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        // for offloaded tracks restoreTrack_l() will just update the sequence and clear
1835b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        // AudioSystem cache. We should not exit here but after calling the callback so
1836b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        // that the upper layers can recreate the track
1837ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent        if (!isOffloadedOrDirect_l() || (mSequence == mObservedSequence)) {
1838f1063e2659cad01ec334a265c31734c63c319cc4Lajos Molnar            status_t status __unused = restoreTrack_l("processAudioBuffer");
1839f1063e2659cad01ec334a265c31734c63c319cc4Lajos Molnar            // FIXME unused status
184053c3b5fc1afe162a8669cb3d27d6bb14e1847e39Andy Hung            // after restoration, continue below to make sure that the loop and buffer events
184153c3b5fc1afe162a8669cb3d27d6bb14e1847e39Andy Hung            // are notified because they have been cleared from mCblk->mFlags above.
1842b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        }
184389fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    }
1844c2f1f07084818942352c6bbfb36af9b6b330eb4eEric Laurent
1845b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald    bool waitStreamEnd = mState == STATE_STOPPING;
18469f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    bool active = mState == STATE_ACTIVE;
184789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
18489f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    // Manage underrun callback, must be done under lock to avoid race with releaseBuffer()
18499f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    bool newUnderrun = false;
18509f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    if (flags & CBLK_UNDERRUN) {
18519f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten#if 0
18529f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        // Currently in shared buffer mode, when the server reaches the end of buffer,
18539f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        // the track stays active in continuous underrun state.  It's up to the application
18549f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        // to pause or stop the track, or set the position to a new offset within buffer.
18559f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        // This was some experimental code to auto-pause on underrun.   Keeping it here
18569f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        // in "if 0" so we can re-visit this if we add a real sequencer for shared memory content.
18579f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        if (mTransfer == TRANSFER_SHARED) {
18589f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            mState = STATE_PAUSED;
18599f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            active = false;
18609f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
18619f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten#endif
18629f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        if (!mInUnderrun) {
18639f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            mInUnderrun = true;
18649f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            newUnderrun = true;
18659f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
186689fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    }
186789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
18689f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    // Get current position of server
186990e8a97dd5c9d391d7a2ea6a2290ed976f928379Andy Hung    Modulo<uint32_t> position(updateAndGetPosition_l());
18709f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
187189fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    // Manage marker callback
18729f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    bool markerReached = false;
187390e8a97dd5c9d391d7a2ea6a2290ed976f928379Andy Hung    Modulo<uint32_t> markerPosition(mMarkerPosition);
187490e8a97dd5c9d391d7a2ea6a2290ed976f928379Andy Hung    // uses 32 bit wraparound for comparison with position.
187590e8a97dd5c9d391d7a2ea6a2290ed976f928379Andy Hung    if (!mMarkerReached && markerPosition.value() > 0 && position >= markerPosition) {
18769f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        mMarkerReached = markerReached = true;
18779f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    }
18789f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
18799f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    // Determine number of new position callback(s) that will be needed, while locked
18809f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    size_t newPosCount = 0;
188190e8a97dd5c9d391d7a2ea6a2290ed976f928379Andy Hung    Modulo<uint32_t> newPosition(mNewPosition);
188290e8a97dd5c9d391d7a2ea6a2290ed976f928379Andy Hung    uint32_t updatePeriod = mUpdatePeriod;
18839f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    // FIXME fails for wraparound, need 64 bits
18849f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    if (updatePeriod > 0 && position >= newPosition) {
188590e8a97dd5c9d391d7a2ea6a2290ed976f928379Andy Hung        newPosCount = ((position - newPosition).value() / updatePeriod) + 1;
18869f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        mNewPosition += updatePeriod * newPosCount;
18879f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    }
18889f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
18899f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    // Cache other fields that will be needed soon
18909f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    uint32_t sampleRate = mSampleRate;
18915a8a95de6dad1a3bcf3da5a37b35766e89086e13Ricardo Garcia    float speed = mPlaybackRate.mSpeed;
1892a7f03353d5f172016f324e2a01f301cca6794152Andy Hung    const uint32_t notificationFrames = mNotificationFramesAct;
18939f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    if (mRefreshRemaining) {
18949f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        mRefreshRemaining = false;
18959f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        mRemainingFrames = notificationFrames;
18969f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        mRetryOnPartialBuffer = false;
18979f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    }
18989f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    size_t misalignment = mProxy->getMisalignment();
1899b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald    uint32_t sequence = mSequence;
190096f04886d1c1bfbc422e2be033ea66be83e42441Glenn Kasten    sp<AudioTrackClientProxy> proxy = mProxy;
19019f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
190253c3b5fc1afe162a8669cb3d27d6bb14e1847e39Andy Hung    // Determine the number of new loop callback(s) that will be needed, while locked.
190353c3b5fc1afe162a8669cb3d27d6bb14e1847e39Andy Hung    int loopCountNotifications = 0;
190453c3b5fc1afe162a8669cb3d27d6bb14e1847e39Andy Hung    uint32_t loopPeriod = 0; // time in frames for next EVENT_LOOP_END or EVENT_BUFFER_END
190553c3b5fc1afe162a8669cb3d27d6bb14e1847e39Andy Hung
190653c3b5fc1afe162a8669cb3d27d6bb14e1847e39Andy Hung    if (mLoopCount > 0) {
190753c3b5fc1afe162a8669cb3d27d6bb14e1847e39Andy Hung        int loopCount;
190853c3b5fc1afe162a8669cb3d27d6bb14e1847e39Andy Hung        size_t bufferPosition;
190953c3b5fc1afe162a8669cb3d27d6bb14e1847e39Andy Hung        mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
191053c3b5fc1afe162a8669cb3d27d6bb14e1847e39Andy Hung        loopPeriod = ((loopCount > 0) ? mLoopEnd : mFrameCount) - bufferPosition;
191153c3b5fc1afe162a8669cb3d27d6bb14e1847e39Andy Hung        loopCountNotifications = min(mLoopCountNotified - loopCount, kMaxLoopCountNotifications);
191253c3b5fc1afe162a8669cb3d27d6bb14e1847e39Andy Hung        mLoopCountNotified = loopCount; // discard any excess notifications
191353c3b5fc1afe162a8669cb3d27d6bb14e1847e39Andy Hung    } else if (mLoopCount < 0) {
191453c3b5fc1afe162a8669cb3d27d6bb14e1847e39Andy Hung        // FIXME: We're not accurate with notification count and position with infinite looping
191553c3b5fc1afe162a8669cb3d27d6bb14e1847e39Andy Hung        // since loopCount from server side will always return -1 (we could decrement it).
191653c3b5fc1afe162a8669cb3d27d6bb14e1847e39Andy Hung        size_t bufferPosition = mStaticProxy->getBufferPosition();
191753c3b5fc1afe162a8669cb3d27d6bb14e1847e39Andy Hung        loopCountNotifications = int((flags & (CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL)) != 0);
191853c3b5fc1afe162a8669cb3d27d6bb14e1847e39Andy Hung        loopPeriod = mLoopEnd - bufferPosition;
191953c3b5fc1afe162a8669cb3d27d6bb14e1847e39Andy Hung    } else if (/* mLoopCount == 0 && */ mSharedBuffer != 0) {
192053c3b5fc1afe162a8669cb3d27d6bb14e1847e39Andy Hung        size_t bufferPosition = mStaticProxy->getBufferPosition();
192153c3b5fc1afe162a8669cb3d27d6bb14e1847e39Andy Hung        loopPeriod = mFrameCount - bufferPosition;
192253c3b5fc1afe162a8669cb3d27d6bb14e1847e39Andy Hung    }
192353c3b5fc1afe162a8669cb3d27d6bb14e1847e39Andy Hung
19249f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    // These fields don't need to be cached, because they are assigned only by set():
1925abdb990953ffe94a9dc544aea0bed17ef7d5f484Andy Hung    //     mTransfer, mCbf, mUserData, mFormat, mFrameSize, mFlags
19269f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    // mFlags is also assigned by createTrack_l(), but not the bit we care about.
19279f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
19289f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    mLock.unlock();
19299f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
1930a7f03353d5f172016f324e2a01f301cca6794152Andy Hung    // get anchor time to account for callbacks.
1931a7f03353d5f172016f324e2a01f301cca6794152Andy Hung    const nsecs_t timeBeforeCallbacks = systemTime();
1932a7f03353d5f172016f324e2a01f301cca6794152Andy Hung
1933b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald    if (waitStreamEnd) {
1934a7f03353d5f172016f324e2a01f301cca6794152Andy Hung        // FIXME:  Instead of blocking in proxy->waitStreamEndDone(), Callback thread
1935a7f03353d5f172016f324e2a01f301cca6794152Andy Hung        // should wait on proxy futex and handle CBLK_STREAM_END_DONE within this function
1936a7f03353d5f172016f324e2a01f301cca6794152Andy Hung        // (and make sure we don't callback for more data while we're stopping).
1937a7f03353d5f172016f324e2a01f301cca6794152Andy Hung        // This helps with position, marker notifications, and track invalidation.
1938b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        struct timespec timeout;
1939b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        timeout.tv_sec = WAIT_STREAM_END_TIMEOUT_SEC;
1940b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        timeout.tv_nsec = 0;
1941b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald
194296f04886d1c1bfbc422e2be033ea66be83e42441Glenn Kasten        status_t status = proxy->waitStreamEndDone(&timeout);
1943b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        switch (status) {
1944b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        case NO_ERROR:
1945b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        case DEAD_OBJECT:
1946b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        case TIMED_OUT:
194739609a0a6d95d003b0f237e6c139b070b4df7071Andy Hung            if (status != DEAD_OBJECT) {
194839609a0a6d95d003b0f237e6c139b070b4df7071Andy Hung                // for DEAD_OBJECT, we do not send a EVENT_STREAM_END after stop();
194939609a0a6d95d003b0f237e6c139b070b4df7071Andy Hung                // instead, the application should handle the EVENT_NEW_IAUDIOTRACK.
195039609a0a6d95d003b0f237e6c139b070b4df7071Andy Hung                mCbf(EVENT_STREAM_END, mUserData, NULL);
195139609a0a6d95d003b0f237e6c139b070b4df7071Andy Hung            }
195296f04886d1c1bfbc422e2be033ea66be83e42441Glenn Kasten            {
195396f04886d1c1bfbc422e2be033ea66be83e42441Glenn Kasten                AutoMutex lock(mLock);
195496f04886d1c1bfbc422e2be033ea66be83e42441Glenn Kasten                // The previously assigned value of waitStreamEnd is no longer valid,
195596f04886d1c1bfbc422e2be033ea66be83e42441Glenn Kasten                // since the mutex has been unlocked and either the callback handler
195696f04886d1c1bfbc422e2be033ea66be83e42441Glenn Kasten                // or another thread could have re-started the AudioTrack during that time.
195796f04886d1c1bfbc422e2be033ea66be83e42441Glenn Kasten                waitStreamEnd = mState == STATE_STOPPING;
195896f04886d1c1bfbc422e2be033ea66be83e42441Glenn Kasten                if (waitStreamEnd) {
195996f04886d1c1bfbc422e2be033ea66be83e42441Glenn Kasten                    mState = STATE_STOPPED;
1960c2813e568aa476e03d159529c0af28c99536db8dAndy Hung                    mReleased = 0;
1961b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald                }
1962b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald            }
196396f04886d1c1bfbc422e2be033ea66be83e42441Glenn Kasten            if (waitStreamEnd && status != DEAD_OBJECT) {
196496f04886d1c1bfbc422e2be033ea66be83e42441Glenn Kasten               return NS_INACTIVE;
196596f04886d1c1bfbc422e2be033ea66be83e42441Glenn Kasten            }
196696f04886d1c1bfbc422e2be033ea66be83e42441Glenn Kasten            break;
1967b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        }
196896f04886d1c1bfbc422e2be033ea66be83e42441Glenn Kasten        return 0;
1969b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald    }
1970b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald
19719f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    // perform callbacks while unlocked
19729f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    if (newUnderrun) {
19739f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        mCbf(EVENT_UNDERRUN, mUserData, NULL);
19749f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    }
197553c3b5fc1afe162a8669cb3d27d6bb14e1847e39Andy Hung    while (loopCountNotifications > 0) {
19769f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        mCbf(EVENT_LOOP_END, mUserData, NULL);
197753c3b5fc1afe162a8669cb3d27d6bb14e1847e39Andy Hung        --loopCountNotifications;
19789f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    }
19799f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    if (flags & CBLK_BUFFER_END) {
19809f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        mCbf(EVENT_BUFFER_END, mUserData, NULL);
19819f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    }
19829f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    if (markerReached) {
19839f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        mCbf(EVENT_MARKER, mUserData, &markerPosition);
19849f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    }
19859f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    while (newPosCount > 0) {
198690e8a97dd5c9d391d7a2ea6a2290ed976f928379Andy Hung        size_t temp = newPosition.value(); // FIXME size_t != uint32_t
19879f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        mCbf(EVENT_NEW_POS, mUserData, &temp);
19889f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        newPosition += updatePeriod;
19899f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        newPosCount--;
19909f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    }
1991b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald
19929f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    if (mObservedSequence != sequence) {
19939f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        mObservedSequence = sequence;
19949f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        mCbf(EVENT_NEW_IAUDIOTRACK, mUserData, NULL);
1995b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        // for offloaded tracks, just wait for the upper layers to recreate the track
1996ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent        if (isOffloadedOrDirect()) {
1997b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald            return NS_INACTIVE;
1998b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        }
199989fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    }
200089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
20019f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    // if inactive, then don't run me again until re-started
20029f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    if (!active) {
20039f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        return NS_INACTIVE;
200489fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    }
200589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
20069f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    // Compute the estimated time until the next timed event (position, markers, loops)
20079f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    // FIXME only for non-compressed audio
20089f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    uint32_t minFrames = ~0;
20099f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    if (!markerReached && position < markerPosition) {
201090e8a97dd5c9d391d7a2ea6a2290ed976f928379Andy Hung        minFrames = (markerPosition - position).value();
20119f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    }
20129f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    if (loopPeriod > 0 && loopPeriod < minFrames) {
20132d85f097d653b21d1ff2c34f0b732c674d20ccc2Andy Hung        // loopPeriod is already adjusted for actual position.
20149f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        minFrames = loopPeriod;
20159f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    }
20162d85f097d653b21d1ff2c34f0b732c674d20ccc2Andy Hung    if (updatePeriod > 0) {
201790e8a97dd5c9d391d7a2ea6a2290ed976f928379Andy Hung        minFrames = min(minFrames, (newPosition - position).value());
201889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    }
201989fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
20209f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    // If > 0, poll periodically to recover from a stuck server.  A good value is 2.
20219f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    static const uint32_t kPoll = 0;
20229f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
20239f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        minFrames = kPoll * notificationFrames;
20242267ba18d0d2b2d4bd7f5411821ad89ac2659a88Eric Laurent    }
20252267ba18d0d2b2d4bd7f5411821ad89ac2659a88Eric Laurent
2026a7f03353d5f172016f324e2a01f301cca6794152Andy Hung    // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
2027a7f03353d5f172016f324e2a01f301cca6794152Andy Hung    static const nsecs_t kWaitPeriodNs = WAIT_PERIOD_MS * 1000000LL;
2028a7f03353d5f172016f324e2a01f301cca6794152Andy Hung    const nsecs_t timeAfterCallbacks = systemTime();
2029a7f03353d5f172016f324e2a01f301cca6794152Andy Hung
20309f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    // Convert frame units to time units
20319f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    nsecs_t ns = NS_WHENEVER;
20329f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    if (minFrames != (uint32_t) ~0) {
2033a7f03353d5f172016f324e2a01f301cca6794152Andy Hung        ns = framesToNanoseconds(minFrames, sampleRate, speed) + kWaitPeriodNs;
2034a7f03353d5f172016f324e2a01f301cca6794152Andy Hung        ns -= (timeAfterCallbacks - timeBeforeCallbacks);  // account for callback time
2035a7f03353d5f172016f324e2a01f301cca6794152Andy Hung        // TODO: Should we warn if the callback time is too long?
2036a7f03353d5f172016f324e2a01f301cca6794152Andy Hung        if (ns < 0) ns = 0;
20379f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    }
20389f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
20399f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    // If not supplying data by EVENT_MORE_DATA, then we're done
20409f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    if (mTransfer != TRANSFER_CALLBACK) {
20419f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        return ns;
20429f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    }
204389fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
2044a7f03353d5f172016f324e2a01f301cca6794152Andy Hung    // EVENT_MORE_DATA callback handling.
2045a7f03353d5f172016f324e2a01f301cca6794152Andy Hung    // Timing for linear pcm audio data formats can be derived directly from the
2046a7f03353d5f172016f324e2a01f301cca6794152Andy Hung    // buffer fill level.
2047a7f03353d5f172016f324e2a01f301cca6794152Andy Hung    // Timing for compressed data is not directly available from the buffer fill level,
2048a7f03353d5f172016f324e2a01f301cca6794152Andy Hung    // rather indirectly from waiting for blocking mode callbacks or waiting for obtain()
2049a7f03353d5f172016f324e2a01f301cca6794152Andy Hung    // to return a certain fill level.
2050a7f03353d5f172016f324e2a01f301cca6794152Andy Hung
20519f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    struct timespec timeout;
20529f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    const struct timespec *requested = &ClientProxy::kForever;
20539f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    if (ns != NS_WHENEVER) {
20549f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        timeout.tv_sec = ns / 1000000000LL;
20559f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        timeout.tv_nsec = ns % 1000000000LL;
20569f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        ALOGV("timeout %ld.%03d", timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
20579f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        requested = &timeout;
20589f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    }
20599f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
2060ea2b9c07b34079f0dbd8610a511e006e69a15adcAndy Hung    size_t writtenFrames = 0;
20619f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    while (mRemainingFrames > 0) {
2062c2f1f07084818942352c6bbfb36af9b6b330eb4eEric Laurent
20639f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        Buffer audioBuffer;
20649f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        audioBuffer.frameCount = mRemainingFrames;
20659f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        size_t nonContig;
20669f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
20679f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
206834fb29696b0f3abf61b10f8d053b1f33d501de0aMark Salyzyn                "obtainBuffer() err=%d frameCount=%zu", err, audioBuffer.frameCount);
20699f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        requested = &ClientProxy::kNonBlocking;
20709f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        size_t avail = audioBuffer.frameCount + nonContig;
207134fb29696b0f3abf61b10f8d053b1f33d501de0aMark Salyzyn        ALOGV("obtainBuffer(%u) returned %zu = %zu + %zu err %d",
2072b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald                mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err);
20739f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        if (err != NO_ERROR) {
2074b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald            if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR ||
2075b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald                    (isOffloaded() && (err == DEAD_OBJECT))) {
2076606fbc1030d686bf1f8dc03d14a79342aca2ca41Glenn Kasten                // FIXME bug 25195759
2077606fbc1030d686bf1f8dc03d14a79342aca2ca41Glenn Kasten                return 1000000;
207889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project            }
20799f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            ALOGE("Error %d obtaining an audio buffer, giving up.", err);
20809f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            return NS_NEVER;
208189fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        }
20829f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
2083fdb3c07db5d44535eb8c3ec46dc78ad8446c01ebPhil Burk        if (mRetryOnPartialBuffer && audio_has_proportional_frames(mFormat)) {
20849f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            mRetryOnPartialBuffer = false;
20859f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            if (avail < mRemainingFrames) {
2086a7f03353d5f172016f324e2a01f301cca6794152Andy Hung                if (ns > 0) { // account for obtain time
2087a7f03353d5f172016f324e2a01f301cca6794152Andy Hung                    const nsecs_t timeNow = systemTime();
2088a7f03353d5f172016f324e2a01f301cca6794152Andy Hung                    ns = max((nsecs_t)0, ns - (timeNow - timeAfterCallbacks));
2089a7f03353d5f172016f324e2a01f301cca6794152Andy Hung                }
2090a7f03353d5f172016f324e2a01f301cca6794152Andy Hung                nsecs_t myns = framesToNanoseconds(mRemainingFrames - avail, sampleRate, speed);
2091a7f03353d5f172016f324e2a01f301cca6794152Andy Hung                if (ns < 0 /* NS_WHENEVER */ || myns < ns) {
20929f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                    ns = myns;
20939f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                }
20949f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten                return ns;
20959f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            }
2096d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kasten        }
209789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
209889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        size_t reqSize = audioBuffer.size;
209989fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
21009f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        size_t writtenSize = audioBuffer.size;
210189fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
210289fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        // Sanity check on returned size
21039f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        if (ssize_t(writtenSize) < 0 || writtenSize > reqSize) {
210434fb29696b0f3abf61b10f8d053b1f33d501de0aMark Salyzyn            ALOGE("EVENT_MORE_DATA requested %zu bytes but callback returned %zd bytes",
210534fb29696b0f3abf61b10f8d053b1f33d501de0aMark Salyzyn                    reqSize, ssize_t(writtenSize));
21069f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            return NS_NEVER;
21079f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
21089f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
21099f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        if (writtenSize == 0) {
21108555d0867c3e8fe6cc5c7ad40af557fe6b92fa72The Android Open Source Project            // The callback is done filling buffers
21118555d0867c3e8fe6cc5c7ad40af557fe6b92fa72The Android Open Source Project            // Keep this thread going to handle timed events and
21128555d0867c3e8fe6cc5c7ad40af557fe6b92fa72The Android Open Source Project            // still try to get more data in intervals of WAIT_PERIOD_MS
21138555d0867c3e8fe6cc5c7ad40af557fe6b92fa72The Android Open Source Project            // but don't just loop and block the CPU, so wait
2114a7f03353d5f172016f324e2a01f301cca6794152Andy Hung
2115a7f03353d5f172016f324e2a01f301cca6794152Andy Hung            // mCbf(EVENT_MORE_DATA, ...) might either
2116a7f03353d5f172016f324e2a01f301cca6794152Andy Hung            // (1) Block until it can fill the buffer, returning 0 size on EOS.
2117a7f03353d5f172016f324e2a01f301cca6794152Andy Hung            // (2) Block until it can fill the buffer, returning 0 data (silence) on EOS.
2118a7f03353d5f172016f324e2a01f301cca6794152Andy Hung            // (3) Return 0 size when no data is available, does not wait for more data.
2119a7f03353d5f172016f324e2a01f301cca6794152Andy Hung            //
2120a7f03353d5f172016f324e2a01f301cca6794152Andy Hung            // (1) and (2) occurs with AudioPlayer/AwesomePlayer; (3) occurs with NuPlayer.
2121a7f03353d5f172016f324e2a01f301cca6794152Andy Hung            // We try to compute the wait time to avoid a tight sleep-wait cycle,
2122a7f03353d5f172016f324e2a01f301cca6794152Andy Hung            // especially for case (3).
2123a7f03353d5f172016f324e2a01f301cca6794152Andy Hung            //
2124a7f03353d5f172016f324e2a01f301cca6794152Andy Hung            // The decision to support (1) and (2) affect the sizing of mRemainingFrames
2125a7f03353d5f172016f324e2a01f301cca6794152Andy Hung            // and this loop; whereas for case (3) we could simply check once with the full
2126a7f03353d5f172016f324e2a01f301cca6794152Andy Hung            // buffer size and skip the loop entirely.
2127a7f03353d5f172016f324e2a01f301cca6794152Andy Hung
2128a7f03353d5f172016f324e2a01f301cca6794152Andy Hung            nsecs_t myns;
2129fdb3c07db5d44535eb8c3ec46dc78ad8446c01ebPhil Burk            if (audio_has_proportional_frames(mFormat)) {
2130a7f03353d5f172016f324e2a01f301cca6794152Andy Hung                // time to wait based on buffer occupancy
2131a7f03353d5f172016f324e2a01f301cca6794152Andy Hung                const nsecs_t datans = mRemainingFrames <= avail ? 0 :
2132a7f03353d5f172016f324e2a01f301cca6794152Andy Hung                        framesToNanoseconds(mRemainingFrames - avail, sampleRate, speed);
2133a7f03353d5f172016f324e2a01f301cca6794152Andy Hung                // audio flinger thread buffer size (TODO: adjust for fast tracks)
2134ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten                // FIXME: use mAfFrameCountHAL instead of mAfFrameCount below for fast tracks.
2135a7f03353d5f172016f324e2a01f301cca6794152Andy Hung                const nsecs_t afns = framesToNanoseconds(mAfFrameCount, mAfSampleRate, speed);
2136a7f03353d5f172016f324e2a01f301cca6794152Andy Hung                // add a half the AudioFlinger buffer time to avoid soaking CPU if datans is 0.
2137a7f03353d5f172016f324e2a01f301cca6794152Andy Hung                myns = datans + (afns / 2);
2138a7f03353d5f172016f324e2a01f301cca6794152Andy Hung            } else {
2139a7f03353d5f172016f324e2a01f301cca6794152Andy Hung                // FIXME: This could ping quite a bit if the buffer isn't full.
2140a7f03353d5f172016f324e2a01f301cca6794152Andy Hung                // Note that when mState is stopping we waitStreamEnd, so it never gets here.
2141a7f03353d5f172016f324e2a01f301cca6794152Andy Hung                myns = kWaitPeriodNs;
2142a7f03353d5f172016f324e2a01f301cca6794152Andy Hung            }
2143a7f03353d5f172016f324e2a01f301cca6794152Andy Hung            if (ns > 0) { // account for obtain and callback time
2144a7f03353d5f172016f324e2a01f301cca6794152Andy Hung                const nsecs_t timeNow = systemTime();
2145a7f03353d5f172016f324e2a01f301cca6794152Andy Hung                ns = max((nsecs_t)0, ns - (timeNow - timeAfterCallbacks));
2146a7f03353d5f172016f324e2a01f301cca6794152Andy Hung            }
2147a7f03353d5f172016f324e2a01f301cca6794152Andy Hung            if (ns < 0 /* NS_WHENEVER */ || myns < ns) {
2148a7f03353d5f172016f324e2a01f301cca6794152Andy Hung                ns = myns;
2149a7f03353d5f172016f324e2a01f301cca6794152Andy Hung            }
2150a7f03353d5f172016f324e2a01f301cca6794152Andy Hung            return ns;
2151d65d73c4ae74d084751b417615a78cbe7a51372aGlenn Kasten        }
215289fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
2153138d6f9b0b77d94773a8a29d3c5bdb78f38ee142Glenn Kasten        size_t releasedFrames = writtenSize / mFrameSize;
21549f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        audioBuffer.frameCount = releasedFrames;
21559f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        mRemainingFrames -= releasedFrames;
21569f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        if (misalignment >= releasedFrames) {
21579f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            misalignment -= releasedFrames;
21589f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        } else {
21599f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            misalignment = 0;
21609f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
216189fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
216289fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project        releaseBuffer(&audioBuffer);
2163ea2b9c07b34079f0dbd8610a511e006e69a15adcAndy Hung        writtenFrames += releasedFrames;
216489fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
21659f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
21669f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        // if callback doesn't like to accept the full chunk
21679f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        if (writtenSize < reqSize) {
21689f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            continue;
21699f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
21709f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
21719f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        // There could be enough non-contiguous frames available to satisfy the remaining request
21729f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        if (mRemainingFrames <= nonContig) {
21739f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            continue;
21749f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
21759f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
21769f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten#if 0
21779f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
21789f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        // sum <= notificationFrames.  It replaces that series by at most two EVENT_MORE_DATA
21799f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        // that total to a sum == notificationFrames.
21809f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        if (0 < misalignment && misalignment <= mRemainingFrames) {
21819f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten            mRemainingFrames = misalignment;
21828edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung            return ((double)mRemainingFrames * 1100000000) / ((double)sampleRate * speed);
21839f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        }
21849f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten#endif
21859f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
218689fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    }
2187ea2b9c07b34079f0dbd8610a511e006e69a15adcAndy Hung    if (writtenFrames > 0) {
2188ea2b9c07b34079f0dbd8610a511e006e69a15adcAndy Hung        AutoMutex lock(mLock);
2189ea2b9c07b34079f0dbd8610a511e006e69a15adcAndy Hung        mFramesWritten += writtenFrames;
2190ea2b9c07b34079f0dbd8610a511e006e69a15adcAndy Hung    }
21919f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    mRemainingFrames = notificationFrames;
21929f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    mRetryOnPartialBuffer = true;
21939f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
21949f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    // A lot has transpired since ns was calculated, so run again immediately and re-calculate
21959f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    return 0;
219689fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project}
219789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
21989f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kastenstatus_t AudioTrack::restoreTrack_l(const char *from)
21991703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent{
2200b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald    ALOGW("dead IAudioTrack, %s, creating a new one from %s()",
2201ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent          isOffloadedOrDirect_l() ? "Offloaded or Direct" : "PCM", from);
22029f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    ++mSequence;
22031703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent
2204a47f3165f53c8e8fb8907a94de7417e2c3047eebGlenn Kasten    // refresh the audio configuration cache in this process to make sure we get new
2205d2d089fc86c62843992e7d5b371ee9227189a1e6Glenn Kasten    // output parameters and new IAudioFlinger in createTrack_l()
2206a47f3165f53c8e8fb8907a94de7417e2c3047eebGlenn Kasten    AudioSystem::clearAudioConfigCache();
2207a47f3165f53c8e8fb8907a94de7417e2c3047eebGlenn Kasten
2208faeb0f291330134dc4468359a36e099aae508449Ronghua Wu    if (isOffloadedOrDirect_l() || mDoNotReconnect) {
22091f1db8356b599bc40703c907fb69e6e539343532Andy Hung        // FIXME re-creation of offloaded and direct tracks is not yet implemented;
22101f1db8356b599bc40703c907fb69e6e539343532Andy Hung        // reconsider enabling for linear PCM encodings when position can be preserved.
2211b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        return DEAD_OBJECT;
2212b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald    }
2213b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald
22142812d9ea3a3a33142dd8e23c9d949c498d6f7a12Phil Burk    // Save so we can return count since creation.
22152812d9ea3a3a33142dd8e23c9d949c498d6f7a12Phil Burk    mUnderrunCountOffset = getUnderrunCount_l();
22162812d9ea3a3a33142dd8e23c9d949c498d6f7a12Phil Burk
2217200092b7f21d2b98f30b800e79d152636f9ba225Glenn Kasten    // save the old static buffer position
2218f20a4e9f84bbb8748f28ca326caeba7a9947a369Andy Hung    uint32_t staticPosition = 0;
22194ede21d9c1f957baf5e561849ff9bbe4bcbefc20Andy Hung    size_t bufferPosition = 0;
22204ede21d9c1f957baf5e561849ff9bbe4bcbefc20Andy Hung    int loopCount = 0;
22214ede21d9c1f957baf5e561849ff9bbe4bcbefc20Andy Hung    if (mStaticProxy != 0) {
22224ede21d9c1f957baf5e561849ff9bbe4bcbefc20Andy Hung        mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
2223f20a4e9f84bbb8748f28ca326caeba7a9947a369Andy Hung        staticPosition = mStaticProxy->getPosition().unsignedValue();
22244ede21d9c1f957baf5e561849ff9bbe4bcbefc20Andy Hung    }
2225200092b7f21d2b98f30b800e79d152636f9ba225Glenn Kasten
2226ae34ed2bcc9fa49a22fe7497327adb689ef27e8dHaynes Mathew George    mFlags = mOrigFlags;
2227ae34ed2bcc9fa49a22fe7497327adb689ef27e8dHaynes Mathew George
2228200092b7f21d2b98f30b800e79d152636f9ba225Glenn Kasten    // If a new IAudioTrack is successfully created, createTrack_l() will modify the
2229a47f3165f53c8e8fb8907a94de7417e2c3047eebGlenn Kasten    // following member variables: mAudioTrack, mCblkMemory and mCblk.
2230200092b7f21d2b98f30b800e79d152636f9ba225Glenn Kasten    // It will also delete the strong references on previous IAudioTrack and IMemory.
2231200092b7f21d2b98f30b800e79d152636f9ba225Glenn Kasten    // If a new IAudioTrack cannot be created, the previous (dead) instance will be left intact.
2232ae4b879d04c4b07c62241a8f507c8dce11e628e4Glenn Kasten    status_t result = createTrack_l();
2233cc21e4f1e41dfa17e7e2bef995fcd22c45f6bcd0Eric Laurent
2234a47f3165f53c8e8fb8907a94de7417e2c3047eebGlenn Kasten    if (result == NO_ERROR) {
2235d7bd69e4d1e74f25413721804d5290c53ea87f2bAndy Hung        // take the frames that will be lost by track recreation into account in saved position
2236d7bd69e4d1e74f25413721804d5290c53ea87f2bAndy Hung        // For streaming tracks, this is the amount we obtained from the user/client
2237d7bd69e4d1e74f25413721804d5290c53ea87f2bAndy Hung        // (not the number actually consumed at the server - those are already lost).
2238d7bd69e4d1e74f25413721804d5290c53ea87f2bAndy Hung        if (mStaticProxy == 0) {
2239d7bd69e4d1e74f25413721804d5290c53ea87f2bAndy Hung            mPosition = mReleased;
2240d7bd69e4d1e74f25413721804d5290c53ea87f2bAndy Hung        }
22414ede21d9c1f957baf5e561849ff9bbe4bcbefc20Andy Hung        // Continue playback from last known position and restore loop.
22424ede21d9c1f957baf5e561849ff9bbe4bcbefc20Andy Hung        if (mStaticProxy != 0) {
22434ede21d9c1f957baf5e561849ff9bbe4bcbefc20Andy Hung            if (loopCount != 0) {
22444ede21d9c1f957baf5e561849ff9bbe4bcbefc20Andy Hung                mStaticProxy->setBufferPositionAndLoop(bufferPosition,
22454ede21d9c1f957baf5e561849ff9bbe4bcbefc20Andy Hung                        mLoopStart, mLoopEnd, loopCount);
22464ede21d9c1f957baf5e561849ff9bbe4bcbefc20Andy Hung            } else {
22474ede21d9c1f957baf5e561849ff9bbe4bcbefc20Andy Hung                mStaticProxy->setBufferPosition(bufferPosition);
224853c3b5fc1afe162a8669cb3d27d6bb14e1847e39Andy Hung                if (bufferPosition == mFrameCount) {
224953c3b5fc1afe162a8669cb3d27d6bb14e1847e39Andy Hung                    ALOGD("restoring track at end of static buffer");
225053c3b5fc1afe162a8669cb3d27d6bb14e1847e39Andy Hung                }
22511703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent            }
22521703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent        }
22534ef88d7106c01f81109ee163cb6789073d80c6aeAndy Hung        // restore volume handler
22544ef88d7106c01f81109ee163cb6789073d80c6aeAndy Hung        mVolumeHandler->forall([this](const sp<VolumeShaper::Configuration> &configuration,
22554ef88d7106c01f81109ee163cb6789073d80c6aeAndy Hung                const sp<VolumeShaper::Operation> &operation) -> VolumeShaper::Status {
22564ef88d7106c01f81109ee163cb6789073d80c6aeAndy Hung            sp<VolumeShaper::Operation> operationToEnd = new VolumeShaper::Operation(*operation);
22574ef88d7106c01f81109ee163cb6789073d80c6aeAndy Hung            // TODO: Ideally we would restore to the exact xOffset position
22584ef88d7106c01f81109ee163cb6789073d80c6aeAndy Hung            // as returned by getVolumeShaperState(), but we don't have that
22594ef88d7106c01f81109ee163cb6789073d80c6aeAndy Hung            // information when restoring at the client unless we periodically poll
22604ef88d7106c01f81109ee163cb6789073d80c6aeAndy Hung            // the server or create shared memory state.
22614ef88d7106c01f81109ee163cb6789073d80c6aeAndy Hung            //
22624ef88d7106c01f81109ee163cb6789073d80c6aeAndy Hung            // For now, we simply advance to the end of the VolumeShaper effect.
22634ef88d7106c01f81109ee163cb6789073d80c6aeAndy Hung            operationToEnd->setXOffset(1.f);
22644ef88d7106c01f81109ee163cb6789073d80c6aeAndy Hung            return mAudioTrack->applyVolumeShaper(configuration, operationToEnd);
22654ef88d7106c01f81109ee163cb6789073d80c6aeAndy Hung        });
22664ef88d7106c01f81109ee163cb6789073d80c6aeAndy Hung
22679f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        if (mState == STATE_ACTIVE) {
2268a47f3165f53c8e8fb8907a94de7417e2c3047eebGlenn Kasten            result = mAudioTrack->start();
22691703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent        }
2270f20a4e9f84bbb8748f28ca326caeba7a9947a369Andy Hung        // server resets to zero so we offset
2271f20a4e9f84bbb8748f28ca326caeba7a9947a369Andy Hung        mFramesWrittenServerOffset =
2272f20a4e9f84bbb8748f28ca326caeba7a9947a369Andy Hung                mStaticProxy.get() != nullptr ? staticPosition : mFramesWritten;
2273f20a4e9f84bbb8748f28ca326caeba7a9947a369Andy Hung        mFramesWrittenAtRestore = mFramesWrittenServerOffset;
22741703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent    }
22759f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    if (result != NO_ERROR) {
22769f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        ALOGW("restoreTrack_l() failed status %d", result);
22779f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        mState = STATE_STOPPED;
2278c2813e568aa476e03d159529c0af28c99536db8dAndy Hung        mReleased = 0;
22791703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent    }
22801703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent
22811703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent    return result;
22821703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent}
22831703cdfee717b1b312bf8979816a9e2f16a82e5dEric Laurent
228490e8a97dd5c9d391d7a2ea6a2290ed976f928379Andy HungModulo<uint32_t> AudioTrack::updateAndGetPosition_l()
2285200092b7f21d2b98f30b800e79d152636f9ba225Glenn Kasten{
2286200092b7f21d2b98f30b800e79d152636f9ba225Glenn Kasten    // This is the sole place to read server consumed frames
228790e8a97dd5c9d391d7a2ea6a2290ed976f928379Andy Hung    Modulo<uint32_t> newServer(mProxy->getPosition());
228890e8a97dd5c9d391d7a2ea6a2290ed976f928379Andy Hung    const int32_t delta = (newServer - mServer).signedValue();
2289200092b7f21d2b98f30b800e79d152636f9ba225Glenn Kasten    // TODO There is controversy about whether there can be "negative jitter" in server position.
2290200092b7f21d2b98f30b800e79d152636f9ba225Glenn Kasten    //      This should be investigated further, and if possible, it should be addressed.
2291200092b7f21d2b98f30b800e79d152636f9ba225Glenn Kasten    //      A more definite failure mode is infrequent polling by client.
2292200092b7f21d2b98f30b800e79d152636f9ba225Glenn Kasten    //      One could call (void)getPosition_l() in releaseBuffer(),
2293200092b7f21d2b98f30b800e79d152636f9ba225Glenn Kasten    //      so mReleased and mPosition are always lock-step as best possible.
2294200092b7f21d2b98f30b800e79d152636f9ba225Glenn Kasten    //      That should ensure delta never goes negative for infrequent polling
2295200092b7f21d2b98f30b800e79d152636f9ba225Glenn Kasten    //      unless the server has more than 2^31 frames in its buffer,
2296200092b7f21d2b98f30b800e79d152636f9ba225Glenn Kasten    //      in which case the use of uint32_t for these counters has bigger issues.
229790e8a97dd5c9d391d7a2ea6a2290ed976f928379Andy Hung    ALOGE_IF(delta < 0,
229890e8a97dd5c9d391d7a2ea6a2290ed976f928379Andy Hung            "detected illegal retrograde motion by the server: mServer advanced by %d",
229990e8a97dd5c9d391d7a2ea6a2290ed976f928379Andy Hung            delta);
2300039c27aeaee809182fc1491311ca6dcbc1ec441bChad Brubaker    mServer = newServer;
230190e8a97dd5c9d391d7a2ea6a2290ed976f928379Andy Hung    if (delta > 0) { // avoid retrograde
230290e8a97dd5c9d391d7a2ea6a2290ed976f928379Andy Hung        mPosition += delta;
230390e8a97dd5c9d391d7a2ea6a2290ed976f928379Andy Hung    }
230490e8a97dd5c9d391d7a2ea6a2290ed976f928379Andy Hung    return mPosition;
2305200092b7f21d2b98f30b800e79d152636f9ba225Glenn Kasten}
2306200092b7f21d2b98f30b800e79d152636f9ba225Glenn Kasten
23078edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hungbool AudioTrack::isSampleRateSpeedAllowed_l(uint32_t sampleRate, float speed) const
23088edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung{
23098edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung    // applicable for mixing tracks only (not offloaded or direct)
23108edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung    if (mStaticProxy != 0) {
23118edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung        return true; // static tracks do not have issues with buffer sizing.
23128edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung    }
23138edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung    const size_t minFrameCount =
2314ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten            calculateMinFrameCount(mAfLatency, mAfFrameCount, mAfSampleRate, sampleRate, speed
2315ea38ee7742e799b23bd8675f5801ef72f94de0f4Glenn Kasten                /*, 0 mNotificationsPerBufferReq*/);
23168edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung    ALOGV("isSampleRateSpeedAllowed_l mFrameCount %zu  minFrameCount %zu",
23178edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung            mFrameCount, minFrameCount);
23188edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung    return mFrameCount >= minFrameCount;
23198edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung}
23208edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung
2321ad3af3305f024bcbbd55c894a4995e449498e1baRichard Fitzgeraldstatus_t AudioTrack::setParameters(const String8& keyValuePairs)
2322ad3af3305f024bcbbd55c894a4995e449498e1baRichard Fitzgerald{
2323ad3af3305f024bcbbd55c894a4995e449498e1baRichard Fitzgerald    AutoMutex lock(mLock);
232453cec22821072719ee02c856e9ac2dda2496c570Glenn Kasten    return mAudioTrack->setParameters(keyValuePairs);
2325ad3af3305f024bcbbd55c894a4995e449498e1baRichard Fitzgerald}
2326ad3af3305f024bcbbd55c894a4995e449498e1baRichard Fitzgerald
23279fc8b5cd4a64ef07e84c69112461324d5c13a0b0Andy HungVolumeShaper::Status AudioTrack::applyVolumeShaper(
23289fc8b5cd4a64ef07e84c69112461324d5c13a0b0Andy Hung        const sp<VolumeShaper::Configuration>& configuration,
23299fc8b5cd4a64ef07e84c69112461324d5c13a0b0Andy Hung        const sp<VolumeShaper::Operation>& operation)
23309fc8b5cd4a64ef07e84c69112461324d5c13a0b0Andy Hung{
23319fc8b5cd4a64ef07e84c69112461324d5c13a0b0Andy Hung    AutoMutex lock(mLock);
23324ef88d7106c01f81109ee163cb6789073d80c6aeAndy Hung    mVolumeHandler->setIdIfNecessary(configuration);
23339fc8b5cd4a64ef07e84c69112461324d5c13a0b0Andy Hung    VolumeShaper::Status status = mAudioTrack->applyVolumeShaper(configuration, operation);
23344ef88d7106c01f81109ee163cb6789073d80c6aeAndy Hung    if (status >= 0) {
23354ef88d7106c01f81109ee163cb6789073d80c6aeAndy Hung        // save VolumeShaper for restore
23364ef88d7106c01f81109ee163cb6789073d80c6aeAndy Hung        mVolumeHandler->applyVolumeShaper(configuration, operation);
23374ef88d7106c01f81109ee163cb6789073d80c6aeAndy Hung    }
23389fc8b5cd4a64ef07e84c69112461324d5c13a0b0Andy Hung    return status;
23399fc8b5cd4a64ef07e84c69112461324d5c13a0b0Andy Hung}
23409fc8b5cd4a64ef07e84c69112461324d5c13a0b0Andy Hung
23419fc8b5cd4a64ef07e84c69112461324d5c13a0b0Andy Hungsp<VolumeShaper::State> AudioTrack::getVolumeShaperState(int id)
23429fc8b5cd4a64ef07e84c69112461324d5c13a0b0Andy Hung{
23439fc8b5cd4a64ef07e84c69112461324d5c13a0b0Andy Hung    // TODO: To properly restore the AudioTrack
23449fc8b5cd4a64ef07e84c69112461324d5c13a0b0Andy Hung    // we will need to save the last state in AudioTrackShared.
23459fc8b5cd4a64ef07e84c69112461324d5c13a0b0Andy Hung    AutoMutex lock(mLock);
23469fc8b5cd4a64ef07e84c69112461324d5c13a0b0Andy Hung    return mAudioTrack->getVolumeShaperState(id);
23479fc8b5cd4a64ef07e84c69112461324d5c13a0b0Andy Hung}
23489fc8b5cd4a64ef07e84c69112461324d5c13a0b0Andy Hung
2349ea2b9c07b34079f0dbd8610a511e006e69a15adcAndy Hungstatus_t AudioTrack::getTimestamp(ExtendedTimestamp *timestamp)
2350ea2b9c07b34079f0dbd8610a511e006e69a15adcAndy Hung{
2351ea2b9c07b34079f0dbd8610a511e006e69a15adcAndy Hung    if (timestamp == nullptr) {
2352ea2b9c07b34079f0dbd8610a511e006e69a15adcAndy Hung        return BAD_VALUE;
2353ea2b9c07b34079f0dbd8610a511e006e69a15adcAndy Hung    }
2354ea2b9c07b34079f0dbd8610a511e006e69a15adcAndy Hung    AutoMutex lock(mLock);
2355e13f8a603867280de9b02ce4839202a182556416Andy Hung    return getTimestamp_l(timestamp);
2356e13f8a603867280de9b02ce4839202a182556416Andy Hung}
2357e13f8a603867280de9b02ce4839202a182556416Andy Hung
2358e13f8a603867280de9b02ce4839202a182556416Andy Hungstatus_t AudioTrack::getTimestamp_l(ExtendedTimestamp *timestamp)
2359e13f8a603867280de9b02ce4839202a182556416Andy Hung{
2360ea2b9c07b34079f0dbd8610a511e006e69a15adcAndy Hung    if (mCblk->mFlags & CBLK_INVALID) {
2361ea2b9c07b34079f0dbd8610a511e006e69a15adcAndy Hung        const status_t status = restoreTrack_l("getTimestampExtended");
2362ea2b9c07b34079f0dbd8610a511e006e69a15adcAndy Hung        if (status != OK) {
2363ea2b9c07b34079f0dbd8610a511e006e69a15adcAndy Hung            // per getTimestamp() API doc in header, we return DEAD_OBJECT here,
2364ea2b9c07b34079f0dbd8610a511e006e69a15adcAndy Hung            // recommending that the track be recreated.
2365ea2b9c07b34079f0dbd8610a511e006e69a15adcAndy Hung            return DEAD_OBJECT;
2366ea2b9c07b34079f0dbd8610a511e006e69a15adcAndy Hung        }
2367ea2b9c07b34079f0dbd8610a511e006e69a15adcAndy Hung    }
2368ea2b9c07b34079f0dbd8610a511e006e69a15adcAndy Hung    // check for offloaded/direct here in case restoring somehow changed those flags.
2369ea2b9c07b34079f0dbd8610a511e006e69a15adcAndy Hung    if (isOffloadedOrDirect_l()) {
2370ea2b9c07b34079f0dbd8610a511e006e69a15adcAndy Hung        return INVALID_OPERATION; // not supported
2371ea2b9c07b34079f0dbd8610a511e006e69a15adcAndy Hung    }
2372ea2b9c07b34079f0dbd8610a511e006e69a15adcAndy Hung    status_t status = mProxy->getTimestamp(timestamp);
2373e1e9846a786a0d77a13b44f8e798e03b4cba9d77Andy Hung    LOG_ALWAYS_FATAL_IF(status != OK, "status %d not allowed from proxy getTimestamp", status);
2374ea2b9c07b34079f0dbd8610a511e006e69a15adcAndy Hung    bool found = false;
2375e1e9846a786a0d77a13b44f8e798e03b4cba9d77Andy Hung    timestamp->mPosition[ExtendedTimestamp::LOCATION_CLIENT] = mFramesWritten;
2376e1e9846a786a0d77a13b44f8e798e03b4cba9d77Andy Hung    timestamp->mTimeNs[ExtendedTimestamp::LOCATION_CLIENT] = 0;
2377e1e9846a786a0d77a13b44f8e798e03b4cba9d77Andy Hung    // server side frame offset in case AudioTrack has been restored.
2378e1e9846a786a0d77a13b44f8e798e03b4cba9d77Andy Hung    for (int i = ExtendedTimestamp::LOCATION_SERVER;
2379e1e9846a786a0d77a13b44f8e798e03b4cba9d77Andy Hung            i < ExtendedTimestamp::LOCATION_MAX; ++i) {
2380e1e9846a786a0d77a13b44f8e798e03b4cba9d77Andy Hung        if (timestamp->mTimeNs[i] >= 0) {
2381e1e9846a786a0d77a13b44f8e798e03b4cba9d77Andy Hung            // apply server offset (frames flushed is ignored
2382e1e9846a786a0d77a13b44f8e798e03b4cba9d77Andy Hung            // so we don't report the jump when the flush occurs).
2383e1e9846a786a0d77a13b44f8e798e03b4cba9d77Andy Hung            timestamp->mPosition[i] += mFramesWrittenServerOffset;
2384e1e9846a786a0d77a13b44f8e798e03b4cba9d77Andy Hung            found = true;
2385ea2b9c07b34079f0dbd8610a511e006e69a15adcAndy Hung        }
2386ea2b9c07b34079f0dbd8610a511e006e69a15adcAndy Hung    }
2387ea2b9c07b34079f0dbd8610a511e006e69a15adcAndy Hung    return found ? OK : WOULD_BLOCK;
2388ea2b9c07b34079f0dbd8610a511e006e69a15adcAndy Hung}
2389ea2b9c07b34079f0dbd8610a511e006e69a15adcAndy Hung
2390ce70374bf105f8a6160bf5dd70affea012b2a464Glenn Kastenstatus_t AudioTrack::getTimestamp(AudioTimestamp& timestamp)
2391ce70374bf105f8a6160bf5dd70affea012b2a464Glenn Kasten{
239253cec22821072719ee02c856e9ac2dda2496c570Glenn Kasten    AutoMutex lock(mLock);
239365ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung    return getTimestamp_l(timestamp);
239465ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung}
23951b42097f38e72574ed853a35f4e8a66e4739c421Phil Burk
239665ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hungstatus_t AudioTrack::getTimestamp_l(AudioTimestamp& timestamp)
239765ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung{
23981b42097f38e72574ed853a35f4e8a66e4739c421Phil Burk    bool previousTimestampValid = mPreviousTimestampValid;
23991b42097f38e72574ed853a35f4e8a66e4739c421Phil Burk    // Set false here to cover all the error return cases.
24001b42097f38e72574ed853a35f4e8a66e4739c421Phil Burk    mPreviousTimestampValid = false;
24011b42097f38e72574ed853a35f4e8a66e4739c421Phil Burk
24027f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung    switch (mState) {
24037f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung    case STATE_ACTIVE:
24047f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung    case STATE_PAUSED:
24057f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung        break; // handle below
24067f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung    case STATE_FLUSHED:
24077f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung    case STATE_STOPPED:
24087f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung        return WOULD_BLOCK;
24097f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung    case STATE_STOPPING:
24107f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung    case STATE_PAUSED_STOPPING:
24117f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung        if (!isOffloaded_l()) {
24127f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung            return INVALID_OPERATION;
24137f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung        }
24147f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung        break; // offloaded tracks handled below
24157f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung    default:
24167f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung        LOG_ALWAYS_FATAL("Invalid mState in getTimestamp(): %d", mState);
24177f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung        break;
2418fe346c707f59d763ded93bc3d27b51f0c0408258Glenn Kasten    }
24197f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung
2420275e8e9de2e11b4b344f5a201f1f0e51fda02d9cEric Laurent    if (mCblk->mFlags & CBLK_INVALID) {
24216653c935d2518a713587b3887ca09aa09ebfa7fdAndy Hung        const status_t status = restoreTrack_l("getTimestamp");
24226653c935d2518a713587b3887ca09aa09ebfa7fdAndy Hung        if (status != OK) {
24236653c935d2518a713587b3887ca09aa09ebfa7fdAndy Hung            // per getTimestamp() API doc in header, we return DEAD_OBJECT here,
24246653c935d2518a713587b3887ca09aa09ebfa7fdAndy Hung            // recommending that the track be recreated.
24256653c935d2518a713587b3887ca09aa09ebfa7fdAndy Hung            return DEAD_OBJECT;
24266653c935d2518a713587b3887ca09aa09ebfa7fdAndy Hung        }
2427275e8e9de2e11b4b344f5a201f1f0e51fda02d9cEric Laurent    }
2428275e8e9de2e11b4b344f5a201f1f0e51fda02d9cEric Laurent
2429200092b7f21d2b98f30b800e79d152636f9ba225Glenn Kasten    // The presented frame count must always lag behind the consumed frame count.
2430200092b7f21d2b98f30b800e79d152636f9ba225Glenn Kasten    // To avoid a race, read the presented frames first.  This ensures that presented <= consumed.
24316ae5843c281301a9ffd1059d185620a9337e15a2Andy Hung
24326ae5843c281301a9ffd1059d185620a9337e15a2Andy Hung    status_t status;
2433818e7a32ce3633980138aff2c2bfcc5158b3cfccAndy Hung    if (isOffloadedOrDirect_l()) {
24346ae5843c281301a9ffd1059d185620a9337e15a2Andy Hung        // use Binder to get timestamp
24356ae5843c281301a9ffd1059d185620a9337e15a2Andy Hung        status = mAudioTrack->getTimestamp(timestamp);
24366ae5843c281301a9ffd1059d185620a9337e15a2Andy Hung    } else {
24376ae5843c281301a9ffd1059d185620a9337e15a2Andy Hung        // read timestamp from shared memory
24386ae5843c281301a9ffd1059d185620a9337e15a2Andy Hung        ExtendedTimestamp ets;
24396ae5843c281301a9ffd1059d185620a9337e15a2Andy Hung        status = mProxy->getTimestamp(&ets);
24406ae5843c281301a9ffd1059d185620a9337e15a2Andy Hung        if (status == OK) {
2441b01faa31462e19957ae3c0c3ada07c9576a9494fAndy Hung            ExtendedTimestamp::Location location;
2442b01faa31462e19957ae3c0c3ada07c9576a9494fAndy Hung            status = ets.getBestTimestamp(&timestamp, &location);
2443b01faa31462e19957ae3c0c3ada07c9576a9494fAndy Hung
2444b01faa31462e19957ae3c0c3ada07c9576a9494fAndy Hung            if (status == OK) {
2445b01faa31462e19957ae3c0c3ada07c9576a9494fAndy Hung                // It is possible that the best location has moved from the kernel to the server.
2446b01faa31462e19957ae3c0c3ada07c9576a9494fAndy Hung                // In this case we adjust the position from the previous computed latency.
2447b01faa31462e19957ae3c0c3ada07c9576a9494fAndy Hung                if (location == ExtendedTimestamp::LOCATION_SERVER) {
2448b01faa31462e19957ae3c0c3ada07c9576a9494fAndy Hung                    ALOGW_IF(mPreviousLocation == ExtendedTimestamp::LOCATION_KERNEL,
2449b01faa31462e19957ae3c0c3ada07c9576a9494fAndy Hung                            "getTimestamp() location moved from kernel to server");
245007eee80b3422c0304491f24bbc415deb0badbefcAndy Hung                    // check that the last kernel OK time info exists and the positions
245107eee80b3422c0304491f24bbc415deb0badbefcAndy Hung                    // are valid (if they predate the current track, the positions may
245207eee80b3422c0304491f24bbc415deb0badbefcAndy Hung                    // be zero or negative).
2453b01faa31462e19957ae3c0c3ada07c9576a9494fAndy Hung                    const int64_t frames =
24546d7b119a416c9f10288051e562f294365e5d954cAndy Hung                            (ets.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] < 0 ||
245507eee80b3422c0304491f24bbc415deb0badbefcAndy Hung                            ets.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] < 0 ||
245607eee80b3422c0304491f24bbc415deb0badbefcAndy Hung                            ets.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] <= 0 ||
245707eee80b3422c0304491f24bbc415deb0badbefcAndy Hung                            ets.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] <= 0)
24586d7b119a416c9f10288051e562f294365e5d954cAndy Hung                            ?
24596d7b119a416c9f10288051e562f294365e5d954cAndy Hung                            int64_t((double)mAfLatency * mSampleRate * mPlaybackRate.mSpeed
24606d7b119a416c9f10288051e562f294365e5d954cAndy Hung                                    / 1000)
24616d7b119a416c9f10288051e562f294365e5d954cAndy Hung                            :
24626d7b119a416c9f10288051e562f294365e5d954cAndy Hung                            (ets.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK]
24636d7b119a416c9f10288051e562f294365e5d954cAndy Hung                            - ets.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK]);
24646d7b119a416c9f10288051e562f294365e5d954cAndy Hung                    ALOGV("frame adjustment:%lld  timestamp:%s",
24656d7b119a416c9f10288051e562f294365e5d954cAndy Hung                            (long long)frames, ets.toString().c_str());
2466b01faa31462e19957ae3c0c3ada07c9576a9494fAndy Hung                    if (frames >= ets.mPosition[location]) {
2467b01faa31462e19957ae3c0c3ada07c9576a9494fAndy Hung                        timestamp.mPosition = 0;
2468b01faa31462e19957ae3c0c3ada07c9576a9494fAndy Hung                    } else {
2469b01faa31462e19957ae3c0c3ada07c9576a9494fAndy Hung                        timestamp.mPosition = (uint32_t)(ets.mPosition[location] - frames);
2470b01faa31462e19957ae3c0c3ada07c9576a9494fAndy Hung                    }
247169488c4ef115c9de52c85f4fcae27c7774720298Andy Hung                } else if (location == ExtendedTimestamp::LOCATION_KERNEL) {
247269488c4ef115c9de52c85f4fcae27c7774720298Andy Hung                    ALOGV_IF(mPreviousLocation == ExtendedTimestamp::LOCATION_SERVER,
247369488c4ef115c9de52c85f4fcae27c7774720298Andy Hung                            "getTimestamp() location moved from server to kernel");
2474b01faa31462e19957ae3c0c3ada07c9576a9494fAndy Hung                }
24755d313803bdd61d59f28e518e7a793f33832f1901Andy Hung
24765d313803bdd61d59f28e518e7a793f33832f1901Andy Hung                // We update the timestamp time even when paused.
24775d313803bdd61d59f28e518e7a793f33832f1901Andy Hung                if (mState == STATE_PAUSED /* not needed: STATE_PAUSED_STOPPING */) {
24785d313803bdd61d59f28e518e7a793f33832f1901Andy Hung                    const int64_t now = systemTime();
24795d313803bdd61d59f28e518e7a793f33832f1901Andy Hung                    const int64_t at = convertTimespecToNs(timestamp.mTime);
24805d313803bdd61d59f28e518e7a793f33832f1901Andy Hung                    const int64_t lag =
24815d313803bdd61d59f28e518e7a793f33832f1901Andy Hung                            (ets.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] < 0 ||
24825d313803bdd61d59f28e518e7a793f33832f1901Andy Hung                                ets.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] < 0)
24835d313803bdd61d59f28e518e7a793f33832f1901Andy Hung                            ? int64_t(mAfLatency * 1000000LL)
24845d313803bdd61d59f28e518e7a793f33832f1901Andy Hung                            : (ets.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK]
24855d313803bdd61d59f28e518e7a793f33832f1901Andy Hung                             - ets.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK])
24865d313803bdd61d59f28e518e7a793f33832f1901Andy Hung                             * NANOS_PER_SECOND / mSampleRate;
24875d313803bdd61d59f28e518e7a793f33832f1901Andy Hung                    const int64_t limit = now - lag; // no earlier than this limit
24885d313803bdd61d59f28e518e7a793f33832f1901Andy Hung                    if (at < limit) {
24895d313803bdd61d59f28e518e7a793f33832f1901Andy Hung                        ALOGV("timestamp pause lag:%lld adjusting from %lld to %lld",
24905d313803bdd61d59f28e518e7a793f33832f1901Andy Hung                                (long long)lag, (long long)at, (long long)limit);
24915d313803bdd61d59f28e518e7a793f33832f1901Andy Hung                        timestamp.mTime.tv_sec = limit / NANOS_PER_SECOND;
24925d313803bdd61d59f28e518e7a793f33832f1901Andy Hung                        timestamp.mTime.tv_nsec = limit % NANOS_PER_SECOND; // compiler opt.
24935d313803bdd61d59f28e518e7a793f33832f1901Andy Hung                    }
24945d313803bdd61d59f28e518e7a793f33832f1901Andy Hung                }
2495b01faa31462e19957ae3c0c3ada07c9576a9494fAndy Hung                mPreviousLocation = location;
2496b01faa31462e19957ae3c0c3ada07c9576a9494fAndy Hung            } else {
2497b01faa31462e19957ae3c0c3ada07c9576a9494fAndy Hung                // right after AudioTrack is started, one may not find a timestamp
2498b01faa31462e19957ae3c0c3ada07c9576a9494fAndy Hung                ALOGV("getBestTimestamp did not find timestamp");
2499b01faa31462e19957ae3c0c3ada07c9576a9494fAndy Hung            }
25006ae5843c281301a9ffd1059d185620a9337e15a2Andy Hung        }
25016ae5843c281301a9ffd1059d185620a9337e15a2Andy Hung        if (status == INVALID_OPERATION) {
2502f20a4e9f84bbb8748f28ca326caeba7a9947a369Andy Hung            // INVALID_OPERATION occurs when no timestamp has been issued by the server;
2503f20a4e9f84bbb8748f28ca326caeba7a9947a369Andy Hung            // other failures are signaled by a negative time.
2504f20a4e9f84bbb8748f28ca326caeba7a9947a369Andy Hung            // If we come out of FLUSHED or STOPPED where the position is known
2505f20a4e9f84bbb8748f28ca326caeba7a9947a369Andy Hung            // to be zero we convert this to WOULD_BLOCK (with the implicit meaning of
2506f20a4e9f84bbb8748f28ca326caeba7a9947a369Andy Hung            // "zero" for NuPlayer).  We don't convert for track restoration as position
2507f20a4e9f84bbb8748f28ca326caeba7a9947a369Andy Hung            // does not reset.
2508f20a4e9f84bbb8748f28ca326caeba7a9947a369Andy Hung            ALOGV("timestamp server offset:%lld restore frames:%lld",
2509f20a4e9f84bbb8748f28ca326caeba7a9947a369Andy Hung                    (long long)mFramesWrittenServerOffset, (long long)mFramesWrittenAtRestore);
2510f20a4e9f84bbb8748f28ca326caeba7a9947a369Andy Hung            if (mFramesWrittenServerOffset != mFramesWrittenAtRestore) {
2511f20a4e9f84bbb8748f28ca326caeba7a9947a369Andy Hung                status = WOULD_BLOCK;
2512f20a4e9f84bbb8748f28ca326caeba7a9947a369Andy Hung            }
25136ae5843c281301a9ffd1059d185620a9337e15a2Andy Hung        }
25146ae5843c281301a9ffd1059d185620a9337e15a2Andy Hung    }
25157f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung    if (status != NO_ERROR) {
2516dfc34daba6d6cb923683d96689a0cb7c7006eee5Glenn Kasten        ALOGV_IF(status != WOULD_BLOCK, "getTimestamp error:%#x", status);
25177f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung        return status;
25187f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung    }
25197f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung    if (isOffloadedOrDirect_l()) {
25207f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung        if (isOffloaded_l() && (mState == STATE_PAUSED || mState == STATE_PAUSED_STOPPING)) {
25217f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung            // use cached paused position in case another offloaded track is running.
25227f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung            timestamp.mPosition = mPausedPosition;
25237f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung            clock_gettime(CLOCK_MONOTONIC, &timestamp.mTime);
25245d313803bdd61d59f28e518e7a793f33832f1901Andy Hung            // TODO: adjust for delay
25257f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung            return NO_ERROR;
25267f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung        }
25277f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung
25287f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung        // Check whether a pending flush or stop has completed, as those commands may
2529c8e09c610fabc7390297ecb48e939acbdfe27325Andy Hung        // be asynchronous or return near finish or exhibit glitchy behavior.
2530c8e09c610fabc7390297ecb48e939acbdfe27325Andy Hung        //
2531c8e09c610fabc7390297ecb48e939acbdfe27325Andy Hung        // Originally this showed up as the first timestamp being a continuation of
2532c8e09c610fabc7390297ecb48e939acbdfe27325Andy Hung        // the previous song under gapless playback.
2533c8e09c610fabc7390297ecb48e939acbdfe27325Andy Hung        // However, we sometimes see zero timestamps, then a glitch of
2534c8e09c610fabc7390297ecb48e939acbdfe27325Andy Hung        // the previous song's position, and then correct timestamps afterwards.
25357f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung        if (mStartUs != 0 && mSampleRate != 0) {
25367f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung            static const int kTimeJitterUs = 100000; // 100 ms
25377f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung            static const int k1SecUs = 1000000;
25387f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung
25397f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung            const int64_t timeNow = getNowUs();
25407f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung
25417f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung            if (timeNow < mStartUs + k1SecUs) { // within first second of starting
25427f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung                const int64_t timestampTimeUs = convertTimespecToUs(timestamp.mTime);
25437f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung                if (timestampTimeUs < mStartUs) {
25447f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung                    return WOULD_BLOCK;  // stale timestamp time, occurs before start.
25457f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung                }
25467f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung                const int64_t deltaTimeUs = timestampTimeUs - mStartUs;
25478edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung                const int64_t deltaPositionByUs = (double)timestamp.mPosition * 1000000
25485a8a95de6dad1a3bcf3da5a37b35766e89086e13Ricardo Garcia                        / ((double)mSampleRate * mPlaybackRate.mSpeed);
25497f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung
25507f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung                if (deltaPositionByUs > deltaTimeUs + kTimeJitterUs) {
25517f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung                    // Verify that the counter can't count faster than the sample rate
2552c8e09c610fabc7390297ecb48e939acbdfe27325Andy Hung                    // since the start time.  If greater, then that means we may have failed
25537f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung                    // to completely flush or stop the previous playing track.
2554c8e09c610fabc7390297ecb48e939acbdfe27325Andy Hung                    ALOGW_IF(!mTimestampStartupGlitchReported,
2555c8e09c610fabc7390297ecb48e939acbdfe27325Andy Hung                            "getTimestamp startup glitch detected"
25567f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung                            " deltaTimeUs(%lld) deltaPositionUs(%lld) tsmPosition(%u)",
25577f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung                            (long long)deltaTimeUs, (long long)deltaPositionByUs,
25587f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung                            timestamp.mPosition);
2559c8e09c610fabc7390297ecb48e939acbdfe27325Andy Hung                    mTimestampStartupGlitchReported = true;
2560c8e09c610fabc7390297ecb48e939acbdfe27325Andy Hung                    if (previousTimestampValid
2561c8e09c610fabc7390297ecb48e939acbdfe27325Andy Hung                            && mPreviousTimestamp.mPosition == 0 /* should be true if valid */) {
2562c8e09c610fabc7390297ecb48e939acbdfe27325Andy Hung                        timestamp = mPreviousTimestamp;
2563c8e09c610fabc7390297ecb48e939acbdfe27325Andy Hung                        mPreviousTimestampValid = true;
2564c8e09c610fabc7390297ecb48e939acbdfe27325Andy Hung                        return NO_ERROR;
2565c8e09c610fabc7390297ecb48e939acbdfe27325Andy Hung                    }
25667f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung                    return WOULD_BLOCK;
25677f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung                }
2568c8e09c610fabc7390297ecb48e939acbdfe27325Andy Hung                if (deltaPositionByUs != 0) {
2569c8e09c610fabc7390297ecb48e939acbdfe27325Andy Hung                    mStartUs = 0; // don't check again, we got valid nonzero position.
2570c8e09c610fabc7390297ecb48e939acbdfe27325Andy Hung                }
2571c8e09c610fabc7390297ecb48e939acbdfe27325Andy Hung            } else {
2572c8e09c610fabc7390297ecb48e939acbdfe27325Andy Hung                mStartUs = 0; // don't check again, start time expired.
25737f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung            }
2574c8e09c610fabc7390297ecb48e939acbdfe27325Andy Hung            mTimestampStartupGlitchReported = false;
25757f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung        }
25767f1bc8af1c46695191bf7e2aba6467f3616629c0Andy Hung    } else {
2577200092b7f21d2b98f30b800e79d152636f9ba225Glenn Kasten        // Update the mapping between local consumed (mPosition) and server consumed (mServer)
2578200092b7f21d2b98f30b800e79d152636f9ba225Glenn Kasten        (void) updateAndGetPosition_l();
2579200092b7f21d2b98f30b800e79d152636f9ba225Glenn Kasten        // Server consumed (mServer) and presented both use the same server time base,
2580200092b7f21d2b98f30b800e79d152636f9ba225Glenn Kasten        // and server consumed is always >= presented.
2581200092b7f21d2b98f30b800e79d152636f9ba225Glenn Kasten        // The delta between these represents the number of frames in the buffer pipeline.
2582200092b7f21d2b98f30b800e79d152636f9ba225Glenn Kasten        // If this delta between these is greater than the client position, it means that
2583200092b7f21d2b98f30b800e79d152636f9ba225Glenn Kasten        // actually presented is still stuck at the starting line (figuratively speaking),
2584200092b7f21d2b98f30b800e79d152636f9ba225Glenn Kasten        // waiting for the first frame to go by.  So we can't report a valid timestamp yet.
258590e8a97dd5c9d391d7a2ea6a2290ed976f928379Andy Hung        // Note: We explicitly use non-Modulo comparison here - potential wrap issue when
258690e8a97dd5c9d391d7a2ea6a2290ed976f928379Andy Hung        // mPosition exceeds 32 bits.
258790e8a97dd5c9d391d7a2ea6a2290ed976f928379Andy Hung        // TODO Remove when timestamp is updated to contain pipeline status info.
258890e8a97dd5c9d391d7a2ea6a2290ed976f928379Andy Hung        const int32_t pipelineDepthInFrames = (mServer - timestamp.mPosition).signedValue();
258990e8a97dd5c9d391d7a2ea6a2290ed976f928379Andy Hung        if (pipelineDepthInFrames > 0 /* should be true, but we check anyways */
259090e8a97dd5c9d391d7a2ea6a2290ed976f928379Andy Hung                && (uint32_t)pipelineDepthInFrames > mPosition.value()) {
2591200092b7f21d2b98f30b800e79d152636f9ba225Glenn Kasten            return INVALID_OPERATION;
2592200092b7f21d2b98f30b800e79d152636f9ba225Glenn Kasten        }
2593200092b7f21d2b98f30b800e79d152636f9ba225Glenn Kasten        // Convert timestamp position from server time base to client time base.
2594200092b7f21d2b98f30b800e79d152636f9ba225Glenn Kasten        // TODO The following code should work OK now because timestamp.mPosition is 32-bit.
2595200092b7f21d2b98f30b800e79d152636f9ba225Glenn Kasten        // But if we change it to 64-bit then this could fail.
259690e8a97dd5c9d391d7a2ea6a2290ed976f928379Andy Hung        // Use Modulo computation here.
259790e8a97dd5c9d391d7a2ea6a2290ed976f928379Andy Hung        timestamp.mPosition = (mPosition - mServer + timestamp.mPosition).value();
2598200092b7f21d2b98f30b800e79d152636f9ba225Glenn Kasten        // Immediately after a call to getPosition_l(), mPosition and
2599200092b7f21d2b98f30b800e79d152636f9ba225Glenn Kasten        // mServer both represent the same frame position.  mPosition is
2600200092b7f21d2b98f30b800e79d152636f9ba225Glenn Kasten        // in client's point of view, and mServer is in server's point of
2601200092b7f21d2b98f30b800e79d152636f9ba225Glenn Kasten        // view.  So the difference between them is the "fudge factor"
2602200092b7f21d2b98f30b800e79d152636f9ba225Glenn Kasten        // between client and server views due to stop() and/or new
2603200092b7f21d2b98f30b800e79d152636f9ba225Glenn Kasten        // IAudioTrack.  And timestamp.mPosition is initially in server's
2604200092b7f21d2b98f30b800e79d152636f9ba225Glenn Kasten        // point of view, so we need to apply the same fudge factor to it.
2605fe346c707f59d763ded93bc3d27b51f0c0408258Glenn Kasten    }
26061b42097f38e72574ed853a35f4e8a66e4739c421Phil Burk
26071b42097f38e72574ed853a35f4e8a66e4739c421Phil Burk    // Prevent retrograde motion in timestamp.
26081b42097f38e72574ed853a35f4e8a66e4739c421Phil Burk    // This is sometimes caused by erratic reports of the available space in the ALSA drivers.
26091b42097f38e72574ed853a35f4e8a66e4739c421Phil Burk    if (status == NO_ERROR) {
26101b42097f38e72574ed853a35f4e8a66e4739c421Phil Burk        if (previousTimestampValid) {
26115d313803bdd61d59f28e518e7a793f33832f1901Andy Hung            const int64_t previousTimeNanos = convertTimespecToNs(mPreviousTimestamp.mTime);
26125d313803bdd61d59f28e518e7a793f33832f1901Andy Hung            const int64_t currentTimeNanos = convertTimespecToNs(timestamp.mTime);
26131b42097f38e72574ed853a35f4e8a66e4739c421Phil Burk            if (currentTimeNanos < previousTimeNanos) {
26145d313803bdd61d59f28e518e7a793f33832f1901Andy Hung                ALOGW("retrograde timestamp time corrected, %lld < %lld",
26155d313803bdd61d59f28e518e7a793f33832f1901Andy Hung                        (long long)currentTimeNanos, (long long)previousTimeNanos);
26165d313803bdd61d59f28e518e7a793f33832f1901Andy Hung                timestamp.mTime = mPreviousTimestamp.mTime;
26171b42097f38e72574ed853a35f4e8a66e4739c421Phil Burk            }
26181b42097f38e72574ed853a35f4e8a66e4739c421Phil Burk
26191b42097f38e72574ed853a35f4e8a66e4739c421Phil Burk            // Looking at signed delta will work even when the timestamps
26201b42097f38e72574ed853a35f4e8a66e4739c421Phil Burk            // are wrapping around.
262190e8a97dd5c9d391d7a2ea6a2290ed976f928379Andy Hung            int32_t deltaPosition = (Modulo<uint32_t>(timestamp.mPosition)
262290e8a97dd5c9d391d7a2ea6a2290ed976f928379Andy Hung                    - mPreviousTimestamp.mPosition).signedValue();
26234c5a3675ed6b429dfaa2707acf2b3faf2808baf2Phil Burk            if (deltaPosition < 0) {
26244c5a3675ed6b429dfaa2707acf2b3faf2808baf2Phil Burk                // Only report once per position instead of spamming the log.
26254c5a3675ed6b429dfaa2707acf2b3faf2808baf2Phil Burk                if (!mRetrogradeMotionReported) {
26264c5a3675ed6b429dfaa2707acf2b3faf2808baf2Phil Burk                    ALOGW("retrograde timestamp position corrected, %d = %u - %u",
26274c5a3675ed6b429dfaa2707acf2b3faf2808baf2Phil Burk                            deltaPosition,
26284c5a3675ed6b429dfaa2707acf2b3faf2808baf2Phil Burk                            timestamp.mPosition,
26294c5a3675ed6b429dfaa2707acf2b3faf2808baf2Phil Burk                            mPreviousTimestamp.mPosition);
26304c5a3675ed6b429dfaa2707acf2b3faf2808baf2Phil Burk                    mRetrogradeMotionReported = true;
26314c5a3675ed6b429dfaa2707acf2b3faf2808baf2Phil Burk                }
26324c5a3675ed6b429dfaa2707acf2b3faf2808baf2Phil Burk            } else {
26334c5a3675ed6b429dfaa2707acf2b3faf2808baf2Phil Burk                mRetrogradeMotionReported = false;
26344c5a3675ed6b429dfaa2707acf2b3faf2808baf2Phil Burk            }
26355d313803bdd61d59f28e518e7a793f33832f1901Andy Hung            if (deltaPosition < 0) {
26365d313803bdd61d59f28e518e7a793f33832f1901Andy Hung                timestamp.mPosition = mPreviousTimestamp.mPosition;
26375d313803bdd61d59f28e518e7a793f33832f1901Andy Hung                deltaPosition = 0;
26385d313803bdd61d59f28e518e7a793f33832f1901Andy Hung            }
26395d313803bdd61d59f28e518e7a793f33832f1901Andy Hung#if 0
26405d313803bdd61d59f28e518e7a793f33832f1901Andy Hung            // Uncomment this to verify audio timestamp rate.
26415d313803bdd61d59f28e518e7a793f33832f1901Andy Hung            const int64_t deltaTime =
26425d313803bdd61d59f28e518e7a793f33832f1901Andy Hung                    convertTimespecToNs(timestamp.mTime) - previousTimeNanos;
26435d313803bdd61d59f28e518e7a793f33832f1901Andy Hung            if (deltaTime != 0) {
26445d313803bdd61d59f28e518e7a793f33832f1901Andy Hung                const int64_t computedSampleRate =
26455d313803bdd61d59f28e518e7a793f33832f1901Andy Hung                        deltaPosition * (long long)NANOS_PER_SECOND / deltaTime;
26465d313803bdd61d59f28e518e7a793f33832f1901Andy Hung                ALOGD("computedSampleRate:%u  sampleRate:%u",
26475d313803bdd61d59f28e518e7a793f33832f1901Andy Hung                        (unsigned)computedSampleRate, mSampleRate);
26481b42097f38e72574ed853a35f4e8a66e4739c421Phil Burk            }
26495d313803bdd61d59f28e518e7a793f33832f1901Andy Hung#endif
26501b42097f38e72574ed853a35f4e8a66e4739c421Phil Burk        }
26511b42097f38e72574ed853a35f4e8a66e4739c421Phil Burk        mPreviousTimestamp = timestamp;
26521b42097f38e72574ed853a35f4e8a66e4739c421Phil Burk        mPreviousTimestampValid = true;
26531b42097f38e72574ed853a35f4e8a66e4739c421Phil Burk    }
26541b42097f38e72574ed853a35f4e8a66e4739c421Phil Burk
2655fe346c707f59d763ded93bc3d27b51f0c0408258Glenn Kasten    return status;
2656ce70374bf105f8a6160bf5dd70affea012b2a464Glenn Kasten}
2657ce70374bf105f8a6160bf5dd70affea012b2a464Glenn Kasten
2658ad3af3305f024bcbbd55c894a4995e449498e1baRichard FitzgeraldString8 AudioTrack::getParameters(const String8& keys)
2659ad3af3305f024bcbbd55c894a4995e449498e1baRichard Fitzgerald{
26602c6c5294388e251ebc1e00d6c8785190561c27fcGlenn Kasten    audio_io_handle_t output = getOutput();
2661142f519aa1acd5804d111e60d100f170fed28405Glenn Kasten    if (output != AUDIO_IO_HANDLE_NONE) {
26622c6c5294388e251ebc1e00d6c8785190561c27fcGlenn Kasten        return AudioSystem::getParameters(output, keys);
2663b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald    } else {
2664b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald        return String8::empty();
2665b1a270d1e926fb9a01b4265a7675ed0c2c8f4868Richard Fitzgerald    }
2666ad3af3305f024bcbbd55c894a4995e449498e1baRichard Fitzgerald}
2667ad3af3305f024bcbbd55c894a4995e449498e1baRichard Fitzgerald
266823a7545c4de71e989c2d8ebf1d5b9dcf463c36a9Glenn Kastenbool AudioTrack::isOffloaded() const
266923a7545c4de71e989c2d8ebf1d5b9dcf463c36a9Glenn Kasten{
267023a7545c4de71e989c2d8ebf1d5b9dcf463c36a9Glenn Kasten    AutoMutex lock(mLock);
267123a7545c4de71e989c2d8ebf1d5b9dcf463c36a9Glenn Kasten    return isOffloaded_l();
267223a7545c4de71e989c2d8ebf1d5b9dcf463c36a9Glenn Kasten}
267323a7545c4de71e989c2d8ebf1d5b9dcf463c36a9Glenn Kasten
2674ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurentbool AudioTrack::isDirect() const
2675ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent{
2676ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent    AutoMutex lock(mLock);
2677ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent    return isDirect_l();
2678ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent}
2679ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent
2680ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurentbool AudioTrack::isOffloadedOrDirect() const
2681ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent{
2682ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent    AutoMutex lock(mLock);
2683ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent    return isOffloadedOrDirect_l();
2684ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent}
2685ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent
2686ab5cdbaf65ca509681d2726aacdf3ac8bfb6b3faEric Laurent
26877c7be1e05634d96d08210efb4bdeb012ffba440dGlenn Kastenstatus_t AudioTrack::dump(int fd, const Vector<String16>& args __unused) const
268889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project{
268989fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
269089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    const size_t SIZE = 256;
269189fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    char buffer[SIZE];
269289fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    String8 result;
269389fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
269489fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    result.append(" AudioTrack::dump\n");
269585ab62c4b433df3f1a9826bed1c9bec07a86c750Glenn Kasten    snprintf(buffer, 255, "  stream type(%d), left - right volume(%f, %f)\n", mStreamType,
2696877a0ac7e8677fa1cbd0e8565ad9d38ba0db5fc0Glenn Kasten            mVolume[AUDIO_INTERLEAVE_LEFT], mVolume[AUDIO_INTERLEAVE_RIGHT]);
269789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    result.append(buffer);
2698377b2ec9a2885f9b6405b07ba900a9e3f4349c38Kévin PETIT    snprintf(buffer, 255, "  format(%d), channel count(%d), frame count(%zu)\n", mFormat,
2699b603744e96b07b1d5bf745bde593fb2c025cefcfGlenn Kasten            mChannelCount, mFrameCount);
270089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    result.append(buffer);
27018edb8dc44b8a2f81bdb5db645b6b708548771a31Andy Hung    snprintf(buffer, 255, "  sample rate(%u), speed(%f), status(%d)\n",
27025a8a95de6dad1a3bcf3da5a37b35766e89086e13Ricardo Garcia            mSampleRate, mPlaybackRate.mSpeed, mStatus);
270389fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    result.append(buffer);
27049f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    snprintf(buffer, 255, "  state(%d), latency (%d)\n", mState, mLatency);
270589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    result.append(buffer);
270689fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    ::write(fd, result.string(), result.size());
270789fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project    return NO_ERROR;
270889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project}
270989fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
27102812d9ea3a3a33142dd8e23c9d949c498d6f7a12Phil Burkuint32_t AudioTrack::getUnderrunCount() const
27112812d9ea3a3a33142dd8e23c9d949c498d6f7a12Phil Burk{
27122812d9ea3a3a33142dd8e23c9d949c498d6f7a12Phil Burk    AutoMutex lock(mLock);
27132812d9ea3a3a33142dd8e23c9d949c498d6f7a12Phil Burk    return getUnderrunCount_l();
27142812d9ea3a3a33142dd8e23c9d949c498d6f7a12Phil Burk}
27152812d9ea3a3a33142dd8e23c9d949c498d6f7a12Phil Burk
27162812d9ea3a3a33142dd8e23c9d949c498d6f7a12Phil Burkuint32_t AudioTrack::getUnderrunCount_l() const
27172812d9ea3a3a33142dd8e23c9d949c498d6f7a12Phil Burk{
27182812d9ea3a3a33142dd8e23c9d949c498d6f7a12Phil Burk    return mProxy->getUnderrunCount() + mUnderrunCountOffset;
27192812d9ea3a3a33142dd8e23c9d949c498d6f7a12Phil Burk}
27202812d9ea3a3a33142dd8e23c9d949c498d6f7a12Phil Burk
27219f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kastenuint32_t AudioTrack::getUnderrunFrames() const
27229f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten{
27239f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    AutoMutex lock(mLock);
27249f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    return mProxy->getUnderrunFrames();
27259f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten}
27269f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
2727296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurentstatus_t AudioTrack::addAudioDeviceCallback(const sp<AudioSystem::AudioDeviceCallback>& callback)
2728296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent{
2729296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent    if (callback == 0) {
2730296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent        ALOGW("%s adding NULL callback!", __FUNCTION__);
2731296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent        return BAD_VALUE;
2732296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent    }
2733296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent    AutoMutex lock(mLock);
2734296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent    if (mDeviceCallback == callback) {
2735296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent        ALOGW("%s adding same callback!", __FUNCTION__);
2736296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent        return INVALID_OPERATION;
2737296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent    }
2738296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent    status_t status = NO_ERROR;
2739296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent    if (mOutput != AUDIO_IO_HANDLE_NONE) {
2740296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent        if (mDeviceCallback != 0) {
2741296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent            ALOGW("%s callback already present!", __FUNCTION__);
2742296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent            AudioSystem::removeAudioDeviceCallback(mDeviceCallback, mOutput);
2743296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent        }
2744296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent        status = AudioSystem::addAudioDeviceCallback(callback, mOutput);
2745296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent    }
2746296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent    mDeviceCallback = callback;
2747296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent    return status;
2748296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent}
2749296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent
2750296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurentstatus_t AudioTrack::removeAudioDeviceCallback(
2751296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent        const sp<AudioSystem::AudioDeviceCallback>& callback)
2752296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent{
2753296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent    if (callback == 0) {
2754296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent        ALOGW("%s removing NULL callback!", __FUNCTION__);
2755296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent        return BAD_VALUE;
2756296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent    }
2757296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent    AutoMutex lock(mLock);
2758296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent    if (mDeviceCallback != callback) {
2759296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent        ALOGW("%s removing different callback!", __FUNCTION__);
2760296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent        return INVALID_OPERATION;
2761296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent    }
2762296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent    if (mOutput != AUDIO_IO_HANDLE_NONE) {
2763296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent        AudioSystem::removeAudioDeviceCallback(mDeviceCallback, mOutput);
2764296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent    }
2765296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent    mDeviceCallback = 0;
2766296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent    return NO_ERROR;
2767296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent}
2768296fb13dd9b5e90d6a05cce897c3b1e7914a478aEric Laurent
2769e13f8a603867280de9b02ce4839202a182556416Andy Hungstatus_t AudioTrack::pendingDuration(int32_t *msec, ExtendedTimestamp::Location location)
2770e13f8a603867280de9b02ce4839202a182556416Andy Hung{
2771e13f8a603867280de9b02ce4839202a182556416Andy Hung    if (msec == nullptr ||
2772e13f8a603867280de9b02ce4839202a182556416Andy Hung            (location != ExtendedTimestamp::LOCATION_SERVER
2773e13f8a603867280de9b02ce4839202a182556416Andy Hung                    && location != ExtendedTimestamp::LOCATION_KERNEL)) {
2774e13f8a603867280de9b02ce4839202a182556416Andy Hung        return BAD_VALUE;
2775e13f8a603867280de9b02ce4839202a182556416Andy Hung    }
2776e13f8a603867280de9b02ce4839202a182556416Andy Hung    AutoMutex lock(mLock);
2777e13f8a603867280de9b02ce4839202a182556416Andy Hung    // inclusive of offloaded and direct tracks.
2778e13f8a603867280de9b02ce4839202a182556416Andy Hung    //
2779e13f8a603867280de9b02ce4839202a182556416Andy Hung    // It is possible, but not enabled, to allow duration computation for non-pcm
2780e13f8a603867280de9b02ce4839202a182556416Andy Hung    // audio_has_proportional_frames() formats because currently they have
2781e13f8a603867280de9b02ce4839202a182556416Andy Hung    // the drain rate equivalent to the pcm sample rate * framesize.
2782e13f8a603867280de9b02ce4839202a182556416Andy Hung    if (!isPurePcmData_l()) {
2783e13f8a603867280de9b02ce4839202a182556416Andy Hung        return INVALID_OPERATION;
2784e13f8a603867280de9b02ce4839202a182556416Andy Hung    }
2785e13f8a603867280de9b02ce4839202a182556416Andy Hung    ExtendedTimestamp ets;
2786e13f8a603867280de9b02ce4839202a182556416Andy Hung    if (getTimestamp_l(&ets) == OK
2787e13f8a603867280de9b02ce4839202a182556416Andy Hung            && ets.mTimeNs[location] > 0) {
2788e13f8a603867280de9b02ce4839202a182556416Andy Hung        int64_t diff = ets.mPosition[ExtendedTimestamp::LOCATION_CLIENT]
2789e13f8a603867280de9b02ce4839202a182556416Andy Hung                - ets.mPosition[location];
2790e13f8a603867280de9b02ce4839202a182556416Andy Hung        if (diff < 0) {
2791e13f8a603867280de9b02ce4839202a182556416Andy Hung            *msec = 0;
2792e13f8a603867280de9b02ce4839202a182556416Andy Hung        } else {
2793e13f8a603867280de9b02ce4839202a182556416Andy Hung            // ms is the playback time by frames
2794e13f8a603867280de9b02ce4839202a182556416Andy Hung            int64_t ms = (int64_t)((double)diff * 1000 /
2795e13f8a603867280de9b02ce4839202a182556416Andy Hung                    ((double)mSampleRate * mPlaybackRate.mSpeed));
2796e13f8a603867280de9b02ce4839202a182556416Andy Hung            // clockdiff is the timestamp age (negative)
2797e13f8a603867280de9b02ce4839202a182556416Andy Hung            int64_t clockdiff = (mState != STATE_ACTIVE) ? 0 :
2798e13f8a603867280de9b02ce4839202a182556416Andy Hung                    ets.mTimeNs[location]
2799e13f8a603867280de9b02ce4839202a182556416Andy Hung                    + ets.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_MONOTONIC]
2800e13f8a603867280de9b02ce4839202a182556416Andy Hung                    - systemTime(SYSTEM_TIME_MONOTONIC);
2801e13f8a603867280de9b02ce4839202a182556416Andy Hung
2802e13f8a603867280de9b02ce4839202a182556416Andy Hung            //ALOGV("ms: %lld  clockdiff: %lld", (long long)ms, (long long)clockdiff);
2803e13f8a603867280de9b02ce4839202a182556416Andy Hung            static const int NANOS_PER_MILLIS = 1000000;
2804e13f8a603867280de9b02ce4839202a182556416Andy Hung            *msec = (int32_t)(ms + clockdiff / NANOS_PER_MILLIS);
2805e13f8a603867280de9b02ce4839202a182556416Andy Hung        }
2806e13f8a603867280de9b02ce4839202a182556416Andy Hung        return NO_ERROR;
2807e13f8a603867280de9b02ce4839202a182556416Andy Hung    }
2808e13f8a603867280de9b02ce4839202a182556416Andy Hung    if (location != ExtendedTimestamp::LOCATION_SERVER) {
2809e13f8a603867280de9b02ce4839202a182556416Andy Hung        return INVALID_OPERATION; // LOCATION_KERNEL is not available
2810e13f8a603867280de9b02ce4839202a182556416Andy Hung    }
2811e13f8a603867280de9b02ce4839202a182556416Andy Hung    // use server position directly (offloaded and direct arrive here)
2812e13f8a603867280de9b02ce4839202a182556416Andy Hung    updateAndGetPosition_l();
2813e13f8a603867280de9b02ce4839202a182556416Andy Hung    int32_t diff = (Modulo<uint32_t>(mFramesWritten) - mPosition).signedValue();
2814e13f8a603867280de9b02ce4839202a182556416Andy Hung    *msec = (diff <= 0) ? 0
2815e13f8a603867280de9b02ce4839202a182556416Andy Hung            : (int32_t)((double)diff * 1000 / ((double)mSampleRate * mPlaybackRate.mSpeed));
2816e13f8a603867280de9b02ce4839202a182556416Andy Hung    return NO_ERROR;
2817e13f8a603867280de9b02ce4839202a182556416Andy Hung}
2818e13f8a603867280de9b02ce4839202a182556416Andy Hung
281965ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hungbool AudioTrack::hasStarted()
282065ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung{
282165ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung    AutoMutex lock(mLock);
282265ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung    switch (mState) {
282365ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung    case STATE_STOPPED:
282465ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung        if (isOffloadedOrDirect_l()) {
282565ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung            // check if we have started in the past to return true.
282665ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung            return mStartUs > 0;
282765ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung        }
282865ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung        // A normal audio track may still be draining, so
282965ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung        // check if stream has ended.  This covers fasttrack position
283065ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung        // instability and start/stop without any data written.
283165ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung        if (mProxy->getStreamEndDone()) {
283265ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung            return true;
283365ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung        }
283465ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung        // fall through
283565ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung    case STATE_ACTIVE:
283665ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung    case STATE_STOPPING:
283765ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung        break;
283865ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung    case STATE_PAUSED:
283965ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung    case STATE_PAUSED_STOPPING:
284065ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung    case STATE_FLUSHED:
284165ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung        return false;  // we're not active
284265ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung    default:
284365ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung        LOG_ALWAYS_FATAL("Invalid mState in hasStarted(): %d", mState);
284465ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung        break;
284565ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung    }
284665ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung
284765ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung    // wait indicates whether we need to wait for a timestamp.
284865ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung    // This is conservatively figured - if we encounter an unexpected error
284965ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung    // then we will not wait.
285065ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung    bool wait = false;
285165ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung    if (isOffloadedOrDirect_l()) {
285265ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung        AudioTimestamp ts;
285365ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung        status_t status = getTimestamp_l(ts);
285465ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung        if (status == WOULD_BLOCK) {
285565ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung            wait = true;
285665ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung        } else if (status == OK) {
285765ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung            wait = (ts.mPosition == 0 || ts.mPosition == mStartTs.mPosition);
285865ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung        }
285965ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung        ALOGV("hasStarted wait:%d  ts:%u  start position:%lld",
286065ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung                (int)wait,
286165ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung                ts.mPosition,
286265ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung                (long long)mStartTs.mPosition);
286365ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung    } else {
286465ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung        int location = ExtendedTimestamp::LOCATION_SERVER; // for ALOG
286565ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung        ExtendedTimestamp ets;
286665ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung        status_t status = getTimestamp_l(&ets);
286765ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung        if (status == WOULD_BLOCK) {  // no SERVER or KERNEL frame info in ets
286865ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung            wait = true;
286965ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung        } else if (status == OK) {
287065ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung            for (location = ExtendedTimestamp::LOCATION_KERNEL;
287165ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung                    location >= ExtendedTimestamp::LOCATION_SERVER; --location) {
287265ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung                if (ets.mTimeNs[location] < 0 || mStartEts.mTimeNs[location] < 0) {
287365ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung                    continue;
287465ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung                }
287565ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung                wait = ets.mPosition[location] == 0
287665ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung                        || ets.mPosition[location] == mStartEts.mPosition[location];
287765ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung                break;
287865ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung            }
287965ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung        }
288065ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung        ALOGV("hasStarted wait:%d  ets:%lld  start position:%lld",
288165ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung                (int)wait,
288265ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung                (long long)ets.mPosition[location],
288365ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung                (long long)mStartEts.mPosition[location]);
288465ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung    }
288565ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung    return !wait;
288665ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung}
288765ffdfc7e92f9900d72bf6dc0b7f4e1231d4da03Andy Hung
28889f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten// =========================================================================
28899f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
28907c7be1e05634d96d08210efb4bdeb012ffba440dGlenn Kastenvoid AudioTrack::DeathNotifier::binderDied(const wp<IBinder>& who __unused)
28919f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten{
28929f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    sp<AudioTrack> audioTrack = mAudioTrack.promote();
28939f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    if (audioTrack != 0) {
28949f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        AutoMutex lock(audioTrack->mLock);
28959f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        audioTrack->mProxy->binderDied();
28969f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    }
28979f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten}
28989f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten
289989fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project// =========================================================================
290089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
290189fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source ProjectAudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
2902598de6c701e989385eeffa7c5dfd61f0459a2631Glenn Kasten    : Thread(bCanCallJava), mReceiver(receiver), mPaused(true), mPausedInt(false), mPausedNs(0LL),
2903598de6c701e989385eeffa7c5dfd61f0459a2631Glenn Kasten      mIgnoreNextPausedInt(false)
29043acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten{
29053acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten}
29063acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten
29073acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn KastenAudioTrack::AudioTrackThread::~AudioTrackThread()
290889fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project{
290989fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project}
291089fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
291189fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Projectbool AudioTrack::AudioTrackThread::threadLoop()
291289fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project{
29133acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten    {
29143acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten        AutoMutex _l(mMyLock);
29153acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten        if (mPaused) {
29163acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten            mMyCond.wait(mMyLock);
29173acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten            // caller will check for exitPending()
29183acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten            return true;
29193acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten        }
2920598de6c701e989385eeffa7c5dfd61f0459a2631Glenn Kasten        if (mIgnoreNextPausedInt) {
2921598de6c701e989385eeffa7c5dfd61f0459a2631Glenn Kasten            mIgnoreNextPausedInt = false;
2922598de6c701e989385eeffa7c5dfd61f0459a2631Glenn Kasten            mPausedInt = false;
2923598de6c701e989385eeffa7c5dfd61f0459a2631Glenn Kasten        }
29245a6cd224d07c05b496b6aca050ce5ecf96f125afGlenn Kasten        if (mPausedInt) {
29255a6cd224d07c05b496b6aca050ce5ecf96f125afGlenn Kasten            if (mPausedNs > 0) {
29265a6cd224d07c05b496b6aca050ce5ecf96f125afGlenn Kasten                (void) mMyCond.waitRelative(mMyLock, mPausedNs);
29275a6cd224d07c05b496b6aca050ce5ecf96f125afGlenn Kasten            } else {
29285a6cd224d07c05b496b6aca050ce5ecf96f125afGlenn Kasten                mMyCond.wait(mMyLock);
29295a6cd224d07c05b496b6aca050ce5ecf96f125afGlenn Kasten            }
29309d2c78c4798ffd8c276c1bf0eaa0b34bc255a2daEric Laurent            mPausedInt = false;
29315a6cd224d07c05b496b6aca050ce5ecf96f125afGlenn Kasten            return true;
29325a6cd224d07c05b496b6aca050ce5ecf96f125afGlenn Kasten        }
29333acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten    }
29347985dcb06e0c29d5cc12d0c0e17e03d5d863cf53Eric Laurent    if (exitPending()) {
29357985dcb06e0c29d5cc12d0c0e17e03d5d863cf53Eric Laurent        return false;
29367985dcb06e0c29d5cc12d0c0e17e03d5d863cf53Eric Laurent    }
29377c7be1e05634d96d08210efb4bdeb012ffba440dGlenn Kasten    nsecs_t ns = mReceiver.processAudioBuffer();
29389f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    switch (ns) {
29399f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    case 0:
29409f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        return true;
29419f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    case NS_INACTIVE:
29425a6cd224d07c05b496b6aca050ce5ecf96f125afGlenn Kasten        pauseInternal();
29439f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        return true;
29449f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    case NS_NEVER:
29459f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        return false;
29465a6cd224d07c05b496b6aca050ce5ecf96f125afGlenn Kasten    case NS_WHENEVER:
29473c09c78aabcb9d314dfb400258fb99a37c7b50c9Andy Hung        // Event driven: call wake() when callback notifications conditions change.
29483c09c78aabcb9d314dfb400258fb99a37c7b50c9Andy Hung        ns = INT64_MAX;
29495a6cd224d07c05b496b6aca050ce5ecf96f125afGlenn Kasten        // fall through
29509f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten    default:
295134fb29696b0f3abf61b10f8d053b1f33d501de0aMark Salyzyn        LOG_ALWAYS_FATAL_IF(ns < 0, "processAudioBuffer() returned %" PRId64, ns);
29525a6cd224d07c05b496b6aca050ce5ecf96f125afGlenn Kasten        pauseInternal(ns);
29539f80dd223d83d9bb9077fb6baee056cee4eaf7e5Glenn Kasten        return true;
2954ca8b28013c0558a4a3323a1a0f58520277200086Glenn Kasten    }
295589fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project}
295689fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5The Android Open Source Project
29573acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kastenvoid AudioTrack::AudioTrackThread::requestExit()
29583acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten{
29593acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten    // must be in this order to avoid a race condition
29603acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten    Thread::requestExit();
2961598de6c701e989385eeffa7c5dfd61f0459a2631Glenn Kasten    resume();
29623acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten}
29633acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten
29643acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kastenvoid AudioTrack::AudioTrackThread::pause()
29653acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten{
29663acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten    AutoMutex _l(mMyLock);
29673acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten    mPaused = true;
29683acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten}
29693acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten
29703acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kastenvoid AudioTrack::AudioTrackThread::resume()
29713acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten{
29723acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten    AutoMutex _l(mMyLock);
2973598de6c701e989385eeffa7c5dfd61f0459a2631Glenn Kasten    mIgnoreNextPausedInt = true;
29749d2c78c4798ffd8c276c1bf0eaa0b34bc255a2daEric Laurent    if (mPaused || mPausedInt) {
29753acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten        mPaused = false;
29769d2c78c4798ffd8c276c1bf0eaa0b34bc255a2daEric Laurent        mPausedInt = false;
29773acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten        mMyCond.signal();
29783acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten    }
29793acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten}
29803acbd053c842e76e1a40fc8a0bf62de87eebf00fGlenn Kasten
29813c09c78aabcb9d314dfb400258fb99a37c7b50c9Andy Hungvoid AudioTrack::AudioTrackThread::wake()
29823c09c78aabcb9d314dfb400258fb99a37c7b50c9Andy Hung{
29833c09c78aabcb9d314dfb400258fb99a37c7b50c9Andy Hung    AutoMutex _l(mMyLock);
2984a8d0890ca969ec40fdcf1cfcbeef85c0c379cfafAndy Hung    if (!mPaused) {
2985a8d0890ca969ec40fdcf1cfcbeef85c0c379cfafAndy Hung        // wake() might be called while servicing a callback - ignore the next
2986a8d0890ca969ec40fdcf1cfcbeef85c0c379cfafAndy Hung        // pause time and call processAudioBuffer.
29873c09c78aabcb9d314dfb400258fb99a37c7b50c9Andy Hung        mIgnoreNextPausedInt = true;
2988a8d0890ca969ec40fdcf1cfcbeef85c0c379cfafAndy Hung        if (mPausedInt && mPausedNs > 0) {
2989a8d0890ca969ec40fdcf1cfcbeef85c0c379cfafAndy Hung            // audio track is active and internally paused with timeout.
2990a8d0890ca969ec40fdcf1cfcbeef85c0c379cfafAndy Hung            mPausedInt = false;
2991a8d0890ca969ec40fdcf1cfcbeef85c0c379cfafAndy Hung            mMyCond.signal();
2992a8d0890ca969ec40fdcf1cfcbeef85c0c379cfafAndy Hung        }
29933c09c78aabcb9d314dfb400258fb99a37c7b50c9Andy Hung    }
29943c09c78aabcb9d314dfb400258fb99a37c7b50c9Andy Hung}
29953c09c78aabcb9d314dfb400258fb99a37c7b50c9Andy Hung
29965a6cd224d07c05b496b6aca050ce5ecf96f125afGlenn Kastenvoid AudioTrack::AudioTrackThread::pauseInternal(nsecs_t ns)
29975a6cd224d07c05b496b6aca050ce5ecf96f125afGlenn Kasten{
29985a6cd224d07c05b496b6aca050ce5ecf96f125afGlenn Kasten    AutoMutex _l(mMyLock);
29995a6cd224d07c05b496b6aca050ce5ecf96f125afGlenn Kasten    mPausedInt = true;
30005a6cd224d07c05b496b6aca050ce5ecf96f125afGlenn Kasten    mPausedNs = ns;
30015a6cd224d07c05b496b6aca050ce5ecf96f125afGlenn Kasten}
30025a6cd224d07c05b496b6aca050ce5ecf96f125afGlenn Kasten
300340bc906252974d0b389ae4a147232d0c9a97193fGlenn Kasten} // namespace android
3004