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