MediaPlayerService.cpp revision db29e5238e28d59978755a2ff2e7e0f05393abdf
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
254    sp<Client> c = new Client(
255            this, pid, connId, client, audioSessionId,
256            IPCThreadState::self()->getCallingUid());
257
258    LOGV("Create new client(%d) from pid %d, uid %d, url=%s, connId=%d, audioSessionId=%d",
259            connId, pid, IPCThreadState::self()->getCallingUid(), url, connId, audioSessionId);
260    if (NO_ERROR != c->setDataSource(url, headers))
261    {
262        c.clear();
263        return c;
264    }
265    wp<Client> w = c;
266    Mutex::Autolock lock(mLock);
267    mClients.add(w);
268    return c;
269}
270
271sp<IMediaPlayer> MediaPlayerService::create(pid_t pid, const sp<IMediaPlayerClient>& client,
272        int fd, int64_t offset, int64_t length, int audioSessionId)
273{
274    int32_t connId = android_atomic_inc(&mNextConnId);
275
276    sp<Client> c = new Client(
277            this, pid, connId, client, audioSessionId,
278            IPCThreadState::self()->getCallingUid());
279
280    LOGV("Create new client(%d) from pid %d, uid %d, fd=%d, offset=%lld, "
281         "length=%lld, audioSessionId=%d", connId, pid,
282         IPCThreadState::self()->getCallingUid(), fd, offset, length, audioSessionId);
283    if (NO_ERROR != c->setDataSource(fd, offset, length)) {
284        c.clear();
285    } else {
286        wp<Client> w = c;
287        Mutex::Autolock lock(mLock);
288        mClients.add(w);
289    }
290    ::close(fd);
291    return c;
292}
293
294sp<IMediaPlayer> MediaPlayerService::create(
295        pid_t pid, const sp<IMediaPlayerClient> &client,
296        const sp<IStreamSource> &source, int audioSessionId) {
297    int32_t connId = android_atomic_inc(&mNextConnId);
298
299    sp<Client> c = new Client(
300            this, pid, connId, client, audioSessionId,
301            IPCThreadState::self()->getCallingUid());
302
303    LOGV("Create new client(%d) from pid %d, audioSessionId=%d",
304         connId, pid, audioSessionId);
305
306    if (OK != c->setDataSource(source)) {
307        c.clear();
308    } else {
309        wp<Client> w = c;
310        Mutex::Autolock lock(mLock);
311        mClients.add(w);
312    }
313
314    return c;
315}
316
317sp<IOMX> MediaPlayerService::getOMX() {
318    Mutex::Autolock autoLock(mLock);
319
320    if (mOMX.get() == NULL) {
321        mOMX = new OMX;
322    }
323
324    return mOMX;
325}
326
327status_t MediaPlayerService::AudioCache::dump(int fd, const Vector<String16>& args) const
328{
329    const size_t SIZE = 256;
330    char buffer[SIZE];
331    String8 result;
332
333    result.append(" AudioCache\n");
334    if (mHeap != 0) {
335        snprintf(buffer, 255, "  heap base(%p), size(%d), flags(%d), device(%s)\n",
336                mHeap->getBase(), mHeap->getSize(), mHeap->getFlags(), mHeap->getDevice());
337        result.append(buffer);
338    }
339    snprintf(buffer, 255, "  msec per frame(%f), channel count(%d), format(%d), frame count(%ld)\n",
340            mMsecsPerFrame, mChannelCount, mFormat, mFrameCount);
341    result.append(buffer);
342    snprintf(buffer, 255, "  sample rate(%d), size(%d), error(%d), command complete(%s)\n",
343            mSampleRate, mSize, mError, mCommandComplete?"true":"false");
344    result.append(buffer);
345    ::write(fd, result.string(), result.size());
346    return NO_ERROR;
347}
348
349status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
350{
351    const size_t SIZE = 256;
352    char buffer[SIZE];
353    String8 result;
354
355    result.append(" AudioOutput\n");
356    snprintf(buffer, 255, "  stream type(%d), left - right volume(%f, %f)\n",
357            mStreamType, mLeftVolume, mRightVolume);
358    result.append(buffer);
359    snprintf(buffer, 255, "  msec per frame(%f), latency (%d)\n",
360            mMsecsPerFrame, mLatency);
361    result.append(buffer);
362    snprintf(buffer, 255, "  aux effect id(%d), send level (%f)\n",
363            mAuxEffectId, mSendLevel);
364    result.append(buffer);
365
366    ::write(fd, result.string(), result.size());
367    if (mTrack != 0) {
368        mTrack->dump(fd, args);
369    }
370    return NO_ERROR;
371}
372
373status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args) const
374{
375    const size_t SIZE = 256;
376    char buffer[SIZE];
377    String8 result;
378    result.append(" Client\n");
379    snprintf(buffer, 255, "  pid(%d), connId(%d), status(%d), looping(%s)\n",
380            mPid, mConnId, mStatus, mLoop?"true": "false");
381    result.append(buffer);
382    write(fd, result.string(), result.size());
383    if (mPlayer != NULL) {
384        mPlayer->dump(fd, args);
385    }
386    if (mAudioOutput != 0) {
387        mAudioOutput->dump(fd, args);
388    }
389    write(fd, "\n", 1);
390    return NO_ERROR;
391}
392
393status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
394{
395    const size_t SIZE = 256;
396    char buffer[SIZE];
397    String8 result;
398    if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
399        snprintf(buffer, SIZE, "Permission Denial: "
400                "can't dump MediaPlayerService from pid=%d, uid=%d\n",
401                IPCThreadState::self()->getCallingPid(),
402                IPCThreadState::self()->getCallingUid());
403        result.append(buffer);
404    } else {
405        Mutex::Autolock lock(mLock);
406        for (int i = 0, n = mClients.size(); i < n; ++i) {
407            sp<Client> c = mClients[i].promote();
408            if (c != 0) c->dump(fd, args);
409        }
410        if (mMediaRecorderClients.size() == 0) {
411                result.append(" No media recorder client\n\n");
412        } else {
413            for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
414                sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
415                snprintf(buffer, 255, " MediaRecorderClient pid(%d)\n", c->mPid);
416                result.append(buffer);
417                write(fd, result.string(), result.size());
418                result = "\n";
419                c->dump(fd, args);
420            }
421        }
422
423        result.append(" Files opened and/or mapped:\n");
424        snprintf(buffer, SIZE, "/proc/%d/maps", gettid());
425        FILE *f = fopen(buffer, "r");
426        if (f) {
427            while (!feof(f)) {
428                fgets(buffer, SIZE, f);
429                if (strstr(buffer, " /mnt/sdcard/") ||
430                    strstr(buffer, " /system/sounds/") ||
431                    strstr(buffer, " /data/") ||
432                    strstr(buffer, " /system/media/")) {
433                    result.append("  ");
434                    result.append(buffer);
435                }
436            }
437            fclose(f);
438        } else {
439            result.append("couldn't open ");
440            result.append(buffer);
441            result.append("\n");
442        }
443
444        snprintf(buffer, SIZE, "/proc/%d/fd", gettid());
445        DIR *d = opendir(buffer);
446        if (d) {
447            struct dirent *ent;
448            while((ent = readdir(d)) != NULL) {
449                if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
450                    snprintf(buffer, SIZE, "/proc/%d/fd/%s", gettid(), ent->d_name);
451                    struct stat s;
452                    if (lstat(buffer, &s) == 0) {
453                        if ((s.st_mode & S_IFMT) == S_IFLNK) {
454                            char linkto[256];
455                            int len = readlink(buffer, linkto, sizeof(linkto));
456                            if(len > 0) {
457                                if(len > 255) {
458                                    linkto[252] = '.';
459                                    linkto[253] = '.';
460                                    linkto[254] = '.';
461                                    linkto[255] = 0;
462                                } else {
463                                    linkto[len] = 0;
464                                }
465                                if (strstr(linkto, "/mnt/sdcard/") == linkto ||
466                                    strstr(linkto, "/system/sounds/") == linkto ||
467                                    strstr(linkto, "/data/") == linkto ||
468                                    strstr(linkto, "/system/media/") == linkto) {
469                                    result.append("  ");
470                                    result.append(buffer);
471                                    result.append(" -> ");
472                                    result.append(linkto);
473                                    result.append("\n");
474                                }
475                            }
476                        } else {
477                            result.append("  unexpected type for ");
478                            result.append(buffer);
479                            result.append("\n");
480                        }
481                    }
482                }
483            }
484            closedir(d);
485        } else {
486            result.append("couldn't open ");
487            result.append(buffer);
488            result.append("\n");
489        }
490
491        bool dumpMem = false;
492        for (size_t i = 0; i < args.size(); i++) {
493            if (args[i] == String16("-m")) {
494                dumpMem = true;
495            }
496        }
497        if (dumpMem) {
498            dumpMemoryAddresses(fd);
499        }
500    }
501    write(fd, result.string(), result.size());
502    return NO_ERROR;
503}
504
505void MediaPlayerService::removeClient(wp<Client> client)
506{
507    Mutex::Autolock lock(mLock);
508    mClients.remove(client);
509}
510
511MediaPlayerService::Client::Client(
512        const sp<MediaPlayerService>& service, pid_t pid,
513        int32_t connId, const sp<IMediaPlayerClient>& client,
514        int audioSessionId, uid_t uid)
515{
516    LOGV("Client(%d) constructor", connId);
517    mPid = pid;
518    mConnId = connId;
519    mService = service;
520    mClient = client;
521    mLoop = false;
522    mStatus = NO_INIT;
523    mAudioSessionId = audioSessionId;
524    mUID = uid;
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
690    if (p != NULL) {
691        p->setUID(mUID);
692    }
693
694    return p;
695}
696
697status_t MediaPlayerService::Client::setDataSource(
698        const char *url, const KeyedVector<String8, String8> *headers)
699{
700    LOGV("setDataSource(%s)", url);
701    if (url == NULL)
702        return UNKNOWN_ERROR;
703
704    if (strncmp(url, "content://", 10) == 0) {
705        // get a filedescriptor for the content Uri and
706        // pass it to the setDataSource(fd) method
707
708        String16 url16(url);
709        int fd = android::openContentProviderFile(url16);
710        if (fd < 0)
711        {
712            LOGE("Couldn't open fd for %s", url);
713            return UNKNOWN_ERROR;
714        }
715        setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
716        close(fd);
717        return mStatus;
718    } else {
719        player_type playerType = getPlayerType(url);
720        LOGV("player type = %d", playerType);
721
722        // create the right type of player
723        sp<MediaPlayerBase> p = createPlayer(playerType);
724        if (p == NULL) return NO_INIT;
725
726        if (!p->hardwareOutput()) {
727            mAudioOutput = new AudioOutput(mAudioSessionId);
728            static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
729        }
730
731        // now set data source
732        LOGV(" setDataSource");
733        mStatus = p->setDataSource(url, headers);
734        if (mStatus == NO_ERROR) {
735            mPlayer = p;
736        } else {
737            LOGE("  error: %d", mStatus);
738        }
739        return mStatus;
740    }
741}
742
743status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
744{
745    LOGV("setDataSource fd=%d, offset=%lld, length=%lld", fd, offset, length);
746    struct stat sb;
747    int ret = fstat(fd, &sb);
748    if (ret != 0) {
749        LOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
750        return UNKNOWN_ERROR;
751    }
752
753    LOGV("st_dev  = %llu", sb.st_dev);
754    LOGV("st_mode = %u", sb.st_mode);
755    LOGV("st_uid  = %lu", sb.st_uid);
756    LOGV("st_gid  = %lu", sb.st_gid);
757    LOGV("st_size = %llu", sb.st_size);
758
759    if (offset >= sb.st_size) {
760        LOGE("offset error");
761        ::close(fd);
762        return UNKNOWN_ERROR;
763    }
764    if (offset + length > sb.st_size) {
765        length = sb.st_size - offset;
766        LOGV("calculated length = %lld", length);
767    }
768
769    player_type playerType = getPlayerType(fd, offset, length);
770    LOGV("player type = %d", playerType);
771
772    // create the right type of player
773    sp<MediaPlayerBase> p = createPlayer(playerType);
774    if (p == NULL) return NO_INIT;
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(fd, offset, length);
783    if (mStatus == NO_ERROR) mPlayer = p;
784    return mStatus;
785}
786
787status_t MediaPlayerService::Client::setDataSource(
788        const sp<IStreamSource> &source) {
789    // create the right type of player
790    sp<MediaPlayerBase> p = createPlayer(NU_PLAYER);
791
792    if (p == NULL) {
793        return NO_INIT;
794    }
795
796    if (!p->hardwareOutput()) {
797        mAudioOutput = new AudioOutput(mAudioSessionId);
798        static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
799    }
800
801    // now set data source
802    mStatus = p->setDataSource(source);
803
804    if (mStatus == OK) {
805        mPlayer = p;
806    }
807
808    return mStatus;
809}
810
811status_t MediaPlayerService::Client::setVideoSurface(const sp<Surface>& surface)
812{
813    LOGV("[%d] setVideoSurface(%p)", mConnId, surface.get());
814    sp<MediaPlayerBase> p = getPlayer();
815    if (p == 0) return UNKNOWN_ERROR;
816    return p->setVideoSurface(surface);
817}
818
819status_t MediaPlayerService::Client::setVideoSurfaceTexture(
820        const sp<ISurfaceTexture>& surfaceTexture)
821{
822    LOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, surfaceTexture.get());
823    sp<MediaPlayerBase> p = getPlayer();
824    if (p == 0) return UNKNOWN_ERROR;
825    return p->setVideoSurfaceTexture(surfaceTexture);
826}
827
828status_t MediaPlayerService::Client::invoke(const Parcel& request,
829                                            Parcel *reply)
830{
831    sp<MediaPlayerBase> p = getPlayer();
832    if (p == NULL) return UNKNOWN_ERROR;
833    return p->invoke(request, reply);
834}
835
836// This call doesn't need to access the native player.
837status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
838{
839    status_t status;
840    media::Metadata::Filter allow, drop;
841
842    if (unmarshallFilter(filter, &allow, &status) &&
843        unmarshallFilter(filter, &drop, &status)) {
844        Mutex::Autolock lock(mLock);
845
846        mMetadataAllow = allow;
847        mMetadataDrop = drop;
848    }
849    return status;
850}
851
852status_t MediaPlayerService::Client::getMetadata(
853        bool update_only, bool apply_filter, Parcel *reply)
854{
855    sp<MediaPlayerBase> player = getPlayer();
856    if (player == 0) return UNKNOWN_ERROR;
857
858    status_t status;
859    // Placeholder for the return code, updated by the caller.
860    reply->writeInt32(-1);
861
862    media::Metadata::Filter ids;
863
864    // We don't block notifications while we fetch the data. We clear
865    // mMetadataUpdated first so we don't lose notifications happening
866    // during the rest of this call.
867    {
868        Mutex::Autolock lock(mLock);
869        if (update_only) {
870            ids = mMetadataUpdated;
871        }
872        mMetadataUpdated.clear();
873    }
874
875    media::Metadata metadata(reply);
876
877    metadata.appendHeader();
878    status = player->getMetadata(ids, reply);
879
880    if (status != OK) {
881        metadata.resetParcel();
882        LOGE("getMetadata failed %d", status);
883        return status;
884    }
885
886    // FIXME: Implement filtering on the result. Not critical since
887    // filtering takes place on the update notifications already. This
888    // would be when all the metadata are fetch and a filter is set.
889
890    // Everything is fine, update the metadata length.
891    metadata.updateLength();
892    return OK;
893}
894
895status_t MediaPlayerService::Client::prepareAsync()
896{
897    LOGV("[%d] prepareAsync", mConnId);
898    sp<MediaPlayerBase> p = getPlayer();
899    if (p == 0) return UNKNOWN_ERROR;
900    status_t ret = p->prepareAsync();
901#if CALLBACK_ANTAGONIZER
902    LOGD("start Antagonizer");
903    if (ret == NO_ERROR) mAntagonizer->start();
904#endif
905    return ret;
906}
907
908status_t MediaPlayerService::Client::start()
909{
910    LOGV("[%d] start", mConnId);
911    sp<MediaPlayerBase> p = getPlayer();
912    if (p == 0) return UNKNOWN_ERROR;
913    p->setLooping(mLoop);
914    return p->start();
915}
916
917status_t MediaPlayerService::Client::stop()
918{
919    LOGV("[%d] stop", mConnId);
920    sp<MediaPlayerBase> p = getPlayer();
921    if (p == 0) return UNKNOWN_ERROR;
922    return p->stop();
923}
924
925status_t MediaPlayerService::Client::pause()
926{
927    LOGV("[%d] pause", mConnId);
928    sp<MediaPlayerBase> p = getPlayer();
929    if (p == 0) return UNKNOWN_ERROR;
930    return p->pause();
931}
932
933status_t MediaPlayerService::Client::isPlaying(bool* state)
934{
935    *state = false;
936    sp<MediaPlayerBase> p = getPlayer();
937    if (p == 0) return UNKNOWN_ERROR;
938    *state = p->isPlaying();
939    LOGV("[%d] isPlaying: %d", mConnId, *state);
940    return NO_ERROR;
941}
942
943status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
944{
945    LOGV("getCurrentPosition");
946    sp<MediaPlayerBase> p = getPlayer();
947    if (p == 0) return UNKNOWN_ERROR;
948    status_t ret = p->getCurrentPosition(msec);
949    if (ret == NO_ERROR) {
950        LOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
951    } else {
952        LOGE("getCurrentPosition returned %d", ret);
953    }
954    return ret;
955}
956
957status_t MediaPlayerService::Client::getDuration(int *msec)
958{
959    LOGV("getDuration");
960    sp<MediaPlayerBase> p = getPlayer();
961    if (p == 0) return UNKNOWN_ERROR;
962    status_t ret = p->getDuration(msec);
963    if (ret == NO_ERROR) {
964        LOGV("[%d] getDuration = %d", mConnId, *msec);
965    } else {
966        LOGE("getDuration returned %d", ret);
967    }
968    return ret;
969}
970
971status_t MediaPlayerService::Client::seekTo(int msec)
972{
973    LOGV("[%d] seekTo(%d)", mConnId, msec);
974    sp<MediaPlayerBase> p = getPlayer();
975    if (p == 0) return UNKNOWN_ERROR;
976    return p->seekTo(msec);
977}
978
979status_t MediaPlayerService::Client::reset()
980{
981    LOGV("[%d] reset", mConnId);
982    sp<MediaPlayerBase> p = getPlayer();
983    if (p == 0) return UNKNOWN_ERROR;
984    return p->reset();
985}
986
987status_t MediaPlayerService::Client::setAudioStreamType(int type)
988{
989    LOGV("[%d] setAudioStreamType(%d)", mConnId, type);
990    // TODO: for hardware output, call player instead
991    Mutex::Autolock l(mLock);
992    if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
993    return NO_ERROR;
994}
995
996status_t MediaPlayerService::Client::setLooping(int loop)
997{
998    LOGV("[%d] setLooping(%d)", mConnId, loop);
999    mLoop = loop;
1000    sp<MediaPlayerBase> p = getPlayer();
1001    if (p != 0) return p->setLooping(loop);
1002    return NO_ERROR;
1003}
1004
1005status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1006{
1007    LOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
1008    // TODO: for hardware output, call player instead
1009    Mutex::Autolock l(mLock);
1010    if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1011    return NO_ERROR;
1012}
1013
1014status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1015{
1016    LOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
1017    Mutex::Autolock l(mLock);
1018    if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1019    return NO_ERROR;
1020}
1021
1022status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1023{
1024    LOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
1025    Mutex::Autolock l(mLock);
1026    if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1027    return NO_ERROR;
1028}
1029
1030status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
1031    LOGV("[%d] setParameter(%d)", mConnId, key);
1032    sp<MediaPlayerBase> p = getPlayer();
1033    if (p == 0) return UNKNOWN_ERROR;
1034    return p->setParameter(key, request);
1035}
1036
1037status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
1038    LOGV("[%d] getParameter(%d)", mConnId, key);
1039    sp<MediaPlayerBase> p = getPlayer();
1040    if (p == 0) return UNKNOWN_ERROR;
1041    return p->getParameter(key, reply);
1042}
1043
1044void MediaPlayerService::Client::notify(
1045        void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
1046{
1047    Client* client = static_cast<Client*>(cookie);
1048
1049    if (MEDIA_INFO == msg &&
1050        MEDIA_INFO_METADATA_UPDATE == ext1) {
1051        const media::Metadata::Type metadata_type = ext2;
1052
1053        if(client->shouldDropMetadata(metadata_type)) {
1054            return;
1055        }
1056
1057        // Update the list of metadata that have changed. getMetadata
1058        // also access mMetadataUpdated and clears it.
1059        client->addNewMetadataUpdate(metadata_type);
1060    }
1061    LOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
1062    client->mClient->notify(msg, ext1, ext2, obj);
1063}
1064
1065
1066bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
1067{
1068    Mutex::Autolock lock(mLock);
1069
1070    if (findMetadata(mMetadataDrop, code)) {
1071        return true;
1072    }
1073
1074    if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
1075        return false;
1076    } else {
1077        return true;
1078    }
1079}
1080
1081
1082void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
1083    Mutex::Autolock lock(mLock);
1084    if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1085        mMetadataUpdated.add(metadata_type);
1086    }
1087}
1088
1089#if CALLBACK_ANTAGONIZER
1090const int Antagonizer::interval = 10000; // 10 msecs
1091
1092Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1093    mExit(false), mActive(false), mClient(client), mCb(cb)
1094{
1095    createThread(callbackThread, this);
1096}
1097
1098void Antagonizer::kill()
1099{
1100    Mutex::Autolock _l(mLock);
1101    mActive = false;
1102    mExit = true;
1103    mCondition.wait(mLock);
1104}
1105
1106int Antagonizer::callbackThread(void* user)
1107{
1108    LOGD("Antagonizer started");
1109    Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1110    while (!p->mExit) {
1111        if (p->mActive) {
1112            LOGV("send event");
1113            p->mCb(p->mClient, 0, 0, 0);
1114        }
1115        usleep(interval);
1116    }
1117    Mutex::Autolock _l(p->mLock);
1118    p->mCondition.signal();
1119    LOGD("Antagonizer stopped");
1120    return 0;
1121}
1122#endif
1123
1124static size_t kDefaultHeapSize = 1024 * 1024; // 1MB
1125
1126sp<IMemory> MediaPlayerService::decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1127{
1128    LOGV("decode(%s)", url);
1129    sp<MemoryBase> mem;
1130    sp<MediaPlayerBase> player;
1131
1132    // Protect our precious, precious DRMd ringtones by only allowing
1133    // decoding of http, but not filesystem paths or content Uris.
1134    // If the application wants to decode those, it should open a
1135    // filedescriptor for them and use that.
1136    if (url != NULL && strncmp(url, "http://", 7) != 0) {
1137        LOGD("Can't decode %s by path, use filedescriptor instead", url);
1138        return mem;
1139    }
1140
1141    player_type playerType = getPlayerType(url);
1142    LOGV("player type = %d", playerType);
1143
1144    // create the right type of player
1145    sp<AudioCache> cache = new AudioCache(url);
1146    player = android::createPlayer(playerType, cache.get(), cache->notify);
1147    if (player == NULL) goto Exit;
1148    if (player->hardwareOutput()) goto Exit;
1149
1150    static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1151
1152    // set data source
1153    if (player->setDataSource(url) != NO_ERROR) goto Exit;
1154
1155    LOGV("prepare");
1156    player->prepareAsync();
1157
1158    LOGV("wait for prepare");
1159    if (cache->wait() != NO_ERROR) goto Exit;
1160
1161    LOGV("start");
1162    player->start();
1163
1164    LOGV("wait for playback complete");
1165    if (cache->wait() != NO_ERROR) goto Exit;
1166
1167    mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1168    *pSampleRate = cache->sampleRate();
1169    *pNumChannels = cache->channelCount();
1170    *pFormat = (int)cache->format();
1171    LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1172
1173Exit:
1174    if (player != 0) player->reset();
1175    return mem;
1176}
1177
1178sp<IMemory> MediaPlayerService::decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1179{
1180    LOGV("decode(%d, %lld, %lld)", fd, offset, length);
1181    sp<MemoryBase> mem;
1182    sp<MediaPlayerBase> player;
1183
1184    player_type playerType = getPlayerType(fd, offset, length);
1185    LOGV("player type = %d", playerType);
1186
1187    // create the right type of player
1188    sp<AudioCache> cache = new AudioCache("decode_fd");
1189    player = android::createPlayer(playerType, cache.get(), cache->notify);
1190    if (player == NULL) goto Exit;
1191    if (player->hardwareOutput()) goto Exit;
1192
1193    static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1194
1195    // set data source
1196    if (player->setDataSource(fd, offset, length) != NO_ERROR) goto Exit;
1197
1198    LOGV("prepare");
1199    player->prepareAsync();
1200
1201    LOGV("wait for prepare");
1202    if (cache->wait() != NO_ERROR) goto Exit;
1203
1204    LOGV("start");
1205    player->start();
1206
1207    LOGV("wait for playback complete");
1208    if (cache->wait() != NO_ERROR) goto Exit;
1209
1210    mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1211    *pSampleRate = cache->sampleRate();
1212    *pNumChannels = cache->channelCount();
1213    *pFormat = cache->format();
1214    LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1215
1216Exit:
1217    if (player != 0) player->reset();
1218    ::close(fd);
1219    return mem;
1220}
1221
1222
1223#undef LOG_TAG
1224#define LOG_TAG "AudioSink"
1225MediaPlayerService::AudioOutput::AudioOutput(int sessionId)
1226    : mCallback(NULL),
1227      mCallbackCookie(NULL),
1228      mSessionId(sessionId) {
1229    LOGV("AudioOutput(%d)", sessionId);
1230    mTrack = 0;
1231    mStreamType = AUDIO_STREAM_MUSIC;
1232    mLeftVolume = 1.0;
1233    mRightVolume = 1.0;
1234    mLatency = 0;
1235    mMsecsPerFrame = 0;
1236    mAuxEffectId = 0;
1237    mSendLevel = 0.0;
1238    setMinBufferCount();
1239}
1240
1241MediaPlayerService::AudioOutput::~AudioOutput()
1242{
1243    close();
1244}
1245
1246void MediaPlayerService::AudioOutput::setMinBufferCount()
1247{
1248    char value[PROPERTY_VALUE_MAX];
1249    if (property_get("ro.kernel.qemu", value, 0)) {
1250        mIsOnEmulator = true;
1251        mMinBufferCount = 12;  // to prevent systematic buffer underrun for emulator
1252    }
1253}
1254
1255bool MediaPlayerService::AudioOutput::isOnEmulator()
1256{
1257    setMinBufferCount();
1258    return mIsOnEmulator;
1259}
1260
1261int MediaPlayerService::AudioOutput::getMinBufferCount()
1262{
1263    setMinBufferCount();
1264    return mMinBufferCount;
1265}
1266
1267ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1268{
1269    if (mTrack == 0) return NO_INIT;
1270    return mTrack->frameCount() * frameSize();
1271}
1272
1273ssize_t MediaPlayerService::AudioOutput::frameCount() const
1274{
1275    if (mTrack == 0) return NO_INIT;
1276    return mTrack->frameCount();
1277}
1278
1279ssize_t MediaPlayerService::AudioOutput::channelCount() const
1280{
1281    if (mTrack == 0) return NO_INIT;
1282    return mTrack->channelCount();
1283}
1284
1285ssize_t MediaPlayerService::AudioOutput::frameSize() const
1286{
1287    if (mTrack == 0) return NO_INIT;
1288    return mTrack->frameSize();
1289}
1290
1291uint32_t MediaPlayerService::AudioOutput::latency () const
1292{
1293    return mLatency;
1294}
1295
1296float MediaPlayerService::AudioOutput::msecsPerFrame() const
1297{
1298    return mMsecsPerFrame;
1299}
1300
1301status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position)
1302{
1303    if (mTrack == 0) return NO_INIT;
1304    return mTrack->getPosition(position);
1305}
1306
1307status_t MediaPlayerService::AudioOutput::open(
1308        uint32_t sampleRate, int channelCount, int format, int bufferCount,
1309        AudioCallback cb, void *cookie)
1310{
1311    mCallback = cb;
1312    mCallbackCookie = cookie;
1313
1314    // Check argument "bufferCount" against the mininum buffer count
1315    if (bufferCount < mMinBufferCount) {
1316        LOGD("bufferCount (%d) is too small and increased to %d", bufferCount, mMinBufferCount);
1317        bufferCount = mMinBufferCount;
1318
1319    }
1320    LOGV("open(%u, %d, %d, %d, %d)", sampleRate, channelCount, format, bufferCount,mSessionId);
1321    if (mTrack) close();
1322    int afSampleRate;
1323    int afFrameCount;
1324    int frameCount;
1325
1326    if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1327        return NO_INIT;
1328    }
1329    if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1330        return NO_INIT;
1331    }
1332
1333    frameCount = (sampleRate*afFrameCount*bufferCount)/afSampleRate;
1334
1335    AudioTrack *t;
1336    if (mCallback != NULL) {
1337        t = new AudioTrack(
1338                mStreamType,
1339                sampleRate,
1340                format,
1341                (channelCount == 2) ? AUDIO_CHANNEL_OUT_STEREO : AUDIO_CHANNEL_OUT_MONO,
1342                frameCount,
1343                0 /* flags */,
1344                CallbackWrapper,
1345                this,
1346                0,
1347                mSessionId);
1348    } else {
1349        t = new AudioTrack(
1350                mStreamType,
1351                sampleRate,
1352                format,
1353                (channelCount == 2) ? AUDIO_CHANNEL_OUT_STEREO : AUDIO_CHANNEL_OUT_MONO,
1354                frameCount,
1355                0,
1356                NULL,
1357                NULL,
1358                0,
1359                mSessionId);
1360    }
1361
1362    if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1363        LOGE("Unable to create audio track");
1364        delete t;
1365        return NO_INIT;
1366    }
1367
1368    LOGV("setVolume");
1369    t->setVolume(mLeftVolume, mRightVolume);
1370
1371    mMsecsPerFrame = 1.e3 / (float) sampleRate;
1372    mLatency = t->latency();
1373    mTrack = t;
1374
1375    t->setAuxEffectSendLevel(mSendLevel);
1376    return t->attachAuxEffect(mAuxEffectId);;
1377}
1378
1379void MediaPlayerService::AudioOutput::start()
1380{
1381    LOGV("start");
1382    if (mTrack) {
1383        mTrack->setVolume(mLeftVolume, mRightVolume);
1384        mTrack->setAuxEffectSendLevel(mSendLevel);
1385        mTrack->start();
1386    }
1387}
1388
1389
1390
1391ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size)
1392{
1393    LOG_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
1394
1395    //LOGV("write(%p, %u)", buffer, size);
1396    if (mTrack) {
1397        ssize_t ret = mTrack->write(buffer, size);
1398        return ret;
1399    }
1400    return NO_INIT;
1401}
1402
1403void MediaPlayerService::AudioOutput::stop()
1404{
1405    LOGV("stop");
1406    if (mTrack) mTrack->stop();
1407}
1408
1409void MediaPlayerService::AudioOutput::flush()
1410{
1411    LOGV("flush");
1412    if (mTrack) mTrack->flush();
1413}
1414
1415void MediaPlayerService::AudioOutput::pause()
1416{
1417    LOGV("pause");
1418    if (mTrack) mTrack->pause();
1419}
1420
1421void MediaPlayerService::AudioOutput::close()
1422{
1423    LOGV("close");
1424    delete mTrack;
1425    mTrack = 0;
1426}
1427
1428void MediaPlayerService::AudioOutput::setVolume(float left, float right)
1429{
1430    LOGV("setVolume(%f, %f)", left, right);
1431    mLeftVolume = left;
1432    mRightVolume = right;
1433    if (mTrack) {
1434        mTrack->setVolume(left, right);
1435    }
1436}
1437
1438status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
1439{
1440    LOGV("setAuxEffectSendLevel(%f)", level);
1441    mSendLevel = level;
1442    if (mTrack) {
1443        return mTrack->setAuxEffectSendLevel(level);
1444    }
1445    return NO_ERROR;
1446}
1447
1448status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
1449{
1450    LOGV("attachAuxEffect(%d)", effectId);
1451    mAuxEffectId = effectId;
1452    if (mTrack) {
1453        return mTrack->attachAuxEffect(effectId);
1454    }
1455    return NO_ERROR;
1456}
1457
1458// static
1459void MediaPlayerService::AudioOutput::CallbackWrapper(
1460        int event, void *cookie, void *info) {
1461    //LOGV("callbackwrapper");
1462    if (event != AudioTrack::EVENT_MORE_DATA) {
1463        return;
1464    }
1465
1466    AudioOutput *me = (AudioOutput *)cookie;
1467    AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
1468
1469    size_t actualSize = (*me->mCallback)(
1470            me, buffer->raw, buffer->size, me->mCallbackCookie);
1471
1472    if (actualSize == 0 && buffer->size > 0) {
1473        // We've reached EOS but the audio track is not stopped yet,
1474        // keep playing silence.
1475
1476        memset(buffer->raw, 0, buffer->size);
1477        actualSize = buffer->size;
1478    }
1479
1480    buffer->size = actualSize;
1481}
1482
1483int MediaPlayerService::AudioOutput::getSessionId()
1484{
1485    return mSessionId;
1486}
1487
1488#undef LOG_TAG
1489#define LOG_TAG "AudioCache"
1490MediaPlayerService::AudioCache::AudioCache(const char* name) :
1491    mChannelCount(0), mFrameCount(1024), mSampleRate(0), mSize(0),
1492    mError(NO_ERROR), mCommandComplete(false)
1493{
1494    // create ashmem heap
1495    mHeap = new MemoryHeapBase(kDefaultHeapSize, 0, name);
1496}
1497
1498uint32_t MediaPlayerService::AudioCache::latency () const
1499{
1500    return 0;
1501}
1502
1503float MediaPlayerService::AudioCache::msecsPerFrame() const
1504{
1505    return mMsecsPerFrame;
1506}
1507
1508status_t MediaPlayerService::AudioCache::getPosition(uint32_t *position)
1509{
1510    if (position == 0) return BAD_VALUE;
1511    *position = mSize;
1512    return NO_ERROR;
1513}
1514
1515////////////////////////////////////////////////////////////////////////////////
1516
1517struct CallbackThread : public Thread {
1518    CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
1519                   MediaPlayerBase::AudioSink::AudioCallback cb,
1520                   void *cookie);
1521
1522protected:
1523    virtual ~CallbackThread();
1524
1525    virtual bool threadLoop();
1526
1527private:
1528    wp<MediaPlayerBase::AudioSink> mSink;
1529    MediaPlayerBase::AudioSink::AudioCallback mCallback;
1530    void *mCookie;
1531    void *mBuffer;
1532    size_t mBufferSize;
1533
1534    CallbackThread(const CallbackThread &);
1535    CallbackThread &operator=(const CallbackThread &);
1536};
1537
1538CallbackThread::CallbackThread(
1539        const wp<MediaPlayerBase::AudioSink> &sink,
1540        MediaPlayerBase::AudioSink::AudioCallback cb,
1541        void *cookie)
1542    : mSink(sink),
1543      mCallback(cb),
1544      mCookie(cookie),
1545      mBuffer(NULL),
1546      mBufferSize(0) {
1547}
1548
1549CallbackThread::~CallbackThread() {
1550    if (mBuffer) {
1551        free(mBuffer);
1552        mBuffer = NULL;
1553    }
1554}
1555
1556bool CallbackThread::threadLoop() {
1557    sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
1558    if (sink == NULL) {
1559        return false;
1560    }
1561
1562    if (mBuffer == NULL) {
1563        mBufferSize = sink->bufferSize();
1564        mBuffer = malloc(mBufferSize);
1565    }
1566
1567    size_t actualSize =
1568        (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie);
1569
1570    if (actualSize > 0) {
1571        sink->write(mBuffer, actualSize);
1572    }
1573
1574    return true;
1575}
1576
1577////////////////////////////////////////////////////////////////////////////////
1578
1579status_t MediaPlayerService::AudioCache::open(
1580        uint32_t sampleRate, int channelCount, int format, int bufferCount,
1581        AudioCallback cb, void *cookie)
1582{
1583    LOGV("open(%u, %d, %d, %d)", sampleRate, channelCount, format, bufferCount);
1584    if (mHeap->getHeapID() < 0) {
1585        return NO_INIT;
1586    }
1587
1588    mSampleRate = sampleRate;
1589    mChannelCount = (uint16_t)channelCount;
1590    mFormat = (uint16_t)format;
1591    mMsecsPerFrame = 1.e3 / (float) sampleRate;
1592
1593    if (cb != NULL) {
1594        mCallbackThread = new CallbackThread(this, cb, cookie);
1595    }
1596    return NO_ERROR;
1597}
1598
1599void MediaPlayerService::AudioCache::start() {
1600    if (mCallbackThread != NULL) {
1601        mCallbackThread->run("AudioCache callback");
1602    }
1603}
1604
1605void MediaPlayerService::AudioCache::stop() {
1606    if (mCallbackThread != NULL) {
1607        mCallbackThread->requestExitAndWait();
1608    }
1609}
1610
1611ssize_t MediaPlayerService::AudioCache::write(const void* buffer, size_t size)
1612{
1613    LOGV("write(%p, %u)", buffer, size);
1614    if ((buffer == 0) || (size == 0)) return size;
1615
1616    uint8_t* p = static_cast<uint8_t*>(mHeap->getBase());
1617    if (p == NULL) return NO_INIT;
1618    p += mSize;
1619    LOGV("memcpy(%p, %p, %u)", p, buffer, size);
1620    if (mSize + size > mHeap->getSize()) {
1621        LOGE("Heap size overflow! req size: %d, max size: %d", (mSize + size), mHeap->getSize());
1622        size = mHeap->getSize() - mSize;
1623    }
1624    memcpy(p, buffer, size);
1625    mSize += size;
1626    return size;
1627}
1628
1629// call with lock held
1630status_t MediaPlayerService::AudioCache::wait()
1631{
1632    Mutex::Autolock lock(mLock);
1633    while (!mCommandComplete) {
1634        mSignal.wait(mLock);
1635    }
1636    mCommandComplete = false;
1637
1638    if (mError == NO_ERROR) {
1639        LOGV("wait - success");
1640    } else {
1641        LOGV("wait - error");
1642    }
1643    return mError;
1644}
1645
1646void MediaPlayerService::AudioCache::notify(
1647        void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
1648{
1649    LOGV("notify(%p, %d, %d, %d)", cookie, msg, ext1, ext2);
1650    AudioCache* p = static_cast<AudioCache*>(cookie);
1651
1652    // ignore buffering messages
1653    switch (msg)
1654    {
1655    case MEDIA_ERROR:
1656        LOGE("Error %d, %d occurred", ext1, ext2);
1657        p->mError = ext1;
1658        break;
1659    case MEDIA_PREPARED:
1660        LOGV("prepared");
1661        break;
1662    case MEDIA_PLAYBACK_COMPLETE:
1663        LOGV("playback complete");
1664        break;
1665    default:
1666        LOGV("ignored");
1667        return;
1668    }
1669
1670    // wake up thread
1671    Mutex::Autolock lock(p->mLock);
1672    p->mCommandComplete = true;
1673    p->mSignal.signal();
1674}
1675
1676int MediaPlayerService::AudioCache::getSessionId()
1677{
1678    return 0;
1679}
1680
1681void MediaPlayerService::addBatteryData(uint32_t params)
1682{
1683    Mutex::Autolock lock(mLock);
1684
1685    int32_t time = systemTime() / 1000000L;
1686
1687    // change audio output devices. This notification comes from AudioFlinger
1688    if ((params & kBatteryDataSpeakerOn)
1689            || (params & kBatteryDataOtherAudioDeviceOn)) {
1690
1691        int deviceOn[NUM_AUDIO_DEVICES];
1692        for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1693            deviceOn[i] = 0;
1694        }
1695
1696        if ((params & kBatteryDataSpeakerOn)
1697                && (params & kBatteryDataOtherAudioDeviceOn)) {
1698            deviceOn[SPEAKER_AND_OTHER] = 1;
1699        } else if (params & kBatteryDataSpeakerOn) {
1700            deviceOn[SPEAKER] = 1;
1701        } else {
1702            deviceOn[OTHER_AUDIO_DEVICE] = 1;
1703        }
1704
1705        for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1706            if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
1707
1708                if (mBatteryAudio.refCount > 0) { // if playing audio
1709                    if (!deviceOn[i]) {
1710                        mBatteryAudio.lastTime[i] += time;
1711                        mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
1712                        mBatteryAudio.lastTime[i] = 0;
1713                    } else {
1714                        mBatteryAudio.lastTime[i] = 0 - time;
1715                    }
1716                }
1717
1718                mBatteryAudio.deviceOn[i] = deviceOn[i];
1719            }
1720        }
1721        return;
1722    }
1723
1724    // an sudio stream is started
1725    if (params & kBatteryDataAudioFlingerStart) {
1726        // record the start time only if currently no other audio
1727        // is being played
1728        if (mBatteryAudio.refCount == 0) {
1729            for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1730                if (mBatteryAudio.deviceOn[i]) {
1731                    mBatteryAudio.lastTime[i] -= time;
1732                }
1733            }
1734        }
1735
1736        mBatteryAudio.refCount ++;
1737        return;
1738
1739    } else if (params & kBatteryDataAudioFlingerStop) {
1740        if (mBatteryAudio.refCount <= 0) {
1741            LOGW("Battery track warning: refCount is <= 0");
1742            return;
1743        }
1744
1745        // record the stop time only if currently this is the only
1746        // audio being played
1747        if (mBatteryAudio.refCount == 1) {
1748            for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1749                if (mBatteryAudio.deviceOn[i]) {
1750                    mBatteryAudio.lastTime[i] += time;
1751                    mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
1752                    mBatteryAudio.lastTime[i] = 0;
1753                }
1754            }
1755        }
1756
1757        mBatteryAudio.refCount --;
1758        return;
1759    }
1760
1761    int uid = IPCThreadState::self()->getCallingUid();
1762    if (uid == AID_MEDIA) {
1763        return;
1764    }
1765    int index = mBatteryData.indexOfKey(uid);
1766
1767    if (index < 0) { // create a new entry for this UID
1768        BatteryUsageInfo info;
1769        info.audioTotalTime = 0;
1770        info.videoTotalTime = 0;
1771        info.audioLastTime = 0;
1772        info.videoLastTime = 0;
1773        info.refCount = 0;
1774
1775        if (mBatteryData.add(uid, info) == NO_MEMORY) {
1776            LOGE("Battery track error: no memory for new app");
1777            return;
1778        }
1779    }
1780
1781    BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
1782
1783    if (params & kBatteryDataCodecStarted) {
1784        if (params & kBatteryDataTrackAudio) {
1785            info.audioLastTime -= time;
1786            info.refCount ++;
1787        }
1788        if (params & kBatteryDataTrackVideo) {
1789            info.videoLastTime -= time;
1790            info.refCount ++;
1791        }
1792    } else {
1793        if (info.refCount == 0) {
1794            LOGW("Battery track warning: refCount is already 0");
1795            return;
1796        } else if (info.refCount < 0) {
1797            LOGE("Battery track error: refCount < 0");
1798            mBatteryData.removeItem(uid);
1799            return;
1800        }
1801
1802        if (params & kBatteryDataTrackAudio) {
1803            info.audioLastTime += time;
1804            info.refCount --;
1805        }
1806        if (params & kBatteryDataTrackVideo) {
1807            info.videoLastTime += time;
1808            info.refCount --;
1809        }
1810
1811        // no stream is being played by this UID
1812        if (info.refCount == 0) {
1813            info.audioTotalTime += info.audioLastTime;
1814            info.audioLastTime = 0;
1815            info.videoTotalTime += info.videoLastTime;
1816            info.videoLastTime = 0;
1817        }
1818    }
1819}
1820
1821status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
1822    Mutex::Autolock lock(mLock);
1823
1824    // audio output devices usage
1825    int32_t time = systemTime() / 1000000L; //in ms
1826    int32_t totalTime;
1827
1828    for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1829        totalTime = mBatteryAudio.totalTime[i];
1830
1831        if (mBatteryAudio.deviceOn[i]
1832            && (mBatteryAudio.lastTime[i] != 0)) {
1833                int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
1834                totalTime += tmpTime;
1835        }
1836
1837        reply->writeInt32(totalTime);
1838        // reset the total time
1839        mBatteryAudio.totalTime[i] = 0;
1840   }
1841
1842    // codec usage
1843    BatteryUsageInfo info;
1844    int size = mBatteryData.size();
1845
1846    reply->writeInt32(size);
1847    int i = 0;
1848
1849    while (i < size) {
1850        info = mBatteryData.valueAt(i);
1851
1852        reply->writeInt32(mBatteryData.keyAt(i)); //UID
1853        reply->writeInt32(info.audioTotalTime);
1854        reply->writeInt32(info.videoTotalTime);
1855
1856        info.audioTotalTime = 0;
1857        info.videoTotalTime = 0;
1858
1859        // remove the UID entry where no stream is being played
1860        if (info.refCount <= 0) {
1861            mBatteryData.removeItemsAt(i);
1862            size --;
1863            i --;
1864        }
1865        i++;
1866    }
1867    return NO_ERROR;
1868}
1869} // namespace android
1870