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