MediaPlayerService.cpp revision b019250df516e094b0cb648851f9a132b045378a
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 <binder/IPCThreadState.h>
38#include <binder/IServiceManager.h>
39#include <binder/MemoryHeapBase.h>
40#include <binder/MemoryBase.h>
41#include <gui/SurfaceTextureClient.h>
42#include <utils/Errors.h>  // for status_t
43#include <utils/String8.h>
44#include <utils/SystemClock.h>
45#include <utils/Vector.h>
46
47#include <media/IRemoteDisplay.h>
48#include <media/IRemoteDisplayClient.h>
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#include <media/stagefright/MediaErrors.h>
56
57#include <system/audio.h>
58
59#include <private/android_filesystem_config.h>
60
61#include "ActivityManager.h"
62#include "MediaRecorderClient.h"
63#include "MediaPlayerService.h"
64#include "MetadataRetrieverClient.h"
65#include "MediaPlayerFactory.h"
66
67#include "MidiFile.h"
68#include "TestPlayerStub.h"
69#include "StagefrightPlayer.h"
70#include "nuplayer/NuPlayerDriver.h"
71
72#include <OMX.h>
73
74#include "Crypto.h"
75#include "RemoteDisplay.h"
76
77namespace {
78using android::media::Metadata;
79using android::status_t;
80using android::OK;
81using android::BAD_VALUE;
82using android::NOT_ENOUGH_DATA;
83using android::Parcel;
84
85// Max number of entries in the filter.
86const int kMaxFilterSize = 64;  // I pulled that out of thin air.
87
88// FIXME: Move all the metadata related function in the Metadata.cpp
89
90
91// Unmarshall a filter from a Parcel.
92// Filter format in a parcel:
93//
94//  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
95// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
96// |                       number of entries (n)                   |
97// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
98// |                       metadata type 1                         |
99// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
100// |                       metadata type 2                         |
101// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
102//  ....
103// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
104// |                       metadata type n                         |
105// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
106//
107// @param p Parcel that should start with a filter.
108// @param[out] filter On exit contains the list of metadata type to be
109//                    filtered.
110// @param[out] status On exit contains the status code to be returned.
111// @return true if the parcel starts with a valid filter.
112bool unmarshallFilter(const Parcel& p,
113                      Metadata::Filter *filter,
114                      status_t *status)
115{
116    int32_t val;
117    if (p.readInt32(&val) != OK)
118    {
119        ALOGE("Failed to read filter's length");
120        *status = NOT_ENOUGH_DATA;
121        return false;
122    }
123
124    if( val > kMaxFilterSize || val < 0)
125    {
126        ALOGE("Invalid filter len %d", val);
127        *status = BAD_VALUE;
128        return false;
129    }
130
131    const size_t num = val;
132
133    filter->clear();
134    filter->setCapacity(num);
135
136    size_t size = num * sizeof(Metadata::Type);
137
138
139    if (p.dataAvail() < size)
140    {
141        ALOGE("Filter too short expected %d but got %d", size, p.dataAvail());
142        *status = NOT_ENOUGH_DATA;
143        return false;
144    }
145
146    const Metadata::Type *data =
147            static_cast<const Metadata::Type*>(p.readInplace(size));
148
149    if (NULL == data)
150    {
151        ALOGE("Filter had no data");
152        *status = BAD_VALUE;
153        return false;
154    }
155
156    // TODO: The stl impl of vector would be more efficient here
157    // because it degenerates into a memcpy on pod types. Try to
158    // replace later or use stl::set.
159    for (size_t i = 0; i < num; ++i)
160    {
161        filter->add(*data);
162        ++data;
163    }
164    *status = OK;
165    return true;
166}
167
168// @param filter Of metadata type.
169// @param val To be searched.
170// @return true if a match was found.
171bool findMetadata(const Metadata::Filter& filter, const int32_t val)
172{
173    // Deal with empty and ANY right away
174    if (filter.isEmpty()) return false;
175    if (filter[0] == Metadata::kAny) return true;
176
177    return filter.indexOf(val) >= 0;
178}
179
180}  // anonymous namespace
181
182
183namespace android {
184
185static bool checkPermission(const char* permissionString) {
186#ifndef HAVE_ANDROID_OS
187    return true;
188#endif
189    if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
190    bool ok = checkCallingPermission(String16(permissionString));
191    if (!ok) ALOGE("Request requires %s", permissionString);
192    return ok;
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    ALOGV("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    MediaPlayerFactory::registerBuiltinFactories();
219}
220
221MediaPlayerService::~MediaPlayerService()
222{
223    ALOGV("MediaPlayerService destroyed");
224}
225
226sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(pid_t pid)
227{
228    sp<MediaRecorderClient> recorder = new MediaRecorderClient(this, pid);
229    wp<MediaRecorderClient> w = recorder;
230    Mutex::Autolock lock(mLock);
231    mMediaRecorderClients.add(w);
232    ALOGV("Create new media recorder client from pid %d", pid);
233    return recorder;
234}
235
236void MediaPlayerService::removeMediaRecorderClient(wp<MediaRecorderClient> client)
237{
238    Mutex::Autolock lock(mLock);
239    mMediaRecorderClients.remove(client);
240    ALOGV("Delete media recorder client");
241}
242
243sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever(pid_t pid)
244{
245    sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
246    ALOGV("Create new media retriever from pid %d", pid);
247    return retriever;
248}
249
250sp<IMediaPlayer> MediaPlayerService::create(pid_t pid, const sp<IMediaPlayerClient>& client,
251        int audioSessionId)
252{
253    int32_t connId = android_atomic_inc(&mNextConnId);
254
255    sp<Client> c = new Client(
256            this, pid, connId, client, audioSessionId,
257            IPCThreadState::self()->getCallingUid());
258
259    ALOGV("Create new client(%d) from pid %d, uid %d, ", connId, pid,
260         IPCThreadState::self()->getCallingUid());
261
262    wp<Client> w = c;
263    {
264        Mutex::Autolock lock(mLock);
265        mClients.add(w);
266    }
267    return c;
268}
269
270sp<IOMX> MediaPlayerService::getOMX() {
271    Mutex::Autolock autoLock(mLock);
272
273    if (mOMX.get() == NULL) {
274        mOMX = new OMX;
275    }
276
277    return mOMX;
278}
279
280sp<ICrypto> MediaPlayerService::makeCrypto() {
281    return new Crypto;
282}
283
284sp<IRemoteDisplay> MediaPlayerService::listenForRemoteDisplay(
285        const sp<IRemoteDisplayClient>& client, const String8& iface) {
286    if (!checkPermission("android.permission.CONTROL_WIFI_DISPLAY")) {
287        return NULL;
288    }
289
290    return new RemoteDisplay(client, iface.string());
291}
292
293// TODO: delete this method
294status_t MediaPlayerService::enableRemoteDisplay(const char *iface) {
295    if (!checkPermission("android.permission.CONTROL_WIFI_DISPLAY")) {
296        return PERMISSION_DENIED;
297    }
298
299    Mutex::Autolock autoLock(mLock);
300
301    if (iface != NULL) {
302        if (mRemoteDisplay != NULL) {
303            return INVALID_OPERATION;
304        }
305
306        mRemoteDisplay = new RemoteDisplay(NULL /* client */, iface);
307        return OK;
308    }
309
310    if (mRemoteDisplay != NULL) {
311        mRemoteDisplay->dispose();
312        mRemoteDisplay.clear();
313    }
314
315    return OK;
316}
317
318status_t MediaPlayerService::AudioCache::dump(int fd, const Vector<String16>& args) const
319{
320    const size_t SIZE = 256;
321    char buffer[SIZE];
322    String8 result;
323
324    result.append(" AudioCache\n");
325    if (mHeap != 0) {
326        snprintf(buffer, 255, "  heap base(%p), size(%d), flags(%d), device(%s)\n",
327                mHeap->getBase(), mHeap->getSize(), mHeap->getFlags(), mHeap->getDevice());
328        result.append(buffer);
329    }
330    snprintf(buffer, 255, "  msec per frame(%f), channel count(%d), format(%d), frame count(%ld)\n",
331            mMsecsPerFrame, mChannelCount, mFormat, mFrameCount);
332    result.append(buffer);
333    snprintf(buffer, 255, "  sample rate(%d), size(%d), error(%d), command complete(%s)\n",
334            mSampleRate, mSize, mError, mCommandComplete?"true":"false");
335    result.append(buffer);
336    ::write(fd, result.string(), result.size());
337    return NO_ERROR;
338}
339
340status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
341{
342    const size_t SIZE = 256;
343    char buffer[SIZE];
344    String8 result;
345
346    result.append(" AudioOutput\n");
347    snprintf(buffer, 255, "  stream type(%d), left - right volume(%f, %f)\n",
348            mStreamType, mLeftVolume, mRightVolume);
349    result.append(buffer);
350    snprintf(buffer, 255, "  msec per frame(%f), latency (%d)\n",
351            mMsecsPerFrame, (mTrack != 0) ? mTrack->latency() : -1);
352    result.append(buffer);
353    snprintf(buffer, 255, "  aux effect id(%d), send level (%f)\n",
354            mAuxEffectId, mSendLevel);
355    result.append(buffer);
356
357    ::write(fd, result.string(), result.size());
358    if (mTrack != 0) {
359        mTrack->dump(fd, args);
360    }
361    return NO_ERROR;
362}
363
364status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args) const
365{
366    const size_t SIZE = 256;
367    char buffer[SIZE];
368    String8 result;
369    result.append(" Client\n");
370    snprintf(buffer, 255, "  pid(%d), connId(%d), status(%d), looping(%s)\n",
371            mPid, mConnId, mStatus, mLoop?"true": "false");
372    result.append(buffer);
373    write(fd, result.string(), result.size());
374    if (mPlayer != NULL) {
375        mPlayer->dump(fd, args);
376    }
377    if (mAudioOutput != 0) {
378        mAudioOutput->dump(fd, args);
379    }
380    write(fd, "\n", 1);
381    return NO_ERROR;
382}
383
384status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
385{
386    const size_t SIZE = 256;
387    char buffer[SIZE];
388    String8 result;
389    if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
390        snprintf(buffer, SIZE, "Permission Denial: "
391                "can't dump MediaPlayerService from pid=%d, uid=%d\n",
392                IPCThreadState::self()->getCallingPid(),
393                IPCThreadState::self()->getCallingUid());
394        result.append(buffer);
395    } else {
396        Mutex::Autolock lock(mLock);
397        for (int i = 0, n = mClients.size(); i < n; ++i) {
398            sp<Client> c = mClients[i].promote();
399            if (c != 0) c->dump(fd, args);
400        }
401        if (mMediaRecorderClients.size() == 0) {
402                result.append(" No media recorder client\n\n");
403        } else {
404            for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
405                sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
406                if (c != 0) {
407                    snprintf(buffer, 255, " MediaRecorderClient pid(%d)\n", c->mPid);
408                    result.append(buffer);
409                    write(fd, result.string(), result.size());
410                    result = "\n";
411                    c->dump(fd, args);
412                }
413            }
414        }
415
416        result.append(" Files opened and/or mapped:\n");
417        snprintf(buffer, SIZE, "/proc/%d/maps", gettid());
418        FILE *f = fopen(buffer, "r");
419        if (f) {
420            while (!feof(f)) {
421                fgets(buffer, SIZE, f);
422                if (strstr(buffer, " /storage/") ||
423                    strstr(buffer, " /system/sounds/") ||
424                    strstr(buffer, " /data/") ||
425                    strstr(buffer, " /system/media/")) {
426                    result.append("  ");
427                    result.append(buffer);
428                }
429            }
430            fclose(f);
431        } else {
432            result.append("couldn't open ");
433            result.append(buffer);
434            result.append("\n");
435        }
436
437        snprintf(buffer, SIZE, "/proc/%d/fd", gettid());
438        DIR *d = opendir(buffer);
439        if (d) {
440            struct dirent *ent;
441            while((ent = readdir(d)) != NULL) {
442                if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
443                    snprintf(buffer, SIZE, "/proc/%d/fd/%s", gettid(), ent->d_name);
444                    struct stat s;
445                    if (lstat(buffer, &s) == 0) {
446                        if ((s.st_mode & S_IFMT) == S_IFLNK) {
447                            char linkto[256];
448                            int len = readlink(buffer, linkto, sizeof(linkto));
449                            if(len > 0) {
450                                if(len > 255) {
451                                    linkto[252] = '.';
452                                    linkto[253] = '.';
453                                    linkto[254] = '.';
454                                    linkto[255] = 0;
455                                } else {
456                                    linkto[len] = 0;
457                                }
458                                if (strstr(linkto, "/storage/") == linkto ||
459                                    strstr(linkto, "/system/sounds/") == linkto ||
460                                    strstr(linkto, "/data/") == linkto ||
461                                    strstr(linkto, "/system/media/") == linkto) {
462                                    result.append("  ");
463                                    result.append(buffer);
464                                    result.append(" -> ");
465                                    result.append(linkto);
466                                    result.append("\n");
467                                }
468                            }
469                        } else {
470                            result.append("  unexpected type for ");
471                            result.append(buffer);
472                            result.append("\n");
473                        }
474                    }
475                }
476            }
477            closedir(d);
478        } else {
479            result.append("couldn't open ");
480            result.append(buffer);
481            result.append("\n");
482        }
483
484        bool dumpMem = false;
485        for (size_t i = 0; i < args.size(); i++) {
486            if (args[i] == String16("-m")) {
487                dumpMem = true;
488            }
489        }
490        if (dumpMem) {
491            dumpMemoryAddresses(fd);
492        }
493    }
494    write(fd, result.string(), result.size());
495    return NO_ERROR;
496}
497
498void MediaPlayerService::removeClient(wp<Client> client)
499{
500    Mutex::Autolock lock(mLock);
501    mClients.remove(client);
502}
503
504MediaPlayerService::Client::Client(
505        const sp<MediaPlayerService>& service, pid_t pid,
506        int32_t connId, const sp<IMediaPlayerClient>& client,
507        int audioSessionId, uid_t uid)
508{
509    ALOGV("Client(%d) constructor", connId);
510    mPid = pid;
511    mConnId = connId;
512    mService = service;
513    mClient = client;
514    mLoop = false;
515    mStatus = NO_INIT;
516    mAudioSessionId = audioSessionId;
517    mUID = uid;
518    mRetransmitEndpointValid = false;
519
520#if CALLBACK_ANTAGONIZER
521    ALOGD("create Antagonizer");
522    mAntagonizer = new Antagonizer(notify, this);
523#endif
524}
525
526MediaPlayerService::Client::~Client()
527{
528    ALOGV("Client(%d) destructor pid = %d", mConnId, mPid);
529    mAudioOutput.clear();
530    wp<Client> client(this);
531    disconnect();
532    mService->removeClient(client);
533}
534
535void MediaPlayerService::Client::disconnect()
536{
537    ALOGV("disconnect(%d) from pid %d", mConnId, mPid);
538    // grab local reference and clear main reference to prevent future
539    // access to object
540    sp<MediaPlayerBase> p;
541    {
542        Mutex::Autolock l(mLock);
543        p = mPlayer;
544    }
545    mClient.clear();
546
547    mPlayer.clear();
548
549    // clear the notification to prevent callbacks to dead client
550    // and reset the player. We assume the player will serialize
551    // access to itself if necessary.
552    if (p != 0) {
553        p->setNotifyCallback(0, 0);
554#if CALLBACK_ANTAGONIZER
555        ALOGD("kill Antagonizer");
556        mAntagonizer->kill();
557#endif
558        p->reset();
559    }
560
561    disconnectNativeWindow();
562
563    IPCThreadState::self()->flushCommands();
564}
565
566sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
567{
568    // determine if we have the right player type
569    sp<MediaPlayerBase> p = mPlayer;
570    if ((p != NULL) && (p->playerType() != playerType)) {
571        ALOGV("delete player");
572        p.clear();
573    }
574    if (p == NULL) {
575        p = MediaPlayerFactory::createPlayer(playerType, this, notify);
576    }
577
578    if (p != NULL) {
579        p->setUID(mUID);
580    }
581
582    return p;
583}
584
585sp<MediaPlayerBase> MediaPlayerService::Client::setDataSource_pre(
586        player_type playerType)
587{
588    ALOGV("player type = %d", playerType);
589
590    // create the right type of player
591    sp<MediaPlayerBase> p = createPlayer(playerType);
592    if (p == NULL) {
593        return p;
594    }
595
596    if (!p->hardwareOutput()) {
597        mAudioOutput = new AudioOutput(mAudioSessionId);
598        static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
599    }
600
601    return p;
602}
603
604void MediaPlayerService::Client::setDataSource_post(
605        const sp<MediaPlayerBase>& p,
606        status_t status)
607{
608    ALOGV(" setDataSource");
609    mStatus = status;
610    if (mStatus != OK) {
611        ALOGE("  error: %d", mStatus);
612        return;
613    }
614
615    // Set the re-transmission endpoint if one was chosen.
616    if (mRetransmitEndpointValid) {
617        mStatus = p->setRetransmitEndpoint(&mRetransmitEndpoint);
618        if (mStatus != NO_ERROR) {
619            ALOGE("setRetransmitEndpoint error: %d", mStatus);
620        }
621    }
622
623    if (mStatus == OK) {
624        mPlayer = p;
625    }
626}
627
628status_t MediaPlayerService::Client::setDataSource(
629        const char *url, const KeyedVector<String8, String8> *headers)
630{
631    ALOGV("setDataSource(%s)", url);
632    if (url == NULL)
633        return UNKNOWN_ERROR;
634
635    if ((strncmp(url, "http://", 7) == 0) ||
636        (strncmp(url, "https://", 8) == 0) ||
637        (strncmp(url, "rtsp://", 7) == 0)) {
638        if (!checkPermission("android.permission.INTERNET")) {
639            return PERMISSION_DENIED;
640        }
641    }
642
643    if (strncmp(url, "content://", 10) == 0) {
644        // get a filedescriptor for the content Uri and
645        // pass it to the setDataSource(fd) method
646
647        String16 url16(url);
648        int fd = android::openContentProviderFile(url16);
649        if (fd < 0)
650        {
651            ALOGE("Couldn't open fd for %s", url);
652            return UNKNOWN_ERROR;
653        }
654        setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
655        close(fd);
656        return mStatus;
657    } else {
658        player_type playerType = MediaPlayerFactory::getPlayerType(this, url);
659        sp<MediaPlayerBase> p = setDataSource_pre(playerType);
660        if (p == NULL) {
661            return NO_INIT;
662        }
663
664        setDataSource_post(p, p->setDataSource(url, headers));
665        return mStatus;
666    }
667}
668
669status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
670{
671    ALOGV("setDataSource fd=%d, offset=%lld, length=%lld", fd, offset, length);
672    struct stat sb;
673    int ret = fstat(fd, &sb);
674    if (ret != 0) {
675        ALOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
676        return UNKNOWN_ERROR;
677    }
678
679    ALOGV("st_dev  = %llu", sb.st_dev);
680    ALOGV("st_mode = %u", sb.st_mode);
681    ALOGV("st_uid  = %lu", sb.st_uid);
682    ALOGV("st_gid  = %lu", sb.st_gid);
683    ALOGV("st_size = %llu", sb.st_size);
684
685    if (offset >= sb.st_size) {
686        ALOGE("offset error");
687        ::close(fd);
688        return UNKNOWN_ERROR;
689    }
690    if (offset + length > sb.st_size) {
691        length = sb.st_size - offset;
692        ALOGV("calculated length = %lld", length);
693    }
694
695    player_type playerType = MediaPlayerFactory::getPlayerType(this,
696                                                               fd,
697                                                               offset,
698                                                               length);
699    sp<MediaPlayerBase> p = setDataSource_pre(playerType);
700    if (p == NULL) {
701        return NO_INIT;
702    }
703
704    // now set data source
705    setDataSource_post(p, p->setDataSource(fd, offset, length));
706    return mStatus;
707}
708
709status_t MediaPlayerService::Client::setDataSource(
710        const sp<IStreamSource> &source) {
711    // create the right type of player
712    player_type playerType = MediaPlayerFactory::getPlayerType(this, source);
713    sp<MediaPlayerBase> p = setDataSource_pre(playerType);
714    if (p == NULL) {
715        return NO_INIT;
716    }
717
718    // now set data source
719    setDataSource_post(p, p->setDataSource(source));
720    return mStatus;
721}
722
723void MediaPlayerService::Client::disconnectNativeWindow() {
724    if (mConnectedWindow != NULL) {
725        status_t err = native_window_api_disconnect(mConnectedWindow.get(),
726                NATIVE_WINDOW_API_MEDIA);
727
728        if (err != OK) {
729            ALOGW("native_window_api_disconnect returned an error: %s (%d)",
730                    strerror(-err), err);
731        }
732    }
733    mConnectedWindow.clear();
734}
735
736status_t MediaPlayerService::Client::setVideoSurfaceTexture(
737        const sp<ISurfaceTexture>& surfaceTexture)
738{
739    ALOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, surfaceTexture.get());
740    sp<MediaPlayerBase> p = getPlayer();
741    if (p == 0) return UNKNOWN_ERROR;
742
743    sp<IBinder> binder(surfaceTexture == NULL ? NULL :
744            surfaceTexture->asBinder());
745    if (mConnectedWindowBinder == binder) {
746        return OK;
747    }
748
749    sp<ANativeWindow> anw;
750    if (surfaceTexture != NULL) {
751        anw = new SurfaceTextureClient(surfaceTexture);
752        status_t err = native_window_api_connect(anw.get(),
753                NATIVE_WINDOW_API_MEDIA);
754
755        if (err != OK) {
756            ALOGE("setVideoSurfaceTexture failed: %d", err);
757            // Note that we must do the reset before disconnecting from the ANW.
758            // Otherwise queue/dequeue calls could be made on the disconnected
759            // ANW, which may result in errors.
760            reset();
761
762            disconnectNativeWindow();
763
764            return err;
765        }
766    }
767
768    // Note that we must set the player's new SurfaceTexture before
769    // disconnecting the old one.  Otherwise queue/dequeue calls could be made
770    // on the disconnected ANW, which may result in errors.
771    status_t err = p->setVideoSurfaceTexture(surfaceTexture);
772
773    disconnectNativeWindow();
774
775    mConnectedWindow = anw;
776
777    if (err == OK) {
778        mConnectedWindowBinder = binder;
779    } else {
780        disconnectNativeWindow();
781    }
782
783    return err;
784}
785
786status_t MediaPlayerService::Client::invoke(const Parcel& request,
787                                            Parcel *reply)
788{
789    sp<MediaPlayerBase> p = getPlayer();
790    if (p == NULL) return UNKNOWN_ERROR;
791    return p->invoke(request, reply);
792}
793
794// This call doesn't need to access the native player.
795status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
796{
797    status_t status;
798    media::Metadata::Filter allow, drop;
799
800    if (unmarshallFilter(filter, &allow, &status) &&
801        unmarshallFilter(filter, &drop, &status)) {
802        Mutex::Autolock lock(mLock);
803
804        mMetadataAllow = allow;
805        mMetadataDrop = drop;
806    }
807    return status;
808}
809
810status_t MediaPlayerService::Client::getMetadata(
811        bool update_only, bool apply_filter, Parcel *reply)
812{
813    sp<MediaPlayerBase> player = getPlayer();
814    if (player == 0) return UNKNOWN_ERROR;
815
816    status_t status;
817    // Placeholder for the return code, updated by the caller.
818    reply->writeInt32(-1);
819
820    media::Metadata::Filter ids;
821
822    // We don't block notifications while we fetch the data. We clear
823    // mMetadataUpdated first so we don't lose notifications happening
824    // during the rest of this call.
825    {
826        Mutex::Autolock lock(mLock);
827        if (update_only) {
828            ids = mMetadataUpdated;
829        }
830        mMetadataUpdated.clear();
831    }
832
833    media::Metadata metadata(reply);
834
835    metadata.appendHeader();
836    status = player->getMetadata(ids, reply);
837
838    if (status != OK) {
839        metadata.resetParcel();
840        ALOGE("getMetadata failed %d", status);
841        return status;
842    }
843
844    // FIXME: Implement filtering on the result. Not critical since
845    // filtering takes place on the update notifications already. This
846    // would be when all the metadata are fetch and a filter is set.
847
848    // Everything is fine, update the metadata length.
849    metadata.updateLength();
850    return OK;
851}
852
853status_t MediaPlayerService::Client::prepareAsync()
854{
855    ALOGV("[%d] prepareAsync", mConnId);
856    sp<MediaPlayerBase> p = getPlayer();
857    if (p == 0) return UNKNOWN_ERROR;
858    status_t ret = p->prepareAsync();
859#if CALLBACK_ANTAGONIZER
860    ALOGD("start Antagonizer");
861    if (ret == NO_ERROR) mAntagonizer->start();
862#endif
863    return ret;
864}
865
866status_t MediaPlayerService::Client::start()
867{
868    ALOGV("[%d] start", mConnId);
869    sp<MediaPlayerBase> p = getPlayer();
870    if (p == 0) return UNKNOWN_ERROR;
871    p->setLooping(mLoop);
872    return p->start();
873}
874
875status_t MediaPlayerService::Client::stop()
876{
877    ALOGV("[%d] stop", mConnId);
878    sp<MediaPlayerBase> p = getPlayer();
879    if (p == 0) return UNKNOWN_ERROR;
880    return p->stop();
881}
882
883status_t MediaPlayerService::Client::pause()
884{
885    ALOGV("[%d] pause", mConnId);
886    sp<MediaPlayerBase> p = getPlayer();
887    if (p == 0) return UNKNOWN_ERROR;
888    return p->pause();
889}
890
891status_t MediaPlayerService::Client::isPlaying(bool* state)
892{
893    *state = false;
894    sp<MediaPlayerBase> p = getPlayer();
895    if (p == 0) return UNKNOWN_ERROR;
896    *state = p->isPlaying();
897    ALOGV("[%d] isPlaying: %d", mConnId, *state);
898    return NO_ERROR;
899}
900
901status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
902{
903    ALOGV("getCurrentPosition");
904    sp<MediaPlayerBase> p = getPlayer();
905    if (p == 0) return UNKNOWN_ERROR;
906    status_t ret = p->getCurrentPosition(msec);
907    if (ret == NO_ERROR) {
908        ALOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
909    } else {
910        ALOGE("getCurrentPosition returned %d", ret);
911    }
912    return ret;
913}
914
915status_t MediaPlayerService::Client::getDuration(int *msec)
916{
917    ALOGV("getDuration");
918    sp<MediaPlayerBase> p = getPlayer();
919    if (p == 0) return UNKNOWN_ERROR;
920    status_t ret = p->getDuration(msec);
921    if (ret == NO_ERROR) {
922        ALOGV("[%d] getDuration = %d", mConnId, *msec);
923    } else {
924        ALOGE("getDuration returned %d", ret);
925    }
926    return ret;
927}
928
929status_t MediaPlayerService::Client::setNextPlayer(const sp<IMediaPlayer>& player) {
930    ALOGV("setNextPlayer");
931    Mutex::Autolock l(mLock);
932    sp<Client> c = static_cast<Client*>(player.get());
933    mNextClient = c;
934
935    if (c != NULL) {
936        if (mAudioOutput != NULL) {
937            mAudioOutput->setNextOutput(c->mAudioOutput);
938        } else if ((mPlayer != NULL) && !mPlayer->hardwareOutput()) {
939            ALOGE("no current audio output");
940        }
941
942        if ((mPlayer != NULL) && (mNextClient->getPlayer() != NULL)) {
943            mPlayer->setNextPlayer(mNextClient->getPlayer());
944        }
945    }
946
947    return OK;
948}
949
950status_t MediaPlayerService::Client::seekTo(int msec)
951{
952    ALOGV("[%d] seekTo(%d)", mConnId, msec);
953    sp<MediaPlayerBase> p = getPlayer();
954    if (p == 0) return UNKNOWN_ERROR;
955    return p->seekTo(msec);
956}
957
958status_t MediaPlayerService::Client::reset()
959{
960    ALOGV("[%d] reset", mConnId);
961    mRetransmitEndpointValid = false;
962    sp<MediaPlayerBase> p = getPlayer();
963    if (p == 0) return UNKNOWN_ERROR;
964    return p->reset();
965}
966
967status_t MediaPlayerService::Client::setAudioStreamType(audio_stream_type_t type)
968{
969    ALOGV("[%d] setAudioStreamType(%d)", mConnId, type);
970    // TODO: for hardware output, call player instead
971    Mutex::Autolock l(mLock);
972    if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
973    return NO_ERROR;
974}
975
976status_t MediaPlayerService::Client::setLooping(int loop)
977{
978    ALOGV("[%d] setLooping(%d)", mConnId, loop);
979    mLoop = loop;
980    sp<MediaPlayerBase> p = getPlayer();
981    if (p != 0) return p->setLooping(loop);
982    return NO_ERROR;
983}
984
985status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
986{
987    ALOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
988
989    // for hardware output, call player instead
990    sp<MediaPlayerBase> p = getPlayer();
991    {
992      Mutex::Autolock l(mLock);
993      if (p != 0 && p->hardwareOutput()) {
994          MediaPlayerHWInterface* hwp =
995                  reinterpret_cast<MediaPlayerHWInterface*>(p.get());
996          return hwp->setVolume(leftVolume, rightVolume);
997      } else {
998          if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
999          return NO_ERROR;
1000      }
1001    }
1002
1003    return NO_ERROR;
1004}
1005
1006status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1007{
1008    ALOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
1009    Mutex::Autolock l(mLock);
1010    if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1011    return NO_ERROR;
1012}
1013
1014status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1015{
1016    ALOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
1017    Mutex::Autolock l(mLock);
1018    if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1019    return NO_ERROR;
1020}
1021
1022status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
1023    ALOGV("[%d] setParameter(%d)", mConnId, key);
1024    sp<MediaPlayerBase> p = getPlayer();
1025    if (p == 0) return UNKNOWN_ERROR;
1026    return p->setParameter(key, request);
1027}
1028
1029status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
1030    ALOGV("[%d] getParameter(%d)", mConnId, key);
1031    sp<MediaPlayerBase> p = getPlayer();
1032    if (p == 0) return UNKNOWN_ERROR;
1033    return p->getParameter(key, reply);
1034}
1035
1036status_t MediaPlayerService::Client::setRetransmitEndpoint(
1037        const struct sockaddr_in* endpoint) {
1038
1039    if (NULL != endpoint) {
1040        uint32_t a = ntohl(endpoint->sin_addr.s_addr);
1041        uint16_t p = ntohs(endpoint->sin_port);
1042        ALOGV("[%d] setRetransmitEndpoint(%u.%u.%u.%u:%hu)", mConnId,
1043                (a >> 24), (a >> 16) & 0xFF, (a >> 8) & 0xFF, (a & 0xFF), p);
1044    } else {
1045        ALOGV("[%d] setRetransmitEndpoint = <none>", mConnId);
1046    }
1047
1048    sp<MediaPlayerBase> p = getPlayer();
1049
1050    // Right now, the only valid time to set a retransmit endpoint is before
1051    // player selection has been made (since the presence or absence of a
1052    // retransmit endpoint is going to determine which player is selected during
1053    // setDataSource).
1054    if (p != 0) return INVALID_OPERATION;
1055
1056    if (NULL != endpoint) {
1057        mRetransmitEndpoint = *endpoint;
1058        mRetransmitEndpointValid = true;
1059    } else {
1060        mRetransmitEndpointValid = false;
1061    }
1062
1063    return NO_ERROR;
1064}
1065
1066status_t MediaPlayerService::Client::getRetransmitEndpoint(
1067        struct sockaddr_in* endpoint)
1068{
1069    if (NULL == endpoint)
1070        return BAD_VALUE;
1071
1072    sp<MediaPlayerBase> p = getPlayer();
1073
1074    if (p != NULL)
1075        return p->getRetransmitEndpoint(endpoint);
1076
1077    if (!mRetransmitEndpointValid)
1078        return NO_INIT;
1079
1080    *endpoint = mRetransmitEndpoint;
1081
1082    return NO_ERROR;
1083}
1084
1085void MediaPlayerService::Client::notify(
1086        void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
1087{
1088    Client* client = static_cast<Client*>(cookie);
1089    if (client == NULL) {
1090        return;
1091    }
1092
1093    sp<IMediaPlayerClient> c;
1094    {
1095        Mutex::Autolock l(client->mLock);
1096        c = client->mClient;
1097        if (msg == MEDIA_PLAYBACK_COMPLETE && client->mNextClient != NULL) {
1098            if (client->mAudioOutput != NULL)
1099                client->mAudioOutput->switchToNextOutput();
1100            client->mNextClient->start();
1101            client->mNextClient->mClient->notify(MEDIA_INFO, MEDIA_INFO_STARTED_AS_NEXT, 0, obj);
1102        }
1103    }
1104
1105    if (MEDIA_INFO == msg &&
1106        MEDIA_INFO_METADATA_UPDATE == ext1) {
1107        const media::Metadata::Type metadata_type = ext2;
1108
1109        if(client->shouldDropMetadata(metadata_type)) {
1110            return;
1111        }
1112
1113        // Update the list of metadata that have changed. getMetadata
1114        // also access mMetadataUpdated and clears it.
1115        client->addNewMetadataUpdate(metadata_type);
1116    }
1117
1118    if (c != NULL) {
1119        ALOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
1120        c->notify(msg, ext1, ext2, obj);
1121    }
1122}
1123
1124
1125bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
1126{
1127    Mutex::Autolock lock(mLock);
1128
1129    if (findMetadata(mMetadataDrop, code)) {
1130        return true;
1131    }
1132
1133    if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
1134        return false;
1135    } else {
1136        return true;
1137    }
1138}
1139
1140
1141void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
1142    Mutex::Autolock lock(mLock);
1143    if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1144        mMetadataUpdated.add(metadata_type);
1145    }
1146}
1147
1148#if CALLBACK_ANTAGONIZER
1149const int Antagonizer::interval = 10000; // 10 msecs
1150
1151Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1152    mExit(false), mActive(false), mClient(client), mCb(cb)
1153{
1154    createThread(callbackThread, this);
1155}
1156
1157void Antagonizer::kill()
1158{
1159    Mutex::Autolock _l(mLock);
1160    mActive = false;
1161    mExit = true;
1162    mCondition.wait(mLock);
1163}
1164
1165int Antagonizer::callbackThread(void* user)
1166{
1167    ALOGD("Antagonizer started");
1168    Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1169    while (!p->mExit) {
1170        if (p->mActive) {
1171            ALOGV("send event");
1172            p->mCb(p->mClient, 0, 0, 0);
1173        }
1174        usleep(interval);
1175    }
1176    Mutex::Autolock _l(p->mLock);
1177    p->mCondition.signal();
1178    ALOGD("Antagonizer stopped");
1179    return 0;
1180}
1181#endif
1182
1183static size_t kDefaultHeapSize = 1024 * 1024; // 1MB
1184
1185sp<IMemory> MediaPlayerService::decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, audio_format_t* pFormat)
1186{
1187    ALOGV("decode(%s)", url);
1188    sp<MemoryBase> mem;
1189    sp<MediaPlayerBase> player;
1190
1191    // Protect our precious, precious DRMd ringtones by only allowing
1192    // decoding of http, but not filesystem paths or content Uris.
1193    // If the application wants to decode those, it should open a
1194    // filedescriptor for them and use that.
1195    if (url != NULL && strncmp(url, "http://", 7) != 0) {
1196        ALOGD("Can't decode %s by path, use filedescriptor instead", url);
1197        return mem;
1198    }
1199
1200    player_type playerType =
1201        MediaPlayerFactory::getPlayerType(NULL /* client */, url);
1202    ALOGV("player type = %d", playerType);
1203
1204    // create the right type of player
1205    sp<AudioCache> cache = new AudioCache(url);
1206    player = MediaPlayerFactory::createPlayer(playerType, cache.get(), cache->notify);
1207    if (player == NULL) goto Exit;
1208    if (player->hardwareOutput()) goto Exit;
1209
1210    static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1211
1212    // set data source
1213    if (player->setDataSource(url) != NO_ERROR) goto Exit;
1214
1215    ALOGV("prepare");
1216    player->prepareAsync();
1217
1218    ALOGV("wait for prepare");
1219    if (cache->wait() != NO_ERROR) goto Exit;
1220
1221    ALOGV("start");
1222    player->start();
1223
1224    ALOGV("wait for playback complete");
1225    cache->wait();
1226    // in case of error, return what was successfully decoded.
1227    if (cache->size() == 0) {
1228        goto Exit;
1229    }
1230
1231    mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1232    *pSampleRate = cache->sampleRate();
1233    *pNumChannels = cache->channelCount();
1234    *pFormat = cache->format();
1235    ALOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1236
1237Exit:
1238    if (player != 0) player->reset();
1239    return mem;
1240}
1241
1242sp<IMemory> MediaPlayerService::decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, audio_format_t* pFormat)
1243{
1244    ALOGV("decode(%d, %lld, %lld)", fd, offset, length);
1245    sp<MemoryBase> mem;
1246    sp<MediaPlayerBase> player;
1247
1248    player_type playerType = MediaPlayerFactory::getPlayerType(NULL /* client */,
1249                                                               fd,
1250                                                               offset,
1251                                                               length);
1252    ALOGV("player type = %d", playerType);
1253
1254    // create the right type of player
1255    sp<AudioCache> cache = new AudioCache("decode_fd");
1256    player = MediaPlayerFactory::createPlayer(playerType, cache.get(), cache->notify);
1257    if (player == NULL) goto Exit;
1258    if (player->hardwareOutput()) goto Exit;
1259
1260    static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1261
1262    // set data source
1263    if (player->setDataSource(fd, offset, length) != NO_ERROR) goto Exit;
1264
1265    ALOGV("prepare");
1266    player->prepareAsync();
1267
1268    ALOGV("wait for prepare");
1269    if (cache->wait() != NO_ERROR) goto Exit;
1270
1271    ALOGV("start");
1272    player->start();
1273
1274    ALOGV("wait for playback complete");
1275    cache->wait();
1276    // in case of error, return what was successfully decoded.
1277    if (cache->size() == 0) {
1278        goto Exit;
1279    }
1280
1281    mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1282    *pSampleRate = cache->sampleRate();
1283    *pNumChannels = cache->channelCount();
1284    *pFormat = cache->format();
1285    ALOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1286
1287Exit:
1288    if (player != 0) player->reset();
1289    ::close(fd);
1290    return mem;
1291}
1292
1293
1294#undef LOG_TAG
1295#define LOG_TAG "AudioSink"
1296MediaPlayerService::AudioOutput::AudioOutput(int sessionId)
1297    : mCallback(NULL),
1298      mCallbackCookie(NULL),
1299      mCallbackData(NULL),
1300      mBytesWritten(0),
1301      mSessionId(sessionId),
1302      mFlags(AUDIO_OUTPUT_FLAG_NONE) {
1303    ALOGV("AudioOutput(%d)", sessionId);
1304    mTrack = 0;
1305    mRecycledTrack = 0;
1306    mStreamType = AUDIO_STREAM_MUSIC;
1307    mLeftVolume = 1.0;
1308    mRightVolume = 1.0;
1309    mPlaybackRatePermille = 1000;
1310    mSampleRateHz = 0;
1311    mMsecsPerFrame = 0;
1312    mAuxEffectId = 0;
1313    mSendLevel = 0.0;
1314    setMinBufferCount();
1315}
1316
1317MediaPlayerService::AudioOutput::~AudioOutput()
1318{
1319    close();
1320    delete mRecycledTrack;
1321    delete mCallbackData;
1322}
1323
1324void MediaPlayerService::AudioOutput::setMinBufferCount()
1325{
1326    char value[PROPERTY_VALUE_MAX];
1327    if (property_get("ro.kernel.qemu", value, 0)) {
1328        mIsOnEmulator = true;
1329        mMinBufferCount = 12;  // to prevent systematic buffer underrun for emulator
1330    }
1331}
1332
1333bool MediaPlayerService::AudioOutput::isOnEmulator()
1334{
1335    setMinBufferCount();
1336    return mIsOnEmulator;
1337}
1338
1339int MediaPlayerService::AudioOutput::getMinBufferCount()
1340{
1341    setMinBufferCount();
1342    return mMinBufferCount;
1343}
1344
1345ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1346{
1347    if (mTrack == 0) return NO_INIT;
1348    return mTrack->frameCount() * frameSize();
1349}
1350
1351ssize_t MediaPlayerService::AudioOutput::frameCount() const
1352{
1353    if (mTrack == 0) return NO_INIT;
1354    return mTrack->frameCount();
1355}
1356
1357ssize_t MediaPlayerService::AudioOutput::channelCount() const
1358{
1359    if (mTrack == 0) return NO_INIT;
1360    return mTrack->channelCount();
1361}
1362
1363ssize_t MediaPlayerService::AudioOutput::frameSize() const
1364{
1365    if (mTrack == 0) return NO_INIT;
1366    return mTrack->frameSize();
1367}
1368
1369uint32_t MediaPlayerService::AudioOutput::latency () const
1370{
1371    if (mTrack == 0) return 0;
1372    return mTrack->latency();
1373}
1374
1375float MediaPlayerService::AudioOutput::msecsPerFrame() const
1376{
1377    return mMsecsPerFrame;
1378}
1379
1380status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position) const
1381{
1382    if (mTrack == 0) return NO_INIT;
1383    return mTrack->getPosition(position);
1384}
1385
1386status_t MediaPlayerService::AudioOutput::getFramesWritten(uint32_t *frameswritten) const
1387{
1388    if (mTrack == 0) return NO_INIT;
1389    *frameswritten = mBytesWritten / frameSize();
1390    return OK;
1391}
1392
1393status_t MediaPlayerService::AudioOutput::open(
1394        uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
1395        audio_format_t format, int bufferCount,
1396        AudioCallback cb, void *cookie,
1397        audio_output_flags_t flags)
1398{
1399    mCallback = cb;
1400    mCallbackCookie = cookie;
1401
1402    // Check argument "bufferCount" against the mininum buffer count
1403    if (bufferCount < mMinBufferCount) {
1404        ALOGD("bufferCount (%d) is too small and increased to %d", bufferCount, mMinBufferCount);
1405        bufferCount = mMinBufferCount;
1406
1407    }
1408    ALOGV("open(%u, %d, 0x%x, %d, %d, %d)", sampleRate, channelCount, channelMask,
1409            format, bufferCount, mSessionId);
1410    int afSampleRate;
1411    int afFrameCount;
1412    uint32_t frameCount;
1413
1414    if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1415        return NO_INIT;
1416    }
1417    if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1418        return NO_INIT;
1419    }
1420
1421    frameCount = (sampleRate*afFrameCount*bufferCount)/afSampleRate;
1422
1423    if (channelMask == CHANNEL_MASK_USE_CHANNEL_ORDER) {
1424        channelMask = audio_channel_out_mask_from_count(channelCount);
1425        if (0 == channelMask) {
1426            ALOGE("open() error, can\'t derive mask for %d audio channels", channelCount);
1427            return NO_INIT;
1428        }
1429    }
1430
1431    AudioTrack *t;
1432    CallbackData *newcbd = NULL;
1433    if (mCallback != NULL) {
1434        newcbd = new CallbackData(this);
1435        t = new AudioTrack(
1436                mStreamType,
1437                sampleRate,
1438                format,
1439                channelMask,
1440                frameCount,
1441                flags,
1442                CallbackWrapper,
1443                newcbd,
1444                0,  // notification frames
1445                mSessionId);
1446    } else {
1447        t = new AudioTrack(
1448                mStreamType,
1449                sampleRate,
1450                format,
1451                channelMask,
1452                frameCount,
1453                flags,
1454                NULL,
1455                NULL,
1456                0,
1457                mSessionId);
1458    }
1459
1460    if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1461        ALOGE("Unable to create audio track");
1462        delete t;
1463        delete newcbd;
1464        return NO_INIT;
1465    }
1466
1467
1468    if (mRecycledTrack) {
1469        // check if the existing track can be reused as-is, or if a new track needs to be created.
1470
1471        bool reuse = true;
1472        if ((mCallbackData == NULL && mCallback != NULL) ||
1473                (mCallbackData != NULL && mCallback == NULL)) {
1474            // recycled track uses callbacks but the caller wants to use writes, or vice versa
1475            ALOGV("can't chain callback and write");
1476            reuse = false;
1477        } else if ((mRecycledTrack->getSampleRate() != sampleRate) ||
1478                (mRecycledTrack->channelCount() != channelCount) ||
1479                (mRecycledTrack->frameCount() != t->frameCount())) {
1480            ALOGV("samplerate, channelcount or framecount differ: %d/%d Hz, %d/%d ch, %d/%d frames",
1481                  mRecycledTrack->getSampleRate(), sampleRate,
1482                  mRecycledTrack->channelCount(), channelCount,
1483                  mRecycledTrack->frameCount(), t->frameCount());
1484            reuse = false;
1485        } else if (flags != mFlags) {
1486            ALOGV("output flags differ %08x/%08x", flags, mFlags);
1487            reuse = false;
1488        }
1489        if (reuse) {
1490            ALOGV("chaining to next output");
1491            close();
1492            mTrack = mRecycledTrack;
1493            mRecycledTrack = NULL;
1494            if (mCallbackData != NULL) {
1495                mCallbackData->setOutput(this);
1496            }
1497            delete t;
1498            delete newcbd;
1499            return OK;
1500        }
1501
1502        // if we're not going to reuse the track, unblock and flush it
1503        if (mCallbackData != NULL) {
1504            mCallbackData->setOutput(NULL);
1505            mCallbackData->endTrackSwitch();
1506        }
1507        mRecycledTrack->flush();
1508        delete mRecycledTrack;
1509        mRecycledTrack = NULL;
1510        delete mCallbackData;
1511        mCallbackData = NULL;
1512        close();
1513    }
1514
1515    mCallbackData = newcbd;
1516    ALOGV("setVolume");
1517    t->setVolume(mLeftVolume, mRightVolume);
1518
1519    mSampleRateHz = sampleRate;
1520    mFlags = flags;
1521    mMsecsPerFrame = mPlaybackRatePermille / (float) sampleRate;
1522    uint32_t pos;
1523    if (t->getPosition(&pos) == OK) {
1524        mBytesWritten = uint64_t(pos) * t->frameSize();
1525    }
1526    mTrack = t;
1527
1528    status_t res = t->setSampleRate(mPlaybackRatePermille * mSampleRateHz / 1000);
1529    if (res != NO_ERROR) {
1530        return res;
1531    }
1532    t->setAuxEffectSendLevel(mSendLevel);
1533    return t->attachAuxEffect(mAuxEffectId);;
1534}
1535
1536void MediaPlayerService::AudioOutput::start()
1537{
1538    ALOGV("start");
1539    if (mCallbackData != NULL) {
1540        mCallbackData->endTrackSwitch();
1541    }
1542    if (mTrack) {
1543        mTrack->setVolume(mLeftVolume, mRightVolume);
1544        mTrack->setAuxEffectSendLevel(mSendLevel);
1545        mTrack->start();
1546    }
1547}
1548
1549void MediaPlayerService::AudioOutput::setNextOutput(const sp<AudioOutput>& nextOutput) {
1550    mNextOutput = nextOutput;
1551}
1552
1553
1554void MediaPlayerService::AudioOutput::switchToNextOutput() {
1555    ALOGV("switchToNextOutput");
1556    if (mNextOutput != NULL) {
1557        if (mCallbackData != NULL) {
1558            mCallbackData->beginTrackSwitch();
1559        }
1560        delete mNextOutput->mCallbackData;
1561        mNextOutput->mCallbackData = mCallbackData;
1562        mCallbackData = NULL;
1563        mNextOutput->mRecycledTrack = mTrack;
1564        mTrack = NULL;
1565        mNextOutput->mSampleRateHz = mSampleRateHz;
1566        mNextOutput->mMsecsPerFrame = mMsecsPerFrame;
1567        mNextOutput->mBytesWritten = mBytesWritten;
1568        mNextOutput->mFlags = mFlags;
1569    }
1570}
1571
1572ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size)
1573{
1574    LOG_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
1575
1576    //ALOGV("write(%p, %u)", buffer, size);
1577    if (mTrack) {
1578        ssize_t ret = mTrack->write(buffer, size);
1579        mBytesWritten += ret;
1580        return ret;
1581    }
1582    return NO_INIT;
1583}
1584
1585void MediaPlayerService::AudioOutput::stop()
1586{
1587    ALOGV("stop");
1588    if (mTrack) mTrack->stop();
1589}
1590
1591void MediaPlayerService::AudioOutput::flush()
1592{
1593    ALOGV("flush");
1594    if (mTrack) mTrack->flush();
1595}
1596
1597void MediaPlayerService::AudioOutput::pause()
1598{
1599    ALOGV("pause");
1600    if (mTrack) mTrack->pause();
1601}
1602
1603void MediaPlayerService::AudioOutput::close()
1604{
1605    ALOGV("close");
1606    delete mTrack;
1607    mTrack = 0;
1608}
1609
1610void MediaPlayerService::AudioOutput::setVolume(float left, float right)
1611{
1612    ALOGV("setVolume(%f, %f)", left, right);
1613    mLeftVolume = left;
1614    mRightVolume = right;
1615    if (mTrack) {
1616        mTrack->setVolume(left, right);
1617    }
1618}
1619
1620status_t MediaPlayerService::AudioOutput::setPlaybackRatePermille(int32_t ratePermille)
1621{
1622    ALOGV("setPlaybackRatePermille(%d)", ratePermille);
1623    status_t res = NO_ERROR;
1624    if (mTrack) {
1625        res = mTrack->setSampleRate(ratePermille * mSampleRateHz / 1000);
1626    } else {
1627        res = NO_INIT;
1628    }
1629    mPlaybackRatePermille = ratePermille;
1630    if (mSampleRateHz != 0) {
1631        mMsecsPerFrame = mPlaybackRatePermille / (float) mSampleRateHz;
1632    }
1633    return res;
1634}
1635
1636status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
1637{
1638    ALOGV("setAuxEffectSendLevel(%f)", level);
1639    mSendLevel = level;
1640    if (mTrack) {
1641        return mTrack->setAuxEffectSendLevel(level);
1642    }
1643    return NO_ERROR;
1644}
1645
1646status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
1647{
1648    ALOGV("attachAuxEffect(%d)", effectId);
1649    mAuxEffectId = effectId;
1650    if (mTrack) {
1651        return mTrack->attachAuxEffect(effectId);
1652    }
1653    return NO_ERROR;
1654}
1655
1656// static
1657void MediaPlayerService::AudioOutput::CallbackWrapper(
1658        int event, void *cookie, void *info) {
1659    //ALOGV("callbackwrapper");
1660    if (event != AudioTrack::EVENT_MORE_DATA) {
1661        return;
1662    }
1663
1664    CallbackData *data = (CallbackData*)cookie;
1665    data->lock();
1666    AudioOutput *me = data->getOutput();
1667    AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
1668    if (me == NULL) {
1669        // no output set, likely because the track was scheduled to be reused
1670        // by another player, but the format turned out to be incompatible.
1671        data->unlock();
1672        buffer->size = 0;
1673        return;
1674    }
1675
1676    size_t actualSize = (*me->mCallback)(
1677            me, buffer->raw, buffer->size, me->mCallbackCookie);
1678
1679    if (actualSize == 0 && buffer->size > 0 && me->mNextOutput == NULL) {
1680        // We've reached EOS but the audio track is not stopped yet,
1681        // keep playing silence.
1682
1683        memset(buffer->raw, 0, buffer->size);
1684        actualSize = buffer->size;
1685    }
1686
1687    buffer->size = actualSize;
1688    data->unlock();
1689}
1690
1691int MediaPlayerService::AudioOutput::getSessionId() const
1692{
1693    return mSessionId;
1694}
1695
1696#undef LOG_TAG
1697#define LOG_TAG "AudioCache"
1698MediaPlayerService::AudioCache::AudioCache(const char* name) :
1699    mChannelCount(0), mFrameCount(1024), mSampleRate(0), mSize(0),
1700    mError(NO_ERROR), mCommandComplete(false)
1701{
1702    // create ashmem heap
1703    mHeap = new MemoryHeapBase(kDefaultHeapSize, 0, name);
1704}
1705
1706uint32_t MediaPlayerService::AudioCache::latency () const
1707{
1708    return 0;
1709}
1710
1711float MediaPlayerService::AudioCache::msecsPerFrame() const
1712{
1713    return mMsecsPerFrame;
1714}
1715
1716status_t MediaPlayerService::AudioCache::getPosition(uint32_t *position) const
1717{
1718    if (position == 0) return BAD_VALUE;
1719    *position = mSize;
1720    return NO_ERROR;
1721}
1722
1723status_t MediaPlayerService::AudioCache::getFramesWritten(uint32_t *written) const
1724{
1725    if (written == 0) return BAD_VALUE;
1726    *written = mSize;
1727    return NO_ERROR;
1728}
1729
1730////////////////////////////////////////////////////////////////////////////////
1731
1732struct CallbackThread : public Thread {
1733    CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
1734                   MediaPlayerBase::AudioSink::AudioCallback cb,
1735                   void *cookie);
1736
1737protected:
1738    virtual ~CallbackThread();
1739
1740    virtual bool threadLoop();
1741
1742private:
1743    wp<MediaPlayerBase::AudioSink> mSink;
1744    MediaPlayerBase::AudioSink::AudioCallback mCallback;
1745    void *mCookie;
1746    void *mBuffer;
1747    size_t mBufferSize;
1748
1749    CallbackThread(const CallbackThread &);
1750    CallbackThread &operator=(const CallbackThread &);
1751};
1752
1753CallbackThread::CallbackThread(
1754        const wp<MediaPlayerBase::AudioSink> &sink,
1755        MediaPlayerBase::AudioSink::AudioCallback cb,
1756        void *cookie)
1757    : mSink(sink),
1758      mCallback(cb),
1759      mCookie(cookie),
1760      mBuffer(NULL),
1761      mBufferSize(0) {
1762}
1763
1764CallbackThread::~CallbackThread() {
1765    if (mBuffer) {
1766        free(mBuffer);
1767        mBuffer = NULL;
1768    }
1769}
1770
1771bool CallbackThread::threadLoop() {
1772    sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
1773    if (sink == NULL) {
1774        return false;
1775    }
1776
1777    if (mBuffer == NULL) {
1778        mBufferSize = sink->bufferSize();
1779        mBuffer = malloc(mBufferSize);
1780    }
1781
1782    size_t actualSize =
1783        (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie);
1784
1785    if (actualSize > 0) {
1786        sink->write(mBuffer, actualSize);
1787    }
1788
1789    return true;
1790}
1791
1792////////////////////////////////////////////////////////////////////////////////
1793
1794status_t MediaPlayerService::AudioCache::open(
1795        uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
1796        audio_format_t format, int bufferCount,
1797        AudioCallback cb, void *cookie, audio_output_flags_t flags)
1798{
1799    ALOGV("open(%u, %d, 0x%x, %d, %d)", sampleRate, channelCount, channelMask, format, bufferCount);
1800    if (mHeap->getHeapID() < 0) {
1801        return NO_INIT;
1802    }
1803
1804    mSampleRate = sampleRate;
1805    mChannelCount = (uint16_t)channelCount;
1806    mFormat = format;
1807    mMsecsPerFrame = 1.e3 / (float) sampleRate;
1808
1809    if (cb != NULL) {
1810        mCallbackThread = new CallbackThread(this, cb, cookie);
1811    }
1812    return NO_ERROR;
1813}
1814
1815void MediaPlayerService::AudioCache::start() {
1816    if (mCallbackThread != NULL) {
1817        mCallbackThread->run("AudioCache callback");
1818    }
1819}
1820
1821void MediaPlayerService::AudioCache::stop() {
1822    if (mCallbackThread != NULL) {
1823        mCallbackThread->requestExitAndWait();
1824    }
1825}
1826
1827ssize_t MediaPlayerService::AudioCache::write(const void* buffer, size_t size)
1828{
1829    ALOGV("write(%p, %u)", buffer, size);
1830    if ((buffer == 0) || (size == 0)) return size;
1831
1832    uint8_t* p = static_cast<uint8_t*>(mHeap->getBase());
1833    if (p == NULL) return NO_INIT;
1834    p += mSize;
1835    ALOGV("memcpy(%p, %p, %u)", p, buffer, size);
1836    if (mSize + size > mHeap->getSize()) {
1837        ALOGE("Heap size overflow! req size: %d, max size: %d", (mSize + size), mHeap->getSize());
1838        size = mHeap->getSize() - mSize;
1839    }
1840    memcpy(p, buffer, size);
1841    mSize += size;
1842    return size;
1843}
1844
1845// call with lock held
1846status_t MediaPlayerService::AudioCache::wait()
1847{
1848    Mutex::Autolock lock(mLock);
1849    while (!mCommandComplete) {
1850        mSignal.wait(mLock);
1851    }
1852    mCommandComplete = false;
1853
1854    if (mError == NO_ERROR) {
1855        ALOGV("wait - success");
1856    } else {
1857        ALOGV("wait - error");
1858    }
1859    return mError;
1860}
1861
1862void MediaPlayerService::AudioCache::notify(
1863        void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
1864{
1865    ALOGV("notify(%p, %d, %d, %d)", cookie, msg, ext1, ext2);
1866    AudioCache* p = static_cast<AudioCache*>(cookie);
1867
1868    // ignore buffering messages
1869    switch (msg)
1870    {
1871    case MEDIA_ERROR:
1872        ALOGE("Error %d, %d occurred", ext1, ext2);
1873        p->mError = ext1;
1874        break;
1875    case MEDIA_PREPARED:
1876        ALOGV("prepared");
1877        break;
1878    case MEDIA_PLAYBACK_COMPLETE:
1879        ALOGV("playback complete");
1880        break;
1881    default:
1882        ALOGV("ignored");
1883        return;
1884    }
1885
1886    // wake up thread
1887    Mutex::Autolock lock(p->mLock);
1888    p->mCommandComplete = true;
1889    p->mSignal.signal();
1890}
1891
1892int MediaPlayerService::AudioCache::getSessionId() const
1893{
1894    return 0;
1895}
1896
1897void MediaPlayerService::addBatteryData(uint32_t params)
1898{
1899    Mutex::Autolock lock(mLock);
1900
1901    int32_t time = systemTime() / 1000000L;
1902
1903    // change audio output devices. This notification comes from AudioFlinger
1904    if ((params & kBatteryDataSpeakerOn)
1905            || (params & kBatteryDataOtherAudioDeviceOn)) {
1906
1907        int deviceOn[NUM_AUDIO_DEVICES];
1908        for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1909            deviceOn[i] = 0;
1910        }
1911
1912        if ((params & kBatteryDataSpeakerOn)
1913                && (params & kBatteryDataOtherAudioDeviceOn)) {
1914            deviceOn[SPEAKER_AND_OTHER] = 1;
1915        } else if (params & kBatteryDataSpeakerOn) {
1916            deviceOn[SPEAKER] = 1;
1917        } else {
1918            deviceOn[OTHER_AUDIO_DEVICE] = 1;
1919        }
1920
1921        for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1922            if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
1923
1924                if (mBatteryAudio.refCount > 0) { // if playing audio
1925                    if (!deviceOn[i]) {
1926                        mBatteryAudio.lastTime[i] += time;
1927                        mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
1928                        mBatteryAudio.lastTime[i] = 0;
1929                    } else {
1930                        mBatteryAudio.lastTime[i] = 0 - time;
1931                    }
1932                }
1933
1934                mBatteryAudio.deviceOn[i] = deviceOn[i];
1935            }
1936        }
1937        return;
1938    }
1939
1940    // an sudio stream is started
1941    if (params & kBatteryDataAudioFlingerStart) {
1942        // record the start time only if currently no other audio
1943        // is being played
1944        if (mBatteryAudio.refCount == 0) {
1945            for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1946                if (mBatteryAudio.deviceOn[i]) {
1947                    mBatteryAudio.lastTime[i] -= time;
1948                }
1949            }
1950        }
1951
1952        mBatteryAudio.refCount ++;
1953        return;
1954
1955    } else if (params & kBatteryDataAudioFlingerStop) {
1956        if (mBatteryAudio.refCount <= 0) {
1957            ALOGW("Battery track warning: refCount is <= 0");
1958            return;
1959        }
1960
1961        // record the stop time only if currently this is the only
1962        // audio being played
1963        if (mBatteryAudio.refCount == 1) {
1964            for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1965                if (mBatteryAudio.deviceOn[i]) {
1966                    mBatteryAudio.lastTime[i] += time;
1967                    mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
1968                    mBatteryAudio.lastTime[i] = 0;
1969                }
1970            }
1971        }
1972
1973        mBatteryAudio.refCount --;
1974        return;
1975    }
1976
1977    int uid = IPCThreadState::self()->getCallingUid();
1978    if (uid == AID_MEDIA) {
1979        return;
1980    }
1981    int index = mBatteryData.indexOfKey(uid);
1982
1983    if (index < 0) { // create a new entry for this UID
1984        BatteryUsageInfo info;
1985        info.audioTotalTime = 0;
1986        info.videoTotalTime = 0;
1987        info.audioLastTime = 0;
1988        info.videoLastTime = 0;
1989        info.refCount = 0;
1990
1991        if (mBatteryData.add(uid, info) == NO_MEMORY) {
1992            ALOGE("Battery track error: no memory for new app");
1993            return;
1994        }
1995    }
1996
1997    BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
1998
1999    if (params & kBatteryDataCodecStarted) {
2000        if (params & kBatteryDataTrackAudio) {
2001            info.audioLastTime -= time;
2002            info.refCount ++;
2003        }
2004        if (params & kBatteryDataTrackVideo) {
2005            info.videoLastTime -= time;
2006            info.refCount ++;
2007        }
2008    } else {
2009        if (info.refCount == 0) {
2010            ALOGW("Battery track warning: refCount is already 0");
2011            return;
2012        } else if (info.refCount < 0) {
2013            ALOGE("Battery track error: refCount < 0");
2014            mBatteryData.removeItem(uid);
2015            return;
2016        }
2017
2018        if (params & kBatteryDataTrackAudio) {
2019            info.audioLastTime += time;
2020            info.refCount --;
2021        }
2022        if (params & kBatteryDataTrackVideo) {
2023            info.videoLastTime += time;
2024            info.refCount --;
2025        }
2026
2027        // no stream is being played by this UID
2028        if (info.refCount == 0) {
2029            info.audioTotalTime += info.audioLastTime;
2030            info.audioLastTime = 0;
2031            info.videoTotalTime += info.videoLastTime;
2032            info.videoLastTime = 0;
2033        }
2034    }
2035}
2036
2037status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
2038    Mutex::Autolock lock(mLock);
2039
2040    // audio output devices usage
2041    int32_t time = systemTime() / 1000000L; //in ms
2042    int32_t totalTime;
2043
2044    for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2045        totalTime = mBatteryAudio.totalTime[i];
2046
2047        if (mBatteryAudio.deviceOn[i]
2048            && (mBatteryAudio.lastTime[i] != 0)) {
2049                int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
2050                totalTime += tmpTime;
2051        }
2052
2053        reply->writeInt32(totalTime);
2054        // reset the total time
2055        mBatteryAudio.totalTime[i] = 0;
2056   }
2057
2058    // codec usage
2059    BatteryUsageInfo info;
2060    int size = mBatteryData.size();
2061
2062    reply->writeInt32(size);
2063    int i = 0;
2064
2065    while (i < size) {
2066        info = mBatteryData.valueAt(i);
2067
2068        reply->writeInt32(mBatteryData.keyAt(i)); //UID
2069        reply->writeInt32(info.audioTotalTime);
2070        reply->writeInt32(info.videoTotalTime);
2071
2072        info.audioTotalTime = 0;
2073        info.videoTotalTime = 0;
2074
2075        // remove the UID entry where no stream is being played
2076        if (info.refCount <= 0) {
2077            mBatteryData.removeItemsAt(i);
2078            size --;
2079            i --;
2080        }
2081        i++;
2082    }
2083    return NO_ERROR;
2084}
2085} // namespace android
2086