MediaPlayerService.cpp revision 4b197e1ffe46eb73ebdb80efc984bfde336b8e92
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 <dirent.h>
27#include <unistd.h>
28
29#include <string.h>
30
31#include <cutils/atomic.h>
32#include <cutils/properties.h> // for property_get
33
34#include <utils/misc.h>
35
36#include <android_runtime/ActivityManager.h>
37
38#include <binder/IPCThreadState.h>
39#include <binder/IServiceManager.h>
40#include <binder/MemoryHeapBase.h>
41#include <binder/MemoryBase.h>
42#include <utils/Errors.h>  // for status_t
43#include <utils/String8.h>
44#include <utils/SystemClock.h>
45#include <utils/Vector.h>
46#include <cutils/properties.h>
47
48#include <media/MediaPlayerInterface.h>
49#include <media/mediarecorder.h>
50#include <media/MediaMetadataRetrieverInterface.h>
51#include <media/Metadata.h>
52#include <media/AudioTrack.h>
53
54#include "MediaRecorderClient.h"
55#include "MediaPlayerService.h"
56#include "MetadataRetrieverClient.h"
57
58#include "MidiFile.h"
59#include "TestPlayerStub.h"
60#include "StagefrightPlayer.h"
61#include "nuplayer/NuPlayerDriver.h"
62
63#include <OMX.h>
64
65/* desktop Linux needs a little help with gettid() */
66#if defined(HAVE_GETTID) && !defined(HAVE_ANDROID_OS)
67#define __KERNEL__
68# include <linux/unistd.h>
69#ifdef _syscall0
70_syscall0(pid_t,gettid)
71#else
72pid_t gettid() { return syscall(__NR_gettid);}
73#endif
74#undef __KERNEL__
75#endif
76
77namespace {
78using android::media::Metadata;
79using android::status_t;
80using android::OK;
81using android::BAD_VALUE;
82using android::NOT_ENOUGH_DATA;
83using android::Parcel;
84
85// Max number of entries in the filter.
86const int kMaxFilterSize = 64;  // I pulled that out of thin air.
87
88// FIXME: Move all the metadata related function in the Metadata.cpp
89
90
91// Unmarshall a filter from a Parcel.
92// Filter format in a parcel:
93//
94//  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
95// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
96// |                       number of entries (n)                   |
97// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
98// |                       metadata type 1                         |
99// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
100// |                       metadata type 2                         |
101// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
102//  ....
103// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
104// |                       metadata type n                         |
105// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
106//
107// @param p Parcel that should start with a filter.
108// @param[out] filter On exit contains the list of metadata type to be
109//                    filtered.
110// @param[out] status On exit contains the status code to be returned.
111// @return true if the parcel starts with a valid filter.
112bool unmarshallFilter(const Parcel& p,
113                      Metadata::Filter *filter,
114                      status_t *status)
115{
116    int32_t val;
117    if (p.readInt32(&val) != OK)
118    {
119        LOGE("Failed to read filter's length");
120        *status = NOT_ENOUGH_DATA;
121        return false;
122    }
123
124    if( val > kMaxFilterSize || val < 0)
125    {
126        LOGE("Invalid filter len %d", val);
127        *status = BAD_VALUE;
128        return false;
129    }
130
131    const size_t num = val;
132
133    filter->clear();
134    filter->setCapacity(num);
135
136    size_t size = num * sizeof(Metadata::Type);
137
138
139    if (p.dataAvail() < size)
140    {
141        LOGE("Filter too short expected %d but got %d", size, p.dataAvail());
142        *status = NOT_ENOUGH_DATA;
143        return false;
144    }
145
146    const Metadata::Type *data =
147            static_cast<const Metadata::Type*>(p.readInplace(size));
148
149    if (NULL == data)
150    {
151        LOGE("Filter had no data");
152        *status = BAD_VALUE;
153        return false;
154    }
155
156    // TODO: The stl impl of vector would be more efficient here
157    // because it degenerates into a memcpy on pod types. Try to
158    // replace later or use stl::set.
159    for (size_t i = 0; i < num; ++i)
160    {
161        filter->add(*data);
162        ++data;
163    }
164    *status = OK;
165    return true;
166}
167
168// @param filter Of metadata type.
169// @param val To be searched.
170// @return true if a match was found.
171bool findMetadata(const Metadata::Filter& filter, const int32_t val)
172{
173    // Deal with empty and ANY right away
174    if (filter.isEmpty()) return false;
175    if (filter[0] == Metadata::kAny) return true;
176
177    return filter.indexOf(val) >= 0;
178}
179
180}  // anonymous namespace
181
182
183namespace android {
184
185// TODO: Temp hack until we can register players
186typedef struct {
187    const char *extension;
188    const player_type playertype;
189} extmap;
190extmap FILE_EXTS [] =  {
191        {".mid", SONIVOX_PLAYER},
192        {".midi", SONIVOX_PLAYER},
193        {".smf", SONIVOX_PLAYER},
194        {".xmf", SONIVOX_PLAYER},
195        {".imy", SONIVOX_PLAYER},
196        {".rtttl", SONIVOX_PLAYER},
197        {".rtx", SONIVOX_PLAYER},
198        {".ota", SONIVOX_PLAYER},
199};
200
201// TODO: Find real cause of Audio/Video delay in PV framework and remove this workaround
202/* static */ int MediaPlayerService::AudioOutput::mMinBufferCount = 4;
203/* static */ bool MediaPlayerService::AudioOutput::mIsOnEmulator = false;
204
205void MediaPlayerService::instantiate() {
206    defaultServiceManager()->addService(
207            String16("media.player"), new MediaPlayerService());
208}
209
210MediaPlayerService::MediaPlayerService()
211{
212    LOGV("MediaPlayerService created");
213    mNextConnId = 1;
214}
215
216MediaPlayerService::~MediaPlayerService()
217{
218    LOGV("MediaPlayerService destroyed");
219}
220
221sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(pid_t pid)
222{
223    sp<MediaRecorderClient> recorder = new MediaRecorderClient(this, pid);
224    wp<MediaRecorderClient> w = recorder;
225    Mutex::Autolock lock(mLock);
226    mMediaRecorderClients.add(w);
227    LOGV("Create new media recorder client from pid %d", pid);
228    return recorder;
229}
230
231void MediaPlayerService::removeMediaRecorderClient(wp<MediaRecorderClient> client)
232{
233    Mutex::Autolock lock(mLock);
234    mMediaRecorderClients.remove(client);
235    LOGV("Delete media recorder client");
236}
237
238sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever(pid_t pid)
239{
240    sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
241    LOGV("Create new media retriever from pid %d", pid);
242    return retriever;
243}
244
245sp<IMediaPlayer> MediaPlayerService::create(
246        pid_t pid, const sp<IMediaPlayerClient>& client, const char* url,
247        const KeyedVector<String8, String8> *headers, int audioSessionId)
248{
249    int32_t connId = android_atomic_inc(&mNextConnId);
250    sp<Client> c = new Client(this, pid, connId, client, audioSessionId);
251    LOGV("Create new client(%d) from pid %d, url=%s, connId=%d, audioSessionId=%d",
252            connId, pid, url, connId, audioSessionId);
253    if (NO_ERROR != c->setDataSource(url, headers))
254    {
255        c.clear();
256        return c;
257    }
258    wp<Client> w = c;
259    Mutex::Autolock lock(mLock);
260    mClients.add(w);
261    return c;
262}
263
264sp<IMediaPlayer> MediaPlayerService::create(pid_t pid, const sp<IMediaPlayerClient>& client,
265        int fd, int64_t offset, int64_t length, int audioSessionId)
266{
267    int32_t connId = android_atomic_inc(&mNextConnId);
268    sp<Client> c = new Client(this, pid, connId, client, audioSessionId);
269    LOGV("Create new client(%d) from pid %d, fd=%d, offset=%lld, length=%lld, audioSessionId=%d",
270            connId, pid, fd, offset, length, audioSessionId);
271    if (NO_ERROR != c->setDataSource(fd, offset, length)) {
272        c.clear();
273    } else {
274        wp<Client> w = c;
275        Mutex::Autolock lock(mLock);
276        mClients.add(w);
277    }
278    ::close(fd);
279    return c;
280}
281
282sp<IMediaPlayer> MediaPlayerService::create(
283        pid_t pid, const sp<IMediaPlayerClient> &client,
284        const sp<IStreamSource> &source, int audioSessionId) {
285    int32_t connId = android_atomic_inc(&mNextConnId);
286    sp<Client> c = new Client(this, pid, connId, client, audioSessionId);
287
288    LOGV("Create new client(%d) from pid %d, audioSessionId=%d",
289         connId, pid, audioSessionId);
290
291    if (OK != c->setDataSource(source)) {
292        c.clear();
293    } else {
294        wp<Client> w = c;
295        Mutex::Autolock lock(mLock);
296        mClients.add(w);
297    }
298
299    return c;
300}
301
302sp<IOMX> MediaPlayerService::getOMX() {
303    Mutex::Autolock autoLock(mLock);
304
305    if (mOMX.get() == NULL) {
306        mOMX = new OMX;
307    }
308
309    return mOMX;
310}
311
312status_t MediaPlayerService::AudioCache::dump(int fd, const Vector<String16>& args) const
313{
314    const size_t SIZE = 256;
315    char buffer[SIZE];
316    String8 result;
317
318    result.append(" AudioCache\n");
319    if (mHeap != 0) {
320        snprintf(buffer, 255, "  heap base(%p), size(%d), flags(%d), device(%s)\n",
321                mHeap->getBase(), mHeap->getSize(), mHeap->getFlags(), mHeap->getDevice());
322        result.append(buffer);
323    }
324    snprintf(buffer, 255, "  msec per frame(%f), channel count(%d), format(%d), frame count(%ld)\n",
325            mMsecsPerFrame, mChannelCount, mFormat, mFrameCount);
326    result.append(buffer);
327    snprintf(buffer, 255, "  sample rate(%d), size(%d), error(%d), command complete(%s)\n",
328            mSampleRate, mSize, mError, mCommandComplete?"true":"false");
329    result.append(buffer);
330    ::write(fd, result.string(), result.size());
331    return NO_ERROR;
332}
333
334status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
335{
336    const size_t SIZE = 256;
337    char buffer[SIZE];
338    String8 result;
339
340    result.append(" AudioOutput\n");
341    snprintf(buffer, 255, "  stream type(%d), left - right volume(%f, %f)\n",
342            mStreamType, mLeftVolume, mRightVolume);
343    result.append(buffer);
344    snprintf(buffer, 255, "  msec per frame(%f), latency (%d)\n",
345            mMsecsPerFrame, mLatency);
346    result.append(buffer);
347    snprintf(buffer, 255, "  aux effect id(%d), send level (%f)\n",
348            mAuxEffectId, mSendLevel);
349    result.append(buffer);
350
351    ::write(fd, result.string(), result.size());
352    if (mTrack != 0) {
353        mTrack->dump(fd, args);
354    }
355    return NO_ERROR;
356}
357
358status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args) const
359{
360    const size_t SIZE = 256;
361    char buffer[SIZE];
362    String8 result;
363    result.append(" Client\n");
364    snprintf(buffer, 255, "  pid(%d), connId(%d), status(%d), looping(%s)\n",
365            mPid, mConnId, mStatus, mLoop?"true": "false");
366    result.append(buffer);
367    write(fd, result.string(), result.size());
368    if (mAudioOutput != 0) {
369        mAudioOutput->dump(fd, args);
370    }
371    write(fd, "\n", 1);
372    return NO_ERROR;
373}
374
375static int myTid() {
376#ifdef HAVE_GETTID
377    return gettid();
378#else
379    return getpid();
380#endif
381}
382
383#if defined(__arm__)
384extern "C" void get_malloc_leak_info(uint8_t** info, size_t* overallSize,
385        size_t* infoSize, size_t* totalMemory, size_t* backtraceSize);
386extern "C" void free_malloc_leak_info(uint8_t* info);
387
388// Use the String-class below instead of String8 to allocate all memory
389// beforehand and not reenter the heap while we are examining it...
390struct MyString8 {
391    static const size_t MAX_SIZE = 256 * 1024;
392
393    MyString8()
394        : mPtr((char *)malloc(MAX_SIZE)) {
395        *mPtr = '\0';
396    }
397
398    ~MyString8() {
399        free(mPtr);
400    }
401
402    void append(const char *s) {
403        strcat(mPtr, s);
404    }
405
406    const char *string() const {
407        return mPtr;
408    }
409
410    size_t size() const {
411        return strlen(mPtr);
412    }
413
414private:
415    char *mPtr;
416
417    MyString8(const MyString8 &);
418    MyString8 &operator=(const MyString8 &);
419};
420
421void memStatus(int fd, const Vector<String16>& args)
422{
423    const size_t SIZE = 256;
424    char buffer[SIZE];
425    MyString8 result;
426
427    typedef struct {
428        size_t size;
429        size_t dups;
430        intptr_t * backtrace;
431    } AllocEntry;
432
433    uint8_t *info = NULL;
434    size_t overallSize = 0;
435    size_t infoSize = 0;
436    size_t totalMemory = 0;
437    size_t backtraceSize = 0;
438
439    get_malloc_leak_info(&info, &overallSize, &infoSize, &totalMemory, &backtraceSize);
440    if (info) {
441        uint8_t *ptr = info;
442        size_t count = overallSize / infoSize;
443
444        snprintf(buffer, SIZE, " Allocation count %i\n", count);
445        result.append(buffer);
446        snprintf(buffer, SIZE, " Total memory %i\n", totalMemory);
447        result.append(buffer);
448
449        AllocEntry * entries = new AllocEntry[count];
450
451        for (size_t i = 0; i < count; i++) {
452            // Each entry should be size_t, size_t, intptr_t[backtraceSize]
453            AllocEntry *e = &entries[i];
454
455            e->size = *reinterpret_cast<size_t *>(ptr);
456            ptr += sizeof(size_t);
457
458            e->dups = *reinterpret_cast<size_t *>(ptr);
459            ptr += sizeof(size_t);
460
461            e->backtrace = reinterpret_cast<intptr_t *>(ptr);
462            ptr += sizeof(intptr_t) * backtraceSize;
463        }
464
465        // Now we need to sort the entries.  They come sorted by size but
466        // not by stack trace which causes problems using diff.
467        bool moved;
468        do {
469            moved = false;
470            for (size_t i = 0; i < (count - 1); i++) {
471                AllocEntry *e1 = &entries[i];
472                AllocEntry *e2 = &entries[i+1];
473
474                bool swap = e1->size < e2->size;
475                if (e1->size == e2->size) {
476                    for(size_t j = 0; j < backtraceSize; j++) {
477                        if (e1->backtrace[j] == e2->backtrace[j]) {
478                            continue;
479                        }
480                        swap = e1->backtrace[j] < e2->backtrace[j];
481                        break;
482                    }
483                }
484                if (swap) {
485                    AllocEntry t = entries[i];
486                    entries[i] = entries[i+1];
487                    entries[i+1] = t;
488                    moved = true;
489                }
490            }
491        } while (moved);
492
493        for (size_t i = 0; i < count; i++) {
494            AllocEntry *e = &entries[i];
495
496            snprintf(buffer, SIZE, "size %8i, dup %4i, ", e->size, e->dups);
497            result.append(buffer);
498            for (size_t ct = 0; (ct < backtraceSize) && e->backtrace[ct]; ct++) {
499                if (ct) {
500                    result.append(", ");
501                }
502                snprintf(buffer, SIZE, "0x%08x", e->backtrace[ct]);
503                result.append(buffer);
504            }
505            result.append("\n");
506        }
507
508        delete[] entries;
509        free_malloc_leak_info(info);
510    }
511
512    write(fd, result.string(), result.size());
513}
514#endif
515
516status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
517{
518    const size_t SIZE = 256;
519    char buffer[SIZE];
520    String8 result;
521    if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
522        snprintf(buffer, SIZE, "Permission Denial: "
523                "can't dump MediaPlayerService from pid=%d, uid=%d\n",
524                IPCThreadState::self()->getCallingPid(),
525                IPCThreadState::self()->getCallingUid());
526        result.append(buffer);
527    } else {
528        Mutex::Autolock lock(mLock);
529        for (int i = 0, n = mClients.size(); i < n; ++i) {
530            sp<Client> c = mClients[i].promote();
531            if (c != 0) c->dump(fd, args);
532        }
533        if (mMediaRecorderClients.size() == 0) {
534                result.append(" No media recorder client\n\n");
535        } else {
536            for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
537                sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
538                snprintf(buffer, 255, " MediaRecorderClient pid(%d)\n", c->mPid);
539                result.append(buffer);
540                write(fd, result.string(), result.size());
541                result = "\n";
542                c->dump(fd, args);
543            }
544        }
545
546        result.append(" Files opened and/or mapped:\n");
547        snprintf(buffer, SIZE, "/proc/%d/maps", myTid());
548        FILE *f = fopen(buffer, "r");
549        if (f) {
550            while (!feof(f)) {
551                fgets(buffer, SIZE, f);
552                if (strstr(buffer, " /mnt/sdcard/") ||
553                    strstr(buffer, " /system/sounds/") ||
554                    strstr(buffer, " /data/") ||
555                    strstr(buffer, " /system/media/")) {
556                    result.append("  ");
557                    result.append(buffer);
558                }
559            }
560            fclose(f);
561        } else {
562            result.append("couldn't open ");
563            result.append(buffer);
564            result.append("\n");
565        }
566
567        snprintf(buffer, SIZE, "/proc/%d/fd", myTid());
568        DIR *d = opendir(buffer);
569        if (d) {
570            struct dirent *ent;
571            while((ent = readdir(d)) != NULL) {
572                if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
573                    snprintf(buffer, SIZE, "/proc/%d/fd/%s", myTid(), ent->d_name);
574                    struct stat s;
575                    if (lstat(buffer, &s) == 0) {
576                        if ((s.st_mode & S_IFMT) == S_IFLNK) {
577                            char linkto[256];
578                            int len = readlink(buffer, linkto, sizeof(linkto));
579                            if(len > 0) {
580                                if(len > 255) {
581                                    linkto[252] = '.';
582                                    linkto[253] = '.';
583                                    linkto[254] = '.';
584                                    linkto[255] = 0;
585                                } else {
586                                    linkto[len] = 0;
587                                }
588                                if (strstr(linkto, "/mnt/sdcard/") == linkto ||
589                                    strstr(linkto, "/system/sounds/") == linkto ||
590                                    strstr(linkto, "/data/") == linkto ||
591                                    strstr(linkto, "/system/media/") == linkto) {
592                                    result.append("  ");
593                                    result.append(buffer);
594                                    result.append(" -> ");
595                                    result.append(linkto);
596                                    result.append("\n");
597                                }
598                            }
599                        } else {
600                            result.append("  unexpected type for ");
601                            result.append(buffer);
602                            result.append("\n");
603                        }
604                    }
605                }
606            }
607            closedir(d);
608        } else {
609            result.append("couldn't open ");
610            result.append(buffer);
611            result.append("\n");
612        }
613
614#if defined(__arm__)
615        bool dumpMem = false;
616        for (size_t i = 0; i < args.size(); i++) {
617            if (args[i] == String16("-m")) {
618                dumpMem = true;
619            }
620        }
621        if (dumpMem) {
622            memStatus(fd, args);
623        }
624#endif
625    }
626    write(fd, result.string(), result.size());
627    return NO_ERROR;
628}
629
630void MediaPlayerService::removeClient(wp<Client> client)
631{
632    Mutex::Autolock lock(mLock);
633    mClients.remove(client);
634}
635
636MediaPlayerService::Client::Client(const sp<MediaPlayerService>& service, pid_t pid,
637        int32_t connId, const sp<IMediaPlayerClient>& client, int audioSessionId)
638{
639    LOGV("Client(%d) constructor", connId);
640    mPid = pid;
641    mConnId = connId;
642    mService = service;
643    mClient = client;
644    mLoop = false;
645    mStatus = NO_INIT;
646    mAudioSessionId = audioSessionId;
647
648#if CALLBACK_ANTAGONIZER
649    LOGD("create Antagonizer");
650    mAntagonizer = new Antagonizer(notify, this);
651#endif
652}
653
654MediaPlayerService::Client::~Client()
655{
656    LOGV("Client(%d) destructor pid = %d", mConnId, mPid);
657    mAudioOutput.clear();
658    wp<Client> client(this);
659    disconnect();
660    mService->removeClient(client);
661}
662
663void MediaPlayerService::Client::disconnect()
664{
665    LOGV("disconnect(%d) from pid %d", mConnId, mPid);
666    // grab local reference and clear main reference to prevent future
667    // access to object
668    sp<MediaPlayerBase> p;
669    {
670        Mutex::Autolock l(mLock);
671        p = mPlayer;
672    }
673    mClient.clear();
674
675    mPlayer.clear();
676
677    // clear the notification to prevent callbacks to dead client
678    // and reset the player. We assume the player will serialize
679    // access to itself if necessary.
680    if (p != 0) {
681        p->setNotifyCallback(0, 0);
682#if CALLBACK_ANTAGONIZER
683        LOGD("kill Antagonizer");
684        mAntagonizer->kill();
685#endif
686        p->reset();
687    }
688
689    IPCThreadState::self()->flushCommands();
690}
691
692static player_type getDefaultPlayerType() {
693    return STAGEFRIGHT_PLAYER;
694}
695
696player_type getPlayerType(int fd, int64_t offset, int64_t length)
697{
698    char buf[20];
699    lseek(fd, offset, SEEK_SET);
700    read(fd, buf, sizeof(buf));
701    lseek(fd, offset, SEEK_SET);
702
703    long ident = *((long*)buf);
704
705    // Ogg vorbis?
706    if (ident == 0x5367674f) // 'OggS'
707        return STAGEFRIGHT_PLAYER;
708
709    // Some kind of MIDI?
710    EAS_DATA_HANDLE easdata;
711    if (EAS_Init(&easdata) == EAS_SUCCESS) {
712        EAS_FILE locator;
713        locator.path = NULL;
714        locator.fd = fd;
715        locator.offset = offset;
716        locator.length = length;
717        EAS_HANDLE  eashandle;
718        if (EAS_OpenFile(easdata, &locator, &eashandle) == EAS_SUCCESS) {
719            EAS_CloseFile(easdata, eashandle);
720            EAS_Shutdown(easdata);
721            return SONIVOX_PLAYER;
722        }
723        EAS_Shutdown(easdata);
724    }
725
726    return getDefaultPlayerType();
727}
728
729player_type getPlayerType(const char* url)
730{
731    if (TestPlayerStub::canBeUsed(url)) {
732        return TEST_PLAYER;
733    }
734
735    char value[PROPERTY_VALUE_MAX];
736    if (!property_get("media.httplive.disable-nuplayer", value, NULL)
737            || (strcasecmp(value, "true") && strcmp(value, "1"))) {
738        if (!strncasecmp("http://", url, 7)) {
739            size_t len = strlen(url);
740            if (len >= 5 && !strcasecmp(".m3u8", &url[len - 5])) {
741                return NU_PLAYER;
742            }
743
744            if (strstr(url,"m3u8")) {
745                return NU_PLAYER;
746            }
747        }
748    }
749
750    // use MidiFile for MIDI extensions
751    int lenURL = strlen(url);
752    for (int i = 0; i < NELEM(FILE_EXTS); ++i) {
753        int len = strlen(FILE_EXTS[i].extension);
754        int start = lenURL - len;
755        if (start > 0) {
756            if (!strncasecmp(url + start, FILE_EXTS[i].extension, len)) {
757                return FILE_EXTS[i].playertype;
758            }
759        }
760    }
761
762    return getDefaultPlayerType();
763}
764
765static sp<MediaPlayerBase> createPlayer(player_type playerType, void* cookie,
766        notify_callback_f notifyFunc)
767{
768    sp<MediaPlayerBase> p;
769    switch (playerType) {
770        case SONIVOX_PLAYER:
771            LOGV(" create MidiFile");
772            p = new MidiFile();
773            break;
774        case STAGEFRIGHT_PLAYER:
775            LOGV(" create StagefrightPlayer");
776            p = new StagefrightPlayer;
777            break;
778        case NU_PLAYER:
779            LOGV(" create NuPlayer");
780            p = new NuPlayerDriver;
781            break;
782        case TEST_PLAYER:
783            LOGV("Create Test Player stub");
784            p = new TestPlayerStub();
785            break;
786        default:
787            LOGE("Unknown player type: %d", playerType);
788            return NULL;
789    }
790    if (p != NULL) {
791        if (p->initCheck() == NO_ERROR) {
792            p->setNotifyCallback(cookie, notifyFunc);
793        } else {
794            p.clear();
795        }
796    }
797    if (p == NULL) {
798        LOGE("Failed to create player object");
799    }
800    return p;
801}
802
803sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
804{
805    // determine if we have the right player type
806    sp<MediaPlayerBase> p = mPlayer;
807    if ((p != NULL) && (p->playerType() != playerType)) {
808        LOGV("delete player");
809        p.clear();
810    }
811    if (p == NULL) {
812        p = android::createPlayer(playerType, this, notify);
813    }
814    return p;
815}
816
817status_t MediaPlayerService::Client::setDataSource(
818        const char *url, const KeyedVector<String8, String8> *headers)
819{
820    LOGV("setDataSource(%s)", url);
821    if (url == NULL)
822        return UNKNOWN_ERROR;
823
824    if (strncmp(url, "content://", 10) == 0) {
825        // get a filedescriptor for the content Uri and
826        // pass it to the setDataSource(fd) method
827
828        String16 url16(url);
829        int fd = android::openContentProviderFile(url16);
830        if (fd < 0)
831        {
832            LOGE("Couldn't open fd for %s", url);
833            return UNKNOWN_ERROR;
834        }
835        setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
836        close(fd);
837        return mStatus;
838    } else {
839        player_type playerType = getPlayerType(url);
840        LOGV("player type = %d", playerType);
841
842        // create the right type of player
843        sp<MediaPlayerBase> p = createPlayer(playerType);
844        if (p == NULL) return NO_INIT;
845
846        if (!p->hardwareOutput()) {
847            mAudioOutput = new AudioOutput(mAudioSessionId);
848            static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
849        }
850
851        // now set data source
852        LOGV(" setDataSource");
853        mStatus = p->setDataSource(url, headers);
854        if (mStatus == NO_ERROR) {
855            mPlayer = p;
856        } else {
857            LOGE("  error: %d", mStatus);
858        }
859        return mStatus;
860    }
861}
862
863status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
864{
865    LOGV("setDataSource fd=%d, offset=%lld, length=%lld", fd, offset, length);
866    struct stat sb;
867    int ret = fstat(fd, &sb);
868    if (ret != 0) {
869        LOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
870        return UNKNOWN_ERROR;
871    }
872
873    LOGV("st_dev  = %llu", sb.st_dev);
874    LOGV("st_mode = %u", sb.st_mode);
875    LOGV("st_uid  = %lu", sb.st_uid);
876    LOGV("st_gid  = %lu", sb.st_gid);
877    LOGV("st_size = %llu", sb.st_size);
878
879    if (offset >= sb.st_size) {
880        LOGE("offset error");
881        ::close(fd);
882        return UNKNOWN_ERROR;
883    }
884    if (offset + length > sb.st_size) {
885        length = sb.st_size - offset;
886        LOGV("calculated length = %lld", length);
887    }
888
889    player_type playerType = getPlayerType(fd, offset, length);
890    LOGV("player type = %d", playerType);
891
892    // create the right type of player
893    sp<MediaPlayerBase> p = createPlayer(playerType);
894    if (p == NULL) return NO_INIT;
895
896    if (!p->hardwareOutput()) {
897        mAudioOutput = new AudioOutput(mAudioSessionId);
898        static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
899    }
900
901    // now set data source
902    mStatus = p->setDataSource(fd, offset, length);
903    if (mStatus == NO_ERROR) mPlayer = p;
904    return mStatus;
905}
906
907status_t MediaPlayerService::Client::setDataSource(
908        const sp<IStreamSource> &source) {
909    // create the right type of player
910    sp<MediaPlayerBase> p = createPlayer(NU_PLAYER);
911
912    if (p == NULL) {
913        return NO_INIT;
914    }
915
916    if (!p->hardwareOutput()) {
917        mAudioOutput = new AudioOutput(mAudioSessionId);
918        static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
919    }
920
921    // now set data source
922    mStatus = p->setDataSource(source);
923
924    if (mStatus == OK) {
925        mPlayer = p;
926    }
927
928    return mStatus;
929}
930
931status_t MediaPlayerService::Client::setVideoSurface(const sp<Surface>& surface)
932{
933    LOGV("[%d] setVideoSurface(%p)", mConnId, surface.get());
934    sp<MediaPlayerBase> p = getPlayer();
935    if (p == 0) return UNKNOWN_ERROR;
936    return p->setVideoSurface(surface);
937}
938
939status_t MediaPlayerService::Client::invoke(const Parcel& request,
940                                            Parcel *reply)
941{
942    sp<MediaPlayerBase> p = getPlayer();
943    if (p == NULL) return UNKNOWN_ERROR;
944    return p->invoke(request, reply);
945}
946
947// This call doesn't need to access the native player.
948status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
949{
950    status_t status;
951    media::Metadata::Filter allow, drop;
952
953    if (unmarshallFilter(filter, &allow, &status) &&
954        unmarshallFilter(filter, &drop, &status)) {
955        Mutex::Autolock lock(mLock);
956
957        mMetadataAllow = allow;
958        mMetadataDrop = drop;
959    }
960    return status;
961}
962
963status_t MediaPlayerService::Client::getMetadata(
964        bool update_only, bool apply_filter, Parcel *reply)
965{
966    sp<MediaPlayerBase> player = getPlayer();
967    if (player == 0) return UNKNOWN_ERROR;
968
969    status_t status;
970    // Placeholder for the return code, updated by the caller.
971    reply->writeInt32(-1);
972
973    media::Metadata::Filter ids;
974
975    // We don't block notifications while we fetch the data. We clear
976    // mMetadataUpdated first so we don't lose notifications happening
977    // during the rest of this call.
978    {
979        Mutex::Autolock lock(mLock);
980        if (update_only) {
981            ids = mMetadataUpdated;
982        }
983        mMetadataUpdated.clear();
984    }
985
986    media::Metadata metadata(reply);
987
988    metadata.appendHeader();
989    status = player->getMetadata(ids, reply);
990
991    if (status != OK) {
992        metadata.resetParcel();
993        LOGE("getMetadata failed %d", status);
994        return status;
995    }
996
997    // FIXME: Implement filtering on the result. Not critical since
998    // filtering takes place on the update notifications already. This
999    // would be when all the metadata are fetch and a filter is set.
1000
1001    // Everything is fine, update the metadata length.
1002    metadata.updateLength();
1003    return OK;
1004}
1005
1006status_t MediaPlayerService::Client::prepareAsync()
1007{
1008    LOGV("[%d] prepareAsync", mConnId);
1009    sp<MediaPlayerBase> p = getPlayer();
1010    if (p == 0) return UNKNOWN_ERROR;
1011    status_t ret = p->prepareAsync();
1012#if CALLBACK_ANTAGONIZER
1013    LOGD("start Antagonizer");
1014    if (ret == NO_ERROR) mAntagonizer->start();
1015#endif
1016    return ret;
1017}
1018
1019status_t MediaPlayerService::Client::start()
1020{
1021    LOGV("[%d] start", mConnId);
1022    sp<MediaPlayerBase> p = getPlayer();
1023    if (p == 0) return UNKNOWN_ERROR;
1024    p->setLooping(mLoop);
1025    return p->start();
1026}
1027
1028status_t MediaPlayerService::Client::stop()
1029{
1030    LOGV("[%d] stop", mConnId);
1031    sp<MediaPlayerBase> p = getPlayer();
1032    if (p == 0) return UNKNOWN_ERROR;
1033    return p->stop();
1034}
1035
1036status_t MediaPlayerService::Client::pause()
1037{
1038    LOGV("[%d] pause", mConnId);
1039    sp<MediaPlayerBase> p = getPlayer();
1040    if (p == 0) return UNKNOWN_ERROR;
1041    return p->pause();
1042}
1043
1044status_t MediaPlayerService::Client::isPlaying(bool* state)
1045{
1046    *state = false;
1047    sp<MediaPlayerBase> p = getPlayer();
1048    if (p == 0) return UNKNOWN_ERROR;
1049    *state = p->isPlaying();
1050    LOGV("[%d] isPlaying: %d", mConnId, *state);
1051    return NO_ERROR;
1052}
1053
1054status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
1055{
1056    LOGV("getCurrentPosition");
1057    sp<MediaPlayerBase> p = getPlayer();
1058    if (p == 0) return UNKNOWN_ERROR;
1059    status_t ret = p->getCurrentPosition(msec);
1060    if (ret == NO_ERROR) {
1061        LOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
1062    } else {
1063        LOGE("getCurrentPosition returned %d", ret);
1064    }
1065    return ret;
1066}
1067
1068status_t MediaPlayerService::Client::getDuration(int *msec)
1069{
1070    LOGV("getDuration");
1071    sp<MediaPlayerBase> p = getPlayer();
1072    if (p == 0) return UNKNOWN_ERROR;
1073    status_t ret = p->getDuration(msec);
1074    if (ret == NO_ERROR) {
1075        LOGV("[%d] getDuration = %d", mConnId, *msec);
1076    } else {
1077        LOGE("getDuration returned %d", ret);
1078    }
1079    return ret;
1080}
1081
1082status_t MediaPlayerService::Client::seekTo(int msec)
1083{
1084    LOGV("[%d] seekTo(%d)", mConnId, msec);
1085    sp<MediaPlayerBase> p = getPlayer();
1086    if (p == 0) return UNKNOWN_ERROR;
1087    return p->seekTo(msec);
1088}
1089
1090status_t MediaPlayerService::Client::reset()
1091{
1092    LOGV("[%d] reset", mConnId);
1093    sp<MediaPlayerBase> p = getPlayer();
1094    if (p == 0) return UNKNOWN_ERROR;
1095    return p->reset();
1096}
1097
1098status_t MediaPlayerService::Client::setAudioStreamType(int type)
1099{
1100    LOGV("[%d] setAudioStreamType(%d)", mConnId, type);
1101    // TODO: for hardware output, call player instead
1102    Mutex::Autolock l(mLock);
1103    if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1104    return NO_ERROR;
1105}
1106
1107status_t MediaPlayerService::Client::setLooping(int loop)
1108{
1109    LOGV("[%d] setLooping(%d)", mConnId, loop);
1110    mLoop = loop;
1111    sp<MediaPlayerBase> p = getPlayer();
1112    if (p != 0) return p->setLooping(loop);
1113    return NO_ERROR;
1114}
1115
1116status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1117{
1118    LOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
1119    // TODO: for hardware output, call player instead
1120    Mutex::Autolock l(mLock);
1121    if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1122    return NO_ERROR;
1123}
1124
1125status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1126{
1127    LOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
1128    Mutex::Autolock l(mLock);
1129    if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1130    return NO_ERROR;
1131}
1132
1133status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1134{
1135    LOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
1136    Mutex::Autolock l(mLock);
1137    if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1138    return NO_ERROR;
1139}
1140
1141void MediaPlayerService::Client::notify(void* cookie, int msg, int ext1, int ext2)
1142{
1143    Client* client = static_cast<Client*>(cookie);
1144
1145    if (MEDIA_INFO == msg &&
1146        MEDIA_INFO_METADATA_UPDATE == ext1) {
1147        const media::Metadata::Type metadata_type = ext2;
1148
1149        if(client->shouldDropMetadata(metadata_type)) {
1150            return;
1151        }
1152
1153        // Update the list of metadata that have changed. getMetadata
1154        // also access mMetadataUpdated and clears it.
1155        client->addNewMetadataUpdate(metadata_type);
1156    }
1157    LOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
1158    client->mClient->notify(msg, ext1, ext2);
1159}
1160
1161
1162bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
1163{
1164    Mutex::Autolock lock(mLock);
1165
1166    if (findMetadata(mMetadataDrop, code)) {
1167        return true;
1168    }
1169
1170    if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
1171        return false;
1172    } else {
1173        return true;
1174    }
1175}
1176
1177
1178void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
1179    Mutex::Autolock lock(mLock);
1180    if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1181        mMetadataUpdated.add(metadata_type);
1182    }
1183}
1184
1185#if CALLBACK_ANTAGONIZER
1186const int Antagonizer::interval = 10000; // 10 msecs
1187
1188Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1189    mExit(false), mActive(false), mClient(client), mCb(cb)
1190{
1191    createThread(callbackThread, this);
1192}
1193
1194void Antagonizer::kill()
1195{
1196    Mutex::Autolock _l(mLock);
1197    mActive = false;
1198    mExit = true;
1199    mCondition.wait(mLock);
1200}
1201
1202int Antagonizer::callbackThread(void* user)
1203{
1204    LOGD("Antagonizer started");
1205    Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1206    while (!p->mExit) {
1207        if (p->mActive) {
1208            LOGV("send event");
1209            p->mCb(p->mClient, 0, 0, 0);
1210        }
1211        usleep(interval);
1212    }
1213    Mutex::Autolock _l(p->mLock);
1214    p->mCondition.signal();
1215    LOGD("Antagonizer stopped");
1216    return 0;
1217}
1218#endif
1219
1220static size_t kDefaultHeapSize = 1024 * 1024; // 1MB
1221
1222sp<IMemory> MediaPlayerService::decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1223{
1224    LOGV("decode(%s)", url);
1225    sp<MemoryBase> mem;
1226    sp<MediaPlayerBase> player;
1227
1228    // Protect our precious, precious DRMd ringtones by only allowing
1229    // decoding of http, but not filesystem paths or content Uris.
1230    // If the application wants to decode those, it should open a
1231    // filedescriptor for them and use that.
1232    if (url != NULL && strncmp(url, "http://", 7) != 0) {
1233        LOGD("Can't decode %s by path, use filedescriptor instead", url);
1234        return mem;
1235    }
1236
1237    player_type playerType = getPlayerType(url);
1238    LOGV("player type = %d", playerType);
1239
1240    // create the right type of player
1241    sp<AudioCache> cache = new AudioCache(url);
1242    player = android::createPlayer(playerType, cache.get(), cache->notify);
1243    if (player == NULL) goto Exit;
1244    if (player->hardwareOutput()) goto Exit;
1245
1246    static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1247
1248    // set data source
1249    if (player->setDataSource(url) != NO_ERROR) goto Exit;
1250
1251    LOGV("prepare");
1252    player->prepareAsync();
1253
1254    LOGV("wait for prepare");
1255    if (cache->wait() != NO_ERROR) goto Exit;
1256
1257    LOGV("start");
1258    player->start();
1259
1260    LOGV("wait for playback complete");
1261    if (cache->wait() != NO_ERROR) goto Exit;
1262
1263    mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1264    *pSampleRate = cache->sampleRate();
1265    *pNumChannels = cache->channelCount();
1266    *pFormat = cache->format();
1267    LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1268
1269Exit:
1270    if (player != 0) player->reset();
1271    return mem;
1272}
1273
1274sp<IMemory> MediaPlayerService::decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1275{
1276    LOGV("decode(%d, %lld, %lld)", fd, offset, length);
1277    sp<MemoryBase> mem;
1278    sp<MediaPlayerBase> player;
1279
1280    player_type playerType = getPlayerType(fd, offset, length);
1281    LOGV("player type = %d", playerType);
1282
1283    // create the right type of player
1284    sp<AudioCache> cache = new AudioCache("decode_fd");
1285    player = android::createPlayer(playerType, cache.get(), cache->notify);
1286    if (player == NULL) goto Exit;
1287    if (player->hardwareOutput()) goto Exit;
1288
1289    static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1290
1291    // set data source
1292    if (player->setDataSource(fd, offset, length) != NO_ERROR) goto Exit;
1293
1294    LOGV("prepare");
1295    player->prepareAsync();
1296
1297    LOGV("wait for prepare");
1298    if (cache->wait() != NO_ERROR) goto Exit;
1299
1300    LOGV("start");
1301    player->start();
1302
1303    LOGV("wait for playback complete");
1304    if (cache->wait() != NO_ERROR) goto Exit;
1305
1306    mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1307    *pSampleRate = cache->sampleRate();
1308    *pNumChannels = cache->channelCount();
1309    *pFormat = cache->format();
1310    LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1311
1312Exit:
1313    if (player != 0) player->reset();
1314    ::close(fd);
1315    return mem;
1316}
1317
1318
1319#undef LOG_TAG
1320#define LOG_TAG "AudioSink"
1321MediaPlayerService::AudioOutput::AudioOutput(int sessionId)
1322    : mCallback(NULL),
1323      mCallbackCookie(NULL),
1324      mSessionId(sessionId) {
1325    LOGV("AudioOutput(%d)", sessionId);
1326    mTrack = 0;
1327    mStreamType = AudioSystem::MUSIC;
1328    mLeftVolume = 1.0;
1329    mRightVolume = 1.0;
1330    mLatency = 0;
1331    mMsecsPerFrame = 0;
1332    mAuxEffectId = 0;
1333    mSendLevel = 0.0;
1334    setMinBufferCount();
1335}
1336
1337MediaPlayerService::AudioOutput::~AudioOutput()
1338{
1339    close();
1340}
1341
1342void MediaPlayerService::AudioOutput::setMinBufferCount()
1343{
1344    char value[PROPERTY_VALUE_MAX];
1345    if (property_get("ro.kernel.qemu", value, 0)) {
1346        mIsOnEmulator = true;
1347        mMinBufferCount = 12;  // to prevent systematic buffer underrun for emulator
1348    }
1349}
1350
1351bool MediaPlayerService::AudioOutput::isOnEmulator()
1352{
1353    setMinBufferCount();
1354    return mIsOnEmulator;
1355}
1356
1357int MediaPlayerService::AudioOutput::getMinBufferCount()
1358{
1359    setMinBufferCount();
1360    return mMinBufferCount;
1361}
1362
1363ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1364{
1365    if (mTrack == 0) return NO_INIT;
1366    return mTrack->frameCount() * frameSize();
1367}
1368
1369ssize_t MediaPlayerService::AudioOutput::frameCount() const
1370{
1371    if (mTrack == 0) return NO_INIT;
1372    return mTrack->frameCount();
1373}
1374
1375ssize_t MediaPlayerService::AudioOutput::channelCount() const
1376{
1377    if (mTrack == 0) return NO_INIT;
1378    return mTrack->channelCount();
1379}
1380
1381ssize_t MediaPlayerService::AudioOutput::frameSize() const
1382{
1383    if (mTrack == 0) return NO_INIT;
1384    return mTrack->frameSize();
1385}
1386
1387uint32_t MediaPlayerService::AudioOutput::latency () const
1388{
1389    return mLatency;
1390}
1391
1392float MediaPlayerService::AudioOutput::msecsPerFrame() const
1393{
1394    return mMsecsPerFrame;
1395}
1396
1397status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position)
1398{
1399    if (mTrack == 0) return NO_INIT;
1400    return mTrack->getPosition(position);
1401}
1402
1403status_t MediaPlayerService::AudioOutput::open(
1404        uint32_t sampleRate, int channelCount, int format, int bufferCount,
1405        AudioCallback cb, void *cookie)
1406{
1407    mCallback = cb;
1408    mCallbackCookie = cookie;
1409
1410    // Check argument "bufferCount" against the mininum buffer count
1411    if (bufferCount < mMinBufferCount) {
1412        LOGD("bufferCount (%d) is too small and increased to %d", bufferCount, mMinBufferCount);
1413        bufferCount = mMinBufferCount;
1414
1415    }
1416    LOGV("open(%u, %d, %d, %d, %d)", sampleRate, channelCount, format, bufferCount,mSessionId);
1417    if (mTrack) close();
1418    int afSampleRate;
1419    int afFrameCount;
1420    int frameCount;
1421
1422    if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1423        return NO_INIT;
1424    }
1425    if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1426        return NO_INIT;
1427    }
1428
1429    frameCount = (sampleRate*afFrameCount*bufferCount)/afSampleRate;
1430
1431    AudioTrack *t;
1432    if (mCallback != NULL) {
1433        t = new AudioTrack(
1434                mStreamType,
1435                sampleRate,
1436                format,
1437                (channelCount == 2) ? AudioSystem::CHANNEL_OUT_STEREO : AudioSystem::CHANNEL_OUT_MONO,
1438                frameCount,
1439                0 /* flags */,
1440                CallbackWrapper,
1441                this,
1442                0,
1443                mSessionId);
1444    } else {
1445        t = new AudioTrack(
1446                mStreamType,
1447                sampleRate,
1448                format,
1449                (channelCount == 2) ? AudioSystem::CHANNEL_OUT_STEREO : AudioSystem::CHANNEL_OUT_MONO,
1450                frameCount,
1451                0,
1452                NULL,
1453                NULL,
1454                0,
1455                mSessionId);
1456    }
1457
1458    if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1459        LOGE("Unable to create audio track");
1460        delete t;
1461        return NO_INIT;
1462    }
1463
1464    LOGV("setVolume");
1465    t->setVolume(mLeftVolume, mRightVolume);
1466
1467    mMsecsPerFrame = 1.e3 / (float) sampleRate;
1468    mLatency = t->latency();
1469    mTrack = t;
1470
1471    t->setAuxEffectSendLevel(mSendLevel);
1472    return t->attachAuxEffect(mAuxEffectId);;
1473}
1474
1475void MediaPlayerService::AudioOutput::start()
1476{
1477    LOGV("start");
1478    if (mTrack) {
1479        mTrack->setVolume(mLeftVolume, mRightVolume);
1480        mTrack->setAuxEffectSendLevel(mSendLevel);
1481        mTrack->start();
1482    }
1483}
1484
1485
1486
1487ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size)
1488{
1489    LOG_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
1490
1491    //LOGV("write(%p, %u)", buffer, size);
1492    if (mTrack) {
1493        ssize_t ret = mTrack->write(buffer, size);
1494        return ret;
1495    }
1496    return NO_INIT;
1497}
1498
1499void MediaPlayerService::AudioOutput::stop()
1500{
1501    LOGV("stop");
1502    if (mTrack) mTrack->stop();
1503}
1504
1505void MediaPlayerService::AudioOutput::flush()
1506{
1507    LOGV("flush");
1508    if (mTrack) mTrack->flush();
1509}
1510
1511void MediaPlayerService::AudioOutput::pause()
1512{
1513    LOGV("pause");
1514    if (mTrack) mTrack->pause();
1515}
1516
1517void MediaPlayerService::AudioOutput::close()
1518{
1519    LOGV("close");
1520    delete mTrack;
1521    mTrack = 0;
1522}
1523
1524void MediaPlayerService::AudioOutput::setVolume(float left, float right)
1525{
1526    LOGV("setVolume(%f, %f)", left, right);
1527    mLeftVolume = left;
1528    mRightVolume = right;
1529    if (mTrack) {
1530        mTrack->setVolume(left, right);
1531    }
1532}
1533
1534status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
1535{
1536    LOGV("setAuxEffectSendLevel(%f)", level);
1537    mSendLevel = level;
1538    if (mTrack) {
1539        return mTrack->setAuxEffectSendLevel(level);
1540    }
1541    return NO_ERROR;
1542}
1543
1544status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
1545{
1546    LOGV("attachAuxEffect(%d)", effectId);
1547    mAuxEffectId = effectId;
1548    if (mTrack) {
1549        return mTrack->attachAuxEffect(effectId);
1550    }
1551    return NO_ERROR;
1552}
1553
1554// static
1555void MediaPlayerService::AudioOutput::CallbackWrapper(
1556        int event, void *cookie, void *info) {
1557    //LOGV("callbackwrapper");
1558    if (event != AudioTrack::EVENT_MORE_DATA) {
1559        return;
1560    }
1561
1562    AudioOutput *me = (AudioOutput *)cookie;
1563    AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
1564
1565    size_t actualSize = (*me->mCallback)(
1566            me, buffer->raw, buffer->size, me->mCallbackCookie);
1567
1568    buffer->size = actualSize;
1569
1570}
1571
1572int MediaPlayerService::AudioOutput::getSessionId()
1573{
1574    return mSessionId;
1575}
1576
1577#undef LOG_TAG
1578#define LOG_TAG "AudioCache"
1579MediaPlayerService::AudioCache::AudioCache(const char* name) :
1580    mChannelCount(0), mFrameCount(1024), mSampleRate(0), mSize(0),
1581    mError(NO_ERROR), mCommandComplete(false)
1582{
1583    // create ashmem heap
1584    mHeap = new MemoryHeapBase(kDefaultHeapSize, 0, name);
1585}
1586
1587uint32_t MediaPlayerService::AudioCache::latency () const
1588{
1589    return 0;
1590}
1591
1592float MediaPlayerService::AudioCache::msecsPerFrame() const
1593{
1594    return mMsecsPerFrame;
1595}
1596
1597status_t MediaPlayerService::AudioCache::getPosition(uint32_t *position)
1598{
1599    if (position == 0) return BAD_VALUE;
1600    *position = mSize;
1601    return NO_ERROR;
1602}
1603
1604////////////////////////////////////////////////////////////////////////////////
1605
1606struct CallbackThread : public Thread {
1607    CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
1608                   MediaPlayerBase::AudioSink::AudioCallback cb,
1609                   void *cookie);
1610
1611protected:
1612    virtual ~CallbackThread();
1613
1614    virtual bool threadLoop();
1615
1616private:
1617    wp<MediaPlayerBase::AudioSink> mSink;
1618    MediaPlayerBase::AudioSink::AudioCallback mCallback;
1619    void *mCookie;
1620    void *mBuffer;
1621    size_t mBufferSize;
1622
1623    CallbackThread(const CallbackThread &);
1624    CallbackThread &operator=(const CallbackThread &);
1625};
1626
1627CallbackThread::CallbackThread(
1628        const wp<MediaPlayerBase::AudioSink> &sink,
1629        MediaPlayerBase::AudioSink::AudioCallback cb,
1630        void *cookie)
1631    : mSink(sink),
1632      mCallback(cb),
1633      mCookie(cookie),
1634      mBuffer(NULL),
1635      mBufferSize(0) {
1636}
1637
1638CallbackThread::~CallbackThread() {
1639    if (mBuffer) {
1640        free(mBuffer);
1641        mBuffer = NULL;
1642    }
1643}
1644
1645bool CallbackThread::threadLoop() {
1646    sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
1647    if (sink == NULL) {
1648        return false;
1649    }
1650
1651    if (mBuffer == NULL) {
1652        mBufferSize = sink->bufferSize();
1653        mBuffer = malloc(mBufferSize);
1654    }
1655
1656    size_t actualSize =
1657        (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie);
1658
1659    if (actualSize > 0) {
1660        sink->write(mBuffer, actualSize);
1661    }
1662
1663    return true;
1664}
1665
1666////////////////////////////////////////////////////////////////////////////////
1667
1668status_t MediaPlayerService::AudioCache::open(
1669        uint32_t sampleRate, int channelCount, int format, int bufferCount,
1670        AudioCallback cb, void *cookie)
1671{
1672    LOGV("open(%u, %d, %d, %d)", sampleRate, channelCount, format, bufferCount);
1673    if (mHeap->getHeapID() < 0) {
1674        return NO_INIT;
1675    }
1676
1677    mSampleRate = sampleRate;
1678    mChannelCount = (uint16_t)channelCount;
1679    mFormat = (uint16_t)format;
1680    mMsecsPerFrame = 1.e3 / (float) sampleRate;
1681
1682    if (cb != NULL) {
1683        mCallbackThread = new CallbackThread(this, cb, cookie);
1684    }
1685    return NO_ERROR;
1686}
1687
1688void MediaPlayerService::AudioCache::start() {
1689    if (mCallbackThread != NULL) {
1690        mCallbackThread->run("AudioCache callback");
1691    }
1692}
1693
1694void MediaPlayerService::AudioCache::stop() {
1695    if (mCallbackThread != NULL) {
1696        mCallbackThread->requestExitAndWait();
1697    }
1698}
1699
1700ssize_t MediaPlayerService::AudioCache::write(const void* buffer, size_t size)
1701{
1702    LOGV("write(%p, %u)", buffer, size);
1703    if ((buffer == 0) || (size == 0)) return size;
1704
1705    uint8_t* p = static_cast<uint8_t*>(mHeap->getBase());
1706    if (p == NULL) return NO_INIT;
1707    p += mSize;
1708    LOGV("memcpy(%p, %p, %u)", p, buffer, size);
1709    if (mSize + size > mHeap->getSize()) {
1710        LOGE("Heap size overflow! req size: %d, max size: %d", (mSize + size), mHeap->getSize());
1711        size = mHeap->getSize() - mSize;
1712    }
1713    memcpy(p, buffer, size);
1714    mSize += size;
1715    return size;
1716}
1717
1718// call with lock held
1719status_t MediaPlayerService::AudioCache::wait()
1720{
1721    Mutex::Autolock lock(mLock);
1722    while (!mCommandComplete) {
1723        mSignal.wait(mLock);
1724    }
1725    mCommandComplete = false;
1726
1727    if (mError == NO_ERROR) {
1728        LOGV("wait - success");
1729    } else {
1730        LOGV("wait - error");
1731    }
1732    return mError;
1733}
1734
1735void MediaPlayerService::AudioCache::notify(void* cookie, int msg, int ext1, int ext2)
1736{
1737    LOGV("notify(%p, %d, %d, %d)", cookie, msg, ext1, ext2);
1738    AudioCache* p = static_cast<AudioCache*>(cookie);
1739
1740    // ignore buffering messages
1741    switch (msg)
1742    {
1743    case MEDIA_ERROR:
1744        LOGE("Error %d, %d occurred", ext1, ext2);
1745        p->mError = ext1;
1746        break;
1747    case MEDIA_PREPARED:
1748        LOGV("prepared");
1749        break;
1750    case MEDIA_PLAYBACK_COMPLETE:
1751        LOGV("playback complete");
1752        break;
1753    default:
1754        LOGV("ignored");
1755        return;
1756    }
1757
1758    // wake up thread
1759    Mutex::Autolock lock(p->mLock);
1760    p->mCommandComplete = true;
1761    p->mSignal.signal();
1762}
1763
1764int MediaPlayerService::AudioCache::getSessionId()
1765{
1766    return 0;
1767}
1768
1769} // namespace android
1770