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