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