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