MediaPlayerService.cpp revision 2f6e73db45995636e5405fb2e1063a55550ba10f
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        audio_session_t 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    ALOGI("MediaPlayerService::getOMX");
350    Mutex::Autolock autoLock(mLock);
351
352    if (mOMX.get() == NULL) {
353        mOMX = new OMX;
354    }
355
356    return mOMX;
357}
358
359sp<ICrypto> MediaPlayerService::makeCrypto() {
360    return new Crypto;
361}
362
363sp<IDrm> MediaPlayerService::makeDrm() {
364    return new Drm;
365}
366
367sp<IHDCP> MediaPlayerService::makeHDCP(bool createEncryptionModule) {
368    return new HDCP(createEncryptionModule);
369}
370
371sp<IRemoteDisplay> MediaPlayerService::listenForRemoteDisplay(
372        const String16 &opPackageName,
373        const sp<IRemoteDisplayClient>& client, const String8& iface) {
374    if (!checkPermission("android.permission.CONTROL_WIFI_DISPLAY")) {
375        return NULL;
376    }
377
378    return new RemoteDisplay(opPackageName, client, iface.string());
379}
380
381status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
382{
383    const size_t SIZE = 256;
384    char buffer[SIZE];
385    String8 result;
386
387    result.append(" AudioOutput\n");
388    snprintf(buffer, 255, "  stream type(%d), left - right volume(%f, %f)\n",
389            mStreamType, mLeftVolume, mRightVolume);
390    result.append(buffer);
391    snprintf(buffer, 255, "  msec per frame(%f), latency (%d)\n",
392            mMsecsPerFrame, (mTrack != 0) ? mTrack->latency() : -1);
393    result.append(buffer);
394    snprintf(buffer, 255, "  aux effect id(%d), send level (%f)\n",
395            mAuxEffectId, mSendLevel);
396    result.append(buffer);
397
398    ::write(fd, result.string(), result.size());
399    if (mTrack != 0) {
400        mTrack->dump(fd, args);
401    }
402    return NO_ERROR;
403}
404
405status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args)
406{
407    const size_t SIZE = 256;
408    char buffer[SIZE];
409    String8 result;
410    result.append(" Client\n");
411    snprintf(buffer, 255, "  pid(%d), connId(%d), status(%d), looping(%s)\n",
412            mPid, mConnId, mStatus, mLoop?"true": "false");
413    result.append(buffer);
414    write(fd, result.string(), result.size());
415    if (mPlayer != NULL) {
416        mPlayer->dump(fd, args);
417    }
418    if (mAudioOutput != 0) {
419        mAudioOutput->dump(fd, args);
420    }
421    write(fd, "\n", 1);
422    return NO_ERROR;
423}
424
425/**
426 * The only arguments this understands right now are -c, -von and -voff,
427 * which are parsed by ALooperRoster::dump()
428 */
429status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
430{
431    const size_t SIZE = 256;
432    char buffer[SIZE];
433    String8 result;
434    SortedVector< sp<Client> > clients; //to serialise the mutex unlock & client destruction.
435    SortedVector< sp<MediaRecorderClient> > mediaRecorderClients;
436
437    if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
438        snprintf(buffer, SIZE, "Permission Denial: "
439                "can't dump MediaPlayerService from pid=%d, uid=%d\n",
440                IPCThreadState::self()->getCallingPid(),
441                IPCThreadState::self()->getCallingUid());
442        result.append(buffer);
443    } else {
444        Mutex::Autolock lock(mLock);
445        for (int i = 0, n = mClients.size(); i < n; ++i) {
446            sp<Client> c = mClients[i].promote();
447            if (c != 0) c->dump(fd, args);
448            clients.add(c);
449        }
450        if (mMediaRecorderClients.size() == 0) {
451                result.append(" No media recorder client\n\n");
452        } else {
453            for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
454                sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
455                if (c != 0) {
456                    snprintf(buffer, 255, " MediaRecorderClient pid(%d)\n", c->mPid);
457                    result.append(buffer);
458                    write(fd, result.string(), result.size());
459                    result = "\n";
460                    c->dump(fd, args);
461                    mediaRecorderClients.add(c);
462                }
463            }
464        }
465
466        result.append(" Files opened and/or mapped:\n");
467        snprintf(buffer, SIZE, "/proc/%d/maps", getpid());
468        FILE *f = fopen(buffer, "r");
469        if (f) {
470            while (!feof(f)) {
471                fgets(buffer, SIZE, f);
472                if (strstr(buffer, " /storage/") ||
473                    strstr(buffer, " /system/sounds/") ||
474                    strstr(buffer, " /data/") ||
475                    strstr(buffer, " /system/media/")) {
476                    result.append("  ");
477                    result.append(buffer);
478                }
479            }
480            fclose(f);
481        } else {
482            result.append("couldn't open ");
483            result.append(buffer);
484            result.append("\n");
485        }
486
487        snprintf(buffer, SIZE, "/proc/%d/fd", getpid());
488        DIR *d = opendir(buffer);
489        if (d) {
490            struct dirent *ent;
491            while((ent = readdir(d)) != NULL) {
492                if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
493                    snprintf(buffer, SIZE, "/proc/%d/fd/%s", getpid(), ent->d_name);
494                    struct stat s;
495                    if (lstat(buffer, &s) == 0) {
496                        if ((s.st_mode & S_IFMT) == S_IFLNK) {
497                            char linkto[256];
498                            int len = readlink(buffer, linkto, sizeof(linkto));
499                            if(len > 0) {
500                                if(len > 255) {
501                                    linkto[252] = '.';
502                                    linkto[253] = '.';
503                                    linkto[254] = '.';
504                                    linkto[255] = 0;
505                                } else {
506                                    linkto[len] = 0;
507                                }
508                                if (strstr(linkto, "/storage/") == linkto ||
509                                    strstr(linkto, "/system/sounds/") == linkto ||
510                                    strstr(linkto, "/data/") == linkto ||
511                                    strstr(linkto, "/system/media/") == linkto) {
512                                    result.append("  ");
513                                    result.append(buffer);
514                                    result.append(" -> ");
515                                    result.append(linkto);
516                                    result.append("\n");
517                                }
518                            }
519                        } else {
520                            result.append("  unexpected type for ");
521                            result.append(buffer);
522                            result.append("\n");
523                        }
524                    }
525                }
526            }
527            closedir(d);
528        } else {
529            result.append("couldn't open ");
530            result.append(buffer);
531            result.append("\n");
532        }
533
534        gLooperRoster.dump(fd, args);
535
536        bool dumpMem = false;
537        for (size_t i = 0; i < args.size(); i++) {
538            if (args[i] == String16("-m")) {
539                dumpMem = true;
540            }
541        }
542        if (dumpMem) {
543            dumpMemoryAddresses(fd);
544        }
545    }
546    write(fd, result.string(), result.size());
547    return NO_ERROR;
548}
549
550void MediaPlayerService::removeClient(wp<Client> client)
551{
552    Mutex::Autolock lock(mLock);
553    mClients.remove(client);
554}
555
556MediaPlayerService::Client::Client(
557        const sp<MediaPlayerService>& service, pid_t pid,
558        int32_t connId, const sp<IMediaPlayerClient>& client,
559        audio_session_t audioSessionId, uid_t uid)
560{
561    ALOGV("Client(%d) constructor", connId);
562    mPid = pid;
563    mConnId = connId;
564    mService = service;
565    mClient = client;
566    mLoop = false;
567    mStatus = NO_INIT;
568    mAudioSessionId = audioSessionId;
569    mUID = uid;
570    mRetransmitEndpointValid = false;
571    mAudioAttributes = NULL;
572
573#if CALLBACK_ANTAGONIZER
574    ALOGD("create Antagonizer");
575    mAntagonizer = new Antagonizer(notify, this);
576#endif
577}
578
579MediaPlayerService::Client::~Client()
580{
581    ALOGV("Client(%d) destructor pid = %d", mConnId, mPid);
582    mAudioOutput.clear();
583    wp<Client> client(this);
584    disconnect();
585    mService->removeClient(client);
586    if (mAudioAttributes != NULL) {
587        free(mAudioAttributes);
588    }
589}
590
591void MediaPlayerService::Client::disconnect()
592{
593    ALOGV("disconnect(%d) from pid %d", mConnId, mPid);
594    // grab local reference and clear main reference to prevent future
595    // access to object
596    sp<MediaPlayerBase> p;
597    {
598        Mutex::Autolock l(mLock);
599        p = mPlayer;
600        mClient.clear();
601    }
602
603    mPlayer.clear();
604
605    // clear the notification to prevent callbacks to dead client
606    // and reset the player. We assume the player will serialize
607    // access to itself if necessary.
608    if (p != 0) {
609        p->setNotifyCallback(0, 0);
610#if CALLBACK_ANTAGONIZER
611        ALOGD("kill Antagonizer");
612        mAntagonizer->kill();
613#endif
614        p->reset();
615    }
616
617    disconnectNativeWindow();
618
619    IPCThreadState::self()->flushCommands();
620}
621
622sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
623{
624    // determine if we have the right player type
625    sp<MediaPlayerBase> p = mPlayer;
626    if ((p != NULL) && (p->playerType() != playerType)) {
627        ALOGV("delete player");
628        p.clear();
629    }
630    if (p == NULL) {
631        p = MediaPlayerFactory::createPlayer(playerType, this, notify, mPid);
632    }
633
634    if (p != NULL) {
635        p->setUID(mUID);
636    }
637
638    return p;
639}
640
641sp<MediaPlayerBase> MediaPlayerService::Client::setDataSource_pre(
642        player_type playerType)
643{
644    ALOGV("player type = %d", playerType);
645
646    // create the right type of player
647    sp<MediaPlayerBase> p = createPlayer(playerType);
648    if (p == NULL) {
649        return p;
650    }
651
652    if (!p->hardwareOutput()) {
653        Mutex::Autolock l(mLock);
654        mAudioOutput = new AudioOutput(mAudioSessionId, IPCThreadState::self()->getCallingUid(),
655                mPid, mAudioAttributes);
656        static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
657    }
658
659    return p;
660}
661
662void MediaPlayerService::Client::setDataSource_post(
663        const sp<MediaPlayerBase>& p,
664        status_t status)
665{
666    ALOGV(" setDataSource");
667    mStatus = status;
668    if (mStatus != OK) {
669        ALOGE("  error: %d", mStatus);
670        return;
671    }
672
673    // Set the re-transmission endpoint if one was chosen.
674    if (mRetransmitEndpointValid) {
675        mStatus = p->setRetransmitEndpoint(&mRetransmitEndpoint);
676        if (mStatus != NO_ERROR) {
677            ALOGE("setRetransmitEndpoint error: %d", mStatus);
678        }
679    }
680
681    if (mStatus == OK) {
682        mPlayer = p;
683    }
684}
685
686status_t MediaPlayerService::Client::setDataSource(
687        const sp<IMediaHTTPService> &httpService,
688        const char *url,
689        const KeyedVector<String8, String8> *headers)
690{
691    ALOGV("setDataSource(%s)", url);
692    if (url == NULL)
693        return UNKNOWN_ERROR;
694
695    if ((strncmp(url, "http://", 7) == 0) ||
696        (strncmp(url, "https://", 8) == 0) ||
697        (strncmp(url, "rtsp://", 7) == 0)) {
698        if (!checkPermission("android.permission.INTERNET")) {
699            return PERMISSION_DENIED;
700        }
701    }
702
703    if (strncmp(url, "content://", 10) == 0) {
704        // get a filedescriptor for the content Uri and
705        // pass it to the setDataSource(fd) method
706
707        String16 url16(url);
708        int fd = android::openContentProviderFile(url16);
709        if (fd < 0)
710        {
711            ALOGE("Couldn't open fd for %s", url);
712            return UNKNOWN_ERROR;
713        }
714        setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
715        close(fd);
716        return mStatus;
717    } else {
718        player_type playerType = MediaPlayerFactory::getPlayerType(this, url);
719        sp<MediaPlayerBase> p = setDataSource_pre(playerType);
720        if (p == NULL) {
721            return NO_INIT;
722        }
723
724        setDataSource_post(p, p->setDataSource(httpService, url, headers));
725        return mStatus;
726    }
727}
728
729status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
730{
731    ALOGV("setDataSource fd=%d (%s), offset=%lld, length=%lld",
732            fd, nameForFd(fd).c_str(), (long long) offset, (long long) length);
733    struct stat sb;
734    int ret = fstat(fd, &sb);
735    if (ret != 0) {
736        ALOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
737        return UNKNOWN_ERROR;
738    }
739
740    ALOGV("st_dev  = %llu", static_cast<uint64_t>(sb.st_dev));
741    ALOGV("st_mode = %u", sb.st_mode);
742    ALOGV("st_uid  = %lu", static_cast<unsigned long>(sb.st_uid));
743    ALOGV("st_gid  = %lu", static_cast<unsigned long>(sb.st_gid));
744    ALOGV("st_size = %llu", sb.st_size);
745
746    if (offset >= sb.st_size) {
747        ALOGE("offset error");
748        return UNKNOWN_ERROR;
749    }
750    if (offset + length > sb.st_size) {
751        length = sb.st_size - offset;
752        ALOGV("calculated length = %lld", length);
753    }
754
755    player_type playerType = MediaPlayerFactory::getPlayerType(this,
756                                                               fd,
757                                                               offset,
758                                                               length);
759    sp<MediaPlayerBase> p = setDataSource_pre(playerType);
760    if (p == NULL) {
761        return NO_INIT;
762    }
763
764    // now set data source
765    setDataSource_post(p, p->setDataSource(fd, offset, length));
766    return mStatus;
767}
768
769status_t MediaPlayerService::Client::setDataSource(
770        const sp<IStreamSource> &source) {
771    // create the right type of player
772    player_type playerType = MediaPlayerFactory::getPlayerType(this, source);
773    sp<MediaPlayerBase> p = setDataSource_pre(playerType);
774    if (p == NULL) {
775        return NO_INIT;
776    }
777
778    // now set data source
779    setDataSource_post(p, p->setDataSource(source));
780    return mStatus;
781}
782
783status_t MediaPlayerService::Client::setDataSource(
784        const sp<IDataSource> &source) {
785    sp<DataSource> dataSource = DataSource::CreateFromIDataSource(source);
786    player_type playerType = MediaPlayerFactory::getPlayerType(this, dataSource);
787    sp<MediaPlayerBase> p = setDataSource_pre(playerType);
788    if (p == NULL) {
789        return NO_INIT;
790    }
791    // now set data source
792    setDataSource_post(p, p->setDataSource(dataSource));
793    return mStatus;
794}
795
796void MediaPlayerService::Client::disconnectNativeWindow() {
797    if (mConnectedWindow != NULL) {
798        status_t err = native_window_api_disconnect(mConnectedWindow.get(),
799                NATIVE_WINDOW_API_MEDIA);
800
801        if (err != OK) {
802            ALOGW("native_window_api_disconnect returned an error: %s (%d)",
803                    strerror(-err), err);
804        }
805    }
806    mConnectedWindow.clear();
807}
808
809status_t MediaPlayerService::Client::setVideoSurfaceTexture(
810        const sp<IGraphicBufferProducer>& bufferProducer)
811{
812    ALOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, bufferProducer.get());
813    sp<MediaPlayerBase> p = getPlayer();
814    if (p == 0) return UNKNOWN_ERROR;
815
816    sp<IBinder> binder(IInterface::asBinder(bufferProducer));
817    if (mConnectedWindowBinder == binder) {
818        return OK;
819    }
820
821    sp<ANativeWindow> anw;
822    if (bufferProducer != NULL) {
823        anw = new Surface(bufferProducer, true /* controlledByApp */);
824        status_t err = native_window_api_connect(anw.get(),
825                NATIVE_WINDOW_API_MEDIA);
826
827        if (err != OK) {
828            ALOGE("setVideoSurfaceTexture failed: %d", err);
829            // Note that we must do the reset before disconnecting from the ANW.
830            // Otherwise queue/dequeue calls could be made on the disconnected
831            // ANW, which may result in errors.
832            reset();
833
834            disconnectNativeWindow();
835
836            return err;
837        }
838    }
839
840    // Note that we must set the player's new GraphicBufferProducer before
841    // disconnecting the old one.  Otherwise queue/dequeue calls could be made
842    // on the disconnected ANW, which may result in errors.
843    status_t err = p->setVideoSurfaceTexture(bufferProducer);
844
845    disconnectNativeWindow();
846
847    mConnectedWindow = anw;
848
849    if (err == OK) {
850        mConnectedWindowBinder = binder;
851    } else {
852        disconnectNativeWindow();
853    }
854
855    return err;
856}
857
858status_t MediaPlayerService::Client::invoke(const Parcel& request,
859                                            Parcel *reply)
860{
861    sp<MediaPlayerBase> p = getPlayer();
862    if (p == NULL) return UNKNOWN_ERROR;
863    return p->invoke(request, reply);
864}
865
866// This call doesn't need to access the native player.
867status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
868{
869    status_t status;
870    media::Metadata::Filter allow, drop;
871
872    if (unmarshallFilter(filter, &allow, &status) &&
873        unmarshallFilter(filter, &drop, &status)) {
874        Mutex::Autolock lock(mLock);
875
876        mMetadataAllow = allow;
877        mMetadataDrop = drop;
878    }
879    return status;
880}
881
882status_t MediaPlayerService::Client::getMetadata(
883        bool update_only, bool /*apply_filter*/, Parcel *reply)
884{
885    sp<MediaPlayerBase> player = getPlayer();
886    if (player == 0) return UNKNOWN_ERROR;
887
888    status_t status;
889    // Placeholder for the return code, updated by the caller.
890    reply->writeInt32(-1);
891
892    media::Metadata::Filter ids;
893
894    // We don't block notifications while we fetch the data. We clear
895    // mMetadataUpdated first so we don't lose notifications happening
896    // during the rest of this call.
897    {
898        Mutex::Autolock lock(mLock);
899        if (update_only) {
900            ids = mMetadataUpdated;
901        }
902        mMetadataUpdated.clear();
903    }
904
905    media::Metadata metadata(reply);
906
907    metadata.appendHeader();
908    status = player->getMetadata(ids, reply);
909
910    if (status != OK) {
911        metadata.resetParcel();
912        ALOGE("getMetadata failed %d", status);
913        return status;
914    }
915
916    // FIXME: Implement filtering on the result. Not critical since
917    // filtering takes place on the update notifications already. This
918    // would be when all the metadata are fetch and a filter is set.
919
920    // Everything is fine, update the metadata length.
921    metadata.updateLength();
922    return OK;
923}
924
925status_t MediaPlayerService::Client::prepareAsync()
926{
927    ALOGV("[%d] prepareAsync", mConnId);
928    sp<MediaPlayerBase> p = getPlayer();
929    if (p == 0) return UNKNOWN_ERROR;
930    status_t ret = p->prepareAsync();
931#if CALLBACK_ANTAGONIZER
932    ALOGD("start Antagonizer");
933    if (ret == NO_ERROR) mAntagonizer->start();
934#endif
935    return ret;
936}
937
938status_t MediaPlayerService::Client::start()
939{
940    ALOGV("[%d] start", mConnId);
941    sp<MediaPlayerBase> p = getPlayer();
942    if (p == 0) return UNKNOWN_ERROR;
943    p->setLooping(mLoop);
944    return p->start();
945}
946
947status_t MediaPlayerService::Client::stop()
948{
949    ALOGV("[%d] stop", mConnId);
950    sp<MediaPlayerBase> p = getPlayer();
951    if (p == 0) return UNKNOWN_ERROR;
952    return p->stop();
953}
954
955status_t MediaPlayerService::Client::pause()
956{
957    ALOGV("[%d] pause", mConnId);
958    sp<MediaPlayerBase> p = getPlayer();
959    if (p == 0) return UNKNOWN_ERROR;
960    return p->pause();
961}
962
963status_t MediaPlayerService::Client::isPlaying(bool* state)
964{
965    *state = false;
966    sp<MediaPlayerBase> p = getPlayer();
967    if (p == 0) return UNKNOWN_ERROR;
968    *state = p->isPlaying();
969    ALOGV("[%d] isPlaying: %d", mConnId, *state);
970    return NO_ERROR;
971}
972
973status_t MediaPlayerService::Client::setPlaybackSettings(const AudioPlaybackRate& rate)
974{
975    ALOGV("[%d] setPlaybackSettings(%f, %f, %d, %d)",
976            mConnId, rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
977    sp<MediaPlayerBase> p = getPlayer();
978    if (p == 0) return UNKNOWN_ERROR;
979    return p->setPlaybackSettings(rate);
980}
981
982status_t MediaPlayerService::Client::getPlaybackSettings(AudioPlaybackRate* rate /* nonnull */)
983{
984    sp<MediaPlayerBase> p = getPlayer();
985    if (p == 0) return UNKNOWN_ERROR;
986    status_t ret = p->getPlaybackSettings(rate);
987    if (ret == NO_ERROR) {
988        ALOGV("[%d] getPlaybackSettings(%f, %f, %d, %d)",
989                mConnId, rate->mSpeed, rate->mPitch, rate->mFallbackMode, rate->mStretchMode);
990    } else {
991        ALOGV("[%d] getPlaybackSettings returned %d", mConnId, ret);
992    }
993    return ret;
994}
995
996status_t MediaPlayerService::Client::setSyncSettings(
997        const AVSyncSettings& sync, float videoFpsHint)
998{
999    ALOGV("[%d] setSyncSettings(%u, %u, %f, %f)",
1000            mConnId, sync.mSource, sync.mAudioAdjustMode, sync.mTolerance, videoFpsHint);
1001    sp<MediaPlayerBase> p = getPlayer();
1002    if (p == 0) return UNKNOWN_ERROR;
1003    return p->setSyncSettings(sync, videoFpsHint);
1004}
1005
1006status_t MediaPlayerService::Client::getSyncSettings(
1007        AVSyncSettings* sync /* nonnull */, float* videoFps /* nonnull */)
1008{
1009    sp<MediaPlayerBase> p = getPlayer();
1010    if (p == 0) return UNKNOWN_ERROR;
1011    status_t ret = p->getSyncSettings(sync, videoFps);
1012    if (ret == NO_ERROR) {
1013        ALOGV("[%d] getSyncSettings(%u, %u, %f, %f)",
1014                mConnId, sync->mSource, sync->mAudioAdjustMode, sync->mTolerance, *videoFps);
1015    } else {
1016        ALOGV("[%d] getSyncSettings returned %d", mConnId, ret);
1017    }
1018    return ret;
1019}
1020
1021status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
1022{
1023    ALOGV("getCurrentPosition");
1024    sp<MediaPlayerBase> p = getPlayer();
1025    if (p == 0) return UNKNOWN_ERROR;
1026    status_t ret = p->getCurrentPosition(msec);
1027    if (ret == NO_ERROR) {
1028        ALOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
1029    } else {
1030        ALOGE("getCurrentPosition returned %d", ret);
1031    }
1032    return ret;
1033}
1034
1035status_t MediaPlayerService::Client::getDuration(int *msec)
1036{
1037    ALOGV("getDuration");
1038    sp<MediaPlayerBase> p = getPlayer();
1039    if (p == 0) return UNKNOWN_ERROR;
1040    status_t ret = p->getDuration(msec);
1041    if (ret == NO_ERROR) {
1042        ALOGV("[%d] getDuration = %d", mConnId, *msec);
1043    } else {
1044        ALOGE("getDuration returned %d", ret);
1045    }
1046    return ret;
1047}
1048
1049status_t MediaPlayerService::Client::setNextPlayer(const sp<IMediaPlayer>& player) {
1050    ALOGV("setNextPlayer");
1051    Mutex::Autolock l(mLock);
1052    sp<Client> c = static_cast<Client*>(player.get());
1053    mNextClient = c;
1054
1055    if (c != NULL) {
1056        if (mAudioOutput != NULL) {
1057            mAudioOutput->setNextOutput(c->mAudioOutput);
1058        } else if ((mPlayer != NULL) && !mPlayer->hardwareOutput()) {
1059            ALOGE("no current audio output");
1060        }
1061
1062        if ((mPlayer != NULL) && (mNextClient->getPlayer() != NULL)) {
1063            mPlayer->setNextPlayer(mNextClient->getPlayer());
1064        }
1065    }
1066
1067    return OK;
1068}
1069
1070status_t MediaPlayerService::Client::seekTo(int msec)
1071{
1072    ALOGV("[%d] seekTo(%d)", mConnId, msec);
1073    sp<MediaPlayerBase> p = getPlayer();
1074    if (p == 0) return UNKNOWN_ERROR;
1075    return p->seekTo(msec);
1076}
1077
1078status_t MediaPlayerService::Client::reset()
1079{
1080    ALOGV("[%d] reset", mConnId);
1081    mRetransmitEndpointValid = false;
1082    sp<MediaPlayerBase> p = getPlayer();
1083    if (p == 0) return UNKNOWN_ERROR;
1084    return p->reset();
1085}
1086
1087status_t MediaPlayerService::Client::setAudioStreamType(audio_stream_type_t type)
1088{
1089    ALOGV("[%d] setAudioStreamType(%d)", mConnId, type);
1090    // TODO: for hardware output, call player instead
1091    Mutex::Autolock l(mLock);
1092    if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1093    return NO_ERROR;
1094}
1095
1096status_t MediaPlayerService::Client::setAudioAttributes_l(const Parcel &parcel)
1097{
1098    if (mAudioAttributes != NULL) { free(mAudioAttributes); }
1099    mAudioAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1100    if (mAudioAttributes == NULL) {
1101        return NO_MEMORY;
1102    }
1103    unmarshallAudioAttributes(parcel, mAudioAttributes);
1104
1105    ALOGV("setAudioAttributes_l() usage=%d content=%d flags=0x%x tags=%s",
1106            mAudioAttributes->usage, mAudioAttributes->content_type, mAudioAttributes->flags,
1107            mAudioAttributes->tags);
1108
1109    if (mAudioOutput != 0) {
1110        mAudioOutput->setAudioAttributes(mAudioAttributes);
1111    }
1112    return NO_ERROR;
1113}
1114
1115status_t MediaPlayerService::Client::setLooping(int loop)
1116{
1117    ALOGV("[%d] setLooping(%d)", mConnId, loop);
1118    mLoop = loop;
1119    sp<MediaPlayerBase> p = getPlayer();
1120    if (p != 0) return p->setLooping(loop);
1121    return NO_ERROR;
1122}
1123
1124status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1125{
1126    ALOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
1127
1128    // for hardware output, call player instead
1129    sp<MediaPlayerBase> p = getPlayer();
1130    {
1131      Mutex::Autolock l(mLock);
1132      if (p != 0 && p->hardwareOutput()) {
1133          MediaPlayerHWInterface* hwp =
1134                  reinterpret_cast<MediaPlayerHWInterface*>(p.get());
1135          return hwp->setVolume(leftVolume, rightVolume);
1136      } else {
1137          if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1138          return NO_ERROR;
1139      }
1140    }
1141
1142    return NO_ERROR;
1143}
1144
1145status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1146{
1147    ALOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
1148    Mutex::Autolock l(mLock);
1149    if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1150    return NO_ERROR;
1151}
1152
1153status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1154{
1155    ALOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
1156    Mutex::Autolock l(mLock);
1157    if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1158    return NO_ERROR;
1159}
1160
1161status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
1162    ALOGV("[%d] setParameter(%d)", mConnId, key);
1163    switch (key) {
1164    case KEY_PARAMETER_AUDIO_ATTRIBUTES:
1165    {
1166        Mutex::Autolock l(mLock);
1167        return setAudioAttributes_l(request);
1168    }
1169    default:
1170        sp<MediaPlayerBase> p = getPlayer();
1171        if (p == 0) { return UNKNOWN_ERROR; }
1172        return p->setParameter(key, request);
1173    }
1174}
1175
1176status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
1177    ALOGV("[%d] getParameter(%d)", mConnId, key);
1178    sp<MediaPlayerBase> p = getPlayer();
1179    if (p == 0) return UNKNOWN_ERROR;
1180    return p->getParameter(key, reply);
1181}
1182
1183status_t MediaPlayerService::Client::setRetransmitEndpoint(
1184        const struct sockaddr_in* endpoint) {
1185
1186    if (NULL != endpoint) {
1187        uint32_t a = ntohl(endpoint->sin_addr.s_addr);
1188        uint16_t p = ntohs(endpoint->sin_port);
1189        ALOGV("[%d] setRetransmitEndpoint(%u.%u.%u.%u:%hu)", mConnId,
1190                (a >> 24), (a >> 16) & 0xFF, (a >> 8) & 0xFF, (a & 0xFF), p);
1191    } else {
1192        ALOGV("[%d] setRetransmitEndpoint = <none>", mConnId);
1193    }
1194
1195    sp<MediaPlayerBase> p = getPlayer();
1196
1197    // Right now, the only valid time to set a retransmit endpoint is before
1198    // player selection has been made (since the presence or absence of a
1199    // retransmit endpoint is going to determine which player is selected during
1200    // setDataSource).
1201    if (p != 0) return INVALID_OPERATION;
1202
1203    if (NULL != endpoint) {
1204        mRetransmitEndpoint = *endpoint;
1205        mRetransmitEndpointValid = true;
1206    } else {
1207        mRetransmitEndpointValid = false;
1208    }
1209
1210    return NO_ERROR;
1211}
1212
1213status_t MediaPlayerService::Client::getRetransmitEndpoint(
1214        struct sockaddr_in* endpoint)
1215{
1216    if (NULL == endpoint)
1217        return BAD_VALUE;
1218
1219    sp<MediaPlayerBase> p = getPlayer();
1220
1221    if (p != NULL)
1222        return p->getRetransmitEndpoint(endpoint);
1223
1224    if (!mRetransmitEndpointValid)
1225        return NO_INIT;
1226
1227    *endpoint = mRetransmitEndpoint;
1228
1229    return NO_ERROR;
1230}
1231
1232void MediaPlayerService::Client::notify(
1233        void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
1234{
1235    Client* client = static_cast<Client*>(cookie);
1236    if (client == NULL) {
1237        return;
1238    }
1239
1240    sp<IMediaPlayerClient> c;
1241    {
1242        Mutex::Autolock l(client->mLock);
1243        c = client->mClient;
1244        if (msg == MEDIA_PLAYBACK_COMPLETE && client->mNextClient != NULL) {
1245            if (client->mAudioOutput != NULL)
1246                client->mAudioOutput->switchToNextOutput();
1247            client->mNextClient->start();
1248            if (client->mNextClient->mClient != NULL) {
1249                client->mNextClient->mClient->notify(
1250                        MEDIA_INFO, MEDIA_INFO_STARTED_AS_NEXT, 0, obj);
1251            }
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(audio_session_t sessionId, int uid, int pid,
1336        const audio_attributes_t* attr)
1337    : mCallback(NULL),
1338      mCallbackCookie(NULL),
1339      mCallbackData(NULL),
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    ExtendedTimestamp ets;
1529    status_t status = mTrack->getTimestamp(&ets);
1530    if (status == OK || status == WOULD_BLOCK) {
1531        *frameswritten = (uint32_t)ets.mPosition[ExtendedTimestamp::LOCATION_CLIENT];
1532    }
1533    return status;
1534}
1535
1536status_t MediaPlayerService::AudioOutput::setParameters(const String8& keyValuePairs)
1537{
1538    Mutex::Autolock lock(mLock);
1539    if (mTrack == 0) return NO_INIT;
1540    return mTrack->setParameters(keyValuePairs);
1541}
1542
1543String8  MediaPlayerService::AudioOutput::getParameters(const String8& keys)
1544{
1545    Mutex::Autolock lock(mLock);
1546    if (mTrack == 0) return String8::empty();
1547    return mTrack->getParameters(keys);
1548}
1549
1550void MediaPlayerService::AudioOutput::setAudioAttributes(const audio_attributes_t * attributes) {
1551    Mutex::Autolock lock(mLock);
1552    if (attributes == NULL) {
1553        free(mAttributes);
1554        mAttributes = NULL;
1555    } else {
1556        if (mAttributes == NULL) {
1557            mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1558        }
1559        memcpy(mAttributes, attributes, sizeof(audio_attributes_t));
1560        mStreamType = audio_attributes_to_stream_type(attributes);
1561    }
1562}
1563
1564void MediaPlayerService::AudioOutput::setAudioStreamType(audio_stream_type_t streamType)
1565{
1566    Mutex::Autolock lock(mLock);
1567    // do not allow direct stream type modification if attributes have been set
1568    if (mAttributes == NULL) {
1569        mStreamType = streamType;
1570    }
1571}
1572
1573void MediaPlayerService::AudioOutput::deleteRecycledTrack_l()
1574{
1575    ALOGV("deleteRecycledTrack_l");
1576    if (mRecycledTrack != 0) {
1577
1578        if (mCallbackData != NULL) {
1579            mCallbackData->setOutput(NULL);
1580            mCallbackData->endTrackSwitch();
1581        }
1582
1583        if ((mRecycledTrack->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) {
1584            int32_t msec = 0;
1585            if (!mRecycledTrack->stopped()) { // check if active
1586                 (void)mRecycledTrack->pendingDuration(&msec);
1587            }
1588            mRecycledTrack->stop(); // ensure full data drain
1589            ALOGD("deleting recycled track, waiting for data drain (%d msec)", msec);
1590            if (msec > 0) {
1591                static const int32_t WAIT_LIMIT_MS = 3000;
1592                if (msec > WAIT_LIMIT_MS) {
1593                    msec = WAIT_LIMIT_MS;
1594                }
1595                usleep(msec * 1000LL);
1596            }
1597        }
1598        // An offloaded track isn't flushed because the STREAM_END is reported
1599        // slightly prematurely to allow time for the gapless track switch
1600        // but this means that if we decide not to recycle the track there
1601        // could be a small amount of residual data still playing. We leave
1602        // AudioFlinger to drain the track.
1603
1604        mRecycledTrack.clear();
1605        close_l();
1606        delete mCallbackData;
1607        mCallbackData = NULL;
1608    }
1609}
1610
1611void MediaPlayerService::AudioOutput::close_l()
1612{
1613    mTrack.clear();
1614}
1615
1616status_t MediaPlayerService::AudioOutput::open(
1617        uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
1618        audio_format_t format, int bufferCount,
1619        AudioCallback cb, void *cookie,
1620        audio_output_flags_t flags,
1621        const audio_offload_info_t *offloadInfo,
1622        bool doNotReconnect,
1623        uint32_t suggestedFrameCount)
1624{
1625    ALOGV("open(%u, %d, 0x%x, 0x%x, %d, %d 0x%x)", sampleRate, channelCount, channelMask,
1626                format, bufferCount, mSessionId, flags);
1627
1628    // offloading is only supported in callback mode for now.
1629    // offloadInfo must be present if offload flag is set
1630    if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) &&
1631            ((cb == NULL) || (offloadInfo == NULL))) {
1632        return BAD_VALUE;
1633    }
1634
1635    // compute frame count for the AudioTrack internal buffer
1636    size_t frameCount;
1637    if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1638        frameCount = 0; // AudioTrack will get frame count from AudioFlinger
1639    } else {
1640        // try to estimate the buffer processing fetch size from AudioFlinger.
1641        // framesPerBuffer is approximate and generally correct, except when it's not :-).
1642        uint32_t afSampleRate;
1643        size_t afFrameCount;
1644        if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1645            return NO_INIT;
1646        }
1647        if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1648            return NO_INIT;
1649        }
1650        const size_t framesPerBuffer =
1651                (unsigned long long)sampleRate * afFrameCount / afSampleRate;
1652
1653        if (bufferCount == 0) {
1654            // use suggestedFrameCount
1655            bufferCount = (suggestedFrameCount + framesPerBuffer - 1) / framesPerBuffer;
1656        }
1657        // Check argument bufferCount against the mininum buffer count
1658        if (bufferCount != 0 && bufferCount < mMinBufferCount) {
1659            ALOGV("bufferCount (%d) increased to %d", bufferCount, mMinBufferCount);
1660            bufferCount = mMinBufferCount;
1661        }
1662        // if frameCount is 0, then AudioTrack will get frame count from AudioFlinger
1663        // which will be the minimum size permitted.
1664        frameCount = bufferCount * framesPerBuffer;
1665    }
1666
1667    if (channelMask == CHANNEL_MASK_USE_CHANNEL_ORDER) {
1668        channelMask = audio_channel_out_mask_from_count(channelCount);
1669        if (0 == channelMask) {
1670            ALOGE("open() error, can\'t derive mask for %d audio channels", channelCount);
1671            return NO_INIT;
1672        }
1673    }
1674
1675    Mutex::Autolock lock(mLock);
1676    mCallback = cb;
1677    mCallbackCookie = cookie;
1678
1679    // Check whether we can recycle the track
1680    bool reuse = false;
1681    bool bothOffloaded = false;
1682
1683    if (mRecycledTrack != 0) {
1684        // check whether we are switching between two offloaded tracks
1685        bothOffloaded = (flags & mRecycledTrack->getFlags()
1686                                & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0;
1687
1688        // check if the existing track can be reused as-is, or if a new track needs to be created.
1689        reuse = true;
1690
1691        if ((mCallbackData == NULL && mCallback != NULL) ||
1692                (mCallbackData != NULL && mCallback == NULL)) {
1693            // recycled track uses callbacks but the caller wants to use writes, or vice versa
1694            ALOGV("can't chain callback and write");
1695            reuse = false;
1696        } else if ((mRecycledTrack->getSampleRate() != sampleRate) ||
1697                (mRecycledTrack->channelCount() != (uint32_t)channelCount) ) {
1698            ALOGV("samplerate, channelcount differ: %u/%u Hz, %u/%d ch",
1699                  mRecycledTrack->getSampleRate(), sampleRate,
1700                  mRecycledTrack->channelCount(), channelCount);
1701            reuse = false;
1702        } else if (flags != mFlags) {
1703            ALOGV("output flags differ %08x/%08x", flags, mFlags);
1704            reuse = false;
1705        } else if (mRecycledTrack->format() != format) {
1706            reuse = false;
1707        }
1708    } else {
1709        ALOGV("no track available to recycle");
1710    }
1711
1712    ALOGV_IF(bothOffloaded, "both tracks offloaded");
1713
1714    // If we can't recycle and both tracks are offloaded
1715    // we must close the previous output before opening a new one
1716    if (bothOffloaded && !reuse) {
1717        ALOGV("both offloaded and not recycling");
1718        deleteRecycledTrack_l();
1719    }
1720
1721    sp<AudioTrack> t;
1722    CallbackData *newcbd = NULL;
1723
1724    // We don't attempt to create a new track if we are recycling an
1725    // offloaded track. But, if we are recycling a non-offloaded or we
1726    // are switching where one is offloaded and one isn't then we create
1727    // the new track in advance so that we can read additional stream info
1728
1729    if (!(reuse && bothOffloaded)) {
1730        ALOGV("creating new AudioTrack");
1731
1732        if (mCallback != NULL) {
1733            newcbd = new CallbackData(this);
1734            t = new AudioTrack(
1735                    mStreamType,
1736                    sampleRate,
1737                    format,
1738                    channelMask,
1739                    frameCount,
1740                    flags,
1741                    CallbackWrapper,
1742                    newcbd,
1743                    0,  // notification frames
1744                    mSessionId,
1745                    AudioTrack::TRANSFER_CALLBACK,
1746                    offloadInfo,
1747                    mUid,
1748                    mPid,
1749                    mAttributes,
1750                    doNotReconnect);
1751        } else {
1752            t = new AudioTrack(
1753                    mStreamType,
1754                    sampleRate,
1755                    format,
1756                    channelMask,
1757                    frameCount,
1758                    flags,
1759                    NULL, // callback
1760                    NULL, // user data
1761                    0, // notification frames
1762                    mSessionId,
1763                    AudioTrack::TRANSFER_DEFAULT,
1764                    NULL, // offload info
1765                    mUid,
1766                    mPid,
1767                    mAttributes,
1768                    doNotReconnect);
1769        }
1770
1771        if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1772            ALOGE("Unable to create audio track");
1773            delete newcbd;
1774            // t goes out of scope, so reference count drops to zero
1775            return NO_INIT;
1776        } else {
1777            // successful AudioTrack initialization implies a legacy stream type was generated
1778            // from the audio attributes
1779            mStreamType = t->streamType();
1780        }
1781    }
1782
1783    if (reuse) {
1784        CHECK(mRecycledTrack != NULL);
1785
1786        if (!bothOffloaded) {
1787            if (mRecycledTrack->frameCount() != t->frameCount()) {
1788                ALOGV("framecount differs: %u/%u frames",
1789                      mRecycledTrack->frameCount(), t->frameCount());
1790                reuse = false;
1791            }
1792        }
1793
1794        if (reuse) {
1795            ALOGV("chaining to next output and recycling track");
1796            close_l();
1797            mTrack = mRecycledTrack;
1798            mRecycledTrack.clear();
1799            if (mCallbackData != NULL) {
1800                mCallbackData->setOutput(this);
1801            }
1802            delete newcbd;
1803            return OK;
1804        }
1805    }
1806
1807    // we're not going to reuse the track, unblock and flush it
1808    // this was done earlier if both tracks are offloaded
1809    if (!bothOffloaded) {
1810        deleteRecycledTrack_l();
1811    }
1812
1813    CHECK((t != NULL) && ((mCallback == NULL) || (newcbd != NULL)));
1814
1815    mCallbackData = newcbd;
1816    ALOGV("setVolume");
1817    t->setVolume(mLeftVolume, mRightVolume);
1818
1819    mSampleRateHz = sampleRate;
1820    mFlags = flags;
1821    mMsecsPerFrame = 1E3f / (mPlaybackRate.mSpeed * sampleRate);
1822    mFrameSize = t->frameSize();
1823    mTrack = t;
1824
1825    status_t res = NO_ERROR;
1826    // Note some output devices may give us a direct track even though we don't specify it.
1827    // Example: Line application b/17459982.
1828    if ((t->getFlags() & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) {
1829        res = t->setPlaybackRate(mPlaybackRate);
1830        if (res == NO_ERROR) {
1831            t->setAuxEffectSendLevel(mSendLevel);
1832            res = t->attachAuxEffect(mAuxEffectId);
1833        }
1834    }
1835    ALOGV("open() DONE status %d", res);
1836    return res;
1837}
1838
1839status_t MediaPlayerService::AudioOutput::start()
1840{
1841    ALOGV("start");
1842    Mutex::Autolock lock(mLock);
1843    if (mCallbackData != NULL) {
1844        mCallbackData->endTrackSwitch();
1845    }
1846    if (mTrack != 0) {
1847        mTrack->setVolume(mLeftVolume, mRightVolume);
1848        mTrack->setAuxEffectSendLevel(mSendLevel);
1849        return mTrack->start();
1850    }
1851    return NO_INIT;
1852}
1853
1854void MediaPlayerService::AudioOutput::setNextOutput(const sp<AudioOutput>& nextOutput) {
1855    Mutex::Autolock lock(mLock);
1856    mNextOutput = nextOutput;
1857}
1858
1859void MediaPlayerService::AudioOutput::switchToNextOutput() {
1860    ALOGV("switchToNextOutput");
1861
1862    // Try to acquire the callback lock before moving track (without incurring deadlock).
1863    const unsigned kMaxSwitchTries = 100;
1864    Mutex::Autolock lock(mLock);
1865    for (unsigned tries = 0;;) {
1866        if (mTrack == 0) {
1867            return;
1868        }
1869        if (mNextOutput != NULL && mNextOutput != this) {
1870            if (mCallbackData != NULL) {
1871                // two alternative approaches
1872#if 1
1873                CallbackData *callbackData = mCallbackData;
1874                mLock.unlock();
1875                // proper acquisition sequence
1876                callbackData->lock();
1877                mLock.lock();
1878                // Caution: it is unlikely that someone deleted our callback or changed our target
1879                if (callbackData != mCallbackData || mNextOutput == NULL || mNextOutput == this) {
1880                    // fatal if we are starved out.
1881                    LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
1882                            "switchToNextOutput() cannot obtain correct lock sequence");
1883                    callbackData->unlock();
1884                    continue;
1885                }
1886                callbackData->mSwitching = true; // begin track switch
1887#else
1888                // tryBeginTrackSwitch() returns false if the callback has the lock.
1889                if (!mCallbackData->tryBeginTrackSwitch()) {
1890                    // fatal if we are starved out.
1891                    LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
1892                            "switchToNextOutput() cannot obtain callback lock");
1893                    mLock.unlock();
1894                    usleep(5 * 1000 /* usec */); // allow callback to use AudioOutput
1895                    mLock.lock();
1896                    continue;
1897                }
1898#endif
1899            }
1900
1901            Mutex::Autolock nextLock(mNextOutput->mLock);
1902
1903            // If the next output track is not NULL, then it has been
1904            // opened already for playback.
1905            // This is possible even without the next player being started,
1906            // for example, the next player could be prepared and seeked.
1907            //
1908            // Presuming it isn't advisable to force the track over.
1909             if (mNextOutput->mTrack == NULL) {
1910                ALOGD("Recycling track for gapless playback");
1911                delete mNextOutput->mCallbackData;
1912                mNextOutput->mCallbackData = mCallbackData;
1913                mNextOutput->mRecycledTrack = mTrack;
1914                mNextOutput->mSampleRateHz = mSampleRateHz;
1915                mNextOutput->mMsecsPerFrame = mMsecsPerFrame;
1916                mNextOutput->mFlags = mFlags;
1917                mNextOutput->mFrameSize = mFrameSize;
1918                close_l();
1919                mCallbackData = NULL;  // destruction handled by mNextOutput
1920            } else {
1921                ALOGW("Ignoring gapless playback because next player has already started");
1922                // remove track in case resource needed for future players.
1923                if (mCallbackData != NULL) {
1924                    mCallbackData->endTrackSwitch();  // release lock for callbacks before close.
1925                }
1926                close_l();
1927            }
1928        }
1929        break;
1930    }
1931}
1932
1933ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size, bool blocking)
1934{
1935    Mutex::Autolock lock(mLock);
1936    LOG_ALWAYS_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
1937
1938    //ALOGV("write(%p, %u)", buffer, size);
1939    if (mTrack != 0) {
1940        return mTrack->write(buffer, size, blocking);
1941    }
1942    return NO_INIT;
1943}
1944
1945void MediaPlayerService::AudioOutput::stop()
1946{
1947    ALOGV("stop");
1948    Mutex::Autolock lock(mLock);
1949    if (mTrack != 0) mTrack->stop();
1950}
1951
1952void MediaPlayerService::AudioOutput::flush()
1953{
1954    ALOGV("flush");
1955    Mutex::Autolock lock(mLock);
1956    if (mTrack != 0) mTrack->flush();
1957}
1958
1959void MediaPlayerService::AudioOutput::pause()
1960{
1961    ALOGV("pause");
1962    Mutex::Autolock lock(mLock);
1963    if (mTrack != 0) mTrack->pause();
1964}
1965
1966void MediaPlayerService::AudioOutput::close()
1967{
1968    ALOGV("close");
1969    sp<AudioTrack> track;
1970    {
1971        Mutex::Autolock lock(mLock);
1972        track = mTrack;
1973        close_l(); // clears mTrack
1974    }
1975    // destruction of the track occurs outside of mutex.
1976}
1977
1978void MediaPlayerService::AudioOutput::setVolume(float left, float right)
1979{
1980    ALOGV("setVolume(%f, %f)", left, right);
1981    Mutex::Autolock lock(mLock);
1982    mLeftVolume = left;
1983    mRightVolume = right;
1984    if (mTrack != 0) {
1985        mTrack->setVolume(left, right);
1986    }
1987}
1988
1989status_t MediaPlayerService::AudioOutput::setPlaybackRate(const AudioPlaybackRate &rate)
1990{
1991    ALOGV("setPlaybackRate(%f %f %d %d)",
1992                rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
1993    Mutex::Autolock lock(mLock);
1994    if (mTrack == 0) {
1995        // remember rate so that we can set it when the track is opened
1996        mPlaybackRate = rate;
1997        return OK;
1998    }
1999    status_t res = mTrack->setPlaybackRate(rate);
2000    if (res != NO_ERROR) {
2001        return res;
2002    }
2003    // rate.mSpeed is always greater than 0 if setPlaybackRate succeeded
2004    CHECK_GT(rate.mSpeed, 0.f);
2005    mPlaybackRate = rate;
2006    if (mSampleRateHz != 0) {
2007        mMsecsPerFrame = 1E3f / (rate.mSpeed * mSampleRateHz);
2008    }
2009    return res;
2010}
2011
2012status_t MediaPlayerService::AudioOutput::getPlaybackRate(AudioPlaybackRate *rate)
2013{
2014    ALOGV("setPlaybackRate");
2015    Mutex::Autolock lock(mLock);
2016    if (mTrack == 0) {
2017        return NO_INIT;
2018    }
2019    *rate = mTrack->getPlaybackRate();
2020    return NO_ERROR;
2021}
2022
2023status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
2024{
2025    ALOGV("setAuxEffectSendLevel(%f)", level);
2026    Mutex::Autolock lock(mLock);
2027    mSendLevel = level;
2028    if (mTrack != 0) {
2029        return mTrack->setAuxEffectSendLevel(level);
2030    }
2031    return NO_ERROR;
2032}
2033
2034status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
2035{
2036    ALOGV("attachAuxEffect(%d)", effectId);
2037    Mutex::Autolock lock(mLock);
2038    mAuxEffectId = effectId;
2039    if (mTrack != 0) {
2040        return mTrack->attachAuxEffect(effectId);
2041    }
2042    return NO_ERROR;
2043}
2044
2045// static
2046void MediaPlayerService::AudioOutput::CallbackWrapper(
2047        int event, void *cookie, void *info) {
2048    //ALOGV("callbackwrapper");
2049    CallbackData *data = (CallbackData*)cookie;
2050    // lock to ensure we aren't caught in the middle of a track switch.
2051    data->lock();
2052    AudioOutput *me = data->getOutput();
2053    AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
2054    if (me == NULL) {
2055        // no output set, likely because the track was scheduled to be reused
2056        // by another player, but the format turned out to be incompatible.
2057        data->unlock();
2058        if (buffer != NULL) {
2059            buffer->size = 0;
2060        }
2061        return;
2062    }
2063
2064    switch(event) {
2065    case AudioTrack::EVENT_MORE_DATA: {
2066        size_t actualSize = (*me->mCallback)(
2067                me, buffer->raw, buffer->size, me->mCallbackCookie,
2068                CB_EVENT_FILL_BUFFER);
2069
2070        // Log when no data is returned from the callback.
2071        // (1) We may have no data (especially with network streaming sources).
2072        // (2) We may have reached the EOS and the audio track is not stopped yet.
2073        // Note that AwesomePlayer/AudioPlayer will only return zero size when it reaches the EOS.
2074        // NuPlayerRenderer will return zero when it doesn't have data (it doesn't block to fill).
2075        //
2076        // This is a benign busy-wait, with the next data request generated 10 ms or more later;
2077        // nevertheless for power reasons, we don't want to see too many of these.
2078
2079        ALOGV_IF(actualSize == 0 && buffer->size > 0, "callbackwrapper: empty buffer returned");
2080
2081        buffer->size = actualSize;
2082        } break;
2083
2084    case AudioTrack::EVENT_STREAM_END:
2085        // currently only occurs for offloaded callbacks
2086        ALOGV("callbackwrapper: deliver EVENT_STREAM_END");
2087        (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2088                me->mCallbackCookie, CB_EVENT_STREAM_END);
2089        break;
2090
2091    case AudioTrack::EVENT_NEW_IAUDIOTRACK :
2092        ALOGV("callbackwrapper: deliver EVENT_TEAR_DOWN");
2093        (*me->mCallback)(me,  NULL /* buffer */, 0 /* size */,
2094                me->mCallbackCookie, CB_EVENT_TEAR_DOWN);
2095        break;
2096
2097    case AudioTrack::EVENT_UNDERRUN:
2098        // This occurs when there is no data available, typically
2099        // when there is a failure to supply data to the AudioTrack.  It can also
2100        // occur in non-offloaded mode when the audio device comes out of standby.
2101        //
2102        // If an AudioTrack underruns it outputs silence. Since this happens suddenly
2103        // it may sound like an audible pop or glitch.
2104        //
2105        // The underrun event is sent once per track underrun; the condition is reset
2106        // when more data is sent to the AudioTrack.
2107        ALOGI("callbackwrapper: EVENT_UNDERRUN (discarded)");
2108        break;
2109
2110    default:
2111        ALOGE("received unknown event type: %d inside CallbackWrapper !", event);
2112    }
2113
2114    data->unlock();
2115}
2116
2117audio_session_t MediaPlayerService::AudioOutput::getSessionId() const
2118{
2119    Mutex::Autolock lock(mLock);
2120    return mSessionId;
2121}
2122
2123uint32_t MediaPlayerService::AudioOutput::getSampleRate() const
2124{
2125    Mutex::Autolock lock(mLock);
2126    if (mTrack == 0) return 0;
2127    return mTrack->getSampleRate();
2128}
2129
2130////////////////////////////////////////////////////////////////////////////////
2131
2132struct CallbackThread : public Thread {
2133    CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
2134                   MediaPlayerBase::AudioSink::AudioCallback cb,
2135                   void *cookie);
2136
2137protected:
2138    virtual ~CallbackThread();
2139
2140    virtual bool threadLoop();
2141
2142private:
2143    wp<MediaPlayerBase::AudioSink> mSink;
2144    MediaPlayerBase::AudioSink::AudioCallback mCallback;
2145    void *mCookie;
2146    void *mBuffer;
2147    size_t mBufferSize;
2148
2149    CallbackThread(const CallbackThread &);
2150    CallbackThread &operator=(const CallbackThread &);
2151};
2152
2153CallbackThread::CallbackThread(
2154        const wp<MediaPlayerBase::AudioSink> &sink,
2155        MediaPlayerBase::AudioSink::AudioCallback cb,
2156        void *cookie)
2157    : mSink(sink),
2158      mCallback(cb),
2159      mCookie(cookie),
2160      mBuffer(NULL),
2161      mBufferSize(0) {
2162}
2163
2164CallbackThread::~CallbackThread() {
2165    if (mBuffer) {
2166        free(mBuffer);
2167        mBuffer = NULL;
2168    }
2169}
2170
2171bool CallbackThread::threadLoop() {
2172    sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
2173    if (sink == NULL) {
2174        return false;
2175    }
2176
2177    if (mBuffer == NULL) {
2178        mBufferSize = sink->bufferSize();
2179        mBuffer = malloc(mBufferSize);
2180    }
2181
2182    size_t actualSize =
2183        (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie,
2184                MediaPlayerBase::AudioSink::CB_EVENT_FILL_BUFFER);
2185
2186    if (actualSize > 0) {
2187        sink->write(mBuffer, actualSize);
2188        // Could return false on sink->write() error or short count.
2189        // Not necessarily appropriate but would work for AudioCache behavior.
2190    }
2191
2192    return true;
2193}
2194
2195////////////////////////////////////////////////////////////////////////////////
2196
2197void MediaPlayerService::addBatteryData(uint32_t params)
2198{
2199    Mutex::Autolock lock(mLock);
2200
2201    int32_t time = systemTime() / 1000000L;
2202
2203    // change audio output devices. This notification comes from AudioFlinger
2204    if ((params & kBatteryDataSpeakerOn)
2205            || (params & kBatteryDataOtherAudioDeviceOn)) {
2206
2207        int deviceOn[NUM_AUDIO_DEVICES];
2208        for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2209            deviceOn[i] = 0;
2210        }
2211
2212        if ((params & kBatteryDataSpeakerOn)
2213                && (params & kBatteryDataOtherAudioDeviceOn)) {
2214            deviceOn[SPEAKER_AND_OTHER] = 1;
2215        } else if (params & kBatteryDataSpeakerOn) {
2216            deviceOn[SPEAKER] = 1;
2217        } else {
2218            deviceOn[OTHER_AUDIO_DEVICE] = 1;
2219        }
2220
2221        for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2222            if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
2223
2224                if (mBatteryAudio.refCount > 0) { // if playing audio
2225                    if (!deviceOn[i]) {
2226                        mBatteryAudio.lastTime[i] += time;
2227                        mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2228                        mBatteryAudio.lastTime[i] = 0;
2229                    } else {
2230                        mBatteryAudio.lastTime[i] = 0 - time;
2231                    }
2232                }
2233
2234                mBatteryAudio.deviceOn[i] = deviceOn[i];
2235            }
2236        }
2237        return;
2238    }
2239
2240    // an audio stream is started
2241    if (params & kBatteryDataAudioFlingerStart) {
2242        // record the start time only if currently no other audio
2243        // is being played
2244        if (mBatteryAudio.refCount == 0) {
2245            for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2246                if (mBatteryAudio.deviceOn[i]) {
2247                    mBatteryAudio.lastTime[i] -= time;
2248                }
2249            }
2250        }
2251
2252        mBatteryAudio.refCount ++;
2253        return;
2254
2255    } else if (params & kBatteryDataAudioFlingerStop) {
2256        if (mBatteryAudio.refCount <= 0) {
2257            ALOGW("Battery track warning: refCount is <= 0");
2258            return;
2259        }
2260
2261        // record the stop time only if currently this is the only
2262        // audio being played
2263        if (mBatteryAudio.refCount == 1) {
2264            for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2265                if (mBatteryAudio.deviceOn[i]) {
2266                    mBatteryAudio.lastTime[i] += time;
2267                    mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2268                    mBatteryAudio.lastTime[i] = 0;
2269                }
2270            }
2271        }
2272
2273        mBatteryAudio.refCount --;
2274        return;
2275    }
2276
2277    int uid = IPCThreadState::self()->getCallingUid();
2278    if (uid == AID_MEDIA) {
2279        return;
2280    }
2281    int index = mBatteryData.indexOfKey(uid);
2282
2283    if (index < 0) { // create a new entry for this UID
2284        BatteryUsageInfo info;
2285        info.audioTotalTime = 0;
2286        info.videoTotalTime = 0;
2287        info.audioLastTime = 0;
2288        info.videoLastTime = 0;
2289        info.refCount = 0;
2290
2291        if (mBatteryData.add(uid, info) == NO_MEMORY) {
2292            ALOGE("Battery track error: no memory for new app");
2293            return;
2294        }
2295    }
2296
2297    BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
2298
2299    if (params & kBatteryDataCodecStarted) {
2300        if (params & kBatteryDataTrackAudio) {
2301            info.audioLastTime -= time;
2302            info.refCount ++;
2303        }
2304        if (params & kBatteryDataTrackVideo) {
2305            info.videoLastTime -= time;
2306            info.refCount ++;
2307        }
2308    } else {
2309        if (info.refCount == 0) {
2310            ALOGW("Battery track warning: refCount is already 0");
2311            return;
2312        } else if (info.refCount < 0) {
2313            ALOGE("Battery track error: refCount < 0");
2314            mBatteryData.removeItem(uid);
2315            return;
2316        }
2317
2318        if (params & kBatteryDataTrackAudio) {
2319            info.audioLastTime += time;
2320            info.refCount --;
2321        }
2322        if (params & kBatteryDataTrackVideo) {
2323            info.videoLastTime += time;
2324            info.refCount --;
2325        }
2326
2327        // no stream is being played by this UID
2328        if (info.refCount == 0) {
2329            info.audioTotalTime += info.audioLastTime;
2330            info.audioLastTime = 0;
2331            info.videoTotalTime += info.videoLastTime;
2332            info.videoLastTime = 0;
2333        }
2334    }
2335}
2336
2337status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
2338    Mutex::Autolock lock(mLock);
2339
2340    // audio output devices usage
2341    int32_t time = systemTime() / 1000000L; //in ms
2342    int32_t totalTime;
2343
2344    for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2345        totalTime = mBatteryAudio.totalTime[i];
2346
2347        if (mBatteryAudio.deviceOn[i]
2348            && (mBatteryAudio.lastTime[i] != 0)) {
2349                int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
2350                totalTime += tmpTime;
2351        }
2352
2353        reply->writeInt32(totalTime);
2354        // reset the total time
2355        mBatteryAudio.totalTime[i] = 0;
2356   }
2357
2358    // codec usage
2359    BatteryUsageInfo info;
2360    int size = mBatteryData.size();
2361
2362    reply->writeInt32(size);
2363    int i = 0;
2364
2365    while (i < size) {
2366        info = mBatteryData.valueAt(i);
2367
2368        reply->writeInt32(mBatteryData.keyAt(i)); //UID
2369        reply->writeInt32(info.audioTotalTime);
2370        reply->writeInt32(info.videoTotalTime);
2371
2372        info.audioTotalTime = 0;
2373        info.videoTotalTime = 0;
2374
2375        // remove the UID entry where no stream is being played
2376        if (info.refCount <= 0) {
2377            mBatteryData.removeItemsAt(i);
2378            size --;
2379            i --;
2380        }
2381        i++;
2382    }
2383    return NO_ERROR;
2384}
2385} // namespace android
2386