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