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