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