MediaPlayerService.cpp revision b483c4724846c0b8d4e82afcbb7c17f671bae81c
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            || !strncasecmp("https://", url, 8)) {
615        size_t len = strlen(url);
616        if (len >= 5 && !strcasecmp(".m3u8", &url[len - 5])) {
617            return NU_PLAYER;
618        }
619
620        if (strstr(url,"m3u8")) {
621            return NU_PLAYER;
622        }
623    }
624
625    // use MidiFile for MIDI extensions
626    int lenURL = strlen(url);
627    for (int i = 0; i < NELEM(FILE_EXTS); ++i) {
628        int len = strlen(FILE_EXTS[i].extension);
629        int start = lenURL - len;
630        if (start > 0) {
631            if (!strncasecmp(url + start, FILE_EXTS[i].extension, len)) {
632                return FILE_EXTS[i].playertype;
633            }
634        }
635    }
636
637    return getDefaultPlayerType();
638}
639
640static sp<MediaPlayerBase> createPlayer(player_type playerType, void* cookie,
641        notify_callback_f notifyFunc)
642{
643    sp<MediaPlayerBase> p;
644    switch (playerType) {
645        case SONIVOX_PLAYER:
646            LOGV(" create MidiFile");
647            p = new MidiFile();
648            break;
649        case STAGEFRIGHT_PLAYER:
650            LOGV(" create StagefrightPlayer");
651            p = new StagefrightPlayer;
652            break;
653        case NU_PLAYER:
654            LOGV(" create NuPlayer");
655            p = new NuPlayerDriver;
656            break;
657        case TEST_PLAYER:
658            LOGV("Create Test Player stub");
659            p = new TestPlayerStub();
660            break;
661        default:
662            LOGE("Unknown player type: %d", playerType);
663            return NULL;
664    }
665    if (p != NULL) {
666        if (p->initCheck() == NO_ERROR) {
667            p->setNotifyCallback(cookie, notifyFunc);
668        } else {
669            p.clear();
670        }
671    }
672    if (p == NULL) {
673        LOGE("Failed to create player object");
674    }
675    return p;
676}
677
678sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
679{
680    // determine if we have the right player type
681    sp<MediaPlayerBase> p = mPlayer;
682    if ((p != NULL) && (p->playerType() != playerType)) {
683        LOGV("delete player");
684        p.clear();
685    }
686    if (p == NULL) {
687        p = android::createPlayer(playerType, this, notify);
688    }
689    return p;
690}
691
692status_t MediaPlayerService::Client::setDataSource(
693        const char *url, const KeyedVector<String8, String8> *headers)
694{
695    LOGV("setDataSource(%s)", url);
696    if (url == NULL)
697        return UNKNOWN_ERROR;
698
699    if (strncmp(url, "content://", 10) == 0) {
700        // get a filedescriptor for the content Uri and
701        // pass it to the setDataSource(fd) method
702
703        String16 url16(url);
704        int fd = android::openContentProviderFile(url16);
705        if (fd < 0)
706        {
707            LOGE("Couldn't open fd for %s", url);
708            return UNKNOWN_ERROR;
709        }
710        setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
711        close(fd);
712        return mStatus;
713    } else {
714        player_type playerType = getPlayerType(url);
715        LOGV("player type = %d", playerType);
716
717        // create the right type of player
718        sp<MediaPlayerBase> p = createPlayer(playerType);
719        if (p == NULL) return NO_INIT;
720
721        if (!p->hardwareOutput()) {
722            mAudioOutput = new AudioOutput(mAudioSessionId);
723            static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
724        }
725
726        // now set data source
727        LOGV(" setDataSource");
728        mStatus = p->setDataSource(url, headers);
729        if (mStatus == NO_ERROR) {
730            mPlayer = p;
731        } else {
732            LOGE("  error: %d", mStatus);
733        }
734        return mStatus;
735    }
736}
737
738status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
739{
740    LOGV("setDataSource fd=%d, offset=%lld, length=%lld", fd, offset, length);
741    struct stat sb;
742    int ret = fstat(fd, &sb);
743    if (ret != 0) {
744        LOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
745        return UNKNOWN_ERROR;
746    }
747
748    LOGV("st_dev  = %llu", sb.st_dev);
749    LOGV("st_mode = %u", sb.st_mode);
750    LOGV("st_uid  = %lu", sb.st_uid);
751    LOGV("st_gid  = %lu", sb.st_gid);
752    LOGV("st_size = %llu", sb.st_size);
753
754    if (offset >= sb.st_size) {
755        LOGE("offset error");
756        ::close(fd);
757        return UNKNOWN_ERROR;
758    }
759    if (offset + length > sb.st_size) {
760        length = sb.st_size - offset;
761        LOGV("calculated length = %lld", length);
762    }
763
764    player_type playerType = getPlayerType(fd, offset, length);
765    LOGV("player type = %d", playerType);
766
767    // create the right type of player
768    sp<MediaPlayerBase> p = createPlayer(playerType);
769    if (p == NULL) return NO_INIT;
770
771    if (!p->hardwareOutput()) {
772        mAudioOutput = new AudioOutput(mAudioSessionId);
773        static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
774    }
775
776    // now set data source
777    mStatus = p->setDataSource(fd, offset, length);
778    if (mStatus == NO_ERROR) mPlayer = p;
779    return mStatus;
780}
781
782status_t MediaPlayerService::Client::setDataSource(
783        const sp<IStreamSource> &source) {
784    // create the right type of player
785    sp<MediaPlayerBase> p = createPlayer(NU_PLAYER);
786
787    if (p == NULL) {
788        return NO_INIT;
789    }
790
791    if (!p->hardwareOutput()) {
792        mAudioOutput = new AudioOutput(mAudioSessionId);
793        static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
794    }
795
796    // now set data source
797    mStatus = p->setDataSource(source);
798
799    if (mStatus == OK) {
800        mPlayer = p;
801    }
802
803    return mStatus;
804}
805
806status_t MediaPlayerService::Client::setVideoSurface(const sp<Surface>& surface)
807{
808    LOGV("[%d] setVideoSurface(%p)", mConnId, surface.get());
809    sp<MediaPlayerBase> p = getPlayer();
810    if (p == 0) return UNKNOWN_ERROR;
811    return p->setVideoSurface(surface);
812}
813
814status_t MediaPlayerService::Client::setVideoSurfaceTexture(
815        const sp<ISurfaceTexture>& surfaceTexture)
816{
817    LOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, surfaceTexture.get());
818    sp<MediaPlayerBase> p = getPlayer();
819    if (p == 0) return UNKNOWN_ERROR;
820    return p->setVideoSurfaceTexture(surfaceTexture);
821}
822
823status_t MediaPlayerService::Client::invoke(const Parcel& request,
824                                            Parcel *reply)
825{
826    sp<MediaPlayerBase> p = getPlayer();
827    if (p == NULL) return UNKNOWN_ERROR;
828    return p->invoke(request, reply);
829}
830
831// This call doesn't need to access the native player.
832status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
833{
834    status_t status;
835    media::Metadata::Filter allow, drop;
836
837    if (unmarshallFilter(filter, &allow, &status) &&
838        unmarshallFilter(filter, &drop, &status)) {
839        Mutex::Autolock lock(mLock);
840
841        mMetadataAllow = allow;
842        mMetadataDrop = drop;
843    }
844    return status;
845}
846
847status_t MediaPlayerService::Client::getMetadata(
848        bool update_only, bool apply_filter, Parcel *reply)
849{
850    sp<MediaPlayerBase> player = getPlayer();
851    if (player == 0) return UNKNOWN_ERROR;
852
853    status_t status;
854    // Placeholder for the return code, updated by the caller.
855    reply->writeInt32(-1);
856
857    media::Metadata::Filter ids;
858
859    // We don't block notifications while we fetch the data. We clear
860    // mMetadataUpdated first so we don't lose notifications happening
861    // during the rest of this call.
862    {
863        Mutex::Autolock lock(mLock);
864        if (update_only) {
865            ids = mMetadataUpdated;
866        }
867        mMetadataUpdated.clear();
868    }
869
870    media::Metadata metadata(reply);
871
872    metadata.appendHeader();
873    status = player->getMetadata(ids, reply);
874
875    if (status != OK) {
876        metadata.resetParcel();
877        LOGE("getMetadata failed %d", status);
878        return status;
879    }
880
881    // FIXME: Implement filtering on the result. Not critical since
882    // filtering takes place on the update notifications already. This
883    // would be when all the metadata are fetch and a filter is set.
884
885    // Everything is fine, update the metadata length.
886    metadata.updateLength();
887    return OK;
888}
889
890status_t MediaPlayerService::Client::prepareAsync()
891{
892    LOGV("[%d] prepareAsync", mConnId);
893    sp<MediaPlayerBase> p = getPlayer();
894    if (p == 0) return UNKNOWN_ERROR;
895    status_t ret = p->prepareAsync();
896#if CALLBACK_ANTAGONIZER
897    LOGD("start Antagonizer");
898    if (ret == NO_ERROR) mAntagonizer->start();
899#endif
900    return ret;
901}
902
903status_t MediaPlayerService::Client::start()
904{
905    LOGV("[%d] start", mConnId);
906    sp<MediaPlayerBase> p = getPlayer();
907    if (p == 0) return UNKNOWN_ERROR;
908    p->setLooping(mLoop);
909    return p->start();
910}
911
912status_t MediaPlayerService::Client::stop()
913{
914    LOGV("[%d] stop", mConnId);
915    sp<MediaPlayerBase> p = getPlayer();
916    if (p == 0) return UNKNOWN_ERROR;
917    return p->stop();
918}
919
920status_t MediaPlayerService::Client::pause()
921{
922    LOGV("[%d] pause", mConnId);
923    sp<MediaPlayerBase> p = getPlayer();
924    if (p == 0) return UNKNOWN_ERROR;
925    return p->pause();
926}
927
928status_t MediaPlayerService::Client::isPlaying(bool* state)
929{
930    *state = false;
931    sp<MediaPlayerBase> p = getPlayer();
932    if (p == 0) return UNKNOWN_ERROR;
933    *state = p->isPlaying();
934    LOGV("[%d] isPlaying: %d", mConnId, *state);
935    return NO_ERROR;
936}
937
938status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
939{
940    LOGV("getCurrentPosition");
941    sp<MediaPlayerBase> p = getPlayer();
942    if (p == 0) return UNKNOWN_ERROR;
943    status_t ret = p->getCurrentPosition(msec);
944    if (ret == NO_ERROR) {
945        LOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
946    } else {
947        LOGE("getCurrentPosition returned %d", ret);
948    }
949    return ret;
950}
951
952status_t MediaPlayerService::Client::getDuration(int *msec)
953{
954    LOGV("getDuration");
955    sp<MediaPlayerBase> p = getPlayer();
956    if (p == 0) return UNKNOWN_ERROR;
957    status_t ret = p->getDuration(msec);
958    if (ret == NO_ERROR) {
959        LOGV("[%d] getDuration = %d", mConnId, *msec);
960    } else {
961        LOGE("getDuration returned %d", ret);
962    }
963    return ret;
964}
965
966status_t MediaPlayerService::Client::seekTo(int msec)
967{
968    LOGV("[%d] seekTo(%d)", mConnId, msec);
969    sp<MediaPlayerBase> p = getPlayer();
970    if (p == 0) return UNKNOWN_ERROR;
971    return p->seekTo(msec);
972}
973
974status_t MediaPlayerService::Client::reset()
975{
976    LOGV("[%d] reset", mConnId);
977    sp<MediaPlayerBase> p = getPlayer();
978    if (p == 0) return UNKNOWN_ERROR;
979    return p->reset();
980}
981
982status_t MediaPlayerService::Client::setAudioStreamType(int type)
983{
984    LOGV("[%d] setAudioStreamType(%d)", mConnId, type);
985    // TODO: for hardware output, call player instead
986    Mutex::Autolock l(mLock);
987    if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
988    return NO_ERROR;
989}
990
991status_t MediaPlayerService::Client::setLooping(int loop)
992{
993    LOGV("[%d] setLooping(%d)", mConnId, loop);
994    mLoop = loop;
995    sp<MediaPlayerBase> p = getPlayer();
996    if (p != 0) return p->setLooping(loop);
997    return NO_ERROR;
998}
999
1000status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1001{
1002    LOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
1003    // TODO: for hardware output, call player instead
1004    Mutex::Autolock l(mLock);
1005    if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1006    return NO_ERROR;
1007}
1008
1009status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1010{
1011    LOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
1012    Mutex::Autolock l(mLock);
1013    if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1014    return NO_ERROR;
1015}
1016
1017status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1018{
1019    LOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
1020    Mutex::Autolock l(mLock);
1021    if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1022    return NO_ERROR;
1023}
1024
1025void MediaPlayerService::Client::notify(
1026        void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
1027{
1028    Client* client = static_cast<Client*>(cookie);
1029
1030    if (MEDIA_INFO == msg &&
1031        MEDIA_INFO_METADATA_UPDATE == ext1) {
1032        const media::Metadata::Type metadata_type = ext2;
1033
1034        if(client->shouldDropMetadata(metadata_type)) {
1035            return;
1036        }
1037
1038        // Update the list of metadata that have changed. getMetadata
1039        // also access mMetadataUpdated and clears it.
1040        client->addNewMetadataUpdate(metadata_type);
1041    }
1042    LOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
1043    client->mClient->notify(msg, ext1, ext2, obj);
1044}
1045
1046
1047bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
1048{
1049    Mutex::Autolock lock(mLock);
1050
1051    if (findMetadata(mMetadataDrop, code)) {
1052        return true;
1053    }
1054
1055    if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
1056        return false;
1057    } else {
1058        return true;
1059    }
1060}
1061
1062
1063void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
1064    Mutex::Autolock lock(mLock);
1065    if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1066        mMetadataUpdated.add(metadata_type);
1067    }
1068}
1069
1070#if CALLBACK_ANTAGONIZER
1071const int Antagonizer::interval = 10000; // 10 msecs
1072
1073Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1074    mExit(false), mActive(false), mClient(client), mCb(cb)
1075{
1076    createThread(callbackThread, this);
1077}
1078
1079void Antagonizer::kill()
1080{
1081    Mutex::Autolock _l(mLock);
1082    mActive = false;
1083    mExit = true;
1084    mCondition.wait(mLock);
1085}
1086
1087int Antagonizer::callbackThread(void* user)
1088{
1089    LOGD("Antagonizer started");
1090    Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1091    while (!p->mExit) {
1092        if (p->mActive) {
1093            LOGV("send event");
1094            p->mCb(p->mClient, 0, 0, 0);
1095        }
1096        usleep(interval);
1097    }
1098    Mutex::Autolock _l(p->mLock);
1099    p->mCondition.signal();
1100    LOGD("Antagonizer stopped");
1101    return 0;
1102}
1103#endif
1104
1105static size_t kDefaultHeapSize = 1024 * 1024; // 1MB
1106
1107sp<IMemory> MediaPlayerService::decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1108{
1109    LOGV("decode(%s)", url);
1110    sp<MemoryBase> mem;
1111    sp<MediaPlayerBase> player;
1112
1113    // Protect our precious, precious DRMd ringtones by only allowing
1114    // decoding of http, but not filesystem paths or content Uris.
1115    // If the application wants to decode those, it should open a
1116    // filedescriptor for them and use that.
1117    if (url != NULL && strncmp(url, "http://", 7) != 0) {
1118        LOGD("Can't decode %s by path, use filedescriptor instead", url);
1119        return mem;
1120    }
1121
1122    player_type playerType = getPlayerType(url);
1123    LOGV("player type = %d", playerType);
1124
1125    // create the right type of player
1126    sp<AudioCache> cache = new AudioCache(url);
1127    player = android::createPlayer(playerType, cache.get(), cache->notify);
1128    if (player == NULL) goto Exit;
1129    if (player->hardwareOutput()) goto Exit;
1130
1131    static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1132
1133    // set data source
1134    if (player->setDataSource(url) != NO_ERROR) goto Exit;
1135
1136    LOGV("prepare");
1137    player->prepareAsync();
1138
1139    LOGV("wait for prepare");
1140    if (cache->wait() != NO_ERROR) goto Exit;
1141
1142    LOGV("start");
1143    player->start();
1144
1145    LOGV("wait for playback complete");
1146    if (cache->wait() != NO_ERROR) goto Exit;
1147
1148    mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1149    *pSampleRate = cache->sampleRate();
1150    *pNumChannels = cache->channelCount();
1151    *pFormat = cache->format();
1152    LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1153
1154Exit:
1155    if (player != 0) player->reset();
1156    return mem;
1157}
1158
1159sp<IMemory> MediaPlayerService::decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1160{
1161    LOGV("decode(%d, %lld, %lld)", fd, offset, length);
1162    sp<MemoryBase> mem;
1163    sp<MediaPlayerBase> player;
1164
1165    player_type playerType = getPlayerType(fd, offset, length);
1166    LOGV("player type = %d", playerType);
1167
1168    // create the right type of player
1169    sp<AudioCache> cache = new AudioCache("decode_fd");
1170    player = android::createPlayer(playerType, cache.get(), cache->notify);
1171    if (player == NULL) goto Exit;
1172    if (player->hardwareOutput()) goto Exit;
1173
1174    static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1175
1176    // set data source
1177    if (player->setDataSource(fd, offset, length) != NO_ERROR) goto Exit;
1178
1179    LOGV("prepare");
1180    player->prepareAsync();
1181
1182    LOGV("wait for prepare");
1183    if (cache->wait() != NO_ERROR) goto Exit;
1184
1185    LOGV("start");
1186    player->start();
1187
1188    LOGV("wait for playback complete");
1189    if (cache->wait() != NO_ERROR) goto Exit;
1190
1191    mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1192    *pSampleRate = cache->sampleRate();
1193    *pNumChannels = cache->channelCount();
1194    *pFormat = cache->format();
1195    LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1196
1197Exit:
1198    if (player != 0) player->reset();
1199    ::close(fd);
1200    return mem;
1201}
1202
1203
1204#undef LOG_TAG
1205#define LOG_TAG "AudioSink"
1206MediaPlayerService::AudioOutput::AudioOutput(int sessionId)
1207    : mCallback(NULL),
1208      mCallbackCookie(NULL),
1209      mSessionId(sessionId) {
1210    LOGV("AudioOutput(%d)", sessionId);
1211    mTrack = 0;
1212    mStreamType = AudioSystem::MUSIC;
1213    mLeftVolume = 1.0;
1214    mRightVolume = 1.0;
1215    mLatency = 0;
1216    mMsecsPerFrame = 0;
1217    mAuxEffectId = 0;
1218    mSendLevel = 0.0;
1219    setMinBufferCount();
1220}
1221
1222MediaPlayerService::AudioOutput::~AudioOutput()
1223{
1224    close();
1225}
1226
1227void MediaPlayerService::AudioOutput::setMinBufferCount()
1228{
1229    char value[PROPERTY_VALUE_MAX];
1230    if (property_get("ro.kernel.qemu", value, 0)) {
1231        mIsOnEmulator = true;
1232        mMinBufferCount = 12;  // to prevent systematic buffer underrun for emulator
1233    }
1234}
1235
1236bool MediaPlayerService::AudioOutput::isOnEmulator()
1237{
1238    setMinBufferCount();
1239    return mIsOnEmulator;
1240}
1241
1242int MediaPlayerService::AudioOutput::getMinBufferCount()
1243{
1244    setMinBufferCount();
1245    return mMinBufferCount;
1246}
1247
1248ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1249{
1250    if (mTrack == 0) return NO_INIT;
1251    return mTrack->frameCount() * frameSize();
1252}
1253
1254ssize_t MediaPlayerService::AudioOutput::frameCount() const
1255{
1256    if (mTrack == 0) return NO_INIT;
1257    return mTrack->frameCount();
1258}
1259
1260ssize_t MediaPlayerService::AudioOutput::channelCount() const
1261{
1262    if (mTrack == 0) return NO_INIT;
1263    return mTrack->channelCount();
1264}
1265
1266ssize_t MediaPlayerService::AudioOutput::frameSize() const
1267{
1268    if (mTrack == 0) return NO_INIT;
1269    return mTrack->frameSize();
1270}
1271
1272uint32_t MediaPlayerService::AudioOutput::latency () const
1273{
1274    return mLatency;
1275}
1276
1277float MediaPlayerService::AudioOutput::msecsPerFrame() const
1278{
1279    return mMsecsPerFrame;
1280}
1281
1282status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position)
1283{
1284    if (mTrack == 0) return NO_INIT;
1285    return mTrack->getPosition(position);
1286}
1287
1288status_t MediaPlayerService::AudioOutput::open(
1289        uint32_t sampleRate, int channelCount, int format, int bufferCount,
1290        AudioCallback cb, void *cookie)
1291{
1292    mCallback = cb;
1293    mCallbackCookie = cookie;
1294
1295    // Check argument "bufferCount" against the mininum buffer count
1296    if (bufferCount < mMinBufferCount) {
1297        LOGD("bufferCount (%d) is too small and increased to %d", bufferCount, mMinBufferCount);
1298        bufferCount = mMinBufferCount;
1299
1300    }
1301    LOGV("open(%u, %d, %d, %d, %d)", sampleRate, channelCount, format, bufferCount,mSessionId);
1302    if (mTrack) close();
1303    int afSampleRate;
1304    int afFrameCount;
1305    int frameCount;
1306
1307    if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1308        return NO_INIT;
1309    }
1310    if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1311        return NO_INIT;
1312    }
1313
1314    frameCount = (sampleRate*afFrameCount*bufferCount)/afSampleRate;
1315
1316    AudioTrack *t;
1317    if (mCallback != NULL) {
1318        t = new AudioTrack(
1319                mStreamType,
1320                sampleRate,
1321                format,
1322                (channelCount == 2) ? AudioSystem::CHANNEL_OUT_STEREO : AudioSystem::CHANNEL_OUT_MONO,
1323                frameCount,
1324                0 /* flags */,
1325                CallbackWrapper,
1326                this,
1327                0,
1328                mSessionId);
1329    } else {
1330        t = new AudioTrack(
1331                mStreamType,
1332                sampleRate,
1333                format,
1334                (channelCount == 2) ? AudioSystem::CHANNEL_OUT_STEREO : AudioSystem::CHANNEL_OUT_MONO,
1335                frameCount,
1336                0,
1337                NULL,
1338                NULL,
1339                0,
1340                mSessionId);
1341    }
1342
1343    if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1344        LOGE("Unable to create audio track");
1345        delete t;
1346        return NO_INIT;
1347    }
1348
1349    LOGV("setVolume");
1350    t->setVolume(mLeftVolume, mRightVolume);
1351
1352    mMsecsPerFrame = 1.e3 / (float) sampleRate;
1353    mLatency = t->latency();
1354    mTrack = t;
1355
1356    t->setAuxEffectSendLevel(mSendLevel);
1357    return t->attachAuxEffect(mAuxEffectId);;
1358}
1359
1360void MediaPlayerService::AudioOutput::start()
1361{
1362    LOGV("start");
1363    if (mTrack) {
1364        mTrack->setVolume(mLeftVolume, mRightVolume);
1365        mTrack->setAuxEffectSendLevel(mSendLevel);
1366        mTrack->start();
1367    }
1368}
1369
1370
1371
1372ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size)
1373{
1374    LOG_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
1375
1376    //LOGV("write(%p, %u)", buffer, size);
1377    if (mTrack) {
1378        ssize_t ret = mTrack->write(buffer, size);
1379        return ret;
1380    }
1381    return NO_INIT;
1382}
1383
1384void MediaPlayerService::AudioOutput::stop()
1385{
1386    LOGV("stop");
1387    if (mTrack) mTrack->stop();
1388}
1389
1390void MediaPlayerService::AudioOutput::flush()
1391{
1392    LOGV("flush");
1393    if (mTrack) mTrack->flush();
1394}
1395
1396void MediaPlayerService::AudioOutput::pause()
1397{
1398    LOGV("pause");
1399    if (mTrack) mTrack->pause();
1400}
1401
1402void MediaPlayerService::AudioOutput::close()
1403{
1404    LOGV("close");
1405    delete mTrack;
1406    mTrack = 0;
1407}
1408
1409void MediaPlayerService::AudioOutput::setVolume(float left, float right)
1410{
1411    LOGV("setVolume(%f, %f)", left, right);
1412    mLeftVolume = left;
1413    mRightVolume = right;
1414    if (mTrack) {
1415        mTrack->setVolume(left, right);
1416    }
1417}
1418
1419status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
1420{
1421    LOGV("setAuxEffectSendLevel(%f)", level);
1422    mSendLevel = level;
1423    if (mTrack) {
1424        return mTrack->setAuxEffectSendLevel(level);
1425    }
1426    return NO_ERROR;
1427}
1428
1429status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
1430{
1431    LOGV("attachAuxEffect(%d)", effectId);
1432    mAuxEffectId = effectId;
1433    if (mTrack) {
1434        return mTrack->attachAuxEffect(effectId);
1435    }
1436    return NO_ERROR;
1437}
1438
1439// static
1440void MediaPlayerService::AudioOutput::CallbackWrapper(
1441        int event, void *cookie, void *info) {
1442    //LOGV("callbackwrapper");
1443    if (event != AudioTrack::EVENT_MORE_DATA) {
1444        return;
1445    }
1446
1447    AudioOutput *me = (AudioOutput *)cookie;
1448    AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
1449
1450    size_t actualSize = (*me->mCallback)(
1451            me, buffer->raw, buffer->size, me->mCallbackCookie);
1452
1453    if (actualSize == 0 && buffer->size > 0) {
1454        // We've reached EOS but the audio track is not stopped yet,
1455        // keep playing silence.
1456
1457        memset(buffer->raw, 0, buffer->size);
1458        actualSize = buffer->size;
1459    }
1460
1461    buffer->size = actualSize;
1462}
1463
1464int MediaPlayerService::AudioOutput::getSessionId()
1465{
1466    return mSessionId;
1467}
1468
1469#undef LOG_TAG
1470#define LOG_TAG "AudioCache"
1471MediaPlayerService::AudioCache::AudioCache(const char* name) :
1472    mChannelCount(0), mFrameCount(1024), mSampleRate(0), mSize(0),
1473    mError(NO_ERROR), mCommandComplete(false)
1474{
1475    // create ashmem heap
1476    mHeap = new MemoryHeapBase(kDefaultHeapSize, 0, name);
1477}
1478
1479uint32_t MediaPlayerService::AudioCache::latency () const
1480{
1481    return 0;
1482}
1483
1484float MediaPlayerService::AudioCache::msecsPerFrame() const
1485{
1486    return mMsecsPerFrame;
1487}
1488
1489status_t MediaPlayerService::AudioCache::getPosition(uint32_t *position)
1490{
1491    if (position == 0) return BAD_VALUE;
1492    *position = mSize;
1493    return NO_ERROR;
1494}
1495
1496////////////////////////////////////////////////////////////////////////////////
1497
1498struct CallbackThread : public Thread {
1499    CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
1500                   MediaPlayerBase::AudioSink::AudioCallback cb,
1501                   void *cookie);
1502
1503protected:
1504    virtual ~CallbackThread();
1505
1506    virtual bool threadLoop();
1507
1508private:
1509    wp<MediaPlayerBase::AudioSink> mSink;
1510    MediaPlayerBase::AudioSink::AudioCallback mCallback;
1511    void *mCookie;
1512    void *mBuffer;
1513    size_t mBufferSize;
1514
1515    CallbackThread(const CallbackThread &);
1516    CallbackThread &operator=(const CallbackThread &);
1517};
1518
1519CallbackThread::CallbackThread(
1520        const wp<MediaPlayerBase::AudioSink> &sink,
1521        MediaPlayerBase::AudioSink::AudioCallback cb,
1522        void *cookie)
1523    : mSink(sink),
1524      mCallback(cb),
1525      mCookie(cookie),
1526      mBuffer(NULL),
1527      mBufferSize(0) {
1528}
1529
1530CallbackThread::~CallbackThread() {
1531    if (mBuffer) {
1532        free(mBuffer);
1533        mBuffer = NULL;
1534    }
1535}
1536
1537bool CallbackThread::threadLoop() {
1538    sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
1539    if (sink == NULL) {
1540        return false;
1541    }
1542
1543    if (mBuffer == NULL) {
1544        mBufferSize = sink->bufferSize();
1545        mBuffer = malloc(mBufferSize);
1546    }
1547
1548    size_t actualSize =
1549        (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie);
1550
1551    if (actualSize > 0) {
1552        sink->write(mBuffer, actualSize);
1553    }
1554
1555    return true;
1556}
1557
1558////////////////////////////////////////////////////////////////////////////////
1559
1560status_t MediaPlayerService::AudioCache::open(
1561        uint32_t sampleRate, int channelCount, int format, int bufferCount,
1562        AudioCallback cb, void *cookie)
1563{
1564    LOGV("open(%u, %d, %d, %d)", sampleRate, channelCount, format, bufferCount);
1565    if (mHeap->getHeapID() < 0) {
1566        return NO_INIT;
1567    }
1568
1569    mSampleRate = sampleRate;
1570    mChannelCount = (uint16_t)channelCount;
1571    mFormat = (uint16_t)format;
1572    mMsecsPerFrame = 1.e3 / (float) sampleRate;
1573
1574    if (cb != NULL) {
1575        mCallbackThread = new CallbackThread(this, cb, cookie);
1576    }
1577    return NO_ERROR;
1578}
1579
1580void MediaPlayerService::AudioCache::start() {
1581    if (mCallbackThread != NULL) {
1582        mCallbackThread->run("AudioCache callback");
1583    }
1584}
1585
1586void MediaPlayerService::AudioCache::stop() {
1587    if (mCallbackThread != NULL) {
1588        mCallbackThread->requestExitAndWait();
1589    }
1590}
1591
1592ssize_t MediaPlayerService::AudioCache::write(const void* buffer, size_t size)
1593{
1594    LOGV("write(%p, %u)", buffer, size);
1595    if ((buffer == 0) || (size == 0)) return size;
1596
1597    uint8_t* p = static_cast<uint8_t*>(mHeap->getBase());
1598    if (p == NULL) return NO_INIT;
1599    p += mSize;
1600    LOGV("memcpy(%p, %p, %u)", p, buffer, size);
1601    if (mSize + size > mHeap->getSize()) {
1602        LOGE("Heap size overflow! req size: %d, max size: %d", (mSize + size), mHeap->getSize());
1603        size = mHeap->getSize() - mSize;
1604    }
1605    memcpy(p, buffer, size);
1606    mSize += size;
1607    return size;
1608}
1609
1610// call with lock held
1611status_t MediaPlayerService::AudioCache::wait()
1612{
1613    Mutex::Autolock lock(mLock);
1614    while (!mCommandComplete) {
1615        mSignal.wait(mLock);
1616    }
1617    mCommandComplete = false;
1618
1619    if (mError == NO_ERROR) {
1620        LOGV("wait - success");
1621    } else {
1622        LOGV("wait - error");
1623    }
1624    return mError;
1625}
1626
1627void MediaPlayerService::AudioCache::notify(
1628        void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
1629{
1630    LOGV("notify(%p, %d, %d, %d)", cookie, msg, ext1, ext2);
1631    AudioCache* p = static_cast<AudioCache*>(cookie);
1632
1633    // ignore buffering messages
1634    switch (msg)
1635    {
1636    case MEDIA_ERROR:
1637        LOGE("Error %d, %d occurred", ext1, ext2);
1638        p->mError = ext1;
1639        break;
1640    case MEDIA_PREPARED:
1641        LOGV("prepared");
1642        break;
1643    case MEDIA_PLAYBACK_COMPLETE:
1644        LOGV("playback complete");
1645        break;
1646    default:
1647        LOGV("ignored");
1648        return;
1649    }
1650
1651    // wake up thread
1652    Mutex::Autolock lock(p->mLock);
1653    p->mCommandComplete = true;
1654    p->mSignal.signal();
1655}
1656
1657int MediaPlayerService::AudioCache::getSessionId()
1658{
1659    return 0;
1660}
1661
1662void MediaPlayerService::addBatteryData(uint32_t params)
1663{
1664    Mutex::Autolock lock(mLock);
1665
1666    int32_t time = systemTime() / 1000000L;
1667
1668    // change audio output devices. This notification comes from AudioFlinger
1669    if ((params & kBatteryDataSpeakerOn)
1670            || (params & kBatteryDataOtherAudioDeviceOn)) {
1671
1672        int deviceOn[NUM_AUDIO_DEVICES];
1673        for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1674            deviceOn[i] = 0;
1675        }
1676
1677        if ((params & kBatteryDataSpeakerOn)
1678                && (params & kBatteryDataOtherAudioDeviceOn)) {
1679            deviceOn[SPEAKER_AND_OTHER] = 1;
1680        } else if (params & kBatteryDataSpeakerOn) {
1681            deviceOn[SPEAKER] = 1;
1682        } else {
1683            deviceOn[OTHER_AUDIO_DEVICE] = 1;
1684        }
1685
1686        for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1687            if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
1688
1689                if (mBatteryAudio.refCount > 0) { // if playing audio
1690                    if (!deviceOn[i]) {
1691                        mBatteryAudio.lastTime[i] += time;
1692                        mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
1693                        mBatteryAudio.lastTime[i] = 0;
1694                    } else {
1695                        mBatteryAudio.lastTime[i] = 0 - time;
1696                    }
1697                }
1698
1699                mBatteryAudio.deviceOn[i] = deviceOn[i];
1700            }
1701        }
1702        return;
1703    }
1704
1705    // an sudio stream is started
1706    if (params & kBatteryDataAudioFlingerStart) {
1707        // record the start time only if currently no other audio
1708        // is being played
1709        if (mBatteryAudio.refCount == 0) {
1710            for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1711                if (mBatteryAudio.deviceOn[i]) {
1712                    mBatteryAudio.lastTime[i] -= time;
1713                }
1714            }
1715        }
1716
1717        mBatteryAudio.refCount ++;
1718        return;
1719
1720    } else if (params & kBatteryDataAudioFlingerStop) {
1721        if (mBatteryAudio.refCount <= 0) {
1722            LOGW("Battery track warning: refCount is <= 0");
1723            return;
1724        }
1725
1726        // record the stop time only if currently this is the only
1727        // audio being played
1728        if (mBatteryAudio.refCount == 1) {
1729            for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1730                if (mBatteryAudio.deviceOn[i]) {
1731                    mBatteryAudio.lastTime[i] += time;
1732                    mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
1733                    mBatteryAudio.lastTime[i] = 0;
1734                }
1735            }
1736        }
1737
1738        mBatteryAudio.refCount --;
1739        return;
1740    }
1741
1742    int uid = IPCThreadState::self()->getCallingUid();
1743    if (uid == AID_MEDIA) {
1744        return;
1745    }
1746    int index = mBatteryData.indexOfKey(uid);
1747
1748    if (index < 0) { // create a new entry for this UID
1749        BatteryUsageInfo info;
1750        info.audioTotalTime = 0;
1751        info.videoTotalTime = 0;
1752        info.audioLastTime = 0;
1753        info.videoLastTime = 0;
1754        info.refCount = 0;
1755
1756        if (mBatteryData.add(uid, info) == NO_MEMORY) {
1757            LOGE("Battery track error: no memory for new app");
1758            return;
1759        }
1760    }
1761
1762    BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
1763
1764    if (params & kBatteryDataCodecStarted) {
1765        if (params & kBatteryDataTrackAudio) {
1766            info.audioLastTime -= time;
1767            info.refCount ++;
1768        }
1769        if (params & kBatteryDataTrackVideo) {
1770            info.videoLastTime -= time;
1771            info.refCount ++;
1772        }
1773    } else {
1774        if (info.refCount == 0) {
1775            LOGW("Battery track warning: refCount is already 0");
1776            return;
1777        } else if (info.refCount < 0) {
1778            LOGE("Battery track error: refCount < 0");
1779            mBatteryData.removeItem(uid);
1780            return;
1781        }
1782
1783        if (params & kBatteryDataTrackAudio) {
1784            info.audioLastTime += time;
1785            info.refCount --;
1786        }
1787        if (params & kBatteryDataTrackVideo) {
1788            info.videoLastTime += time;
1789            info.refCount --;
1790        }
1791
1792        // no stream is being played by this UID
1793        if (info.refCount == 0) {
1794            info.audioTotalTime += info.audioLastTime;
1795            info.audioLastTime = 0;
1796            info.videoTotalTime += info.videoLastTime;
1797            info.videoLastTime = 0;
1798        }
1799    }
1800}
1801
1802status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
1803    Mutex::Autolock lock(mLock);
1804
1805    // audio output devices usage
1806    int32_t time = systemTime() / 1000000L; //in ms
1807    int32_t totalTime;
1808
1809    for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1810        totalTime = mBatteryAudio.totalTime[i];
1811
1812        if (mBatteryAudio.deviceOn[i]
1813            && (mBatteryAudio.lastTime[i] != 0)) {
1814                int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
1815                totalTime += tmpTime;
1816        }
1817
1818        reply->writeInt32(totalTime);
1819        // reset the total time
1820        mBatteryAudio.totalTime[i] = 0;
1821   }
1822
1823    // codec usage
1824    BatteryUsageInfo info;
1825    int size = mBatteryData.size();
1826
1827    reply->writeInt32(size);
1828    int i = 0;
1829
1830    while (i < size) {
1831        info = mBatteryData.valueAt(i);
1832
1833        reply->writeInt32(mBatteryData.keyAt(i)); //UID
1834        reply->writeInt32(info.audioTotalTime);
1835        reply->writeInt32(info.videoTotalTime);
1836
1837        info.audioTotalTime = 0;
1838        info.videoTotalTime = 0;
1839
1840        // remove the UID entry where no stream is being played
1841        if (info.refCount <= 0) {
1842            mBatteryData.removeItemsAt(i);
1843            size --;
1844            i --;
1845        }
1846        i++;
1847    }
1848    return NO_ERROR;
1849}
1850} // namespace android
1851