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