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