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