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