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