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