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