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