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