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