MediaPlayerService.cpp revision 8635b7b095fbf7ffc63d3ce791891a9116ace1f6
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 <sys/time.h>
27#include <dirent.h>
28#include <unistd.h>
29
30#include <string.h>
31
32#include <cutils/atomic.h>
33#include <cutils/properties.h> // for property_get
34
35#include <utils/misc.h>
36
37#include <android_runtime/ActivityManager.h>
38
39#include <binder/IPCThreadState.h>
40#include <binder/IServiceManager.h>
41#include <binder/MemoryHeapBase.h>
42#include <binder/MemoryBase.h>
43#include <utils/Errors.h>  // for status_t
44#include <utils/String8.h>
45#include <utils/SystemClock.h>
46#include <utils/Vector.h>
47#include <cutils/properties.h>
48
49#include <media/MediaPlayerInterface.h>
50#include <media/mediarecorder.h>
51#include <media/MediaMetadataRetrieverInterface.h>
52#include <media/Metadata.h>
53#include <media/AudioTrack.h>
54#include <media/MemoryLeakTrackUtil.h>
55
56#include <private/android_filesystem_config.h>
57
58#include "MediaRecorderClient.h"
59#include "MediaPlayerService.h"
60#include "MetadataRetrieverClient.h"
61
62#include "MidiFile.h"
63#include "TestPlayerStub.h"
64#include "StagefrightPlayer.h"
65#include "nuplayer/NuPlayerDriver.h"
66
67#include <OMX.h>
68
69/* desktop Linux needs a little help with gettid() */
70#if defined(HAVE_GETTID) && !defined(HAVE_ANDROID_OS)
71#define __KERNEL__
72# include <linux/unistd.h>
73#ifdef _syscall0
74_syscall0(pid_t,gettid)
75#else
76pid_t gettid() { return syscall(__NR_gettid);}
77#endif
78#undef __KERNEL__
79#endif
80
81namespace {
82using android::media::Metadata;
83using android::status_t;
84using android::OK;
85using android::BAD_VALUE;
86using android::NOT_ENOUGH_DATA;
87using android::Parcel;
88
89// Max number of entries in the filter.
90const int kMaxFilterSize = 64;  // I pulled that out of thin air.
91
92// FIXME: Move all the metadata related function in the Metadata.cpp
93
94
95// Unmarshall a filter from a Parcel.
96// Filter format in a parcel:
97//
98//  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
99// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
100// |                       number of entries (n)                   |
101// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
102// |                       metadata type 1                         |
103// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
104// |                       metadata type 2                         |
105// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
106//  ....
107// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
108// |                       metadata type n                         |
109// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
110//
111// @param p Parcel that should start with a filter.
112// @param[out] filter On exit contains the list of metadata type to be
113//                    filtered.
114// @param[out] status On exit contains the status code to be returned.
115// @return true if the parcel starts with a valid filter.
116bool unmarshallFilter(const Parcel& p,
117                      Metadata::Filter *filter,
118                      status_t *status)
119{
120    int32_t val;
121    if (p.readInt32(&val) != OK)
122    {
123        LOGE("Failed to read filter's length");
124        *status = NOT_ENOUGH_DATA;
125        return false;
126    }
127
128    if( val > kMaxFilterSize || val < 0)
129    {
130        LOGE("Invalid filter len %d", val);
131        *status = BAD_VALUE;
132        return false;
133    }
134
135    const size_t num = val;
136
137    filter->clear();
138    filter->setCapacity(num);
139
140    size_t size = num * sizeof(Metadata::Type);
141
142
143    if (p.dataAvail() < size)
144    {
145        LOGE("Filter too short expected %d but got %d", size, p.dataAvail());
146        *status = NOT_ENOUGH_DATA;
147        return false;
148    }
149
150    const Metadata::Type *data =
151            static_cast<const Metadata::Type*>(p.readInplace(size));
152
153    if (NULL == data)
154    {
155        LOGE("Filter had no data");
156        *status = BAD_VALUE;
157        return false;
158    }
159
160    // TODO: The stl impl of vector would be more efficient here
161    // because it degenerates into a memcpy on pod types. Try to
162    // replace later or use stl::set.
163    for (size_t i = 0; i < num; ++i)
164    {
165        filter->add(*data);
166        ++data;
167    }
168    *status = OK;
169    return true;
170}
171
172// @param filter Of metadata type.
173// @param val To be searched.
174// @return true if a match was found.
175bool findMetadata(const Metadata::Filter& filter, const int32_t val)
176{
177    // Deal with empty and ANY right away
178    if (filter.isEmpty()) return false;
179    if (filter[0] == Metadata::kAny) return true;
180
181    return filter.indexOf(val) >= 0;
182}
183
184}  // anonymous namespace
185
186
187namespace android {
188
189// TODO: Temp hack until we can register players
190typedef struct {
191    const char *extension;
192    const player_type playertype;
193} extmap;
194extmap FILE_EXTS [] =  {
195        {".mid", SONIVOX_PLAYER},
196        {".midi", SONIVOX_PLAYER},
197        {".smf", SONIVOX_PLAYER},
198        {".xmf", SONIVOX_PLAYER},
199        {".imy", SONIVOX_PLAYER},
200        {".rtttl", SONIVOX_PLAYER},
201        {".rtx", SONIVOX_PLAYER},
202        {".ota", SONIVOX_PLAYER},
203};
204
205// TODO: Find real cause of Audio/Video delay in PV framework and remove this workaround
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    mBatteryAudio.refCount = 0;
220    for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
221        mBatteryAudio.deviceOn[i] = 0;
222        mBatteryAudio.lastTime[i] = 0;
223        mBatteryAudio.totalTime[i] = 0;
224    }
225    // speaker is on by default
226    mBatteryAudio.deviceOn[SPEAKER] = 1;
227}
228
229MediaPlayerService::~MediaPlayerService()
230{
231    LOGV("MediaPlayerService destroyed");
232}
233
234sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(pid_t pid)
235{
236    sp<MediaRecorderClient> recorder = new MediaRecorderClient(this, pid);
237    wp<MediaRecorderClient> w = recorder;
238    Mutex::Autolock lock(mLock);
239    mMediaRecorderClients.add(w);
240    LOGV("Create new media recorder client from pid %d", pid);
241    return recorder;
242}
243
244void MediaPlayerService::removeMediaRecorderClient(wp<MediaRecorderClient> client)
245{
246    Mutex::Autolock lock(mLock);
247    mMediaRecorderClients.remove(client);
248    LOGV("Delete media recorder client");
249}
250
251sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever(pid_t pid)
252{
253    sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
254    LOGV("Create new media retriever from pid %d", pid);
255    return retriever;
256}
257
258sp<IMediaPlayer> MediaPlayerService::create(
259        pid_t pid, const sp<IMediaPlayerClient>& client, const char* url,
260        const KeyedVector<String8, String8> *headers, int audioSessionId)
261{
262    int32_t connId = android_atomic_inc(&mNextConnId);
263    sp<Client> c = new Client(this, pid, connId, client, audioSessionId);
264    LOGV("Create new client(%d) from pid %d, url=%s, connId=%d, audioSessionId=%d",
265            connId, pid, url, connId, audioSessionId);
266    if (NO_ERROR != c->setDataSource(url, headers))
267    {
268        c.clear();
269        return c;
270    }
271    wp<Client> w = c;
272    Mutex::Autolock lock(mLock);
273    mClients.add(w);
274    return c;
275}
276
277sp<IMediaPlayer> MediaPlayerService::create(pid_t pid, const sp<IMediaPlayerClient>& client,
278        int fd, int64_t offset, int64_t length, int audioSessionId)
279{
280    int32_t connId = android_atomic_inc(&mNextConnId);
281    sp<Client> c = new Client(this, pid, connId, client, audioSessionId);
282    LOGV("Create new client(%d) from pid %d, fd=%d, offset=%lld, length=%lld, audioSessionId=%d",
283            connId, pid, fd, offset, length, audioSessionId);
284    if (NO_ERROR != c->setDataSource(fd, offset, length)) {
285        c.clear();
286    } else {
287        wp<Client> w = c;
288        Mutex::Autolock lock(mLock);
289        mClients.add(w);
290    }
291    ::close(fd);
292    return c;
293}
294
295sp<IMediaPlayer> MediaPlayerService::create(
296        pid_t pid, const sp<IMediaPlayerClient> &client,
297        const sp<IStreamSource> &source, int audioSessionId) {
298    int32_t connId = android_atomic_inc(&mNextConnId);
299    sp<Client> c = new Client(this, pid, connId, client, audioSessionId);
300
301    LOGV("Create new client(%d) from pid %d, audioSessionId=%d",
302         connId, pid, audioSessionId);
303
304    if (OK != c->setDataSource(source)) {
305        c.clear();
306    } else {
307        wp<Client> w = c;
308        Mutex::Autolock lock(mLock);
309        mClients.add(w);
310    }
311
312    return c;
313}
314
315sp<IOMX> MediaPlayerService::getOMX() {
316    Mutex::Autolock autoLock(mLock);
317
318    if (mOMX.get() == NULL) {
319        mOMX = new OMX;
320    }
321
322    return mOMX;
323}
324
325status_t MediaPlayerService::AudioCache::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(" AudioCache\n");
332    if (mHeap != 0) {
333        snprintf(buffer, 255, "  heap base(%p), size(%d), flags(%d), device(%s)\n",
334                mHeap->getBase(), mHeap->getSize(), mHeap->getFlags(), mHeap->getDevice());
335        result.append(buffer);
336    }
337    snprintf(buffer, 255, "  msec per frame(%f), channel count(%d), format(%d), frame count(%ld)\n",
338            mMsecsPerFrame, mChannelCount, mFormat, mFrameCount);
339    result.append(buffer);
340    snprintf(buffer, 255, "  sample rate(%d), size(%d), error(%d), command complete(%s)\n",
341            mSampleRate, mSize, mError, mCommandComplete?"true":"false");
342    result.append(buffer);
343    ::write(fd, result.string(), result.size());
344    return NO_ERROR;
345}
346
347status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
348{
349    const size_t SIZE = 256;
350    char buffer[SIZE];
351    String8 result;
352
353    result.append(" AudioOutput\n");
354    snprintf(buffer, 255, "  stream type(%d), left - right volume(%f, %f)\n",
355            mStreamType, mLeftVolume, mRightVolume);
356    result.append(buffer);
357    snprintf(buffer, 255, "  msec per frame(%f), latency (%d)\n",
358            mMsecsPerFrame, mLatency);
359    result.append(buffer);
360    snprintf(buffer, 255, "  aux effect id(%d), send level (%f)\n",
361            mAuxEffectId, mSendLevel);
362    result.append(buffer);
363
364    ::write(fd, result.string(), result.size());
365    if (mTrack != 0) {
366        mTrack->dump(fd, args);
367    }
368    return NO_ERROR;
369}
370
371status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args) const
372{
373    const size_t SIZE = 256;
374    char buffer[SIZE];
375    String8 result;
376    result.append(" Client\n");
377    snprintf(buffer, 255, "  pid(%d), connId(%d), status(%d), looping(%s)\n",
378            mPid, mConnId, mStatus, mLoop?"true": "false");
379    result.append(buffer);
380    write(fd, result.string(), result.size());
381    if (mAudioOutput != 0) {
382        mAudioOutput->dump(fd, args);
383    }
384    write(fd, "\n", 1);
385    return NO_ERROR;
386}
387
388static int myTid() {
389#ifdef HAVE_GETTID
390    return gettid();
391#else
392    return getpid();
393#endif
394}
395
396status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
397{
398    const size_t SIZE = 256;
399    char buffer[SIZE];
400    String8 result;
401    if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
402        snprintf(buffer, SIZE, "Permission Denial: "
403                "can't dump MediaPlayerService from pid=%d, uid=%d\n",
404                IPCThreadState::self()->getCallingPid(),
405                IPCThreadState::self()->getCallingUid());
406        result.append(buffer);
407    } else {
408        Mutex::Autolock lock(mLock);
409        for (int i = 0, n = mClients.size(); i < n; ++i) {
410            sp<Client> c = mClients[i].promote();
411            if (c != 0) c->dump(fd, args);
412        }
413        if (mMediaRecorderClients.size() == 0) {
414                result.append(" No media recorder client\n\n");
415        } else {
416            for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
417                sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
418                snprintf(buffer, 255, " MediaRecorderClient pid(%d)\n", c->mPid);
419                result.append(buffer);
420                write(fd, result.string(), result.size());
421                result = "\n";
422                c->dump(fd, args);
423            }
424        }
425
426        result.append(" Files opened and/or mapped:\n");
427        snprintf(buffer, SIZE, "/proc/%d/maps", myTid());
428        FILE *f = fopen(buffer, "r");
429        if (f) {
430            while (!feof(f)) {
431                fgets(buffer, SIZE, f);
432                if (strstr(buffer, " /mnt/sdcard/") ||
433                    strstr(buffer, " /system/sounds/") ||
434                    strstr(buffer, " /data/") ||
435                    strstr(buffer, " /system/media/")) {
436                    result.append("  ");
437                    result.append(buffer);
438                }
439            }
440            fclose(f);
441        } else {
442            result.append("couldn't open ");
443            result.append(buffer);
444            result.append("\n");
445        }
446
447        snprintf(buffer, SIZE, "/proc/%d/fd", myTid());
448        DIR *d = opendir(buffer);
449        if (d) {
450            struct dirent *ent;
451            while((ent = readdir(d)) != NULL) {
452                if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
453                    snprintf(buffer, SIZE, "/proc/%d/fd/%s", myTid(), ent->d_name);
454                    struct stat s;
455                    if (lstat(buffer, &s) == 0) {
456                        if ((s.st_mode & S_IFMT) == S_IFLNK) {
457                            char linkto[256];
458                            int len = readlink(buffer, linkto, sizeof(linkto));
459                            if(len > 0) {
460                                if(len > 255) {
461                                    linkto[252] = '.';
462                                    linkto[253] = '.';
463                                    linkto[254] = '.';
464                                    linkto[255] = 0;
465                                } else {
466                                    linkto[len] = 0;
467                                }
468                                if (strstr(linkto, "/mnt/sdcard/") == linkto ||
469                                    strstr(linkto, "/system/sounds/") == linkto ||
470                                    strstr(linkto, "/data/") == linkto ||
471                                    strstr(linkto, "/system/media/") == linkto) {
472                                    result.append("  ");
473                                    result.append(buffer);
474                                    result.append(" -> ");
475                                    result.append(linkto);
476                                    result.append("\n");
477                                }
478                            }
479                        } else {
480                            result.append("  unexpected type for ");
481                            result.append(buffer);
482                            result.append("\n");
483                        }
484                    }
485                }
486            }
487            closedir(d);
488        } else {
489            result.append("couldn't open ");
490            result.append(buffer);
491            result.append("\n");
492        }
493
494        bool dumpMem = false;
495        for (size_t i = 0; i < args.size(); i++) {
496            if (args[i] == String16("-m")) {
497                dumpMem = true;
498            }
499        }
500        if (dumpMem) {
501            dumpMemoryAddresses(fd);
502        }
503    }
504    write(fd, result.string(), result.size());
505    return NO_ERROR;
506}
507
508void MediaPlayerService::removeClient(wp<Client> client)
509{
510    Mutex::Autolock lock(mLock);
511    mClients.remove(client);
512}
513
514MediaPlayerService::Client::Client(const sp<MediaPlayerService>& service, pid_t pid,
515        int32_t connId, const sp<IMediaPlayerClient>& client, int audioSessionId)
516{
517    LOGV("Client(%d) constructor", connId);
518    mPid = pid;
519    mConnId = connId;
520    mService = service;
521    mClient = client;
522    mLoop = false;
523    mStatus = NO_INIT;
524    mAudioSessionId = audioSessionId;
525
526#if CALLBACK_ANTAGONIZER
527    LOGD("create Antagonizer");
528    mAntagonizer = new Antagonizer(notify, this);
529#endif
530}
531
532MediaPlayerService::Client::~Client()
533{
534    LOGV("Client(%d) destructor pid = %d", mConnId, mPid);
535    mAudioOutput.clear();
536    wp<Client> client(this);
537    disconnect();
538    mService->removeClient(client);
539}
540
541void MediaPlayerService::Client::disconnect()
542{
543    LOGV("disconnect(%d) from pid %d", mConnId, mPid);
544    // grab local reference and clear main reference to prevent future
545    // access to object
546    sp<MediaPlayerBase> p;
547    {
548        Mutex::Autolock l(mLock);
549        p = mPlayer;
550    }
551    mClient.clear();
552
553    mPlayer.clear();
554
555    // clear the notification to prevent callbacks to dead client
556    // and reset the player. We assume the player will serialize
557    // access to itself if necessary.
558    if (p != 0) {
559        p->setNotifyCallback(0, 0);
560#if CALLBACK_ANTAGONIZER
561        LOGD("kill Antagonizer");
562        mAntagonizer->kill();
563#endif
564        p->reset();
565    }
566
567    IPCThreadState::self()->flushCommands();
568}
569
570static player_type getDefaultPlayerType() {
571    return STAGEFRIGHT_PLAYER;
572}
573
574player_type getPlayerType(int fd, int64_t offset, int64_t length)
575{
576    char buf[20];
577    lseek(fd, offset, SEEK_SET);
578    read(fd, buf, sizeof(buf));
579    lseek(fd, offset, SEEK_SET);
580
581    long ident = *((long*)buf);
582
583    // Ogg vorbis?
584    if (ident == 0x5367674f) // 'OggS'
585        return STAGEFRIGHT_PLAYER;
586
587    // Some kind of MIDI?
588    EAS_DATA_HANDLE easdata;
589    if (EAS_Init(&easdata) == EAS_SUCCESS) {
590        EAS_FILE locator;
591        locator.path = NULL;
592        locator.fd = fd;
593        locator.offset = offset;
594        locator.length = length;
595        EAS_HANDLE  eashandle;
596        if (EAS_OpenFile(easdata, &locator, &eashandle) == EAS_SUCCESS) {
597            EAS_CloseFile(easdata, eashandle);
598            EAS_Shutdown(easdata);
599            return SONIVOX_PLAYER;
600        }
601        EAS_Shutdown(easdata);
602    }
603
604    return getDefaultPlayerType();
605}
606
607player_type getPlayerType(const char* url)
608{
609    if (TestPlayerStub::canBeUsed(url)) {
610        return TEST_PLAYER;
611    }
612
613    if (!strncasecmp("http://", url, 7)) {
614        size_t len = strlen(url);
615        if (len >= 5 && !strcasecmp(".m3u8", &url[len - 5])) {
616            return NU_PLAYER;
617        }
618
619        if (strstr(url,"m3u8")) {
620            return NU_PLAYER;
621        }
622    }
623
624    // use MidiFile for MIDI extensions
625    int lenURL = strlen(url);
626    for (int i = 0; i < NELEM(FILE_EXTS); ++i) {
627        int len = strlen(FILE_EXTS[i].extension);
628        int start = lenURL - len;
629        if (start > 0) {
630            if (!strncasecmp(url + start, FILE_EXTS[i].extension, len)) {
631                return FILE_EXTS[i].playertype;
632            }
633        }
634    }
635
636    return getDefaultPlayerType();
637}
638
639static sp<MediaPlayerBase> createPlayer(player_type playerType, void* cookie,
640        notify_callback_f notifyFunc)
641{
642    sp<MediaPlayerBase> p;
643    switch (playerType) {
644        case SONIVOX_PLAYER:
645            LOGV(" create MidiFile");
646            p = new MidiFile();
647            break;
648        case STAGEFRIGHT_PLAYER:
649            LOGV(" create StagefrightPlayer");
650            p = new StagefrightPlayer;
651            break;
652        case NU_PLAYER:
653            LOGV(" create NuPlayer");
654            p = new NuPlayerDriver;
655            break;
656        case TEST_PLAYER:
657            LOGV("Create Test Player stub");
658            p = new TestPlayerStub();
659            break;
660        default:
661            LOGE("Unknown player type: %d", playerType);
662            return NULL;
663    }
664    if (p != NULL) {
665        if (p->initCheck() == NO_ERROR) {
666            p->setNotifyCallback(cookie, notifyFunc);
667        } else {
668            p.clear();
669        }
670    }
671    if (p == NULL) {
672        LOGE("Failed to create player object");
673    }
674    return p;
675}
676
677sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
678{
679    // determine if we have the right player type
680    sp<MediaPlayerBase> p = mPlayer;
681    if ((p != NULL) && (p->playerType() != playerType)) {
682        LOGV("delete player");
683        p.clear();
684    }
685    if (p == NULL) {
686        p = android::createPlayer(playerType, this, notify);
687    }
688    return p;
689}
690
691status_t MediaPlayerService::Client::setDataSource(
692        const char *url, const KeyedVector<String8, String8> *headers)
693{
694    LOGV("setDataSource(%s)", url);
695    if (url == NULL)
696        return UNKNOWN_ERROR;
697
698    if (strncmp(url, "content://", 10) == 0) {
699        // get a filedescriptor for the content Uri and
700        // pass it to the setDataSource(fd) method
701
702        String16 url16(url);
703        int fd = android::openContentProviderFile(url16);
704        if (fd < 0)
705        {
706            LOGE("Couldn't open fd for %s", url);
707            return UNKNOWN_ERROR;
708        }
709        setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
710        close(fd);
711        return mStatus;
712    } else {
713        player_type playerType = getPlayerType(url);
714        LOGV("player type = %d", playerType);
715
716        // create the right type of player
717        sp<MediaPlayerBase> p = createPlayer(playerType);
718        if (p == NULL) return NO_INIT;
719
720        if (!p->hardwareOutput()) {
721            mAudioOutput = new AudioOutput(mAudioSessionId);
722            static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
723        }
724
725        // now set data source
726        LOGV(" setDataSource");
727        mStatus = p->setDataSource(url, headers);
728        if (mStatus == NO_ERROR) {
729            mPlayer = p;
730        } else {
731            LOGE("  error: %d", mStatus);
732        }
733        return mStatus;
734    }
735}
736
737status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
738{
739    LOGV("setDataSource fd=%d, offset=%lld, length=%lld", fd, offset, length);
740    struct stat sb;
741    int ret = fstat(fd, &sb);
742    if (ret != 0) {
743        LOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
744        return UNKNOWN_ERROR;
745    }
746
747    LOGV("st_dev  = %llu", sb.st_dev);
748    LOGV("st_mode = %u", sb.st_mode);
749    LOGV("st_uid  = %lu", sb.st_uid);
750    LOGV("st_gid  = %lu", sb.st_gid);
751    LOGV("st_size = %llu", sb.st_size);
752
753    if (offset >= sb.st_size) {
754        LOGE("offset error");
755        ::close(fd);
756        return UNKNOWN_ERROR;
757    }
758    if (offset + length > sb.st_size) {
759        length = sb.st_size - offset;
760        LOGV("calculated length = %lld", length);
761    }
762
763    player_type playerType = getPlayerType(fd, offset, length);
764    LOGV("player type = %d", playerType);
765
766    // create the right type of player
767    sp<MediaPlayerBase> p = createPlayer(playerType);
768    if (p == NULL) return NO_INIT;
769
770    if (!p->hardwareOutput()) {
771        mAudioOutput = new AudioOutput(mAudioSessionId);
772        static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
773    }
774
775    // now set data source
776    mStatus = p->setDataSource(fd, offset, length);
777    if (mStatus == NO_ERROR) mPlayer = p;
778    return mStatus;
779}
780
781status_t MediaPlayerService::Client::setDataSource(
782        const sp<IStreamSource> &source) {
783    // create the right type of player
784    sp<MediaPlayerBase> p = createPlayer(NU_PLAYER);
785
786    if (p == NULL) {
787        return NO_INIT;
788    }
789
790    if (!p->hardwareOutput()) {
791        mAudioOutput = new AudioOutput(mAudioSessionId);
792        static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
793    }
794
795    // now set data source
796    mStatus = p->setDataSource(source);
797
798    if (mStatus == OK) {
799        mPlayer = p;
800    }
801
802    return mStatus;
803}
804
805status_t MediaPlayerService::Client::setVideoSurface(const sp<Surface>& surface)
806{
807    LOGV("[%d] setVideoSurface(%p)", mConnId, surface.get());
808    sp<MediaPlayerBase> p = getPlayer();
809    if (p == 0) return UNKNOWN_ERROR;
810    return p->setVideoSurface(surface);
811}
812
813status_t MediaPlayerService::Client::setVideoSurfaceTexture(
814        const sp<ISurfaceTexture>& surfaceTexture)
815{
816    LOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, surfaceTexture.get());
817    sp<MediaPlayerBase> p = getPlayer();
818    if (p == 0) return UNKNOWN_ERROR;
819    return p->setVideoSurfaceTexture(surfaceTexture);
820}
821
822status_t MediaPlayerService::Client::invoke(const Parcel& request,
823                                            Parcel *reply)
824{
825    sp<MediaPlayerBase> p = getPlayer();
826    if (p == NULL) return UNKNOWN_ERROR;
827    return p->invoke(request, reply);
828}
829
830// This call doesn't need to access the native player.
831status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
832{
833    status_t status;
834    media::Metadata::Filter allow, drop;
835
836    if (unmarshallFilter(filter, &allow, &status) &&
837        unmarshallFilter(filter, &drop, &status)) {
838        Mutex::Autolock lock(mLock);
839
840        mMetadataAllow = allow;
841        mMetadataDrop = drop;
842    }
843    return status;
844}
845
846status_t MediaPlayerService::Client::getMetadata(
847        bool update_only, bool apply_filter, Parcel *reply)
848{
849    sp<MediaPlayerBase> player = getPlayer();
850    if (player == 0) return UNKNOWN_ERROR;
851
852    status_t status;
853    // Placeholder for the return code, updated by the caller.
854    reply->writeInt32(-1);
855
856    media::Metadata::Filter ids;
857
858    // We don't block notifications while we fetch the data. We clear
859    // mMetadataUpdated first so we don't lose notifications happening
860    // during the rest of this call.
861    {
862        Mutex::Autolock lock(mLock);
863        if (update_only) {
864            ids = mMetadataUpdated;
865        }
866        mMetadataUpdated.clear();
867    }
868
869    media::Metadata metadata(reply);
870
871    metadata.appendHeader();
872    status = player->getMetadata(ids, reply);
873
874    if (status != OK) {
875        metadata.resetParcel();
876        LOGE("getMetadata failed %d", status);
877        return status;
878    }
879
880    // FIXME: Implement filtering on the result. Not critical since
881    // filtering takes place on the update notifications already. This
882    // would be when all the metadata are fetch and a filter is set.
883
884    // Everything is fine, update the metadata length.
885    metadata.updateLength();
886    return OK;
887}
888
889status_t MediaPlayerService::Client::prepareAsync()
890{
891    LOGV("[%d] prepareAsync", mConnId);
892    sp<MediaPlayerBase> p = getPlayer();
893    if (p == 0) return UNKNOWN_ERROR;
894    status_t ret = p->prepareAsync();
895#if CALLBACK_ANTAGONIZER
896    LOGD("start Antagonizer");
897    if (ret == NO_ERROR) mAntagonizer->start();
898#endif
899    return ret;
900}
901
902status_t MediaPlayerService::Client::start()
903{
904    LOGV("[%d] start", mConnId);
905    sp<MediaPlayerBase> p = getPlayer();
906    if (p == 0) return UNKNOWN_ERROR;
907    p->setLooping(mLoop);
908    return p->start();
909}
910
911status_t MediaPlayerService::Client::stop()
912{
913    LOGV("[%d] stop", mConnId);
914    sp<MediaPlayerBase> p = getPlayer();
915    if (p == 0) return UNKNOWN_ERROR;
916    return p->stop();
917}
918
919status_t MediaPlayerService::Client::pause()
920{
921    LOGV("[%d] pause", mConnId);
922    sp<MediaPlayerBase> p = getPlayer();
923    if (p == 0) return UNKNOWN_ERROR;
924    return p->pause();
925}
926
927status_t MediaPlayerService::Client::isPlaying(bool* state)
928{
929    *state = false;
930    sp<MediaPlayerBase> p = getPlayer();
931    if (p == 0) return UNKNOWN_ERROR;
932    *state = p->isPlaying();
933    LOGV("[%d] isPlaying: %d", mConnId, *state);
934    return NO_ERROR;
935}
936
937status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
938{
939    LOGV("getCurrentPosition");
940    sp<MediaPlayerBase> p = getPlayer();
941    if (p == 0) return UNKNOWN_ERROR;
942    status_t ret = p->getCurrentPosition(msec);
943    if (ret == NO_ERROR) {
944        LOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
945    } else {
946        LOGE("getCurrentPosition returned %d", ret);
947    }
948    return ret;
949}
950
951status_t MediaPlayerService::Client::getDuration(int *msec)
952{
953    LOGV("getDuration");
954    sp<MediaPlayerBase> p = getPlayer();
955    if (p == 0) return UNKNOWN_ERROR;
956    status_t ret = p->getDuration(msec);
957    if (ret == NO_ERROR) {
958        LOGV("[%d] getDuration = %d", mConnId, *msec);
959    } else {
960        LOGE("getDuration returned %d", ret);
961    }
962    return ret;
963}
964
965status_t MediaPlayerService::Client::seekTo(int msec)
966{
967    LOGV("[%d] seekTo(%d)", mConnId, msec);
968    sp<MediaPlayerBase> p = getPlayer();
969    if (p == 0) return UNKNOWN_ERROR;
970    return p->seekTo(msec);
971}
972
973status_t MediaPlayerService::Client::reset()
974{
975    LOGV("[%d] reset", mConnId);
976    sp<MediaPlayerBase> p = getPlayer();
977    if (p == 0) return UNKNOWN_ERROR;
978    return p->reset();
979}
980
981status_t MediaPlayerService::Client::setAudioStreamType(int type)
982{
983    LOGV("[%d] setAudioStreamType(%d)", mConnId, type);
984    // TODO: for hardware output, call player instead
985    Mutex::Autolock l(mLock);
986    if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
987    return NO_ERROR;
988}
989
990status_t MediaPlayerService::Client::setLooping(int loop)
991{
992    LOGV("[%d] setLooping(%d)", mConnId, loop);
993    mLoop = loop;
994    sp<MediaPlayerBase> p = getPlayer();
995    if (p != 0) return p->setLooping(loop);
996    return NO_ERROR;
997}
998
999status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1000{
1001    LOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
1002    // TODO: for hardware output, call player instead
1003    Mutex::Autolock l(mLock);
1004    if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1005    return NO_ERROR;
1006}
1007
1008status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1009{
1010    LOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
1011    Mutex::Autolock l(mLock);
1012    if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1013    return NO_ERROR;
1014}
1015
1016status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1017{
1018    LOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
1019    Mutex::Autolock l(mLock);
1020    if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1021    return NO_ERROR;
1022}
1023
1024void MediaPlayerService::Client::notify(void* cookie, int msg, int ext1, int ext2)
1025{
1026    Client* client = static_cast<Client*>(cookie);
1027
1028    if (MEDIA_INFO == msg &&
1029        MEDIA_INFO_METADATA_UPDATE == ext1) {
1030        const media::Metadata::Type metadata_type = ext2;
1031
1032        if(client->shouldDropMetadata(metadata_type)) {
1033            return;
1034        }
1035
1036        // Update the list of metadata that have changed. getMetadata
1037        // also access mMetadataUpdated and clears it.
1038        client->addNewMetadataUpdate(metadata_type);
1039    }
1040    LOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
1041    client->mClient->notify(msg, ext1, ext2);
1042}
1043
1044
1045bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
1046{
1047    Mutex::Autolock lock(mLock);
1048
1049    if (findMetadata(mMetadataDrop, code)) {
1050        return true;
1051    }
1052
1053    if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
1054        return false;
1055    } else {
1056        return true;
1057    }
1058}
1059
1060
1061void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
1062    Mutex::Autolock lock(mLock);
1063    if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1064        mMetadataUpdated.add(metadata_type);
1065    }
1066}
1067
1068#if CALLBACK_ANTAGONIZER
1069const int Antagonizer::interval = 10000; // 10 msecs
1070
1071Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1072    mExit(false), mActive(false), mClient(client), mCb(cb)
1073{
1074    createThread(callbackThread, this);
1075}
1076
1077void Antagonizer::kill()
1078{
1079    Mutex::Autolock _l(mLock);
1080    mActive = false;
1081    mExit = true;
1082    mCondition.wait(mLock);
1083}
1084
1085int Antagonizer::callbackThread(void* user)
1086{
1087    LOGD("Antagonizer started");
1088    Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1089    while (!p->mExit) {
1090        if (p->mActive) {
1091            LOGV("send event");
1092            p->mCb(p->mClient, 0, 0, 0);
1093        }
1094        usleep(interval);
1095    }
1096    Mutex::Autolock _l(p->mLock);
1097    p->mCondition.signal();
1098    LOGD("Antagonizer stopped");
1099    return 0;
1100}
1101#endif
1102
1103static size_t kDefaultHeapSize = 1024 * 1024; // 1MB
1104
1105sp<IMemory> MediaPlayerService::decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1106{
1107    LOGV("decode(%s)", url);
1108    sp<MemoryBase> mem;
1109    sp<MediaPlayerBase> player;
1110
1111    // Protect our precious, precious DRMd ringtones by only allowing
1112    // decoding of http, but not filesystem paths or content Uris.
1113    // If the application wants to decode those, it should open a
1114    // filedescriptor for them and use that.
1115    if (url != NULL && strncmp(url, "http://", 7) != 0) {
1116        LOGD("Can't decode %s by path, use filedescriptor instead", url);
1117        return mem;
1118    }
1119
1120    player_type playerType = getPlayerType(url);
1121    LOGV("player type = %d", playerType);
1122
1123    // create the right type of player
1124    sp<AudioCache> cache = new AudioCache(url);
1125    player = android::createPlayer(playerType, cache.get(), cache->notify);
1126    if (player == NULL) goto Exit;
1127    if (player->hardwareOutput()) goto Exit;
1128
1129    static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1130
1131    // set data source
1132    if (player->setDataSource(url) != NO_ERROR) goto Exit;
1133
1134    LOGV("prepare");
1135    player->prepareAsync();
1136
1137    LOGV("wait for prepare");
1138    if (cache->wait() != NO_ERROR) goto Exit;
1139
1140    LOGV("start");
1141    player->start();
1142
1143    LOGV("wait for playback complete");
1144    if (cache->wait() != NO_ERROR) goto Exit;
1145
1146    mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1147    *pSampleRate = cache->sampleRate();
1148    *pNumChannels = cache->channelCount();
1149    *pFormat = cache->format();
1150    LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1151
1152Exit:
1153    if (player != 0) player->reset();
1154    return mem;
1155}
1156
1157sp<IMemory> MediaPlayerService::decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1158{
1159    LOGV("decode(%d, %lld, %lld)", fd, offset, length);
1160    sp<MemoryBase> mem;
1161    sp<MediaPlayerBase> player;
1162
1163    player_type playerType = getPlayerType(fd, offset, length);
1164    LOGV("player type = %d", playerType);
1165
1166    // create the right type of player
1167    sp<AudioCache> cache = new AudioCache("decode_fd");
1168    player = android::createPlayer(playerType, cache.get(), cache->notify);
1169    if (player == NULL) goto Exit;
1170    if (player->hardwareOutput()) goto Exit;
1171
1172    static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1173
1174    // set data source
1175    if (player->setDataSource(fd, offset, length) != NO_ERROR) goto Exit;
1176
1177    LOGV("prepare");
1178    player->prepareAsync();
1179
1180    LOGV("wait for prepare");
1181    if (cache->wait() != NO_ERROR) goto Exit;
1182
1183    LOGV("start");
1184    player->start();
1185
1186    LOGV("wait for playback complete");
1187    if (cache->wait() != NO_ERROR) goto Exit;
1188
1189    mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1190    *pSampleRate = cache->sampleRate();
1191    *pNumChannels = cache->channelCount();
1192    *pFormat = cache->format();
1193    LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1194
1195Exit:
1196    if (player != 0) player->reset();
1197    ::close(fd);
1198    return mem;
1199}
1200
1201
1202#undef LOG_TAG
1203#define LOG_TAG "AudioSink"
1204MediaPlayerService::AudioOutput::AudioOutput(int sessionId)
1205    : mCallback(NULL),
1206      mCallbackCookie(NULL),
1207      mSessionId(sessionId) {
1208    LOGV("AudioOutput(%d)", sessionId);
1209    mTrack = 0;
1210    mStreamType = AudioSystem::MUSIC;
1211    mLeftVolume = 1.0;
1212    mRightVolume = 1.0;
1213    mLatency = 0;
1214    mMsecsPerFrame = 0;
1215    mAuxEffectId = 0;
1216    mSendLevel = 0.0;
1217    setMinBufferCount();
1218}
1219
1220MediaPlayerService::AudioOutput::~AudioOutput()
1221{
1222    close();
1223}
1224
1225void MediaPlayerService::AudioOutput::setMinBufferCount()
1226{
1227    char value[PROPERTY_VALUE_MAX];
1228    if (property_get("ro.kernel.qemu", value, 0)) {
1229        mIsOnEmulator = true;
1230        mMinBufferCount = 12;  // to prevent systematic buffer underrun for emulator
1231    }
1232}
1233
1234bool MediaPlayerService::AudioOutput::isOnEmulator()
1235{
1236    setMinBufferCount();
1237    return mIsOnEmulator;
1238}
1239
1240int MediaPlayerService::AudioOutput::getMinBufferCount()
1241{
1242    setMinBufferCount();
1243    return mMinBufferCount;
1244}
1245
1246ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1247{
1248    if (mTrack == 0) return NO_INIT;
1249    return mTrack->frameCount() * frameSize();
1250}
1251
1252ssize_t MediaPlayerService::AudioOutput::frameCount() const
1253{
1254    if (mTrack == 0) return NO_INIT;
1255    return mTrack->frameCount();
1256}
1257
1258ssize_t MediaPlayerService::AudioOutput::channelCount() const
1259{
1260    if (mTrack == 0) return NO_INIT;
1261    return mTrack->channelCount();
1262}
1263
1264ssize_t MediaPlayerService::AudioOutput::frameSize() const
1265{
1266    if (mTrack == 0) return NO_INIT;
1267    return mTrack->frameSize();
1268}
1269
1270uint32_t MediaPlayerService::AudioOutput::latency () const
1271{
1272    return mLatency;
1273}
1274
1275float MediaPlayerService::AudioOutput::msecsPerFrame() const
1276{
1277    return mMsecsPerFrame;
1278}
1279
1280status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position)
1281{
1282    if (mTrack == 0) return NO_INIT;
1283    return mTrack->getPosition(position);
1284}
1285
1286status_t MediaPlayerService::AudioOutput::open(
1287        uint32_t sampleRate, int channelCount, int format, int bufferCount,
1288        AudioCallback cb, void *cookie)
1289{
1290    mCallback = cb;
1291    mCallbackCookie = cookie;
1292
1293    // Check argument "bufferCount" against the mininum buffer count
1294    if (bufferCount < mMinBufferCount) {
1295        LOGD("bufferCount (%d) is too small and increased to %d", bufferCount, mMinBufferCount);
1296        bufferCount = mMinBufferCount;
1297
1298    }
1299    LOGV("open(%u, %d, %d, %d, %d)", sampleRate, channelCount, format, bufferCount,mSessionId);
1300    if (mTrack) close();
1301    int afSampleRate;
1302    int afFrameCount;
1303    int frameCount;
1304
1305    if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1306        return NO_INIT;
1307    }
1308    if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1309        return NO_INIT;
1310    }
1311
1312    frameCount = (sampleRate*afFrameCount*bufferCount)/afSampleRate;
1313
1314    AudioTrack *t;
1315    if (mCallback != NULL) {
1316        t = new AudioTrack(
1317                mStreamType,
1318                sampleRate,
1319                format,
1320                (channelCount == 2) ? AudioSystem::CHANNEL_OUT_STEREO : AudioSystem::CHANNEL_OUT_MONO,
1321                frameCount,
1322                0 /* flags */,
1323                CallbackWrapper,
1324                this,
1325                0,
1326                mSessionId);
1327    } else {
1328        t = new AudioTrack(
1329                mStreamType,
1330                sampleRate,
1331                format,
1332                (channelCount == 2) ? AudioSystem::CHANNEL_OUT_STEREO : AudioSystem::CHANNEL_OUT_MONO,
1333                frameCount,
1334                0,
1335                NULL,
1336                NULL,
1337                0,
1338                mSessionId);
1339    }
1340
1341    if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1342        LOGE("Unable to create audio track");
1343        delete t;
1344        return NO_INIT;
1345    }
1346
1347    LOGV("setVolume");
1348    t->setVolume(mLeftVolume, mRightVolume);
1349
1350    mMsecsPerFrame = 1.e3 / (float) sampleRate;
1351    mLatency = t->latency();
1352    mTrack = t;
1353
1354    t->setAuxEffectSendLevel(mSendLevel);
1355    return t->attachAuxEffect(mAuxEffectId);;
1356}
1357
1358void MediaPlayerService::AudioOutput::start()
1359{
1360    LOGV("start");
1361    if (mTrack) {
1362        mTrack->setVolume(mLeftVolume, mRightVolume);
1363        mTrack->setAuxEffectSendLevel(mSendLevel);
1364        mTrack->start();
1365    }
1366}
1367
1368
1369
1370ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size)
1371{
1372    LOG_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
1373
1374    //LOGV("write(%p, %u)", buffer, size);
1375    if (mTrack) {
1376        ssize_t ret = mTrack->write(buffer, size);
1377        return ret;
1378    }
1379    return NO_INIT;
1380}
1381
1382void MediaPlayerService::AudioOutput::stop()
1383{
1384    LOGV("stop");
1385    if (mTrack) mTrack->stop();
1386}
1387
1388void MediaPlayerService::AudioOutput::flush()
1389{
1390    LOGV("flush");
1391    if (mTrack) mTrack->flush();
1392}
1393
1394void MediaPlayerService::AudioOutput::pause()
1395{
1396    LOGV("pause");
1397    if (mTrack) mTrack->pause();
1398}
1399
1400void MediaPlayerService::AudioOutput::close()
1401{
1402    LOGV("close");
1403    delete mTrack;
1404    mTrack = 0;
1405}
1406
1407void MediaPlayerService::AudioOutput::setVolume(float left, float right)
1408{
1409    LOGV("setVolume(%f, %f)", left, right);
1410    mLeftVolume = left;
1411    mRightVolume = right;
1412    if (mTrack) {
1413        mTrack->setVolume(left, right);
1414    }
1415}
1416
1417status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
1418{
1419    LOGV("setAuxEffectSendLevel(%f)", level);
1420    mSendLevel = level;
1421    if (mTrack) {
1422        return mTrack->setAuxEffectSendLevel(level);
1423    }
1424    return NO_ERROR;
1425}
1426
1427status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
1428{
1429    LOGV("attachAuxEffect(%d)", effectId);
1430    mAuxEffectId = effectId;
1431    if (mTrack) {
1432        return mTrack->attachAuxEffect(effectId);
1433    }
1434    return NO_ERROR;
1435}
1436
1437// static
1438void MediaPlayerService::AudioOutput::CallbackWrapper(
1439        int event, void *cookie, void *info) {
1440    //LOGV("callbackwrapper");
1441    if (event != AudioTrack::EVENT_MORE_DATA) {
1442        return;
1443    }
1444
1445    AudioOutput *me = (AudioOutput *)cookie;
1446    AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
1447
1448    size_t actualSize = (*me->mCallback)(
1449            me, buffer->raw, buffer->size, me->mCallbackCookie);
1450
1451    buffer->size = actualSize;
1452
1453}
1454
1455int MediaPlayerService::AudioOutput::getSessionId()
1456{
1457    return mSessionId;
1458}
1459
1460#undef LOG_TAG
1461#define LOG_TAG "AudioCache"
1462MediaPlayerService::AudioCache::AudioCache(const char* name) :
1463    mChannelCount(0), mFrameCount(1024), mSampleRate(0), mSize(0),
1464    mError(NO_ERROR), mCommandComplete(false)
1465{
1466    // create ashmem heap
1467    mHeap = new MemoryHeapBase(kDefaultHeapSize, 0, name);
1468}
1469
1470uint32_t MediaPlayerService::AudioCache::latency () const
1471{
1472    return 0;
1473}
1474
1475float MediaPlayerService::AudioCache::msecsPerFrame() const
1476{
1477    return mMsecsPerFrame;
1478}
1479
1480status_t MediaPlayerService::AudioCache::getPosition(uint32_t *position)
1481{
1482    if (position == 0) return BAD_VALUE;
1483    *position = mSize;
1484    return NO_ERROR;
1485}
1486
1487////////////////////////////////////////////////////////////////////////////////
1488
1489struct CallbackThread : public Thread {
1490    CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
1491                   MediaPlayerBase::AudioSink::AudioCallback cb,
1492                   void *cookie);
1493
1494protected:
1495    virtual ~CallbackThread();
1496
1497    virtual bool threadLoop();
1498
1499private:
1500    wp<MediaPlayerBase::AudioSink> mSink;
1501    MediaPlayerBase::AudioSink::AudioCallback mCallback;
1502    void *mCookie;
1503    void *mBuffer;
1504    size_t mBufferSize;
1505
1506    CallbackThread(const CallbackThread &);
1507    CallbackThread &operator=(const CallbackThread &);
1508};
1509
1510CallbackThread::CallbackThread(
1511        const wp<MediaPlayerBase::AudioSink> &sink,
1512        MediaPlayerBase::AudioSink::AudioCallback cb,
1513        void *cookie)
1514    : mSink(sink),
1515      mCallback(cb),
1516      mCookie(cookie),
1517      mBuffer(NULL),
1518      mBufferSize(0) {
1519}
1520
1521CallbackThread::~CallbackThread() {
1522    if (mBuffer) {
1523        free(mBuffer);
1524        mBuffer = NULL;
1525    }
1526}
1527
1528bool CallbackThread::threadLoop() {
1529    sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
1530    if (sink == NULL) {
1531        return false;
1532    }
1533
1534    if (mBuffer == NULL) {
1535        mBufferSize = sink->bufferSize();
1536        mBuffer = malloc(mBufferSize);
1537    }
1538
1539    size_t actualSize =
1540        (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie);
1541
1542    if (actualSize > 0) {
1543        sink->write(mBuffer, actualSize);
1544    }
1545
1546    return true;
1547}
1548
1549////////////////////////////////////////////////////////////////////////////////
1550
1551status_t MediaPlayerService::AudioCache::open(
1552        uint32_t sampleRate, int channelCount, int format, int bufferCount,
1553        AudioCallback cb, void *cookie)
1554{
1555    LOGV("open(%u, %d, %d, %d)", sampleRate, channelCount, format, bufferCount);
1556    if (mHeap->getHeapID() < 0) {
1557        return NO_INIT;
1558    }
1559
1560    mSampleRate = sampleRate;
1561    mChannelCount = (uint16_t)channelCount;
1562    mFormat = (uint16_t)format;
1563    mMsecsPerFrame = 1.e3 / (float) sampleRate;
1564
1565    if (cb != NULL) {
1566        mCallbackThread = new CallbackThread(this, cb, cookie);
1567    }
1568    return NO_ERROR;
1569}
1570
1571void MediaPlayerService::AudioCache::start() {
1572    if (mCallbackThread != NULL) {
1573        mCallbackThread->run("AudioCache callback");
1574    }
1575}
1576
1577void MediaPlayerService::AudioCache::stop() {
1578    if (mCallbackThread != NULL) {
1579        mCallbackThread->requestExitAndWait();
1580    }
1581}
1582
1583ssize_t MediaPlayerService::AudioCache::write(const void* buffer, size_t size)
1584{
1585    LOGV("write(%p, %u)", buffer, size);
1586    if ((buffer == 0) || (size == 0)) return size;
1587
1588    uint8_t* p = static_cast<uint8_t*>(mHeap->getBase());
1589    if (p == NULL) return NO_INIT;
1590    p += mSize;
1591    LOGV("memcpy(%p, %p, %u)", p, buffer, size);
1592    if (mSize + size > mHeap->getSize()) {
1593        LOGE("Heap size overflow! req size: %d, max size: %d", (mSize + size), mHeap->getSize());
1594        size = mHeap->getSize() - mSize;
1595    }
1596    memcpy(p, buffer, size);
1597    mSize += size;
1598    return size;
1599}
1600
1601// call with lock held
1602status_t MediaPlayerService::AudioCache::wait()
1603{
1604    Mutex::Autolock lock(mLock);
1605    while (!mCommandComplete) {
1606        mSignal.wait(mLock);
1607    }
1608    mCommandComplete = false;
1609
1610    if (mError == NO_ERROR) {
1611        LOGV("wait - success");
1612    } else {
1613        LOGV("wait - error");
1614    }
1615    return mError;
1616}
1617
1618void MediaPlayerService::AudioCache::notify(void* cookie, int msg, int ext1, int ext2)
1619{
1620    LOGV("notify(%p, %d, %d, %d)", cookie, msg, ext1, ext2);
1621    AudioCache* p = static_cast<AudioCache*>(cookie);
1622
1623    // ignore buffering messages
1624    switch (msg)
1625    {
1626    case MEDIA_ERROR:
1627        LOGE("Error %d, %d occurred", ext1, ext2);
1628        p->mError = ext1;
1629        break;
1630    case MEDIA_PREPARED:
1631        LOGV("prepared");
1632        break;
1633    case MEDIA_PLAYBACK_COMPLETE:
1634        LOGV("playback complete");
1635        break;
1636    default:
1637        LOGV("ignored");
1638        return;
1639    }
1640
1641    // wake up thread
1642    Mutex::Autolock lock(p->mLock);
1643    p->mCommandComplete = true;
1644    p->mSignal.signal();
1645}
1646
1647int MediaPlayerService::AudioCache::getSessionId()
1648{
1649    return 0;
1650}
1651
1652void MediaPlayerService::addBatteryData(uint32_t params)
1653{
1654    Mutex::Autolock lock(mLock);
1655
1656    int32_t time = systemTime() / 1000000L;
1657
1658    // change audio output devices. This notification comes from AudioFlinger
1659    if ((params & kBatteryDataSpeakerOn)
1660            || (params & kBatteryDataOtherAudioDeviceOn)) {
1661
1662        int deviceOn[NUM_AUDIO_DEVICES];
1663        for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1664            deviceOn[i] = 0;
1665        }
1666
1667        if ((params & kBatteryDataSpeakerOn)
1668                && (params & kBatteryDataOtherAudioDeviceOn)) {
1669            deviceOn[SPEAKER_AND_OTHER] = 1;
1670        } else if (params & kBatteryDataSpeakerOn) {
1671            deviceOn[SPEAKER] = 1;
1672        } else {
1673            deviceOn[OTHER_AUDIO_DEVICE] = 1;
1674        }
1675
1676        for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1677            if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
1678
1679                if (mBatteryAudio.refCount > 0) { // if playing audio
1680                    if (!deviceOn[i]) {
1681                        mBatteryAudio.lastTime[i] += time;
1682                        mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
1683                        mBatteryAudio.lastTime[i] = 0;
1684                    } else {
1685                        mBatteryAudio.lastTime[i] = 0 - time;
1686                    }
1687                }
1688
1689                mBatteryAudio.deviceOn[i] = deviceOn[i];
1690            }
1691        }
1692        return;
1693    }
1694
1695    // an sudio stream is started
1696    if (params & kBatteryDataAudioFlingerStart) {
1697        // record the start time only if currently no other audio
1698        // is being played
1699        if (mBatteryAudio.refCount == 0) {
1700            for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1701                if (mBatteryAudio.deviceOn[i]) {
1702                    mBatteryAudio.lastTime[i] -= time;
1703                }
1704            }
1705        }
1706
1707        mBatteryAudio.refCount ++;
1708        return;
1709
1710    } else if (params & kBatteryDataAudioFlingerStop) {
1711        if (mBatteryAudio.refCount <= 0) {
1712            LOGW("Battery track warning: refCount is <= 0");
1713            return;
1714        }
1715
1716        // record the stop time only if currently this is the only
1717        // audio being played
1718        if (mBatteryAudio.refCount == 1) {
1719            for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1720                if (mBatteryAudio.deviceOn[i]) {
1721                    mBatteryAudio.lastTime[i] += time;
1722                    mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
1723                    mBatteryAudio.lastTime[i] = 0;
1724                }
1725            }
1726        }
1727
1728        mBatteryAudio.refCount --;
1729        return;
1730    }
1731
1732    int uid = IPCThreadState::self()->getCallingUid();
1733    if (uid == AID_MEDIA) {
1734        return;
1735    }
1736    int index = mBatteryData.indexOfKey(uid);
1737
1738    if (index < 0) { // create a new entry for this UID
1739        BatteryUsageInfo info;
1740        info.audioTotalTime = 0;
1741        info.videoTotalTime = 0;
1742        info.audioLastTime = 0;
1743        info.videoLastTime = 0;
1744        info.refCount = 0;
1745
1746        if (mBatteryData.add(uid, info) == NO_MEMORY) {
1747            LOGE("Battery track error: no memory for new app");
1748            return;
1749        }
1750    }
1751
1752    BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
1753
1754    if (params & kBatteryDataCodecStarted) {
1755        if (params & kBatteryDataTrackAudio) {
1756            info.audioLastTime -= time;
1757            info.refCount ++;
1758        }
1759        if (params & kBatteryDataTrackVideo) {
1760            info.videoLastTime -= time;
1761            info.refCount ++;
1762        }
1763    } else {
1764        if (info.refCount == 0) {
1765            LOGW("Battery track warning: refCount is already 0");
1766            return;
1767        } else if (info.refCount < 0) {
1768            LOGE("Battery track error: refCount < 0");
1769            mBatteryData.removeItem(uid);
1770            return;
1771        }
1772
1773        if (params & kBatteryDataTrackAudio) {
1774            info.audioLastTime += time;
1775            info.refCount --;
1776        }
1777        if (params & kBatteryDataTrackVideo) {
1778            info.videoLastTime += time;
1779            info.refCount --;
1780        }
1781
1782        // no stream is being played by this UID
1783        if (info.refCount == 0) {
1784            info.audioTotalTime += info.audioLastTime;
1785            info.audioLastTime = 0;
1786            info.videoTotalTime += info.videoLastTime;
1787            info.videoLastTime = 0;
1788        }
1789    }
1790}
1791
1792status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
1793    Mutex::Autolock lock(mLock);
1794
1795    // audio output devices usage
1796    int32_t time = systemTime() / 1000000L; //in ms
1797    int32_t totalTime;
1798
1799    for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1800        totalTime = mBatteryAudio.totalTime[i];
1801
1802        if (mBatteryAudio.deviceOn[i]
1803            && (mBatteryAudio.lastTime[i] != 0)) {
1804                int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
1805                totalTime += tmpTime;
1806        }
1807
1808        reply->writeInt32(totalTime);
1809        // reset the total time
1810        mBatteryAudio.totalTime[i] = 0;
1811   }
1812
1813    // codec usage
1814    BatteryUsageInfo info;
1815    int size = mBatteryData.size();
1816
1817    reply->writeInt32(size);
1818    int i = 0;
1819
1820    while (i < size) {
1821        info = mBatteryData.valueAt(i);
1822
1823        reply->writeInt32(mBatteryData.keyAt(i)); //UID
1824        reply->writeInt32(info.audioTotalTime);
1825        reply->writeInt32(info.videoTotalTime);
1826
1827        info.audioTotalTime = 0;
1828        info.videoTotalTime = 0;
1829
1830        // remove the UID entry where no stream is being played
1831        if (info.refCount <= 0) {
1832            mBatteryData.removeItemsAt(i);
1833            size --;
1834            i --;
1835        }
1836        i++;
1837    }
1838    return NO_ERROR;
1839}
1840} // namespace android
1841