MediaPlayerService.cpp revision a0b1d4b161599c2bb2a47119e50c51e75bbe980e
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 <system/audio.h>
57
58#include <private/android_filesystem_config.h>
59
60#include "MediaRecorderClient.h"
61#include "MediaPlayerService.h"
62#include "MetadataRetrieverClient.h"
63
64#include "MidiFile.h"
65#include "TestPlayerStub.h"
66#include "StagefrightPlayer.h"
67#include "nuplayer/NuPlayerDriver.h"
68
69#include <OMX.h>
70
71namespace {
72using android::media::Metadata;
73using android::status_t;
74using android::OK;
75using android::BAD_VALUE;
76using android::NOT_ENOUGH_DATA;
77using android::Parcel;
78
79// Max number of entries in the filter.
80const int kMaxFilterSize = 64;  // I pulled that out of thin air.
81
82// FIXME: Move all the metadata related function in the Metadata.cpp
83
84
85// Unmarshall a filter from a Parcel.
86// Filter format in a parcel:
87//
88//  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
89// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
90// |                       number of entries (n)                   |
91// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
92// |                       metadata type 1                         |
93// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
94// |                       metadata type 2                         |
95// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
96//  ....
97// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
98// |                       metadata type n                         |
99// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
100//
101// @param p Parcel that should start with a filter.
102// @param[out] filter On exit contains the list of metadata type to be
103//                    filtered.
104// @param[out] status On exit contains the status code to be returned.
105// @return true if the parcel starts with a valid filter.
106bool unmarshallFilter(const Parcel& p,
107                      Metadata::Filter *filter,
108                      status_t *status)
109{
110    int32_t val;
111    if (p.readInt32(&val) != OK)
112    {
113        LOGE("Failed to read filter's length");
114        *status = NOT_ENOUGH_DATA;
115        return false;
116    }
117
118    if( val > kMaxFilterSize || val < 0)
119    {
120        LOGE("Invalid filter len %d", val);
121        *status = BAD_VALUE;
122        return false;
123    }
124
125    const size_t num = val;
126
127    filter->clear();
128    filter->setCapacity(num);
129
130    size_t size = num * sizeof(Metadata::Type);
131
132
133    if (p.dataAvail() < size)
134    {
135        LOGE("Filter too short expected %d but got %d", size, p.dataAvail());
136        *status = NOT_ENOUGH_DATA;
137        return false;
138    }
139
140    const Metadata::Type *data =
141            static_cast<const Metadata::Type*>(p.readInplace(size));
142
143    if (NULL == data)
144    {
145        LOGE("Filter had no data");
146        *status = BAD_VALUE;
147        return false;
148    }
149
150    // TODO: The stl impl of vector would be more efficient here
151    // because it degenerates into a memcpy on pod types. Try to
152    // replace later or use stl::set.
153    for (size_t i = 0; i < num; ++i)
154    {
155        filter->add(*data);
156        ++data;
157    }
158    *status = OK;
159    return true;
160}
161
162// @param filter Of metadata type.
163// @param val To be searched.
164// @return true if a match was found.
165bool findMetadata(const Metadata::Filter& filter, const int32_t val)
166{
167    // Deal with empty and ANY right away
168    if (filter.isEmpty()) return false;
169    if (filter[0] == Metadata::kAny) return true;
170
171    return filter.indexOf(val) >= 0;
172}
173
174}  // anonymous namespace
175
176
177namespace android {
178
179// TODO: Temp hack until we can register players
180typedef struct {
181    const char *extension;
182    const player_type playertype;
183} extmap;
184extmap FILE_EXTS [] =  {
185        {".mid", SONIVOX_PLAYER},
186        {".midi", SONIVOX_PLAYER},
187        {".smf", SONIVOX_PLAYER},
188        {".xmf", SONIVOX_PLAYER},
189        {".imy", SONIVOX_PLAYER},
190        {".rtttl", SONIVOX_PLAYER},
191        {".rtx", SONIVOX_PLAYER},
192        {".ota", SONIVOX_PLAYER},
193};
194
195// TODO: Find real cause of Audio/Video delay in PV framework and remove this workaround
196/* static */ int MediaPlayerService::AudioOutput::mMinBufferCount = 4;
197/* static */ bool MediaPlayerService::AudioOutput::mIsOnEmulator = false;
198
199void MediaPlayerService::instantiate() {
200    defaultServiceManager()->addService(
201            String16("media.player"), new MediaPlayerService());
202}
203
204MediaPlayerService::MediaPlayerService()
205{
206    LOGV("MediaPlayerService created");
207    mNextConnId = 1;
208
209    mBatteryAudio.refCount = 0;
210    for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
211        mBatteryAudio.deviceOn[i] = 0;
212        mBatteryAudio.lastTime[i] = 0;
213        mBatteryAudio.totalTime[i] = 0;
214    }
215    // speaker is on by default
216    mBatteryAudio.deviceOn[SPEAKER] = 1;
217}
218
219MediaPlayerService::~MediaPlayerService()
220{
221    LOGV("MediaPlayerService destroyed");
222}
223
224sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(pid_t pid)
225{
226    sp<MediaRecorderClient> recorder = new MediaRecorderClient(this, pid);
227    wp<MediaRecorderClient> w = recorder;
228    Mutex::Autolock lock(mLock);
229    mMediaRecorderClients.add(w);
230    LOGV("Create new media recorder client from pid %d", pid);
231    return recorder;
232}
233
234void MediaPlayerService::removeMediaRecorderClient(wp<MediaRecorderClient> client)
235{
236    Mutex::Autolock lock(mLock);
237    mMediaRecorderClients.remove(client);
238    LOGV("Delete media recorder client");
239}
240
241sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever(pid_t pid)
242{
243    sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
244    LOGV("Create new media retriever from pid %d", pid);
245    return retriever;
246}
247
248sp<IMediaPlayer> MediaPlayerService::create(
249        pid_t pid, const sp<IMediaPlayerClient>& client, const char* url,
250        const KeyedVector<String8, String8> *headers, int audioSessionId)
251{
252    int32_t connId = android_atomic_inc(&mNextConnId);
253    sp<Client> c = new Client(this, pid, connId, client, audioSessionId);
254    LOGV("Create new client(%d) from pid %d, url=%s, connId=%d, audioSessionId=%d",
255            connId, pid, url, connId, audioSessionId);
256    if (NO_ERROR != c->setDataSource(url, headers))
257    {
258        c.clear();
259        return c;
260    }
261    wp<Client> w = c;
262    Mutex::Autolock lock(mLock);
263    mClients.add(w);
264    return c;
265}
266
267sp<IMediaPlayer> MediaPlayerService::create(pid_t pid, const sp<IMediaPlayerClient>& client,
268        int fd, int64_t offset, int64_t length, int audioSessionId)
269{
270    int32_t connId = android_atomic_inc(&mNextConnId);
271    sp<Client> c = new Client(this, pid, connId, client, audioSessionId);
272    LOGV("Create new client(%d) from pid %d, fd=%d, offset=%lld, length=%lld, audioSessionId=%d",
273            connId, pid, fd, offset, length, audioSessionId);
274    if (NO_ERROR != c->setDataSource(fd, offset, length)) {
275        c.clear();
276    } else {
277        wp<Client> w = c;
278        Mutex::Autolock lock(mLock);
279        mClients.add(w);
280    }
281    ::close(fd);
282    return c;
283}
284
285sp<IMediaPlayer> MediaPlayerService::create(
286        pid_t pid, const sp<IMediaPlayerClient> &client,
287        const sp<IStreamSource> &source, int audioSessionId) {
288    int32_t connId = android_atomic_inc(&mNextConnId);
289    sp<Client> c = new Client(this, pid, connId, client, audioSessionId);
290
291    LOGV("Create new client(%d) from pid %d, audioSessionId=%d",
292         connId, pid, audioSessionId);
293
294    if (OK != c->setDataSource(source)) {
295        c.clear();
296    } else {
297        wp<Client> w = c;
298        Mutex::Autolock lock(mLock);
299        mClients.add(w);
300    }
301
302    return c;
303}
304
305sp<IOMX> MediaPlayerService::getOMX() {
306    Mutex::Autolock autoLock(mLock);
307
308    if (mOMX.get() == NULL) {
309        mOMX = new OMX;
310    }
311
312    return mOMX;
313}
314
315status_t MediaPlayerService::AudioCache::dump(int fd, const Vector<String16>& args) const
316{
317    const size_t SIZE = 256;
318    char buffer[SIZE];
319    String8 result;
320
321    result.append(" AudioCache\n");
322    if (mHeap != 0) {
323        snprintf(buffer, 255, "  heap base(%p), size(%d), flags(%d), device(%s)\n",
324                mHeap->getBase(), mHeap->getSize(), mHeap->getFlags(), mHeap->getDevice());
325        result.append(buffer);
326    }
327    snprintf(buffer, 255, "  msec per frame(%f), channel count(%d), format(%d), frame count(%ld)\n",
328            mMsecsPerFrame, mChannelCount, mFormat, mFrameCount);
329    result.append(buffer);
330    snprintf(buffer, 255, "  sample rate(%d), size(%d), error(%d), command complete(%s)\n",
331            mSampleRate, mSize, mError, mCommandComplete?"true":"false");
332    result.append(buffer);
333    ::write(fd, result.string(), result.size());
334    return NO_ERROR;
335}
336
337status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
338{
339    const size_t SIZE = 256;
340    char buffer[SIZE];
341    String8 result;
342
343    result.append(" AudioOutput\n");
344    snprintf(buffer, 255, "  stream type(%d), left - right volume(%f, %f)\n",
345            mStreamType, mLeftVolume, mRightVolume);
346    result.append(buffer);
347    snprintf(buffer, 255, "  msec per frame(%f), latency (%d)\n",
348            mMsecsPerFrame, mLatency);
349    result.append(buffer);
350    snprintf(buffer, 255, "  aux effect id(%d), send level (%f)\n",
351            mAuxEffectId, mSendLevel);
352    result.append(buffer);
353
354    ::write(fd, result.string(), result.size());
355    if (mTrack != 0) {
356        mTrack->dump(fd, args);
357    }
358    return NO_ERROR;
359}
360
361status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args) const
362{
363    const size_t SIZE = 256;
364    char buffer[SIZE];
365    String8 result;
366    result.append(" Client\n");
367    snprintf(buffer, 255, "  pid(%d), connId(%d), status(%d), looping(%s)\n",
368            mPid, mConnId, mStatus, mLoop?"true": "false");
369    result.append(buffer);
370    write(fd, result.string(), result.size());
371    if (mPlayer != NULL) {
372        mPlayer->dump(fd, args);
373    }
374    if (mAudioOutput != 0) {
375        mAudioOutput->dump(fd, args);
376    }
377    write(fd, "\n", 1);
378    return NO_ERROR;
379}
380
381status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
382{
383    const size_t SIZE = 256;
384    char buffer[SIZE];
385    String8 result;
386    if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
387        snprintf(buffer, SIZE, "Permission Denial: "
388                "can't dump MediaPlayerService from pid=%d, uid=%d\n",
389                IPCThreadState::self()->getCallingPid(),
390                IPCThreadState::self()->getCallingUid());
391        result.append(buffer);
392    } else {
393        Mutex::Autolock lock(mLock);
394        for (int i = 0, n = mClients.size(); i < n; ++i) {
395            sp<Client> c = mClients[i].promote();
396            if (c != 0) c->dump(fd, args);
397        }
398        if (mMediaRecorderClients.size() == 0) {
399                result.append(" No media recorder client\n\n");
400        } else {
401            for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
402                sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
403                snprintf(buffer, 255, " MediaRecorderClient pid(%d)\n", c->mPid);
404                result.append(buffer);
405                write(fd, result.string(), result.size());
406                result = "\n";
407                c->dump(fd, args);
408            }
409        }
410
411        result.append(" Files opened and/or mapped:\n");
412        snprintf(buffer, SIZE, "/proc/%d/maps", gettid());
413        FILE *f = fopen(buffer, "r");
414        if (f) {
415            while (!feof(f)) {
416                fgets(buffer, SIZE, f);
417                if (strstr(buffer, " /mnt/sdcard/") ||
418                    strstr(buffer, " /system/sounds/") ||
419                    strstr(buffer, " /data/") ||
420                    strstr(buffer, " /system/media/")) {
421                    result.append("  ");
422                    result.append(buffer);
423                }
424            }
425            fclose(f);
426        } else {
427            result.append("couldn't open ");
428            result.append(buffer);
429            result.append("\n");
430        }
431
432        snprintf(buffer, SIZE, "/proc/%d/fd", gettid());
433        DIR *d = opendir(buffer);
434        if (d) {
435            struct dirent *ent;
436            while((ent = readdir(d)) != NULL) {
437                if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
438                    snprintf(buffer, SIZE, "/proc/%d/fd/%s", gettid(), ent->d_name);
439                    struct stat s;
440                    if (lstat(buffer, &s) == 0) {
441                        if ((s.st_mode & S_IFMT) == S_IFLNK) {
442                            char linkto[256];
443                            int len = readlink(buffer, linkto, sizeof(linkto));
444                            if(len > 0) {
445                                if(len > 255) {
446                                    linkto[252] = '.';
447                                    linkto[253] = '.';
448                                    linkto[254] = '.';
449                                    linkto[255] = 0;
450                                } else {
451                                    linkto[len] = 0;
452                                }
453                                if (strstr(linkto, "/mnt/sdcard/") == linkto ||
454                                    strstr(linkto, "/system/sounds/") == linkto ||
455                                    strstr(linkto, "/data/") == linkto ||
456                                    strstr(linkto, "/system/media/") == linkto) {
457                                    result.append("  ");
458                                    result.append(buffer);
459                                    result.append(" -> ");
460                                    result.append(linkto);
461                                    result.append("\n");
462                                }
463                            }
464                        } else {
465                            result.append("  unexpected type for ");
466                            result.append(buffer);
467                            result.append("\n");
468                        }
469                    }
470                }
471            }
472            closedir(d);
473        } else {
474            result.append("couldn't open ");
475            result.append(buffer);
476            result.append("\n");
477        }
478
479        bool dumpMem = false;
480        for (size_t i = 0; i < args.size(); i++) {
481            if (args[i] == String16("-m")) {
482                dumpMem = true;
483            }
484        }
485        if (dumpMem) {
486            dumpMemoryAddresses(fd);
487        }
488    }
489    write(fd, result.string(), result.size());
490    return NO_ERROR;
491}
492
493void MediaPlayerService::removeClient(wp<Client> client)
494{
495    Mutex::Autolock lock(mLock);
496    mClients.remove(client);
497}
498
499MediaPlayerService::Client::Client(const sp<MediaPlayerService>& service, pid_t pid,
500        int32_t connId, const sp<IMediaPlayerClient>& client, int audioSessionId)
501{
502    LOGV("Client(%d) constructor", connId);
503    mPid = pid;
504    mConnId = connId;
505    mService = service;
506    mClient = client;
507    mLoop = false;
508    mStatus = NO_INIT;
509    mAudioSessionId = audioSessionId;
510
511#if CALLBACK_ANTAGONIZER
512    LOGD("create Antagonizer");
513    mAntagonizer = new Antagonizer(notify, this);
514#endif
515}
516
517MediaPlayerService::Client::~Client()
518{
519    LOGV("Client(%d) destructor pid = %d", mConnId, mPid);
520    mAudioOutput.clear();
521    wp<Client> client(this);
522    disconnect();
523    mService->removeClient(client);
524}
525
526void MediaPlayerService::Client::disconnect()
527{
528    LOGV("disconnect(%d) from pid %d", mConnId, mPid);
529    // grab local reference and clear main reference to prevent future
530    // access to object
531    sp<MediaPlayerBase> p;
532    {
533        Mutex::Autolock l(mLock);
534        p = mPlayer;
535    }
536    mClient.clear();
537
538    mPlayer.clear();
539
540    // clear the notification to prevent callbacks to dead client
541    // and reset the player. We assume the player will serialize
542    // access to itself if necessary.
543    if (p != 0) {
544        p->setNotifyCallback(0, 0);
545#if CALLBACK_ANTAGONIZER
546        LOGD("kill Antagonizer");
547        mAntagonizer->kill();
548#endif
549        p->reset();
550    }
551
552    IPCThreadState::self()->flushCommands();
553}
554
555static player_type getDefaultPlayerType() {
556    return STAGEFRIGHT_PLAYER;
557}
558
559player_type getPlayerType(int fd, int64_t offset, int64_t length)
560{
561    char buf[20];
562    lseek(fd, offset, SEEK_SET);
563    read(fd, buf, sizeof(buf));
564    lseek(fd, offset, SEEK_SET);
565
566    long ident = *((long*)buf);
567
568    // Ogg vorbis?
569    if (ident == 0x5367674f) // 'OggS'
570        return STAGEFRIGHT_PLAYER;
571
572    // Some kind of MIDI?
573    EAS_DATA_HANDLE easdata;
574    if (EAS_Init(&easdata) == EAS_SUCCESS) {
575        EAS_FILE locator;
576        locator.path = NULL;
577        locator.fd = fd;
578        locator.offset = offset;
579        locator.length = length;
580        EAS_HANDLE  eashandle;
581        if (EAS_OpenFile(easdata, &locator, &eashandle) == EAS_SUCCESS) {
582            EAS_CloseFile(easdata, eashandle);
583            EAS_Shutdown(easdata);
584            return SONIVOX_PLAYER;
585        }
586        EAS_Shutdown(easdata);
587    }
588
589    return getDefaultPlayerType();
590}
591
592player_type getPlayerType(const char* url)
593{
594    if (TestPlayerStub::canBeUsed(url)) {
595        return TEST_PLAYER;
596    }
597
598    if (!strncasecmp("http://", url, 7)
599            || !strncasecmp("https://", url, 8)) {
600        size_t len = strlen(url);
601        if (len >= 5 && !strcasecmp(".m3u8", &url[len - 5])) {
602            return NU_PLAYER;
603        }
604
605        if (strstr(url,"m3u8")) {
606            return NU_PLAYER;
607        }
608    }
609
610    // use MidiFile for MIDI extensions
611    int lenURL = strlen(url);
612    for (int i = 0; i < NELEM(FILE_EXTS); ++i) {
613        int len = strlen(FILE_EXTS[i].extension);
614        int start = lenURL - len;
615        if (start > 0) {
616            if (!strncasecmp(url + start, FILE_EXTS[i].extension, len)) {
617                return FILE_EXTS[i].playertype;
618            }
619        }
620    }
621
622    return getDefaultPlayerType();
623}
624
625static sp<MediaPlayerBase> createPlayer(player_type playerType, void* cookie,
626        notify_callback_f notifyFunc)
627{
628    sp<MediaPlayerBase> p;
629    switch (playerType) {
630        case SONIVOX_PLAYER:
631            LOGV(" create MidiFile");
632            p = new MidiFile();
633            break;
634        case STAGEFRIGHT_PLAYER:
635            LOGV(" create StagefrightPlayer");
636            p = new StagefrightPlayer;
637            break;
638        case NU_PLAYER:
639            LOGV(" create NuPlayer");
640            p = new NuPlayerDriver;
641            break;
642        case TEST_PLAYER:
643            LOGV("Create Test Player stub");
644            p = new TestPlayerStub();
645            break;
646        default:
647            LOGE("Unknown player type: %d", playerType);
648            return NULL;
649    }
650    if (p != NULL) {
651        if (p->initCheck() == NO_ERROR) {
652            p->setNotifyCallback(cookie, notifyFunc);
653        } else {
654            p.clear();
655        }
656    }
657    if (p == NULL) {
658        LOGE("Failed to create player object");
659    }
660    return p;
661}
662
663sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
664{
665    // determine if we have the right player type
666    sp<MediaPlayerBase> p = mPlayer;
667    if ((p != NULL) && (p->playerType() != playerType)) {
668        LOGV("delete player");
669        p.clear();
670    }
671    if (p == NULL) {
672        p = android::createPlayer(playerType, this, notify);
673    }
674    return p;
675}
676
677status_t MediaPlayerService::Client::setDataSource(
678        const char *url, const KeyedVector<String8, String8> *headers)
679{
680    LOGV("setDataSource(%s)", url);
681    if (url == NULL)
682        return UNKNOWN_ERROR;
683
684    if (strncmp(url, "content://", 10) == 0) {
685        // get a filedescriptor for the content Uri and
686        // pass it to the setDataSource(fd) method
687
688        String16 url16(url);
689        int fd = android::openContentProviderFile(url16);
690        if (fd < 0)
691        {
692            LOGE("Couldn't open fd for %s", url);
693            return UNKNOWN_ERROR;
694        }
695        setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
696        close(fd);
697        return mStatus;
698    } else {
699        player_type playerType = getPlayerType(url);
700        LOGV("player type = %d", playerType);
701
702        // create the right type of player
703        sp<MediaPlayerBase> p = createPlayer(playerType);
704        if (p == NULL) return NO_INIT;
705
706        if (!p->hardwareOutput()) {
707            mAudioOutput = new AudioOutput(mAudioSessionId);
708            static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
709        }
710
711        // now set data source
712        LOGV(" setDataSource");
713        mStatus = p->setDataSource(url, headers);
714        if (mStatus == NO_ERROR) {
715            mPlayer = p;
716        } else {
717            LOGE("  error: %d", mStatus);
718        }
719        return mStatus;
720    }
721}
722
723status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
724{
725    LOGV("setDataSource fd=%d, offset=%lld, length=%lld", fd, offset, length);
726    struct stat sb;
727    int ret = fstat(fd, &sb);
728    if (ret != 0) {
729        LOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
730        return UNKNOWN_ERROR;
731    }
732
733    LOGV("st_dev  = %llu", sb.st_dev);
734    LOGV("st_mode = %u", sb.st_mode);
735    LOGV("st_uid  = %lu", sb.st_uid);
736    LOGV("st_gid  = %lu", sb.st_gid);
737    LOGV("st_size = %llu", sb.st_size);
738
739    if (offset >= sb.st_size) {
740        LOGE("offset error");
741        ::close(fd);
742        return UNKNOWN_ERROR;
743    }
744    if (offset + length > sb.st_size) {
745        length = sb.st_size - offset;
746        LOGV("calculated length = %lld", length);
747    }
748
749    player_type playerType = getPlayerType(fd, offset, length);
750    LOGV("player type = %d", playerType);
751
752    // create the right type of player
753    sp<MediaPlayerBase> p = createPlayer(playerType);
754    if (p == NULL) return NO_INIT;
755
756    if (!p->hardwareOutput()) {
757        mAudioOutput = new AudioOutput(mAudioSessionId);
758        static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
759    }
760
761    // now set data source
762    mStatus = p->setDataSource(fd, offset, length);
763    if (mStatus == NO_ERROR) mPlayer = p;
764    return mStatus;
765}
766
767status_t MediaPlayerService::Client::setDataSource(
768        const sp<IStreamSource> &source) {
769    // create the right type of player
770    sp<MediaPlayerBase> p = createPlayer(NU_PLAYER);
771
772    if (p == NULL) {
773        return NO_INIT;
774    }
775
776    if (!p->hardwareOutput()) {
777        mAudioOutput = new AudioOutput(mAudioSessionId);
778        static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
779    }
780
781    // now set data source
782    mStatus = p->setDataSource(source);
783
784    if (mStatus == OK) {
785        mPlayer = p;
786    }
787
788    return mStatus;
789}
790
791status_t MediaPlayerService::Client::setVideoSurface(const sp<Surface>& surface)
792{
793    LOGV("[%d] setVideoSurface(%p)", mConnId, surface.get());
794    sp<MediaPlayerBase> p = getPlayer();
795    if (p == 0) return UNKNOWN_ERROR;
796    return p->setVideoSurface(surface);
797}
798
799status_t MediaPlayerService::Client::setVideoSurfaceTexture(
800        const sp<ISurfaceTexture>& surfaceTexture)
801{
802    LOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, surfaceTexture.get());
803    sp<MediaPlayerBase> p = getPlayer();
804    if (p == 0) return UNKNOWN_ERROR;
805    return p->setVideoSurfaceTexture(surfaceTexture);
806}
807
808status_t MediaPlayerService::Client::invoke(const Parcel& request,
809                                            Parcel *reply)
810{
811    sp<MediaPlayerBase> p = getPlayer();
812    if (p == NULL) return UNKNOWN_ERROR;
813    return p->invoke(request, reply);
814}
815
816// This call doesn't need to access the native player.
817status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
818{
819    status_t status;
820    media::Metadata::Filter allow, drop;
821
822    if (unmarshallFilter(filter, &allow, &status) &&
823        unmarshallFilter(filter, &drop, &status)) {
824        Mutex::Autolock lock(mLock);
825
826        mMetadataAllow = allow;
827        mMetadataDrop = drop;
828    }
829    return status;
830}
831
832status_t MediaPlayerService::Client::getMetadata(
833        bool update_only, bool apply_filter, Parcel *reply)
834{
835    sp<MediaPlayerBase> player = getPlayer();
836    if (player == 0) return UNKNOWN_ERROR;
837
838    status_t status;
839    // Placeholder for the return code, updated by the caller.
840    reply->writeInt32(-1);
841
842    media::Metadata::Filter ids;
843
844    // We don't block notifications while we fetch the data. We clear
845    // mMetadataUpdated first so we don't lose notifications happening
846    // during the rest of this call.
847    {
848        Mutex::Autolock lock(mLock);
849        if (update_only) {
850            ids = mMetadataUpdated;
851        }
852        mMetadataUpdated.clear();
853    }
854
855    media::Metadata metadata(reply);
856
857    metadata.appendHeader();
858    status = player->getMetadata(ids, reply);
859
860    if (status != OK) {
861        metadata.resetParcel();
862        LOGE("getMetadata failed %d", status);
863        return status;
864    }
865
866    // FIXME: Implement filtering on the result. Not critical since
867    // filtering takes place on the update notifications already. This
868    // would be when all the metadata are fetch and a filter is set.
869
870    // Everything is fine, update the metadata length.
871    metadata.updateLength();
872    return OK;
873}
874
875status_t MediaPlayerService::Client::prepareAsync()
876{
877    LOGV("[%d] prepareAsync", mConnId);
878    sp<MediaPlayerBase> p = getPlayer();
879    if (p == 0) return UNKNOWN_ERROR;
880    status_t ret = p->prepareAsync();
881#if CALLBACK_ANTAGONIZER
882    LOGD("start Antagonizer");
883    if (ret == NO_ERROR) mAntagonizer->start();
884#endif
885    return ret;
886}
887
888status_t MediaPlayerService::Client::start()
889{
890    LOGV("[%d] start", mConnId);
891    sp<MediaPlayerBase> p = getPlayer();
892    if (p == 0) return UNKNOWN_ERROR;
893    p->setLooping(mLoop);
894    return p->start();
895}
896
897status_t MediaPlayerService::Client::stop()
898{
899    LOGV("[%d] stop", mConnId);
900    sp<MediaPlayerBase> p = getPlayer();
901    if (p == 0) return UNKNOWN_ERROR;
902    return p->stop();
903}
904
905status_t MediaPlayerService::Client::pause()
906{
907    LOGV("[%d] pause", mConnId);
908    sp<MediaPlayerBase> p = getPlayer();
909    if (p == 0) return UNKNOWN_ERROR;
910    return p->pause();
911}
912
913status_t MediaPlayerService::Client::isPlaying(bool* state)
914{
915    *state = false;
916    sp<MediaPlayerBase> p = getPlayer();
917    if (p == 0) return UNKNOWN_ERROR;
918    *state = p->isPlaying();
919    LOGV("[%d] isPlaying: %d", mConnId, *state);
920    return NO_ERROR;
921}
922
923status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
924{
925    LOGV("getCurrentPosition");
926    sp<MediaPlayerBase> p = getPlayer();
927    if (p == 0) return UNKNOWN_ERROR;
928    status_t ret = p->getCurrentPosition(msec);
929    if (ret == NO_ERROR) {
930        LOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
931    } else {
932        LOGE("getCurrentPosition returned %d", ret);
933    }
934    return ret;
935}
936
937status_t MediaPlayerService::Client::getDuration(int *msec)
938{
939    LOGV("getDuration");
940    sp<MediaPlayerBase> p = getPlayer();
941    if (p == 0) return UNKNOWN_ERROR;
942    status_t ret = p->getDuration(msec);
943    if (ret == NO_ERROR) {
944        LOGV("[%d] getDuration = %d", mConnId, *msec);
945    } else {
946        LOGE("getDuration returned %d", ret);
947    }
948    return ret;
949}
950
951status_t MediaPlayerService::Client::seekTo(int msec)
952{
953    LOGV("[%d] seekTo(%d)", mConnId, msec);
954    sp<MediaPlayerBase> p = getPlayer();
955    if (p == 0) return UNKNOWN_ERROR;
956    return p->seekTo(msec);
957}
958
959status_t MediaPlayerService::Client::reset()
960{
961    LOGV("[%d] reset", mConnId);
962    sp<MediaPlayerBase> p = getPlayer();
963    if (p == 0) return UNKNOWN_ERROR;
964    return p->reset();
965}
966
967status_t MediaPlayerService::Client::setAudioStreamType(int type)
968{
969    LOGV("[%d] setAudioStreamType(%d)", mConnId, type);
970    // TODO: for hardware output, call player instead
971    Mutex::Autolock l(mLock);
972    if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
973    return NO_ERROR;
974}
975
976status_t MediaPlayerService::Client::setLooping(int loop)
977{
978    LOGV("[%d] setLooping(%d)", mConnId, loop);
979    mLoop = loop;
980    sp<MediaPlayerBase> p = getPlayer();
981    if (p != 0) return p->setLooping(loop);
982    return NO_ERROR;
983}
984
985status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
986{
987    LOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
988    // TODO: for hardware output, call player instead
989    Mutex::Autolock l(mLock);
990    if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
991    return NO_ERROR;
992}
993
994status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
995{
996    LOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
997    Mutex::Autolock l(mLock);
998    if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
999    return NO_ERROR;
1000}
1001
1002status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1003{
1004    LOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
1005    Mutex::Autolock l(mLock);
1006    if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1007    return NO_ERROR;
1008}
1009
1010status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
1011    LOGV("[%d] setParameter(%d)", mConnId, key);
1012    sp<MediaPlayerBase> p = getPlayer();
1013    if (p == 0) return UNKNOWN_ERROR;
1014    return p->setParameter(key, request);
1015}
1016
1017status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
1018    LOGV("[%d] getParameter(%d)", mConnId, key);
1019    sp<MediaPlayerBase> p = getPlayer();
1020    if (p == 0) return UNKNOWN_ERROR;
1021    return p->getParameter(key, reply);
1022}
1023
1024void MediaPlayerService::Client::notify(
1025        void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
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, obj);
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 = (int)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 = AUDIO_STREAM_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) ? AUDIO_CHANNEL_OUT_STEREO : AUDIO_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) ? AUDIO_CHANNEL_OUT_STEREO : AUDIO_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(
1627        void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
1628{
1629    LOGV("notify(%p, %d, %d, %d)", cookie, msg, ext1, ext2);
1630    AudioCache* p = static_cast<AudioCache*>(cookie);
1631
1632    // ignore buffering messages
1633    switch (msg)
1634    {
1635    case MEDIA_ERROR:
1636        LOGE("Error %d, %d occurred", ext1, ext2);
1637        p->mError = ext1;
1638        break;
1639    case MEDIA_PREPARED:
1640        LOGV("prepared");
1641        break;
1642    case MEDIA_PLAYBACK_COMPLETE:
1643        LOGV("playback complete");
1644        break;
1645    default:
1646        LOGV("ignored");
1647        return;
1648    }
1649
1650    // wake up thread
1651    Mutex::Autolock lock(p->mLock);
1652    p->mCommandComplete = true;
1653    p->mSignal.signal();
1654}
1655
1656int MediaPlayerService::AudioCache::getSessionId()
1657{
1658    return 0;
1659}
1660
1661void MediaPlayerService::addBatteryData(uint32_t params)
1662{
1663    Mutex::Autolock lock(mLock);
1664
1665    int32_t time = systemTime() / 1000000L;
1666
1667    // change audio output devices. This notification comes from AudioFlinger
1668    if ((params & kBatteryDataSpeakerOn)
1669            || (params & kBatteryDataOtherAudioDeviceOn)) {
1670
1671        int deviceOn[NUM_AUDIO_DEVICES];
1672        for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1673            deviceOn[i] = 0;
1674        }
1675
1676        if ((params & kBatteryDataSpeakerOn)
1677                && (params & kBatteryDataOtherAudioDeviceOn)) {
1678            deviceOn[SPEAKER_AND_OTHER] = 1;
1679        } else if (params & kBatteryDataSpeakerOn) {
1680            deviceOn[SPEAKER] = 1;
1681        } else {
1682            deviceOn[OTHER_AUDIO_DEVICE] = 1;
1683        }
1684
1685        for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1686            if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
1687
1688                if (mBatteryAudio.refCount > 0) { // if playing audio
1689                    if (!deviceOn[i]) {
1690                        mBatteryAudio.lastTime[i] += time;
1691                        mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
1692                        mBatteryAudio.lastTime[i] = 0;
1693                    } else {
1694                        mBatteryAudio.lastTime[i] = 0 - time;
1695                    }
1696                }
1697
1698                mBatteryAudio.deviceOn[i] = deviceOn[i];
1699            }
1700        }
1701        return;
1702    }
1703
1704    // an sudio stream is started
1705    if (params & kBatteryDataAudioFlingerStart) {
1706        // record the start time only if currently no other audio
1707        // is being played
1708        if (mBatteryAudio.refCount == 0) {
1709            for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1710                if (mBatteryAudio.deviceOn[i]) {
1711                    mBatteryAudio.lastTime[i] -= time;
1712                }
1713            }
1714        }
1715
1716        mBatteryAudio.refCount ++;
1717        return;
1718
1719    } else if (params & kBatteryDataAudioFlingerStop) {
1720        if (mBatteryAudio.refCount <= 0) {
1721            LOGW("Battery track warning: refCount is <= 0");
1722            return;
1723        }
1724
1725        // record the stop time only if currently this is the only
1726        // audio being played
1727        if (mBatteryAudio.refCount == 1) {
1728            for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1729                if (mBatteryAudio.deviceOn[i]) {
1730                    mBatteryAudio.lastTime[i] += time;
1731                    mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
1732                    mBatteryAudio.lastTime[i] = 0;
1733                }
1734            }
1735        }
1736
1737        mBatteryAudio.refCount --;
1738        return;
1739    }
1740
1741    int uid = IPCThreadState::self()->getCallingUid();
1742    if (uid == AID_MEDIA) {
1743        return;
1744    }
1745    int index = mBatteryData.indexOfKey(uid);
1746
1747    if (index < 0) { // create a new entry for this UID
1748        BatteryUsageInfo info;
1749        info.audioTotalTime = 0;
1750        info.videoTotalTime = 0;
1751        info.audioLastTime = 0;
1752        info.videoLastTime = 0;
1753        info.refCount = 0;
1754
1755        if (mBatteryData.add(uid, info) == NO_MEMORY) {
1756            LOGE("Battery track error: no memory for new app");
1757            return;
1758        }
1759    }
1760
1761    BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
1762
1763    if (params & kBatteryDataCodecStarted) {
1764        if (params & kBatteryDataTrackAudio) {
1765            info.audioLastTime -= time;
1766            info.refCount ++;
1767        }
1768        if (params & kBatteryDataTrackVideo) {
1769            info.videoLastTime -= time;
1770            info.refCount ++;
1771        }
1772    } else {
1773        if (info.refCount == 0) {
1774            LOGW("Battery track warning: refCount is already 0");
1775            return;
1776        } else if (info.refCount < 0) {
1777            LOGE("Battery track error: refCount < 0");
1778            mBatteryData.removeItem(uid);
1779            return;
1780        }
1781
1782        if (params & kBatteryDataTrackAudio) {
1783            info.audioLastTime += time;
1784            info.refCount --;
1785        }
1786        if (params & kBatteryDataTrackVideo) {
1787            info.videoLastTime += time;
1788            info.refCount --;
1789        }
1790
1791        // no stream is being played by this UID
1792        if (info.refCount == 0) {
1793            info.audioTotalTime += info.audioLastTime;
1794            info.audioLastTime = 0;
1795            info.videoTotalTime += info.videoLastTime;
1796            info.videoLastTime = 0;
1797        }
1798    }
1799}
1800
1801status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
1802    Mutex::Autolock lock(mLock);
1803
1804    // audio output devices usage
1805    int32_t time = systemTime() / 1000000L; //in ms
1806    int32_t totalTime;
1807
1808    for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1809        totalTime = mBatteryAudio.totalTime[i];
1810
1811        if (mBatteryAudio.deviceOn[i]
1812            && (mBatteryAudio.lastTime[i] != 0)) {
1813                int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
1814                totalTime += tmpTime;
1815        }
1816
1817        reply->writeInt32(totalTime);
1818        // reset the total time
1819        mBatteryAudio.totalTime[i] = 0;
1820   }
1821
1822    // codec usage
1823    BatteryUsageInfo info;
1824    int size = mBatteryData.size();
1825
1826    reply->writeInt32(size);
1827    int i = 0;
1828
1829    while (i < size) {
1830        info = mBatteryData.valueAt(i);
1831
1832        reply->writeInt32(mBatteryData.keyAt(i)); //UID
1833        reply->writeInt32(info.audioTotalTime);
1834        reply->writeInt32(info.videoTotalTime);
1835
1836        info.audioTotalTime = 0;
1837        info.videoTotalTime = 0;
1838
1839        // remove the UID entry where no stream is being played
1840        if (info.refCount <= 0) {
1841            mBatteryData.removeItemsAt(i);
1842            size --;
1843            i --;
1844        }
1845        i++;
1846    }
1847    return NO_ERROR;
1848}
1849} // namespace android
1850