MediaPlayerService.cpp revision 0024245e134467d120b40099da16c467dc365e76
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/Metadata.h>
51#include <media/AudioTrack.h>
52
53#include "MediaRecorderClient.h"
54#include "MediaPlayerService.h"
55#include "MetadataRetrieverClient.h"
56
57#include "MidiFile.h"
58#include "VorbisPlayer.h"
59#include <media/PVPlayer.h>
60#include "TestPlayerStub.h"
61
62//#undef USE_STAGEFRIGHT
63
64#if USE_STAGEFRIGHT
65#include "StagefrightPlayer.h"
66#endif
67
68#ifdef BUILD_WITH_STAGEFRIGHT
69#include <OMX.h>
70#else
71#include <media/IOMX.h>
72#endif
73
74
75
76/* desktop Linux needs a little help with gettid() */
77#if defined(HAVE_GETTID) && !defined(HAVE_ANDROID_OS)
78#define __KERNEL__
79# include <linux/unistd.h>
80#ifdef _syscall0
81_syscall0(pid_t,gettid)
82#else
83pid_t gettid() { return syscall(__NR_gettid);}
84#endif
85#undef __KERNEL__
86#endif
87
88namespace {
89using android::media::Metadata;
90using android::status_t;
91using android::OK;
92using android::BAD_VALUE;
93using android::NOT_ENOUGH_DATA;
94using android::Parcel;
95
96// Max number of entries in the filter.
97const int kMaxFilterSize = 64;  // I pulled that out of thin air.
98
99// FIXME: Move all the metadata related function in the Metadata.cpp
100
101
102// Unmarshall a filter from a Parcel.
103// Filter format in a parcel:
104//
105//  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
106// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
107// |                       number of entries (n)                   |
108// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
109// |                       metadata type 1                         |
110// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
111// |                       metadata type 2                         |
112// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
113//  ....
114// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
115// |                       metadata type n                         |
116// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
117//
118// @param p Parcel that should start with a filter.
119// @param[out] filter On exit contains the list of metadata type to be
120//                    filtered.
121// @param[out] status On exit contains the status code to be returned.
122// @return true if the parcel starts with a valid filter.
123bool unmarshallFilter(const Parcel& p,
124                      Metadata::Filter *filter,
125                      status_t *status)
126{
127    int32_t val;
128    if (p.readInt32(&val) != OK)
129    {
130        LOGE("Failed to read filter's length");
131        *status = NOT_ENOUGH_DATA;
132        return false;
133    }
134
135    if( val > kMaxFilterSize || val < 0)
136    {
137        LOGE("Invalid filter len %d", val);
138        *status = BAD_VALUE;
139        return false;
140    }
141
142    const size_t num = val;
143
144    filter->clear();
145    filter->setCapacity(num);
146
147    size_t size = num * sizeof(Metadata::Type);
148
149
150    if (p.dataAvail() < size)
151    {
152        LOGE("Filter too short expected %d but got %d", size, p.dataAvail());
153        *status = NOT_ENOUGH_DATA;
154        return false;
155    }
156
157    const Metadata::Type *data =
158            static_cast<const Metadata::Type*>(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 Metadata::Filter& filter, const int32_t val)
183{
184    // Deal with empty and ANY right away
185    if (filter.isEmpty()) return false;
186    if (filter[0] == Metadata::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    media::Metadata::Filter 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    sp<MediaPlayerBase> player = getPlayer();
874    if (player == 0) return UNKNOWN_ERROR;
875
876    status_t status;
877    // Placeholder for the return code, updated by the caller.
878    reply->writeInt32(-1);
879
880    media::Metadata::Filter ids;
881
882    // We don't block notifications while we fetch the data. We clear
883    // mMetadataUpdated first so we don't lose notifications happening
884    // during the rest of this call.
885    {
886        Mutex::Autolock lock(mLock);
887        if (update_only) {
888            ids = mMetadataUpdated;
889        }
890        mMetadataUpdated.clear();
891    }
892
893    media::Metadata metadata(reply);
894
895    metadata.appendHeader();
896    status = player->getMetadata(ids, reply);
897
898    if (status != OK) {
899        metadata.resetParcel();
900        LOGE("getMetadata failed %d", status);
901        return status;
902    }
903
904    // FIXME: Implement filtering on the result. Not critical since
905    // filtering takes place on the update notifications already. This
906    // would be when all the metadata are fetch and a filter is set.
907
908    // Everything is fine, update the metadata length.
909    metadata.updateLength();
910    return OK;
911}
912
913status_t MediaPlayerService::Client::prepareAsync()
914{
915    LOGV("[%d] prepareAsync", mConnId);
916    sp<MediaPlayerBase> p = getPlayer();
917    if (p == 0) return UNKNOWN_ERROR;
918    status_t ret = p->prepareAsync();
919#if CALLBACK_ANTAGONIZER
920    LOGD("start Antagonizer");
921    if (ret == NO_ERROR) mAntagonizer->start();
922#endif
923    return ret;
924}
925
926status_t MediaPlayerService::Client::start()
927{
928    LOGV("[%d] start", mConnId);
929    sp<MediaPlayerBase> p = getPlayer();
930    if (p == 0) return UNKNOWN_ERROR;
931    p->setLooping(mLoop);
932    return p->start();
933}
934
935status_t MediaPlayerService::Client::stop()
936{
937    LOGV("[%d] stop", mConnId);
938    sp<MediaPlayerBase> p = getPlayer();
939    if (p == 0) return UNKNOWN_ERROR;
940    return p->stop();
941}
942
943status_t MediaPlayerService::Client::pause()
944{
945    LOGV("[%d] pause", mConnId);
946    sp<MediaPlayerBase> p = getPlayer();
947    if (p == 0) return UNKNOWN_ERROR;
948    return p->pause();
949}
950
951status_t MediaPlayerService::Client::isPlaying(bool* state)
952{
953    *state = false;
954    sp<MediaPlayerBase> p = getPlayer();
955    if (p == 0) return UNKNOWN_ERROR;
956    *state = p->isPlaying();
957    LOGV("[%d] isPlaying: %d", mConnId, *state);
958    return NO_ERROR;
959}
960
961status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
962{
963    LOGV("getCurrentPosition");
964    sp<MediaPlayerBase> p = getPlayer();
965    if (p == 0) return UNKNOWN_ERROR;
966    status_t ret = p->getCurrentPosition(msec);
967    if (ret == NO_ERROR) {
968        LOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
969    } else {
970        LOGE("getCurrentPosition returned %d", ret);
971    }
972    return ret;
973}
974
975status_t MediaPlayerService::Client::getDuration(int *msec)
976{
977    LOGV("getDuration");
978    sp<MediaPlayerBase> p = getPlayer();
979    if (p == 0) return UNKNOWN_ERROR;
980    status_t ret = p->getDuration(msec);
981    if (ret == NO_ERROR) {
982        LOGV("[%d] getDuration = %d", mConnId, *msec);
983    } else {
984        LOGE("getDuration returned %d", ret);
985    }
986    return ret;
987}
988
989status_t MediaPlayerService::Client::seekTo(int msec)
990{
991    LOGV("[%d] seekTo(%d)", mConnId, msec);
992    sp<MediaPlayerBase> p = getPlayer();
993    if (p == 0) return UNKNOWN_ERROR;
994    return p->seekTo(msec);
995}
996
997status_t MediaPlayerService::Client::reset()
998{
999    LOGV("[%d] reset", mConnId);
1000    sp<MediaPlayerBase> p = getPlayer();
1001    if (p == 0) return UNKNOWN_ERROR;
1002    return p->reset();
1003}
1004
1005status_t MediaPlayerService::Client::setAudioStreamType(int type)
1006{
1007    LOGV("[%d] setAudioStreamType(%d)", mConnId, type);
1008    // TODO: for hardware output, call player instead
1009    Mutex::Autolock l(mLock);
1010    if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1011    return NO_ERROR;
1012}
1013
1014status_t MediaPlayerService::Client::setLooping(int loop)
1015{
1016    LOGV("[%d] setLooping(%d)", mConnId, loop);
1017    mLoop = loop;
1018    sp<MediaPlayerBase> p = getPlayer();
1019    if (p != 0) return p->setLooping(loop);
1020    return NO_ERROR;
1021}
1022
1023status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1024{
1025    LOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
1026    // TODO: for hardware output, call player instead
1027    Mutex::Autolock l(mLock);
1028    if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1029    return NO_ERROR;
1030}
1031
1032
1033void MediaPlayerService::Client::notify(void* cookie, int msg, int ext1, int ext2)
1034{
1035    Client* client = static_cast<Client*>(cookie);
1036
1037    if (MEDIA_INFO == msg &&
1038        MEDIA_INFO_METADATA_UPDATE == ext1) {
1039        const media::Metadata::Type metadata_type = ext2;
1040
1041        if(client->shouldDropMetadata(metadata_type)) {
1042            return;
1043        }
1044
1045        // Update the list of metadata that have changed. getMetadata
1046        // also access mMetadataUpdated and clears it.
1047        client->addNewMetadataUpdate(metadata_type);
1048    }
1049    LOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
1050    client->mClient->notify(msg, ext1, ext2);
1051}
1052
1053
1054bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
1055{
1056    Mutex::Autolock lock(mLock);
1057
1058    if (findMetadata(mMetadataDrop, code)) {
1059        return true;
1060    }
1061
1062    if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
1063        return false;
1064    } else {
1065        return true;
1066    }
1067}
1068
1069
1070void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
1071    Mutex::Autolock lock(mLock);
1072    if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1073        mMetadataUpdated.add(metadata_type);
1074    }
1075}
1076
1077#if CALLBACK_ANTAGONIZER
1078const int Antagonizer::interval = 10000; // 10 msecs
1079
1080Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1081    mExit(false), mActive(false), mClient(client), mCb(cb)
1082{
1083    createThread(callbackThread, this);
1084}
1085
1086void Antagonizer::kill()
1087{
1088    Mutex::Autolock _l(mLock);
1089    mActive = false;
1090    mExit = true;
1091    mCondition.wait(mLock);
1092}
1093
1094int Antagonizer::callbackThread(void* user)
1095{
1096    LOGD("Antagonizer started");
1097    Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1098    while (!p->mExit) {
1099        if (p->mActive) {
1100            LOGV("send event");
1101            p->mCb(p->mClient, 0, 0, 0);
1102        }
1103        usleep(interval);
1104    }
1105    Mutex::Autolock _l(p->mLock);
1106    p->mCondition.signal();
1107    LOGD("Antagonizer stopped");
1108    return 0;
1109}
1110#endif
1111
1112static size_t kDefaultHeapSize = 1024 * 1024; // 1MB
1113
1114sp<IMemory> MediaPlayerService::decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1115{
1116    LOGV("decode(%s)", url);
1117    sp<MemoryBase> mem;
1118    sp<MediaPlayerBase> player;
1119
1120    // Protect our precious, precious DRMd ringtones by only allowing
1121    // decoding of http, but not filesystem paths or content Uris.
1122    // If the application wants to decode those, it should open a
1123    // filedescriptor for them and use that.
1124    if (url != NULL && strncmp(url, "http://", 7) != 0) {
1125        LOGD("Can't decode %s by path, use filedescriptor instead", url);
1126        return mem;
1127    }
1128
1129    player_type playerType = getPlayerType(url);
1130    LOGV("player type = %d", playerType);
1131
1132    // create the right type of player
1133    sp<AudioCache> cache = new AudioCache(url);
1134    player = android::createPlayer(playerType, cache.get(), cache->notify);
1135    if (player == NULL) goto Exit;
1136    if (player->hardwareOutput()) goto Exit;
1137
1138    static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1139
1140    // set data source
1141    if (player->setDataSource(url) != NO_ERROR) goto Exit;
1142
1143    LOGV("prepare");
1144    player->prepareAsync();
1145
1146    LOGV("wait for prepare");
1147    if (cache->wait() != NO_ERROR) goto Exit;
1148
1149    LOGV("start");
1150    player->start();
1151
1152    LOGV("wait for playback complete");
1153    if (cache->wait() != NO_ERROR) goto Exit;
1154
1155    mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1156    *pSampleRate = cache->sampleRate();
1157    *pNumChannels = cache->channelCount();
1158    *pFormat = cache->format();
1159    LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1160
1161Exit:
1162    if (player != 0) player->reset();
1163    return mem;
1164}
1165
1166sp<IMemory> MediaPlayerService::decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1167{
1168    LOGV("decode(%d, %lld, %lld)", fd, offset, length);
1169    sp<MemoryBase> mem;
1170    sp<MediaPlayerBase> player;
1171
1172    player_type playerType = getPlayerType(fd, offset, length);
1173    LOGV("player type = %d", playerType);
1174
1175    // create the right type of player
1176    sp<AudioCache> cache = new AudioCache("decode_fd");
1177    player = android::createPlayer(playerType, cache.get(), cache->notify);
1178    if (player == NULL) goto Exit;
1179    if (player->hardwareOutput()) goto Exit;
1180
1181    static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1182
1183    // set data source
1184    if (player->setDataSource(fd, offset, length) != NO_ERROR) goto Exit;
1185
1186    LOGV("prepare");
1187    player->prepareAsync();
1188
1189    LOGV("wait for prepare");
1190    if (cache->wait() != NO_ERROR) goto Exit;
1191
1192    LOGV("start");
1193    player->start();
1194
1195    LOGV("wait for playback complete");
1196    if (cache->wait() != NO_ERROR) goto Exit;
1197
1198    mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1199    *pSampleRate = cache->sampleRate();
1200    *pNumChannels = cache->channelCount();
1201    *pFormat = cache->format();
1202    LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1203
1204Exit:
1205    if (player != 0) player->reset();
1206    ::close(fd);
1207    return mem;
1208}
1209
1210#undef LOG_TAG
1211#define LOG_TAG "AudioSink"
1212MediaPlayerService::AudioOutput::AudioOutput()
1213    : mCallback(NULL),
1214      mCallbackCookie(NULL) {
1215    mTrack = 0;
1216    mStreamType = AudioSystem::MUSIC;
1217    mLeftVolume = 1.0;
1218    mRightVolume = 1.0;
1219    mLatency = 0;
1220    mMsecsPerFrame = 0;
1221    setMinBufferCount();
1222}
1223
1224MediaPlayerService::AudioOutput::~AudioOutput()
1225{
1226    close();
1227}
1228
1229void MediaPlayerService::AudioOutput::setMinBufferCount()
1230{
1231    char value[PROPERTY_VALUE_MAX];
1232    if (property_get("ro.kernel.qemu", value, 0)) {
1233        mIsOnEmulator = true;
1234        mMinBufferCount = 12;  // to prevent systematic buffer underrun for emulator
1235    }
1236}
1237
1238bool MediaPlayerService::AudioOutput::isOnEmulator()
1239{
1240    setMinBufferCount();
1241    return mIsOnEmulator;
1242}
1243
1244int MediaPlayerService::AudioOutput::getMinBufferCount()
1245{
1246    setMinBufferCount();
1247    return mMinBufferCount;
1248}
1249
1250ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1251{
1252    if (mTrack == 0) return NO_INIT;
1253    return mTrack->frameCount() * frameSize();
1254}
1255
1256ssize_t MediaPlayerService::AudioOutput::frameCount() const
1257{
1258    if (mTrack == 0) return NO_INIT;
1259    return mTrack->frameCount();
1260}
1261
1262ssize_t MediaPlayerService::AudioOutput::channelCount() const
1263{
1264    if (mTrack == 0) return NO_INIT;
1265    return mTrack->channelCount();
1266}
1267
1268ssize_t MediaPlayerService::AudioOutput::frameSize() const
1269{
1270    if (mTrack == 0) return NO_INIT;
1271    return mTrack->frameSize();
1272}
1273
1274uint32_t MediaPlayerService::AudioOutput::latency () const
1275{
1276    return mLatency;
1277}
1278
1279float MediaPlayerService::AudioOutput::msecsPerFrame() const
1280{
1281    return mMsecsPerFrame;
1282}
1283
1284status_t MediaPlayerService::AudioOutput::open(
1285        uint32_t sampleRate, int channelCount, int format, int bufferCount,
1286        AudioCallback cb, void *cookie)
1287{
1288    mCallback = cb;
1289    mCallbackCookie = cookie;
1290
1291    // Check argument "bufferCount" against the mininum buffer count
1292    if (bufferCount < mMinBufferCount) {
1293        LOGD("bufferCount (%d) is too small and increased to %d", bufferCount, mMinBufferCount);
1294        bufferCount = mMinBufferCount;
1295
1296    }
1297    LOGV("open(%u, %d, %d, %d)", sampleRate, channelCount, format, bufferCount);
1298    if (mTrack) close();
1299    int afSampleRate;
1300    int afFrameCount;
1301    int frameCount;
1302
1303    if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1304        return NO_INIT;
1305    }
1306    if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1307        return NO_INIT;
1308    }
1309
1310    frameCount = (sampleRate*afFrameCount*bufferCount)/afSampleRate;
1311
1312    AudioTrack *t;
1313    if (mCallback != NULL) {
1314        t = new AudioTrack(
1315                mStreamType,
1316                sampleRate,
1317                format,
1318                (channelCount == 2) ? AudioSystem::CHANNEL_OUT_STEREO : AudioSystem::CHANNEL_OUT_MONO,
1319                frameCount,
1320                0 /* flags */,
1321                CallbackWrapper,
1322                this);
1323    } else {
1324        t = new AudioTrack(
1325                mStreamType,
1326                sampleRate,
1327                format,
1328                (channelCount == 2) ? AudioSystem::CHANNEL_OUT_STEREO : AudioSystem::CHANNEL_OUT_MONO,
1329                frameCount);
1330    }
1331
1332    if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1333        LOGE("Unable to create audio track");
1334        delete t;
1335        return NO_INIT;
1336    }
1337
1338    LOGV("setVolume");
1339    t->setVolume(mLeftVolume, mRightVolume);
1340    mMsecsPerFrame = 1.e3 / (float) sampleRate;
1341    mLatency = t->latency() + kAudioVideoDelayMs;
1342    mTrack = t;
1343    return NO_ERROR;
1344}
1345
1346void MediaPlayerService::AudioOutput::start()
1347{
1348    LOGV("start");
1349    if (mTrack) {
1350        mTrack->setVolume(mLeftVolume, mRightVolume);
1351        mTrack->start();
1352    }
1353}
1354
1355ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size)
1356{
1357    LOG_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
1358
1359    //LOGV("write(%p, %u)", buffer, size);
1360    if (mTrack) return mTrack->write(buffer, size);
1361    return NO_INIT;
1362}
1363
1364void MediaPlayerService::AudioOutput::stop()
1365{
1366    LOGV("stop");
1367    if (mTrack) mTrack->stop();
1368}
1369
1370void MediaPlayerService::AudioOutput::flush()
1371{
1372    LOGV("flush");
1373    if (mTrack) mTrack->flush();
1374}
1375
1376void MediaPlayerService::AudioOutput::pause()
1377{
1378    LOGV("pause");
1379    if (mTrack) mTrack->pause();
1380}
1381
1382void MediaPlayerService::AudioOutput::close()
1383{
1384    LOGV("close");
1385    delete mTrack;
1386    mTrack = 0;
1387}
1388
1389void MediaPlayerService::AudioOutput::setVolume(float left, float right)
1390{
1391    LOGV("setVolume(%f, %f)", left, right);
1392    mLeftVolume = left;
1393    mRightVolume = right;
1394    if (mTrack) {
1395        mTrack->setVolume(left, right);
1396    }
1397}
1398
1399// static
1400void MediaPlayerService::AudioOutput::CallbackWrapper(
1401        int event, void *cookie, void *info) {
1402    if (event != AudioTrack::EVENT_MORE_DATA) {
1403        return;
1404    }
1405
1406    AudioOutput *me = (AudioOutput *)cookie;
1407    AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
1408
1409    (*me->mCallback)(
1410            me, buffer->raw, buffer->size, me->mCallbackCookie);
1411}
1412
1413#undef LOG_TAG
1414#define LOG_TAG "AudioCache"
1415MediaPlayerService::AudioCache::AudioCache(const char* name) :
1416    mChannelCount(0), mFrameCount(1024), mSampleRate(0), mSize(0),
1417    mError(NO_ERROR), mCommandComplete(false)
1418{
1419    // create ashmem heap
1420    mHeap = new MemoryHeapBase(kDefaultHeapSize, 0, name);
1421}
1422
1423uint32_t MediaPlayerService::AudioCache::latency () const
1424{
1425    return 0;
1426}
1427
1428float MediaPlayerService::AudioCache::msecsPerFrame() const
1429{
1430    return mMsecsPerFrame;
1431}
1432
1433status_t MediaPlayerService::AudioCache::open(
1434        uint32_t sampleRate, int channelCount, int format, int bufferCount,
1435        AudioCallback cb, void *cookie)
1436{
1437    if (cb != NULL) {
1438        return UNKNOWN_ERROR;  // TODO: implement this.
1439    }
1440
1441    LOGV("open(%u, %d, %d, %d)", sampleRate, channelCount, format, bufferCount);
1442    if (mHeap->getHeapID() < 0) return NO_INIT;
1443    mSampleRate = sampleRate;
1444    mChannelCount = (uint16_t)channelCount;
1445    mFormat = (uint16_t)format;
1446    mMsecsPerFrame = 1.e3 / (float) sampleRate;
1447    return NO_ERROR;
1448}
1449
1450ssize_t MediaPlayerService::AudioCache::write(const void* buffer, size_t size)
1451{
1452    LOGV("write(%p, %u)", buffer, size);
1453    if ((buffer == 0) || (size == 0)) return size;
1454
1455    uint8_t* p = static_cast<uint8_t*>(mHeap->getBase());
1456    if (p == NULL) return NO_INIT;
1457    p += mSize;
1458    LOGV("memcpy(%p, %p, %u)", p, buffer, size);
1459    if (mSize + size > mHeap->getSize()) {
1460        LOGE("Heap size overflow! req size: %d, max size: %d", (mSize + size), mHeap->getSize());
1461        size = mHeap->getSize() - mSize;
1462    }
1463    memcpy(p, buffer, size);
1464    mSize += size;
1465    return size;
1466}
1467
1468// call with lock held
1469status_t MediaPlayerService::AudioCache::wait()
1470{
1471    Mutex::Autolock lock(mLock);
1472    if (!mCommandComplete) {
1473        mSignal.wait(mLock);
1474    }
1475    mCommandComplete = false;
1476
1477    if (mError == NO_ERROR) {
1478        LOGV("wait - success");
1479    } else {
1480        LOGV("wait - error");
1481    }
1482    return mError;
1483}
1484
1485void MediaPlayerService::AudioCache::notify(void* cookie, int msg, int ext1, int ext2)
1486{
1487    LOGV("notify(%p, %d, %d, %d)", cookie, msg, ext1, ext2);
1488    AudioCache* p = static_cast<AudioCache*>(cookie);
1489
1490    // ignore buffering messages
1491    if (msg == MEDIA_BUFFERING_UPDATE) return;
1492
1493    // set error condition
1494    if (msg == MEDIA_ERROR) {
1495        LOGE("Error %d, %d occurred", ext1, ext2);
1496        p->mError = ext1;
1497    }
1498
1499    // wake up thread
1500    LOGV("wakeup thread");
1501    p->mCommandComplete = true;
1502    p->mSignal.signal();
1503}
1504
1505} // namespace android
1506