MediaPlayerService.cpp revision 3f273d10817ddb2f792ae043de692efcdf1988ae
1/*
2**
3** Copyright 2008, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9**     http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18// Proxy for media player implementations
19
20//#define LOG_NDEBUG 0
21#define LOG_TAG "MediaPlayerService"
22#include <utils/Log.h>
23
24#include <sys/types.h>
25#include <sys/stat.h>
26#include <sys/time.h>
27#include <dirent.h>
28#include <unistd.h>
29
30#include <string.h>
31
32#include <cutils/atomic.h>
33#include <cutils/properties.h> // for property_get
34
35#include <utils/misc.h>
36
37#include <binder/IPCThreadState.h>
38#include <binder/IServiceManager.h>
39#include <binder/MemoryHeapBase.h>
40#include <binder/MemoryBase.h>
41#include <gui/Surface.h>
42#include <utils/Errors.h>  // for status_t
43#include <utils/String8.h>
44#include <utils/SystemClock.h>
45#include <utils/Timers.h>
46#include <utils/Vector.h>
47
48#include <media/AudioPolicyHelper.h>
49#include <media/IMediaHTTPService.h>
50#include <media/IRemoteDisplay.h>
51#include <media/IRemoteDisplayClient.h>
52#include <media/MediaPlayerInterface.h>
53#include <media/mediarecorder.h>
54#include <media/MediaMetadataRetrieverInterface.h>
55#include <media/Metadata.h>
56#include <media/AudioTrack.h>
57#include <media/MemoryLeakTrackUtil.h>
58#include <media/stagefright/MediaCodecList.h>
59#include <media/stagefright/MediaErrors.h>
60#include <media/stagefright/AudioPlayer.h>
61#include <media/stagefright/Utils.h>
62#include <media/stagefright/foundation/ADebug.h>
63#include <media/stagefright/foundation/ALooperRoster.h>
64#include <mediautils/BatteryNotifier.h>
65
66#include <system/audio.h>
67
68#include <private/android_filesystem_config.h>
69
70#include "ActivityManager.h"
71#include "MediaRecorderClient.h"
72#include "MediaPlayerService.h"
73#include "MetadataRetrieverClient.h"
74#include "MediaPlayerFactory.h"
75
76#include "TestPlayerStub.h"
77#include "StagefrightPlayer.h"
78#include "nuplayer/NuPlayerDriver.h"
79
80#include <OMX.h>
81
82#include "Crypto.h"
83#include "Drm.h"
84#include "HDCP.h"
85#include "HTTPBase.h"
86#include "RemoteDisplay.h"
87
88namespace {
89using android::media::Metadata;
90using android::status_t;
91using android::OK;
92using android::BAD_VALUE;
93using android::NOT_ENOUGH_DATA;
94using android::Parcel;
95
96// Max number of entries in the filter.
97const int kMaxFilterSize = 64;  // I pulled that out of thin air.
98
99// FIXME: Move all the metadata related function in the Metadata.cpp
100
101
102// Unmarshall a filter from a Parcel.
103// Filter format in a parcel:
104//
105//  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
106// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
107// |                       number of entries (n)                   |
108// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
109// |                       metadata type 1                         |
110// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
111// |                       metadata type 2                         |
112// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
113//  ....
114// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
115// |                       metadata type n                         |
116// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
117//
118// @param p Parcel that should start with a filter.
119// @param[out] filter On exit contains the list of metadata type to be
120//                    filtered.
121// @param[out] status On exit contains the status code to be returned.
122// @return true if the parcel starts with a valid filter.
123bool unmarshallFilter(const Parcel& p,
124                      Metadata::Filter *filter,
125                      status_t *status)
126{
127    int32_t val;
128    if (p.readInt32(&val) != OK)
129    {
130        ALOGE("Failed to read filter's length");
131        *status = NOT_ENOUGH_DATA;
132        return false;
133    }
134
135    if( val > kMaxFilterSize || val < 0)
136    {
137        ALOGE("Invalid filter len %d", val);
138        *status = BAD_VALUE;
139        return false;
140    }
141
142    const size_t num = val;
143
144    filter->clear();
145    filter->setCapacity(num);
146
147    size_t size = num * sizeof(Metadata::Type);
148
149
150    if (p.dataAvail() < size)
151    {
152        ALOGE("Filter too short expected %d but got %d", size, p.dataAvail());
153        *status = NOT_ENOUGH_DATA;
154        return false;
155    }
156
157    const Metadata::Type *data =
158            static_cast<const Metadata::Type*>(p.readInplace(size));
159
160    if (NULL == data)
161    {
162        ALOGE("Filter had no data");
163        *status = BAD_VALUE;
164        return false;
165    }
166
167    // TODO: The stl impl of vector would be more efficient here
168    // because it degenerates into a memcpy on pod types. Try to
169    // replace later or use stl::set.
170    for (size_t i = 0; i < num; ++i)
171    {
172        filter->add(*data);
173        ++data;
174    }
175    *status = OK;
176    return true;
177}
178
179// @param filter Of metadata type.
180// @param val To be searched.
181// @return true if a match was found.
182bool findMetadata(const Metadata::Filter& filter, const int32_t val)
183{
184    // Deal with empty and ANY right away
185    if (filter.isEmpty()) return false;
186    if (filter[0] == Metadata::kAny) return true;
187
188    return filter.indexOf(val) >= 0;
189}
190
191}  // anonymous namespace
192
193
194namespace {
195using android::Parcel;
196using android::String16;
197
198// marshalling tag indicating flattened utf16 tags
199// keep in sync with frameworks/base/media/java/android/media/AudioAttributes.java
200const int32_t kAudioAttributesMarshallTagFlattenTags = 1;
201
202// Audio attributes format in a parcel:
203//
204//  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
205// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
206// |                       usage                                   |
207// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
208// |                       content_type                            |
209// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
210// |                       source                                  |
211// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
212// |                       flags                                   |
213// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
214// |                       kAudioAttributesMarshallTagFlattenTags  | // ignore tags if not found
215// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
216// |                       flattened tags in UTF16                 |
217// |                         ...                                   |
218// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
219//
220// @param p Parcel that contains audio attributes.
221// @param[out] attributes On exit points to an initialized audio_attributes_t structure
222// @param[out] status On exit contains the status code to be returned.
223void unmarshallAudioAttributes(const Parcel& parcel, audio_attributes_t *attributes)
224{
225    attributes->usage = (audio_usage_t) parcel.readInt32();
226    attributes->content_type = (audio_content_type_t) parcel.readInt32();
227    attributes->source = (audio_source_t) parcel.readInt32();
228    attributes->flags = (audio_flags_mask_t) parcel.readInt32();
229    const bool hasFlattenedTag = (parcel.readInt32() == kAudioAttributesMarshallTagFlattenTags);
230    if (hasFlattenedTag) {
231        // the tags are UTF16, convert to UTF8
232        String16 tags = parcel.readString16();
233        ssize_t realTagSize = utf16_to_utf8_length(tags.string(), tags.size());
234        if (realTagSize <= 0) {
235            strcpy(attributes->tags, "");
236        } else {
237            // copy the flattened string into the attributes as the destination for the conversion:
238            // copying array size -1, array for tags was calloc'd, no need to NULL-terminate it
239            size_t tagSize = realTagSize > AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 ?
240                    AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 : realTagSize;
241            utf16_to_utf8(tags.string(), tagSize, attributes->tags);
242        }
243    } else {
244        ALOGE("unmarshallAudioAttributes() received unflattened tags, ignoring tag values");
245        strcpy(attributes->tags, "");
246    }
247}
248} // anonymous namespace
249
250
251namespace android {
252
253extern ALooperRoster gLooperRoster;
254
255
256static bool checkPermission(const char* permissionString) {
257    if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
258    bool ok = checkCallingPermission(String16(permissionString));
259    if (!ok) ALOGE("Request requires %s", permissionString);
260    return ok;
261}
262
263// TODO: Find real cause of Audio/Video delay in PV framework and remove this workaround
264/* static */ int MediaPlayerService::AudioOutput::mMinBufferCount = 4;
265/* static */ bool MediaPlayerService::AudioOutput::mIsOnEmulator = false;
266
267void MediaPlayerService::instantiate() {
268    defaultServiceManager()->addService(
269            String16("media.player"), new MediaPlayerService());
270}
271
272MediaPlayerService::MediaPlayerService()
273{
274    ALOGV("MediaPlayerService created");
275    mNextConnId = 1;
276
277    mBatteryAudio.refCount = 0;
278    for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
279        mBatteryAudio.deviceOn[i] = 0;
280        mBatteryAudio.lastTime[i] = 0;
281        mBatteryAudio.totalTime[i] = 0;
282    }
283    // speaker is on by default
284    mBatteryAudio.deviceOn[SPEAKER] = 1;
285
286    // reset battery stats
287    // if the mediaserver has crashed, battery stats could be left
288    // in bad state, reset the state upon service start.
289    BatteryNotifier::getInstance().noteResetVideo();
290
291    MediaPlayerFactory::registerBuiltinFactories();
292}
293
294MediaPlayerService::~MediaPlayerService()
295{
296    ALOGV("MediaPlayerService destroyed");
297}
298
299sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(const String16 &opPackageName)
300{
301    pid_t pid = IPCThreadState::self()->getCallingPid();
302    sp<MediaRecorderClient> recorder = new MediaRecorderClient(this, pid, opPackageName);
303    wp<MediaRecorderClient> w = recorder;
304    Mutex::Autolock lock(mLock);
305    mMediaRecorderClients.add(w);
306    ALOGV("Create new media recorder client from pid %d", pid);
307    return recorder;
308}
309
310void MediaPlayerService::removeMediaRecorderClient(wp<MediaRecorderClient> client)
311{
312    Mutex::Autolock lock(mLock);
313    mMediaRecorderClients.remove(client);
314    ALOGV("Delete media recorder client");
315}
316
317sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever()
318{
319    pid_t pid = IPCThreadState::self()->getCallingPid();
320    sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
321    ALOGV("Create new media retriever from pid %d", pid);
322    return retriever;
323}
324
325sp<IMediaPlayer> MediaPlayerService::create(const sp<IMediaPlayerClient>& client,
326        int audioSessionId)
327{
328    pid_t pid = IPCThreadState::self()->getCallingPid();
329    int32_t connId = android_atomic_inc(&mNextConnId);
330
331    sp<Client> c = new Client(
332            this, pid, connId, client, audioSessionId,
333            IPCThreadState::self()->getCallingUid());
334
335    ALOGV("Create new client(%d) from pid %d, uid %d, ", connId, pid,
336         IPCThreadState::self()->getCallingUid());
337
338    wp<Client> w = c;
339    {
340        Mutex::Autolock lock(mLock);
341        mClients.add(w);
342    }
343    return c;
344}
345
346sp<IMediaCodecList> MediaPlayerService::getCodecList() const {
347    return MediaCodecList::getLocalInstance();
348}
349
350sp<IOMX> MediaPlayerService::getOMX() {
351    Mutex::Autolock autoLock(mLock);
352
353    if (mOMX.get() == NULL) {
354        mOMX = new OMX;
355    }
356
357    return mOMX;
358}
359
360sp<ICrypto> MediaPlayerService::makeCrypto() {
361    return new Crypto;
362}
363
364sp<IDrm> MediaPlayerService::makeDrm() {
365    return new Drm;
366}
367
368sp<IHDCP> MediaPlayerService::makeHDCP(bool createEncryptionModule) {
369    return new HDCP(createEncryptionModule);
370}
371
372sp<IRemoteDisplay> MediaPlayerService::listenForRemoteDisplay(
373        const String16 &opPackageName,
374        const sp<IRemoteDisplayClient>& client, const String8& iface) {
375    if (!checkPermission("android.permission.CONTROL_WIFI_DISPLAY")) {
376        return NULL;
377    }
378
379    return new RemoteDisplay(opPackageName, client, iface.string());
380}
381
382status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
383{
384    const size_t SIZE = 256;
385    char buffer[SIZE];
386    String8 result;
387
388    result.append(" AudioOutput\n");
389    snprintf(buffer, 255, "  stream type(%d), left - right volume(%f, %f)\n",
390            mStreamType, mLeftVolume, mRightVolume);
391    result.append(buffer);
392    snprintf(buffer, 255, "  msec per frame(%f), latency (%d)\n",
393            mMsecsPerFrame, (mTrack != 0) ? mTrack->latency() : -1);
394    result.append(buffer);
395    snprintf(buffer, 255, "  aux effect id(%d), send level (%f)\n",
396            mAuxEffectId, mSendLevel);
397    result.append(buffer);
398
399    ::write(fd, result.string(), result.size());
400    if (mTrack != 0) {
401        mTrack->dump(fd, args);
402    }
403    return NO_ERROR;
404}
405
406status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args)
407{
408    const size_t SIZE = 256;
409    char buffer[SIZE];
410    String8 result;
411    result.append(" Client\n");
412    snprintf(buffer, 255, "  pid(%d), connId(%d), status(%d), looping(%s)\n",
413            mPid, mConnId, mStatus, mLoop?"true": "false");
414    result.append(buffer);
415    write(fd, result.string(), result.size());
416    if (mPlayer != NULL) {
417        mPlayer->dump(fd, args);
418    }
419    if (mAudioOutput != 0) {
420        mAudioOutput->dump(fd, args);
421    }
422    write(fd, "\n", 1);
423    return NO_ERROR;
424}
425
426/**
427 * The only arguments this understands right now are -c, -von and -voff,
428 * which are parsed by ALooperRoster::dump()
429 */
430status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
431{
432    const size_t SIZE = 256;
433    char buffer[SIZE];
434    String8 result;
435    SortedVector< sp<Client> > clients; //to serialise the mutex unlock & client destruction.
436    SortedVector< sp<MediaRecorderClient> > mediaRecorderClients;
437
438    if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
439        snprintf(buffer, SIZE, "Permission Denial: "
440                "can't dump MediaPlayerService from pid=%d, uid=%d\n",
441                IPCThreadState::self()->getCallingPid(),
442                IPCThreadState::self()->getCallingUid());
443        result.append(buffer);
444    } else {
445        Mutex::Autolock lock(mLock);
446        for (int i = 0, n = mClients.size(); i < n; ++i) {
447            sp<Client> c = mClients[i].promote();
448            if (c != 0) c->dump(fd, args);
449            clients.add(c);
450        }
451        if (mMediaRecorderClients.size() == 0) {
452                result.append(" No media recorder client\n\n");
453        } else {
454            for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
455                sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
456                if (c != 0) {
457                    snprintf(buffer, 255, " MediaRecorderClient pid(%d)\n", c->mPid);
458                    result.append(buffer);
459                    write(fd, result.string(), result.size());
460                    result = "\n";
461                    c->dump(fd, args);
462                    mediaRecorderClients.add(c);
463                }
464            }
465        }
466
467        result.append(" Files opened and/or mapped:\n");
468        snprintf(buffer, SIZE, "/proc/%d/maps", getpid());
469        FILE *f = fopen(buffer, "r");
470        if (f) {
471            while (!feof(f)) {
472                fgets(buffer, SIZE, f);
473                if (strstr(buffer, " /storage/") ||
474                    strstr(buffer, " /system/sounds/") ||
475                    strstr(buffer, " /data/") ||
476                    strstr(buffer, " /system/media/")) {
477                    result.append("  ");
478                    result.append(buffer);
479                }
480            }
481            fclose(f);
482        } else {
483            result.append("couldn't open ");
484            result.append(buffer);
485            result.append("\n");
486        }
487
488        snprintf(buffer, SIZE, "/proc/%d/fd", getpid());
489        DIR *d = opendir(buffer);
490        if (d) {
491            struct dirent *ent;
492            while((ent = readdir(d)) != NULL) {
493                if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
494                    snprintf(buffer, SIZE, "/proc/%d/fd/%s", getpid(), ent->d_name);
495                    struct stat s;
496                    if (lstat(buffer, &s) == 0) {
497                        if ((s.st_mode & S_IFMT) == S_IFLNK) {
498                            char linkto[256];
499                            int len = readlink(buffer, linkto, sizeof(linkto));
500                            if(len > 0) {
501                                if(len > 255) {
502                                    linkto[252] = '.';
503                                    linkto[253] = '.';
504                                    linkto[254] = '.';
505                                    linkto[255] = 0;
506                                } else {
507                                    linkto[len] = 0;
508                                }
509                                if (strstr(linkto, "/storage/") == linkto ||
510                                    strstr(linkto, "/system/sounds/") == linkto ||
511                                    strstr(linkto, "/data/") == linkto ||
512                                    strstr(linkto, "/system/media/") == linkto) {
513                                    result.append("  ");
514                                    result.append(buffer);
515                                    result.append(" -> ");
516                                    result.append(linkto);
517                                    result.append("\n");
518                                }
519                            }
520                        } else {
521                            result.append("  unexpected type for ");
522                            result.append(buffer);
523                            result.append("\n");
524                        }
525                    }
526                }
527            }
528            closedir(d);
529        } else {
530            result.append("couldn't open ");
531            result.append(buffer);
532            result.append("\n");
533        }
534
535        gLooperRoster.dump(fd, args);
536
537        bool dumpMem = false;
538        for (size_t i = 0; i < args.size(); i++) {
539            if (args[i] == String16("-m")) {
540                dumpMem = true;
541            }
542        }
543        if (dumpMem) {
544            dumpMemoryAddresses(fd);
545        }
546    }
547    write(fd, result.string(), result.size());
548    return NO_ERROR;
549}
550
551void MediaPlayerService::removeClient(wp<Client> client)
552{
553    Mutex::Autolock lock(mLock);
554    mClients.remove(client);
555}
556
557MediaPlayerService::Client::Client(
558        const sp<MediaPlayerService>& service, pid_t pid,
559        int32_t connId, const sp<IMediaPlayerClient>& client,
560        int audioSessionId, uid_t uid)
561{
562    ALOGV("Client(%d) constructor", connId);
563    mPid = pid;
564    mConnId = connId;
565    mService = service;
566    mClient = client;
567    mLoop = false;
568    mStatus = NO_INIT;
569    mAudioSessionId = audioSessionId;
570    mUID = uid;
571    mRetransmitEndpointValid = false;
572    mAudioAttributes = NULL;
573
574#if CALLBACK_ANTAGONIZER
575    ALOGD("create Antagonizer");
576    mAntagonizer = new Antagonizer(notify, this);
577#endif
578}
579
580MediaPlayerService::Client::~Client()
581{
582    ALOGV("Client(%d) destructor pid = %d", mConnId, mPid);
583    mAudioOutput.clear();
584    wp<Client> client(this);
585    disconnect();
586    mService->removeClient(client);
587    if (mAudioAttributes != NULL) {
588        free(mAudioAttributes);
589    }
590}
591
592void MediaPlayerService::Client::disconnect()
593{
594    ALOGV("disconnect(%d) from pid %d", mConnId, mPid);
595    // grab local reference and clear main reference to prevent future
596    // access to object
597    sp<MediaPlayerBase> p;
598    {
599        Mutex::Autolock l(mLock);
600        p = mPlayer;
601        mClient.clear();
602    }
603
604    mPlayer.clear();
605
606    // clear the notification to prevent callbacks to dead client
607    // and reset the player. We assume the player will serialize
608    // access to itself if necessary.
609    if (p != 0) {
610        p->setNotifyCallback(0, 0);
611#if CALLBACK_ANTAGONIZER
612        ALOGD("kill Antagonizer");
613        mAntagonizer->kill();
614#endif
615        p->reset();
616    }
617
618    disconnectNativeWindow();
619
620    IPCThreadState::self()->flushCommands();
621}
622
623sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
624{
625    // determine if we have the right player type
626    sp<MediaPlayerBase> p = mPlayer;
627    if ((p != NULL) && (p->playerType() != playerType)) {
628        ALOGV("delete player");
629        p.clear();
630    }
631    if (p == NULL) {
632        p = MediaPlayerFactory::createPlayer(playerType, this, notify, mPid);
633    }
634
635    if (p != NULL) {
636        p->setUID(mUID);
637    }
638
639    return p;
640}
641
642sp<MediaPlayerBase> MediaPlayerService::Client::setDataSource_pre(
643        player_type playerType)
644{
645    ALOGV("player type = %d", playerType);
646
647    // create the right type of player
648    sp<MediaPlayerBase> p = createPlayer(playerType);
649    if (p == NULL) {
650        return p;
651    }
652
653    if (!p->hardwareOutput()) {
654        Mutex::Autolock l(mLock);
655        mAudioOutput = new AudioOutput(mAudioSessionId, IPCThreadState::self()->getCallingUid(),
656                mPid, mAudioAttributes);
657        static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
658    }
659
660    return p;
661}
662
663void MediaPlayerService::Client::setDataSource_post(
664        const sp<MediaPlayerBase>& p,
665        status_t status)
666{
667    ALOGV(" setDataSource");
668    mStatus = status;
669    if (mStatus != OK) {
670        ALOGE("  error: %d", mStatus);
671        return;
672    }
673
674    // Set the re-transmission endpoint if one was chosen.
675    if (mRetransmitEndpointValid) {
676        mStatus = p->setRetransmitEndpoint(&mRetransmitEndpoint);
677        if (mStatus != NO_ERROR) {
678            ALOGE("setRetransmitEndpoint error: %d", mStatus);
679        }
680    }
681
682    if (mStatus == OK) {
683        mPlayer = p;
684    }
685}
686
687status_t MediaPlayerService::Client::setDataSource(
688        const sp<IMediaHTTPService> &httpService,
689        const char *url,
690        const KeyedVector<String8, String8> *headers)
691{
692    ALOGV("setDataSource(%s)", url);
693    if (url == NULL)
694        return UNKNOWN_ERROR;
695
696    if ((strncmp(url, "http://", 7) == 0) ||
697        (strncmp(url, "https://", 8) == 0) ||
698        (strncmp(url, "rtsp://", 7) == 0)) {
699        if (!checkPermission("android.permission.INTERNET")) {
700            return PERMISSION_DENIED;
701        }
702    }
703
704    if (strncmp(url, "content://", 10) == 0) {
705        // get a filedescriptor for the content Uri and
706        // pass it to the setDataSource(fd) method
707
708        String16 url16(url);
709        int fd = android::openContentProviderFile(url16);
710        if (fd < 0)
711        {
712            ALOGE("Couldn't open fd for %s", url);
713            return UNKNOWN_ERROR;
714        }
715        setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
716        close(fd);
717        return mStatus;
718    } else {
719        player_type playerType = MediaPlayerFactory::getPlayerType(this, url);
720        sp<MediaPlayerBase> p = setDataSource_pre(playerType);
721        if (p == NULL) {
722            return NO_INIT;
723        }
724
725        setDataSource_post(p, p->setDataSource(httpService, url, headers));
726        return mStatus;
727    }
728}
729
730status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
731{
732    ALOGV("setDataSource fd=%d (%s), offset=%lld, length=%lld",
733            fd, nameForFd(fd).c_str(), (long long) offset, (long long) length);
734    struct stat sb;
735    int ret = fstat(fd, &sb);
736    if (ret != 0) {
737        ALOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
738        return UNKNOWN_ERROR;
739    }
740
741    ALOGV("st_dev  = %llu", static_cast<uint64_t>(sb.st_dev));
742    ALOGV("st_mode = %u", sb.st_mode);
743    ALOGV("st_uid  = %lu", static_cast<unsigned long>(sb.st_uid));
744    ALOGV("st_gid  = %lu", static_cast<unsigned long>(sb.st_gid));
745    ALOGV("st_size = %llu", sb.st_size);
746
747    if (offset >= sb.st_size) {
748        ALOGE("offset error");
749        return UNKNOWN_ERROR;
750    }
751    if (offset + length > sb.st_size) {
752        length = sb.st_size - offset;
753        ALOGV("calculated length = %lld", length);
754    }
755
756    player_type playerType = MediaPlayerFactory::getPlayerType(this,
757                                                               fd,
758                                                               offset,
759                                                               length);
760    sp<MediaPlayerBase> p = setDataSource_pre(playerType);
761    if (p == NULL) {
762        return NO_INIT;
763    }
764
765    // now set data source
766    setDataSource_post(p, p->setDataSource(fd, offset, length));
767    return mStatus;
768}
769
770status_t MediaPlayerService::Client::setDataSource(
771        const sp<IStreamSource> &source) {
772    // create the right type of player
773    player_type playerType = MediaPlayerFactory::getPlayerType(this, source);
774    sp<MediaPlayerBase> p = setDataSource_pre(playerType);
775    if (p == NULL) {
776        return NO_INIT;
777    }
778
779    // now set data source
780    setDataSource_post(p, p->setDataSource(source));
781    return mStatus;
782}
783
784status_t MediaPlayerService::Client::setDataSource(
785        const sp<IDataSource> &source) {
786    sp<DataSource> dataSource = DataSource::CreateFromIDataSource(source);
787    player_type playerType = MediaPlayerFactory::getPlayerType(this, dataSource);
788    sp<MediaPlayerBase> p = setDataSource_pre(playerType);
789    if (p == NULL) {
790        return NO_INIT;
791    }
792    // now set data source
793    setDataSource_post(p, p->setDataSource(dataSource));
794    return mStatus;
795}
796
797void MediaPlayerService::Client::disconnectNativeWindow() {
798    if (mConnectedWindow != NULL) {
799        status_t err = native_window_api_disconnect(mConnectedWindow.get(),
800                NATIVE_WINDOW_API_MEDIA);
801
802        if (err != OK) {
803            ALOGW("native_window_api_disconnect returned an error: %s (%d)",
804                    strerror(-err), err);
805        }
806    }
807    mConnectedWindow.clear();
808}
809
810status_t MediaPlayerService::Client::setVideoSurfaceTexture(
811        const sp<IGraphicBufferProducer>& bufferProducer)
812{
813    ALOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, bufferProducer.get());
814    sp<MediaPlayerBase> p = getPlayer();
815    if (p == 0) return UNKNOWN_ERROR;
816
817    sp<IBinder> binder(IInterface::asBinder(bufferProducer));
818    if (mConnectedWindowBinder == binder) {
819        return OK;
820    }
821
822    sp<ANativeWindow> anw;
823    if (bufferProducer != NULL) {
824        anw = new Surface(bufferProducer, true /* controlledByApp */);
825        status_t err = native_window_api_connect(anw.get(),
826                NATIVE_WINDOW_API_MEDIA);
827
828        if (err != OK) {
829            ALOGE("setVideoSurfaceTexture failed: %d", err);
830            // Note that we must do the reset before disconnecting from the ANW.
831            // Otherwise queue/dequeue calls could be made on the disconnected
832            // ANW, which may result in errors.
833            reset();
834
835            disconnectNativeWindow();
836
837            return err;
838        }
839    }
840
841    // Note that we must set the player's new GraphicBufferProducer before
842    // disconnecting the old one.  Otherwise queue/dequeue calls could be made
843    // on the disconnected ANW, which may result in errors.
844    status_t err = p->setVideoSurfaceTexture(bufferProducer);
845
846    disconnectNativeWindow();
847
848    mConnectedWindow = anw;
849
850    if (err == OK) {
851        mConnectedWindowBinder = binder;
852    } else {
853        disconnectNativeWindow();
854    }
855
856    return err;
857}
858
859status_t MediaPlayerService::Client::invoke(const Parcel& request,
860                                            Parcel *reply)
861{
862    sp<MediaPlayerBase> p = getPlayer();
863    if (p == NULL) return UNKNOWN_ERROR;
864    return p->invoke(request, reply);
865}
866
867// This call doesn't need to access the native player.
868status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
869{
870    status_t status;
871    media::Metadata::Filter allow, drop;
872
873    if (unmarshallFilter(filter, &allow, &status) &&
874        unmarshallFilter(filter, &drop, &status)) {
875        Mutex::Autolock lock(mLock);
876
877        mMetadataAllow = allow;
878        mMetadataDrop = drop;
879    }
880    return status;
881}
882
883status_t MediaPlayerService::Client::getMetadata(
884        bool update_only, bool /*apply_filter*/, Parcel *reply)
885{
886    sp<MediaPlayerBase> player = getPlayer();
887    if (player == 0) return UNKNOWN_ERROR;
888
889    status_t status;
890    // Placeholder for the return code, updated by the caller.
891    reply->writeInt32(-1);
892
893    media::Metadata::Filter ids;
894
895    // We don't block notifications while we fetch the data. We clear
896    // mMetadataUpdated first so we don't lose notifications happening
897    // during the rest of this call.
898    {
899        Mutex::Autolock lock(mLock);
900        if (update_only) {
901            ids = mMetadataUpdated;
902        }
903        mMetadataUpdated.clear();
904    }
905
906    media::Metadata metadata(reply);
907
908    metadata.appendHeader();
909    status = player->getMetadata(ids, reply);
910
911    if (status != OK) {
912        metadata.resetParcel();
913        ALOGE("getMetadata failed %d", status);
914        return status;
915    }
916
917    // FIXME: Implement filtering on the result. Not critical since
918    // filtering takes place on the update notifications already. This
919    // would be when all the metadata are fetch and a filter is set.
920
921    // Everything is fine, update the metadata length.
922    metadata.updateLength();
923    return OK;
924}
925
926status_t MediaPlayerService::Client::prepareAsync()
927{
928    ALOGV("[%d] prepareAsync", mConnId);
929    sp<MediaPlayerBase> p = getPlayer();
930    if (p == 0) return UNKNOWN_ERROR;
931    status_t ret = p->prepareAsync();
932#if CALLBACK_ANTAGONIZER
933    ALOGD("start Antagonizer");
934    if (ret == NO_ERROR) mAntagonizer->start();
935#endif
936    return ret;
937}
938
939status_t MediaPlayerService::Client::start()
940{
941    ALOGV("[%d] start", mConnId);
942    sp<MediaPlayerBase> p = getPlayer();
943    if (p == 0) return UNKNOWN_ERROR;
944    p->setLooping(mLoop);
945    return p->start();
946}
947
948status_t MediaPlayerService::Client::stop()
949{
950    ALOGV("[%d] stop", mConnId);
951    sp<MediaPlayerBase> p = getPlayer();
952    if (p == 0) return UNKNOWN_ERROR;
953    return p->stop();
954}
955
956status_t MediaPlayerService::Client::pause()
957{
958    ALOGV("[%d] pause", mConnId);
959    sp<MediaPlayerBase> p = getPlayer();
960    if (p == 0) return UNKNOWN_ERROR;
961    return p->pause();
962}
963
964status_t MediaPlayerService::Client::isPlaying(bool* state)
965{
966    *state = false;
967    sp<MediaPlayerBase> p = getPlayer();
968    if (p == 0) return UNKNOWN_ERROR;
969    *state = p->isPlaying();
970    ALOGV("[%d] isPlaying: %d", mConnId, *state);
971    return NO_ERROR;
972}
973
974status_t MediaPlayerService::Client::setPlaybackSettings(const AudioPlaybackRate& rate)
975{
976    ALOGV("[%d] setPlaybackSettings(%f, %f, %d, %d)",
977            mConnId, rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
978    sp<MediaPlayerBase> p = getPlayer();
979    if (p == 0) return UNKNOWN_ERROR;
980    return p->setPlaybackSettings(rate);
981}
982
983status_t MediaPlayerService::Client::getPlaybackSettings(AudioPlaybackRate* rate /* nonnull */)
984{
985    sp<MediaPlayerBase> p = getPlayer();
986    if (p == 0) return UNKNOWN_ERROR;
987    status_t ret = p->getPlaybackSettings(rate);
988    if (ret == NO_ERROR) {
989        ALOGV("[%d] getPlaybackSettings(%f, %f, %d, %d)",
990                mConnId, rate->mSpeed, rate->mPitch, rate->mFallbackMode, rate->mStretchMode);
991    } else {
992        ALOGV("[%d] getPlaybackSettings returned %d", mConnId, ret);
993    }
994    return ret;
995}
996
997status_t MediaPlayerService::Client::setSyncSettings(
998        const AVSyncSettings& sync, float videoFpsHint)
999{
1000    ALOGV("[%d] setSyncSettings(%u, %u, %f, %f)",
1001            mConnId, sync.mSource, sync.mAudioAdjustMode, sync.mTolerance, videoFpsHint);
1002    sp<MediaPlayerBase> p = getPlayer();
1003    if (p == 0) return UNKNOWN_ERROR;
1004    return p->setSyncSettings(sync, videoFpsHint);
1005}
1006
1007status_t MediaPlayerService::Client::getSyncSettings(
1008        AVSyncSettings* sync /* nonnull */, float* videoFps /* nonnull */)
1009{
1010    sp<MediaPlayerBase> p = getPlayer();
1011    if (p == 0) return UNKNOWN_ERROR;
1012    status_t ret = p->getSyncSettings(sync, videoFps);
1013    if (ret == NO_ERROR) {
1014        ALOGV("[%d] getSyncSettings(%u, %u, %f, %f)",
1015                mConnId, sync->mSource, sync->mAudioAdjustMode, sync->mTolerance, *videoFps);
1016    } else {
1017        ALOGV("[%d] getSyncSettings returned %d", mConnId, ret);
1018    }
1019    return ret;
1020}
1021
1022status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
1023{
1024    ALOGV("getCurrentPosition");
1025    sp<MediaPlayerBase> p = getPlayer();
1026    if (p == 0) return UNKNOWN_ERROR;
1027    status_t ret = p->getCurrentPosition(msec);
1028    if (ret == NO_ERROR) {
1029        ALOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
1030    } else {
1031        ALOGE("getCurrentPosition returned %d", ret);
1032    }
1033    return ret;
1034}
1035
1036status_t MediaPlayerService::Client::getDuration(int *msec)
1037{
1038    ALOGV("getDuration");
1039    sp<MediaPlayerBase> p = getPlayer();
1040    if (p == 0) return UNKNOWN_ERROR;
1041    status_t ret = p->getDuration(msec);
1042    if (ret == NO_ERROR) {
1043        ALOGV("[%d] getDuration = %d", mConnId, *msec);
1044    } else {
1045        ALOGE("getDuration returned %d", ret);
1046    }
1047    return ret;
1048}
1049
1050status_t MediaPlayerService::Client::setNextPlayer(const sp<IMediaPlayer>& player) {
1051    ALOGV("setNextPlayer");
1052    Mutex::Autolock l(mLock);
1053    sp<Client> c = static_cast<Client*>(player.get());
1054    mNextClient = c;
1055
1056    if (c != NULL) {
1057        if (mAudioOutput != NULL) {
1058            mAudioOutput->setNextOutput(c->mAudioOutput);
1059        } else if ((mPlayer != NULL) && !mPlayer->hardwareOutput()) {
1060            ALOGE("no current audio output");
1061        }
1062
1063        if ((mPlayer != NULL) && (mNextClient->getPlayer() != NULL)) {
1064            mPlayer->setNextPlayer(mNextClient->getPlayer());
1065        }
1066    }
1067
1068    return OK;
1069}
1070
1071status_t MediaPlayerService::Client::seekTo(int msec)
1072{
1073    ALOGV("[%d] seekTo(%d)", mConnId, msec);
1074    sp<MediaPlayerBase> p = getPlayer();
1075    if (p == 0) return UNKNOWN_ERROR;
1076    return p->seekTo(msec);
1077}
1078
1079status_t MediaPlayerService::Client::reset()
1080{
1081    ALOGV("[%d] reset", mConnId);
1082    mRetransmitEndpointValid = false;
1083    sp<MediaPlayerBase> p = getPlayer();
1084    if (p == 0) return UNKNOWN_ERROR;
1085    return p->reset();
1086}
1087
1088status_t MediaPlayerService::Client::setAudioStreamType(audio_stream_type_t type)
1089{
1090    ALOGV("[%d] setAudioStreamType(%d)", mConnId, type);
1091    // TODO: for hardware output, call player instead
1092    Mutex::Autolock l(mLock);
1093    if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1094    return NO_ERROR;
1095}
1096
1097status_t MediaPlayerService::Client::setAudioAttributes_l(const Parcel &parcel)
1098{
1099    if (mAudioAttributes != NULL) { free(mAudioAttributes); }
1100    mAudioAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1101    if (mAudioAttributes == NULL) {
1102        return NO_MEMORY;
1103    }
1104    unmarshallAudioAttributes(parcel, mAudioAttributes);
1105
1106    ALOGV("setAudioAttributes_l() usage=%d content=%d flags=0x%x tags=%s",
1107            mAudioAttributes->usage, mAudioAttributes->content_type, mAudioAttributes->flags,
1108            mAudioAttributes->tags);
1109
1110    if (mAudioOutput != 0) {
1111        mAudioOutput->setAudioAttributes(mAudioAttributes);
1112    }
1113    return NO_ERROR;
1114}
1115
1116status_t MediaPlayerService::Client::setLooping(int loop)
1117{
1118    ALOGV("[%d] setLooping(%d)", mConnId, loop);
1119    mLoop = loop;
1120    sp<MediaPlayerBase> p = getPlayer();
1121    if (p != 0) return p->setLooping(loop);
1122    return NO_ERROR;
1123}
1124
1125status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1126{
1127    ALOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
1128
1129    // for hardware output, call player instead
1130    sp<MediaPlayerBase> p = getPlayer();
1131    {
1132      Mutex::Autolock l(mLock);
1133      if (p != 0 && p->hardwareOutput()) {
1134          MediaPlayerHWInterface* hwp =
1135                  reinterpret_cast<MediaPlayerHWInterface*>(p.get());
1136          return hwp->setVolume(leftVolume, rightVolume);
1137      } else {
1138          if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1139          return NO_ERROR;
1140      }
1141    }
1142
1143    return NO_ERROR;
1144}
1145
1146status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1147{
1148    ALOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
1149    Mutex::Autolock l(mLock);
1150    if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1151    return NO_ERROR;
1152}
1153
1154status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1155{
1156    ALOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
1157    Mutex::Autolock l(mLock);
1158    if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1159    return NO_ERROR;
1160}
1161
1162status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
1163    ALOGV("[%d] setParameter(%d)", mConnId, key);
1164    switch (key) {
1165    case KEY_PARAMETER_AUDIO_ATTRIBUTES:
1166    {
1167        Mutex::Autolock l(mLock);
1168        return setAudioAttributes_l(request);
1169    }
1170    default:
1171        sp<MediaPlayerBase> p = getPlayer();
1172        if (p == 0) { return UNKNOWN_ERROR; }
1173        return p->setParameter(key, request);
1174    }
1175}
1176
1177status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
1178    ALOGV("[%d] getParameter(%d)", mConnId, key);
1179    sp<MediaPlayerBase> p = getPlayer();
1180    if (p == 0) return UNKNOWN_ERROR;
1181    return p->getParameter(key, reply);
1182}
1183
1184status_t MediaPlayerService::Client::setRetransmitEndpoint(
1185        const struct sockaddr_in* endpoint) {
1186
1187    if (NULL != endpoint) {
1188        uint32_t a = ntohl(endpoint->sin_addr.s_addr);
1189        uint16_t p = ntohs(endpoint->sin_port);
1190        ALOGV("[%d] setRetransmitEndpoint(%u.%u.%u.%u:%hu)", mConnId,
1191                (a >> 24), (a >> 16) & 0xFF, (a >> 8) & 0xFF, (a & 0xFF), p);
1192    } else {
1193        ALOGV("[%d] setRetransmitEndpoint = <none>", mConnId);
1194    }
1195
1196    sp<MediaPlayerBase> p = getPlayer();
1197
1198    // Right now, the only valid time to set a retransmit endpoint is before
1199    // player selection has been made (since the presence or absence of a
1200    // retransmit endpoint is going to determine which player is selected during
1201    // setDataSource).
1202    if (p != 0) return INVALID_OPERATION;
1203
1204    if (NULL != endpoint) {
1205        mRetransmitEndpoint = *endpoint;
1206        mRetransmitEndpointValid = true;
1207    } else {
1208        mRetransmitEndpointValid = false;
1209    }
1210
1211    return NO_ERROR;
1212}
1213
1214status_t MediaPlayerService::Client::getRetransmitEndpoint(
1215        struct sockaddr_in* endpoint)
1216{
1217    if (NULL == endpoint)
1218        return BAD_VALUE;
1219
1220    sp<MediaPlayerBase> p = getPlayer();
1221
1222    if (p != NULL)
1223        return p->getRetransmitEndpoint(endpoint);
1224
1225    if (!mRetransmitEndpointValid)
1226        return NO_INIT;
1227
1228    *endpoint = mRetransmitEndpoint;
1229
1230    return NO_ERROR;
1231}
1232
1233void MediaPlayerService::Client::notify(
1234        void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
1235{
1236    Client* client = static_cast<Client*>(cookie);
1237    if (client == NULL) {
1238        return;
1239    }
1240
1241    sp<IMediaPlayerClient> c;
1242    {
1243        Mutex::Autolock l(client->mLock);
1244        c = client->mClient;
1245        if (msg == MEDIA_PLAYBACK_COMPLETE && client->mNextClient != NULL) {
1246            if (client->mAudioOutput != NULL)
1247                client->mAudioOutput->switchToNextOutput();
1248            client->mNextClient->start();
1249            client->mNextClient->mClient->notify(MEDIA_INFO, MEDIA_INFO_STARTED_AS_NEXT, 0, obj);
1250        }
1251    }
1252
1253    if (MEDIA_INFO == msg &&
1254        MEDIA_INFO_METADATA_UPDATE == ext1) {
1255        const media::Metadata::Type metadata_type = ext2;
1256
1257        if(client->shouldDropMetadata(metadata_type)) {
1258            return;
1259        }
1260
1261        // Update the list of metadata that have changed. getMetadata
1262        // also access mMetadataUpdated and clears it.
1263        client->addNewMetadataUpdate(metadata_type);
1264    }
1265
1266    if (c != NULL) {
1267        ALOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
1268        c->notify(msg, ext1, ext2, obj);
1269    }
1270}
1271
1272
1273bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
1274{
1275    Mutex::Autolock lock(mLock);
1276
1277    if (findMetadata(mMetadataDrop, code)) {
1278        return true;
1279    }
1280
1281    if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
1282        return false;
1283    } else {
1284        return true;
1285    }
1286}
1287
1288
1289void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
1290    Mutex::Autolock lock(mLock);
1291    if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1292        mMetadataUpdated.add(metadata_type);
1293    }
1294}
1295
1296#if CALLBACK_ANTAGONIZER
1297const int Antagonizer::interval = 10000; // 10 msecs
1298
1299Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1300    mExit(false), mActive(false), mClient(client), mCb(cb)
1301{
1302    createThread(callbackThread, this);
1303}
1304
1305void Antagonizer::kill()
1306{
1307    Mutex::Autolock _l(mLock);
1308    mActive = false;
1309    mExit = true;
1310    mCondition.wait(mLock);
1311}
1312
1313int Antagonizer::callbackThread(void* user)
1314{
1315    ALOGD("Antagonizer started");
1316    Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1317    while (!p->mExit) {
1318        if (p->mActive) {
1319            ALOGV("send event");
1320            p->mCb(p->mClient, 0, 0, 0);
1321        }
1322        usleep(interval);
1323    }
1324    Mutex::Autolock _l(p->mLock);
1325    p->mCondition.signal();
1326    ALOGD("Antagonizer stopped");
1327    return 0;
1328}
1329#endif
1330
1331#undef LOG_TAG
1332#define LOG_TAG "AudioSink"
1333MediaPlayerService::AudioOutput::AudioOutput(int sessionId, int uid, int pid,
1334        const audio_attributes_t* attr)
1335    : mCallback(NULL),
1336      mCallbackCookie(NULL),
1337      mCallbackData(NULL),
1338      mBytesWritten(0),
1339      mStreamType(AUDIO_STREAM_MUSIC),
1340      mLeftVolume(1.0),
1341      mRightVolume(1.0),
1342      mPlaybackRate(AUDIO_PLAYBACK_RATE_DEFAULT),
1343      mSampleRateHz(0),
1344      mMsecsPerFrame(0),
1345      mFrameSize(0),
1346      mSessionId(sessionId),
1347      mUid(uid),
1348      mPid(pid),
1349      mSendLevel(0.0),
1350      mAuxEffectId(0),
1351      mFlags(AUDIO_OUTPUT_FLAG_NONE)
1352{
1353    ALOGV("AudioOutput(%d)", sessionId);
1354    if (attr != NULL) {
1355        mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1356        if (mAttributes != NULL) {
1357            memcpy(mAttributes, attr, sizeof(audio_attributes_t));
1358            mStreamType = audio_attributes_to_stream_type(attr);
1359        }
1360    } else {
1361        mAttributes = NULL;
1362    }
1363
1364    setMinBufferCount();
1365}
1366
1367MediaPlayerService::AudioOutput::~AudioOutput()
1368{
1369    close();
1370    free(mAttributes);
1371    delete mCallbackData;
1372}
1373
1374//static
1375void MediaPlayerService::AudioOutput::setMinBufferCount()
1376{
1377    char value[PROPERTY_VALUE_MAX];
1378    if (property_get("ro.kernel.qemu", value, 0)) {
1379        mIsOnEmulator = true;
1380        mMinBufferCount = 12;  // to prevent systematic buffer underrun for emulator
1381    }
1382}
1383
1384// static
1385bool MediaPlayerService::AudioOutput::isOnEmulator()
1386{
1387    setMinBufferCount(); // benign race wrt other threads
1388    return mIsOnEmulator;
1389}
1390
1391// static
1392int MediaPlayerService::AudioOutput::getMinBufferCount()
1393{
1394    setMinBufferCount(); // benign race wrt other threads
1395    return mMinBufferCount;
1396}
1397
1398ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1399{
1400    Mutex::Autolock lock(mLock);
1401    if (mTrack == 0) return NO_INIT;
1402    return mTrack->frameCount() * mFrameSize;
1403}
1404
1405ssize_t MediaPlayerService::AudioOutput::frameCount() const
1406{
1407    Mutex::Autolock lock(mLock);
1408    if (mTrack == 0) return NO_INIT;
1409    return mTrack->frameCount();
1410}
1411
1412ssize_t MediaPlayerService::AudioOutput::channelCount() const
1413{
1414    Mutex::Autolock lock(mLock);
1415    if (mTrack == 0) return NO_INIT;
1416    return mTrack->channelCount();
1417}
1418
1419ssize_t MediaPlayerService::AudioOutput::frameSize() const
1420{
1421    Mutex::Autolock lock(mLock);
1422    if (mTrack == 0) return NO_INIT;
1423    return mFrameSize;
1424}
1425
1426uint32_t MediaPlayerService::AudioOutput::latency () const
1427{
1428    Mutex::Autolock lock(mLock);
1429    if (mTrack == 0) return 0;
1430    return mTrack->latency();
1431}
1432
1433float MediaPlayerService::AudioOutput::msecsPerFrame() const
1434{
1435    Mutex::Autolock lock(mLock);
1436    return mMsecsPerFrame;
1437}
1438
1439status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position) const
1440{
1441    Mutex::Autolock lock(mLock);
1442    if (mTrack == 0) return NO_INIT;
1443    return mTrack->getPosition(position);
1444}
1445
1446status_t MediaPlayerService::AudioOutput::getTimestamp(AudioTimestamp &ts) const
1447{
1448    Mutex::Autolock lock(mLock);
1449    if (mTrack == 0) return NO_INIT;
1450    return mTrack->getTimestamp(ts);
1451}
1452
1453// TODO: Remove unnecessary calls to getPlayedOutDurationUs()
1454// as it acquires locks and may query the audio driver.
1455//
1456// Some calls could conceivably retrieve extrapolated data instead of
1457// accessing getTimestamp() or getPosition() every time a data buffer with
1458// a media time is received.
1459//
1460// Calculate duration of played samples if played at normal rate (i.e., 1.0).
1461int64_t MediaPlayerService::AudioOutput::getPlayedOutDurationUs(int64_t nowUs) const
1462{
1463    Mutex::Autolock lock(mLock);
1464    if (mTrack == 0 || mSampleRateHz == 0) {
1465        return 0;
1466    }
1467
1468    uint32_t numFramesPlayed;
1469    int64_t numFramesPlayedAt;
1470    AudioTimestamp ts;
1471    static const int64_t kStaleTimestamp100ms = 100000;
1472
1473    status_t res = mTrack->getTimestamp(ts);
1474    if (res == OK) {                 // case 1: mixing audio tracks and offloaded tracks.
1475        numFramesPlayed = ts.mPosition;
1476        numFramesPlayedAt = ts.mTime.tv_sec * 1000000LL + ts.mTime.tv_nsec / 1000;
1477        const int64_t timestampAge = nowUs - numFramesPlayedAt;
1478        if (timestampAge > kStaleTimestamp100ms) {
1479            // This is an audio FIXME.
1480            // getTimestamp returns a timestamp which may come from audio mixing threads.
1481            // After pausing, the MixerThread may go idle, thus the mTime estimate may
1482            // become stale. Assuming that the MixerThread runs 20ms, with FastMixer at 5ms,
1483            // the max latency should be about 25ms with an average around 12ms (to be verified).
1484            // For safety we use 100ms.
1485            ALOGV("getTimestamp: returned stale timestamp nowUs(%lld) numFramesPlayedAt(%lld)",
1486                    (long long)nowUs, (long long)numFramesPlayedAt);
1487            numFramesPlayedAt = nowUs - kStaleTimestamp100ms;
1488        }
1489        //ALOGD("getTimestamp: OK %d %lld", numFramesPlayed, (long long)numFramesPlayedAt);
1490    } else if (res == WOULD_BLOCK) { // case 2: transitory state on start of a new track
1491        numFramesPlayed = 0;
1492        numFramesPlayedAt = nowUs;
1493        //ALOGD("getTimestamp: WOULD_BLOCK %d %lld",
1494        //        numFramesPlayed, (long long)numFramesPlayedAt);
1495    } else {                         // case 3: transitory at new track or audio fast tracks.
1496        res = mTrack->getPosition(&numFramesPlayed);
1497        CHECK_EQ(res, (status_t)OK);
1498        numFramesPlayedAt = nowUs;
1499        numFramesPlayedAt += 1000LL * mTrack->latency() / 2; /* XXX */
1500        //ALOGD("getPosition: %u %lld", numFramesPlayed, (long long)numFramesPlayedAt);
1501    }
1502
1503    // CHECK_EQ(numFramesPlayed & (1 << 31), 0);  // can't be negative until 12.4 hrs, test
1504    // TODO: remove the (int32_t) casting below as it may overflow at 12.4 hours.
1505    int64_t durationUs = (int64_t)((int32_t)numFramesPlayed * 1000000LL / mSampleRateHz)
1506            + nowUs - numFramesPlayedAt;
1507    if (durationUs < 0) {
1508        // Occurs when numFramesPlayed position is very small and the following:
1509        // (1) In case 1, the time nowUs is computed before getTimestamp() is called and
1510        //     numFramesPlayedAt is greater than nowUs by time more than numFramesPlayed.
1511        // (2) In case 3, using getPosition and adding mAudioSink->latency() to
1512        //     numFramesPlayedAt, by a time amount greater than numFramesPlayed.
1513        //
1514        // Both of these are transitory conditions.
1515        ALOGV("getPlayedOutDurationUs: negative duration %lld set to zero", (long long)durationUs);
1516        durationUs = 0;
1517    }
1518    ALOGV("getPlayedOutDurationUs(%lld) nowUs(%lld) frames(%u) framesAt(%lld)",
1519            (long long)durationUs, (long long)nowUs, numFramesPlayed, (long long)numFramesPlayedAt);
1520    return durationUs;
1521}
1522
1523status_t MediaPlayerService::AudioOutput::getFramesWritten(uint32_t *frameswritten) const
1524{
1525    Mutex::Autolock lock(mLock);
1526    if (mTrack == 0) return NO_INIT;
1527    *frameswritten = mBytesWritten / mFrameSize;
1528    return OK;
1529}
1530
1531status_t MediaPlayerService::AudioOutput::setParameters(const String8& keyValuePairs)
1532{
1533    Mutex::Autolock lock(mLock);
1534    if (mTrack == 0) return NO_INIT;
1535    return mTrack->setParameters(keyValuePairs);
1536}
1537
1538String8  MediaPlayerService::AudioOutput::getParameters(const String8& keys)
1539{
1540    Mutex::Autolock lock(mLock);
1541    if (mTrack == 0) return String8::empty();
1542    return mTrack->getParameters(keys);
1543}
1544
1545void MediaPlayerService::AudioOutput::setAudioAttributes(const audio_attributes_t * attributes) {
1546    Mutex::Autolock lock(mLock);
1547    if (attributes == NULL) {
1548        free(mAttributes);
1549        mAttributes = NULL;
1550    } else {
1551        if (mAttributes == NULL) {
1552            mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1553        }
1554        memcpy(mAttributes, attributes, sizeof(audio_attributes_t));
1555        mStreamType = audio_attributes_to_stream_type(attributes);
1556    }
1557}
1558
1559void MediaPlayerService::AudioOutput::setAudioStreamType(audio_stream_type_t streamType)
1560{
1561    Mutex::Autolock lock(mLock);
1562    // do not allow direct stream type modification if attributes have been set
1563    if (mAttributes == NULL) {
1564        mStreamType = streamType;
1565    }
1566}
1567
1568void MediaPlayerService::AudioOutput::deleteRecycledTrack_l()
1569{
1570    ALOGV("deleteRecycledTrack_l");
1571    if (mRecycledTrack != 0) {
1572
1573        if (mCallbackData != NULL) {
1574            mCallbackData->setOutput(NULL);
1575            mCallbackData->endTrackSwitch();
1576        }
1577
1578        if ((mRecycledTrack->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) {
1579            mRecycledTrack->flush();
1580        }
1581        // An offloaded track isn't flushed because the STREAM_END is reported
1582        // slightly prematurely to allow time for the gapless track switch
1583        // but this means that if we decide not to recycle the track there
1584        // could be a small amount of residual data still playing. We leave
1585        // AudioFlinger to drain the track.
1586
1587        mRecycledTrack.clear();
1588        close_l();
1589        delete mCallbackData;
1590        mCallbackData = NULL;
1591    }
1592}
1593
1594void MediaPlayerService::AudioOutput::close_l()
1595{
1596    mTrack.clear();
1597}
1598
1599status_t MediaPlayerService::AudioOutput::open(
1600        uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
1601        audio_format_t format, int bufferCount,
1602        AudioCallback cb, void *cookie,
1603        audio_output_flags_t flags,
1604        const audio_offload_info_t *offloadInfo,
1605        bool doNotReconnect,
1606        uint32_t suggestedFrameCount)
1607{
1608    ALOGV("open(%u, %d, 0x%x, 0x%x, %d, %d 0x%x)", sampleRate, channelCount, channelMask,
1609                format, bufferCount, mSessionId, flags);
1610
1611    // offloading is only supported in callback mode for now.
1612    // offloadInfo must be present if offload flag is set
1613    if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) &&
1614            ((cb == NULL) || (offloadInfo == NULL))) {
1615        return BAD_VALUE;
1616    }
1617
1618    // compute frame count for the AudioTrack internal buffer
1619    size_t frameCount;
1620    if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1621        frameCount = 0; // AudioTrack will get frame count from AudioFlinger
1622    } else {
1623        // try to estimate the buffer processing fetch size from AudioFlinger.
1624        // framesPerBuffer is approximate and generally correct, except when it's not :-).
1625        uint32_t afSampleRate;
1626        size_t afFrameCount;
1627        if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1628            return NO_INIT;
1629        }
1630        if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1631            return NO_INIT;
1632        }
1633        const size_t framesPerBuffer =
1634                (unsigned long long)sampleRate * afFrameCount / afSampleRate;
1635
1636        if (bufferCount == 0) {
1637            // use suggestedFrameCount
1638            bufferCount = (suggestedFrameCount + framesPerBuffer - 1) / framesPerBuffer;
1639        }
1640        // Check argument bufferCount against the mininum buffer count
1641        if (bufferCount != 0 && bufferCount < mMinBufferCount) {
1642            ALOGV("bufferCount (%d) increased to %d", bufferCount, mMinBufferCount);
1643            bufferCount = mMinBufferCount;
1644        }
1645        // if frameCount is 0, then AudioTrack will get frame count from AudioFlinger
1646        // which will be the minimum size permitted.
1647        frameCount = bufferCount * framesPerBuffer;
1648    }
1649
1650    if (channelMask == CHANNEL_MASK_USE_CHANNEL_ORDER) {
1651        channelMask = audio_channel_out_mask_from_count(channelCount);
1652        if (0 == channelMask) {
1653            ALOGE("open() error, can\'t derive mask for %d audio channels", channelCount);
1654            return NO_INIT;
1655        }
1656    }
1657
1658    Mutex::Autolock lock(mLock);
1659    mCallback = cb;
1660    mCallbackCookie = cookie;
1661
1662    // Check whether we can recycle the track
1663    bool reuse = false;
1664    bool bothOffloaded = false;
1665
1666    if (mRecycledTrack != 0) {
1667        // check whether we are switching between two offloaded tracks
1668        bothOffloaded = (flags & mRecycledTrack->getFlags()
1669                                & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0;
1670
1671        // check if the existing track can be reused as-is, or if a new track needs to be created.
1672        reuse = true;
1673
1674        if ((mCallbackData == NULL && mCallback != NULL) ||
1675                (mCallbackData != NULL && mCallback == NULL)) {
1676            // recycled track uses callbacks but the caller wants to use writes, or vice versa
1677            ALOGV("can't chain callback and write");
1678            reuse = false;
1679        } else if ((mRecycledTrack->getSampleRate() != sampleRate) ||
1680                (mRecycledTrack->channelCount() != (uint32_t)channelCount) ) {
1681            ALOGV("samplerate, channelcount differ: %u/%u Hz, %u/%d ch",
1682                  mRecycledTrack->getSampleRate(), sampleRate,
1683                  mRecycledTrack->channelCount(), channelCount);
1684            reuse = false;
1685        } else if (flags != mFlags) {
1686            ALOGV("output flags differ %08x/%08x", flags, mFlags);
1687            reuse = false;
1688        } else if (mRecycledTrack->format() != format) {
1689            reuse = false;
1690        }
1691    } else {
1692        ALOGV("no track available to recycle");
1693    }
1694
1695    ALOGV_IF(bothOffloaded, "both tracks offloaded");
1696
1697    // If we can't recycle and both tracks are offloaded
1698    // we must close the previous output before opening a new one
1699    if (bothOffloaded && !reuse) {
1700        ALOGV("both offloaded and not recycling");
1701        deleteRecycledTrack_l();
1702    }
1703
1704    sp<AudioTrack> t;
1705    CallbackData *newcbd = NULL;
1706
1707    // We don't attempt to create a new track if we are recycling an
1708    // offloaded track. But, if we are recycling a non-offloaded or we
1709    // are switching where one is offloaded and one isn't then we create
1710    // the new track in advance so that we can read additional stream info
1711
1712    if (!(reuse && bothOffloaded)) {
1713        ALOGV("creating new AudioTrack");
1714
1715        if (mCallback != NULL) {
1716            newcbd = new CallbackData(this);
1717            t = new AudioTrack(
1718                    mStreamType,
1719                    sampleRate,
1720                    format,
1721                    channelMask,
1722                    frameCount,
1723                    flags,
1724                    CallbackWrapper,
1725                    newcbd,
1726                    0,  // notification frames
1727                    mSessionId,
1728                    AudioTrack::TRANSFER_CALLBACK,
1729                    offloadInfo,
1730                    mUid,
1731                    mPid,
1732                    mAttributes,
1733                    doNotReconnect);
1734        } else {
1735            t = new AudioTrack(
1736                    mStreamType,
1737                    sampleRate,
1738                    format,
1739                    channelMask,
1740                    frameCount,
1741                    flags,
1742                    NULL, // callback
1743                    NULL, // user data
1744                    0, // notification frames
1745                    mSessionId,
1746                    AudioTrack::TRANSFER_DEFAULT,
1747                    NULL, // offload info
1748                    mUid,
1749                    mPid,
1750                    mAttributes,
1751                    doNotReconnect);
1752        }
1753
1754        if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1755            ALOGE("Unable to create audio track");
1756            delete newcbd;
1757            // t goes out of scope, so reference count drops to zero
1758            return NO_INIT;
1759        } else {
1760            // successful AudioTrack initialization implies a legacy stream type was generated
1761            // from the audio attributes
1762            mStreamType = t->streamType();
1763        }
1764    }
1765
1766    if (reuse) {
1767        CHECK(mRecycledTrack != NULL);
1768
1769        if (!bothOffloaded) {
1770            if (mRecycledTrack->frameCount() != t->frameCount()) {
1771                ALOGV("framecount differs: %u/%u frames",
1772                      mRecycledTrack->frameCount(), t->frameCount());
1773                reuse = false;
1774            }
1775        }
1776
1777        if (reuse) {
1778            ALOGV("chaining to next output and recycling track");
1779            close_l();
1780            mTrack = mRecycledTrack;
1781            mRecycledTrack.clear();
1782            if (mCallbackData != NULL) {
1783                mCallbackData->setOutput(this);
1784            }
1785            delete newcbd;
1786            return OK;
1787        }
1788    }
1789
1790    // we're not going to reuse the track, unblock and flush it
1791    // this was done earlier if both tracks are offloaded
1792    if (!bothOffloaded) {
1793        deleteRecycledTrack_l();
1794    }
1795
1796    CHECK((t != NULL) && ((mCallback == NULL) || (newcbd != NULL)));
1797
1798    mCallbackData = newcbd;
1799    ALOGV("setVolume");
1800    t->setVolume(mLeftVolume, mRightVolume);
1801
1802    mSampleRateHz = sampleRate;
1803    mFlags = flags;
1804    mMsecsPerFrame = 1E3f / (mPlaybackRate.mSpeed * sampleRate);
1805    mFrameSize = t->frameSize();
1806    uint32_t pos;
1807    if (t->getPosition(&pos) == OK) {
1808        mBytesWritten = uint64_t(pos) * mFrameSize;
1809    }
1810    mTrack = t;
1811
1812    status_t res = NO_ERROR;
1813    // Note some output devices may give us a direct track even though we don't specify it.
1814    // Example: Line application b/17459982.
1815    if ((t->getFlags() & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) {
1816        res = t->setPlaybackRate(mPlaybackRate);
1817        if (res == NO_ERROR) {
1818            t->setAuxEffectSendLevel(mSendLevel);
1819            res = t->attachAuxEffect(mAuxEffectId);
1820        }
1821    }
1822    ALOGV("open() DONE status %d", res);
1823    return res;
1824}
1825
1826status_t MediaPlayerService::AudioOutput::start()
1827{
1828    ALOGV("start");
1829    Mutex::Autolock lock(mLock);
1830    if (mCallbackData != NULL) {
1831        mCallbackData->endTrackSwitch();
1832    }
1833    if (mTrack != 0) {
1834        mTrack->setVolume(mLeftVolume, mRightVolume);
1835        mTrack->setAuxEffectSendLevel(mSendLevel);
1836        return mTrack->start();
1837    }
1838    return NO_INIT;
1839}
1840
1841void MediaPlayerService::AudioOutput::setNextOutput(const sp<AudioOutput>& nextOutput) {
1842    Mutex::Autolock lock(mLock);
1843    mNextOutput = nextOutput;
1844}
1845
1846void MediaPlayerService::AudioOutput::switchToNextOutput() {
1847    ALOGV("switchToNextOutput");
1848
1849    // Try to acquire the callback lock before moving track (without incurring deadlock).
1850    const unsigned kMaxSwitchTries = 100;
1851    Mutex::Autolock lock(mLock);
1852    for (unsigned tries = 0;;) {
1853        if (mTrack == 0) {
1854            return;
1855        }
1856        if (mNextOutput != NULL && mNextOutput != this) {
1857            if (mCallbackData != NULL) {
1858                // two alternative approaches
1859#if 1
1860                CallbackData *callbackData = mCallbackData;
1861                mLock.unlock();
1862                // proper acquisition sequence
1863                callbackData->lock();
1864                mLock.lock();
1865                // Caution: it is unlikely that someone deleted our callback or changed our target
1866                if (callbackData != mCallbackData || mNextOutput == NULL || mNextOutput == this) {
1867                    // fatal if we are starved out.
1868                    LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
1869                            "switchToNextOutput() cannot obtain correct lock sequence");
1870                    callbackData->unlock();
1871                    continue;
1872                }
1873                callbackData->mSwitching = true; // begin track switch
1874#else
1875                // tryBeginTrackSwitch() returns false if the callback has the lock.
1876                if (!mCallbackData->tryBeginTrackSwitch()) {
1877                    // fatal if we are starved out.
1878                    LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
1879                            "switchToNextOutput() cannot obtain callback lock");
1880                    mLock.unlock();
1881                    usleep(5 * 1000 /* usec */); // allow callback to use AudioOutput
1882                    mLock.lock();
1883                    continue;
1884                }
1885#endif
1886            }
1887
1888            Mutex::Autolock nextLock(mNextOutput->mLock);
1889
1890            // If the next output track is not NULL, then it has been
1891            // opened already for playback.
1892            // This is possible even without the next player being started,
1893            // for example, the next player could be prepared and seeked.
1894            //
1895            // Presuming it isn't advisable to force the track over.
1896             if (mNextOutput->mTrack == NULL) {
1897                ALOGD("Recycling track for gapless playback");
1898                delete mNextOutput->mCallbackData;
1899                mNextOutput->mCallbackData = mCallbackData;
1900                mNextOutput->mRecycledTrack = mTrack;
1901                mNextOutput->mSampleRateHz = mSampleRateHz;
1902                mNextOutput->mMsecsPerFrame = mMsecsPerFrame;
1903                mNextOutput->mBytesWritten = mBytesWritten;
1904                mNextOutput->mFlags = mFlags;
1905                mNextOutput->mFrameSize = mFrameSize;
1906                close_l();
1907                mCallbackData = NULL;  // destruction handled by mNextOutput
1908            } else {
1909                ALOGW("Ignoring gapless playback because next player has already started");
1910                // remove track in case resource needed for future players.
1911                if (mCallbackData != NULL) {
1912                    mCallbackData->endTrackSwitch();  // release lock for callbacks before close.
1913                }
1914                close_l();
1915            }
1916        }
1917        break;
1918    }
1919}
1920
1921ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size, bool blocking)
1922{
1923    Mutex::Autolock lock(mLock);
1924    LOG_ALWAYS_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
1925
1926    //ALOGV("write(%p, %u)", buffer, size);
1927    if (mTrack != 0) {
1928        ssize_t ret = mTrack->write(buffer, size, blocking);
1929        if (ret >= 0) {
1930            mBytesWritten += ret;
1931        }
1932        return ret;
1933    }
1934    return NO_INIT;
1935}
1936
1937void MediaPlayerService::AudioOutput::stop()
1938{
1939    ALOGV("stop");
1940    Mutex::Autolock lock(mLock);
1941    mBytesWritten = 0;
1942    if (mTrack != 0) mTrack->stop();
1943}
1944
1945void MediaPlayerService::AudioOutput::flush()
1946{
1947    ALOGV("flush");
1948    Mutex::Autolock lock(mLock);
1949    mBytesWritten = 0;
1950    if (mTrack != 0) mTrack->flush();
1951}
1952
1953void MediaPlayerService::AudioOutput::pause()
1954{
1955    ALOGV("pause");
1956    Mutex::Autolock lock(mLock);
1957    if (mTrack != 0) mTrack->pause();
1958}
1959
1960void MediaPlayerService::AudioOutput::close()
1961{
1962    ALOGV("close");
1963    sp<AudioTrack> track;
1964    {
1965        Mutex::Autolock lock(mLock);
1966        track = mTrack;
1967        close_l(); // clears mTrack
1968    }
1969    // destruction of the track occurs outside of mutex.
1970}
1971
1972void MediaPlayerService::AudioOutput::setVolume(float left, float right)
1973{
1974    ALOGV("setVolume(%f, %f)", left, right);
1975    Mutex::Autolock lock(mLock);
1976    mLeftVolume = left;
1977    mRightVolume = right;
1978    if (mTrack != 0) {
1979        mTrack->setVolume(left, right);
1980    }
1981}
1982
1983status_t MediaPlayerService::AudioOutput::setPlaybackRate(const AudioPlaybackRate &rate)
1984{
1985    ALOGV("setPlaybackRate(%f %f %d %d)",
1986                rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
1987    Mutex::Autolock lock(mLock);
1988    if (mTrack == 0) {
1989        // remember rate so that we can set it when the track is opened
1990        mPlaybackRate = rate;
1991        return OK;
1992    }
1993    status_t res = mTrack->setPlaybackRate(rate);
1994    if (res != NO_ERROR) {
1995        return res;
1996    }
1997    // rate.mSpeed is always greater than 0 if setPlaybackRate succeeded
1998    CHECK_GT(rate.mSpeed, 0.f);
1999    mPlaybackRate = rate;
2000    if (mSampleRateHz != 0) {
2001        mMsecsPerFrame = 1E3f / (rate.mSpeed * mSampleRateHz);
2002    }
2003    return res;
2004}
2005
2006status_t MediaPlayerService::AudioOutput::getPlaybackRate(AudioPlaybackRate *rate)
2007{
2008    ALOGV("setPlaybackRate");
2009    Mutex::Autolock lock(mLock);
2010    if (mTrack == 0) {
2011        return NO_INIT;
2012    }
2013    *rate = mTrack->getPlaybackRate();
2014    return NO_ERROR;
2015}
2016
2017status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
2018{
2019    ALOGV("setAuxEffectSendLevel(%f)", level);
2020    Mutex::Autolock lock(mLock);
2021    mSendLevel = level;
2022    if (mTrack != 0) {
2023        return mTrack->setAuxEffectSendLevel(level);
2024    }
2025    return NO_ERROR;
2026}
2027
2028status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
2029{
2030    ALOGV("attachAuxEffect(%d)", effectId);
2031    Mutex::Autolock lock(mLock);
2032    mAuxEffectId = effectId;
2033    if (mTrack != 0) {
2034        return mTrack->attachAuxEffect(effectId);
2035    }
2036    return NO_ERROR;
2037}
2038
2039// static
2040void MediaPlayerService::AudioOutput::CallbackWrapper(
2041        int event, void *cookie, void *info) {
2042    //ALOGV("callbackwrapper");
2043    CallbackData *data = (CallbackData*)cookie;
2044    // lock to ensure we aren't caught in the middle of a track switch.
2045    data->lock();
2046    AudioOutput *me = data->getOutput();
2047    AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
2048    if (me == NULL) {
2049        // no output set, likely because the track was scheduled to be reused
2050        // by another player, but the format turned out to be incompatible.
2051        data->unlock();
2052        if (buffer != NULL) {
2053            buffer->size = 0;
2054        }
2055        return;
2056    }
2057
2058    switch(event) {
2059    case AudioTrack::EVENT_MORE_DATA: {
2060        size_t actualSize = (*me->mCallback)(
2061                me, buffer->raw, buffer->size, me->mCallbackCookie,
2062                CB_EVENT_FILL_BUFFER);
2063
2064        // Log when no data is returned from the callback.
2065        // (1) We may have no data (especially with network streaming sources).
2066        // (2) We may have reached the EOS and the audio track is not stopped yet.
2067        // Note that AwesomePlayer/AudioPlayer will only return zero size when it reaches the EOS.
2068        // NuPlayerRenderer will return zero when it doesn't have data (it doesn't block to fill).
2069        //
2070        // This is a benign busy-wait, with the next data request generated 10 ms or more later;
2071        // nevertheless for power reasons, we don't want to see too many of these.
2072
2073        ALOGV_IF(actualSize == 0 && buffer->size > 0, "callbackwrapper: empty buffer returned");
2074
2075        me->mBytesWritten += actualSize;  // benign race with reader.
2076        buffer->size = actualSize;
2077        } break;
2078
2079    case AudioTrack::EVENT_STREAM_END:
2080        // currently only occurs for offloaded callbacks
2081        ALOGV("callbackwrapper: deliver EVENT_STREAM_END");
2082        (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2083                me->mCallbackCookie, CB_EVENT_STREAM_END);
2084        break;
2085
2086    case AudioTrack::EVENT_NEW_IAUDIOTRACK :
2087        ALOGV("callbackwrapper: deliver EVENT_TEAR_DOWN");
2088        (*me->mCallback)(me,  NULL /* buffer */, 0 /* size */,
2089                me->mCallbackCookie, CB_EVENT_TEAR_DOWN);
2090        break;
2091
2092    case AudioTrack::EVENT_UNDERRUN:
2093        // This occurs when there is no data available, typically
2094        // when there is a failure to supply data to the AudioTrack.  It can also
2095        // occur in non-offloaded mode when the audio device comes out of standby.
2096        //
2097        // If an AudioTrack underruns it outputs silence. Since this happens suddenly
2098        // it may sound like an audible pop or glitch.
2099        //
2100        // The underrun event is sent once per track underrun; the condition is reset
2101        // when more data is sent to the AudioTrack.
2102        ALOGI("callbackwrapper: EVENT_UNDERRUN (discarded)");
2103        break;
2104
2105    default:
2106        ALOGE("received unknown event type: %d inside CallbackWrapper !", event);
2107    }
2108
2109    data->unlock();
2110}
2111
2112int MediaPlayerService::AudioOutput::getSessionId() const
2113{
2114    Mutex::Autolock lock(mLock);
2115    return mSessionId;
2116}
2117
2118uint32_t MediaPlayerService::AudioOutput::getSampleRate() const
2119{
2120    Mutex::Autolock lock(mLock);
2121    if (mTrack == 0) return 0;
2122    return mTrack->getSampleRate();
2123}
2124
2125////////////////////////////////////////////////////////////////////////////////
2126
2127struct CallbackThread : public Thread {
2128    CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
2129                   MediaPlayerBase::AudioSink::AudioCallback cb,
2130                   void *cookie);
2131
2132protected:
2133    virtual ~CallbackThread();
2134
2135    virtual bool threadLoop();
2136
2137private:
2138    wp<MediaPlayerBase::AudioSink> mSink;
2139    MediaPlayerBase::AudioSink::AudioCallback mCallback;
2140    void *mCookie;
2141    void *mBuffer;
2142    size_t mBufferSize;
2143
2144    CallbackThread(const CallbackThread &);
2145    CallbackThread &operator=(const CallbackThread &);
2146};
2147
2148CallbackThread::CallbackThread(
2149        const wp<MediaPlayerBase::AudioSink> &sink,
2150        MediaPlayerBase::AudioSink::AudioCallback cb,
2151        void *cookie)
2152    : mSink(sink),
2153      mCallback(cb),
2154      mCookie(cookie),
2155      mBuffer(NULL),
2156      mBufferSize(0) {
2157}
2158
2159CallbackThread::~CallbackThread() {
2160    if (mBuffer) {
2161        free(mBuffer);
2162        mBuffer = NULL;
2163    }
2164}
2165
2166bool CallbackThread::threadLoop() {
2167    sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
2168    if (sink == NULL) {
2169        return false;
2170    }
2171
2172    if (mBuffer == NULL) {
2173        mBufferSize = sink->bufferSize();
2174        mBuffer = malloc(mBufferSize);
2175    }
2176
2177    size_t actualSize =
2178        (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie,
2179                MediaPlayerBase::AudioSink::CB_EVENT_FILL_BUFFER);
2180
2181    if (actualSize > 0) {
2182        sink->write(mBuffer, actualSize);
2183        // Could return false on sink->write() error or short count.
2184        // Not necessarily appropriate but would work for AudioCache behavior.
2185    }
2186
2187    return true;
2188}
2189
2190////////////////////////////////////////////////////////////////////////////////
2191
2192void MediaPlayerService::addBatteryData(uint32_t params)
2193{
2194    Mutex::Autolock lock(mLock);
2195
2196    int32_t time = systemTime() / 1000000L;
2197
2198    // change audio output devices. This notification comes from AudioFlinger
2199    if ((params & kBatteryDataSpeakerOn)
2200            || (params & kBatteryDataOtherAudioDeviceOn)) {
2201
2202        int deviceOn[NUM_AUDIO_DEVICES];
2203        for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2204            deviceOn[i] = 0;
2205        }
2206
2207        if ((params & kBatteryDataSpeakerOn)
2208                && (params & kBatteryDataOtherAudioDeviceOn)) {
2209            deviceOn[SPEAKER_AND_OTHER] = 1;
2210        } else if (params & kBatteryDataSpeakerOn) {
2211            deviceOn[SPEAKER] = 1;
2212        } else {
2213            deviceOn[OTHER_AUDIO_DEVICE] = 1;
2214        }
2215
2216        for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2217            if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
2218
2219                if (mBatteryAudio.refCount > 0) { // if playing audio
2220                    if (!deviceOn[i]) {
2221                        mBatteryAudio.lastTime[i] += time;
2222                        mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2223                        mBatteryAudio.lastTime[i] = 0;
2224                    } else {
2225                        mBatteryAudio.lastTime[i] = 0 - time;
2226                    }
2227                }
2228
2229                mBatteryAudio.deviceOn[i] = deviceOn[i];
2230            }
2231        }
2232        return;
2233    }
2234
2235    // an audio stream is started
2236    if (params & kBatteryDataAudioFlingerStart) {
2237        // record the start time only if currently no other audio
2238        // is being played
2239        if (mBatteryAudio.refCount == 0) {
2240            for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2241                if (mBatteryAudio.deviceOn[i]) {
2242                    mBatteryAudio.lastTime[i] -= time;
2243                }
2244            }
2245        }
2246
2247        mBatteryAudio.refCount ++;
2248        return;
2249
2250    } else if (params & kBatteryDataAudioFlingerStop) {
2251        if (mBatteryAudio.refCount <= 0) {
2252            ALOGW("Battery track warning: refCount is <= 0");
2253            return;
2254        }
2255
2256        // record the stop time only if currently this is the only
2257        // audio being played
2258        if (mBatteryAudio.refCount == 1) {
2259            for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2260                if (mBatteryAudio.deviceOn[i]) {
2261                    mBatteryAudio.lastTime[i] += time;
2262                    mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2263                    mBatteryAudio.lastTime[i] = 0;
2264                }
2265            }
2266        }
2267
2268        mBatteryAudio.refCount --;
2269        return;
2270    }
2271
2272    int uid = IPCThreadState::self()->getCallingUid();
2273    if (uid == AID_MEDIA) {
2274        return;
2275    }
2276    int index = mBatteryData.indexOfKey(uid);
2277
2278    if (index < 0) { // create a new entry for this UID
2279        BatteryUsageInfo info;
2280        info.audioTotalTime = 0;
2281        info.videoTotalTime = 0;
2282        info.audioLastTime = 0;
2283        info.videoLastTime = 0;
2284        info.refCount = 0;
2285
2286        if (mBatteryData.add(uid, info) == NO_MEMORY) {
2287            ALOGE("Battery track error: no memory for new app");
2288            return;
2289        }
2290    }
2291
2292    BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
2293
2294    if (params & kBatteryDataCodecStarted) {
2295        if (params & kBatteryDataTrackAudio) {
2296            info.audioLastTime -= time;
2297            info.refCount ++;
2298        }
2299        if (params & kBatteryDataTrackVideo) {
2300            info.videoLastTime -= time;
2301            info.refCount ++;
2302        }
2303    } else {
2304        if (info.refCount == 0) {
2305            ALOGW("Battery track warning: refCount is already 0");
2306            return;
2307        } else if (info.refCount < 0) {
2308            ALOGE("Battery track error: refCount < 0");
2309            mBatteryData.removeItem(uid);
2310            return;
2311        }
2312
2313        if (params & kBatteryDataTrackAudio) {
2314            info.audioLastTime += time;
2315            info.refCount --;
2316        }
2317        if (params & kBatteryDataTrackVideo) {
2318            info.videoLastTime += time;
2319            info.refCount --;
2320        }
2321
2322        // no stream is being played by this UID
2323        if (info.refCount == 0) {
2324            info.audioTotalTime += info.audioLastTime;
2325            info.audioLastTime = 0;
2326            info.videoTotalTime += info.videoLastTime;
2327            info.videoLastTime = 0;
2328        }
2329    }
2330}
2331
2332status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
2333    Mutex::Autolock lock(mLock);
2334
2335    // audio output devices usage
2336    int32_t time = systemTime() / 1000000L; //in ms
2337    int32_t totalTime;
2338
2339    for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2340        totalTime = mBatteryAudio.totalTime[i];
2341
2342        if (mBatteryAudio.deviceOn[i]
2343            && (mBatteryAudio.lastTime[i] != 0)) {
2344                int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
2345                totalTime += tmpTime;
2346        }
2347
2348        reply->writeInt32(totalTime);
2349        // reset the total time
2350        mBatteryAudio.totalTime[i] = 0;
2351   }
2352
2353    // codec usage
2354    BatteryUsageInfo info;
2355    int size = mBatteryData.size();
2356
2357    reply->writeInt32(size);
2358    int i = 0;
2359
2360    while (i < size) {
2361        info = mBatteryData.valueAt(i);
2362
2363        reply->writeInt32(mBatteryData.keyAt(i)); //UID
2364        reply->writeInt32(info.audioTotalTime);
2365        reply->writeInt32(info.videoTotalTime);
2366
2367        info.audioTotalTime = 0;
2368        info.videoTotalTime = 0;
2369
2370        // remove the UID entry where no stream is being played
2371        if (info.refCount <= 0) {
2372            mBatteryData.removeItemsAt(i);
2373            size --;
2374            i --;
2375        }
2376        i++;
2377    }
2378    return NO_ERROR;
2379}
2380} // namespace android
2381