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