MediaPlayerService.cpp revision 51c1e0e86a0ad95bf3d890a9a2f51e54b8ef9444
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(void* cookie, int msg, int ext1, int ext2)
1026{
1027    Client* client = static_cast<Client*>(cookie);
1028
1029    if (MEDIA_INFO == msg &&
1030        MEDIA_INFO_METADATA_UPDATE == ext1) {
1031        const media::Metadata::Type metadata_type = ext2;
1032
1033        if(client->shouldDropMetadata(metadata_type)) {
1034            return;
1035        }
1036
1037        // Update the list of metadata that have changed. getMetadata
1038        // also access mMetadataUpdated and clears it.
1039        client->addNewMetadataUpdate(metadata_type);
1040    }
1041    LOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
1042    client->mClient->notify(msg, ext1, ext2);
1043}
1044
1045
1046bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
1047{
1048    Mutex::Autolock lock(mLock);
1049
1050    if (findMetadata(mMetadataDrop, code)) {
1051        return true;
1052    }
1053
1054    if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
1055        return false;
1056    } else {
1057        return true;
1058    }
1059}
1060
1061
1062void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
1063    Mutex::Autolock lock(mLock);
1064    if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1065        mMetadataUpdated.add(metadata_type);
1066    }
1067}
1068
1069#if CALLBACK_ANTAGONIZER
1070const int Antagonizer::interval = 10000; // 10 msecs
1071
1072Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1073    mExit(false), mActive(false), mClient(client), mCb(cb)
1074{
1075    createThread(callbackThread, this);
1076}
1077
1078void Antagonizer::kill()
1079{
1080    Mutex::Autolock _l(mLock);
1081    mActive = false;
1082    mExit = true;
1083    mCondition.wait(mLock);
1084}
1085
1086int Antagonizer::callbackThread(void* user)
1087{
1088    LOGD("Antagonizer started");
1089    Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1090    while (!p->mExit) {
1091        if (p->mActive) {
1092            LOGV("send event");
1093            p->mCb(p->mClient, 0, 0, 0);
1094        }
1095        usleep(interval);
1096    }
1097    Mutex::Autolock _l(p->mLock);
1098    p->mCondition.signal();
1099    LOGD("Antagonizer stopped");
1100    return 0;
1101}
1102#endif
1103
1104static size_t kDefaultHeapSize = 1024 * 1024; // 1MB
1105
1106sp<IMemory> MediaPlayerService::decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1107{
1108    LOGV("decode(%s)", url);
1109    sp<MemoryBase> mem;
1110    sp<MediaPlayerBase> player;
1111
1112    // Protect our precious, precious DRMd ringtones by only allowing
1113    // decoding of http, but not filesystem paths or content Uris.
1114    // If the application wants to decode those, it should open a
1115    // filedescriptor for them and use that.
1116    if (url != NULL && strncmp(url, "http://", 7) != 0) {
1117        LOGD("Can't decode %s by path, use filedescriptor instead", url);
1118        return mem;
1119    }
1120
1121    player_type playerType = getPlayerType(url);
1122    LOGV("player type = %d", playerType);
1123
1124    // create the right type of player
1125    sp<AudioCache> cache = new AudioCache(url);
1126    player = android::createPlayer(playerType, cache.get(), cache->notify);
1127    if (player == NULL) goto Exit;
1128    if (player->hardwareOutput()) goto Exit;
1129
1130    static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1131
1132    // set data source
1133    if (player->setDataSource(url) != NO_ERROR) goto Exit;
1134
1135    LOGV("prepare");
1136    player->prepareAsync();
1137
1138    LOGV("wait for prepare");
1139    if (cache->wait() != NO_ERROR) goto Exit;
1140
1141    LOGV("start");
1142    player->start();
1143
1144    LOGV("wait for playback complete");
1145    if (cache->wait() != NO_ERROR) goto Exit;
1146
1147    mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1148    *pSampleRate = cache->sampleRate();
1149    *pNumChannels = cache->channelCount();
1150    *pFormat = cache->format();
1151    LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1152
1153Exit:
1154    if (player != 0) player->reset();
1155    return mem;
1156}
1157
1158sp<IMemory> MediaPlayerService::decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1159{
1160    LOGV("decode(%d, %lld, %lld)", fd, offset, length);
1161    sp<MemoryBase> mem;
1162    sp<MediaPlayerBase> player;
1163
1164    player_type playerType = getPlayerType(fd, offset, length);
1165    LOGV("player type = %d", playerType);
1166
1167    // create the right type of player
1168    sp<AudioCache> cache = new AudioCache("decode_fd");
1169    player = android::createPlayer(playerType, cache.get(), cache->notify);
1170    if (player == NULL) goto Exit;
1171    if (player->hardwareOutput()) goto Exit;
1172
1173    static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1174
1175    // set data source
1176    if (player->setDataSource(fd, offset, length) != NO_ERROR) goto Exit;
1177
1178    LOGV("prepare");
1179    player->prepareAsync();
1180
1181    LOGV("wait for prepare");
1182    if (cache->wait() != NO_ERROR) goto Exit;
1183
1184    LOGV("start");
1185    player->start();
1186
1187    LOGV("wait for playback complete");
1188    if (cache->wait() != NO_ERROR) goto Exit;
1189
1190    mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1191    *pSampleRate = cache->sampleRate();
1192    *pNumChannels = cache->channelCount();
1193    *pFormat = cache->format();
1194    LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1195
1196Exit:
1197    if (player != 0) player->reset();
1198    ::close(fd);
1199    return mem;
1200}
1201
1202
1203#undef LOG_TAG
1204#define LOG_TAG "AudioSink"
1205MediaPlayerService::AudioOutput::AudioOutput(int sessionId)
1206    : mCallback(NULL),
1207      mCallbackCookie(NULL),
1208      mSessionId(sessionId) {
1209    LOGV("AudioOutput(%d)", sessionId);
1210    mTrack = 0;
1211    mStreamType = AudioSystem::MUSIC;
1212    mLeftVolume = 1.0;
1213    mRightVolume = 1.0;
1214    mLatency = 0;
1215    mMsecsPerFrame = 0;
1216    mAuxEffectId = 0;
1217    mSendLevel = 0.0;
1218    setMinBufferCount();
1219}
1220
1221MediaPlayerService::AudioOutput::~AudioOutput()
1222{
1223    close();
1224}
1225
1226void MediaPlayerService::AudioOutput::setMinBufferCount()
1227{
1228    char value[PROPERTY_VALUE_MAX];
1229    if (property_get("ro.kernel.qemu", value, 0)) {
1230        mIsOnEmulator = true;
1231        mMinBufferCount = 12;  // to prevent systematic buffer underrun for emulator
1232    }
1233}
1234
1235bool MediaPlayerService::AudioOutput::isOnEmulator()
1236{
1237    setMinBufferCount();
1238    return mIsOnEmulator;
1239}
1240
1241int MediaPlayerService::AudioOutput::getMinBufferCount()
1242{
1243    setMinBufferCount();
1244    return mMinBufferCount;
1245}
1246
1247ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1248{
1249    if (mTrack == 0) return NO_INIT;
1250    return mTrack->frameCount() * frameSize();
1251}
1252
1253ssize_t MediaPlayerService::AudioOutput::frameCount() const
1254{
1255    if (mTrack == 0) return NO_INIT;
1256    return mTrack->frameCount();
1257}
1258
1259ssize_t MediaPlayerService::AudioOutput::channelCount() const
1260{
1261    if (mTrack == 0) return NO_INIT;
1262    return mTrack->channelCount();
1263}
1264
1265ssize_t MediaPlayerService::AudioOutput::frameSize() const
1266{
1267    if (mTrack == 0) return NO_INIT;
1268    return mTrack->frameSize();
1269}
1270
1271uint32_t MediaPlayerService::AudioOutput::latency () const
1272{
1273    return mLatency;
1274}
1275
1276float MediaPlayerService::AudioOutput::msecsPerFrame() const
1277{
1278    return mMsecsPerFrame;
1279}
1280
1281status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position)
1282{
1283    if (mTrack == 0) return NO_INIT;
1284    return mTrack->getPosition(position);
1285}
1286
1287status_t MediaPlayerService::AudioOutput::open(
1288        uint32_t sampleRate, int channelCount, int format, int bufferCount,
1289        AudioCallback cb, void *cookie)
1290{
1291    mCallback = cb;
1292    mCallbackCookie = cookie;
1293
1294    // Check argument "bufferCount" against the mininum buffer count
1295    if (bufferCount < mMinBufferCount) {
1296        LOGD("bufferCount (%d) is too small and increased to %d", bufferCount, mMinBufferCount);
1297        bufferCount = mMinBufferCount;
1298
1299    }
1300    LOGV("open(%u, %d, %d, %d, %d)", sampleRate, channelCount, format, bufferCount,mSessionId);
1301    if (mTrack) close();
1302    int afSampleRate;
1303    int afFrameCount;
1304    int frameCount;
1305
1306    if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1307        return NO_INIT;
1308    }
1309    if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1310        return NO_INIT;
1311    }
1312
1313    frameCount = (sampleRate*afFrameCount*bufferCount)/afSampleRate;
1314
1315    AudioTrack *t;
1316    if (mCallback != NULL) {
1317        t = new AudioTrack(
1318                mStreamType,
1319                sampleRate,
1320                format,
1321                (channelCount == 2) ? AudioSystem::CHANNEL_OUT_STEREO : AudioSystem::CHANNEL_OUT_MONO,
1322                frameCount,
1323                0 /* flags */,
1324                CallbackWrapper,
1325                this,
1326                0,
1327                mSessionId);
1328    } else {
1329        t = new AudioTrack(
1330                mStreamType,
1331                sampleRate,
1332                format,
1333                (channelCount == 2) ? AudioSystem::CHANNEL_OUT_STEREO : AudioSystem::CHANNEL_OUT_MONO,
1334                frameCount,
1335                0,
1336                NULL,
1337                NULL,
1338                0,
1339                mSessionId);
1340    }
1341
1342    if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1343        LOGE("Unable to create audio track");
1344        delete t;
1345        return NO_INIT;
1346    }
1347
1348    LOGV("setVolume");
1349    t->setVolume(mLeftVolume, mRightVolume);
1350
1351    mMsecsPerFrame = 1.e3 / (float) sampleRate;
1352    mLatency = t->latency();
1353    mTrack = t;
1354
1355    t->setAuxEffectSendLevel(mSendLevel);
1356    return t->attachAuxEffect(mAuxEffectId);;
1357}
1358
1359void MediaPlayerService::AudioOutput::start()
1360{
1361    LOGV("start");
1362    if (mTrack) {
1363        mTrack->setVolume(mLeftVolume, mRightVolume);
1364        mTrack->setAuxEffectSendLevel(mSendLevel);
1365        mTrack->start();
1366    }
1367}
1368
1369
1370
1371ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size)
1372{
1373    LOG_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
1374
1375    //LOGV("write(%p, %u)", buffer, size);
1376    if (mTrack) {
1377        ssize_t ret = mTrack->write(buffer, size);
1378        return ret;
1379    }
1380    return NO_INIT;
1381}
1382
1383void MediaPlayerService::AudioOutput::stop()
1384{
1385    LOGV("stop");
1386    if (mTrack) mTrack->stop();
1387}
1388
1389void MediaPlayerService::AudioOutput::flush()
1390{
1391    LOGV("flush");
1392    if (mTrack) mTrack->flush();
1393}
1394
1395void MediaPlayerService::AudioOutput::pause()
1396{
1397    LOGV("pause");
1398    if (mTrack) mTrack->pause();
1399}
1400
1401void MediaPlayerService::AudioOutput::close()
1402{
1403    LOGV("close");
1404    delete mTrack;
1405    mTrack = 0;
1406}
1407
1408void MediaPlayerService::AudioOutput::setVolume(float left, float right)
1409{
1410    LOGV("setVolume(%f, %f)", left, right);
1411    mLeftVolume = left;
1412    mRightVolume = right;
1413    if (mTrack) {
1414        mTrack->setVolume(left, right);
1415    }
1416}
1417
1418status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
1419{
1420    LOGV("setAuxEffectSendLevel(%f)", level);
1421    mSendLevel = level;
1422    if (mTrack) {
1423        return mTrack->setAuxEffectSendLevel(level);
1424    }
1425    return NO_ERROR;
1426}
1427
1428status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
1429{
1430    LOGV("attachAuxEffect(%d)", effectId);
1431    mAuxEffectId = effectId;
1432    if (mTrack) {
1433        return mTrack->attachAuxEffect(effectId);
1434    }
1435    return NO_ERROR;
1436}
1437
1438// static
1439void MediaPlayerService::AudioOutput::CallbackWrapper(
1440        int event, void *cookie, void *info) {
1441    //LOGV("callbackwrapper");
1442    if (event != AudioTrack::EVENT_MORE_DATA) {
1443        return;
1444    }
1445
1446    AudioOutput *me = (AudioOutput *)cookie;
1447    AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
1448
1449    size_t actualSize = (*me->mCallback)(
1450            me, buffer->raw, buffer->size, me->mCallbackCookie);
1451
1452    if (actualSize == 0 && buffer->size > 0) {
1453        // We've reached EOS but the audio track is not stopped yet,
1454        // keep playing silence.
1455
1456        memset(buffer->raw, 0, buffer->size);
1457        actualSize = buffer->size;
1458    }
1459
1460    buffer->size = actualSize;
1461}
1462
1463int MediaPlayerService::AudioOutput::getSessionId()
1464{
1465    return mSessionId;
1466}
1467
1468#undef LOG_TAG
1469#define LOG_TAG "AudioCache"
1470MediaPlayerService::AudioCache::AudioCache(const char* name) :
1471    mChannelCount(0), mFrameCount(1024), mSampleRate(0), mSize(0),
1472    mError(NO_ERROR), mCommandComplete(false)
1473{
1474    // create ashmem heap
1475    mHeap = new MemoryHeapBase(kDefaultHeapSize, 0, name);
1476}
1477
1478uint32_t MediaPlayerService::AudioCache::latency () const
1479{
1480    return 0;
1481}
1482
1483float MediaPlayerService::AudioCache::msecsPerFrame() const
1484{
1485    return mMsecsPerFrame;
1486}
1487
1488status_t MediaPlayerService::AudioCache::getPosition(uint32_t *position)
1489{
1490    if (position == 0) return BAD_VALUE;
1491    *position = mSize;
1492    return NO_ERROR;
1493}
1494
1495////////////////////////////////////////////////////////////////////////////////
1496
1497struct CallbackThread : public Thread {
1498    CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
1499                   MediaPlayerBase::AudioSink::AudioCallback cb,
1500                   void *cookie);
1501
1502protected:
1503    virtual ~CallbackThread();
1504
1505    virtual bool threadLoop();
1506
1507private:
1508    wp<MediaPlayerBase::AudioSink> mSink;
1509    MediaPlayerBase::AudioSink::AudioCallback mCallback;
1510    void *mCookie;
1511    void *mBuffer;
1512    size_t mBufferSize;
1513
1514    CallbackThread(const CallbackThread &);
1515    CallbackThread &operator=(const CallbackThread &);
1516};
1517
1518CallbackThread::CallbackThread(
1519        const wp<MediaPlayerBase::AudioSink> &sink,
1520        MediaPlayerBase::AudioSink::AudioCallback cb,
1521        void *cookie)
1522    : mSink(sink),
1523      mCallback(cb),
1524      mCookie(cookie),
1525      mBuffer(NULL),
1526      mBufferSize(0) {
1527}
1528
1529CallbackThread::~CallbackThread() {
1530    if (mBuffer) {
1531        free(mBuffer);
1532        mBuffer = NULL;
1533    }
1534}
1535
1536bool CallbackThread::threadLoop() {
1537    sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
1538    if (sink == NULL) {
1539        return false;
1540    }
1541
1542    if (mBuffer == NULL) {
1543        mBufferSize = sink->bufferSize();
1544        mBuffer = malloc(mBufferSize);
1545    }
1546
1547    size_t actualSize =
1548        (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie);
1549
1550    if (actualSize > 0) {
1551        sink->write(mBuffer, actualSize);
1552    }
1553
1554    return true;
1555}
1556
1557////////////////////////////////////////////////////////////////////////////////
1558
1559status_t MediaPlayerService::AudioCache::open(
1560        uint32_t sampleRate, int channelCount, int format, int bufferCount,
1561        AudioCallback cb, void *cookie)
1562{
1563    LOGV("open(%u, %d, %d, %d)", sampleRate, channelCount, format, bufferCount);
1564    if (mHeap->getHeapID() < 0) {
1565        return NO_INIT;
1566    }
1567
1568    mSampleRate = sampleRate;
1569    mChannelCount = (uint16_t)channelCount;
1570    mFormat = (uint16_t)format;
1571    mMsecsPerFrame = 1.e3 / (float) sampleRate;
1572
1573    if (cb != NULL) {
1574        mCallbackThread = new CallbackThread(this, cb, cookie);
1575    }
1576    return NO_ERROR;
1577}
1578
1579void MediaPlayerService::AudioCache::start() {
1580    if (mCallbackThread != NULL) {
1581        mCallbackThread->run("AudioCache callback");
1582    }
1583}
1584
1585void MediaPlayerService::AudioCache::stop() {
1586    if (mCallbackThread != NULL) {
1587        mCallbackThread->requestExitAndWait();
1588    }
1589}
1590
1591ssize_t MediaPlayerService::AudioCache::write(const void* buffer, size_t size)
1592{
1593    LOGV("write(%p, %u)", buffer, size);
1594    if ((buffer == 0) || (size == 0)) return size;
1595
1596    uint8_t* p = static_cast<uint8_t*>(mHeap->getBase());
1597    if (p == NULL) return NO_INIT;
1598    p += mSize;
1599    LOGV("memcpy(%p, %p, %u)", p, buffer, size);
1600    if (mSize + size > mHeap->getSize()) {
1601        LOGE("Heap size overflow! req size: %d, max size: %d", (mSize + size), mHeap->getSize());
1602        size = mHeap->getSize() - mSize;
1603    }
1604    memcpy(p, buffer, size);
1605    mSize += size;
1606    return size;
1607}
1608
1609// call with lock held
1610status_t MediaPlayerService::AudioCache::wait()
1611{
1612    Mutex::Autolock lock(mLock);
1613    while (!mCommandComplete) {
1614        mSignal.wait(mLock);
1615    }
1616    mCommandComplete = false;
1617
1618    if (mError == NO_ERROR) {
1619        LOGV("wait - success");
1620    } else {
1621        LOGV("wait - error");
1622    }
1623    return mError;
1624}
1625
1626void MediaPlayerService::AudioCache::notify(void* cookie, int msg, int ext1, int ext2)
1627{
1628    LOGV("notify(%p, %d, %d, %d)", cookie, msg, ext1, ext2);
1629    AudioCache* p = static_cast<AudioCache*>(cookie);
1630
1631    // ignore buffering messages
1632    switch (msg)
1633    {
1634    case MEDIA_ERROR:
1635        LOGE("Error %d, %d occurred", ext1, ext2);
1636        p->mError = ext1;
1637        break;
1638    case MEDIA_PREPARED:
1639        LOGV("prepared");
1640        break;
1641    case MEDIA_PLAYBACK_COMPLETE:
1642        LOGV("playback complete");
1643        break;
1644    default:
1645        LOGV("ignored");
1646        return;
1647    }
1648
1649    // wake up thread
1650    Mutex::Autolock lock(p->mLock);
1651    p->mCommandComplete = true;
1652    p->mSignal.signal();
1653}
1654
1655int MediaPlayerService::AudioCache::getSessionId()
1656{
1657    return 0;
1658}
1659
1660void MediaPlayerService::addBatteryData(uint32_t params)
1661{
1662    Mutex::Autolock lock(mLock);
1663
1664    int32_t time = systemTime() / 1000000L;
1665
1666    // change audio output devices. This notification comes from AudioFlinger
1667    if ((params & kBatteryDataSpeakerOn)
1668            || (params & kBatteryDataOtherAudioDeviceOn)) {
1669
1670        int deviceOn[NUM_AUDIO_DEVICES];
1671        for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1672            deviceOn[i] = 0;
1673        }
1674
1675        if ((params & kBatteryDataSpeakerOn)
1676                && (params & kBatteryDataOtherAudioDeviceOn)) {
1677            deviceOn[SPEAKER_AND_OTHER] = 1;
1678        } else if (params & kBatteryDataSpeakerOn) {
1679            deviceOn[SPEAKER] = 1;
1680        } else {
1681            deviceOn[OTHER_AUDIO_DEVICE] = 1;
1682        }
1683
1684        for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1685            if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
1686
1687                if (mBatteryAudio.refCount > 0) { // if playing audio
1688                    if (!deviceOn[i]) {
1689                        mBatteryAudio.lastTime[i] += time;
1690                        mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
1691                        mBatteryAudio.lastTime[i] = 0;
1692                    } else {
1693                        mBatteryAudio.lastTime[i] = 0 - time;
1694                    }
1695                }
1696
1697                mBatteryAudio.deviceOn[i] = deviceOn[i];
1698            }
1699        }
1700        return;
1701    }
1702
1703    // an sudio stream is started
1704    if (params & kBatteryDataAudioFlingerStart) {
1705        // record the start time only if currently no other audio
1706        // is being played
1707        if (mBatteryAudio.refCount == 0) {
1708            for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1709                if (mBatteryAudio.deviceOn[i]) {
1710                    mBatteryAudio.lastTime[i] -= time;
1711                }
1712            }
1713        }
1714
1715        mBatteryAudio.refCount ++;
1716        return;
1717
1718    } else if (params & kBatteryDataAudioFlingerStop) {
1719        if (mBatteryAudio.refCount <= 0) {
1720            LOGW("Battery track warning: refCount is <= 0");
1721            return;
1722        }
1723
1724        // record the stop time only if currently this is the only
1725        // audio being played
1726        if (mBatteryAudio.refCount == 1) {
1727            for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1728                if (mBatteryAudio.deviceOn[i]) {
1729                    mBatteryAudio.lastTime[i] += time;
1730                    mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
1731                    mBatteryAudio.lastTime[i] = 0;
1732                }
1733            }
1734        }
1735
1736        mBatteryAudio.refCount --;
1737        return;
1738    }
1739
1740    int uid = IPCThreadState::self()->getCallingUid();
1741    if (uid == AID_MEDIA) {
1742        return;
1743    }
1744    int index = mBatteryData.indexOfKey(uid);
1745
1746    if (index < 0) { // create a new entry for this UID
1747        BatteryUsageInfo info;
1748        info.audioTotalTime = 0;
1749        info.videoTotalTime = 0;
1750        info.audioLastTime = 0;
1751        info.videoLastTime = 0;
1752        info.refCount = 0;
1753
1754        if (mBatteryData.add(uid, info) == NO_MEMORY) {
1755            LOGE("Battery track error: no memory for new app");
1756            return;
1757        }
1758    }
1759
1760    BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
1761
1762    if (params & kBatteryDataCodecStarted) {
1763        if (params & kBatteryDataTrackAudio) {
1764            info.audioLastTime -= time;
1765            info.refCount ++;
1766        }
1767        if (params & kBatteryDataTrackVideo) {
1768            info.videoLastTime -= time;
1769            info.refCount ++;
1770        }
1771    } else {
1772        if (info.refCount == 0) {
1773            LOGW("Battery track warning: refCount is already 0");
1774            return;
1775        } else if (info.refCount < 0) {
1776            LOGE("Battery track error: refCount < 0");
1777            mBatteryData.removeItem(uid);
1778            return;
1779        }
1780
1781        if (params & kBatteryDataTrackAudio) {
1782            info.audioLastTime += time;
1783            info.refCount --;
1784        }
1785        if (params & kBatteryDataTrackVideo) {
1786            info.videoLastTime += time;
1787            info.refCount --;
1788        }
1789
1790        // no stream is being played by this UID
1791        if (info.refCount == 0) {
1792            info.audioTotalTime += info.audioLastTime;
1793            info.audioLastTime = 0;
1794            info.videoTotalTime += info.videoLastTime;
1795            info.videoLastTime = 0;
1796        }
1797    }
1798}
1799
1800status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
1801    Mutex::Autolock lock(mLock);
1802
1803    // audio output devices usage
1804    int32_t time = systemTime() / 1000000L; //in ms
1805    int32_t totalTime;
1806
1807    for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1808        totalTime = mBatteryAudio.totalTime[i];
1809
1810        if (mBatteryAudio.deviceOn[i]
1811            && (mBatteryAudio.lastTime[i] != 0)) {
1812                int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
1813                totalTime += tmpTime;
1814        }
1815
1816        reply->writeInt32(totalTime);
1817        // reset the total time
1818        mBatteryAudio.totalTime[i] = 0;
1819   }
1820
1821    // codec usage
1822    BatteryUsageInfo info;
1823    int size = mBatteryData.size();
1824
1825    reply->writeInt32(size);
1826    int i = 0;
1827
1828    while (i < size) {
1829        info = mBatteryData.valueAt(i);
1830
1831        reply->writeInt32(mBatteryData.keyAt(i)); //UID
1832        reply->writeInt32(info.audioTotalTime);
1833        reply->writeInt32(info.videoTotalTime);
1834
1835        info.audioTotalTime = 0;
1836        info.videoTotalTime = 0;
1837
1838        // remove the UID entry where no stream is being played
1839        if (info.refCount <= 0) {
1840            mBatteryData.removeItemsAt(i);
1841            size --;
1842            i --;
1843        }
1844        i++;
1845    }
1846    return NO_ERROR;
1847}
1848} // namespace android
1849