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