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