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