MediaPlayerService.cpp revision 213f490215c2946edc2cc3f589219efe283d6548
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/Timers.h>
46#include <utils/Vector.h>
47
48#include <media/AudioPolicyHelper.h>
49#include <media/IMediaHTTPService.h>
50#include <media/IRemoteDisplay.h>
51#include <media/IRemoteDisplayClient.h>
52#include <media/MediaPlayerInterface.h>
53#include <media/mediarecorder.h>
54#include <media/MediaMetadataRetrieverInterface.h>
55#include <media/Metadata.h>
56#include <media/AudioTrack.h>
57#include <media/MemoryLeakTrackUtil.h>
58#include <media/stagefright/MediaCodecList.h>
59#include <media/stagefright/MediaErrors.h>
60#include <media/stagefright/AudioPlayer.h>
61#include <media/stagefright/Utils.h>
62#include <media/stagefright/foundation/ADebug.h>
63#include <media/stagefright/foundation/ALooperRoster.h>
64#include <mediautils/BatteryNotifier.h>
65
66#include <system/audio.h>
67
68#include <private/android_filesystem_config.h>
69
70#include "ActivityManager.h"
71#include "MediaRecorderClient.h"
72#include "MediaPlayerService.h"
73#include "MetadataRetrieverClient.h"
74#include "MediaPlayerFactory.h"
75
76#include "TestPlayerStub.h"
77#include "StagefrightPlayer.h"
78#include "nuplayer/NuPlayerDriver.h"
79
80#include <OMX.h>
81
82#include "Crypto.h"
83#include "Drm.h"
84#include "HDCP.h"
85#include "HTTPBase.h"
86#include "RemoteDisplay.h"
87
88namespace {
89using android::media::Metadata;
90using android::status_t;
91using android::OK;
92using android::BAD_VALUE;
93using android::NOT_ENOUGH_DATA;
94using android::Parcel;
95
96// Max number of entries in the filter.
97const int kMaxFilterSize = 64;  // I pulled that out of thin air.
98
99// FIXME: Move all the metadata related function in the Metadata.cpp
100
101
102// Unmarshall a filter from a Parcel.
103// Filter format in a parcel:
104//
105//  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
106// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
107// |                       number of entries (n)                   |
108// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
109// |                       metadata type 1                         |
110// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
111// |                       metadata type 2                         |
112// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
113//  ....
114// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
115// |                       metadata type n                         |
116// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
117//
118// @param p Parcel that should start with a filter.
119// @param[out] filter On exit contains the list of metadata type to be
120//                    filtered.
121// @param[out] status On exit contains the status code to be returned.
122// @return true if the parcel starts with a valid filter.
123bool unmarshallFilter(const Parcel& p,
124                      Metadata::Filter *filter,
125                      status_t *status)
126{
127    int32_t val;
128    if (p.readInt32(&val) != OK)
129    {
130        ALOGE("Failed to read filter's length");
131        *status = NOT_ENOUGH_DATA;
132        return false;
133    }
134
135    if( val > kMaxFilterSize || val < 0)
136    {
137        ALOGE("Invalid filter len %d", val);
138        *status = BAD_VALUE;
139        return false;
140    }
141
142    const size_t num = val;
143
144    filter->clear();
145    filter->setCapacity(num);
146
147    size_t size = num * sizeof(Metadata::Type);
148
149
150    if (p.dataAvail() < size)
151    {
152        ALOGE("Filter too short expected %d but got %d", size, p.dataAvail());
153        *status = NOT_ENOUGH_DATA;
154        return false;
155    }
156
157    const Metadata::Type *data =
158            static_cast<const Metadata::Type*>(p.readInplace(size));
159
160    if (NULL == data)
161    {
162        ALOGE("Filter had no data");
163        *status = BAD_VALUE;
164        return false;
165    }
166
167    // TODO: The stl impl of vector would be more efficient here
168    // because it degenerates into a memcpy on pod types. Try to
169    // replace later or use stl::set.
170    for (size_t i = 0; i < num; ++i)
171    {
172        filter->add(*data);
173        ++data;
174    }
175    *status = OK;
176    return true;
177}
178
179// @param filter Of metadata type.
180// @param val To be searched.
181// @return true if a match was found.
182bool findMetadata(const Metadata::Filter& filter, const int32_t val)
183{
184    // Deal with empty and ANY right away
185    if (filter.isEmpty()) return false;
186    if (filter[0] == Metadata::kAny) return true;
187
188    return filter.indexOf(val) >= 0;
189}
190
191}  // anonymous namespace
192
193
194namespace {
195using android::Parcel;
196using android::String16;
197
198// marshalling tag indicating flattened utf16 tags
199// keep in sync with frameworks/base/media/java/android/media/AudioAttributes.java
200const int32_t kAudioAttributesMarshallTagFlattenTags = 1;
201
202// Audio attributes format in a parcel:
203//
204//  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
205// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
206// |                       usage                                   |
207// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
208// |                       content_type                            |
209// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
210// |                       source                                  |
211// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
212// |                       flags                                   |
213// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
214// |                       kAudioAttributesMarshallTagFlattenTags  | // ignore tags if not found
215// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
216// |                       flattened tags in UTF16                 |
217// |                         ...                                   |
218// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
219//
220// @param p Parcel that contains audio attributes.
221// @param[out] attributes On exit points to an initialized audio_attributes_t structure
222// @param[out] status On exit contains the status code to be returned.
223void unmarshallAudioAttributes(const Parcel& parcel, audio_attributes_t *attributes)
224{
225    attributes->usage = (audio_usage_t) parcel.readInt32();
226    attributes->content_type = (audio_content_type_t) parcel.readInt32();
227    attributes->source = (audio_source_t) parcel.readInt32();
228    attributes->flags = (audio_flags_mask_t) parcel.readInt32();
229    const bool hasFlattenedTag = (parcel.readInt32() == kAudioAttributesMarshallTagFlattenTags);
230    if (hasFlattenedTag) {
231        // the tags are UTF16, convert to UTF8
232        String16 tags = parcel.readString16();
233        ssize_t realTagSize = utf16_to_utf8_length(tags.string(), tags.size());
234        if (realTagSize <= 0) {
235            strcpy(attributes->tags, "");
236        } else {
237            // copy the flattened string into the attributes as the destination for the conversion:
238            // copying array size -1, array for tags was calloc'd, no need to NULL-terminate it
239            size_t tagSize = realTagSize > AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 ?
240                    AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 : realTagSize;
241            utf16_to_utf8(tags.string(), tagSize, attributes->tags);
242        }
243    } else {
244        ALOGE("unmarshallAudioAttributes() received unflattened tags, ignoring tag values");
245        strcpy(attributes->tags, "");
246    }
247}
248} // anonymous namespace
249
250
251namespace android {
252
253extern ALooperRoster gLooperRoster;
254
255
256static bool checkPermission(const char* permissionString) {
257    if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
258    bool ok = checkCallingPermission(String16(permissionString));
259    if (!ok) ALOGE("Request requires %s", permissionString);
260    return ok;
261}
262
263// TODO: Find real cause of Audio/Video delay in PV framework and remove this workaround
264/* static */ int MediaPlayerService::AudioOutput::mMinBufferCount = 4;
265/* static */ bool MediaPlayerService::AudioOutput::mIsOnEmulator = false;
266
267void MediaPlayerService::instantiate() {
268    defaultServiceManager()->addService(
269            String16("media.player"), new MediaPlayerService());
270}
271
272MediaPlayerService::MediaPlayerService()
273{
274    ALOGV("MediaPlayerService created");
275    mNextConnId = 1;
276
277    mBatteryAudio.refCount = 0;
278    for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
279        mBatteryAudio.deviceOn[i] = 0;
280        mBatteryAudio.lastTime[i] = 0;
281        mBatteryAudio.totalTime[i] = 0;
282    }
283    // speaker is on by default
284    mBatteryAudio.deviceOn[SPEAKER] = 1;
285
286    // reset battery stats
287    // if the mediaserver has crashed, battery stats could be left
288    // in bad state, reset the state upon service start.
289    BatteryNotifier& notifier(BatteryNotifier::getInstance());
290    notifier.noteResetVideo();
291    notifier.noteResetAudio();
292
293    MediaPlayerFactory::registerBuiltinFactories();
294}
295
296MediaPlayerService::~MediaPlayerService()
297{
298    ALOGV("MediaPlayerService destroyed");
299}
300
301sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(const String16 &opPackageName)
302{
303    pid_t pid = IPCThreadState::self()->getCallingPid();
304    sp<MediaRecorderClient> recorder = new MediaRecorderClient(this, pid, opPackageName);
305    wp<MediaRecorderClient> w = recorder;
306    Mutex::Autolock lock(mLock);
307    mMediaRecorderClients.add(w);
308    ALOGV("Create new media recorder client from pid %d", pid);
309    return recorder;
310}
311
312void MediaPlayerService::removeMediaRecorderClient(wp<MediaRecorderClient> client)
313{
314    Mutex::Autolock lock(mLock);
315    mMediaRecorderClients.remove(client);
316    ALOGV("Delete media recorder client");
317}
318
319sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever()
320{
321    pid_t pid = IPCThreadState::self()->getCallingPid();
322    sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
323    ALOGV("Create new media retriever from pid %d", pid);
324    return retriever;
325}
326
327sp<IMediaPlayer> MediaPlayerService::create(const sp<IMediaPlayerClient>& client,
328        int audioSessionId)
329{
330    pid_t pid = IPCThreadState::self()->getCallingPid();
331    int32_t connId = android_atomic_inc(&mNextConnId);
332
333    sp<Client> c = new Client(
334            this, pid, connId, client, audioSessionId,
335            IPCThreadState::self()->getCallingUid());
336
337    ALOGV("Create new client(%d) from pid %d, uid %d, ", connId, pid,
338         IPCThreadState::self()->getCallingUid());
339
340    wp<Client> w = c;
341    {
342        Mutex::Autolock lock(mLock);
343        mClients.add(w);
344    }
345    return c;
346}
347
348sp<IMediaCodecList> MediaPlayerService::getCodecList() const {
349    return MediaCodecList::getLocalInstance();
350}
351
352sp<IOMX> MediaPlayerService::getOMX() {
353    Mutex::Autolock autoLock(mLock);
354
355    if (mOMX.get() == NULL) {
356        mOMX = new OMX;
357    }
358
359    return mOMX;
360}
361
362sp<ICrypto> MediaPlayerService::makeCrypto() {
363    return new Crypto;
364}
365
366sp<IDrm> MediaPlayerService::makeDrm() {
367    return new Drm;
368}
369
370sp<IHDCP> MediaPlayerService::makeHDCP(bool createEncryptionModule) {
371    return new HDCP(createEncryptionModule);
372}
373
374sp<IRemoteDisplay> MediaPlayerService::listenForRemoteDisplay(
375        const String16 &opPackageName,
376        const sp<IRemoteDisplayClient>& client, const String8& iface) {
377    if (!checkPermission("android.permission.CONTROL_WIFI_DISPLAY")) {
378        return NULL;
379    }
380
381    return new RemoteDisplay(opPackageName, client, iface.string());
382}
383
384status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
385{
386    const size_t SIZE = 256;
387    char buffer[SIZE];
388    String8 result;
389
390    result.append(" AudioOutput\n");
391    snprintf(buffer, 255, "  stream type(%d), left - right volume(%f, %f)\n",
392            mStreamType, mLeftVolume, mRightVolume);
393    result.append(buffer);
394    snprintf(buffer, 255, "  msec per frame(%f), latency (%d)\n",
395            mMsecsPerFrame, (mTrack != 0) ? mTrack->latency() : -1);
396    result.append(buffer);
397    snprintf(buffer, 255, "  aux effect id(%d), send level (%f)\n",
398            mAuxEffectId, mSendLevel);
399    result.append(buffer);
400
401    ::write(fd, result.string(), result.size());
402    if (mTrack != 0) {
403        mTrack->dump(fd, args);
404    }
405    return NO_ERROR;
406}
407
408status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args)
409{
410    const size_t SIZE = 256;
411    char buffer[SIZE];
412    String8 result;
413    result.append(" Client\n");
414    snprintf(buffer, 255, "  pid(%d), connId(%d), status(%d), looping(%s)\n",
415            mPid, mConnId, mStatus, mLoop?"true": "false");
416    result.append(buffer);
417    write(fd, result.string(), result.size());
418    if (mPlayer != NULL) {
419        mPlayer->dump(fd, args);
420    }
421    if (mAudioOutput != 0) {
422        mAudioOutput->dump(fd, args);
423    }
424    write(fd, "\n", 1);
425    return NO_ERROR;
426}
427
428/**
429 * The only arguments this understands right now are -c, -von and -voff,
430 * which are parsed by ALooperRoster::dump()
431 */
432status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
433{
434    const size_t SIZE = 256;
435    char buffer[SIZE];
436    String8 result;
437    SortedVector< sp<Client> > clients; //to serialise the mutex unlock & client destruction.
438    SortedVector< sp<MediaRecorderClient> > mediaRecorderClients;
439
440    if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
441        snprintf(buffer, SIZE, "Permission Denial: "
442                "can't dump MediaPlayerService from pid=%d, uid=%d\n",
443                IPCThreadState::self()->getCallingPid(),
444                IPCThreadState::self()->getCallingUid());
445        result.append(buffer);
446    } else {
447        Mutex::Autolock lock(mLock);
448        for (int i = 0, n = mClients.size(); i < n; ++i) {
449            sp<Client> c = mClients[i].promote();
450            if (c != 0) c->dump(fd, args);
451            clients.add(c);
452        }
453        if (mMediaRecorderClients.size() == 0) {
454                result.append(" No media recorder client\n\n");
455        } else {
456            for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
457                sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
458                if (c != 0) {
459                    snprintf(buffer, 255, " MediaRecorderClient pid(%d)\n", c->mPid);
460                    result.append(buffer);
461                    write(fd, result.string(), result.size());
462                    result = "\n";
463                    c->dump(fd, args);
464                    mediaRecorderClients.add(c);
465                }
466            }
467        }
468
469        result.append(" Files opened and/or mapped:\n");
470        snprintf(buffer, SIZE, "/proc/%d/maps", getpid());
471        FILE *f = fopen(buffer, "r");
472        if (f) {
473            while (!feof(f)) {
474                fgets(buffer, SIZE, f);
475                if (strstr(buffer, " /storage/") ||
476                    strstr(buffer, " /system/sounds/") ||
477                    strstr(buffer, " /data/") ||
478                    strstr(buffer, " /system/media/")) {
479                    result.append("  ");
480                    result.append(buffer);
481                }
482            }
483            fclose(f);
484        } else {
485            result.append("couldn't open ");
486            result.append(buffer);
487            result.append("\n");
488        }
489
490        snprintf(buffer, SIZE, "/proc/%d/fd", getpid());
491        DIR *d = opendir(buffer);
492        if (d) {
493            struct dirent *ent;
494            while((ent = readdir(d)) != NULL) {
495                if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
496                    snprintf(buffer, SIZE, "/proc/%d/fd/%s", getpid(), ent->d_name);
497                    struct stat s;
498                    if (lstat(buffer, &s) == 0) {
499                        if ((s.st_mode & S_IFMT) == S_IFLNK) {
500                            char linkto[256];
501                            int len = readlink(buffer, linkto, sizeof(linkto));
502                            if(len > 0) {
503                                if(len > 255) {
504                                    linkto[252] = '.';
505                                    linkto[253] = '.';
506                                    linkto[254] = '.';
507                                    linkto[255] = 0;
508                                } else {
509                                    linkto[len] = 0;
510                                }
511                                if (strstr(linkto, "/storage/") == linkto ||
512                                    strstr(linkto, "/system/sounds/") == linkto ||
513                                    strstr(linkto, "/data/") == linkto ||
514                                    strstr(linkto, "/system/media/") == linkto) {
515                                    result.append("  ");
516                                    result.append(buffer);
517                                    result.append(" -> ");
518                                    result.append(linkto);
519                                    result.append("\n");
520                                }
521                            }
522                        } else {
523                            result.append("  unexpected type for ");
524                            result.append(buffer);
525                            result.append("\n");
526                        }
527                    }
528                }
529            }
530            closedir(d);
531        } else {
532            result.append("couldn't open ");
533            result.append(buffer);
534            result.append("\n");
535        }
536
537        gLooperRoster.dump(fd, args);
538
539        bool dumpMem = false;
540        for (size_t i = 0; i < args.size(); i++) {
541            if (args[i] == String16("-m")) {
542                dumpMem = true;
543            }
544        }
545        if (dumpMem) {
546            dumpMemoryAddresses(fd);
547        }
548    }
549    write(fd, result.string(), result.size());
550    return NO_ERROR;
551}
552
553void MediaPlayerService::removeClient(wp<Client> client)
554{
555    Mutex::Autolock lock(mLock);
556    mClients.remove(client);
557}
558
559MediaPlayerService::Client::Client(
560        const sp<MediaPlayerService>& service, pid_t pid,
561        int32_t connId, const sp<IMediaPlayerClient>& client,
562        int audioSessionId, uid_t uid)
563{
564    ALOGV("Client(%d) constructor", connId);
565    mPid = pid;
566    mConnId = connId;
567    mService = service;
568    mClient = client;
569    mLoop = false;
570    mStatus = NO_INIT;
571    mAudioSessionId = audioSessionId;
572    mUID = uid;
573    mRetransmitEndpointValid = false;
574    mAudioAttributes = NULL;
575
576#if CALLBACK_ANTAGONIZER
577    ALOGD("create Antagonizer");
578    mAntagonizer = new Antagonizer(notify, this);
579#endif
580}
581
582MediaPlayerService::Client::~Client()
583{
584    ALOGV("Client(%d) destructor pid = %d", mConnId, mPid);
585    mAudioOutput.clear();
586    wp<Client> client(this);
587    disconnect();
588    mService->removeClient(client);
589    if (mAudioAttributes != NULL) {
590        free(mAudioAttributes);
591    }
592}
593
594void MediaPlayerService::Client::disconnect()
595{
596    ALOGV("disconnect(%d) from pid %d", mConnId, mPid);
597    // grab local reference and clear main reference to prevent future
598    // access to object
599    sp<MediaPlayerBase> p;
600    {
601        Mutex::Autolock l(mLock);
602        p = mPlayer;
603        mClient.clear();
604    }
605
606    mPlayer.clear();
607
608    // clear the notification to prevent callbacks to dead client
609    // and reset the player. We assume the player will serialize
610    // access to itself if necessary.
611    if (p != 0) {
612        p->setNotifyCallback(0, 0);
613#if CALLBACK_ANTAGONIZER
614        ALOGD("kill Antagonizer");
615        mAntagonizer->kill();
616#endif
617        p->reset();
618    }
619
620    disconnectNativeWindow();
621
622    IPCThreadState::self()->flushCommands();
623}
624
625sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
626{
627    // determine if we have the right player type
628    sp<MediaPlayerBase> p = mPlayer;
629    if ((p != NULL) && (p->playerType() != playerType)) {
630        ALOGV("delete player");
631        p.clear();
632    }
633    if (p == NULL) {
634        p = MediaPlayerFactory::createPlayer(playerType, this, notify, mPid);
635    }
636
637    if (p != NULL) {
638        p->setUID(mUID);
639    }
640
641    return p;
642}
643
644sp<MediaPlayerBase> MediaPlayerService::Client::setDataSource_pre(
645        player_type playerType)
646{
647    ALOGV("player type = %d", playerType);
648
649    // create the right type of player
650    sp<MediaPlayerBase> p = createPlayer(playerType);
651    if (p == NULL) {
652        return p;
653    }
654
655    if (!p->hardwareOutput()) {
656        Mutex::Autolock l(mLock);
657        mAudioOutput = new AudioOutput(mAudioSessionId, IPCThreadState::self()->getCallingUid(),
658                mPid, mAudioAttributes);
659        static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
660    }
661
662    return p;
663}
664
665void MediaPlayerService::Client::setDataSource_post(
666        const sp<MediaPlayerBase>& p,
667        status_t status)
668{
669    ALOGV(" setDataSource");
670    mStatus = status;
671    if (mStatus != OK) {
672        ALOGE("  error: %d", mStatus);
673        return;
674    }
675
676    // Set the re-transmission endpoint if one was chosen.
677    if (mRetransmitEndpointValid) {
678        mStatus = p->setRetransmitEndpoint(&mRetransmitEndpoint);
679        if (mStatus != NO_ERROR) {
680            ALOGE("setRetransmitEndpoint error: %d", mStatus);
681        }
682    }
683
684    if (mStatus == OK) {
685        mPlayer = p;
686    }
687}
688
689status_t MediaPlayerService::Client::setDataSource(
690        const sp<IMediaHTTPService> &httpService,
691        const char *url,
692        const KeyedVector<String8, String8> *headers)
693{
694    ALOGV("setDataSource(%s)", url);
695    if (url == NULL)
696        return UNKNOWN_ERROR;
697
698    if ((strncmp(url, "http://", 7) == 0) ||
699        (strncmp(url, "https://", 8) == 0) ||
700        (strncmp(url, "rtsp://", 7) == 0)) {
701        if (!checkPermission("android.permission.INTERNET")) {
702            return PERMISSION_DENIED;
703        }
704    }
705
706    if (strncmp(url, "content://", 10) == 0) {
707        // get a filedescriptor for the content Uri and
708        // pass it to the setDataSource(fd) method
709
710        String16 url16(url);
711        int fd = android::openContentProviderFile(url16);
712        if (fd < 0)
713        {
714            ALOGE("Couldn't open fd for %s", url);
715            return UNKNOWN_ERROR;
716        }
717        setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
718        close(fd);
719        return mStatus;
720    } else {
721        player_type playerType = MediaPlayerFactory::getPlayerType(this, url);
722        sp<MediaPlayerBase> p = setDataSource_pre(playerType);
723        if (p == NULL) {
724            return NO_INIT;
725        }
726
727        setDataSource_post(p, p->setDataSource(httpService, url, headers));
728        return mStatus;
729    }
730}
731
732status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
733{
734    ALOGV("setDataSource fd=%d (%s), offset=%lld, length=%lld",
735            fd, nameForFd(fd).c_str(), (long long) offset, (long long) length);
736    struct stat sb;
737    int ret = fstat(fd, &sb);
738    if (ret != 0) {
739        ALOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
740        return UNKNOWN_ERROR;
741    }
742
743    ALOGV("st_dev  = %llu", static_cast<uint64_t>(sb.st_dev));
744    ALOGV("st_mode = %u", sb.st_mode);
745    ALOGV("st_uid  = %lu", static_cast<unsigned long>(sb.st_uid));
746    ALOGV("st_gid  = %lu", static_cast<unsigned long>(sb.st_gid));
747    ALOGV("st_size = %llu", sb.st_size);
748
749    if (offset >= sb.st_size) {
750        ALOGE("offset error");
751        return UNKNOWN_ERROR;
752    }
753    if (offset + length > sb.st_size) {
754        length = sb.st_size - offset;
755        ALOGV("calculated length = %lld", length);
756    }
757
758    player_type playerType = MediaPlayerFactory::getPlayerType(this,
759                                                               fd,
760                                                               offset,
761                                                               length);
762    sp<MediaPlayerBase> p = setDataSource_pre(playerType);
763    if (p == NULL) {
764        return NO_INIT;
765    }
766
767    // now set data source
768    setDataSource_post(p, p->setDataSource(fd, offset, length));
769    return mStatus;
770}
771
772status_t MediaPlayerService::Client::setDataSource(
773        const sp<IStreamSource> &source) {
774    // create the right type of player
775    player_type playerType = MediaPlayerFactory::getPlayerType(this, source);
776    sp<MediaPlayerBase> p = setDataSource_pre(playerType);
777    if (p == NULL) {
778        return NO_INIT;
779    }
780
781    // now set data source
782    setDataSource_post(p, p->setDataSource(source));
783    return mStatus;
784}
785
786status_t MediaPlayerService::Client::setDataSource(
787        const sp<IDataSource> &source) {
788    sp<DataSource> dataSource = DataSource::CreateFromIDataSource(source);
789    player_type playerType = MediaPlayerFactory::getPlayerType(this, dataSource);
790    sp<MediaPlayerBase> p = setDataSource_pre(playerType);
791    if (p == NULL) {
792        return NO_INIT;
793    }
794    // now set data source
795    setDataSource_post(p, p->setDataSource(dataSource));
796    return mStatus;
797}
798
799void MediaPlayerService::Client::disconnectNativeWindow() {
800    if (mConnectedWindow != NULL) {
801        status_t err = native_window_api_disconnect(mConnectedWindow.get(),
802                NATIVE_WINDOW_API_MEDIA);
803
804        if (err != OK) {
805            ALOGW("native_window_api_disconnect returned an error: %s (%d)",
806                    strerror(-err), err);
807        }
808    }
809    mConnectedWindow.clear();
810}
811
812status_t MediaPlayerService::Client::setVideoSurfaceTexture(
813        const sp<IGraphicBufferProducer>& bufferProducer)
814{
815    ALOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, bufferProducer.get());
816    sp<MediaPlayerBase> p = getPlayer();
817    if (p == 0) return UNKNOWN_ERROR;
818
819    sp<IBinder> binder(IInterface::asBinder(bufferProducer));
820    if (mConnectedWindowBinder == binder) {
821        return OK;
822    }
823
824    sp<ANativeWindow> anw;
825    if (bufferProducer != NULL) {
826        anw = new Surface(bufferProducer, true /* controlledByApp */);
827        status_t err = native_window_api_connect(anw.get(),
828                NATIVE_WINDOW_API_MEDIA);
829
830        if (err != OK) {
831            ALOGE("setVideoSurfaceTexture failed: %d", err);
832            // Note that we must do the reset before disconnecting from the ANW.
833            // Otherwise queue/dequeue calls could be made on the disconnected
834            // ANW, which may result in errors.
835            reset();
836
837            disconnectNativeWindow();
838
839            return err;
840        }
841    }
842
843    // Note that we must set the player's new GraphicBufferProducer before
844    // disconnecting the old one.  Otherwise queue/dequeue calls could be made
845    // on the disconnected ANW, which may result in errors.
846    status_t err = p->setVideoSurfaceTexture(bufferProducer);
847
848    disconnectNativeWindow();
849
850    mConnectedWindow = anw;
851
852    if (err == OK) {
853        mConnectedWindowBinder = binder;
854    } else {
855        disconnectNativeWindow();
856    }
857
858    return err;
859}
860
861status_t MediaPlayerService::Client::invoke(const Parcel& request,
862                                            Parcel *reply)
863{
864    sp<MediaPlayerBase> p = getPlayer();
865    if (p == NULL) return UNKNOWN_ERROR;
866    return p->invoke(request, reply);
867}
868
869// This call doesn't need to access the native player.
870status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
871{
872    status_t status;
873    media::Metadata::Filter allow, drop;
874
875    if (unmarshallFilter(filter, &allow, &status) &&
876        unmarshallFilter(filter, &drop, &status)) {
877        Mutex::Autolock lock(mLock);
878
879        mMetadataAllow = allow;
880        mMetadataDrop = drop;
881    }
882    return status;
883}
884
885status_t MediaPlayerService::Client::getMetadata(
886        bool update_only, bool /*apply_filter*/, Parcel *reply)
887{
888    sp<MediaPlayerBase> player = getPlayer();
889    if (player == 0) return UNKNOWN_ERROR;
890
891    status_t status;
892    // Placeholder for the return code, updated by the caller.
893    reply->writeInt32(-1);
894
895    media::Metadata::Filter ids;
896
897    // We don't block notifications while we fetch the data. We clear
898    // mMetadataUpdated first so we don't lose notifications happening
899    // during the rest of this call.
900    {
901        Mutex::Autolock lock(mLock);
902        if (update_only) {
903            ids = mMetadataUpdated;
904        }
905        mMetadataUpdated.clear();
906    }
907
908    media::Metadata metadata(reply);
909
910    metadata.appendHeader();
911    status = player->getMetadata(ids, reply);
912
913    if (status != OK) {
914        metadata.resetParcel();
915        ALOGE("getMetadata failed %d", status);
916        return status;
917    }
918
919    // FIXME: Implement filtering on the result. Not critical since
920    // filtering takes place on the update notifications already. This
921    // would be when all the metadata are fetch and a filter is set.
922
923    // Everything is fine, update the metadata length.
924    metadata.updateLength();
925    return OK;
926}
927
928status_t MediaPlayerService::Client::prepareAsync()
929{
930    ALOGV("[%d] prepareAsync", mConnId);
931    sp<MediaPlayerBase> p = getPlayer();
932    if (p == 0) return UNKNOWN_ERROR;
933    status_t ret = p->prepareAsync();
934#if CALLBACK_ANTAGONIZER
935    ALOGD("start Antagonizer");
936    if (ret == NO_ERROR) mAntagonizer->start();
937#endif
938    return ret;
939}
940
941status_t MediaPlayerService::Client::start()
942{
943    ALOGV("[%d] start", mConnId);
944    sp<MediaPlayerBase> p = getPlayer();
945    if (p == 0) return UNKNOWN_ERROR;
946    p->setLooping(mLoop);
947    return p->start();
948}
949
950status_t MediaPlayerService::Client::stop()
951{
952    ALOGV("[%d] stop", mConnId);
953    sp<MediaPlayerBase> p = getPlayer();
954    if (p == 0) return UNKNOWN_ERROR;
955    return p->stop();
956}
957
958status_t MediaPlayerService::Client::pause()
959{
960    ALOGV("[%d] pause", mConnId);
961    sp<MediaPlayerBase> p = getPlayer();
962    if (p == 0) return UNKNOWN_ERROR;
963    return p->pause();
964}
965
966status_t MediaPlayerService::Client::isPlaying(bool* state)
967{
968    *state = false;
969    sp<MediaPlayerBase> p = getPlayer();
970    if (p == 0) return UNKNOWN_ERROR;
971    *state = p->isPlaying();
972    ALOGV("[%d] isPlaying: %d", mConnId, *state);
973    return NO_ERROR;
974}
975
976status_t MediaPlayerService::Client::setPlaybackSettings(const AudioPlaybackRate& rate)
977{
978    ALOGV("[%d] setPlaybackSettings(%f, %f, %d, %d)",
979            mConnId, rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
980    sp<MediaPlayerBase> p = getPlayer();
981    if (p == 0) return UNKNOWN_ERROR;
982    return p->setPlaybackSettings(rate);
983}
984
985status_t MediaPlayerService::Client::getPlaybackSettings(AudioPlaybackRate* rate /* nonnull */)
986{
987    sp<MediaPlayerBase> p = getPlayer();
988    if (p == 0) return UNKNOWN_ERROR;
989    status_t ret = p->getPlaybackSettings(rate);
990    if (ret == NO_ERROR) {
991        ALOGV("[%d] getPlaybackSettings(%f, %f, %d, %d)",
992                mConnId, rate->mSpeed, rate->mPitch, rate->mFallbackMode, rate->mStretchMode);
993    } else {
994        ALOGV("[%d] getPlaybackSettings returned %d", mConnId, ret);
995    }
996    return ret;
997}
998
999status_t MediaPlayerService::Client::setSyncSettings(
1000        const AVSyncSettings& sync, float videoFpsHint)
1001{
1002    ALOGV("[%d] setSyncSettings(%u, %u, %f, %f)",
1003            mConnId, sync.mSource, sync.mAudioAdjustMode, sync.mTolerance, videoFpsHint);
1004    sp<MediaPlayerBase> p = getPlayer();
1005    if (p == 0) return UNKNOWN_ERROR;
1006    return p->setSyncSettings(sync, videoFpsHint);
1007}
1008
1009status_t MediaPlayerService::Client::getSyncSettings(
1010        AVSyncSettings* sync /* nonnull */, float* videoFps /* nonnull */)
1011{
1012    sp<MediaPlayerBase> p = getPlayer();
1013    if (p == 0) return UNKNOWN_ERROR;
1014    status_t ret = p->getSyncSettings(sync, videoFps);
1015    if (ret == NO_ERROR) {
1016        ALOGV("[%d] getSyncSettings(%u, %u, %f, %f)",
1017                mConnId, sync->mSource, sync->mAudioAdjustMode, sync->mTolerance, *videoFps);
1018    } else {
1019        ALOGV("[%d] getSyncSettings returned %d", mConnId, ret);
1020    }
1021    return ret;
1022}
1023
1024status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
1025{
1026    ALOGV("getCurrentPosition");
1027    sp<MediaPlayerBase> p = getPlayer();
1028    if (p == 0) return UNKNOWN_ERROR;
1029    status_t ret = p->getCurrentPosition(msec);
1030    if (ret == NO_ERROR) {
1031        ALOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
1032    } else {
1033        ALOGE("getCurrentPosition returned %d", ret);
1034    }
1035    return ret;
1036}
1037
1038status_t MediaPlayerService::Client::getDuration(int *msec)
1039{
1040    ALOGV("getDuration");
1041    sp<MediaPlayerBase> p = getPlayer();
1042    if (p == 0) return UNKNOWN_ERROR;
1043    status_t ret = p->getDuration(msec);
1044    if (ret == NO_ERROR) {
1045        ALOGV("[%d] getDuration = %d", mConnId, *msec);
1046    } else {
1047        ALOGE("getDuration returned %d", ret);
1048    }
1049    return ret;
1050}
1051
1052status_t MediaPlayerService::Client::setNextPlayer(const sp<IMediaPlayer>& player) {
1053    ALOGV("setNextPlayer");
1054    Mutex::Autolock l(mLock);
1055    sp<Client> c = static_cast<Client*>(player.get());
1056    mNextClient = c;
1057
1058    if (c != NULL) {
1059        if (mAudioOutput != NULL) {
1060            mAudioOutput->setNextOutput(c->mAudioOutput);
1061        } else if ((mPlayer != NULL) && !mPlayer->hardwareOutput()) {
1062            ALOGE("no current audio output");
1063        }
1064
1065        if ((mPlayer != NULL) && (mNextClient->getPlayer() != NULL)) {
1066            mPlayer->setNextPlayer(mNextClient->getPlayer());
1067        }
1068    }
1069
1070    return OK;
1071}
1072
1073status_t MediaPlayerService::Client::seekTo(int msec)
1074{
1075    ALOGV("[%d] seekTo(%d)", mConnId, msec);
1076    sp<MediaPlayerBase> p = getPlayer();
1077    if (p == 0) return UNKNOWN_ERROR;
1078    return p->seekTo(msec);
1079}
1080
1081status_t MediaPlayerService::Client::reset()
1082{
1083    ALOGV("[%d] reset", mConnId);
1084    mRetransmitEndpointValid = false;
1085    sp<MediaPlayerBase> p = getPlayer();
1086    if (p == 0) return UNKNOWN_ERROR;
1087    return p->reset();
1088}
1089
1090status_t MediaPlayerService::Client::setAudioStreamType(audio_stream_type_t type)
1091{
1092    ALOGV("[%d] setAudioStreamType(%d)", mConnId, type);
1093    // TODO: for hardware output, call player instead
1094    Mutex::Autolock l(mLock);
1095    if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1096    return NO_ERROR;
1097}
1098
1099status_t MediaPlayerService::Client::setAudioAttributes_l(const Parcel &parcel)
1100{
1101    if (mAudioAttributes != NULL) { free(mAudioAttributes); }
1102    mAudioAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1103    if (mAudioAttributes == NULL) {
1104        return NO_MEMORY;
1105    }
1106    unmarshallAudioAttributes(parcel, mAudioAttributes);
1107
1108    ALOGV("setAudioAttributes_l() usage=%d content=%d flags=0x%x tags=%s",
1109            mAudioAttributes->usage, mAudioAttributes->content_type, mAudioAttributes->flags,
1110            mAudioAttributes->tags);
1111
1112    if (mAudioOutput != 0) {
1113        mAudioOutput->setAudioAttributes(mAudioAttributes);
1114    }
1115    return NO_ERROR;
1116}
1117
1118status_t MediaPlayerService::Client::setLooping(int loop)
1119{
1120    ALOGV("[%d] setLooping(%d)", mConnId, loop);
1121    mLoop = loop;
1122    sp<MediaPlayerBase> p = getPlayer();
1123    if (p != 0) return p->setLooping(loop);
1124    return NO_ERROR;
1125}
1126
1127status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1128{
1129    ALOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
1130
1131    // for hardware output, call player instead
1132    sp<MediaPlayerBase> p = getPlayer();
1133    {
1134      Mutex::Autolock l(mLock);
1135      if (p != 0 && p->hardwareOutput()) {
1136          MediaPlayerHWInterface* hwp =
1137                  reinterpret_cast<MediaPlayerHWInterface*>(p.get());
1138          return hwp->setVolume(leftVolume, rightVolume);
1139      } else {
1140          if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1141          return NO_ERROR;
1142      }
1143    }
1144
1145    return NO_ERROR;
1146}
1147
1148status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1149{
1150    ALOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
1151    Mutex::Autolock l(mLock);
1152    if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1153    return NO_ERROR;
1154}
1155
1156status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1157{
1158    ALOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
1159    Mutex::Autolock l(mLock);
1160    if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1161    return NO_ERROR;
1162}
1163
1164status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
1165    ALOGV("[%d] setParameter(%d)", mConnId, key);
1166    switch (key) {
1167    case KEY_PARAMETER_AUDIO_ATTRIBUTES:
1168    {
1169        Mutex::Autolock l(mLock);
1170        return setAudioAttributes_l(request);
1171    }
1172    default:
1173        sp<MediaPlayerBase> p = getPlayer();
1174        if (p == 0) { return UNKNOWN_ERROR; }
1175        return p->setParameter(key, request);
1176    }
1177}
1178
1179status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
1180    ALOGV("[%d] getParameter(%d)", mConnId, key);
1181    sp<MediaPlayerBase> p = getPlayer();
1182    if (p == 0) return UNKNOWN_ERROR;
1183    return p->getParameter(key, reply);
1184}
1185
1186status_t MediaPlayerService::Client::setRetransmitEndpoint(
1187        const struct sockaddr_in* endpoint) {
1188
1189    if (NULL != endpoint) {
1190        uint32_t a = ntohl(endpoint->sin_addr.s_addr);
1191        uint16_t p = ntohs(endpoint->sin_port);
1192        ALOGV("[%d] setRetransmitEndpoint(%u.%u.%u.%u:%hu)", mConnId,
1193                (a >> 24), (a >> 16) & 0xFF, (a >> 8) & 0xFF, (a & 0xFF), p);
1194    } else {
1195        ALOGV("[%d] setRetransmitEndpoint = <none>", mConnId);
1196    }
1197
1198    sp<MediaPlayerBase> p = getPlayer();
1199
1200    // Right now, the only valid time to set a retransmit endpoint is before
1201    // player selection has been made (since the presence or absence of a
1202    // retransmit endpoint is going to determine which player is selected during
1203    // setDataSource).
1204    if (p != 0) return INVALID_OPERATION;
1205
1206    if (NULL != endpoint) {
1207        mRetransmitEndpoint = *endpoint;
1208        mRetransmitEndpointValid = true;
1209    } else {
1210        mRetransmitEndpointValid = false;
1211    }
1212
1213    return NO_ERROR;
1214}
1215
1216status_t MediaPlayerService::Client::getRetransmitEndpoint(
1217        struct sockaddr_in* endpoint)
1218{
1219    if (NULL == endpoint)
1220        return BAD_VALUE;
1221
1222    sp<MediaPlayerBase> p = getPlayer();
1223
1224    if (p != NULL)
1225        return p->getRetransmitEndpoint(endpoint);
1226
1227    if (!mRetransmitEndpointValid)
1228        return NO_INIT;
1229
1230    *endpoint = mRetransmitEndpoint;
1231
1232    return NO_ERROR;
1233}
1234
1235void MediaPlayerService::Client::notify(
1236        void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
1237{
1238    Client* client = static_cast<Client*>(cookie);
1239    if (client == NULL) {
1240        return;
1241    }
1242
1243    sp<IMediaPlayerClient> c;
1244    {
1245        Mutex::Autolock l(client->mLock);
1246        c = client->mClient;
1247        if (msg == MEDIA_PLAYBACK_COMPLETE && client->mNextClient != NULL) {
1248            if (client->mAudioOutput != NULL)
1249                client->mAudioOutput->switchToNextOutput();
1250            client->mNextClient->start();
1251            client->mNextClient->mClient->notify(MEDIA_INFO, MEDIA_INFO_STARTED_AS_NEXT, 0, obj);
1252        }
1253    }
1254
1255    if (MEDIA_INFO == msg &&
1256        MEDIA_INFO_METADATA_UPDATE == ext1) {
1257        const media::Metadata::Type metadata_type = ext2;
1258
1259        if(client->shouldDropMetadata(metadata_type)) {
1260            return;
1261        }
1262
1263        // Update the list of metadata that have changed. getMetadata
1264        // also access mMetadataUpdated and clears it.
1265        client->addNewMetadataUpdate(metadata_type);
1266    }
1267
1268    if (c != NULL) {
1269        ALOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
1270        c->notify(msg, ext1, ext2, obj);
1271    }
1272}
1273
1274
1275bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
1276{
1277    Mutex::Autolock lock(mLock);
1278
1279    if (findMetadata(mMetadataDrop, code)) {
1280        return true;
1281    }
1282
1283    if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
1284        return false;
1285    } else {
1286        return true;
1287    }
1288}
1289
1290
1291void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
1292    Mutex::Autolock lock(mLock);
1293    if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1294        mMetadataUpdated.add(metadata_type);
1295    }
1296}
1297
1298#if CALLBACK_ANTAGONIZER
1299const int Antagonizer::interval = 10000; // 10 msecs
1300
1301Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1302    mExit(false), mActive(false), mClient(client), mCb(cb)
1303{
1304    createThread(callbackThread, this);
1305}
1306
1307void Antagonizer::kill()
1308{
1309    Mutex::Autolock _l(mLock);
1310    mActive = false;
1311    mExit = true;
1312    mCondition.wait(mLock);
1313}
1314
1315int Antagonizer::callbackThread(void* user)
1316{
1317    ALOGD("Antagonizer started");
1318    Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1319    while (!p->mExit) {
1320        if (p->mActive) {
1321            ALOGV("send event");
1322            p->mCb(p->mClient, 0, 0, 0);
1323        }
1324        usleep(interval);
1325    }
1326    Mutex::Autolock _l(p->mLock);
1327    p->mCondition.signal();
1328    ALOGD("Antagonizer stopped");
1329    return 0;
1330}
1331#endif
1332
1333#undef LOG_TAG
1334#define LOG_TAG "AudioSink"
1335MediaPlayerService::AudioOutput::AudioOutput(int sessionId, int uid, int pid,
1336        const audio_attributes_t* attr)
1337    : mCallback(NULL),
1338      mCallbackCookie(NULL),
1339      mCallbackData(NULL),
1340      mBytesWritten(0),
1341      mStreamType(AUDIO_STREAM_MUSIC),
1342      mLeftVolume(1.0),
1343      mRightVolume(1.0),
1344      mPlaybackRate(AUDIO_PLAYBACK_RATE_DEFAULT),
1345      mSampleRateHz(0),
1346      mMsecsPerFrame(0),
1347      mFrameSize(0),
1348      mSessionId(sessionId),
1349      mUid(uid),
1350      mPid(pid),
1351      mSendLevel(0.0),
1352      mAuxEffectId(0),
1353      mFlags(AUDIO_OUTPUT_FLAG_NONE)
1354{
1355    ALOGV("AudioOutput(%d)", sessionId);
1356    if (attr != NULL) {
1357        mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1358        if (mAttributes != NULL) {
1359            memcpy(mAttributes, attr, sizeof(audio_attributes_t));
1360            mStreamType = audio_attributes_to_stream_type(attr);
1361        }
1362    } else {
1363        mAttributes = NULL;
1364    }
1365
1366    setMinBufferCount();
1367}
1368
1369MediaPlayerService::AudioOutput::~AudioOutput()
1370{
1371    close();
1372    free(mAttributes);
1373    delete mCallbackData;
1374}
1375
1376//static
1377void MediaPlayerService::AudioOutput::setMinBufferCount()
1378{
1379    char value[PROPERTY_VALUE_MAX];
1380    if (property_get("ro.kernel.qemu", value, 0)) {
1381        mIsOnEmulator = true;
1382        mMinBufferCount = 12;  // to prevent systematic buffer underrun for emulator
1383    }
1384}
1385
1386// static
1387bool MediaPlayerService::AudioOutput::isOnEmulator()
1388{
1389    setMinBufferCount(); // benign race wrt other threads
1390    return mIsOnEmulator;
1391}
1392
1393// static
1394int MediaPlayerService::AudioOutput::getMinBufferCount()
1395{
1396    setMinBufferCount(); // benign race wrt other threads
1397    return mMinBufferCount;
1398}
1399
1400ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1401{
1402    Mutex::Autolock lock(mLock);
1403    if (mTrack == 0) return NO_INIT;
1404    return mTrack->frameCount() * mFrameSize;
1405}
1406
1407ssize_t MediaPlayerService::AudioOutput::frameCount() const
1408{
1409    Mutex::Autolock lock(mLock);
1410    if (mTrack == 0) return NO_INIT;
1411    return mTrack->frameCount();
1412}
1413
1414ssize_t MediaPlayerService::AudioOutput::channelCount() const
1415{
1416    Mutex::Autolock lock(mLock);
1417    if (mTrack == 0) return NO_INIT;
1418    return mTrack->channelCount();
1419}
1420
1421ssize_t MediaPlayerService::AudioOutput::frameSize() const
1422{
1423    Mutex::Autolock lock(mLock);
1424    if (mTrack == 0) return NO_INIT;
1425    return mFrameSize;
1426}
1427
1428uint32_t MediaPlayerService::AudioOutput::latency () const
1429{
1430    Mutex::Autolock lock(mLock);
1431    if (mTrack == 0) return 0;
1432    return mTrack->latency();
1433}
1434
1435float MediaPlayerService::AudioOutput::msecsPerFrame() const
1436{
1437    Mutex::Autolock lock(mLock);
1438    return mMsecsPerFrame;
1439}
1440
1441status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position) const
1442{
1443    Mutex::Autolock lock(mLock);
1444    if (mTrack == 0) return NO_INIT;
1445    return mTrack->getPosition(position);
1446}
1447
1448status_t MediaPlayerService::AudioOutput::getTimestamp(AudioTimestamp &ts) const
1449{
1450    Mutex::Autolock lock(mLock);
1451    if (mTrack == 0) return NO_INIT;
1452    return mTrack->getTimestamp(ts);
1453}
1454
1455// TODO: Remove unnecessary calls to getPlayedOutDurationUs()
1456// as it acquires locks and may query the audio driver.
1457//
1458// Some calls could conceivably retrieve extrapolated data instead of
1459// accessing getTimestamp() or getPosition() every time a data buffer with
1460// a media time is received.
1461//
1462// Calculate duration of played samples if played at normal rate (i.e., 1.0).
1463int64_t MediaPlayerService::AudioOutput::getPlayedOutDurationUs(int64_t nowUs) const
1464{
1465    Mutex::Autolock lock(mLock);
1466    if (mTrack == 0 || mSampleRateHz == 0) {
1467        return 0;
1468    }
1469
1470    uint32_t numFramesPlayed;
1471    int64_t numFramesPlayedAt;
1472    AudioTimestamp ts;
1473    static const int64_t kStaleTimestamp100ms = 100000;
1474
1475    status_t res = mTrack->getTimestamp(ts);
1476    if (res == OK) {                 // case 1: mixing audio tracks and offloaded tracks.
1477        numFramesPlayed = ts.mPosition;
1478        numFramesPlayedAt = ts.mTime.tv_sec * 1000000LL + ts.mTime.tv_nsec / 1000;
1479        const int64_t timestampAge = nowUs - numFramesPlayedAt;
1480        if (timestampAge > kStaleTimestamp100ms) {
1481            // This is an audio FIXME.
1482            // getTimestamp returns a timestamp which may come from audio mixing threads.
1483            // After pausing, the MixerThread may go idle, thus the mTime estimate may
1484            // become stale. Assuming that the MixerThread runs 20ms, with FastMixer at 5ms,
1485            // the max latency should be about 25ms with an average around 12ms (to be verified).
1486            // For safety we use 100ms.
1487            ALOGV("getTimestamp: returned stale timestamp nowUs(%lld) numFramesPlayedAt(%lld)",
1488                    (long long)nowUs, (long long)numFramesPlayedAt);
1489            numFramesPlayedAt = nowUs - kStaleTimestamp100ms;
1490        }
1491        //ALOGD("getTimestamp: OK %d %lld", numFramesPlayed, (long long)numFramesPlayedAt);
1492    } else if (res == WOULD_BLOCK) { // case 2: transitory state on start of a new track
1493        numFramesPlayed = 0;
1494        numFramesPlayedAt = nowUs;
1495        //ALOGD("getTimestamp: WOULD_BLOCK %d %lld",
1496        //        numFramesPlayed, (long long)numFramesPlayedAt);
1497    } else {                         // case 3: transitory at new track or audio fast tracks.
1498        res = mTrack->getPosition(&numFramesPlayed);
1499        CHECK_EQ(res, (status_t)OK);
1500        numFramesPlayedAt = nowUs;
1501        numFramesPlayedAt += 1000LL * mTrack->latency() / 2; /* XXX */
1502        //ALOGD("getPosition: %u %lld", numFramesPlayed, (long long)numFramesPlayedAt);
1503    }
1504
1505    // CHECK_EQ(numFramesPlayed & (1 << 31), 0);  // can't be negative until 12.4 hrs, test
1506    // TODO: remove the (int32_t) casting below as it may overflow at 12.4 hours.
1507    int64_t durationUs = (int64_t)((int32_t)numFramesPlayed * 1000000LL / mSampleRateHz)
1508            + nowUs - numFramesPlayedAt;
1509    if (durationUs < 0) {
1510        // Occurs when numFramesPlayed position is very small and the following:
1511        // (1) In case 1, the time nowUs is computed before getTimestamp() is called and
1512        //     numFramesPlayedAt is greater than nowUs by time more than numFramesPlayed.
1513        // (2) In case 3, using getPosition and adding mAudioSink->latency() to
1514        //     numFramesPlayedAt, by a time amount greater than numFramesPlayed.
1515        //
1516        // Both of these are transitory conditions.
1517        ALOGV("getPlayedOutDurationUs: negative duration %lld set to zero", (long long)durationUs);
1518        durationUs = 0;
1519    }
1520    ALOGV("getPlayedOutDurationUs(%lld) nowUs(%lld) frames(%u) framesAt(%lld)",
1521            (long long)durationUs, (long long)nowUs, numFramesPlayed, (long long)numFramesPlayedAt);
1522    return durationUs;
1523}
1524
1525status_t MediaPlayerService::AudioOutput::getFramesWritten(uint32_t *frameswritten) const
1526{
1527    Mutex::Autolock lock(mLock);
1528    if (mTrack == 0) return NO_INIT;
1529    *frameswritten = mBytesWritten / mFrameSize;
1530    return OK;
1531}
1532
1533status_t MediaPlayerService::AudioOutput::setParameters(const String8& keyValuePairs)
1534{
1535    Mutex::Autolock lock(mLock);
1536    if (mTrack == 0) return NO_INIT;
1537    return mTrack->setParameters(keyValuePairs);
1538}
1539
1540String8  MediaPlayerService::AudioOutput::getParameters(const String8& keys)
1541{
1542    Mutex::Autolock lock(mLock);
1543    if (mTrack == 0) return String8::empty();
1544    return mTrack->getParameters(keys);
1545}
1546
1547void MediaPlayerService::AudioOutput::setAudioAttributes(const audio_attributes_t * attributes) {
1548    Mutex::Autolock lock(mLock);
1549    if (attributes == NULL) {
1550        free(mAttributes);
1551        mAttributes = NULL;
1552    } else {
1553        if (mAttributes == NULL) {
1554            mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1555        }
1556        memcpy(mAttributes, attributes, sizeof(audio_attributes_t));
1557        mStreamType = audio_attributes_to_stream_type(attributes);
1558    }
1559}
1560
1561void MediaPlayerService::AudioOutput::setAudioStreamType(audio_stream_type_t streamType)
1562{
1563    Mutex::Autolock lock(mLock);
1564    // do not allow direct stream type modification if attributes have been set
1565    if (mAttributes == NULL) {
1566        mStreamType = streamType;
1567    }
1568}
1569
1570void MediaPlayerService::AudioOutput::deleteRecycledTrack_l()
1571{
1572    ALOGV("deleteRecycledTrack_l");
1573    if (mRecycledTrack != 0) {
1574
1575        if (mCallbackData != NULL) {
1576            mCallbackData->setOutput(NULL);
1577            mCallbackData->endTrackSwitch();
1578        }
1579
1580        if ((mRecycledTrack->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) {
1581            mRecycledTrack->flush();
1582        }
1583        // An offloaded track isn't flushed because the STREAM_END is reported
1584        // slightly prematurely to allow time for the gapless track switch
1585        // but this means that if we decide not to recycle the track there
1586        // could be a small amount of residual data still playing. We leave
1587        // AudioFlinger to drain the track.
1588
1589        mRecycledTrack.clear();
1590        close_l();
1591        delete mCallbackData;
1592        mCallbackData = NULL;
1593    }
1594}
1595
1596void MediaPlayerService::AudioOutput::close_l()
1597{
1598    mTrack.clear();
1599}
1600
1601status_t MediaPlayerService::AudioOutput::open(
1602        uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
1603        audio_format_t format, int bufferCount,
1604        AudioCallback cb, void *cookie,
1605        audio_output_flags_t flags,
1606        const audio_offload_info_t *offloadInfo,
1607        bool doNotReconnect,
1608        uint32_t suggestedFrameCount)
1609{
1610    ALOGV("open(%u, %d, 0x%x, 0x%x, %d, %d 0x%x)", sampleRate, channelCount, channelMask,
1611                format, bufferCount, mSessionId, flags);
1612
1613    // offloading is only supported in callback mode for now.
1614    // offloadInfo must be present if offload flag is set
1615    if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) &&
1616            ((cb == NULL) || (offloadInfo == NULL))) {
1617        return BAD_VALUE;
1618    }
1619
1620    // compute frame count for the AudioTrack internal buffer
1621    size_t frameCount;
1622    if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1623        frameCount = 0; // AudioTrack will get frame count from AudioFlinger
1624    } else {
1625        // try to estimate the buffer processing fetch size from AudioFlinger.
1626        // framesPerBuffer is approximate and generally correct, except when it's not :-).
1627        uint32_t afSampleRate;
1628        size_t afFrameCount;
1629        if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1630            return NO_INIT;
1631        }
1632        if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1633            return NO_INIT;
1634        }
1635        const size_t framesPerBuffer =
1636                (unsigned long long)sampleRate * afFrameCount / afSampleRate;
1637
1638        if (bufferCount == 0) {
1639            // use suggestedFrameCount
1640            bufferCount = (suggestedFrameCount + framesPerBuffer - 1) / framesPerBuffer;
1641        }
1642        // Check argument bufferCount against the mininum buffer count
1643        if (bufferCount != 0 && bufferCount < mMinBufferCount) {
1644            ALOGV("bufferCount (%d) increased to %d", bufferCount, mMinBufferCount);
1645            bufferCount = mMinBufferCount;
1646        }
1647        // if frameCount is 0, then AudioTrack will get frame count from AudioFlinger
1648        // which will be the minimum size permitted.
1649        frameCount = bufferCount * framesPerBuffer;
1650    }
1651
1652    if (channelMask == CHANNEL_MASK_USE_CHANNEL_ORDER) {
1653        channelMask = audio_channel_out_mask_from_count(channelCount);
1654        if (0 == channelMask) {
1655            ALOGE("open() error, can\'t derive mask for %d audio channels", channelCount);
1656            return NO_INIT;
1657        }
1658    }
1659
1660    Mutex::Autolock lock(mLock);
1661    mCallback = cb;
1662    mCallbackCookie = cookie;
1663
1664    // Check whether we can recycle the track
1665    bool reuse = false;
1666    bool bothOffloaded = false;
1667
1668    if (mRecycledTrack != 0) {
1669        // check whether we are switching between two offloaded tracks
1670        bothOffloaded = (flags & mRecycledTrack->getFlags()
1671                                & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0;
1672
1673        // check if the existing track can be reused as-is, or if a new track needs to be created.
1674        reuse = true;
1675
1676        if ((mCallbackData == NULL && mCallback != NULL) ||
1677                (mCallbackData != NULL && mCallback == NULL)) {
1678            // recycled track uses callbacks but the caller wants to use writes, or vice versa
1679            ALOGV("can't chain callback and write");
1680            reuse = false;
1681        } else if ((mRecycledTrack->getSampleRate() != sampleRate) ||
1682                (mRecycledTrack->channelCount() != (uint32_t)channelCount) ) {
1683            ALOGV("samplerate, channelcount differ: %u/%u Hz, %u/%d ch",
1684                  mRecycledTrack->getSampleRate(), sampleRate,
1685                  mRecycledTrack->channelCount(), channelCount);
1686            reuse = false;
1687        } else if (flags != mFlags) {
1688            ALOGV("output flags differ %08x/%08x", flags, mFlags);
1689            reuse = false;
1690        } else if (mRecycledTrack->format() != format) {
1691            reuse = false;
1692        }
1693    } else {
1694        ALOGV("no track available to recycle");
1695    }
1696
1697    ALOGV_IF(bothOffloaded, "both tracks offloaded");
1698
1699    // If we can't recycle and both tracks are offloaded
1700    // we must close the previous output before opening a new one
1701    if (bothOffloaded && !reuse) {
1702        ALOGV("both offloaded and not recycling");
1703        deleteRecycledTrack_l();
1704    }
1705
1706    sp<AudioTrack> t;
1707    CallbackData *newcbd = NULL;
1708
1709    // We don't attempt to create a new track if we are recycling an
1710    // offloaded track. But, if we are recycling a non-offloaded or we
1711    // are switching where one is offloaded and one isn't then we create
1712    // the new track in advance so that we can read additional stream info
1713
1714    if (!(reuse && bothOffloaded)) {
1715        ALOGV("creating new AudioTrack");
1716
1717        if (mCallback != NULL) {
1718            newcbd = new CallbackData(this);
1719            t = new AudioTrack(
1720                    mStreamType,
1721                    sampleRate,
1722                    format,
1723                    channelMask,
1724                    frameCount,
1725                    flags,
1726                    CallbackWrapper,
1727                    newcbd,
1728                    0,  // notification frames
1729                    mSessionId,
1730                    AudioTrack::TRANSFER_CALLBACK,
1731                    offloadInfo,
1732                    mUid,
1733                    mPid,
1734                    mAttributes,
1735                    doNotReconnect);
1736        } else {
1737            t = new AudioTrack(
1738                    mStreamType,
1739                    sampleRate,
1740                    format,
1741                    channelMask,
1742                    frameCount,
1743                    flags,
1744                    NULL, // callback
1745                    NULL, // user data
1746                    0, // notification frames
1747                    mSessionId,
1748                    AudioTrack::TRANSFER_DEFAULT,
1749                    NULL, // offload info
1750                    mUid,
1751                    mPid,
1752                    mAttributes,
1753                    doNotReconnect);
1754        }
1755
1756        if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1757            ALOGE("Unable to create audio track");
1758            delete newcbd;
1759            // t goes out of scope, so reference count drops to zero
1760            return NO_INIT;
1761        } else {
1762            // successful AudioTrack initialization implies a legacy stream type was generated
1763            // from the audio attributes
1764            mStreamType = t->streamType();
1765        }
1766    }
1767
1768    if (reuse) {
1769        CHECK(mRecycledTrack != NULL);
1770
1771        if (!bothOffloaded) {
1772            if (mRecycledTrack->frameCount() != t->frameCount()) {
1773                ALOGV("framecount differs: %u/%u frames",
1774                      mRecycledTrack->frameCount(), t->frameCount());
1775                reuse = false;
1776            }
1777        }
1778
1779        if (reuse) {
1780            ALOGV("chaining to next output and recycling track");
1781            close_l();
1782            mTrack = mRecycledTrack;
1783            mRecycledTrack.clear();
1784            if (mCallbackData != NULL) {
1785                mCallbackData->setOutput(this);
1786            }
1787            delete newcbd;
1788            return OK;
1789        }
1790    }
1791
1792    // we're not going to reuse the track, unblock and flush it
1793    // this was done earlier if both tracks are offloaded
1794    if (!bothOffloaded) {
1795        deleteRecycledTrack_l();
1796    }
1797
1798    CHECK((t != NULL) && ((mCallback == NULL) || (newcbd != NULL)));
1799
1800    mCallbackData = newcbd;
1801    ALOGV("setVolume");
1802    t->setVolume(mLeftVolume, mRightVolume);
1803
1804    mSampleRateHz = sampleRate;
1805    mFlags = flags;
1806    mMsecsPerFrame = 1E3f / (mPlaybackRate.mSpeed * sampleRate);
1807    mFrameSize = t->frameSize();
1808    uint32_t pos;
1809    if (t->getPosition(&pos) == OK) {
1810        mBytesWritten = uint64_t(pos) * mFrameSize;
1811    }
1812    mTrack = t;
1813
1814    status_t res = NO_ERROR;
1815    // Note some output devices may give us a direct track even though we don't specify it.
1816    // Example: Line application b/17459982.
1817    if ((t->getFlags() & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) {
1818        res = t->setPlaybackRate(mPlaybackRate);
1819        if (res == NO_ERROR) {
1820            t->setAuxEffectSendLevel(mSendLevel);
1821            res = t->attachAuxEffect(mAuxEffectId);
1822        }
1823    }
1824    ALOGV("open() DONE status %d", res);
1825    return res;
1826}
1827
1828status_t MediaPlayerService::AudioOutput::start()
1829{
1830    ALOGV("start");
1831    Mutex::Autolock lock(mLock);
1832    if (mCallbackData != NULL) {
1833        mCallbackData->endTrackSwitch();
1834    }
1835    if (mTrack != 0) {
1836        mTrack->setVolume(mLeftVolume, mRightVolume);
1837        mTrack->setAuxEffectSendLevel(mSendLevel);
1838        return mTrack->start();
1839    }
1840    return NO_INIT;
1841}
1842
1843void MediaPlayerService::AudioOutput::setNextOutput(const sp<AudioOutput>& nextOutput) {
1844    Mutex::Autolock lock(mLock);
1845    mNextOutput = nextOutput;
1846}
1847
1848void MediaPlayerService::AudioOutput::switchToNextOutput() {
1849    ALOGV("switchToNextOutput");
1850
1851    // Try to acquire the callback lock before moving track (without incurring deadlock).
1852    const unsigned kMaxSwitchTries = 100;
1853    Mutex::Autolock lock(mLock);
1854    for (unsigned tries = 0;;) {
1855        if (mTrack == 0) {
1856            return;
1857        }
1858        if (mNextOutput != NULL && mNextOutput != this) {
1859            if (mCallbackData != NULL) {
1860                // two alternative approaches
1861#if 1
1862                CallbackData *callbackData = mCallbackData;
1863                mLock.unlock();
1864                // proper acquisition sequence
1865                callbackData->lock();
1866                mLock.lock();
1867                // Caution: it is unlikely that someone deleted our callback or changed our target
1868                if (callbackData != mCallbackData || mNextOutput == NULL || mNextOutput == this) {
1869                    // fatal if we are starved out.
1870                    LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
1871                            "switchToNextOutput() cannot obtain correct lock sequence");
1872                    callbackData->unlock();
1873                    continue;
1874                }
1875                callbackData->mSwitching = true; // begin track switch
1876#else
1877                // tryBeginTrackSwitch() returns false if the callback has the lock.
1878                if (!mCallbackData->tryBeginTrackSwitch()) {
1879                    // fatal if we are starved out.
1880                    LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
1881                            "switchToNextOutput() cannot obtain callback lock");
1882                    mLock.unlock();
1883                    usleep(5 * 1000 /* usec */); // allow callback to use AudioOutput
1884                    mLock.lock();
1885                    continue;
1886                }
1887#endif
1888            }
1889
1890            Mutex::Autolock nextLock(mNextOutput->mLock);
1891
1892            // If the next output track is not NULL, then it has been
1893            // opened already for playback.
1894            // This is possible even without the next player being started,
1895            // for example, the next player could be prepared and seeked.
1896            //
1897            // Presuming it isn't advisable to force the track over.
1898             if (mNextOutput->mTrack == NULL) {
1899                ALOGD("Recycling track for gapless playback");
1900                delete mNextOutput->mCallbackData;
1901                mNextOutput->mCallbackData = mCallbackData;
1902                mNextOutput->mRecycledTrack = mTrack;
1903                mNextOutput->mSampleRateHz = mSampleRateHz;
1904                mNextOutput->mMsecsPerFrame = mMsecsPerFrame;
1905                mNextOutput->mBytesWritten = mBytesWritten;
1906                mNextOutput->mFlags = mFlags;
1907                mNextOutput->mFrameSize = mFrameSize;
1908                close_l();
1909                mCallbackData = NULL;  // destruction handled by mNextOutput
1910            } else {
1911                ALOGW("Ignoring gapless playback because next player has already started");
1912                // remove track in case resource needed for future players.
1913                if (mCallbackData != NULL) {
1914                    mCallbackData->endTrackSwitch();  // release lock for callbacks before close.
1915                }
1916                close_l();
1917            }
1918        }
1919        break;
1920    }
1921}
1922
1923ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size, bool blocking)
1924{
1925    Mutex::Autolock lock(mLock);
1926    LOG_ALWAYS_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
1927
1928    //ALOGV("write(%p, %u)", buffer, size);
1929    if (mTrack != 0) {
1930        ssize_t ret = mTrack->write(buffer, size, blocking);
1931        if (ret >= 0) {
1932            mBytesWritten += ret;
1933        }
1934        return ret;
1935    }
1936    return NO_INIT;
1937}
1938
1939void MediaPlayerService::AudioOutput::stop()
1940{
1941    ALOGV("stop");
1942    Mutex::Autolock lock(mLock);
1943    mBytesWritten = 0;
1944    if (mTrack != 0) mTrack->stop();
1945}
1946
1947void MediaPlayerService::AudioOutput::flush()
1948{
1949    ALOGV("flush");
1950    Mutex::Autolock lock(mLock);
1951    mBytesWritten = 0;
1952    if (mTrack != 0) mTrack->flush();
1953}
1954
1955void MediaPlayerService::AudioOutput::pause()
1956{
1957    ALOGV("pause");
1958    Mutex::Autolock lock(mLock);
1959    if (mTrack != 0) mTrack->pause();
1960}
1961
1962void MediaPlayerService::AudioOutput::close()
1963{
1964    ALOGV("close");
1965    Mutex::Autolock lock(mLock);
1966    close_l();
1967}
1968
1969void MediaPlayerService::AudioOutput::setVolume(float left, float right)
1970{
1971    ALOGV("setVolume(%f, %f)", left, right);
1972    Mutex::Autolock lock(mLock);
1973    mLeftVolume = left;
1974    mRightVolume = right;
1975    if (mTrack != 0) {
1976        mTrack->setVolume(left, right);
1977    }
1978}
1979
1980status_t MediaPlayerService::AudioOutput::setPlaybackRate(const AudioPlaybackRate &rate)
1981{
1982    ALOGV("setPlaybackRate(%f %f %d %d)",
1983                rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
1984    Mutex::Autolock lock(mLock);
1985    if (mTrack == 0) {
1986        // remember rate so that we can set it when the track is opened
1987        mPlaybackRate = rate;
1988        return OK;
1989    }
1990    status_t res = mTrack->setPlaybackRate(rate);
1991    if (res != NO_ERROR) {
1992        return res;
1993    }
1994    // rate.mSpeed is always greater than 0 if setPlaybackRate succeeded
1995    CHECK_GT(rate.mSpeed, 0.f);
1996    mPlaybackRate = rate;
1997    if (mSampleRateHz != 0) {
1998        mMsecsPerFrame = 1E3f / (rate.mSpeed * mSampleRateHz);
1999    }
2000    return res;
2001}
2002
2003status_t MediaPlayerService::AudioOutput::getPlaybackRate(AudioPlaybackRate *rate)
2004{
2005    ALOGV("setPlaybackRate");
2006    Mutex::Autolock lock(mLock);
2007    if (mTrack == 0) {
2008        return NO_INIT;
2009    }
2010    *rate = mTrack->getPlaybackRate();
2011    return NO_ERROR;
2012}
2013
2014status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
2015{
2016    ALOGV("setAuxEffectSendLevel(%f)", level);
2017    Mutex::Autolock lock(mLock);
2018    mSendLevel = level;
2019    if (mTrack != 0) {
2020        return mTrack->setAuxEffectSendLevel(level);
2021    }
2022    return NO_ERROR;
2023}
2024
2025status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
2026{
2027    ALOGV("attachAuxEffect(%d)", effectId);
2028    Mutex::Autolock lock(mLock);
2029    mAuxEffectId = effectId;
2030    if (mTrack != 0) {
2031        return mTrack->attachAuxEffect(effectId);
2032    }
2033    return NO_ERROR;
2034}
2035
2036// static
2037void MediaPlayerService::AudioOutput::CallbackWrapper(
2038        int event, void *cookie, void *info) {
2039    //ALOGV("callbackwrapper");
2040    CallbackData *data = (CallbackData*)cookie;
2041    // lock to ensure we aren't caught in the middle of a track switch.
2042    data->lock();
2043    AudioOutput *me = data->getOutput();
2044    AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
2045    if (me == NULL) {
2046        // no output set, likely because the track was scheduled to be reused
2047        // by another player, but the format turned out to be incompatible.
2048        data->unlock();
2049        if (buffer != NULL) {
2050            buffer->size = 0;
2051        }
2052        return;
2053    }
2054
2055    switch(event) {
2056    case AudioTrack::EVENT_MORE_DATA: {
2057        size_t actualSize = (*me->mCallback)(
2058                me, buffer->raw, buffer->size, me->mCallbackCookie,
2059                CB_EVENT_FILL_BUFFER);
2060
2061        // Log when no data is returned from the callback.
2062        // (1) We may have no data (especially with network streaming sources).
2063        // (2) We may have reached the EOS and the audio track is not stopped yet.
2064        // Note that AwesomePlayer/AudioPlayer will only return zero size when it reaches the EOS.
2065        // NuPlayerRenderer will return zero when it doesn't have data (it doesn't block to fill).
2066        //
2067        // This is a benign busy-wait, with the next data request generated 10 ms or more later;
2068        // nevertheless for power reasons, we don't want to see too many of these.
2069
2070        ALOGV_IF(actualSize == 0 && buffer->size > 0, "callbackwrapper: empty buffer returned");
2071
2072        me->mBytesWritten += actualSize;  // benign race with reader.
2073        buffer->size = actualSize;
2074        } break;
2075
2076    case AudioTrack::EVENT_STREAM_END:
2077        // currently only occurs for offloaded callbacks
2078        ALOGV("callbackwrapper: deliver EVENT_STREAM_END");
2079        (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2080                me->mCallbackCookie, CB_EVENT_STREAM_END);
2081        break;
2082
2083    case AudioTrack::EVENT_NEW_IAUDIOTRACK :
2084        ALOGV("callbackwrapper: deliver EVENT_TEAR_DOWN");
2085        (*me->mCallback)(me,  NULL /* buffer */, 0 /* size */,
2086                me->mCallbackCookie, CB_EVENT_TEAR_DOWN);
2087        break;
2088
2089    case AudioTrack::EVENT_UNDERRUN:
2090        // This occurs when there is no data available, typically
2091        // when there is a failure to supply data to the AudioTrack.  It can also
2092        // occur in non-offloaded mode when the audio device comes out of standby.
2093        //
2094        // If an AudioTrack underruns it outputs silence. Since this happens suddenly
2095        // it may sound like an audible pop or glitch.
2096        //
2097        // The underrun event is sent once per track underrun; the condition is reset
2098        // when more data is sent to the AudioTrack.
2099        ALOGI("callbackwrapper: EVENT_UNDERRUN (discarded)");
2100        break;
2101
2102    default:
2103        ALOGE("received unknown event type: %d inside CallbackWrapper !", event);
2104    }
2105
2106    data->unlock();
2107}
2108
2109int MediaPlayerService::AudioOutput::getSessionId() const
2110{
2111    Mutex::Autolock lock(mLock);
2112    return mSessionId;
2113}
2114
2115uint32_t MediaPlayerService::AudioOutput::getSampleRate() const
2116{
2117    Mutex::Autolock lock(mLock);
2118    if (mTrack == 0) return 0;
2119    return mTrack->getSampleRate();
2120}
2121
2122////////////////////////////////////////////////////////////////////////////////
2123
2124struct CallbackThread : public Thread {
2125    CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
2126                   MediaPlayerBase::AudioSink::AudioCallback cb,
2127                   void *cookie);
2128
2129protected:
2130    virtual ~CallbackThread();
2131
2132    virtual bool threadLoop();
2133
2134private:
2135    wp<MediaPlayerBase::AudioSink> mSink;
2136    MediaPlayerBase::AudioSink::AudioCallback mCallback;
2137    void *mCookie;
2138    void *mBuffer;
2139    size_t mBufferSize;
2140
2141    CallbackThread(const CallbackThread &);
2142    CallbackThread &operator=(const CallbackThread &);
2143};
2144
2145CallbackThread::CallbackThread(
2146        const wp<MediaPlayerBase::AudioSink> &sink,
2147        MediaPlayerBase::AudioSink::AudioCallback cb,
2148        void *cookie)
2149    : mSink(sink),
2150      mCallback(cb),
2151      mCookie(cookie),
2152      mBuffer(NULL),
2153      mBufferSize(0) {
2154}
2155
2156CallbackThread::~CallbackThread() {
2157    if (mBuffer) {
2158        free(mBuffer);
2159        mBuffer = NULL;
2160    }
2161}
2162
2163bool CallbackThread::threadLoop() {
2164    sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
2165    if (sink == NULL) {
2166        return false;
2167    }
2168
2169    if (mBuffer == NULL) {
2170        mBufferSize = sink->bufferSize();
2171        mBuffer = malloc(mBufferSize);
2172    }
2173
2174    size_t actualSize =
2175        (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie,
2176                MediaPlayerBase::AudioSink::CB_EVENT_FILL_BUFFER);
2177
2178    if (actualSize > 0) {
2179        sink->write(mBuffer, actualSize);
2180        // Could return false on sink->write() error or short count.
2181        // Not necessarily appropriate but would work for AudioCache behavior.
2182    }
2183
2184    return true;
2185}
2186
2187////////////////////////////////////////////////////////////////////////////////
2188
2189void MediaPlayerService::addBatteryData(uint32_t params)
2190{
2191    Mutex::Autolock lock(mLock);
2192
2193    int32_t time = systemTime() / 1000000L;
2194
2195    // change audio output devices. This notification comes from AudioFlinger
2196    if ((params & kBatteryDataSpeakerOn)
2197            || (params & kBatteryDataOtherAudioDeviceOn)) {
2198
2199        int deviceOn[NUM_AUDIO_DEVICES];
2200        for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2201            deviceOn[i] = 0;
2202        }
2203
2204        if ((params & kBatteryDataSpeakerOn)
2205                && (params & kBatteryDataOtherAudioDeviceOn)) {
2206            deviceOn[SPEAKER_AND_OTHER] = 1;
2207        } else if (params & kBatteryDataSpeakerOn) {
2208            deviceOn[SPEAKER] = 1;
2209        } else {
2210            deviceOn[OTHER_AUDIO_DEVICE] = 1;
2211        }
2212
2213        for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2214            if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
2215
2216                if (mBatteryAudio.refCount > 0) { // if playing audio
2217                    if (!deviceOn[i]) {
2218                        mBatteryAudio.lastTime[i] += time;
2219                        mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2220                        mBatteryAudio.lastTime[i] = 0;
2221                    } else {
2222                        mBatteryAudio.lastTime[i] = 0 - time;
2223                    }
2224                }
2225
2226                mBatteryAudio.deviceOn[i] = deviceOn[i];
2227            }
2228        }
2229        return;
2230    }
2231
2232    // an audio stream is started
2233    if (params & kBatteryDataAudioFlingerStart) {
2234        // record the start time only if currently no other audio
2235        // is being played
2236        if (mBatteryAudio.refCount == 0) {
2237            for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2238                if (mBatteryAudio.deviceOn[i]) {
2239                    mBatteryAudio.lastTime[i] -= time;
2240                }
2241            }
2242        }
2243
2244        mBatteryAudio.refCount ++;
2245        return;
2246
2247    } else if (params & kBatteryDataAudioFlingerStop) {
2248        if (mBatteryAudio.refCount <= 0) {
2249            ALOGW("Battery track warning: refCount is <= 0");
2250            return;
2251        }
2252
2253        // record the stop time only if currently this is the only
2254        // audio being played
2255        if (mBatteryAudio.refCount == 1) {
2256            for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2257                if (mBatteryAudio.deviceOn[i]) {
2258                    mBatteryAudio.lastTime[i] += time;
2259                    mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2260                    mBatteryAudio.lastTime[i] = 0;
2261                }
2262            }
2263        }
2264
2265        mBatteryAudio.refCount --;
2266        return;
2267    }
2268
2269    int uid = IPCThreadState::self()->getCallingUid();
2270    if (uid == AID_MEDIA) {
2271        return;
2272    }
2273    int index = mBatteryData.indexOfKey(uid);
2274
2275    if (index < 0) { // create a new entry for this UID
2276        BatteryUsageInfo info;
2277        info.audioTotalTime = 0;
2278        info.videoTotalTime = 0;
2279        info.audioLastTime = 0;
2280        info.videoLastTime = 0;
2281        info.refCount = 0;
2282
2283        if (mBatteryData.add(uid, info) == NO_MEMORY) {
2284            ALOGE("Battery track error: no memory for new app");
2285            return;
2286        }
2287    }
2288
2289    BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
2290
2291    if (params & kBatteryDataCodecStarted) {
2292        if (params & kBatteryDataTrackAudio) {
2293            info.audioLastTime -= time;
2294            info.refCount ++;
2295        }
2296        if (params & kBatteryDataTrackVideo) {
2297            info.videoLastTime -= time;
2298            info.refCount ++;
2299        }
2300    } else {
2301        if (info.refCount == 0) {
2302            ALOGW("Battery track warning: refCount is already 0");
2303            return;
2304        } else if (info.refCount < 0) {
2305            ALOGE("Battery track error: refCount < 0");
2306            mBatteryData.removeItem(uid);
2307            return;
2308        }
2309
2310        if (params & kBatteryDataTrackAudio) {
2311            info.audioLastTime += time;
2312            info.refCount --;
2313        }
2314        if (params & kBatteryDataTrackVideo) {
2315            info.videoLastTime += time;
2316            info.refCount --;
2317        }
2318
2319        // no stream is being played by this UID
2320        if (info.refCount == 0) {
2321            info.audioTotalTime += info.audioLastTime;
2322            info.audioLastTime = 0;
2323            info.videoTotalTime += info.videoLastTime;
2324            info.videoLastTime = 0;
2325        }
2326    }
2327}
2328
2329status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
2330    Mutex::Autolock lock(mLock);
2331
2332    // audio output devices usage
2333    int32_t time = systemTime() / 1000000L; //in ms
2334    int32_t totalTime;
2335
2336    for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2337        totalTime = mBatteryAudio.totalTime[i];
2338
2339        if (mBatteryAudio.deviceOn[i]
2340            && (mBatteryAudio.lastTime[i] != 0)) {
2341                int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
2342                totalTime += tmpTime;
2343        }
2344
2345        reply->writeInt32(totalTime);
2346        // reset the total time
2347        mBatteryAudio.totalTime[i] = 0;
2348   }
2349
2350    // codec usage
2351    BatteryUsageInfo info;
2352    int size = mBatteryData.size();
2353
2354    reply->writeInt32(size);
2355    int i = 0;
2356
2357    while (i < size) {
2358        info = mBatteryData.valueAt(i);
2359
2360        reply->writeInt32(mBatteryData.keyAt(i)); //UID
2361        reply->writeInt32(info.audioTotalTime);
2362        reply->writeInt32(info.videoTotalTime);
2363
2364        info.audioTotalTime = 0;
2365        info.videoTotalTime = 0;
2366
2367        // remove the UID entry where no stream is being played
2368        if (info.refCount <= 0) {
2369            mBatteryData.removeItemsAt(i);
2370            size --;
2371            i --;
2372        }
2373        i++;
2374    }
2375    return NO_ERROR;
2376}
2377} // namespace android
2378