MediaPlayerService.cpp revision 0a5ca668c6f7d45706e9aec4a1dfec0aacc6d233
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::setVideoSurface(const sp<Surface>& surface)
868{
869    LOGV("[%d] setVideoSurface(%p)", mConnId, surface.get());
870    sp<MediaPlayerBase> p = getPlayer();
871    if (p == 0) return UNKNOWN_ERROR;
872    return p->setVideoSurface(surface);
873}
874
875status_t MediaPlayerService::Client::invoke(const Parcel& request,
876                                            Parcel *reply)
877{
878    sp<MediaPlayerBase> p = getPlayer();
879    if (p == NULL) return UNKNOWN_ERROR;
880    return p->invoke(request, reply);
881}
882
883// This call doesn't need to access the native player.
884status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
885{
886    status_t status;
887    media::Metadata::Filter allow, drop;
888
889    if (unmarshallFilter(filter, &allow, &status) &&
890        unmarshallFilter(filter, &drop, &status)) {
891        Mutex::Autolock lock(mLock);
892
893        mMetadataAllow = allow;
894        mMetadataDrop = drop;
895    }
896    return status;
897}
898
899status_t MediaPlayerService::Client::getMetadata(
900        bool update_only, bool apply_filter, Parcel *reply)
901{
902    sp<MediaPlayerBase> player = getPlayer();
903    if (player == 0) return UNKNOWN_ERROR;
904
905    status_t status;
906    // Placeholder for the return code, updated by the caller.
907    reply->writeInt32(-1);
908
909    media::Metadata::Filter ids;
910
911    // We don't block notifications while we fetch the data. We clear
912    // mMetadataUpdated first so we don't lose notifications happening
913    // during the rest of this call.
914    {
915        Mutex::Autolock lock(mLock);
916        if (update_only) {
917            ids = mMetadataUpdated;
918        }
919        mMetadataUpdated.clear();
920    }
921
922    media::Metadata metadata(reply);
923
924    metadata.appendHeader();
925    status = player->getMetadata(ids, reply);
926
927    if (status != OK) {
928        metadata.resetParcel();
929        LOGE("getMetadata failed %d", status);
930        return status;
931    }
932
933    // FIXME: Implement filtering on the result. Not critical since
934    // filtering takes place on the update notifications already. This
935    // would be when all the metadata are fetch and a filter is set.
936
937    // Everything is fine, update the metadata length.
938    metadata.updateLength();
939    return OK;
940}
941
942status_t MediaPlayerService::Client::prepareAsync()
943{
944    LOGV("[%d] prepareAsync", mConnId);
945    sp<MediaPlayerBase> p = getPlayer();
946    if (p == 0) return UNKNOWN_ERROR;
947    status_t ret = p->prepareAsync();
948#if CALLBACK_ANTAGONIZER
949    LOGD("start Antagonizer");
950    if (ret == NO_ERROR) mAntagonizer->start();
951#endif
952    return ret;
953}
954
955status_t MediaPlayerService::Client::start()
956{
957    LOGV("[%d] start", mConnId);
958    sp<MediaPlayerBase> p = getPlayer();
959    if (p == 0) return UNKNOWN_ERROR;
960    p->setLooping(mLoop);
961    return p->start();
962}
963
964status_t MediaPlayerService::Client::stop()
965{
966    LOGV("[%d] stop", mConnId);
967    sp<MediaPlayerBase> p = getPlayer();
968    if (p == 0) return UNKNOWN_ERROR;
969    return p->stop();
970}
971
972status_t MediaPlayerService::Client::pause()
973{
974    LOGV("[%d] pause", mConnId);
975    sp<MediaPlayerBase> p = getPlayer();
976    if (p == 0) return UNKNOWN_ERROR;
977    return p->pause();
978}
979
980status_t MediaPlayerService::Client::isPlaying(bool* state)
981{
982    *state = false;
983    sp<MediaPlayerBase> p = getPlayer();
984    if (p == 0) return UNKNOWN_ERROR;
985    *state = p->isPlaying();
986    LOGV("[%d] isPlaying: %d", mConnId, *state);
987    return NO_ERROR;
988}
989
990status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
991{
992    LOGV("getCurrentPosition");
993    sp<MediaPlayerBase> p = getPlayer();
994    if (p == 0) return UNKNOWN_ERROR;
995    status_t ret = p->getCurrentPosition(msec);
996    if (ret == NO_ERROR) {
997        LOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
998    } else {
999        LOGE("getCurrentPosition returned %d", ret);
1000    }
1001    return ret;
1002}
1003
1004status_t MediaPlayerService::Client::getDuration(int *msec)
1005{
1006    LOGV("getDuration");
1007    sp<MediaPlayerBase> p = getPlayer();
1008    if (p == 0) return UNKNOWN_ERROR;
1009    status_t ret = p->getDuration(msec);
1010    if (ret == NO_ERROR) {
1011        LOGV("[%d] getDuration = %d", mConnId, *msec);
1012    } else {
1013        LOGE("getDuration returned %d", ret);
1014    }
1015    return ret;
1016}
1017
1018status_t MediaPlayerService::Client::seekTo(int msec)
1019{
1020    LOGV("[%d] seekTo(%d)", mConnId, msec);
1021    sp<MediaPlayerBase> p = getPlayer();
1022    if (p == 0) return UNKNOWN_ERROR;
1023    return p->seekTo(msec);
1024}
1025
1026status_t MediaPlayerService::Client::reset()
1027{
1028    LOGV("[%d] reset", mConnId);
1029    sp<MediaPlayerBase> p = getPlayer();
1030    if (p == 0) return UNKNOWN_ERROR;
1031    return p->reset();
1032}
1033
1034status_t MediaPlayerService::Client::setAudioStreamType(int type)
1035{
1036    LOGV("[%d] setAudioStreamType(%d)", mConnId, type);
1037    // TODO: for hardware output, call player instead
1038    Mutex::Autolock l(mLock);
1039    if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1040    return NO_ERROR;
1041}
1042
1043status_t MediaPlayerService::Client::setLooping(int loop)
1044{
1045    LOGV("[%d] setLooping(%d)", mConnId, loop);
1046    mLoop = loop;
1047    sp<MediaPlayerBase> p = getPlayer();
1048    if (p != 0) return p->setLooping(loop);
1049    return NO_ERROR;
1050}
1051
1052status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1053{
1054    LOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
1055    // TODO: for hardware output, call player instead
1056    Mutex::Autolock l(mLock);
1057    if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1058    return NO_ERROR;
1059}
1060
1061status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1062{
1063    LOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
1064    Mutex::Autolock l(mLock);
1065    if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1066    return NO_ERROR;
1067}
1068
1069status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1070{
1071    LOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
1072    Mutex::Autolock l(mLock);
1073    if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1074    return NO_ERROR;
1075}
1076
1077void MediaPlayerService::Client::notify(void* cookie, int msg, int ext1, int ext2)
1078{
1079    Client* client = static_cast<Client*>(cookie);
1080
1081    if (MEDIA_INFO == msg &&
1082        MEDIA_INFO_METADATA_UPDATE == ext1) {
1083        const media::Metadata::Type metadata_type = ext2;
1084
1085        if(client->shouldDropMetadata(metadata_type)) {
1086            return;
1087        }
1088
1089        // Update the list of metadata that have changed. getMetadata
1090        // also access mMetadataUpdated and clears it.
1091        client->addNewMetadataUpdate(metadata_type);
1092    }
1093    LOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
1094    client->mClient->notify(msg, ext1, ext2);
1095}
1096
1097
1098bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
1099{
1100    Mutex::Autolock lock(mLock);
1101
1102    if (findMetadata(mMetadataDrop, code)) {
1103        return true;
1104    }
1105
1106    if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
1107        return false;
1108    } else {
1109        return true;
1110    }
1111}
1112
1113
1114void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
1115    Mutex::Autolock lock(mLock);
1116    if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1117        mMetadataUpdated.add(metadata_type);
1118    }
1119}
1120
1121#if CALLBACK_ANTAGONIZER
1122const int Antagonizer::interval = 10000; // 10 msecs
1123
1124Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1125    mExit(false), mActive(false), mClient(client), mCb(cb)
1126{
1127    createThread(callbackThread, this);
1128}
1129
1130void Antagonizer::kill()
1131{
1132    Mutex::Autolock _l(mLock);
1133    mActive = false;
1134    mExit = true;
1135    mCondition.wait(mLock);
1136}
1137
1138int Antagonizer::callbackThread(void* user)
1139{
1140    LOGD("Antagonizer started");
1141    Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1142    while (!p->mExit) {
1143        if (p->mActive) {
1144            LOGV("send event");
1145            p->mCb(p->mClient, 0, 0, 0);
1146        }
1147        usleep(interval);
1148    }
1149    Mutex::Autolock _l(p->mLock);
1150    p->mCondition.signal();
1151    LOGD("Antagonizer stopped");
1152    return 0;
1153}
1154#endif
1155
1156static size_t kDefaultHeapSize = 1024 * 1024; // 1MB
1157
1158sp<IMemory> MediaPlayerService::decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1159{
1160    LOGV("decode(%s)", url);
1161    sp<MemoryBase> mem;
1162    sp<MediaPlayerBase> player;
1163
1164    // Protect our precious, precious DRMd ringtones by only allowing
1165    // decoding of http, but not filesystem paths or content Uris.
1166    // If the application wants to decode those, it should open a
1167    // filedescriptor for them and use that.
1168    if (url != NULL && strncmp(url, "http://", 7) != 0) {
1169        LOGD("Can't decode %s by path, use filedescriptor instead", url);
1170        return mem;
1171    }
1172
1173    player_type playerType = getPlayerType(url);
1174    LOGV("player type = %d", playerType);
1175
1176    // create the right type of player
1177    sp<AudioCache> cache = new AudioCache(url);
1178    player = android::createPlayer(playerType, cache.get(), cache->notify);
1179    if (player == NULL) goto Exit;
1180    if (player->hardwareOutput()) goto Exit;
1181
1182    static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1183
1184    // set data source
1185    if (player->setDataSource(url) != NO_ERROR) goto Exit;
1186
1187    LOGV("prepare");
1188    player->prepareAsync();
1189
1190    LOGV("wait for prepare");
1191    if (cache->wait() != NO_ERROR) goto Exit;
1192
1193    LOGV("start");
1194    player->start();
1195
1196    LOGV("wait for playback complete");
1197    if (cache->wait() != NO_ERROR) goto Exit;
1198
1199    mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1200    *pSampleRate = cache->sampleRate();
1201    *pNumChannels = cache->channelCount();
1202    *pFormat = cache->format();
1203    LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1204
1205Exit:
1206    if (player != 0) player->reset();
1207    return mem;
1208}
1209
1210sp<IMemory> MediaPlayerService::decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1211{
1212    LOGV("decode(%d, %lld, %lld)", fd, offset, length);
1213    sp<MemoryBase> mem;
1214    sp<MediaPlayerBase> player;
1215
1216    player_type playerType = getPlayerType(fd, offset, length);
1217    LOGV("player type = %d", playerType);
1218
1219    // create the right type of player
1220    sp<AudioCache> cache = new AudioCache("decode_fd");
1221    player = android::createPlayer(playerType, cache.get(), cache->notify);
1222    if (player == NULL) goto Exit;
1223    if (player->hardwareOutput()) goto Exit;
1224
1225    static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1226
1227    // set data source
1228    if (player->setDataSource(fd, offset, length) != NO_ERROR) goto Exit;
1229
1230    LOGV("prepare");
1231    player->prepareAsync();
1232
1233    LOGV("wait for prepare");
1234    if (cache->wait() != NO_ERROR) goto Exit;
1235
1236    LOGV("start");
1237    player->start();
1238
1239    LOGV("wait for playback complete");
1240    if (cache->wait() != NO_ERROR) goto Exit;
1241
1242    mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1243    *pSampleRate = cache->sampleRate();
1244    *pNumChannels = cache->channelCount();
1245    *pFormat = cache->format();
1246    LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1247
1248Exit:
1249    if (player != 0) player->reset();
1250    ::close(fd);
1251    return mem;
1252}
1253
1254
1255#undef LOG_TAG
1256#define LOG_TAG "AudioSink"
1257MediaPlayerService::AudioOutput::AudioOutput(int sessionId)
1258    : mCallback(NULL),
1259      mCallbackCookie(NULL),
1260      mSessionId(sessionId) {
1261    LOGV("AudioOutput(%d)", sessionId);
1262    mTrack = 0;
1263    mStreamType = AudioSystem::MUSIC;
1264    mLeftVolume = 1.0;
1265    mRightVolume = 1.0;
1266    mLatency = 0;
1267    mMsecsPerFrame = 0;
1268    mAuxEffectId = 0;
1269    mSendLevel = 0.0;
1270    setMinBufferCount();
1271}
1272
1273MediaPlayerService::AudioOutput::~AudioOutput()
1274{
1275    close();
1276}
1277
1278void MediaPlayerService::AudioOutput::setMinBufferCount()
1279{
1280    char value[PROPERTY_VALUE_MAX];
1281    if (property_get("ro.kernel.qemu", value, 0)) {
1282        mIsOnEmulator = true;
1283        mMinBufferCount = 12;  // to prevent systematic buffer underrun for emulator
1284    }
1285}
1286
1287bool MediaPlayerService::AudioOutput::isOnEmulator()
1288{
1289    setMinBufferCount();
1290    return mIsOnEmulator;
1291}
1292
1293int MediaPlayerService::AudioOutput::getMinBufferCount()
1294{
1295    setMinBufferCount();
1296    return mMinBufferCount;
1297}
1298
1299ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1300{
1301    if (mTrack == 0) return NO_INIT;
1302    return mTrack->frameCount() * frameSize();
1303}
1304
1305ssize_t MediaPlayerService::AudioOutput::frameCount() const
1306{
1307    if (mTrack == 0) return NO_INIT;
1308    return mTrack->frameCount();
1309}
1310
1311ssize_t MediaPlayerService::AudioOutput::channelCount() const
1312{
1313    if (mTrack == 0) return NO_INIT;
1314    return mTrack->channelCount();
1315}
1316
1317ssize_t MediaPlayerService::AudioOutput::frameSize() const
1318{
1319    if (mTrack == 0) return NO_INIT;
1320    return mTrack->frameSize();
1321}
1322
1323uint32_t MediaPlayerService::AudioOutput::latency () const
1324{
1325    return mLatency;
1326}
1327
1328float MediaPlayerService::AudioOutput::msecsPerFrame() const
1329{
1330    return mMsecsPerFrame;
1331}
1332
1333status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position)
1334{
1335    if (mTrack == 0) return NO_INIT;
1336    return mTrack->getPosition(position);
1337}
1338
1339status_t MediaPlayerService::AudioOutput::open(
1340        uint32_t sampleRate, int channelCount, int format, int bufferCount,
1341        AudioCallback cb, void *cookie)
1342{
1343    mCallback = cb;
1344    mCallbackCookie = cookie;
1345
1346    // Check argument "bufferCount" against the mininum buffer count
1347    if (bufferCount < mMinBufferCount) {
1348        LOGD("bufferCount (%d) is too small and increased to %d", bufferCount, mMinBufferCount);
1349        bufferCount = mMinBufferCount;
1350
1351    }
1352    LOGV("open(%u, %d, %d, %d, %d)", sampleRate, channelCount, format, bufferCount,mSessionId);
1353    if (mTrack) close();
1354    int afSampleRate;
1355    int afFrameCount;
1356    int frameCount;
1357
1358    if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1359        return NO_INIT;
1360    }
1361    if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1362        return NO_INIT;
1363    }
1364
1365    frameCount = (sampleRate*afFrameCount*bufferCount)/afSampleRate;
1366
1367    AudioTrack *t;
1368    if (mCallback != NULL) {
1369        t = new AudioTrack(
1370                mStreamType,
1371                sampleRate,
1372                format,
1373                (channelCount == 2) ? AudioSystem::CHANNEL_OUT_STEREO : AudioSystem::CHANNEL_OUT_MONO,
1374                frameCount,
1375                0 /* flags */,
1376                CallbackWrapper,
1377                this,
1378                0,
1379                mSessionId);
1380    } else {
1381        t = new AudioTrack(
1382                mStreamType,
1383                sampleRate,
1384                format,
1385                (channelCount == 2) ? AudioSystem::CHANNEL_OUT_STEREO : AudioSystem::CHANNEL_OUT_MONO,
1386                frameCount,
1387                0,
1388                NULL,
1389                NULL,
1390                0,
1391                mSessionId);
1392    }
1393
1394    if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1395        LOGE("Unable to create audio track");
1396        delete t;
1397        return NO_INIT;
1398    }
1399
1400    LOGV("setVolume");
1401    t->setVolume(mLeftVolume, mRightVolume);
1402
1403    mMsecsPerFrame = 1.e3 / (float) sampleRate;
1404    mLatency = t->latency();
1405    mTrack = t;
1406
1407    t->setAuxEffectSendLevel(mSendLevel);
1408    return t->attachAuxEffect(mAuxEffectId);;
1409}
1410
1411void MediaPlayerService::AudioOutput::start()
1412{
1413    LOGV("start");
1414    if (mTrack) {
1415        mTrack->setVolume(mLeftVolume, mRightVolume);
1416        mTrack->setAuxEffectSendLevel(mSendLevel);
1417        mTrack->start();
1418    }
1419}
1420
1421
1422
1423ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size)
1424{
1425    LOG_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
1426
1427    //LOGV("write(%p, %u)", buffer, size);
1428    if (mTrack) {
1429        ssize_t ret = mTrack->write(buffer, size);
1430        return ret;
1431    }
1432    return NO_INIT;
1433}
1434
1435void MediaPlayerService::AudioOutput::stop()
1436{
1437    LOGV("stop");
1438    if (mTrack) mTrack->stop();
1439}
1440
1441void MediaPlayerService::AudioOutput::flush()
1442{
1443    LOGV("flush");
1444    if (mTrack) mTrack->flush();
1445}
1446
1447void MediaPlayerService::AudioOutput::pause()
1448{
1449    LOGV("pause");
1450    if (mTrack) mTrack->pause();
1451}
1452
1453void MediaPlayerService::AudioOutput::close()
1454{
1455    LOGV("close");
1456    delete mTrack;
1457    mTrack = 0;
1458}
1459
1460void MediaPlayerService::AudioOutput::setVolume(float left, float right)
1461{
1462    LOGV("setVolume(%f, %f)", left, right);
1463    mLeftVolume = left;
1464    mRightVolume = right;
1465    if (mTrack) {
1466        mTrack->setVolume(left, right);
1467    }
1468}
1469
1470status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
1471{
1472    LOGV("setAuxEffectSendLevel(%f)", level);
1473    mSendLevel = level;
1474    if (mTrack) {
1475        return mTrack->setAuxEffectSendLevel(level);
1476    }
1477    return NO_ERROR;
1478}
1479
1480status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
1481{
1482    LOGV("attachAuxEffect(%d)", effectId);
1483    mAuxEffectId = effectId;
1484    if (mTrack) {
1485        return mTrack->attachAuxEffect(effectId);
1486    }
1487    return NO_ERROR;
1488}
1489
1490// static
1491void MediaPlayerService::AudioOutput::CallbackWrapper(
1492        int event, void *cookie, void *info) {
1493    //LOGV("callbackwrapper");
1494    if (event != AudioTrack::EVENT_MORE_DATA) {
1495        return;
1496    }
1497
1498    AudioOutput *me = (AudioOutput *)cookie;
1499    AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
1500
1501    size_t actualSize = (*me->mCallback)(
1502            me, buffer->raw, buffer->size, me->mCallbackCookie);
1503
1504    buffer->size = actualSize;
1505
1506}
1507
1508int MediaPlayerService::AudioOutput::getSessionId()
1509{
1510    return mSessionId;
1511}
1512
1513#undef LOG_TAG
1514#define LOG_TAG "AudioCache"
1515MediaPlayerService::AudioCache::AudioCache(const char* name) :
1516    mChannelCount(0), mFrameCount(1024), mSampleRate(0), mSize(0),
1517    mError(NO_ERROR), mCommandComplete(false)
1518{
1519    // create ashmem heap
1520    mHeap = new MemoryHeapBase(kDefaultHeapSize, 0, name);
1521}
1522
1523uint32_t MediaPlayerService::AudioCache::latency () const
1524{
1525    return 0;
1526}
1527
1528float MediaPlayerService::AudioCache::msecsPerFrame() const
1529{
1530    return mMsecsPerFrame;
1531}
1532
1533status_t MediaPlayerService::AudioCache::getPosition(uint32_t *position)
1534{
1535    if (position == 0) return BAD_VALUE;
1536    *position = mSize;
1537    return NO_ERROR;
1538}
1539
1540////////////////////////////////////////////////////////////////////////////////
1541
1542struct CallbackThread : public Thread {
1543    CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
1544                   MediaPlayerBase::AudioSink::AudioCallback cb,
1545                   void *cookie);
1546
1547protected:
1548    virtual ~CallbackThread();
1549
1550    virtual bool threadLoop();
1551
1552private:
1553    wp<MediaPlayerBase::AudioSink> mSink;
1554    MediaPlayerBase::AudioSink::AudioCallback mCallback;
1555    void *mCookie;
1556    void *mBuffer;
1557    size_t mBufferSize;
1558
1559    CallbackThread(const CallbackThread &);
1560    CallbackThread &operator=(const CallbackThread &);
1561};
1562
1563CallbackThread::CallbackThread(
1564        const wp<MediaPlayerBase::AudioSink> &sink,
1565        MediaPlayerBase::AudioSink::AudioCallback cb,
1566        void *cookie)
1567    : mSink(sink),
1568      mCallback(cb),
1569      mCookie(cookie),
1570      mBuffer(NULL),
1571      mBufferSize(0) {
1572}
1573
1574CallbackThread::~CallbackThread() {
1575    if (mBuffer) {
1576        free(mBuffer);
1577        mBuffer = NULL;
1578    }
1579}
1580
1581bool CallbackThread::threadLoop() {
1582    sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
1583    if (sink == NULL) {
1584        return false;
1585    }
1586
1587    if (mBuffer == NULL) {
1588        mBufferSize = sink->bufferSize();
1589        mBuffer = malloc(mBufferSize);
1590    }
1591
1592    size_t actualSize =
1593        (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie);
1594
1595    if (actualSize > 0) {
1596        sink->write(mBuffer, actualSize);
1597    }
1598
1599    return true;
1600}
1601
1602////////////////////////////////////////////////////////////////////////////////
1603
1604status_t MediaPlayerService::AudioCache::open(
1605        uint32_t sampleRate, int channelCount, int format, int bufferCount,
1606        AudioCallback cb, void *cookie)
1607{
1608    LOGV("open(%u, %d, %d, %d)", sampleRate, channelCount, format, bufferCount);
1609    if (mHeap->getHeapID() < 0) {
1610        return NO_INIT;
1611    }
1612
1613    mSampleRate = sampleRate;
1614    mChannelCount = (uint16_t)channelCount;
1615    mFormat = (uint16_t)format;
1616    mMsecsPerFrame = 1.e3 / (float) sampleRate;
1617
1618    if (cb != NULL) {
1619        mCallbackThread = new CallbackThread(this, cb, cookie);
1620    }
1621    return NO_ERROR;
1622}
1623
1624void MediaPlayerService::AudioCache::start() {
1625    if (mCallbackThread != NULL) {
1626        mCallbackThread->run("AudioCache callback");
1627    }
1628}
1629
1630void MediaPlayerService::AudioCache::stop() {
1631    if (mCallbackThread != NULL) {
1632        mCallbackThread->requestExitAndWait();
1633    }
1634}
1635
1636ssize_t MediaPlayerService::AudioCache::write(const void* buffer, size_t size)
1637{
1638    LOGV("write(%p, %u)", buffer, size);
1639    if ((buffer == 0) || (size == 0)) return size;
1640
1641    uint8_t* p = static_cast<uint8_t*>(mHeap->getBase());
1642    if (p == NULL) return NO_INIT;
1643    p += mSize;
1644    LOGV("memcpy(%p, %p, %u)", p, buffer, size);
1645    if (mSize + size > mHeap->getSize()) {
1646        LOGE("Heap size overflow! req size: %d, max size: %d", (mSize + size), mHeap->getSize());
1647        size = mHeap->getSize() - mSize;
1648    }
1649    memcpy(p, buffer, size);
1650    mSize += size;
1651    return size;
1652}
1653
1654// call with lock held
1655status_t MediaPlayerService::AudioCache::wait()
1656{
1657    Mutex::Autolock lock(mLock);
1658    while (!mCommandComplete) {
1659        mSignal.wait(mLock);
1660    }
1661    mCommandComplete = false;
1662
1663    if (mError == NO_ERROR) {
1664        LOGV("wait - success");
1665    } else {
1666        LOGV("wait - error");
1667    }
1668    return mError;
1669}
1670
1671void MediaPlayerService::AudioCache::notify(void* cookie, int msg, int ext1, int ext2)
1672{
1673    LOGV("notify(%p, %d, %d, %d)", cookie, msg, ext1, ext2);
1674    AudioCache* p = static_cast<AudioCache*>(cookie);
1675
1676    // ignore buffering messages
1677    switch (msg)
1678    {
1679    case MEDIA_ERROR:
1680        LOGE("Error %d, %d occurred", ext1, ext2);
1681        p->mError = ext1;
1682        break;
1683    case MEDIA_PREPARED:
1684        LOGV("prepared");
1685        break;
1686    case MEDIA_PLAYBACK_COMPLETE:
1687        LOGV("playback complete");
1688        break;
1689    default:
1690        LOGV("ignored");
1691        return;
1692    }
1693
1694    // wake up thread
1695    Mutex::Autolock lock(p->mLock);
1696    p->mCommandComplete = true;
1697    p->mSignal.signal();
1698}
1699
1700int MediaPlayerService::AudioCache::getSessionId()
1701{
1702    return 0;
1703}
1704
1705} // namespace android
1706