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,std::string opPackageName)482 sp<IMediaPlayer> MediaPlayerService::create(const sp<IMediaPlayerClient>& client,
483 audio_session_t audioSessionId, std::string opPackageName)
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(), opPackageName);
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,const std::string & opPackageName)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, const std::string& opPackageName)
737 : mOpPackageName(opPackageName)
738 {
739 ALOGV("Client(%d) constructor", connId);
740 mPid = pid;
741 mConnId = connId;
742 mService = service;
743 mClient = client;
744 mLoop = false;
745 mStatus = NO_INIT;
746 mAudioSessionId = audioSessionId;
747 mUid = uid;
748 mRetransmitEndpointValid = false;
749 mAudioAttributes = NULL;
750 mListener = new Listener(this);
751
752 #if CALLBACK_ANTAGONIZER
753 ALOGD("create Antagonizer");
754 mAntagonizer = new Antagonizer(mListener);
755 #endif
756 }
757
~Client()758 MediaPlayerService::Client::~Client()
759 {
760 ALOGV("Client(%d) destructor pid = %d", mConnId, mPid);
761 mAudioOutput.clear();
762 wp<Client> client(this);
763 disconnect();
764 mService->removeClient(client);
765 if (mAudioAttributes != NULL) {
766 free(mAudioAttributes);
767 }
768 mAudioDeviceUpdatedListener.clear();
769 }
770
disconnect()771 void MediaPlayerService::Client::disconnect()
772 {
773 ALOGV("disconnect(%d) from pid %d", mConnId, mPid);
774 // grab local reference and clear main reference to prevent future
775 // access to object
776 sp<MediaPlayerBase> p;
777 {
778 Mutex::Autolock l(mLock);
779 p = mPlayer;
780 mClient.clear();
781 mPlayer.clear();
782 }
783
784 // clear the notification to prevent callbacks to dead client
785 // and reset the player. We assume the player will serialize
786 // access to itself if necessary.
787 if (p != 0) {
788 p->setNotifyCallback(0);
789 #if CALLBACK_ANTAGONIZER
790 ALOGD("kill Antagonizer");
791 mAntagonizer->kill();
792 #endif
793 p->reset();
794 }
795
796 {
797 Mutex::Autolock l(mLock);
798 disconnectNativeWindow_l();
799 }
800
801 IPCThreadState::self()->flushCommands();
802 }
803
createPlayer(player_type playerType)804 sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
805 {
806 // determine if we have the right player type
807 sp<MediaPlayerBase> p = getPlayer();
808 if ((p != NULL) && (p->playerType() != playerType)) {
809 ALOGV("delete player");
810 p.clear();
811 }
812 if (p == NULL) {
813 p = MediaPlayerFactory::createPlayer(playerType, mListener, mPid);
814 }
815
816 if (p != NULL) {
817 p->setUID(mUid);
818 }
819
820 return p;
821 }
822
onAudioDeviceUpdate(audio_io_handle_t audioIo,audio_port_handle_t deviceId)823 void MediaPlayerService::Client::AudioDeviceUpdatedNotifier::onAudioDeviceUpdate(
824 audio_io_handle_t audioIo,
825 audio_port_handle_t deviceId) {
826 sp<MediaPlayerBase> listener = mListener.promote();
827 if (listener != NULL) {
828 listener->sendEvent(MEDIA_AUDIO_ROUTING_CHANGED, audioIo, deviceId);
829 } else {
830 ALOGW("listener for process %d death is gone", MEDIA_AUDIO_ROUTING_CHANGED);
831 }
832 }
833
setDataSource_pre(player_type playerType)834 sp<MediaPlayerBase> MediaPlayerService::Client::setDataSource_pre(
835 player_type playerType)
836 {
837 ALOGV("player type = %d", playerType);
838
839 // create the right type of player
840 sp<MediaPlayerBase> p = createPlayer(playerType);
841 if (p == NULL) {
842 return p;
843 }
844
845 std::vector<DeathNotifier> deathNotifiers;
846
847 // Listen to death of media.extractor service
848 sp<IServiceManager> sm = defaultServiceManager();
849 sp<IBinder> binder = sm->getService(String16("media.extractor"));
850 if (binder == NULL) {
851 ALOGE("extractor service not available");
852 return NULL;
853 }
854 deathNotifiers.emplace_back(
855 binder, [l = wp<MediaPlayerBase>(p)]() {
856 sp<MediaPlayerBase> listener = l.promote();
857 if (listener) {
858 ALOGI("media.extractor died. Sending death notification.");
859 listener->sendEvent(MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED,
860 MEDIAEXTRACTOR_PROCESS_DEATH);
861 } else {
862 ALOGW("media.extractor died without a death handler.");
863 }
864 });
865
866 {
867 using ::android::hidl::base::V1_0::IBase;
868
869 // Listen to death of OMX service
870 {
871 sp<IBase> base = ::android::hardware::media::omx::V1_0::
872 IOmx::getService();
873 if (base == nullptr) {
874 ALOGD("OMX service is not available");
875 } else {
876 deathNotifiers.emplace_back(
877 base, [l = wp<MediaPlayerBase>(p)]() {
878 sp<MediaPlayerBase> listener = l.promote();
879 if (listener) {
880 ALOGI("OMX service died. "
881 "Sending death notification.");
882 listener->sendEvent(
883 MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED,
884 MEDIACODEC_PROCESS_DEATH);
885 } else {
886 ALOGW("OMX service died without a death handler.");
887 }
888 });
889 }
890 }
891
892 // Listen to death of Codec2 services
893 {
894 for (std::shared_ptr<Codec2Client> const& client :
895 Codec2Client::CreateFromAllServices()) {
896 sp<IBase> base = client->getBase();
897 deathNotifiers.emplace_back(
898 base, [l = wp<MediaPlayerBase>(p),
899 name = std::string(client->getServiceName())]() {
900 sp<MediaPlayerBase> listener = l.promote();
901 if (listener) {
902 ALOGI("Codec2 service \"%s\" died. "
903 "Sending death notification.",
904 name.c_str());
905 listener->sendEvent(
906 MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED,
907 MEDIACODEC_PROCESS_DEATH);
908 } else {
909 ALOGW("Codec2 service \"%s\" died "
910 "without a death handler.",
911 name.c_str());
912 }
913 });
914 }
915 }
916 }
917
918 Mutex::Autolock lock(mLock);
919
920 mDeathNotifiers.clear();
921 mDeathNotifiers.swap(deathNotifiers);
922 mAudioDeviceUpdatedListener = new AudioDeviceUpdatedNotifier(p);
923
924 if (!p->hardwareOutput()) {
925 mAudioOutput = new AudioOutput(mAudioSessionId, IPCThreadState::self()->getCallingUid(),
926 mPid, mAudioAttributes, mAudioDeviceUpdatedListener, mOpPackageName);
927 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
928 }
929
930 return p;
931 }
932
setDataSource_post(const sp<MediaPlayerBase> & p,status_t status)933 status_t MediaPlayerService::Client::setDataSource_post(
934 const sp<MediaPlayerBase>& p,
935 status_t status)
936 {
937 ALOGV(" setDataSource");
938 if (status != OK) {
939 ALOGE(" error: %d", status);
940 return status;
941 }
942
943 // Set the re-transmission endpoint if one was chosen.
944 if (mRetransmitEndpointValid) {
945 status = p->setRetransmitEndpoint(&mRetransmitEndpoint);
946 if (status != NO_ERROR) {
947 ALOGE("setRetransmitEndpoint error: %d", status);
948 }
949 }
950
951 if (status == OK) {
952 Mutex::Autolock lock(mLock);
953 mPlayer = p;
954 }
955 return status;
956 }
957
setDataSource(const sp<IMediaHTTPService> & httpService,const char * url,const KeyedVector<String8,String8> * headers)958 status_t MediaPlayerService::Client::setDataSource(
959 const sp<IMediaHTTPService> &httpService,
960 const char *url,
961 const KeyedVector<String8, String8> *headers)
962 {
963 ALOGV("setDataSource(%s)", url);
964 if (url == NULL)
965 return UNKNOWN_ERROR;
966
967 if ((strncmp(url, "http://", 7) == 0) ||
968 (strncmp(url, "https://", 8) == 0) ||
969 (strncmp(url, "rtsp://", 7) == 0)) {
970 if (!checkPermission("android.permission.INTERNET")) {
971 return PERMISSION_DENIED;
972 }
973 }
974
975 if (strncmp(url, "content://", 10) == 0) {
976 // get a filedescriptor for the content Uri and
977 // pass it to the setDataSource(fd) method
978
979 String16 url16(url);
980 int fd = android::openContentProviderFile(url16);
981 if (fd < 0)
982 {
983 ALOGE("Couldn't open fd for %s", url);
984 return UNKNOWN_ERROR;
985 }
986 status_t status = setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
987 close(fd);
988 return mStatus = status;
989 } else {
990 player_type playerType = MediaPlayerFactory::getPlayerType(this, url);
991 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
992 if (p == NULL) {
993 return NO_INIT;
994 }
995
996 return mStatus =
997 setDataSource_post(
998 p, p->setDataSource(httpService, url, headers));
999 }
1000 }
1001
setDataSource(int fd,int64_t offset,int64_t length)1002 status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
1003 {
1004 ALOGV("setDataSource fd=%d (%s), offset=%lld, length=%lld",
1005 fd, nameForFd(fd).c_str(), (long long) offset, (long long) length);
1006 struct stat sb;
1007 int ret = fstat(fd, &sb);
1008 if (ret != 0) {
1009 ALOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
1010 return UNKNOWN_ERROR;
1011 }
1012
1013 ALOGV("st_dev = %llu", static_cast<unsigned long long>(sb.st_dev));
1014 ALOGV("st_mode = %u", sb.st_mode);
1015 ALOGV("st_uid = %lu", static_cast<unsigned long>(sb.st_uid));
1016 ALOGV("st_gid = %lu", static_cast<unsigned long>(sb.st_gid));
1017 ALOGV("st_size = %llu", static_cast<unsigned long long>(sb.st_size));
1018
1019 if (offset >= sb.st_size) {
1020 ALOGE("offset error");
1021 return UNKNOWN_ERROR;
1022 }
1023 if (offset + length > sb.st_size) {
1024 length = sb.st_size - offset;
1025 ALOGV("calculated length = %lld", (long long)length);
1026 }
1027
1028 player_type playerType = MediaPlayerFactory::getPlayerType(this,
1029 fd,
1030 offset,
1031 length);
1032 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
1033 if (p == NULL) {
1034 return NO_INIT;
1035 }
1036
1037 // now set data source
1038 return mStatus = setDataSource_post(p, p->setDataSource(fd, offset, length));
1039 }
1040
setDataSource(const sp<IStreamSource> & source)1041 status_t MediaPlayerService::Client::setDataSource(
1042 const sp<IStreamSource> &source) {
1043 // create the right type of player
1044 player_type playerType = MediaPlayerFactory::getPlayerType(this, source);
1045 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
1046 if (p == NULL) {
1047 return NO_INIT;
1048 }
1049
1050 // now set data source
1051 return mStatus = setDataSource_post(p, p->setDataSource(source));
1052 }
1053
setDataSource(const sp<IDataSource> & source)1054 status_t MediaPlayerService::Client::setDataSource(
1055 const sp<IDataSource> &source) {
1056 sp<DataSource> dataSource = CreateDataSourceFromIDataSource(source);
1057 player_type playerType = MediaPlayerFactory::getPlayerType(this, dataSource);
1058 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
1059 if (p == NULL) {
1060 return NO_INIT;
1061 }
1062 // now set data source
1063 return mStatus = setDataSource_post(p, p->setDataSource(dataSource));
1064 }
1065
disconnectNativeWindow_l()1066 void MediaPlayerService::Client::disconnectNativeWindow_l() {
1067 if (mConnectedWindow != NULL) {
1068 status_t err = nativeWindowDisconnect(
1069 mConnectedWindow.get(), "disconnectNativeWindow");
1070
1071 if (err != OK) {
1072 ALOGW("nativeWindowDisconnect returned an error: %s (%d)",
1073 strerror(-err), err);
1074 }
1075 }
1076 mConnectedWindow.clear();
1077 }
1078
setVideoSurfaceTexture(const sp<IGraphicBufferProducer> & bufferProducer)1079 status_t MediaPlayerService::Client::setVideoSurfaceTexture(
1080 const sp<IGraphicBufferProducer>& bufferProducer)
1081 {
1082 ALOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, bufferProducer.get());
1083 sp<MediaPlayerBase> p = getPlayer();
1084 if (p == 0) return UNKNOWN_ERROR;
1085
1086 sp<IBinder> binder(IInterface::asBinder(bufferProducer));
1087 if (mConnectedWindowBinder == binder) {
1088 return OK;
1089 }
1090
1091 sp<ANativeWindow> anw;
1092 if (bufferProducer != NULL) {
1093 anw = new Surface(bufferProducer, true /* controlledByApp */);
1094 status_t err = nativeWindowConnect(anw.get(), "setVideoSurfaceTexture");
1095
1096 if (err != OK) {
1097 ALOGE("setVideoSurfaceTexture failed: %d", err);
1098 // Note that we must do the reset before disconnecting from the ANW.
1099 // Otherwise queue/dequeue calls could be made on the disconnected
1100 // ANW, which may result in errors.
1101 reset();
1102
1103 Mutex::Autolock lock(mLock);
1104 disconnectNativeWindow_l();
1105
1106 return err;
1107 }
1108 }
1109
1110 // Note that we must set the player's new GraphicBufferProducer before
1111 // disconnecting the old one. Otherwise queue/dequeue calls could be made
1112 // on the disconnected ANW, which may result in errors.
1113 status_t err = p->setVideoSurfaceTexture(bufferProducer);
1114
1115 mLock.lock();
1116 disconnectNativeWindow_l();
1117
1118 if (err == OK) {
1119 mConnectedWindow = anw;
1120 mConnectedWindowBinder = binder;
1121 mLock.unlock();
1122 } else {
1123 mLock.unlock();
1124 status_t err = nativeWindowDisconnect(
1125 anw.get(), "disconnectNativeWindow");
1126
1127 if (err != OK) {
1128 ALOGW("nativeWindowDisconnect returned an error: %s (%d)",
1129 strerror(-err), err);
1130 }
1131 }
1132
1133 return err;
1134 }
1135
invoke(const Parcel & request,Parcel * reply)1136 status_t MediaPlayerService::Client::invoke(const Parcel& request,
1137 Parcel *reply)
1138 {
1139 sp<MediaPlayerBase> p = getPlayer();
1140 if (p == NULL) return UNKNOWN_ERROR;
1141 return p->invoke(request, reply);
1142 }
1143
1144 // This call doesn't need to access the native player.
setMetadataFilter(const Parcel & filter)1145 status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
1146 {
1147 status_t status;
1148 media::Metadata::Filter allow, drop;
1149
1150 if (unmarshallFilter(filter, &allow, &status) &&
1151 unmarshallFilter(filter, &drop, &status)) {
1152 Mutex::Autolock lock(mLock);
1153
1154 mMetadataAllow = allow;
1155 mMetadataDrop = drop;
1156 }
1157 return status;
1158 }
1159
getMetadata(bool update_only,bool,Parcel * reply)1160 status_t MediaPlayerService::Client::getMetadata(
1161 bool update_only, bool /*apply_filter*/, Parcel *reply)
1162 {
1163 sp<MediaPlayerBase> player = getPlayer();
1164 if (player == 0) return UNKNOWN_ERROR;
1165
1166 status_t status;
1167 // Placeholder for the return code, updated by the caller.
1168 reply->writeInt32(-1);
1169
1170 media::Metadata::Filter ids;
1171
1172 // We don't block notifications while we fetch the data. We clear
1173 // mMetadataUpdated first so we don't lose notifications happening
1174 // during the rest of this call.
1175 {
1176 Mutex::Autolock lock(mLock);
1177 if (update_only) {
1178 ids = mMetadataUpdated;
1179 }
1180 mMetadataUpdated.clear();
1181 }
1182
1183 media::Metadata metadata(reply);
1184
1185 metadata.appendHeader();
1186 status = player->getMetadata(ids, reply);
1187
1188 if (status != OK) {
1189 metadata.resetParcel();
1190 ALOGE("getMetadata failed %d", status);
1191 return status;
1192 }
1193
1194 // FIXME: Implement filtering on the result. Not critical since
1195 // filtering takes place on the update notifications already. This
1196 // would be when all the metadata are fetch and a filter is set.
1197
1198 // Everything is fine, update the metadata length.
1199 metadata.updateLength();
1200 return OK;
1201 }
1202
setBufferingSettings(const BufferingSettings & buffering)1203 status_t MediaPlayerService::Client::setBufferingSettings(
1204 const BufferingSettings& buffering)
1205 {
1206 ALOGV("[%d] setBufferingSettings{%s}",
1207 mConnId, buffering.toString().string());
1208 sp<MediaPlayerBase> p = getPlayer();
1209 if (p == 0) return UNKNOWN_ERROR;
1210 return p->setBufferingSettings(buffering);
1211 }
1212
getBufferingSettings(BufferingSettings * buffering)1213 status_t MediaPlayerService::Client::getBufferingSettings(
1214 BufferingSettings* buffering /* nonnull */)
1215 {
1216 sp<MediaPlayerBase> p = getPlayer();
1217 // TODO: create mPlayer on demand.
1218 if (p == 0) return UNKNOWN_ERROR;
1219 status_t ret = p->getBufferingSettings(buffering);
1220 if (ret == NO_ERROR) {
1221 ALOGV("[%d] getBufferingSettings{%s}",
1222 mConnId, buffering->toString().string());
1223 } else {
1224 ALOGE("[%d] getBufferingSettings returned %d", mConnId, ret);
1225 }
1226 return ret;
1227 }
1228
prepareAsync()1229 status_t MediaPlayerService::Client::prepareAsync()
1230 {
1231 ALOGV("[%d] prepareAsync", mConnId);
1232 sp<MediaPlayerBase> p = getPlayer();
1233 if (p == 0) return UNKNOWN_ERROR;
1234 status_t ret = p->prepareAsync();
1235 #if CALLBACK_ANTAGONIZER
1236 ALOGD("start Antagonizer");
1237 if (ret == NO_ERROR) mAntagonizer->start();
1238 #endif
1239 return ret;
1240 }
1241
start()1242 status_t MediaPlayerService::Client::start()
1243 {
1244 ALOGV("[%d] start", mConnId);
1245 sp<MediaPlayerBase> p = getPlayer();
1246 if (p == 0) return UNKNOWN_ERROR;
1247 p->setLooping(mLoop);
1248 return p->start();
1249 }
1250
stop()1251 status_t MediaPlayerService::Client::stop()
1252 {
1253 ALOGV("[%d] stop", mConnId);
1254 sp<MediaPlayerBase> p = getPlayer();
1255 if (p == 0) return UNKNOWN_ERROR;
1256 return p->stop();
1257 }
1258
pause()1259 status_t MediaPlayerService::Client::pause()
1260 {
1261 ALOGV("[%d] pause", mConnId);
1262 sp<MediaPlayerBase> p = getPlayer();
1263 if (p == 0) return UNKNOWN_ERROR;
1264 return p->pause();
1265 }
1266
isPlaying(bool * state)1267 status_t MediaPlayerService::Client::isPlaying(bool* state)
1268 {
1269 *state = false;
1270 sp<MediaPlayerBase> p = getPlayer();
1271 if (p == 0) return UNKNOWN_ERROR;
1272 *state = p->isPlaying();
1273 ALOGV("[%d] isPlaying: %d", mConnId, *state);
1274 return NO_ERROR;
1275 }
1276
setPlaybackSettings(const AudioPlaybackRate & rate)1277 status_t MediaPlayerService::Client::setPlaybackSettings(const AudioPlaybackRate& rate)
1278 {
1279 ALOGV("[%d] setPlaybackSettings(%f, %f, %d, %d)",
1280 mConnId, rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
1281 sp<MediaPlayerBase> p = getPlayer();
1282 if (p == 0) return UNKNOWN_ERROR;
1283 return p->setPlaybackSettings(rate);
1284 }
1285
getPlaybackSettings(AudioPlaybackRate * rate)1286 status_t MediaPlayerService::Client::getPlaybackSettings(AudioPlaybackRate* rate /* nonnull */)
1287 {
1288 sp<MediaPlayerBase> p = getPlayer();
1289 if (p == 0) return UNKNOWN_ERROR;
1290 status_t ret = p->getPlaybackSettings(rate);
1291 if (ret == NO_ERROR) {
1292 ALOGV("[%d] getPlaybackSettings(%f, %f, %d, %d)",
1293 mConnId, rate->mSpeed, rate->mPitch, rate->mFallbackMode, rate->mStretchMode);
1294 } else {
1295 ALOGV("[%d] getPlaybackSettings returned %d", mConnId, ret);
1296 }
1297 return ret;
1298 }
1299
setSyncSettings(const AVSyncSettings & sync,float videoFpsHint)1300 status_t MediaPlayerService::Client::setSyncSettings(
1301 const AVSyncSettings& sync, float videoFpsHint)
1302 {
1303 ALOGV("[%d] setSyncSettings(%u, %u, %f, %f)",
1304 mConnId, sync.mSource, sync.mAudioAdjustMode, sync.mTolerance, videoFpsHint);
1305 sp<MediaPlayerBase> p = getPlayer();
1306 if (p == 0) return UNKNOWN_ERROR;
1307 return p->setSyncSettings(sync, videoFpsHint);
1308 }
1309
getSyncSettings(AVSyncSettings * sync,float * videoFps)1310 status_t MediaPlayerService::Client::getSyncSettings(
1311 AVSyncSettings* sync /* nonnull */, float* videoFps /* nonnull */)
1312 {
1313 sp<MediaPlayerBase> p = getPlayer();
1314 if (p == 0) return UNKNOWN_ERROR;
1315 status_t ret = p->getSyncSettings(sync, videoFps);
1316 if (ret == NO_ERROR) {
1317 ALOGV("[%d] getSyncSettings(%u, %u, %f, %f)",
1318 mConnId, sync->mSource, sync->mAudioAdjustMode, sync->mTolerance, *videoFps);
1319 } else {
1320 ALOGV("[%d] getSyncSettings returned %d", mConnId, ret);
1321 }
1322 return ret;
1323 }
1324
getCurrentPosition(int * msec)1325 status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
1326 {
1327 ALOGV("getCurrentPosition");
1328 sp<MediaPlayerBase> p = getPlayer();
1329 if (p == 0) return UNKNOWN_ERROR;
1330 status_t ret = p->getCurrentPosition(msec);
1331 if (ret == NO_ERROR) {
1332 ALOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
1333 } else {
1334 ALOGE("getCurrentPosition returned %d", ret);
1335 }
1336 return ret;
1337 }
1338
getDuration(int * msec)1339 status_t MediaPlayerService::Client::getDuration(int *msec)
1340 {
1341 ALOGV("getDuration");
1342 sp<MediaPlayerBase> p = getPlayer();
1343 if (p == 0) return UNKNOWN_ERROR;
1344 status_t ret = p->getDuration(msec);
1345 if (ret == NO_ERROR) {
1346 ALOGV("[%d] getDuration = %d", mConnId, *msec);
1347 } else {
1348 ALOGE("getDuration returned %d", ret);
1349 }
1350 return ret;
1351 }
1352
setNextPlayer(const sp<IMediaPlayer> & player)1353 status_t MediaPlayerService::Client::setNextPlayer(const sp<IMediaPlayer>& player) {
1354 ALOGV("setNextPlayer");
1355 Mutex::Autolock l(mLock);
1356 sp<Client> c = static_cast<Client*>(player.get());
1357 if (c != NULL && !mService->hasClient(c)) {
1358 return BAD_VALUE;
1359 }
1360
1361 mNextClient = c;
1362
1363 if (c != NULL) {
1364 if (mAudioOutput != NULL) {
1365 mAudioOutput->setNextOutput(c->mAudioOutput);
1366 } else if ((mPlayer != NULL) && !mPlayer->hardwareOutput()) {
1367 ALOGE("no current audio output");
1368 }
1369
1370 if ((mPlayer != NULL) && (mNextClient->getPlayer() != NULL)) {
1371 mPlayer->setNextPlayer(mNextClient->getPlayer());
1372 }
1373 }
1374
1375 return OK;
1376 }
1377
applyVolumeShaper(const sp<VolumeShaper::Configuration> & configuration,const sp<VolumeShaper::Operation> & operation)1378 VolumeShaper::Status MediaPlayerService::Client::applyVolumeShaper(
1379 const sp<VolumeShaper::Configuration>& configuration,
1380 const sp<VolumeShaper::Operation>& operation) {
1381 // for hardware output, call player instead
1382 ALOGV("Client::applyVolumeShaper(%p)", this);
1383 sp<MediaPlayerBase> p = getPlayer();
1384 {
1385 Mutex::Autolock l(mLock);
1386 if (p != 0 && p->hardwareOutput()) {
1387 // TODO: investigate internal implementation
1388 return VolumeShaper::Status(INVALID_OPERATION);
1389 }
1390 if (mAudioOutput.get() != nullptr) {
1391 return mAudioOutput->applyVolumeShaper(configuration, operation);
1392 }
1393 }
1394 return VolumeShaper::Status(INVALID_OPERATION);
1395 }
1396
getVolumeShaperState(int id)1397 sp<VolumeShaper::State> MediaPlayerService::Client::getVolumeShaperState(int id) {
1398 // for hardware output, call player instead
1399 ALOGV("Client::getVolumeShaperState(%p)", this);
1400 sp<MediaPlayerBase> p = getPlayer();
1401 {
1402 Mutex::Autolock l(mLock);
1403 if (p != 0 && p->hardwareOutput()) {
1404 // TODO: investigate internal implementation.
1405 return nullptr;
1406 }
1407 if (mAudioOutput.get() != nullptr) {
1408 return mAudioOutput->getVolumeShaperState(id);
1409 }
1410 }
1411 return nullptr;
1412 }
1413
seekTo(int msec,MediaPlayerSeekMode mode)1414 status_t MediaPlayerService::Client::seekTo(int msec, MediaPlayerSeekMode mode)
1415 {
1416 ALOGV("[%d] seekTo(%d, %d)", mConnId, msec, mode);
1417 sp<MediaPlayerBase> p = getPlayer();
1418 if (p == 0) return UNKNOWN_ERROR;
1419 return p->seekTo(msec, mode);
1420 }
1421
reset()1422 status_t MediaPlayerService::Client::reset()
1423 {
1424 ALOGV("[%d] reset", mConnId);
1425 mRetransmitEndpointValid = false;
1426 sp<MediaPlayerBase> p = getPlayer();
1427 if (p == 0) return UNKNOWN_ERROR;
1428 return p->reset();
1429 }
1430
notifyAt(int64_t mediaTimeUs)1431 status_t MediaPlayerService::Client::notifyAt(int64_t mediaTimeUs)
1432 {
1433 ALOGV("[%d] notifyAt(%lld)", mConnId, (long long)mediaTimeUs);
1434 sp<MediaPlayerBase> p = getPlayer();
1435 if (p == 0) return UNKNOWN_ERROR;
1436 return p->notifyAt(mediaTimeUs);
1437 }
1438
setAudioStreamType(audio_stream_type_t type)1439 status_t MediaPlayerService::Client::setAudioStreamType(audio_stream_type_t type)
1440 {
1441 ALOGV("[%d] setAudioStreamType(%d)", mConnId, type);
1442 // TODO: for hardware output, call player instead
1443 Mutex::Autolock l(mLock);
1444 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1445 return NO_ERROR;
1446 }
1447
setAudioAttributes_l(const Parcel & parcel)1448 status_t MediaPlayerService::Client::setAudioAttributes_l(const Parcel &parcel)
1449 {
1450 if (mAudioAttributes != NULL) { free(mAudioAttributes); }
1451 mAudioAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1452 if (mAudioAttributes == NULL) {
1453 return NO_MEMORY;
1454 }
1455 unmarshallAudioAttributes(parcel, mAudioAttributes);
1456
1457 ALOGV("setAudioAttributes_l() usage=%d content=%d flags=0x%x tags=%s",
1458 mAudioAttributes->usage, mAudioAttributes->content_type, mAudioAttributes->flags,
1459 mAudioAttributes->tags);
1460
1461 if (mAudioOutput != 0) {
1462 mAudioOutput->setAudioAttributes(mAudioAttributes);
1463 }
1464 return NO_ERROR;
1465 }
1466
setLooping(int loop)1467 status_t MediaPlayerService::Client::setLooping(int loop)
1468 {
1469 ALOGV("[%d] setLooping(%d)", mConnId, loop);
1470 mLoop = loop;
1471 sp<MediaPlayerBase> p = getPlayer();
1472 if (p != 0) return p->setLooping(loop);
1473 return NO_ERROR;
1474 }
1475
setVolume(float leftVolume,float rightVolume)1476 status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1477 {
1478 ALOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
1479
1480 // for hardware output, call player instead
1481 sp<MediaPlayerBase> p = getPlayer();
1482 {
1483 Mutex::Autolock l(mLock);
1484 if (p != 0 && p->hardwareOutput()) {
1485 MediaPlayerHWInterface* hwp =
1486 reinterpret_cast<MediaPlayerHWInterface*>(p.get());
1487 return hwp->setVolume(leftVolume, rightVolume);
1488 } else {
1489 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1490 return NO_ERROR;
1491 }
1492 }
1493
1494 return NO_ERROR;
1495 }
1496
setAuxEffectSendLevel(float level)1497 status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1498 {
1499 ALOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
1500 Mutex::Autolock l(mLock);
1501 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1502 return NO_ERROR;
1503 }
1504
attachAuxEffect(int effectId)1505 status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1506 {
1507 ALOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
1508 Mutex::Autolock l(mLock);
1509 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1510 return NO_ERROR;
1511 }
1512
setParameter(int key,const Parcel & request)1513 status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
1514 ALOGV("[%d] setParameter(%d)", mConnId, key);
1515 switch (key) {
1516 case KEY_PARAMETER_AUDIO_ATTRIBUTES:
1517 {
1518 Mutex::Autolock l(mLock);
1519 return setAudioAttributes_l(request);
1520 }
1521 default:
1522 sp<MediaPlayerBase> p = getPlayer();
1523 if (p == 0) { return UNKNOWN_ERROR; }
1524 return p->setParameter(key, request);
1525 }
1526 }
1527
getParameter(int key,Parcel * reply)1528 status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
1529 ALOGV("[%d] getParameter(%d)", mConnId, key);
1530 sp<MediaPlayerBase> p = getPlayer();
1531 if (p == 0) return UNKNOWN_ERROR;
1532 return p->getParameter(key, reply);
1533 }
1534
setRetransmitEndpoint(const struct sockaddr_in * endpoint)1535 status_t MediaPlayerService::Client::setRetransmitEndpoint(
1536 const struct sockaddr_in* endpoint) {
1537
1538 if (NULL != endpoint) {
1539 uint32_t a = ntohl(endpoint->sin_addr.s_addr);
1540 uint16_t p = ntohs(endpoint->sin_port);
1541 ALOGV("[%d] setRetransmitEndpoint(%u.%u.%u.%u:%hu)", mConnId,
1542 (a >> 24), (a >> 16) & 0xFF, (a >> 8) & 0xFF, (a & 0xFF), p);
1543 } else {
1544 ALOGV("[%d] setRetransmitEndpoint = <none>", mConnId);
1545 }
1546
1547 sp<MediaPlayerBase> p = getPlayer();
1548
1549 // Right now, the only valid time to set a retransmit endpoint is before
1550 // player selection has been made (since the presence or absence of a
1551 // retransmit endpoint is going to determine which player is selected during
1552 // setDataSource).
1553 if (p != 0) return INVALID_OPERATION;
1554
1555 if (NULL != endpoint) {
1556 Mutex::Autolock lock(mLock);
1557 mRetransmitEndpoint = *endpoint;
1558 mRetransmitEndpointValid = true;
1559 } else {
1560 Mutex::Autolock lock(mLock);
1561 mRetransmitEndpointValid = false;
1562 }
1563
1564 return NO_ERROR;
1565 }
1566
getRetransmitEndpoint(struct sockaddr_in * endpoint)1567 status_t MediaPlayerService::Client::getRetransmitEndpoint(
1568 struct sockaddr_in* endpoint)
1569 {
1570 if (NULL == endpoint)
1571 return BAD_VALUE;
1572
1573 sp<MediaPlayerBase> p = getPlayer();
1574
1575 if (p != NULL)
1576 return p->getRetransmitEndpoint(endpoint);
1577
1578 Mutex::Autolock lock(mLock);
1579 if (!mRetransmitEndpointValid)
1580 return NO_INIT;
1581
1582 *endpoint = mRetransmitEndpoint;
1583
1584 return NO_ERROR;
1585 }
1586
notify(int msg,int ext1,int ext2,const Parcel * obj)1587 void MediaPlayerService::Client::notify(
1588 int msg, int ext1, int ext2, const Parcel *obj)
1589 {
1590 sp<IMediaPlayerClient> c;
1591 sp<Client> nextClient;
1592 status_t errStartNext = NO_ERROR;
1593 {
1594 Mutex::Autolock l(mLock);
1595 c = mClient;
1596 if (msg == MEDIA_PLAYBACK_COMPLETE && mNextClient != NULL) {
1597 nextClient = mNextClient;
1598
1599 if (mAudioOutput != NULL)
1600 mAudioOutput->switchToNextOutput();
1601
1602 errStartNext = nextClient->start();
1603 }
1604 }
1605
1606 if (nextClient != NULL) {
1607 sp<IMediaPlayerClient> nc;
1608 {
1609 Mutex::Autolock l(nextClient->mLock);
1610 nc = nextClient->mClient;
1611 }
1612 if (nc != NULL) {
1613 if (errStartNext == NO_ERROR) {
1614 nc->notify(MEDIA_INFO, MEDIA_INFO_STARTED_AS_NEXT, 0, obj);
1615 } else {
1616 nc->notify(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN , 0, obj);
1617 ALOGE("gapless:start playback for next track failed, err(%d)", errStartNext);
1618 }
1619 }
1620 }
1621
1622 if (MEDIA_INFO == msg &&
1623 MEDIA_INFO_METADATA_UPDATE == ext1) {
1624 const media::Metadata::Type metadata_type = ext2;
1625
1626 if(shouldDropMetadata(metadata_type)) {
1627 return;
1628 }
1629
1630 // Update the list of metadata that have changed. getMetadata
1631 // also access mMetadataUpdated and clears it.
1632 addNewMetadataUpdate(metadata_type);
1633 }
1634
1635 if (c != NULL) {
1636 ALOGV("[%d] notify (%d, %d, %d)", mConnId, msg, ext1, ext2);
1637 c->notify(msg, ext1, ext2, obj);
1638 }
1639 }
1640
1641
shouldDropMetadata(media::Metadata::Type code) const1642 bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
1643 {
1644 Mutex::Autolock lock(mLock);
1645
1646 if (findMetadata(mMetadataDrop, code)) {
1647 return true;
1648 }
1649
1650 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
1651 return false;
1652 } else {
1653 return true;
1654 }
1655 }
1656
1657
addNewMetadataUpdate(media::Metadata::Type metadata_type)1658 void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
1659 Mutex::Autolock lock(mLock);
1660 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1661 mMetadataUpdated.add(metadata_type);
1662 }
1663 }
1664
1665 // Modular DRM
prepareDrm(const uint8_t uuid[16],const Vector<uint8_t> & drmSessionId)1666 status_t MediaPlayerService::Client::prepareDrm(const uint8_t uuid[16],
1667 const Vector<uint8_t>& drmSessionId)
1668 {
1669 ALOGV("[%d] prepareDrm", mConnId);
1670 sp<MediaPlayerBase> p = getPlayer();
1671 if (p == 0) return UNKNOWN_ERROR;
1672
1673 status_t ret = p->prepareDrm(uuid, drmSessionId);
1674 ALOGV("prepareDrm ret: %d", ret);
1675
1676 return ret;
1677 }
1678
releaseDrm()1679 status_t MediaPlayerService::Client::releaseDrm()
1680 {
1681 ALOGV("[%d] releaseDrm", mConnId);
1682 sp<MediaPlayerBase> p = getPlayer();
1683 if (p == 0) return UNKNOWN_ERROR;
1684
1685 status_t ret = p->releaseDrm();
1686 ALOGV("releaseDrm ret: %d", ret);
1687
1688 return ret;
1689 }
1690
setOutputDevice(audio_port_handle_t deviceId)1691 status_t MediaPlayerService::Client::setOutputDevice(audio_port_handle_t deviceId)
1692 {
1693 ALOGV("[%d] setOutputDevice", mConnId);
1694 {
1695 Mutex::Autolock l(mLock);
1696 if (mAudioOutput.get() != nullptr) {
1697 return mAudioOutput->setOutputDevice(deviceId);
1698 }
1699 }
1700 return NO_INIT;
1701 }
1702
getRoutedDeviceId(audio_port_handle_t * deviceId)1703 status_t MediaPlayerService::Client::getRoutedDeviceId(audio_port_handle_t* deviceId)
1704 {
1705 ALOGV("[%d] getRoutedDeviceId", mConnId);
1706 {
1707 Mutex::Autolock l(mLock);
1708 if (mAudioOutput.get() != nullptr) {
1709 return mAudioOutput->getRoutedDeviceId(deviceId);
1710 }
1711 }
1712 return NO_INIT;
1713 }
1714
enableAudioDeviceCallback(bool enabled)1715 status_t MediaPlayerService::Client::enableAudioDeviceCallback(bool enabled)
1716 {
1717 ALOGV("[%d] enableAudioDeviceCallback, %d", mConnId, enabled);
1718 {
1719 Mutex::Autolock l(mLock);
1720 if (mAudioOutput.get() != nullptr) {
1721 return mAudioOutput->enableAudioDeviceCallback(enabled);
1722 }
1723 }
1724 return NO_INIT;
1725 }
1726
1727 #if CALLBACK_ANTAGONIZER
1728 const int Antagonizer::interval = 10000; // 10 msecs
1729
Antagonizer(const sp<MediaPlayerBase::Listener> & listener)1730 Antagonizer::Antagonizer(const sp<MediaPlayerBase::Listener> &listener) :
1731 mExit(false), mActive(false), mListener(listener)
1732 {
1733 createThread(callbackThread, this);
1734 }
1735
kill()1736 void Antagonizer::kill()
1737 {
1738 Mutex::Autolock _l(mLock);
1739 mActive = false;
1740 mExit = true;
1741 mCondition.wait(mLock);
1742 }
1743
callbackThread(void * user)1744 int Antagonizer::callbackThread(void* user)
1745 {
1746 ALOGD("Antagonizer started");
1747 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1748 while (!p->mExit) {
1749 if (p->mActive) {
1750 ALOGV("send event");
1751 p->mListener->notify(0, 0, 0, 0);
1752 }
1753 usleep(interval);
1754 }
1755 Mutex::Autolock _l(p->mLock);
1756 p->mCondition.signal();
1757 ALOGD("Antagonizer stopped");
1758 return 0;
1759 }
1760 #endif
1761
1762 #undef LOG_TAG
1763 #define LOG_TAG "AudioSink"
AudioOutput(audio_session_t sessionId,uid_t uid,int pid,const audio_attributes_t * attr,const sp<AudioSystem::AudioDeviceCallback> & deviceCallback,const std::string & opPackageName)1764 MediaPlayerService::AudioOutput::AudioOutput(audio_session_t sessionId, uid_t uid, int pid,
1765 const audio_attributes_t* attr, const sp<AudioSystem::AudioDeviceCallback>& deviceCallback,
1766 const std::string& opPackageName)
1767 : mCallback(NULL),
1768 mCallbackCookie(NULL),
1769 mCallbackData(NULL),
1770 mStreamType(AUDIO_STREAM_MUSIC),
1771 mLeftVolume(1.0),
1772 mRightVolume(1.0),
1773 mPlaybackRate(AUDIO_PLAYBACK_RATE_DEFAULT),
1774 mSampleRateHz(0),
1775 mMsecsPerFrame(0),
1776 mFrameSize(0),
1777 mSessionId(sessionId),
1778 mUid(uid),
1779 mPid(pid),
1780 mSendLevel(0.0),
1781 mAuxEffectId(0),
1782 mFlags(AUDIO_OUTPUT_FLAG_NONE),
1783 mVolumeHandler(new media::VolumeHandler()),
1784 mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE),
1785 mRoutedDeviceId(AUDIO_PORT_HANDLE_NONE),
1786 mDeviceCallbackEnabled(false),
1787 mDeviceCallback(deviceCallback),
1788 mOpPackageName(opPackageName)
1789 {
1790 ALOGV("AudioOutput(%d)", sessionId);
1791 if (attr != NULL) {
1792 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1793 if (mAttributes != NULL) {
1794 memcpy(mAttributes, attr, sizeof(audio_attributes_t));
1795 mStreamType = AudioSystem::attributesToStreamType(*attr);
1796 }
1797 } else {
1798 mAttributes = NULL;
1799 }
1800
1801 setMinBufferCount();
1802 }
1803
~AudioOutput()1804 MediaPlayerService::AudioOutput::~AudioOutput()
1805 {
1806 close();
1807 free(mAttributes);
1808 delete mCallbackData;
1809 }
1810
1811 //static
setMinBufferCount()1812 void MediaPlayerService::AudioOutput::setMinBufferCount()
1813 {
1814 char value[PROPERTY_VALUE_MAX];
1815 if (property_get("ro.kernel.qemu", value, 0)) {
1816 mIsOnEmulator = true;
1817 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1818 }
1819 }
1820
1821 // static
isOnEmulator()1822 bool MediaPlayerService::AudioOutput::isOnEmulator()
1823 {
1824 setMinBufferCount(); // benign race wrt other threads
1825 return mIsOnEmulator;
1826 }
1827
1828 // static
getMinBufferCount()1829 int MediaPlayerService::AudioOutput::getMinBufferCount()
1830 {
1831 setMinBufferCount(); // benign race wrt other threads
1832 return mMinBufferCount;
1833 }
1834
bufferSize() const1835 ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1836 {
1837 Mutex::Autolock lock(mLock);
1838 if (mTrack == 0) return NO_INIT;
1839 return mTrack->frameCount() * mFrameSize;
1840 }
1841
frameCount() const1842 ssize_t MediaPlayerService::AudioOutput::frameCount() const
1843 {
1844 Mutex::Autolock lock(mLock);
1845 if (mTrack == 0) return NO_INIT;
1846 return mTrack->frameCount();
1847 }
1848
channelCount() const1849 ssize_t MediaPlayerService::AudioOutput::channelCount() const
1850 {
1851 Mutex::Autolock lock(mLock);
1852 if (mTrack == 0) return NO_INIT;
1853 return mTrack->channelCount();
1854 }
1855
frameSize() const1856 ssize_t MediaPlayerService::AudioOutput::frameSize() const
1857 {
1858 Mutex::Autolock lock(mLock);
1859 if (mTrack == 0) return NO_INIT;
1860 return mFrameSize;
1861 }
1862
latency() const1863 uint32_t MediaPlayerService::AudioOutput::latency () const
1864 {
1865 Mutex::Autolock lock(mLock);
1866 if (mTrack == 0) return 0;
1867 return mTrack->latency();
1868 }
1869
msecsPerFrame() const1870 float MediaPlayerService::AudioOutput::msecsPerFrame() const
1871 {
1872 Mutex::Autolock lock(mLock);
1873 return mMsecsPerFrame;
1874 }
1875
getPosition(uint32_t * position) const1876 status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position) const
1877 {
1878 Mutex::Autolock lock(mLock);
1879 if (mTrack == 0) return NO_INIT;
1880 return mTrack->getPosition(position);
1881 }
1882
getTimestamp(AudioTimestamp & ts) const1883 status_t MediaPlayerService::AudioOutput::getTimestamp(AudioTimestamp &ts) const
1884 {
1885 Mutex::Autolock lock(mLock);
1886 if (mTrack == 0) return NO_INIT;
1887 return mTrack->getTimestamp(ts);
1888 }
1889
1890 // TODO: Remove unnecessary calls to getPlayedOutDurationUs()
1891 // as it acquires locks and may query the audio driver.
1892 //
1893 // Some calls could conceivably retrieve extrapolated data instead of
1894 // accessing getTimestamp() or getPosition() every time a data buffer with
1895 // a media time is received.
1896 //
1897 // Calculate duration of played samples if played at normal rate (i.e., 1.0).
getPlayedOutDurationUs(int64_t nowUs) const1898 int64_t MediaPlayerService::AudioOutput::getPlayedOutDurationUs(int64_t nowUs) const
1899 {
1900 Mutex::Autolock lock(mLock);
1901 if (mTrack == 0 || mSampleRateHz == 0) {
1902 return 0;
1903 }
1904
1905 uint32_t numFramesPlayed;
1906 int64_t numFramesPlayedAtUs;
1907 AudioTimestamp ts;
1908
1909 status_t res = mTrack->getTimestamp(ts);
1910 if (res == OK) { // case 1: mixing audio tracks and offloaded tracks.
1911 numFramesPlayed = ts.mPosition;
1912 numFramesPlayedAtUs = ts.mTime.tv_sec * 1000000LL + ts.mTime.tv_nsec / 1000;
1913 //ALOGD("getTimestamp: OK %d %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
1914 } else if (res == WOULD_BLOCK) { // case 2: transitory state on start of a new track
1915 numFramesPlayed = 0;
1916 numFramesPlayedAtUs = nowUs;
1917 //ALOGD("getTimestamp: WOULD_BLOCK %d %lld",
1918 // numFramesPlayed, (long long)numFramesPlayedAtUs);
1919 } else { // case 3: transitory at new track or audio fast tracks.
1920 res = mTrack->getPosition(&numFramesPlayed);
1921 CHECK_EQ(res, (status_t)OK);
1922 numFramesPlayedAtUs = nowUs;
1923 numFramesPlayedAtUs += 1000LL * mTrack->latency() / 2; /* XXX */
1924 //ALOGD("getPosition: %u %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
1925 }
1926
1927 // CHECK_EQ(numFramesPlayed & (1 << 31), 0); // can't be negative until 12.4 hrs, test
1928 // TODO: remove the (int32_t) casting below as it may overflow at 12.4 hours.
1929 int64_t durationUs = (int64_t)((int32_t)numFramesPlayed * 1000000LL / mSampleRateHz)
1930 + nowUs - numFramesPlayedAtUs;
1931 if (durationUs < 0) {
1932 // Occurs when numFramesPlayed position is very small and the following:
1933 // (1) In case 1, the time nowUs is computed before getTimestamp() is called and
1934 // numFramesPlayedAtUs is greater than nowUs by time more than numFramesPlayed.
1935 // (2) In case 3, using getPosition and adding mAudioSink->latency() to
1936 // numFramesPlayedAtUs, by a time amount greater than numFramesPlayed.
1937 //
1938 // Both of these are transitory conditions.
1939 ALOGV("getPlayedOutDurationUs: negative duration %lld set to zero", (long long)durationUs);
1940 durationUs = 0;
1941 }
1942 ALOGV("getPlayedOutDurationUs(%lld) nowUs(%lld) frames(%u) framesAt(%lld)",
1943 (long long)durationUs, (long long)nowUs,
1944 numFramesPlayed, (long long)numFramesPlayedAtUs);
1945 return durationUs;
1946 }
1947
getFramesWritten(uint32_t * frameswritten) const1948 status_t MediaPlayerService::AudioOutput::getFramesWritten(uint32_t *frameswritten) const
1949 {
1950 Mutex::Autolock lock(mLock);
1951 if (mTrack == 0) return NO_INIT;
1952 ExtendedTimestamp ets;
1953 status_t status = mTrack->getTimestamp(&ets);
1954 if (status == OK || status == WOULD_BLOCK) {
1955 *frameswritten = (uint32_t)ets.mPosition[ExtendedTimestamp::LOCATION_CLIENT];
1956 }
1957 return status;
1958 }
1959
setParameters(const String8 & keyValuePairs)1960 status_t MediaPlayerService::AudioOutput::setParameters(const String8& keyValuePairs)
1961 {
1962 Mutex::Autolock lock(mLock);
1963 if (mTrack == 0) return NO_INIT;
1964 return mTrack->setParameters(keyValuePairs);
1965 }
1966
getParameters(const String8 & keys)1967 String8 MediaPlayerService::AudioOutput::getParameters(const String8& keys)
1968 {
1969 Mutex::Autolock lock(mLock);
1970 if (mTrack == 0) return String8::empty();
1971 return mTrack->getParameters(keys);
1972 }
1973
setAudioAttributes(const audio_attributes_t * attributes)1974 void MediaPlayerService::AudioOutput::setAudioAttributes(const audio_attributes_t * attributes) {
1975 Mutex::Autolock lock(mLock);
1976 if (attributes == NULL) {
1977 free(mAttributes);
1978 mAttributes = NULL;
1979 } else {
1980 if (mAttributes == NULL) {
1981 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1982 }
1983 memcpy(mAttributes, attributes, sizeof(audio_attributes_t));
1984 mStreamType = AudioSystem::attributesToStreamType(*attributes);
1985 }
1986 }
1987
setAudioStreamType(audio_stream_type_t streamType)1988 void MediaPlayerService::AudioOutput::setAudioStreamType(audio_stream_type_t streamType)
1989 {
1990 Mutex::Autolock lock(mLock);
1991 // do not allow direct stream type modification if attributes have been set
1992 if (mAttributes == NULL) {
1993 mStreamType = streamType;
1994 }
1995 }
1996
deleteRecycledTrack_l()1997 void MediaPlayerService::AudioOutput::deleteRecycledTrack_l()
1998 {
1999 ALOGV("deleteRecycledTrack_l");
2000 if (mRecycledTrack != 0) {
2001
2002 if (mCallbackData != NULL) {
2003 mCallbackData->setOutput(NULL);
2004 mCallbackData->endTrackSwitch();
2005 }
2006
2007 if ((mRecycledTrack->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) {
2008 int32_t msec = 0;
2009 if (!mRecycledTrack->stopped()) { // check if active
2010 (void)mRecycledTrack->pendingDuration(&msec);
2011 }
2012 mRecycledTrack->stop(); // ensure full data drain
2013 ALOGD("deleting recycled track, waiting for data drain (%d msec)", msec);
2014 if (msec > 0) {
2015 static const int32_t WAIT_LIMIT_MS = 3000;
2016 if (msec > WAIT_LIMIT_MS) {
2017 msec = WAIT_LIMIT_MS;
2018 }
2019 usleep(msec * 1000LL);
2020 }
2021 }
2022 // An offloaded track isn't flushed because the STREAM_END is reported
2023 // slightly prematurely to allow time for the gapless track switch
2024 // but this means that if we decide not to recycle the track there
2025 // could be a small amount of residual data still playing. We leave
2026 // AudioFlinger to drain the track.
2027
2028 mRecycledTrack.clear();
2029 close_l();
2030 delete mCallbackData;
2031 mCallbackData = NULL;
2032 }
2033 }
2034
close_l()2035 void MediaPlayerService::AudioOutput::close_l()
2036 {
2037 mTrack.clear();
2038 }
2039
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)2040 status_t MediaPlayerService::AudioOutput::open(
2041 uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
2042 audio_format_t format, int bufferCount,
2043 AudioCallback cb, void *cookie,
2044 audio_output_flags_t flags,
2045 const audio_offload_info_t *offloadInfo,
2046 bool doNotReconnect,
2047 uint32_t suggestedFrameCount)
2048 {
2049 ALOGV("open(%u, %d, 0x%x, 0x%x, %d, %d 0x%x)", sampleRate, channelCount, channelMask,
2050 format, bufferCount, mSessionId, flags);
2051
2052 // offloading is only supported in callback mode for now.
2053 // offloadInfo must be present if offload flag is set
2054 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) &&
2055 ((cb == NULL) || (offloadInfo == NULL))) {
2056 return BAD_VALUE;
2057 }
2058
2059 // compute frame count for the AudioTrack internal buffer
2060 size_t frameCount;
2061 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
2062 frameCount = 0; // AudioTrack will get frame count from AudioFlinger
2063 } else {
2064 // try to estimate the buffer processing fetch size from AudioFlinger.
2065 // framesPerBuffer is approximate and generally correct, except when it's not :-).
2066 uint32_t afSampleRate;
2067 size_t afFrameCount;
2068 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
2069 return NO_INIT;
2070 }
2071 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
2072 return NO_INIT;
2073 }
2074 if (afSampleRate == 0) {
2075 return NO_INIT;
2076 }
2077 const size_t framesPerBuffer =
2078 (unsigned long long)sampleRate * afFrameCount / afSampleRate;
2079
2080 if (bufferCount == 0) {
2081 if (framesPerBuffer == 0) {
2082 return NO_INIT;
2083 }
2084 // use suggestedFrameCount
2085 bufferCount = (suggestedFrameCount + framesPerBuffer - 1) / framesPerBuffer;
2086 }
2087 // Check argument bufferCount against the mininum buffer count
2088 if (bufferCount != 0 && bufferCount < mMinBufferCount) {
2089 ALOGV("bufferCount (%d) increased to %d", bufferCount, mMinBufferCount);
2090 bufferCount = mMinBufferCount;
2091 }
2092 // if frameCount is 0, then AudioTrack will get frame count from AudioFlinger
2093 // which will be the minimum size permitted.
2094 frameCount = bufferCount * framesPerBuffer;
2095 }
2096
2097 if (channelMask == CHANNEL_MASK_USE_CHANNEL_ORDER) {
2098 channelMask = audio_channel_out_mask_from_count(channelCount);
2099 if (0 == channelMask) {
2100 ALOGE("open() error, can\'t derive mask for %d audio channels", channelCount);
2101 return NO_INIT;
2102 }
2103 }
2104
2105 Mutex::Autolock lock(mLock);
2106 mCallback = cb;
2107 mCallbackCookie = cookie;
2108
2109 // Check whether we can recycle the track
2110 bool reuse = false;
2111 bool bothOffloaded = false;
2112
2113 if (mRecycledTrack != 0) {
2114 // check whether we are switching between two offloaded tracks
2115 bothOffloaded = (flags & mRecycledTrack->getFlags()
2116 & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0;
2117
2118 // check if the existing track can be reused as-is, or if a new track needs to be created.
2119 reuse = true;
2120
2121 if ((mCallbackData == NULL && mCallback != NULL) ||
2122 (mCallbackData != NULL && mCallback == NULL)) {
2123 // recycled track uses callbacks but the caller wants to use writes, or vice versa
2124 ALOGV("can't chain callback and write");
2125 reuse = false;
2126 } else if ((mRecycledTrack->getSampleRate() != sampleRate) ||
2127 (mRecycledTrack->channelCount() != (uint32_t)channelCount) ) {
2128 ALOGV("samplerate, channelcount differ: %u/%u Hz, %u/%d ch",
2129 mRecycledTrack->getSampleRate(), sampleRate,
2130 mRecycledTrack->channelCount(), channelCount);
2131 reuse = false;
2132 } else if (flags != mFlags) {
2133 ALOGV("output flags differ %08x/%08x", flags, mFlags);
2134 reuse = false;
2135 } else if (mRecycledTrack->format() != format) {
2136 reuse = false;
2137 }
2138 } else {
2139 ALOGV("no track available to recycle");
2140 }
2141
2142 ALOGV_IF(bothOffloaded, "both tracks offloaded");
2143
2144 // If we can't recycle and both tracks are offloaded
2145 // we must close the previous output before opening a new one
2146 if (bothOffloaded && !reuse) {
2147 ALOGV("both offloaded and not recycling");
2148 deleteRecycledTrack_l();
2149 }
2150
2151 sp<AudioTrack> t;
2152 CallbackData *newcbd = NULL;
2153
2154 // We don't attempt to create a new track if we are recycling an
2155 // offloaded track. But, if we are recycling a non-offloaded or we
2156 // are switching where one is offloaded and one isn't then we create
2157 // the new track in advance so that we can read additional stream info
2158
2159 if (!(reuse && bothOffloaded)) {
2160 ALOGV("creating new AudioTrack");
2161
2162 if (mCallback != NULL) {
2163 newcbd = new CallbackData(this);
2164 t = new AudioTrack(
2165 mStreamType,
2166 sampleRate,
2167 format,
2168 channelMask,
2169 frameCount,
2170 flags,
2171 CallbackWrapper,
2172 newcbd,
2173 0, // notification frames
2174 mSessionId,
2175 AudioTrack::TRANSFER_CALLBACK,
2176 offloadInfo,
2177 mUid,
2178 mPid,
2179 mAttributes,
2180 doNotReconnect,
2181 1.0f, // default value for maxRequiredSpeed
2182 mSelectedDeviceId,
2183 mOpPackageName);
2184 } else {
2185 // TODO: Due to buffer memory concerns, we use a max target playback speed
2186 // based on mPlaybackRate at the time of open (instead of kMaxRequiredSpeed),
2187 // also clamping the target speed to 1.0 <= targetSpeed <= kMaxRequiredSpeed.
2188 const float targetSpeed =
2189 std::min(std::max(mPlaybackRate.mSpeed, 1.0f), kMaxRequiredSpeed);
2190 ALOGW_IF(targetSpeed != mPlaybackRate.mSpeed,
2191 "track target speed:%f clamped from playback speed:%f",
2192 targetSpeed, mPlaybackRate.mSpeed);
2193 t = new AudioTrack(
2194 mStreamType,
2195 sampleRate,
2196 format,
2197 channelMask,
2198 frameCount,
2199 flags,
2200 NULL, // callback
2201 NULL, // user data
2202 0, // notification frames
2203 mSessionId,
2204 AudioTrack::TRANSFER_DEFAULT,
2205 NULL, // offload info
2206 mUid,
2207 mPid,
2208 mAttributes,
2209 doNotReconnect,
2210 targetSpeed,
2211 mSelectedDeviceId,
2212 mOpPackageName);
2213 }
2214 // Set caller name so it can be logged in destructor.
2215 // MediaMetricsConstants.h: AMEDIAMETRICS_PROP_CALLERNAME_VALUE_MEDIA
2216 t->setCallerName("media");
2217 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
2218 ALOGE("Unable to create audio track");
2219 delete newcbd;
2220 // t goes out of scope, so reference count drops to zero
2221 return NO_INIT;
2222 } else {
2223 // successful AudioTrack initialization implies a legacy stream type was generated
2224 // from the audio attributes
2225 mStreamType = t->streamType();
2226 }
2227 }
2228
2229 if (reuse) {
2230 CHECK(mRecycledTrack != NULL);
2231
2232 if (!bothOffloaded) {
2233 if (mRecycledTrack->frameCount() != t->frameCount()) {
2234 ALOGV("framecount differs: %zu/%zu frames",
2235 mRecycledTrack->frameCount(), t->frameCount());
2236 reuse = false;
2237 }
2238 }
2239
2240 if (reuse) {
2241 ALOGV("chaining to next output and recycling track");
2242 close_l();
2243 mTrack = mRecycledTrack;
2244 mRecycledTrack.clear();
2245 if (mCallbackData != NULL) {
2246 mCallbackData->setOutput(this);
2247 }
2248 delete newcbd;
2249 return updateTrack();
2250 }
2251 }
2252
2253 // we're not going to reuse the track, unblock and flush it
2254 // this was done earlier if both tracks are offloaded
2255 if (!bothOffloaded) {
2256 deleteRecycledTrack_l();
2257 }
2258
2259 CHECK((t != NULL) && ((mCallback == NULL) || (newcbd != NULL)));
2260
2261 mCallbackData = newcbd;
2262 ALOGV("setVolume");
2263 t->setVolume(mLeftVolume, mRightVolume);
2264
2265 // Restore VolumeShapers for the MediaPlayer in case the track was recreated
2266 // due to an output sink error (e.g. offload to non-offload switch).
2267 mVolumeHandler->forall([&t](const VolumeShaper &shaper) -> VolumeShaper::Status {
2268 sp<VolumeShaper::Operation> operationToEnd =
2269 new VolumeShaper::Operation(shaper.mOperation);
2270 // TODO: Ideally we would restore to the exact xOffset position
2271 // as returned by getVolumeShaperState(), but we don't have that
2272 // information when restoring at the client unless we periodically poll
2273 // the server or create shared memory state.
2274 //
2275 // For now, we simply advance to the end of the VolumeShaper effect
2276 // if it has been started.
2277 if (shaper.isStarted()) {
2278 operationToEnd->setNormalizedTime(1.f);
2279 }
2280 return t->applyVolumeShaper(shaper.mConfiguration, operationToEnd);
2281 });
2282
2283 mSampleRateHz = sampleRate;
2284 mFlags = flags;
2285 mMsecsPerFrame = 1E3f / (mPlaybackRate.mSpeed * sampleRate);
2286 mFrameSize = t->frameSize();
2287 mTrack = t;
2288
2289 return updateTrack();
2290 }
2291
updateTrack()2292 status_t MediaPlayerService::AudioOutput::updateTrack() {
2293 if (mTrack == NULL) {
2294 return NO_ERROR;
2295 }
2296
2297 status_t res = NO_ERROR;
2298 // Note some output devices may give us a direct track even though we don't specify it.
2299 // Example: Line application b/17459982.
2300 if ((mTrack->getFlags()
2301 & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) {
2302 res = mTrack->setPlaybackRate(mPlaybackRate);
2303 if (res == NO_ERROR) {
2304 mTrack->setAuxEffectSendLevel(mSendLevel);
2305 res = mTrack->attachAuxEffect(mAuxEffectId);
2306 }
2307 }
2308 mTrack->setOutputDevice(mSelectedDeviceId);
2309 if (mDeviceCallbackEnabled) {
2310 mTrack->addAudioDeviceCallback(mDeviceCallback.promote());
2311 }
2312 ALOGV("updateTrack() DONE status %d", res);
2313 return res;
2314 }
2315
start()2316 status_t MediaPlayerService::AudioOutput::start()
2317 {
2318 ALOGV("start");
2319 Mutex::Autolock lock(mLock);
2320 if (mCallbackData != NULL) {
2321 mCallbackData->endTrackSwitch();
2322 }
2323 if (mTrack != 0) {
2324 mTrack->setVolume(mLeftVolume, mRightVolume);
2325 mTrack->setAuxEffectSendLevel(mSendLevel);
2326 status_t status = mTrack->start();
2327 if (status == NO_ERROR) {
2328 mVolumeHandler->setStarted();
2329 }
2330 return status;
2331 }
2332 return NO_INIT;
2333 }
2334
setNextOutput(const sp<AudioOutput> & nextOutput)2335 void MediaPlayerService::AudioOutput::setNextOutput(const sp<AudioOutput>& nextOutput) {
2336 Mutex::Autolock lock(mLock);
2337 mNextOutput = nextOutput;
2338 }
2339
switchToNextOutput()2340 void MediaPlayerService::AudioOutput::switchToNextOutput() {
2341 ALOGV("switchToNextOutput");
2342
2343 // Try to acquire the callback lock before moving track (without incurring deadlock).
2344 const unsigned kMaxSwitchTries = 100;
2345 Mutex::Autolock lock(mLock);
2346 for (unsigned tries = 0;;) {
2347 if (mTrack == 0) {
2348 return;
2349 }
2350 if (mNextOutput != NULL && mNextOutput != this) {
2351 if (mCallbackData != NULL) {
2352 // two alternative approaches
2353 #if 1
2354 CallbackData *callbackData = mCallbackData;
2355 mLock.unlock();
2356 // proper acquisition sequence
2357 callbackData->lock();
2358 mLock.lock();
2359 // Caution: it is unlikely that someone deleted our callback or changed our target
2360 if (callbackData != mCallbackData || mNextOutput == NULL || mNextOutput == this) {
2361 // fatal if we are starved out.
2362 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2363 "switchToNextOutput() cannot obtain correct lock sequence");
2364 callbackData->unlock();
2365 continue;
2366 }
2367 callbackData->mSwitching = true; // begin track switch
2368 callbackData->setOutput(NULL);
2369 #else
2370 // tryBeginTrackSwitch() returns false if the callback has the lock.
2371 if (!mCallbackData->tryBeginTrackSwitch()) {
2372 // fatal if we are starved out.
2373 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2374 "switchToNextOutput() cannot obtain callback lock");
2375 mLock.unlock();
2376 usleep(5 * 1000 /* usec */); // allow callback to use AudioOutput
2377 mLock.lock();
2378 continue;
2379 }
2380 #endif
2381 }
2382
2383 Mutex::Autolock nextLock(mNextOutput->mLock);
2384
2385 // If the next output track is not NULL, then it has been
2386 // opened already for playback.
2387 // This is possible even without the next player being started,
2388 // for example, the next player could be prepared and seeked.
2389 //
2390 // Presuming it isn't advisable to force the track over.
2391 if (mNextOutput->mTrack == NULL) {
2392 ALOGD("Recycling track for gapless playback");
2393 delete mNextOutput->mCallbackData;
2394 mNextOutput->mCallbackData = mCallbackData;
2395 mNextOutput->mRecycledTrack = mTrack;
2396 mNextOutput->mSampleRateHz = mSampleRateHz;
2397 mNextOutput->mMsecsPerFrame = mMsecsPerFrame;
2398 mNextOutput->mFlags = mFlags;
2399 mNextOutput->mFrameSize = mFrameSize;
2400 close_l();
2401 mCallbackData = NULL; // destruction handled by mNextOutput
2402 } else {
2403 ALOGW("Ignoring gapless playback because next player has already started");
2404 // remove track in case resource needed for future players.
2405 if (mCallbackData != NULL) {
2406 mCallbackData->endTrackSwitch(); // release lock for callbacks before close.
2407 }
2408 close_l();
2409 }
2410 }
2411 break;
2412 }
2413 }
2414
write(const void * buffer,size_t size,bool blocking)2415 ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size, bool blocking)
2416 {
2417 Mutex::Autolock lock(mLock);
2418 LOG_ALWAYS_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
2419
2420 //ALOGV("write(%p, %u)", buffer, size);
2421 if (mTrack != 0) {
2422 return mTrack->write(buffer, size, blocking);
2423 }
2424 return NO_INIT;
2425 }
2426
stop()2427 void MediaPlayerService::AudioOutput::stop()
2428 {
2429 ALOGV("stop");
2430 Mutex::Autolock lock(mLock);
2431 if (mTrack != 0) mTrack->stop();
2432 }
2433
flush()2434 void MediaPlayerService::AudioOutput::flush()
2435 {
2436 ALOGV("flush");
2437 Mutex::Autolock lock(mLock);
2438 if (mTrack != 0) mTrack->flush();
2439 }
2440
pause()2441 void MediaPlayerService::AudioOutput::pause()
2442 {
2443 ALOGV("pause");
2444 Mutex::Autolock lock(mLock);
2445 if (mTrack != 0) mTrack->pause();
2446 }
2447
close()2448 void MediaPlayerService::AudioOutput::close()
2449 {
2450 ALOGV("close");
2451 sp<AudioTrack> track;
2452 {
2453 Mutex::Autolock lock(mLock);
2454 track = mTrack;
2455 close_l(); // clears mTrack
2456 }
2457 // destruction of the track occurs outside of mutex.
2458 }
2459
setVolume(float left,float right)2460 void MediaPlayerService::AudioOutput::setVolume(float left, float right)
2461 {
2462 ALOGV("setVolume(%f, %f)", left, right);
2463 Mutex::Autolock lock(mLock);
2464 mLeftVolume = left;
2465 mRightVolume = right;
2466 if (mTrack != 0) {
2467 mTrack->setVolume(left, right);
2468 }
2469 }
2470
setPlaybackRate(const AudioPlaybackRate & rate)2471 status_t MediaPlayerService::AudioOutput::setPlaybackRate(const AudioPlaybackRate &rate)
2472 {
2473 ALOGV("setPlaybackRate(%f %f %d %d)",
2474 rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
2475 Mutex::Autolock lock(mLock);
2476 if (mTrack == 0) {
2477 // remember rate so that we can set it when the track is opened
2478 mPlaybackRate = rate;
2479 return OK;
2480 }
2481 status_t res = mTrack->setPlaybackRate(rate);
2482 if (res != NO_ERROR) {
2483 return res;
2484 }
2485 // rate.mSpeed is always greater than 0 if setPlaybackRate succeeded
2486 CHECK_GT(rate.mSpeed, 0.f);
2487 mPlaybackRate = rate;
2488 if (mSampleRateHz != 0) {
2489 mMsecsPerFrame = 1E3f / (rate.mSpeed * mSampleRateHz);
2490 }
2491 return res;
2492 }
2493
getPlaybackRate(AudioPlaybackRate * rate)2494 status_t MediaPlayerService::AudioOutput::getPlaybackRate(AudioPlaybackRate *rate)
2495 {
2496 ALOGV("setPlaybackRate");
2497 Mutex::Autolock lock(mLock);
2498 if (mTrack == 0) {
2499 return NO_INIT;
2500 }
2501 *rate = mTrack->getPlaybackRate();
2502 return NO_ERROR;
2503 }
2504
setAuxEffectSendLevel(float level)2505 status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
2506 {
2507 ALOGV("setAuxEffectSendLevel(%f)", level);
2508 Mutex::Autolock lock(mLock);
2509 mSendLevel = level;
2510 if (mTrack != 0) {
2511 return mTrack->setAuxEffectSendLevel(level);
2512 }
2513 return NO_ERROR;
2514 }
2515
attachAuxEffect(int effectId)2516 status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
2517 {
2518 ALOGV("attachAuxEffect(%d)", effectId);
2519 Mutex::Autolock lock(mLock);
2520 mAuxEffectId = effectId;
2521 if (mTrack != 0) {
2522 return mTrack->attachAuxEffect(effectId);
2523 }
2524 return NO_ERROR;
2525 }
2526
setOutputDevice(audio_port_handle_t deviceId)2527 status_t MediaPlayerService::AudioOutput::setOutputDevice(audio_port_handle_t deviceId)
2528 {
2529 ALOGV("setOutputDevice(%d)", deviceId);
2530 Mutex::Autolock lock(mLock);
2531 mSelectedDeviceId = deviceId;
2532 if (mTrack != 0) {
2533 return mTrack->setOutputDevice(deviceId);
2534 }
2535 return NO_ERROR;
2536 }
2537
getRoutedDeviceId(audio_port_handle_t * deviceId)2538 status_t MediaPlayerService::AudioOutput::getRoutedDeviceId(audio_port_handle_t* deviceId)
2539 {
2540 ALOGV("getRoutedDeviceId");
2541 Mutex::Autolock lock(mLock);
2542 if (mTrack != 0) {
2543 mRoutedDeviceId = mTrack->getRoutedDeviceId();
2544 }
2545 *deviceId = mRoutedDeviceId;
2546 return NO_ERROR;
2547 }
2548
enableAudioDeviceCallback(bool enabled)2549 status_t MediaPlayerService::AudioOutput::enableAudioDeviceCallback(bool enabled)
2550 {
2551 ALOGV("enableAudioDeviceCallback, %d", enabled);
2552 Mutex::Autolock lock(mLock);
2553 mDeviceCallbackEnabled = enabled;
2554 if (mTrack != 0) {
2555 status_t status;
2556 if (enabled) {
2557 status = mTrack->addAudioDeviceCallback(mDeviceCallback.promote());
2558 } else {
2559 status = mTrack->removeAudioDeviceCallback(mDeviceCallback.promote());
2560 }
2561 return status;
2562 }
2563 return NO_ERROR;
2564 }
2565
applyVolumeShaper(const sp<VolumeShaper::Configuration> & configuration,const sp<VolumeShaper::Operation> & operation)2566 VolumeShaper::Status MediaPlayerService::AudioOutput::applyVolumeShaper(
2567 const sp<VolumeShaper::Configuration>& configuration,
2568 const sp<VolumeShaper::Operation>& operation)
2569 {
2570 Mutex::Autolock lock(mLock);
2571 ALOGV("AudioOutput::applyVolumeShaper");
2572
2573 mVolumeHandler->setIdIfNecessary(configuration);
2574
2575 VolumeShaper::Status status;
2576 if (mTrack != 0) {
2577 status = mTrack->applyVolumeShaper(configuration, operation);
2578 if (status >= 0) {
2579 (void)mVolumeHandler->applyVolumeShaper(configuration, operation);
2580 if (mTrack->isPlaying()) { // match local AudioTrack to properly restore.
2581 mVolumeHandler->setStarted();
2582 }
2583 }
2584 } else {
2585 // VolumeShapers are not affected when a track moves between players for
2586 // gapless playback (setNextMediaPlayer).
2587 // We forward VolumeShaper operations that do not change configuration
2588 // to the new player so that unducking may occur as expected.
2589 // Unducking is an idempotent operation, same if applied back-to-back.
2590 if (configuration->getType() == VolumeShaper::Configuration::TYPE_ID
2591 && mNextOutput != nullptr) {
2592 ALOGV("applyVolumeShaper: Attempting to forward missed operation: %s %s",
2593 configuration->toString().c_str(), operation->toString().c_str());
2594 Mutex::Autolock nextLock(mNextOutput->mLock);
2595
2596 // recycled track should be forwarded from this AudioSink by switchToNextOutput
2597 sp<AudioTrack> track = mNextOutput->mRecycledTrack;
2598 if (track != nullptr) {
2599 ALOGD("Forward VolumeShaper operation to recycled track %p", track.get());
2600 (void)track->applyVolumeShaper(configuration, operation);
2601 } else {
2602 // There is a small chance that the unduck occurs after the next
2603 // player has already started, but before it is registered to receive
2604 // the unduck command.
2605 track = mNextOutput->mTrack;
2606 if (track != nullptr) {
2607 ALOGD("Forward VolumeShaper operation to track %p", track.get());
2608 (void)track->applyVolumeShaper(configuration, operation);
2609 }
2610 }
2611 }
2612 status = mVolumeHandler->applyVolumeShaper(configuration, operation);
2613 }
2614 return status;
2615 }
2616
getVolumeShaperState(int id)2617 sp<VolumeShaper::State> MediaPlayerService::AudioOutput::getVolumeShaperState(int id)
2618 {
2619 Mutex::Autolock lock(mLock);
2620 if (mTrack != 0) {
2621 return mTrack->getVolumeShaperState(id);
2622 } else {
2623 return mVolumeHandler->getVolumeShaperState(id);
2624 }
2625 }
2626
2627 // static
CallbackWrapper(int event,void * cookie,void * info)2628 void MediaPlayerService::AudioOutput::CallbackWrapper(
2629 int event, void *cookie, void *info) {
2630 //ALOGV("callbackwrapper");
2631 CallbackData *data = (CallbackData*)cookie;
2632 // lock to ensure we aren't caught in the middle of a track switch.
2633 data->lock();
2634 AudioOutput *me = data->getOutput();
2635 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
2636 if (me == NULL) {
2637 // no output set, likely because the track was scheduled to be reused
2638 // by another player, but the format turned out to be incompatible.
2639 data->unlock();
2640 if (buffer != NULL) {
2641 buffer->size = 0;
2642 }
2643 return;
2644 }
2645
2646 switch(event) {
2647 case AudioTrack::EVENT_MORE_DATA: {
2648 size_t actualSize = (*me->mCallback)(
2649 me, buffer->raw, buffer->size, me->mCallbackCookie,
2650 CB_EVENT_FILL_BUFFER);
2651
2652 // Log when no data is returned from the callback.
2653 // (1) We may have no data (especially with network streaming sources).
2654 // (2) We may have reached the EOS and the audio track is not stopped yet.
2655 // Note that AwesomePlayer/AudioPlayer will only return zero size when it reaches the EOS.
2656 // NuPlayerRenderer will return zero when it doesn't have data (it doesn't block to fill).
2657 //
2658 // This is a benign busy-wait, with the next data request generated 10 ms or more later;
2659 // nevertheless for power reasons, we don't want to see too many of these.
2660
2661 ALOGV_IF(actualSize == 0 && buffer->size > 0, "callbackwrapper: empty buffer returned");
2662
2663 buffer->size = actualSize;
2664 } break;
2665
2666 case AudioTrack::EVENT_STREAM_END:
2667 // currently only occurs for offloaded callbacks
2668 ALOGV("callbackwrapper: deliver EVENT_STREAM_END");
2669 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2670 me->mCallbackCookie, CB_EVENT_STREAM_END);
2671 break;
2672
2673 case AudioTrack::EVENT_NEW_IAUDIOTRACK :
2674 ALOGV("callbackwrapper: deliver EVENT_TEAR_DOWN");
2675 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2676 me->mCallbackCookie, CB_EVENT_TEAR_DOWN);
2677 break;
2678
2679 case AudioTrack::EVENT_UNDERRUN:
2680 // This occurs when there is no data available, typically
2681 // when there is a failure to supply data to the AudioTrack. It can also
2682 // occur in non-offloaded mode when the audio device comes out of standby.
2683 //
2684 // If an AudioTrack underruns it outputs silence. Since this happens suddenly
2685 // it may sound like an audible pop or glitch.
2686 //
2687 // The underrun event is sent once per track underrun; the condition is reset
2688 // when more data is sent to the AudioTrack.
2689 ALOGD("callbackwrapper: EVENT_UNDERRUN (discarded)");
2690 break;
2691
2692 default:
2693 ALOGE("received unknown event type: %d inside CallbackWrapper !", event);
2694 }
2695
2696 data->unlock();
2697 }
2698
getSessionId() const2699 audio_session_t MediaPlayerService::AudioOutput::getSessionId() const
2700 {
2701 Mutex::Autolock lock(mLock);
2702 return mSessionId;
2703 }
2704
getSampleRate() const2705 uint32_t MediaPlayerService::AudioOutput::getSampleRate() const
2706 {
2707 Mutex::Autolock lock(mLock);
2708 if (mTrack == 0) return 0;
2709 return mTrack->getSampleRate();
2710 }
2711
getBufferDurationInUs() const2712 int64_t MediaPlayerService::AudioOutput::getBufferDurationInUs() const
2713 {
2714 Mutex::Autolock lock(mLock);
2715 if (mTrack == 0) {
2716 return 0;
2717 }
2718 int64_t duration;
2719 if (mTrack->getBufferDurationInUs(&duration) != OK) {
2720 return 0;
2721 }
2722 return duration;
2723 }
2724
2725 ////////////////////////////////////////////////////////////////////////////////
2726
2727 struct CallbackThread : public Thread {
2728 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
2729 MediaPlayerBase::AudioSink::AudioCallback cb,
2730 void *cookie);
2731
2732 protected:
2733 virtual ~CallbackThread();
2734
2735 virtual bool threadLoop();
2736
2737 private:
2738 wp<MediaPlayerBase::AudioSink> mSink;
2739 MediaPlayerBase::AudioSink::AudioCallback mCallback;
2740 void *mCookie;
2741 void *mBuffer;
2742 size_t mBufferSize;
2743
2744 CallbackThread(const CallbackThread &);
2745 CallbackThread &operator=(const CallbackThread &);
2746 };
2747
CallbackThread(const wp<MediaPlayerBase::AudioSink> & sink,MediaPlayerBase::AudioSink::AudioCallback cb,void * cookie)2748 CallbackThread::CallbackThread(
2749 const wp<MediaPlayerBase::AudioSink> &sink,
2750 MediaPlayerBase::AudioSink::AudioCallback cb,
2751 void *cookie)
2752 : mSink(sink),
2753 mCallback(cb),
2754 mCookie(cookie),
2755 mBuffer(NULL),
2756 mBufferSize(0) {
2757 }
2758
~CallbackThread()2759 CallbackThread::~CallbackThread() {
2760 if (mBuffer) {
2761 free(mBuffer);
2762 mBuffer = NULL;
2763 }
2764 }
2765
threadLoop()2766 bool CallbackThread::threadLoop() {
2767 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
2768 if (sink == NULL) {
2769 return false;
2770 }
2771
2772 if (mBuffer == NULL) {
2773 mBufferSize = sink->bufferSize();
2774 mBuffer = malloc(mBufferSize);
2775 }
2776
2777 size_t actualSize =
2778 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie,
2779 MediaPlayerBase::AudioSink::CB_EVENT_FILL_BUFFER);
2780
2781 if (actualSize > 0) {
2782 sink->write(mBuffer, actualSize);
2783 // Could return false on sink->write() error or short count.
2784 // Not necessarily appropriate but would work for AudioCache behavior.
2785 }
2786
2787 return true;
2788 }
2789
2790 ////////////////////////////////////////////////////////////////////////////////
2791
addBatteryData(uint32_t params)2792 void MediaPlayerService::addBatteryData(uint32_t params) {
2793 mBatteryTracker.addBatteryData(params);
2794 }
2795
pullBatteryData(Parcel * reply)2796 status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
2797 return mBatteryTracker.pullBatteryData(reply);
2798 }
2799
BatteryTracker()2800 MediaPlayerService::BatteryTracker::BatteryTracker() {
2801 mBatteryAudio.refCount = 0;
2802 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2803 mBatteryAudio.deviceOn[i] = 0;
2804 mBatteryAudio.lastTime[i] = 0;
2805 mBatteryAudio.totalTime[i] = 0;
2806 }
2807 // speaker is on by default
2808 mBatteryAudio.deviceOn[SPEAKER] = 1;
2809
2810 // reset battery stats
2811 // if the mediaserver has crashed, battery stats could be left
2812 // in bad state, reset the state upon service start.
2813 BatteryNotifier::getInstance().noteResetVideo();
2814 }
2815
addBatteryData(uint32_t params)2816 void MediaPlayerService::BatteryTracker::addBatteryData(uint32_t params)
2817 {
2818 Mutex::Autolock lock(mLock);
2819
2820 int32_t time = systemTime() / 1000000L;
2821
2822 // change audio output devices. This notification comes from AudioFlinger
2823 if ((params & kBatteryDataSpeakerOn)
2824 || (params & kBatteryDataOtherAudioDeviceOn)) {
2825
2826 int deviceOn[NUM_AUDIO_DEVICES];
2827 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2828 deviceOn[i] = 0;
2829 }
2830
2831 if ((params & kBatteryDataSpeakerOn)
2832 && (params & kBatteryDataOtherAudioDeviceOn)) {
2833 deviceOn[SPEAKER_AND_OTHER] = 1;
2834 } else if (params & kBatteryDataSpeakerOn) {
2835 deviceOn[SPEAKER] = 1;
2836 } else {
2837 deviceOn[OTHER_AUDIO_DEVICE] = 1;
2838 }
2839
2840 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2841 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
2842
2843 if (mBatteryAudio.refCount > 0) { // if playing audio
2844 if (!deviceOn[i]) {
2845 mBatteryAudio.lastTime[i] += time;
2846 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2847 mBatteryAudio.lastTime[i] = 0;
2848 } else {
2849 mBatteryAudio.lastTime[i] = 0 - time;
2850 }
2851 }
2852
2853 mBatteryAudio.deviceOn[i] = deviceOn[i];
2854 }
2855 }
2856 return;
2857 }
2858
2859 // an audio stream is started
2860 if (params & kBatteryDataAudioFlingerStart) {
2861 // record the start time only if currently no other audio
2862 // is being played
2863 if (mBatteryAudio.refCount == 0) {
2864 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2865 if (mBatteryAudio.deviceOn[i]) {
2866 mBatteryAudio.lastTime[i] -= time;
2867 }
2868 }
2869 }
2870
2871 mBatteryAudio.refCount ++;
2872 return;
2873
2874 } else if (params & kBatteryDataAudioFlingerStop) {
2875 if (mBatteryAudio.refCount <= 0) {
2876 ALOGW("Battery track warning: refCount is <= 0");
2877 return;
2878 }
2879
2880 // record the stop time only if currently this is the only
2881 // audio being played
2882 if (mBatteryAudio.refCount == 1) {
2883 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2884 if (mBatteryAudio.deviceOn[i]) {
2885 mBatteryAudio.lastTime[i] += time;
2886 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2887 mBatteryAudio.lastTime[i] = 0;
2888 }
2889 }
2890 }
2891
2892 mBatteryAudio.refCount --;
2893 return;
2894 }
2895
2896 uid_t uid = IPCThreadState::self()->getCallingUid();
2897 if (uid == AID_MEDIA) {
2898 return;
2899 }
2900 int index = mBatteryData.indexOfKey(uid);
2901
2902 if (index < 0) { // create a new entry for this UID
2903 BatteryUsageInfo info;
2904 info.audioTotalTime = 0;
2905 info.videoTotalTime = 0;
2906 info.audioLastTime = 0;
2907 info.videoLastTime = 0;
2908 info.refCount = 0;
2909
2910 if (mBatteryData.add(uid, info) == NO_MEMORY) {
2911 ALOGE("Battery track error: no memory for new app");
2912 return;
2913 }
2914 }
2915
2916 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
2917
2918 if (params & kBatteryDataCodecStarted) {
2919 if (params & kBatteryDataTrackAudio) {
2920 info.audioLastTime -= time;
2921 info.refCount ++;
2922 }
2923 if (params & kBatteryDataTrackVideo) {
2924 info.videoLastTime -= time;
2925 info.refCount ++;
2926 }
2927 } else {
2928 if (info.refCount == 0) {
2929 ALOGW("Battery track warning: refCount is already 0");
2930 return;
2931 } else if (info.refCount < 0) {
2932 ALOGE("Battery track error: refCount < 0");
2933 mBatteryData.removeItem(uid);
2934 return;
2935 }
2936
2937 if (params & kBatteryDataTrackAudio) {
2938 info.audioLastTime += time;
2939 info.refCount --;
2940 }
2941 if (params & kBatteryDataTrackVideo) {
2942 info.videoLastTime += time;
2943 info.refCount --;
2944 }
2945
2946 // no stream is being played by this UID
2947 if (info.refCount == 0) {
2948 info.audioTotalTime += info.audioLastTime;
2949 info.audioLastTime = 0;
2950 info.videoTotalTime += info.videoLastTime;
2951 info.videoLastTime = 0;
2952 }
2953 }
2954 }
2955
pullBatteryData(Parcel * reply)2956 status_t MediaPlayerService::BatteryTracker::pullBatteryData(Parcel* reply) {
2957 Mutex::Autolock lock(mLock);
2958
2959 // audio output devices usage
2960 int32_t time = systemTime() / 1000000L; //in ms
2961 int32_t totalTime;
2962
2963 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2964 totalTime = mBatteryAudio.totalTime[i];
2965
2966 if (mBatteryAudio.deviceOn[i]
2967 && (mBatteryAudio.lastTime[i] != 0)) {
2968 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
2969 totalTime += tmpTime;
2970 }
2971
2972 reply->writeInt32(totalTime);
2973 // reset the total time
2974 mBatteryAudio.totalTime[i] = 0;
2975 }
2976
2977 // codec usage
2978 BatteryUsageInfo info;
2979 int size = mBatteryData.size();
2980
2981 reply->writeInt32(size);
2982 int i = 0;
2983
2984 while (i < size) {
2985 info = mBatteryData.valueAt(i);
2986
2987 reply->writeInt32(mBatteryData.keyAt(i)); //UID
2988 reply->writeInt32(info.audioTotalTime);
2989 reply->writeInt32(info.videoTotalTime);
2990
2991 info.audioTotalTime = 0;
2992 info.videoTotalTime = 0;
2993
2994 // remove the UID entry where no stream is being played
2995 if (info.refCount <= 0) {
2996 mBatteryData.removeItemsAt(i);
2997 size --;
2998 i --;
2999 }
3000 i++;
3001 }
3002 return NO_ERROR;
3003 }
3004 } // namespace android
3005