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