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