blob: 7cda2fb2f8e1d447f83245670641f8ab1562c9a8 [file] [log] [blame]
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001/*
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>
Gloria Wang7cf180c2011-02-19 18:37:57 -080026#include <sys/time.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080027#include <dirent.h>
28#include <unistd.h>
29
30#include <string.h>
Mathias Agopian6f74b0c2009-06-03 17:32:49 -070031
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080032#include <cutils/atomic.h>
Nicolas Catania14d27472009-07-13 14:37:49 -070033#include <cutils/properties.h> // for property_get
Mathias Agopian6f74b0c2009-06-03 17:32:49 -070034
35#include <utils/misc.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080036
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -070037#include <android/hardware/media/omx/1.0/IOmx.h>
Marco Nelissena0c98412019-03-29 12:10:19 -070038#include <android/hardware/media/c2/1.0/IComponentStore.h>
Mathias Agopian75624082009-05-19 19:08:10 -070039#include <binder/IPCThreadState.h>
40#include <binder/IServiceManager.h>
41#include <binder/MemoryHeapBase.h>
42#include <binder/MemoryBase.h>
Mathias Agopianb1e7cd12013-02-14 17:11:27 -080043#include <gui/Surface.h>
Nicolas Catania1d187f12009-05-12 23:25:55 -070044#include <utils/Errors.h> // for status_t
45#include <utils/String8.h>
Marco Nelissen10dbb8e2009-09-20 10:42:13 -070046#include <utils/SystemClock.h>
Lajos Molnar06ad1522014-08-28 07:27:44 -070047#include <utils/Timers.h>
Nicolas Catania1d187f12009-05-12 23:25:55 -070048#include <utils/Vector.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080049
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -070050#include <codec2/hidl/client.h>
Marco Nelissen42057ce2019-09-23 12:15:57 -070051#include <datasource/HTTPBase.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080052#include <media/IMediaHTTPService.h>
Jeff Brown2013a542012-09-04 21:38:42 -070053#include <media/IRemoteDisplay.h>
54#include <media/IRemoteDisplayClient.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080055#include <media/MediaPlayerInterface.h>
56#include <media/mediarecorder.h>
57#include <media/MediaMetadataRetrieverInterface.h>
nikoa64c8c72009-07-20 15:07:26 -070058#include <media/Metadata.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080059#include <media/AudioTrack.h>
Dongwon Kangd91dc5a2017-10-10 00:07:09 -070060#include <media/stagefright/InterfaceUtils.h>
Wonsik Kim6f675772019-08-20 17:06:53 -070061#include <media/stagefright/MediaCodecConstants.h>
Lajos Molnar1381d4b2014-08-07 15:18:35 -070062#include <media/stagefright/MediaCodecList.h>
Eric Laurent9cb839a2011-09-27 09:48:56 -070063#include <media/stagefright/MediaErrors.h>
Marco Nelissen83b0fd92015-09-16 13:48:07 -070064#include <media/stagefright/Utils.h>
Marco Nelissen42057ce2019-09-23 12:15:57 -070065#include <media/stagefright/FoundationUtils.h>
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +010066#include <media/stagefright/foundation/ADebug.h>
Marco Nelissenf09611f2015-02-13 14:12:42 -080067#include <media/stagefright/foundation/ALooperRoster.h>
Chong Zhang181fd9b2017-02-16 15:53:03 -080068#include <media/stagefright/SurfaceUtils.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070069#include <mediautils/BatteryNotifier.h>
Andy Hunge9eb03e2020-04-04 14:08:23 -070070#include <mediautils/MemoryLeakTrackUtil.h>
Andy Hung53541292016-04-13 16:48:51 -070071#include <memunreachable/memunreachable.h>
Dima Zavin64760242011-05-11 14:15:23 -070072#include <system/audio.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070073
Gloria Wang7cf180c2011-02-19 18:37:57 -080074#include <private/android_filesystem_config.h>
75
James Dong559bf282012-03-28 10:29:14 -070076#include "ActivityManager.h"
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080077#include "MediaRecorderClient.h"
78#include "MediaPlayerService.h"
79#include "MetadataRetrieverClient.h"
John Grossman44a7e422012-06-21 17:29:24 -070080#include "MediaPlayerFactory.h"
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080081
Nicolas Catania14d27472009-07-13 14:37:49 -070082#include "TestPlayerStub.h"
Andreas Huberf9334412010-12-15 15:17:42 -080083#include "nuplayer/NuPlayerDriver.h"
Andreas Huber20111aa2009-07-14 16:56:47 -070084
Andreas Hubered3e3e02012-03-26 11:13:27 -070085
Wei Jia502c2f42017-07-13 17:47:56 -070086static const int kDumpLockRetries = 50;
87static const int kDumpLockSleepUs = 20000;
88
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070089namespace {
nikoa64c8c72009-07-20 15:07:26 -070090using android::media::Metadata;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070091using android::status_t;
92using android::OK;
93using android::BAD_VALUE;
94using android::NOT_ENOUGH_DATA;
95using android::Parcel;
Ivan Lozano8cf3a072017-08-09 09:01:33 -070096using android::media::VolumeShaper;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070097
98// Max number of entries in the filter.
99const int kMaxFilterSize = 64; // I pulled that out of thin air.
100
Andy Hungff874dc2016-04-11 16:49:09 -0700101const float kMaxRequiredSpeed = 8.0f; // for PCM tracks allow up to 8x speedup.
102
nikoa64c8c72009-07-20 15:07:26 -0700103// FIXME: Move all the metadata related function in the Metadata.cpp
nikod608a812009-07-16 16:39:53 -0700104
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700105
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.
127bool unmarshallFilter(const Parcel& p,
nikoa64c8c72009-07-20 15:07:26 -0700128 Metadata::Filter *filter,
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700129 status_t *status)
130{
Nicolas Catania48290382009-07-10 13:53:06 -0700131 int32_t val;
132 if (p.readInt32(&val) != OK)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700133 {
Steve Block29357bc2012-01-06 19:20:56 +0000134 ALOGE("Failed to read filter's length");
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700135 *status = NOT_ENOUGH_DATA;
136 return false;
137 }
138
Nicolas Catania48290382009-07-10 13:53:06 -0700139 if( val > kMaxFilterSize || val < 0)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700140 {
Steve Block29357bc2012-01-06 19:20:56 +0000141 ALOGE("Invalid filter len %d", val);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700142 *status = BAD_VALUE;
143 return false;
144 }
145
Nicolas Catania48290382009-07-10 13:53:06 -0700146 const size_t num = val;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700147
148 filter->clear();
Nicolas Catania48290382009-07-10 13:53:06 -0700149 filter->setCapacity(num);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700150
nikoa64c8c72009-07-20 15:07:26 -0700151 size_t size = num * sizeof(Metadata::Type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700152
Nicolas Catania48290382009-07-10 13:53:06 -0700153
154 if (p.dataAvail() < size)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700155 {
Andy Hung833b4752016-04-04 17:15:48 -0700156 ALOGE("Filter too short expected %zu but got %zu", size, p.dataAvail());
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700157 *status = NOT_ENOUGH_DATA;
158 return false;
159 }
160
nikoa64c8c72009-07-20 15:07:26 -0700161 const Metadata::Type *data =
162 static_cast<const Metadata::Type*>(p.readInplace(size));
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700163
Nicolas Catania48290382009-07-10 13:53:06 -0700164 if (NULL == data)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700165 {
Steve Block29357bc2012-01-06 19:20:56 +0000166 ALOGE("Filter had no data");
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700167 *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.
Nicolas Catania48290382009-07-10 13:53:06 -0700174 for (size_t i = 0; i < num; ++i)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700175 {
Nicolas Catania48290382009-07-10 13:53:06 -0700176 filter->add(*data);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700177 ++data;
178 }
179 *status = OK;
180 return true;
181}
182
Nicolas Catania48290382009-07-10 13:53:06 -0700183// @param filter Of metadata type.
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700184// @param val To be searched.
185// @return true if a match was found.
nikoa64c8c72009-07-20 15:07:26 -0700186bool findMetadata(const Metadata::Filter& filter, const int32_t val)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700187{
188 // Deal with empty and ANY right away
189 if (filter.isEmpty()) return false;
nikoa64c8c72009-07-20 15:07:26 -0700190 if (filter[0] == Metadata::kAny) return true;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700191
Nicolas Catania48290382009-07-10 13:53:06 -0700192 return filter.indexOf(val) >= 0;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700193}
194
195} // anonymous namespace
196
197
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700198namespace {
199using android::Parcel;
200using android::String16;
201
202// marshalling tag indicating flattened utf16 tags
203// keep in sync with frameworks/base/media/java/android/media/AudioAttributes.java
204const 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// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Hyejin Kim4f418f92014-09-05 15:50:03 +0900214// | source |
215// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700216// | 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.
227void 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();
Hyejin Kim4f418f92014-09-05 15:50:03 +0900231 attributes->source = (audio_source_t) parcel.readInt32();
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700232 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;
Sergio Giro1d3f4272016-06-28 18:24:52 +0100245 utf16_to_utf8(tags.string(), tagSize, attributes->tags,
246 sizeof(attributes->tags) / sizeof(attributes->tags[0]));
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700247 }
248 } else {
249 ALOGE("unmarshallAudioAttributes() received unflattened tags, ignoring tag values");
250 strcpy(attributes->tags, "");
251 }
252}
253} // anonymous namespace
254
255
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800256namespace android {
257
Marco Nelissenf09611f2015-02-13 14:12:42 -0800258extern ALooperRoster gLooperRoster;
259
260
Dave Burked681bbb2011-08-30 14:39:17 +0100261static bool checkPermission(const char* permissionString) {
Dave Burked681bbb2011-08-30 14:39:17 +0100262 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
263 bool ok = checkCallingPermission(String16(permissionString));
Steve Block29357bc2012-01-06 19:20:56 +0000264 if (!ok) ALOGE("Request requires %s", permissionString);
Dave Burked681bbb2011-08-30 14:39:17 +0100265 return ok;
266}
267
Wonsik Kim6f675772019-08-20 17:06:53 -0700268static 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
Wonsik Kimd579f3e2019-10-07 14:14:09 -0700424 result.append(" details: ");
425 result.append(caps->getDetails()->debugString(6).c_str());
426 result.append("\n");
Wonsik Kim6f675772019-08-20 17:06:53 -0700427 }
428 }
429 result.append("\n");
430 ::write(fd, result.string(), result.size());
431}
432
433
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800434// TODO: Find real cause of Audio/Video delay in PV framework and remove this workaround
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800435/* static */ int MediaPlayerService::AudioOutput::mMinBufferCount = 4;
436/* static */ bool MediaPlayerService::AudioOutput::mIsOnEmulator = false;
437
438void MediaPlayerService::instantiate() {
439 defaultServiceManager()->addService(
440 String16("media.player"), new MediaPlayerService());
441}
442
443MediaPlayerService::MediaPlayerService()
444{
Steve Block3856b092011-10-20 11:56:00 +0100445 ALOGV("MediaPlayerService created");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800446 mNextConnId = 1;
Gloria Wang9ee159b2011-02-24 14:51:45 -0800447
John Grossman44a7e422012-06-21 17:29:24 -0700448 MediaPlayerFactory::registerBuiltinFactories();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800449}
450
451MediaPlayerService::~MediaPlayerService()
452{
Steve Block3856b092011-10-20 11:56:00 +0100453 ALOGV("MediaPlayerService destroyed");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800454}
455
Svet Ganovbe71aa22015-04-28 12:06:02 -0700456sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(const String16 &opPackageName)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800457{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800458 pid_t pid = IPCThreadState::self()->getCallingPid();
Svet Ganovbe71aa22015-04-28 12:06:02 -0700459 sp<MediaRecorderClient> recorder = new MediaRecorderClient(this, pid, opPackageName);
Gloria Wangdac6a312009-10-29 15:46:37 -0700460 wp<MediaRecorderClient> w = recorder;
461 Mutex::Autolock lock(mLock);
462 mMediaRecorderClients.add(w);
Steve Block3856b092011-10-20 11:56:00 +0100463 ALOGV("Create new media recorder client from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800464 return recorder;
465}
466
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -0700467void MediaPlayerService::removeMediaRecorderClient(const wp<MediaRecorderClient>& client)
Gloria Wangdac6a312009-10-29 15:46:37 -0700468{
469 Mutex::Autolock lock(mLock);
470 mMediaRecorderClients.remove(client);
Steve Block3856b092011-10-20 11:56:00 +0100471 ALOGV("Delete media recorder client");
Gloria Wangdac6a312009-10-29 15:46:37 -0700472}
473
Glenn Kastenf37971f2012-02-03 11:06:53 -0800474sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800475{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800476 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800477 sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
Steve Block3856b092011-10-20 11:56:00 +0100478 ALOGV("Create new media retriever from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800479 return retriever;
480}
481
Glenn Kastenf37971f2012-02-03 11:06:53 -0800482sp<IMediaPlayer> MediaPlayerService::create(const sp<IMediaPlayerClient>& client,
jiabin375283d2020-08-21 18:14:43 -0700483 audio_session_t audioSessionId, std::string opPackageName)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800484{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800485 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800486 int32_t connId = android_atomic_inc(&mNextConnId);
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700487
488 sp<Client> c = new Client(
489 this, pid, connId, client, audioSessionId,
jiabin375283d2020-08-21 18:14:43 -0700490 IPCThreadState::self()->getCallingUid(), opPackageName);
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700491
Steve Block3856b092011-10-20 11:56:00 +0100492 ALOGV("Create new client(%d) from pid %d, uid %d, ", connId, pid,
Dave Burked681bbb2011-08-30 14:39:17 +0100493 IPCThreadState::self()->getCallingUid());
494
495 wp<Client> w = c;
496 {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800497 Mutex::Autolock lock(mLock);
498 mClients.add(w);
499 }
Andreas Hubere2b10282010-11-23 11:41:34 -0800500 return c;
501}
502
Lajos Molnar1381d4b2014-08-07 15:18:35 -0700503sp<IMediaCodecList> MediaPlayerService::getCodecList() const {
504 return MediaCodecList::getLocalInstance();
505}
506
Jeff Brown2013a542012-09-04 21:38:42 -0700507sp<IRemoteDisplay> MediaPlayerService::listenForRemoteDisplay(
Chong Zhangd0a98fa2017-09-14 17:43:10 -0700508 const String16 &/*opPackageName*/,
509 const sp<IRemoteDisplayClient>& /*client*/,
510 const String8& /*iface*/) {
511 ALOGE("listenForRemoteDisplay is no longer supported!");
Jeff Brownaba33d52012-09-07 17:38:58 -0700512
Chong Zhangd0a98fa2017-09-14 17:43:10 -0700513 return NULL;
Jeff Brown2013a542012-09-04 21:38:42 -0700514}
515
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800516status_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",
Eric Laurentdb354e52012-03-05 17:27:11 -0800527 mMsecsPerFrame, (mTrack != 0) ? mTrack->latency() : -1);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800528 result.append(buffer);
Eric Laurent2beeb502010-07-16 07:43:46 -0700529 snprintf(buffer, 255, " aux effect id(%d), send level (%f)\n",
530 mAuxEffectId, mSendLevel);
531 result.append(buffer);
532
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800533 ::write(fd, result.string(), result.size());
534 if (mTrack != 0) {
535 mTrack->dump(fd, args);
536 }
537 return NO_ERROR;
538}
539
Lajos Molnar6d339f12015-04-17 16:15:53 -0700540status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800541{
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);
Wei Jia502c2f42017-07-13 17:47:56 -0700549
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);
Andreas Hubera0b1d4b2011-06-07 15:52:25 -0700559 }
Wei Jia502c2f42017-07-13 17:47:56 -0700560
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);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800575 }
576 write(fd, "\n", 1);
577 return NO_ERROR;
578}
579
Marco Nelissenf09611f2015-02-13 14:12:42 -0800580/**
581 * The only arguments this understands right now are -c, -von and -voff,
582 * which are parsed by ALooperRoster::dump()
583 */
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800584status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
585{
586 const size_t SIZE = 256;
587 char buffer[SIZE];
588 String8 result;
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530589 SortedVector< sp<Client> > clients; //to serialise the mutex unlock & client destruction.
590 SortedVector< sp<MediaRecorderClient> > mediaRecorderClients;
591
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800592 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
Wonsik Kim6f675772019-08-20 17:06:53 -0700593 snprintf(buffer, SIZE - 1, "Permission Denial: "
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800594 "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);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530603 clients.add(c);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800604 }
James Dongb9141222010-07-08 11:16:11 -0700605 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();
James Donge579e282011-10-18 22:29:20 -0700610 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);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530616 mediaRecorderClients.add(c);
James Donge579e282011-10-18 22:29:20 -0700617 }
James Dongb9141222010-07-08 11:16:11 -0700618 }
Gloria Wangdac6a312009-10-29 15:46:37 -0700619 }
620
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800621 result.append(" Files opened and/or mapped:\n");
Wonsik Kim6f675772019-08-20 17:06:53 -0700622 snprintf(buffer, SIZE - 1, "/proc/%d/maps", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800623 FILE *f = fopen(buffer, "r");
624 if (f) {
625 while (!feof(f)) {
Wonsik Kim6f675772019-08-20 17:06:53 -0700626 fgets(buffer, SIZE - 1, f);
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700627 if (strstr(buffer, " /storage/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800628 strstr(buffer, " /system/sounds/") ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700629 strstr(buffer, " /data/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800630 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
Wonsik Kim6f675772019-08-20 17:06:53 -0700642 snprintf(buffer, SIZE - 1, "/proc/%d/fd", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800643 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,"..")) {
Wonsik Kim6f675772019-08-20 17:06:53 -0700648 snprintf(buffer, SIZE - 1, "/proc/%d/fd/%s", getpid(), ent->d_name);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800649 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 }
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700663 if (strstr(linkto, "/storage/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800664 strstr(linkto, "/system/sounds/") == linkto ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700665 strstr(linkto, "/data/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800666 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
Marco Nelissenf09611f2015-02-13 14:12:42 -0800689 gLooperRoster.dump(fd, args);
690
Wonsik Kimd579f3e2019-10-07 14:14:09 -0700691 sp<IMediaCodecList> codecList = getCodecList();
692 dumpCodecDetails(fd, codecList, true /* decoders */);
693 dumpCodecDetails(fd, codecList, false /* !decoders */);
694
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800695 bool dumpMem = false;
Andy Hung53541292016-04-13 16:48:51 -0700696 bool unreachableMemory = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800697 for (size_t i = 0; i < args.size(); i++) {
698 if (args[i] == String16("-m")) {
699 dumpMem = true;
Andy Hung53541292016-04-13 16:48:51 -0700700 } else if (args[i] == String16("--unreachable")) {
701 unreachableMemory = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800702 }
703 }
704 if (dumpMem) {
Andy Hung07b745e2016-05-23 16:21:07 -0700705 result.append("\nDumping memory:\n");
706 std::string s = dumpMemoryAddresses(100 /* limit */);
707 result.append(s.c_str(), s.size());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800708 }
Andy Hung53541292016-04-13 16:48:51 -0700709 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 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800715 }
716 write(fd, result.string(), result.size());
Wonsik Kim6f675772019-08-20 17:06:53 -0700717
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800718 return NO_ERROR;
719}
720
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -0700721void MediaPlayerService::removeClient(const wp<Client>& client)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800722{
723 Mutex::Autolock lock(mLock);
724 mClients.remove(client);
725}
726
Robert Shihee0a0e32016-08-16 16:50:54 -0700727bool MediaPlayerService::hasClient(wp<Client> client)
728{
729 Mutex::Autolock lock(mLock);
730 return mClients.indexOf(client) != NAME_NOT_FOUND;
731}
732
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700733MediaPlayerService::Client::Client(
734 const sp<MediaPlayerService>& service, pid_t pid,
735 int32_t connId, const sp<IMediaPlayerClient>& client,
jiabin375283d2020-08-21 18:14:43 -0700736 audio_session_t audioSessionId, uid_t uid, const std::string& opPackageName)
737 : mOpPackageName(opPackageName)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800738{
Steve Block3856b092011-10-20 11:56:00 +0100739 ALOGV("Client(%d) constructor", connId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800740 mPid = pid;
741 mConnId = connId;
742 mService = service;
743 mClient = client;
744 mLoop = false;
745 mStatus = NO_INIT;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700746 mAudioSessionId = audioSessionId;
Andy Hung1afd0982016-11-08 16:13:44 -0800747 mUid = uid;
John Grossmanc795b642012-02-22 15:38:35 -0800748 mRetransmitEndpointValid = false;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700749 mAudioAttributes = NULL;
Pawin Vongmasa082e4f72017-12-17 02:31:18 -0800750 mListener = new Listener(this);
Eric Laurenta514bdb2010-06-21 09:27:30 -0700751
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800752#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000753 ALOGD("create Antagonizer");
Pawin Vongmasa082e4f72017-12-17 02:31:18 -0800754 mAntagonizer = new Antagonizer(mListener);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800755#endif
756}
757
758MediaPlayerService::Client::~Client()
759{
Steve Block3856b092011-10-20 11:56:00 +0100760 ALOGV("Client(%d) destructor pid = %d", mConnId, mPid);
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700761 mAudioOutput.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800762 wp<Client> client(this);
763 disconnect();
764 mService->removeClient(client);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700765 if (mAudioAttributes != NULL) {
766 free(mAudioAttributes);
767 }
jiabin156c6872017-10-06 09:47:15 -0700768 mAudioDeviceUpdatedListener.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800769}
770
771void MediaPlayerService::Client::disconnect()
772{
Steve Block3856b092011-10-20 11:56:00 +0100773 ALOGV("disconnect(%d) from pid %d", mConnId, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800774 // 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;
beanzdcfefde2012-11-05 09:51:43 +0800780 mClient.clear();
Wei Jia502c2f42017-07-13 17:47:56 -0700781 mPlayer.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800782 }
Andreas Huber20111aa2009-07-14 16:56:47 -0700783
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800784 // 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) {
Pawin Vongmasa082e4f72017-12-17 02:31:18 -0800788 p->setNotifyCallback(0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800789#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000790 ALOGD("kill Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800791 mAntagonizer->kill();
792#endif
793 p->reset();
794 }
795
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700796 {
797 Mutex::Autolock l(mLock);
798 disconnectNativeWindow_l();
799 }
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700800
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800801 IPCThreadState::self()->flushCommands();
802}
803
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800804sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
805{
806 // determine if we have the right player type
Wei Jia502c2f42017-07-13 17:47:56 -0700807 sp<MediaPlayerBase> p = getPlayer();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800808 if ((p != NULL) && (p->playerType() != playerType)) {
Steve Block3856b092011-10-20 11:56:00 +0100809 ALOGV("delete player");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800810 p.clear();
811 }
812 if (p == NULL) {
Pawin Vongmasa082e4f72017-12-17 02:31:18 -0800813 p = MediaPlayerFactory::createPlayer(playerType, mListener, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800814 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700815
Jason Simmonsdb29e522011-08-12 13:46:55 -0700816 if (p != NULL) {
Andy Hung1afd0982016-11-08 16:13:44 -0800817 p->setUID(mUid);
Jason Simmonsdb29e522011-08-12 13:46:55 -0700818 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700819
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800820 return p;
821}
822
jiabin156c6872017-10-06 09:47:15 -0700823void 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
John Grossmanc795b642012-02-22 15:38:35 -0800834sp<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
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700845 std::vector<DeathNotifier> deathNotifiers;
846
847 // Listen to death of media.extractor service
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700848 sp<IServiceManager> sm = defaultServiceManager();
849 sp<IBinder> binder = sm->getService(String16("media.extractor"));
Marco Nelissen1b5a7ee2016-09-30 13:54:30 -0700850 if (binder == NULL) {
851 ALOGE("extractor service not available");
852 return NULL;
853 }
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700854 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 });
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700865
Marco Nelissena0c98412019-03-29 12:10:19 -0700866 {
867 using ::android::hidl::base::V1_0::IBase;
868
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700869 // Listen to death of OMX service
Marco Nelissena0c98412019-03-29 12:10:19 -0700870 {
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700871 sp<IBase> base = ::android::hardware::media::omx::V1_0::
872 IOmx::getService();
873 if (base == nullptr) {
Marco Nelissena0c98412019-03-29 12:10:19 -0700874 ALOGD("OMX service is not available");
875 } else {
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700876 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 });
Marco Nelissena0c98412019-03-29 12:10:19 -0700889 }
890 }
891
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700892 // Listen to death of Codec2 services
Marco Nelissena0c98412019-03-29 12:10:19 -0700893 {
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700894 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 });
Marco Nelissene4da6c62019-04-01 15:01:41 -0700914 }
Marco Nelissena0c98412019-03-29 12:10:19 -0700915 }
Marco Nelissen1b5a7ee2016-09-30 13:54:30 -0700916 }
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700917
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700918 Mutex::Autolock lock(mLock);
919
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700920 mDeathNotifiers.clear();
921 mDeathNotifiers.swap(deathNotifiers);
jiabin156c6872017-10-06 09:47:15 -0700922 mAudioDeviceUpdatedListener = new AudioDeviceUpdatedNotifier(p);
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700923
John Grossmanc795b642012-02-22 15:38:35 -0800924 if (!p->hardwareOutput()) {
Marco Nelissend457c972014-02-11 08:47:07 -0800925 mAudioOutput = new AudioOutput(mAudioSessionId, IPCThreadState::self()->getCallingUid(),
jiabin375283d2020-08-21 18:14:43 -0700926 mPid, mAudioAttributes, mAudioDeviceUpdatedListener, mOpPackageName);
John Grossmanc795b642012-02-22 15:38:35 -0800927 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
928 }
929
930 return p;
931}
932
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700933status_t MediaPlayerService::Client::setDataSource_post(
John Grossmanc795b642012-02-22 15:38:35 -0800934 const sp<MediaPlayerBase>& p,
935 status_t status)
936{
937 ALOGV(" setDataSource");
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700938 if (status != OK) {
939 ALOGE(" error: %d", status);
940 return status;
John Grossmanc795b642012-02-22 15:38:35 -0800941 }
942
943 // Set the re-transmission endpoint if one was chosen.
944 if (mRetransmitEndpointValid) {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700945 status = p->setRetransmitEndpoint(&mRetransmitEndpoint);
946 if (status != NO_ERROR) {
947 ALOGE("setRetransmitEndpoint error: %d", status);
John Grossmanc795b642012-02-22 15:38:35 -0800948 }
949 }
950
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700951 if (status == OK) {
952 Mutex::Autolock lock(mLock);
John Grossmanc795b642012-02-22 15:38:35 -0800953 mPlayer = p;
954 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700955 return status;
John Grossmanc795b642012-02-22 15:38:35 -0800956}
957
Andreas Huber2db84552010-01-28 11:19:57 -0800958status_t MediaPlayerService::Client::setDataSource(
Andreas Huber1b86fe02014-01-29 11:13:26 -0800959 const sp<IMediaHTTPService> &httpService,
960 const char *url,
961 const KeyedVector<String8, String8> *headers)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800962{
Steve Block3856b092011-10-20 11:56:00 +0100963 ALOGV("setDataSource(%s)", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800964 if (url == NULL)
965 return UNKNOWN_ERROR;
966
Dave Burked681bbb2011-08-30 14:39:17 +0100967 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
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800975 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 {
Steve Block29357bc2012-01-06 19:20:56 +0000983 ALOGE("Couldn't open fd for %s", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800984 return UNKNOWN_ERROR;
985 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700986 status_t status = setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800987 close(fd);
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700988 return mStatus = status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800989 } else {
John Grossman44a7e422012-06-21 17:29:24 -0700990 player_type playerType = MediaPlayerFactory::getPlayerType(this, url);
John Grossmanc795b642012-02-22 15:38:35 -0800991 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
992 if (p == NULL) {
993 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800994 }
995
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700996 return mStatus =
997 setDataSource_post(
998 p, p->setDataSource(httpService, url, headers));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800999 }
1000}
1001
1002status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
1003{
Marco Nelissen83b0fd92015-09-16 13:48:07 -07001004 ALOGV("setDataSource fd=%d (%s), offset=%lld, length=%lld",
1005 fd, nameForFd(fd).c_str(), (long long) offset, (long long) length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001006 struct stat sb;
1007 int ret = fstat(fd, &sb);
1008 if (ret != 0) {
Steve Block29357bc2012-01-06 19:20:56 +00001009 ALOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001010 return UNKNOWN_ERROR;
1011 }
1012
Andy Hung833b4752016-04-04 17:15:48 -07001013 ALOGV("st_dev = %llu", static_cast<unsigned long long>(sb.st_dev));
Steve Block3856b092011-10-20 11:56:00 +01001014 ALOGV("st_mode = %u", sb.st_mode);
Mark Salyzyn77342f72014-06-18 16:31:32 -07001015 ALOGV("st_uid = %lu", static_cast<unsigned long>(sb.st_uid));
1016 ALOGV("st_gid = %lu", static_cast<unsigned long>(sb.st_gid));
Andy Hung833b4752016-04-04 17:15:48 -07001017 ALOGV("st_size = %llu", static_cast<unsigned long long>(sb.st_size));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001018
1019 if (offset >= sb.st_size) {
Steve Block29357bc2012-01-06 19:20:56 +00001020 ALOGE("offset error");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001021 return UNKNOWN_ERROR;
1022 }
1023 if (offset + length > sb.st_size) {
1024 length = sb.st_size - offset;
Andy Hung833b4752016-04-04 17:15:48 -07001025 ALOGV("calculated length = %lld", (long long)length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001026 }
1027
John Grossman44a7e422012-06-21 17:29:24 -07001028 player_type playerType = MediaPlayerFactory::getPlayerType(this,
1029 fd,
1030 offset,
1031 length);
John Grossmanc795b642012-02-22 15:38:35 -08001032 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
1033 if (p == NULL) {
1034 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001035 }
1036
1037 // now set data source
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001038 return mStatus = setDataSource_post(p, p->setDataSource(fd, offset, length));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001039}
1040
Andreas Hubere2b10282010-11-23 11:41:34 -08001041status_t MediaPlayerService::Client::setDataSource(
1042 const sp<IStreamSource> &source) {
1043 // create the right type of player
John Grossman44a7e422012-06-21 17:29:24 -07001044 player_type playerType = MediaPlayerFactory::getPlayerType(this, source);
John Grossmanc795b642012-02-22 15:38:35 -08001045 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
Andreas Hubere2b10282010-11-23 11:41:34 -08001046 if (p == NULL) {
1047 return NO_INIT;
1048 }
1049
Andreas Hubere2b10282010-11-23 11:41:34 -08001050 // now set data source
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001051 return mStatus = setDataSource_post(p, p->setDataSource(source));
Andreas Hubere2b10282010-11-23 11:41:34 -08001052}
1053
Chris Watkins99f31602015-03-20 13:06:33 -07001054status_t MediaPlayerService::Client::setDataSource(
1055 const sp<IDataSource> &source) {
Dongwon Kangd91dc5a2017-10-10 00:07:09 -07001056 sp<DataSource> dataSource = CreateDataSourceFromIDataSource(source);
Chris Watkins99f31602015-03-20 13:06:33 -07001057 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
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001063 return mStatus = setDataSource_post(p, p->setDataSource(dataSource));
Chris Watkins99f31602015-03-20 13:06:33 -07001064}
1065
Byeongjo Park33209352019-01-24 20:31:19 +09001066status_t MediaPlayerService::Client::setDataSource(
1067 const String8& rtpParams) {
1068 player_type playerType = NU_PLAYER;
1069 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
1070 if (p == NULL) {
1071 return NO_INIT;
1072 }
1073 // now set data source
1074 return mStatus = setDataSource_post(p, p->setDataSource(rtpParams));
1075}
1076
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001077void MediaPlayerService::Client::disconnectNativeWindow_l() {
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001078 if (mConnectedWindow != NULL) {
Chong Zhang181fd9b2017-02-16 15:53:03 -08001079 status_t err = nativeWindowDisconnect(
1080 mConnectedWindow.get(), "disconnectNativeWindow");
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001081
1082 if (err != OK) {
Chong Zhang181fd9b2017-02-16 15:53:03 -08001083 ALOGW("nativeWindowDisconnect returned an error: %s (%d)",
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001084 strerror(-err), err);
1085 }
1086 }
1087 mConnectedWindow.clear();
1088}
1089
Glenn Kasten11731182011-02-08 17:26:17 -08001090status_t MediaPlayerService::Client::setVideoSurfaceTexture(
Andy McFadden484566c2012-12-18 09:46:54 -08001091 const sp<IGraphicBufferProducer>& bufferProducer)
Glenn Kasten11731182011-02-08 17:26:17 -08001092{
Andy McFadden484566c2012-12-18 09:46:54 -08001093 ALOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, bufferProducer.get());
Glenn Kasten11731182011-02-08 17:26:17 -08001094 sp<MediaPlayerBase> p = getPlayer();
1095 if (p == 0) return UNKNOWN_ERROR;
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001096
Marco Nelissenf8880202014-11-14 07:58:25 -08001097 sp<IBinder> binder(IInterface::asBinder(bufferProducer));
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001098 if (mConnectedWindowBinder == binder) {
1099 return OK;
1100 }
1101
1102 sp<ANativeWindow> anw;
Andy McFadden484566c2012-12-18 09:46:54 -08001103 if (bufferProducer != NULL) {
Marco Nelissenee08f7e2013-09-16 13:30:01 -07001104 anw = new Surface(bufferProducer, true /* controlledByApp */);
Chong Zhang181fd9b2017-02-16 15:53:03 -08001105 status_t err = nativeWindowConnect(anw.get(), "setVideoSurfaceTexture");
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001106
1107 if (err != OK) {
Steve Block29357bc2012-01-06 19:20:56 +00001108 ALOGE("setVideoSurfaceTexture failed: %d", err);
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001109 // Note that we must do the reset before disconnecting from the ANW.
1110 // Otherwise queue/dequeue calls could be made on the disconnected
1111 // ANW, which may result in errors.
1112 reset();
1113
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001114 Mutex::Autolock lock(mLock);
1115 disconnectNativeWindow_l();
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001116
1117 return err;
1118 }
1119 }
1120
Andy McFadden484566c2012-12-18 09:46:54 -08001121 // Note that we must set the player's new GraphicBufferProducer before
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001122 // disconnecting the old one. Otherwise queue/dequeue calls could be made
1123 // on the disconnected ANW, which may result in errors.
Andy McFadden484566c2012-12-18 09:46:54 -08001124 status_t err = p->setVideoSurfaceTexture(bufferProducer);
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001125
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001126 mLock.lock();
1127 disconnectNativeWindow_l();
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001128
1129 if (err == OK) {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001130 mConnectedWindow = anw;
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001131 mConnectedWindowBinder = binder;
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001132 mLock.unlock();
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001133 } else {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001134 mLock.unlock();
1135 status_t err = nativeWindowDisconnect(
1136 anw.get(), "disconnectNativeWindow");
1137
1138 if (err != OK) {
1139 ALOGW("nativeWindowDisconnect returned an error: %s (%d)",
1140 strerror(-err), err);
1141 }
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001142 }
1143
1144 return err;
Glenn Kasten11731182011-02-08 17:26:17 -08001145}
1146
Nicolas Catania1d187f12009-05-12 23:25:55 -07001147status_t MediaPlayerService::Client::invoke(const Parcel& request,
1148 Parcel *reply)
1149{
1150 sp<MediaPlayerBase> p = getPlayer();
1151 if (p == NULL) return UNKNOWN_ERROR;
1152 return p->invoke(request, reply);
1153}
1154
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001155// This call doesn't need to access the native player.
1156status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
1157{
1158 status_t status;
nikoa64c8c72009-07-20 15:07:26 -07001159 media::Metadata::Filter allow, drop;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001160
Nicolas Catania48290382009-07-10 13:53:06 -07001161 if (unmarshallFilter(filter, &allow, &status) &&
1162 unmarshallFilter(filter, &drop, &status)) {
1163 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001164
1165 mMetadataAllow = allow;
1166 mMetadataDrop = drop;
1167 }
1168 return status;
1169}
1170
Nicolas Catania48290382009-07-10 13:53:06 -07001171status_t MediaPlayerService::Client::getMetadata(
Mark Salyzyn77342f72014-06-18 16:31:32 -07001172 bool update_only, bool /*apply_filter*/, Parcel *reply)
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001173{
nikoa64c8c72009-07-20 15:07:26 -07001174 sp<MediaPlayerBase> player = getPlayer();
1175 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania48290382009-07-10 13:53:06 -07001176
nikod608a812009-07-16 16:39:53 -07001177 status_t status;
1178 // Placeholder for the return code, updated by the caller.
1179 reply->writeInt32(-1);
1180
nikoa64c8c72009-07-20 15:07:26 -07001181 media::Metadata::Filter ids;
Nicolas Catania48290382009-07-10 13:53:06 -07001182
1183 // We don't block notifications while we fetch the data. We clear
1184 // mMetadataUpdated first so we don't lose notifications happening
1185 // during the rest of this call.
1186 {
1187 Mutex::Autolock lock(mLock);
1188 if (update_only) {
nikod608a812009-07-16 16:39:53 -07001189 ids = mMetadataUpdated;
Nicolas Catania48290382009-07-10 13:53:06 -07001190 }
1191 mMetadataUpdated.clear();
1192 }
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001193
nikoa64c8c72009-07-20 15:07:26 -07001194 media::Metadata metadata(reply);
Nicolas Catania48290382009-07-10 13:53:06 -07001195
nikoa64c8c72009-07-20 15:07:26 -07001196 metadata.appendHeader();
1197 status = player->getMetadata(ids, reply);
nikod608a812009-07-16 16:39:53 -07001198
1199 if (status != OK) {
nikoa64c8c72009-07-20 15:07:26 -07001200 metadata.resetParcel();
Steve Block29357bc2012-01-06 19:20:56 +00001201 ALOGE("getMetadata failed %d", status);
nikod608a812009-07-16 16:39:53 -07001202 return status;
1203 }
1204
1205 // FIXME: Implement filtering on the result. Not critical since
1206 // filtering takes place on the update notifications already. This
1207 // would be when all the metadata are fetch and a filter is set.
1208
nikod608a812009-07-16 16:39:53 -07001209 // Everything is fine, update the metadata length.
nikoa64c8c72009-07-20 15:07:26 -07001210 metadata.updateLength();
nikod608a812009-07-16 16:39:53 -07001211 return OK;
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001212}
1213
Wei Jiad399e7e2016-10-26 15:49:11 -07001214status_t MediaPlayerService::Client::setBufferingSettings(
1215 const BufferingSettings& buffering)
1216{
Wei Jiadc6f3402017-01-09 15:04:18 -08001217 ALOGV("[%d] setBufferingSettings{%s}",
1218 mConnId, buffering.toString().string());
Wei Jiad399e7e2016-10-26 15:49:11 -07001219 sp<MediaPlayerBase> p = getPlayer();
1220 if (p == 0) return UNKNOWN_ERROR;
1221 return p->setBufferingSettings(buffering);
1222}
1223
Wei Jia9bb38032017-03-23 18:00:38 -07001224status_t MediaPlayerService::Client::getBufferingSettings(
Wei Jiad399e7e2016-10-26 15:49:11 -07001225 BufferingSettings* buffering /* nonnull */)
1226{
1227 sp<MediaPlayerBase> p = getPlayer();
1228 // TODO: create mPlayer on demand.
1229 if (p == 0) return UNKNOWN_ERROR;
Wei Jia9bb38032017-03-23 18:00:38 -07001230 status_t ret = p->getBufferingSettings(buffering);
Wei Jiad399e7e2016-10-26 15:49:11 -07001231 if (ret == NO_ERROR) {
Wei Jia9bb38032017-03-23 18:00:38 -07001232 ALOGV("[%d] getBufferingSettings{%s}",
Wei Jiadc6f3402017-01-09 15:04:18 -08001233 mConnId, buffering->toString().string());
Wei Jiad399e7e2016-10-26 15:49:11 -07001234 } else {
Wei Jia9bb38032017-03-23 18:00:38 -07001235 ALOGE("[%d] getBufferingSettings returned %d", mConnId, ret);
Wei Jiad399e7e2016-10-26 15:49:11 -07001236 }
1237 return ret;
1238}
1239
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001240status_t MediaPlayerService::Client::prepareAsync()
1241{
Steve Block3856b092011-10-20 11:56:00 +01001242 ALOGV("[%d] prepareAsync", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001243 sp<MediaPlayerBase> p = getPlayer();
1244 if (p == 0) return UNKNOWN_ERROR;
1245 status_t ret = p->prepareAsync();
1246#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +00001247 ALOGD("start Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001248 if (ret == NO_ERROR) mAntagonizer->start();
1249#endif
1250 return ret;
1251}
1252
1253status_t MediaPlayerService::Client::start()
1254{
Steve Block3856b092011-10-20 11:56:00 +01001255 ALOGV("[%d] start", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001256 sp<MediaPlayerBase> p = getPlayer();
1257 if (p == 0) return UNKNOWN_ERROR;
1258 p->setLooping(mLoop);
1259 return p->start();
1260}
1261
1262status_t MediaPlayerService::Client::stop()
1263{
Steve Block3856b092011-10-20 11:56:00 +01001264 ALOGV("[%d] stop", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001265 sp<MediaPlayerBase> p = getPlayer();
1266 if (p == 0) return UNKNOWN_ERROR;
1267 return p->stop();
1268}
1269
1270status_t MediaPlayerService::Client::pause()
1271{
Steve Block3856b092011-10-20 11:56:00 +01001272 ALOGV("[%d] pause", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001273 sp<MediaPlayerBase> p = getPlayer();
1274 if (p == 0) return UNKNOWN_ERROR;
1275 return p->pause();
1276}
1277
1278status_t MediaPlayerService::Client::isPlaying(bool* state)
1279{
1280 *state = false;
1281 sp<MediaPlayerBase> p = getPlayer();
1282 if (p == 0) return UNKNOWN_ERROR;
1283 *state = p->isPlaying();
Steve Block3856b092011-10-20 11:56:00 +01001284 ALOGV("[%d] isPlaying: %d", mConnId, *state);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001285 return NO_ERROR;
1286}
1287
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001288status_t MediaPlayerService::Client::setPlaybackSettings(const AudioPlaybackRate& rate)
Wei Jia98160162015-02-04 17:01:11 -08001289{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001290 ALOGV("[%d] setPlaybackSettings(%f, %f, %d, %d)",
1291 mConnId, rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Wei Jia98160162015-02-04 17:01:11 -08001292 sp<MediaPlayerBase> p = getPlayer();
1293 if (p == 0) return UNKNOWN_ERROR;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001294 return p->setPlaybackSettings(rate);
1295}
1296
1297status_t MediaPlayerService::Client::getPlaybackSettings(AudioPlaybackRate* rate /* nonnull */)
1298{
1299 sp<MediaPlayerBase> p = getPlayer();
1300 if (p == 0) return UNKNOWN_ERROR;
1301 status_t ret = p->getPlaybackSettings(rate);
1302 if (ret == NO_ERROR) {
1303 ALOGV("[%d] getPlaybackSettings(%f, %f, %d, %d)",
1304 mConnId, rate->mSpeed, rate->mPitch, rate->mFallbackMode, rate->mStretchMode);
1305 } else {
1306 ALOGV("[%d] getPlaybackSettings returned %d", mConnId, ret);
1307 }
1308 return ret;
1309}
1310
1311status_t MediaPlayerService::Client::setSyncSettings(
1312 const AVSyncSettings& sync, float videoFpsHint)
1313{
1314 ALOGV("[%d] setSyncSettings(%u, %u, %f, %f)",
1315 mConnId, sync.mSource, sync.mAudioAdjustMode, sync.mTolerance, videoFpsHint);
1316 sp<MediaPlayerBase> p = getPlayer();
1317 if (p == 0) return UNKNOWN_ERROR;
1318 return p->setSyncSettings(sync, videoFpsHint);
1319}
1320
1321status_t MediaPlayerService::Client::getSyncSettings(
1322 AVSyncSettings* sync /* nonnull */, float* videoFps /* nonnull */)
1323{
1324 sp<MediaPlayerBase> p = getPlayer();
1325 if (p == 0) return UNKNOWN_ERROR;
1326 status_t ret = p->getSyncSettings(sync, videoFps);
1327 if (ret == NO_ERROR) {
1328 ALOGV("[%d] getSyncSettings(%u, %u, %f, %f)",
1329 mConnId, sync->mSource, sync->mAudioAdjustMode, sync->mTolerance, *videoFps);
1330 } else {
1331 ALOGV("[%d] getSyncSettings returned %d", mConnId, ret);
1332 }
1333 return ret;
Wei Jia98160162015-02-04 17:01:11 -08001334}
1335
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001336status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
1337{
Steve Block3856b092011-10-20 11:56:00 +01001338 ALOGV("getCurrentPosition");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001339 sp<MediaPlayerBase> p = getPlayer();
1340 if (p == 0) return UNKNOWN_ERROR;
1341 status_t ret = p->getCurrentPosition(msec);
1342 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001343 ALOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001344 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001345 ALOGE("getCurrentPosition returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001346 }
1347 return ret;
1348}
1349
1350status_t MediaPlayerService::Client::getDuration(int *msec)
1351{
Steve Block3856b092011-10-20 11:56:00 +01001352 ALOGV("getDuration");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001353 sp<MediaPlayerBase> p = getPlayer();
1354 if (p == 0) return UNKNOWN_ERROR;
1355 status_t ret = p->getDuration(msec);
1356 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001357 ALOGV("[%d] getDuration = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001358 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001359 ALOGE("getDuration returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001360 }
1361 return ret;
1362}
1363
Marco Nelissen6b74d672012-02-28 16:07:44 -08001364status_t MediaPlayerService::Client::setNextPlayer(const sp<IMediaPlayer>& player) {
1365 ALOGV("setNextPlayer");
1366 Mutex::Autolock l(mLock);
1367 sp<Client> c = static_cast<Client*>(player.get());
Wei Jia28284122016-08-30 13:49:06 -07001368 if (c != NULL && !mService->hasClient(c)) {
Robert Shihee0a0e32016-08-16 16:50:54 -07001369 return BAD_VALUE;
1370 }
1371
Marco Nelissen6b74d672012-02-28 16:07:44 -08001372 mNextClient = c;
John Grossman5f7e55e2012-08-24 14:47:25 -07001373
1374 if (c != NULL) {
1375 if (mAudioOutput != NULL) {
1376 mAudioOutput->setNextOutput(c->mAudioOutput);
1377 } else if ((mPlayer != NULL) && !mPlayer->hardwareOutput()) {
1378 ALOGE("no current audio output");
1379 }
1380
1381 if ((mPlayer != NULL) && (mNextClient->getPlayer() != NULL)) {
1382 mPlayer->setNextPlayer(mNextClient->getPlayer());
1383 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001384 }
John Grossman5f7e55e2012-08-24 14:47:25 -07001385
Marco Nelissen6b74d672012-02-28 16:07:44 -08001386 return OK;
1387}
1388
Andy Hung9fc8b5c2017-01-24 13:36:48 -08001389VolumeShaper::Status MediaPlayerService::Client::applyVolumeShaper(
1390 const sp<VolumeShaper::Configuration>& configuration,
1391 const sp<VolumeShaper::Operation>& operation) {
1392 // for hardware output, call player instead
1393 ALOGV("Client::applyVolumeShaper(%p)", this);
1394 sp<MediaPlayerBase> p = getPlayer();
1395 {
1396 Mutex::Autolock l(mLock);
1397 if (p != 0 && p->hardwareOutput()) {
1398 // TODO: investigate internal implementation
1399 return VolumeShaper::Status(INVALID_OPERATION);
1400 }
1401 if (mAudioOutput.get() != nullptr) {
1402 return mAudioOutput->applyVolumeShaper(configuration, operation);
1403 }
1404 }
1405 return VolumeShaper::Status(INVALID_OPERATION);
1406}
1407
1408sp<VolumeShaper::State> MediaPlayerService::Client::getVolumeShaperState(int id) {
1409 // for hardware output, call player instead
1410 ALOGV("Client::getVolumeShaperState(%p)", this);
1411 sp<MediaPlayerBase> p = getPlayer();
1412 {
1413 Mutex::Autolock l(mLock);
1414 if (p != 0 && p->hardwareOutput()) {
1415 // TODO: investigate internal implementation.
1416 return nullptr;
1417 }
1418 if (mAudioOutput.get() != nullptr) {
1419 return mAudioOutput->getVolumeShaperState(id);
1420 }
1421 }
1422 return nullptr;
1423}
1424
Wei Jiac5de0912016-11-18 10:22:14 -08001425status_t MediaPlayerService::Client::seekTo(int msec, MediaPlayerSeekMode mode)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001426{
Wei Jiac5de0912016-11-18 10:22:14 -08001427 ALOGV("[%d] seekTo(%d, %d)", mConnId, msec, mode);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001428 sp<MediaPlayerBase> p = getPlayer();
1429 if (p == 0) return UNKNOWN_ERROR;
Wei Jiac5de0912016-11-18 10:22:14 -08001430 return p->seekTo(msec, mode);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001431}
1432
1433status_t MediaPlayerService::Client::reset()
1434{
Steve Block3856b092011-10-20 11:56:00 +01001435 ALOGV("[%d] reset", mConnId);
John Grossmanc795b642012-02-22 15:38:35 -08001436 mRetransmitEndpointValid = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001437 sp<MediaPlayerBase> p = getPlayer();
1438 if (p == 0) return UNKNOWN_ERROR;
1439 return p->reset();
1440}
1441
Wei Jia52c28512017-09-13 18:17:51 -07001442status_t MediaPlayerService::Client::notifyAt(int64_t mediaTimeUs)
1443{
1444 ALOGV("[%d] notifyAt(%lld)", mConnId, (long long)mediaTimeUs);
1445 sp<MediaPlayerBase> p = getPlayer();
1446 if (p == 0) return UNKNOWN_ERROR;
1447 return p->notifyAt(mediaTimeUs);
1448}
1449
Glenn Kastenfff6d712012-01-12 16:38:12 -08001450status_t MediaPlayerService::Client::setAudioStreamType(audio_stream_type_t type)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001451{
Steve Block3856b092011-10-20 11:56:00 +01001452 ALOGV("[%d] setAudioStreamType(%d)", mConnId, type);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001453 // TODO: for hardware output, call player instead
1454 Mutex::Autolock l(mLock);
1455 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1456 return NO_ERROR;
1457}
1458
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001459status_t MediaPlayerService::Client::setAudioAttributes_l(const Parcel &parcel)
1460{
1461 if (mAudioAttributes != NULL) { free(mAudioAttributes); }
1462 mAudioAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001463 if (mAudioAttributes == NULL) {
1464 return NO_MEMORY;
1465 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001466 unmarshallAudioAttributes(parcel, mAudioAttributes);
1467
1468 ALOGV("setAudioAttributes_l() usage=%d content=%d flags=0x%x tags=%s",
1469 mAudioAttributes->usage, mAudioAttributes->content_type, mAudioAttributes->flags,
1470 mAudioAttributes->tags);
1471
1472 if (mAudioOutput != 0) {
1473 mAudioOutput->setAudioAttributes(mAudioAttributes);
1474 }
1475 return NO_ERROR;
1476}
1477
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001478status_t MediaPlayerService::Client::setLooping(int loop)
1479{
Steve Block3856b092011-10-20 11:56:00 +01001480 ALOGV("[%d] setLooping(%d)", mConnId, loop);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001481 mLoop = loop;
1482 sp<MediaPlayerBase> p = getPlayer();
1483 if (p != 0) return p->setLooping(loop);
1484 return NO_ERROR;
1485}
1486
1487status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1488{
Steve Block3856b092011-10-20 11:56:00 +01001489 ALOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
John Grossman761defc2012-02-09 15:09:05 -08001490
1491 // for hardware output, call player instead
1492 sp<MediaPlayerBase> p = getPlayer();
1493 {
1494 Mutex::Autolock l(mLock);
1495 if (p != 0 && p->hardwareOutput()) {
1496 MediaPlayerHWInterface* hwp =
1497 reinterpret_cast<MediaPlayerHWInterface*>(p.get());
1498 return hwp->setVolume(leftVolume, rightVolume);
1499 } else {
1500 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1501 return NO_ERROR;
1502 }
1503 }
1504
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001505 return NO_ERROR;
1506}
1507
Eric Laurent2beeb502010-07-16 07:43:46 -07001508status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1509{
Steve Block3856b092011-10-20 11:56:00 +01001510 ALOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
Eric Laurent2beeb502010-07-16 07:43:46 -07001511 Mutex::Autolock l(mLock);
1512 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1513 return NO_ERROR;
1514}
1515
1516status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1517{
Steve Block3856b092011-10-20 11:56:00 +01001518 ALOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
Eric Laurent2beeb502010-07-16 07:43:46 -07001519 Mutex::Autolock l(mLock);
1520 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1521 return NO_ERROR;
1522}
Nicolas Catania48290382009-07-10 13:53:06 -07001523
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001524status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
Steve Block3856b092011-10-20 11:56:00 +01001525 ALOGV("[%d] setParameter(%d)", mConnId, key);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001526 switch (key) {
1527 case KEY_PARAMETER_AUDIO_ATTRIBUTES:
1528 {
1529 Mutex::Autolock l(mLock);
1530 return setAudioAttributes_l(request);
1531 }
1532 default:
1533 sp<MediaPlayerBase> p = getPlayer();
1534 if (p == 0) { return UNKNOWN_ERROR; }
1535 return p->setParameter(key, request);
1536 }
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001537}
1538
1539status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
Steve Block3856b092011-10-20 11:56:00 +01001540 ALOGV("[%d] getParameter(%d)", mConnId, key);
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001541 sp<MediaPlayerBase> p = getPlayer();
1542 if (p == 0) return UNKNOWN_ERROR;
1543 return p->getParameter(key, reply);
1544}
1545
John Grossmanc795b642012-02-22 15:38:35 -08001546status_t MediaPlayerService::Client::setRetransmitEndpoint(
1547 const struct sockaddr_in* endpoint) {
1548
1549 if (NULL != endpoint) {
1550 uint32_t a = ntohl(endpoint->sin_addr.s_addr);
1551 uint16_t p = ntohs(endpoint->sin_port);
1552 ALOGV("[%d] setRetransmitEndpoint(%u.%u.%u.%u:%hu)", mConnId,
1553 (a >> 24), (a >> 16) & 0xFF, (a >> 8) & 0xFF, (a & 0xFF), p);
1554 } else {
1555 ALOGV("[%d] setRetransmitEndpoint = <none>", mConnId);
1556 }
1557
1558 sp<MediaPlayerBase> p = getPlayer();
1559
1560 // Right now, the only valid time to set a retransmit endpoint is before
1561 // player selection has been made (since the presence or absence of a
1562 // retransmit endpoint is going to determine which player is selected during
1563 // setDataSource).
1564 if (p != 0) return INVALID_OPERATION;
1565
1566 if (NULL != endpoint) {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001567 Mutex::Autolock lock(mLock);
John Grossmanc795b642012-02-22 15:38:35 -08001568 mRetransmitEndpoint = *endpoint;
1569 mRetransmitEndpointValid = true;
1570 } else {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001571 Mutex::Autolock lock(mLock);
John Grossmanc795b642012-02-22 15:38:35 -08001572 mRetransmitEndpointValid = false;
1573 }
1574
1575 return NO_ERROR;
1576}
1577
John Grossman44a7e422012-06-21 17:29:24 -07001578status_t MediaPlayerService::Client::getRetransmitEndpoint(
1579 struct sockaddr_in* endpoint)
1580{
1581 if (NULL == endpoint)
1582 return BAD_VALUE;
1583
1584 sp<MediaPlayerBase> p = getPlayer();
1585
1586 if (p != NULL)
1587 return p->getRetransmitEndpoint(endpoint);
1588
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001589 Mutex::Autolock lock(mLock);
John Grossman44a7e422012-06-21 17:29:24 -07001590 if (!mRetransmitEndpointValid)
1591 return NO_INIT;
1592
1593 *endpoint = mRetransmitEndpoint;
1594
1595 return NO_ERROR;
1596}
1597
Gloria Wangb483c472011-04-11 17:23:27 -07001598void MediaPlayerService::Client::notify(
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001599 int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001600{
James Dongb8a98252012-08-26 16:13:03 -07001601 sp<IMediaPlayerClient> c;
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001602 sp<Client> nextClient;
1603 status_t errStartNext = NO_ERROR;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001604 {
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001605 Mutex::Autolock l(mLock);
1606 c = mClient;
1607 if (msg == MEDIA_PLAYBACK_COMPLETE && mNextClient != NULL) {
1608 nextClient = mNextClient;
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001609
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001610 if (mAudioOutput != NULL)
1611 mAudioOutput->switchToNextOutput();
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001612
1613 errStartNext = nextClient->start();
1614 }
1615 }
1616
1617 if (nextClient != NULL) {
1618 sp<IMediaPlayerClient> nc;
1619 {
1620 Mutex::Autolock l(nextClient->mLock);
1621 nc = nextClient->mClient;
1622 }
1623 if (nc != NULL) {
1624 if (errStartNext == NO_ERROR) {
1625 nc->notify(MEDIA_INFO, MEDIA_INFO_STARTED_AS_NEXT, 0, obj);
1626 } else {
1627 nc->notify(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN , 0, obj);
1628 ALOGE("gapless:start playback for next track failed, err(%d)", errStartNext);
Wei Jia2afac0c2016-01-07 12:13:07 -08001629 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001630 }
1631 }
1632
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001633 if (MEDIA_INFO == msg &&
Nicolas Catania48290382009-07-10 13:53:06 -07001634 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikoa64c8c72009-07-20 15:07:26 -07001635 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania48290382009-07-10 13:53:06 -07001636
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001637 if(shouldDropMetadata(metadata_type)) {
Nicolas Catania48290382009-07-10 13:53:06 -07001638 return;
1639 }
1640
1641 // Update the list of metadata that have changed. getMetadata
1642 // also access mMetadataUpdated and clears it.
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001643 addNewMetadataUpdate(metadata_type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001644 }
James Dongb8a98252012-08-26 16:13:03 -07001645
1646 if (c != NULL) {
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001647 ALOGV("[%d] notify (%d, %d, %d)", mConnId, msg, ext1, ext2);
James Dongb8a98252012-08-26 16:13:03 -07001648 c->notify(msg, ext1, ext2, obj);
1649 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001650}
1651
Nicolas Catania48290382009-07-10 13:53:06 -07001652
nikoa64c8c72009-07-20 15:07:26 -07001653bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001654{
Nicolas Catania48290382009-07-10 13:53:06 -07001655 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001656
Nicolas Catania48290382009-07-10 13:53:06 -07001657 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001658 return true;
1659 }
1660
Nicolas Catania48290382009-07-10 13:53:06 -07001661 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001662 return false;
Nicolas Catania48290382009-07-10 13:53:06 -07001663 } else {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001664 return true;
1665 }
1666}
1667
Nicolas Catania48290382009-07-10 13:53:06 -07001668
nikoa64c8c72009-07-20 15:07:26 -07001669void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania48290382009-07-10 13:53:06 -07001670 Mutex::Autolock lock(mLock);
1671 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1672 mMetadataUpdated.add(metadata_type);
1673 }
1674}
1675
Hassan Shojaniacefac142017-02-06 21:02:02 -08001676// Modular DRM
1677status_t MediaPlayerService::Client::prepareDrm(const uint8_t uuid[16],
1678 const Vector<uint8_t>& drmSessionId)
1679{
1680 ALOGV("[%d] prepareDrm", mConnId);
1681 sp<MediaPlayerBase> p = getPlayer();
1682 if (p == 0) return UNKNOWN_ERROR;
1683
1684 status_t ret = p->prepareDrm(uuid, drmSessionId);
1685 ALOGV("prepareDrm ret: %d", ret);
1686
1687 return ret;
1688}
1689
1690status_t MediaPlayerService::Client::releaseDrm()
1691{
1692 ALOGV("[%d] releaseDrm", mConnId);
1693 sp<MediaPlayerBase> p = getPlayer();
1694 if (p == 0) return UNKNOWN_ERROR;
1695
1696 status_t ret = p->releaseDrm();
1697 ALOGV("releaseDrm ret: %d", ret);
1698
1699 return ret;
1700}
1701
jiabin156c6872017-10-06 09:47:15 -07001702status_t MediaPlayerService::Client::setOutputDevice(audio_port_handle_t deviceId)
1703{
1704 ALOGV("[%d] setOutputDevice", mConnId);
1705 {
1706 Mutex::Autolock l(mLock);
1707 if (mAudioOutput.get() != nullptr) {
1708 return mAudioOutput->setOutputDevice(deviceId);
1709 }
1710 }
1711 return NO_INIT;
1712}
1713
1714status_t MediaPlayerService::Client::getRoutedDeviceId(audio_port_handle_t* deviceId)
1715{
1716 ALOGV("[%d] getRoutedDeviceId", mConnId);
1717 {
1718 Mutex::Autolock l(mLock);
1719 if (mAudioOutput.get() != nullptr) {
1720 return mAudioOutput->getRoutedDeviceId(deviceId);
1721 }
1722 }
1723 return NO_INIT;
1724}
1725
1726status_t MediaPlayerService::Client::enableAudioDeviceCallback(bool enabled)
1727{
1728 ALOGV("[%d] enableAudioDeviceCallback, %d", mConnId, enabled);
1729 {
1730 Mutex::Autolock l(mLock);
1731 if (mAudioOutput.get() != nullptr) {
1732 return mAudioOutput->enableAudioDeviceCallback(enabled);
1733 }
1734 }
1735 return NO_INIT;
1736}
1737
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001738#if CALLBACK_ANTAGONIZER
1739const int Antagonizer::interval = 10000; // 10 msecs
1740
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001741Antagonizer::Antagonizer(const sp<MediaPlayerBase::Listener> &listener) :
1742 mExit(false), mActive(false), mListener(listener)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001743{
1744 createThread(callbackThread, this);
1745}
1746
1747void Antagonizer::kill()
1748{
1749 Mutex::Autolock _l(mLock);
1750 mActive = false;
1751 mExit = true;
1752 mCondition.wait(mLock);
1753}
1754
1755int Antagonizer::callbackThread(void* user)
1756{
Steve Blockb8a80522011-12-20 16:23:08 +00001757 ALOGD("Antagonizer started");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001758 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1759 while (!p->mExit) {
1760 if (p->mActive) {
Steve Block3856b092011-10-20 11:56:00 +01001761 ALOGV("send event");
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001762 p->mListener->notify(0, 0, 0, 0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001763 }
1764 usleep(interval);
1765 }
1766 Mutex::Autolock _l(p->mLock);
1767 p->mCondition.signal();
Steve Blockb8a80522011-12-20 16:23:08 +00001768 ALOGD("Antagonizer stopped");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001769 return 0;
1770}
1771#endif
1772
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001773#undef LOG_TAG
1774#define LOG_TAG "AudioSink"
Andy Hung1afd0982016-11-08 16:13:44 -08001775MediaPlayerService::AudioOutput::AudioOutput(audio_session_t sessionId, uid_t uid, int pid,
jiabin375283d2020-08-21 18:14:43 -07001776 const audio_attributes_t* attr, const sp<AudioSystem::AudioDeviceCallback>& deviceCallback,
1777 const std::string& opPackageName)
Andreas Huber20111aa2009-07-14 16:56:47 -07001778 : mCallback(NULL),
Eric Laurenta514bdb2010-06-21 09:27:30 -07001779 mCallbackCookie(NULL),
Marco Nelissen6b74d672012-02-28 16:07:44 -08001780 mCallbackData(NULL),
Andy Hungd1c74342015-07-07 16:54:23 -07001781 mStreamType(AUDIO_STREAM_MUSIC),
Andy Hungd1c74342015-07-07 16:54:23 -07001782 mLeftVolume(1.0),
1783 mRightVolume(1.0),
1784 mPlaybackRate(AUDIO_PLAYBACK_RATE_DEFAULT),
1785 mSampleRateHz(0),
1786 mMsecsPerFrame(0),
1787 mFrameSize(0),
Eric Laurent1948eb32012-04-13 16:50:19 -07001788 mSessionId(sessionId),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001789 mUid(uid),
Marco Nelissend457c972014-02-11 08:47:07 -08001790 mPid(pid),
Andy Hungd1c74342015-07-07 16:54:23 -07001791 mSendLevel(0.0),
1792 mAuxEffectId(0),
Andy Hung4ef88d72017-02-21 19:47:53 -08001793 mFlags(AUDIO_OUTPUT_FLAG_NONE),
jiabin156c6872017-10-06 09:47:15 -07001794 mVolumeHandler(new media::VolumeHandler()),
1795 mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE),
jiabin161b64fc2017-11-17 09:31:48 -08001796 mRoutedDeviceId(AUDIO_PORT_HANDLE_NONE),
jiabin156c6872017-10-06 09:47:15 -07001797 mDeviceCallbackEnabled(false),
jiabin375283d2020-08-21 18:14:43 -07001798 mDeviceCallback(deviceCallback),
1799 mOpPackageName(opPackageName)
Andy Hungd1c74342015-07-07 16:54:23 -07001800{
Steve Block3856b092011-10-20 11:56:00 +01001801 ALOGV("AudioOutput(%d)", sessionId);
Eric Laurent43562692015-07-15 16:49:07 -07001802 if (attr != NULL) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001803 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1804 if (mAttributes != NULL) {
1805 memcpy(mAttributes, attr, sizeof(audio_attributes_t));
François Gaffie58d4be52018-11-06 15:30:12 +01001806 mStreamType = AudioSystem::attributesToStreamType(*attr);
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001807 }
1808 } else {
1809 mAttributes = NULL;
Eric Laurent43562692015-07-15 16:49:07 -07001810 }
1811
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001812 setMinBufferCount();
1813}
1814
1815MediaPlayerService::AudioOutput::~AudioOutput()
1816{
1817 close();
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001818 free(mAttributes);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001819 delete mCallbackData;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001820}
1821
Andy Hungd1c74342015-07-07 16:54:23 -07001822//static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001823void MediaPlayerService::AudioOutput::setMinBufferCount()
1824{
Roman Kiryanova3f34462021-03-10 16:17:24 -08001825 if (property_get_bool("ro.boot.qemu", false)) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001826 mIsOnEmulator = true;
1827 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1828 }
1829}
1830
Andy Hungd1c74342015-07-07 16:54:23 -07001831// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001832bool MediaPlayerService::AudioOutput::isOnEmulator()
1833{
Andy Hungd1c74342015-07-07 16:54:23 -07001834 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001835 return mIsOnEmulator;
1836}
1837
Andy Hungd1c74342015-07-07 16:54:23 -07001838// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001839int MediaPlayerService::AudioOutput::getMinBufferCount()
1840{
Andy Hungd1c74342015-07-07 16:54:23 -07001841 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001842 return mMinBufferCount;
1843}
1844
1845ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1846{
Andy Hungd1c74342015-07-07 16:54:23 -07001847 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001848 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001849 return mTrack->frameCount() * mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001850}
1851
1852ssize_t MediaPlayerService::AudioOutput::frameCount() const
1853{
Andy Hungd1c74342015-07-07 16:54:23 -07001854 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001855 if (mTrack == 0) return NO_INIT;
1856 return mTrack->frameCount();
1857}
1858
1859ssize_t MediaPlayerService::AudioOutput::channelCount() const
1860{
Andy Hungd1c74342015-07-07 16:54:23 -07001861 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001862 if (mTrack == 0) return NO_INIT;
1863 return mTrack->channelCount();
1864}
1865
1866ssize_t MediaPlayerService::AudioOutput::frameSize() const
1867{
Andy Hungd1c74342015-07-07 16:54:23 -07001868 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001869 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001870 return mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001871}
1872
1873uint32_t MediaPlayerService::AudioOutput::latency () const
1874{
Andy Hungd1c74342015-07-07 16:54:23 -07001875 Mutex::Autolock lock(mLock);
Eric Laurentdb354e52012-03-05 17:27:11 -08001876 if (mTrack == 0) return 0;
1877 return mTrack->latency();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001878}
1879
1880float MediaPlayerService::AudioOutput::msecsPerFrame() const
1881{
Andy Hungd1c74342015-07-07 16:54:23 -07001882 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001883 return mMsecsPerFrame;
1884}
1885
Marco Nelissen4110c102012-03-29 09:31:28 -07001886status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position) const
Eric Laurent342e9cf2010-01-19 17:37:09 -08001887{
Andy Hungd1c74342015-07-07 16:54:23 -07001888 Mutex::Autolock lock(mLock);
Eric Laurent342e9cf2010-01-19 17:37:09 -08001889 if (mTrack == 0) return NO_INIT;
1890 return mTrack->getPosition(position);
1891}
1892
Lajos Molnar06ad1522014-08-28 07:27:44 -07001893status_t MediaPlayerService::AudioOutput::getTimestamp(AudioTimestamp &ts) const
1894{
Andy Hungd1c74342015-07-07 16:54:23 -07001895 Mutex::Autolock lock(mLock);
Lajos Molnar06ad1522014-08-28 07:27:44 -07001896 if (mTrack == 0) return NO_INIT;
1897 return mTrack->getTimestamp(ts);
1898}
1899
Wei Jiac4ac8172015-10-21 10:35:48 -07001900// TODO: Remove unnecessary calls to getPlayedOutDurationUs()
1901// as it acquires locks and may query the audio driver.
1902//
1903// Some calls could conceivably retrieve extrapolated data instead of
1904// accessing getTimestamp() or getPosition() every time a data buffer with
1905// a media time is received.
1906//
1907// Calculate duration of played samples if played at normal rate (i.e., 1.0).
1908int64_t MediaPlayerService::AudioOutput::getPlayedOutDurationUs(int64_t nowUs) const
1909{
1910 Mutex::Autolock lock(mLock);
1911 if (mTrack == 0 || mSampleRateHz == 0) {
Wei Jia213f4902015-10-22 08:55:25 -07001912 return 0;
Wei Jiac4ac8172015-10-21 10:35:48 -07001913 }
1914
1915 uint32_t numFramesPlayed;
Andy Hung5d313802016-10-10 15:09:39 -07001916 int64_t numFramesPlayedAtUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001917 AudioTimestamp ts;
Wei Jiac4ac8172015-10-21 10:35:48 -07001918
1919 status_t res = mTrack->getTimestamp(ts);
1920 if (res == OK) { // case 1: mixing audio tracks and offloaded tracks.
1921 numFramesPlayed = ts.mPosition;
Andy Hung5d313802016-10-10 15:09:39 -07001922 numFramesPlayedAtUs = ts.mTime.tv_sec * 1000000LL + ts.mTime.tv_nsec / 1000;
1923 //ALOGD("getTimestamp: OK %d %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001924 } else if (res == WOULD_BLOCK) { // case 2: transitory state on start of a new track
1925 numFramesPlayed = 0;
Andy Hung5d313802016-10-10 15:09:39 -07001926 numFramesPlayedAtUs = nowUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001927 //ALOGD("getTimestamp: WOULD_BLOCK %d %lld",
Andy Hung5d313802016-10-10 15:09:39 -07001928 // numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001929 } else { // case 3: transitory at new track or audio fast tracks.
1930 res = mTrack->getPosition(&numFramesPlayed);
1931 CHECK_EQ(res, (status_t)OK);
Andy Hung5d313802016-10-10 15:09:39 -07001932 numFramesPlayedAtUs = nowUs;
1933 numFramesPlayedAtUs += 1000LL * mTrack->latency() / 2; /* XXX */
1934 //ALOGD("getPosition: %u %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001935 }
1936
1937 // CHECK_EQ(numFramesPlayed & (1 << 31), 0); // can't be negative until 12.4 hrs, test
1938 // TODO: remove the (int32_t) casting below as it may overflow at 12.4 hours.
1939 int64_t durationUs = (int64_t)((int32_t)numFramesPlayed * 1000000LL / mSampleRateHz)
Andy Hung5d313802016-10-10 15:09:39 -07001940 + nowUs - numFramesPlayedAtUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001941 if (durationUs < 0) {
1942 // Occurs when numFramesPlayed position is very small and the following:
1943 // (1) In case 1, the time nowUs is computed before getTimestamp() is called and
Andy Hung5d313802016-10-10 15:09:39 -07001944 // numFramesPlayedAtUs is greater than nowUs by time more than numFramesPlayed.
Wei Jiac4ac8172015-10-21 10:35:48 -07001945 // (2) In case 3, using getPosition and adding mAudioSink->latency() to
Andy Hung5d313802016-10-10 15:09:39 -07001946 // numFramesPlayedAtUs, by a time amount greater than numFramesPlayed.
Wei Jiac4ac8172015-10-21 10:35:48 -07001947 //
1948 // Both of these are transitory conditions.
1949 ALOGV("getPlayedOutDurationUs: negative duration %lld set to zero", (long long)durationUs);
1950 durationUs = 0;
1951 }
1952 ALOGV("getPlayedOutDurationUs(%lld) nowUs(%lld) frames(%u) framesAt(%lld)",
Andy Hung5d313802016-10-10 15:09:39 -07001953 (long long)durationUs, (long long)nowUs,
1954 numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001955 return durationUs;
1956}
1957
Marco Nelissen4110c102012-03-29 09:31:28 -07001958status_t MediaPlayerService::AudioOutput::getFramesWritten(uint32_t *frameswritten) const
1959{
Andy Hungd1c74342015-07-07 16:54:23 -07001960 Mutex::Autolock lock(mLock);
Marco Nelissen4110c102012-03-29 09:31:28 -07001961 if (mTrack == 0) return NO_INIT;
Andy Hung2f6e73d2016-04-08 12:12:58 -07001962 ExtendedTimestamp ets;
1963 status_t status = mTrack->getTimestamp(&ets);
1964 if (status == OK || status == WOULD_BLOCK) {
1965 *frameswritten = (uint32_t)ets.mPosition[ExtendedTimestamp::LOCATION_CLIENT];
1966 }
1967 return status;
Marco Nelissen4110c102012-03-29 09:31:28 -07001968}
1969
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001970status_t MediaPlayerService::AudioOutput::setParameters(const String8& keyValuePairs)
1971{
Andy Hungd1c74342015-07-07 16:54:23 -07001972 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001973 if (mTrack == 0) return NO_INIT;
1974 return mTrack->setParameters(keyValuePairs);
1975}
1976
1977String8 MediaPlayerService::AudioOutput::getParameters(const String8& keys)
1978{
Andy Hungd1c74342015-07-07 16:54:23 -07001979 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001980 if (mTrack == 0) return String8::empty();
1981 return mTrack->getParameters(keys);
1982}
1983
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001984void MediaPlayerService::AudioOutput::setAudioAttributes(const audio_attributes_t * attributes) {
Andy Hungd1c74342015-07-07 16:54:23 -07001985 Mutex::Autolock lock(mLock);
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001986 if (attributes == NULL) {
1987 free(mAttributes);
1988 mAttributes = NULL;
1989 } else {
1990 if (mAttributes == NULL) {
1991 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1992 }
1993 memcpy(mAttributes, attributes, sizeof(audio_attributes_t));
François Gaffie58d4be52018-11-06 15:30:12 +01001994 mStreamType = AudioSystem::attributesToStreamType(*attributes);
Eric Laurent43562692015-07-15 16:49:07 -07001995 }
1996}
1997
1998void MediaPlayerService::AudioOutput::setAudioStreamType(audio_stream_type_t streamType)
1999{
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07002000 Mutex::Autolock lock(mLock);
Eric Laurent43562692015-07-15 16:49:07 -07002001 // do not allow direct stream type modification if attributes have been set
2002 if (mAttributes == NULL) {
2003 mStreamType = streamType;
2004 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07002005}
2006
Andy Hungd1c74342015-07-07 16:54:23 -07002007void MediaPlayerService::AudioOutput::deleteRecycledTrack_l()
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002008{
Andy Hungd1c74342015-07-07 16:54:23 -07002009 ALOGV("deleteRecycledTrack_l");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002010 if (mRecycledTrack != 0) {
2011
2012 if (mCallbackData != NULL) {
2013 mCallbackData->setOutput(NULL);
2014 mCallbackData->endTrackSwitch();
2015 }
2016
2017 if ((mRecycledTrack->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) {
Andy Hunge13f8a62016-03-30 14:20:42 -07002018 int32_t msec = 0;
2019 if (!mRecycledTrack->stopped()) { // check if active
2020 (void)mRecycledTrack->pendingDuration(&msec);
2021 }
2022 mRecycledTrack->stop(); // ensure full data drain
2023 ALOGD("deleting recycled track, waiting for data drain (%d msec)", msec);
2024 if (msec > 0) {
2025 static const int32_t WAIT_LIMIT_MS = 3000;
2026 if (msec > WAIT_LIMIT_MS) {
2027 msec = WAIT_LIMIT_MS;
2028 }
2029 usleep(msec * 1000LL);
2030 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002031 }
2032 // An offloaded track isn't flushed because the STREAM_END is reported
2033 // slightly prematurely to allow time for the gapless track switch
2034 // but this means that if we decide not to recycle the track there
2035 // could be a small amount of residual data still playing. We leave
2036 // AudioFlinger to drain the track.
2037
2038 mRecycledTrack.clear();
Andy Hungd1c74342015-07-07 16:54:23 -07002039 close_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002040 delete mCallbackData;
2041 mCallbackData = NULL;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002042 }
2043}
2044
Andy Hungd1c74342015-07-07 16:54:23 -07002045void MediaPlayerService::AudioOutput::close_l()
2046{
2047 mTrack.clear();
2048}
2049
Andreas Huber20111aa2009-07-14 16:56:47 -07002050status_t MediaPlayerService::AudioOutput::open(
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08002051 uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
2052 audio_format_t format, int bufferCount,
Eric Laurent1948eb32012-04-13 16:50:19 -07002053 AudioCallback cb, void *cookie,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002054 audio_output_flags_t flags,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07002055 const audio_offload_info_t *offloadInfo,
Andy Hung179652e2015-05-31 22:49:46 -07002056 bool doNotReconnect,
2057 uint32_t suggestedFrameCount)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002058{
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002059 ALOGV("open(%u, %d, 0x%x, 0x%x, %d, %d 0x%x)", sampleRate, channelCount, channelMask,
2060 format, bufferCount, mSessionId, flags);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002061
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002062 // offloading is only supported in callback mode for now.
2063 // offloadInfo must be present if offload flag is set
2064 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) &&
2065 ((cb == NULL) || (offloadInfo == NULL))) {
2066 return BAD_VALUE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002067 }
2068
Andy Hung179652e2015-05-31 22:49:46 -07002069 // compute frame count for the AudioTrack internal buffer
2070 size_t frameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002071 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
2072 frameCount = 0; // AudioTrack will get frame count from AudioFlinger
2073 } else {
Andy Hung179652e2015-05-31 22:49:46 -07002074 // try to estimate the buffer processing fetch size from AudioFlinger.
2075 // framesPerBuffer is approximate and generally correct, except when it's not :-).
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002076 uint32_t afSampleRate;
2077 size_t afFrameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002078 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
2079 return NO_INIT;
2080 }
2081 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
2082 return NO_INIT;
2083 }
Ben Romberger259fb462018-08-07 17:58:53 -07002084 if (afSampleRate == 0) {
2085 return NO_INIT;
2086 }
Andy Hung179652e2015-05-31 22:49:46 -07002087 const size_t framesPerBuffer =
2088 (unsigned long long)sampleRate * afFrameCount / afSampleRate;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002089
Andy Hung179652e2015-05-31 22:49:46 -07002090 if (bufferCount == 0) {
Ben Romberger259fb462018-08-07 17:58:53 -07002091 if (framesPerBuffer == 0) {
2092 return NO_INIT;
2093 }
Andy Hung179652e2015-05-31 22:49:46 -07002094 // use suggestedFrameCount
2095 bufferCount = (suggestedFrameCount + framesPerBuffer - 1) / framesPerBuffer;
2096 }
2097 // Check argument bufferCount against the mininum buffer count
2098 if (bufferCount != 0 && bufferCount < mMinBufferCount) {
2099 ALOGV("bufferCount (%d) increased to %d", bufferCount, mMinBufferCount);
2100 bufferCount = mMinBufferCount;
2101 }
2102 // if frameCount is 0, then AudioTrack will get frame count from AudioFlinger
2103 // which will be the minimum size permitted.
2104 frameCount = bufferCount * framesPerBuffer;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002105 }
Andreas Huber20111aa2009-07-14 16:56:47 -07002106
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08002107 if (channelMask == CHANNEL_MASK_USE_CHANNEL_ORDER) {
Glenn Kastenab334fd2012-03-14 12:56:06 -07002108 channelMask = audio_channel_out_mask_from_count(channelCount);
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08002109 if (0 == channelMask) {
2110 ALOGE("open() error, can\'t derive mask for %d audio channels", channelCount);
2111 return NO_INIT;
2112 }
2113 }
Eric Laurent1948eb32012-04-13 16:50:19 -07002114
Andy Hungd1c74342015-07-07 16:54:23 -07002115 Mutex::Autolock lock(mLock);
Andy Hung179652e2015-05-31 22:49:46 -07002116 mCallback = cb;
2117 mCallbackCookie = cookie;
2118
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002119 // Check whether we can recycle the track
2120 bool reuse = false;
2121 bool bothOffloaded = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07002122
Glenn Kasten2799d742013-05-30 14:33:29 -07002123 if (mRecycledTrack != 0) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002124 // check whether we are switching between two offloaded tracks
2125 bothOffloaded = (flags & mRecycledTrack->getFlags()
2126 & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0;
Marco Nelissen67295b52012-06-11 14:52:53 -07002127
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002128 // check if the existing track can be reused as-is, or if a new track needs to be created.
2129 reuse = true;
2130
Marco Nelissen67295b52012-06-11 14:52:53 -07002131 if ((mCallbackData == NULL && mCallback != NULL) ||
2132 (mCallbackData != NULL && mCallback == NULL)) {
2133 // recycled track uses callbacks but the caller wants to use writes, or vice versa
2134 ALOGV("can't chain callback and write");
2135 reuse = false;
2136 } else if ((mRecycledTrack->getSampleRate() != sampleRate) ||
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002137 (mRecycledTrack->channelCount() != (uint32_t)channelCount) ) {
2138 ALOGV("samplerate, channelcount differ: %u/%u Hz, %u/%d ch",
Marco Nelissen67295b52012-06-11 14:52:53 -07002139 mRecycledTrack->getSampleRate(), sampleRate,
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002140 mRecycledTrack->channelCount(), channelCount);
Marco Nelissen67295b52012-06-11 14:52:53 -07002141 reuse = false;
2142 } else if (flags != mFlags) {
2143 ALOGV("output flags differ %08x/%08x", flags, mFlags);
2144 reuse = false;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002145 } else if (mRecycledTrack->format() != format) {
2146 reuse = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07002147 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002148 } else {
2149 ALOGV("no track available to recycle");
2150 }
2151
2152 ALOGV_IF(bothOffloaded, "both tracks offloaded");
2153
2154 // If we can't recycle and both tracks are offloaded
2155 // we must close the previous output before opening a new one
2156 if (bothOffloaded && !reuse) {
2157 ALOGV("both offloaded and not recycling");
Andy Hungd1c74342015-07-07 16:54:23 -07002158 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002159 }
2160
2161 sp<AudioTrack> t;
2162 CallbackData *newcbd = NULL;
2163
2164 // We don't attempt to create a new track if we are recycling an
2165 // offloaded track. But, if we are recycling a non-offloaded or we
2166 // are switching where one is offloaded and one isn't then we create
2167 // the new track in advance so that we can read additional stream info
2168
2169 if (!(reuse && bothOffloaded)) {
2170 ALOGV("creating new AudioTrack");
2171
2172 if (mCallback != NULL) {
2173 newcbd = new CallbackData(this);
2174 t = new AudioTrack(
2175 mStreamType,
2176 sampleRate,
2177 format,
2178 channelMask,
2179 frameCount,
2180 flags,
2181 CallbackWrapper,
2182 newcbd,
2183 0, // notification frames
2184 mSessionId,
2185 AudioTrack::TRANSFER_CALLBACK,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002186 offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -08002187 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07002188 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07002189 mAttributes,
jiabin156c6872017-10-06 09:47:15 -07002190 doNotReconnect,
2191 1.0f, // default value for maxRequiredSpeed
jiabin375283d2020-08-21 18:14:43 -07002192 mSelectedDeviceId,
2193 mOpPackageName);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002194 } else {
Andy Hungff874dc2016-04-11 16:49:09 -07002195 // TODO: Due to buffer memory concerns, we use a max target playback speed
2196 // based on mPlaybackRate at the time of open (instead of kMaxRequiredSpeed),
2197 // also clamping the target speed to 1.0 <= targetSpeed <= kMaxRequiredSpeed.
2198 const float targetSpeed =
2199 std::min(std::max(mPlaybackRate.mSpeed, 1.0f), kMaxRequiredSpeed);
2200 ALOGW_IF(targetSpeed != mPlaybackRate.mSpeed,
2201 "track target speed:%f clamped from playback speed:%f",
2202 targetSpeed, mPlaybackRate.mSpeed);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002203 t = new AudioTrack(
2204 mStreamType,
2205 sampleRate,
2206 format,
2207 channelMask,
2208 frameCount,
2209 flags,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002210 NULL, // callback
2211 NULL, // user data
2212 0, // notification frames
2213 mSessionId,
2214 AudioTrack::TRANSFER_DEFAULT,
2215 NULL, // offload info
Marco Nelissend457c972014-02-11 08:47:07 -08002216 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07002217 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07002218 mAttributes,
Andy Hungff874dc2016-04-11 16:49:09 -07002219 doNotReconnect,
jiabin156c6872017-10-06 09:47:15 -07002220 targetSpeed,
jiabin375283d2020-08-21 18:14:43 -07002221 mSelectedDeviceId,
2222 mOpPackageName);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002223 }
Andy Hunga6b27032020-04-27 10:34:24 -07002224 // Set caller name so it can be logged in destructor.
2225 // MediaMetricsConstants.h: AMEDIAMETRICS_PROP_CALLERNAME_VALUE_MEDIA
2226 t->setCallerName("media");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002227 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
2228 ALOGE("Unable to create audio track");
2229 delete newcbd;
Glenn Kasten3e98ecd2015-05-18 13:13:24 -07002230 // t goes out of scope, so reference count drops to zero
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002231 return NO_INIT;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07002232 } else {
2233 // successful AudioTrack initialization implies a legacy stream type was generated
2234 // from the audio attributes
2235 mStreamType = t->streamType();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002236 }
2237 }
2238
2239 if (reuse) {
2240 CHECK(mRecycledTrack != NULL);
2241
2242 if (!bothOffloaded) {
2243 if (mRecycledTrack->frameCount() != t->frameCount()) {
Andy Hung833b4752016-04-04 17:15:48 -07002244 ALOGV("framecount differs: %zu/%zu frames",
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002245 mRecycledTrack->frameCount(), t->frameCount());
2246 reuse = false;
2247 }
2248 }
2249
Marco Nelissen67295b52012-06-11 14:52:53 -07002250 if (reuse) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002251 ALOGV("chaining to next output and recycling track");
Andy Hungd1c74342015-07-07 16:54:23 -07002252 close_l();
Marco Nelissen67295b52012-06-11 14:52:53 -07002253 mTrack = mRecycledTrack;
Glenn Kasten2799d742013-05-30 14:33:29 -07002254 mRecycledTrack.clear();
Marco Nelissen67295b52012-06-11 14:52:53 -07002255 if (mCallbackData != NULL) {
2256 mCallbackData->setOutput(this);
2257 }
Marco Nelissen67295b52012-06-11 14:52:53 -07002258 delete newcbd;
Wei Jiae0bbac92016-07-18 16:04:53 -07002259 return updateTrack();
Marco Nelissen67295b52012-06-11 14:52:53 -07002260 }
Marco Nelissen67295b52012-06-11 14:52:53 -07002261 }
2262
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002263 // we're not going to reuse the track, unblock and flush it
2264 // this was done earlier if both tracks are offloaded
2265 if (!bothOffloaded) {
Andy Hungd1c74342015-07-07 16:54:23 -07002266 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002267 }
2268
2269 CHECK((t != NULL) && ((mCallback == NULL) || (newcbd != NULL)));
2270
Marco Nelissen67295b52012-06-11 14:52:53 -07002271 mCallbackData = newcbd;
Steve Block3856b092011-10-20 11:56:00 +01002272 ALOGV("setVolume");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002273 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07002274
Andy Hung39399b62017-04-21 15:07:45 -07002275 // Restore VolumeShapers for the MediaPlayer in case the track was recreated
2276 // due to an output sink error (e.g. offload to non-offload switch).
2277 mVolumeHandler->forall([&t](const VolumeShaper &shaper) -> VolumeShaper::Status {
2278 sp<VolumeShaper::Operation> operationToEnd =
2279 new VolumeShaper::Operation(shaper.mOperation);
2280 // TODO: Ideally we would restore to the exact xOffset position
2281 // as returned by getVolumeShaperState(), but we don't have that
2282 // information when restoring at the client unless we periodically poll
2283 // the server or create shared memory state.
2284 //
2285 // For now, we simply advance to the end of the VolumeShaper effect
2286 // if it has been started.
2287 if (shaper.isStarted()) {
Andy Hungf3702642017-05-05 17:33:32 -07002288 operationToEnd->setNormalizedTime(1.f);
Andy Hung39399b62017-04-21 15:07:45 -07002289 }
2290 return t->applyVolumeShaper(shaper.mConfiguration, operationToEnd);
Andy Hung4ef88d72017-02-21 19:47:53 -08002291 });
Andy Hung4ef88d72017-02-21 19:47:53 -08002292
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002293 mSampleRateHz = sampleRate;
Preetam Singh Ranawat2e17eef2015-08-12 12:11:46 -07002294 mFlags = flags;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002295 mMsecsPerFrame = 1E3f / (mPlaybackRate.mSpeed * sampleRate);
Andy Hungd1c74342015-07-07 16:54:23 -07002296 mFrameSize = t->frameSize();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002297 mTrack = t;
Eric Laurent2beeb502010-07-16 07:43:46 -07002298
Wei Jiae0bbac92016-07-18 16:04:53 -07002299 return updateTrack();
2300}
2301
2302status_t MediaPlayerService::AudioOutput::updateTrack() {
2303 if (mTrack == NULL) {
2304 return NO_ERROR;
2305 }
2306
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002307 status_t res = NO_ERROR;
Wei Jia0162d002015-06-09 11:59:33 -07002308 // Note some output devices may give us a direct track even though we don't specify it.
2309 // Example: Line application b/17459982.
Wei Jiae0bbac92016-07-18 16:04:53 -07002310 if ((mTrack->getFlags()
2311 & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) {
2312 res = mTrack->setPlaybackRate(mPlaybackRate);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002313 if (res == NO_ERROR) {
Wei Jiae0bbac92016-07-18 16:04:53 -07002314 mTrack->setAuxEffectSendLevel(mSendLevel);
2315 res = mTrack->attachAuxEffect(mAuxEffectId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002316 }
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002317 }
jiabin156c6872017-10-06 09:47:15 -07002318 mTrack->setOutputDevice(mSelectedDeviceId);
2319 if (mDeviceCallbackEnabled) {
2320 mTrack->addAudioDeviceCallback(mDeviceCallback.promote());
2321 }
Wei Jiae0bbac92016-07-18 16:04:53 -07002322 ALOGV("updateTrack() DONE status %d", res);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002323 return res;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002324}
2325
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002326status_t MediaPlayerService::AudioOutput::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002327{
Steve Block3856b092011-10-20 11:56:00 +01002328 ALOGV("start");
Andy Hungd1c74342015-07-07 16:54:23 -07002329 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08002330 if (mCallbackData != NULL) {
2331 mCallbackData->endTrackSwitch();
2332 }
Glenn Kasten2799d742013-05-30 14:33:29 -07002333 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002334 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07002335 mTrack->setAuxEffectSendLevel(mSendLevel);
Andy Hung39399b62017-04-21 15:07:45 -07002336 status_t status = mTrack->start();
2337 if (status == NO_ERROR) {
2338 mVolumeHandler->setStarted();
2339 }
2340 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002341 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002342 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002343}
2344
Marco Nelissen6b74d672012-02-28 16:07:44 -08002345void MediaPlayerService::AudioOutput::setNextOutput(const sp<AudioOutput>& nextOutput) {
Andy Hungd1c74342015-07-07 16:54:23 -07002346 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08002347 mNextOutput = nextOutput;
2348}
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08002349
Marco Nelissen6b74d672012-02-28 16:07:44 -08002350void MediaPlayerService::AudioOutput::switchToNextOutput() {
2351 ALOGV("switchToNextOutput");
Andy Hungd1c74342015-07-07 16:54:23 -07002352
2353 // Try to acquire the callback lock before moving track (without incurring deadlock).
2354 const unsigned kMaxSwitchTries = 100;
2355 Mutex::Autolock lock(mLock);
2356 for (unsigned tries = 0;;) {
2357 if (mTrack == 0) {
2358 return;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002359 }
Andy Hungd1c74342015-07-07 16:54:23 -07002360 if (mNextOutput != NULL && mNextOutput != this) {
2361 if (mCallbackData != NULL) {
2362 // two alternative approaches
2363#if 1
2364 CallbackData *callbackData = mCallbackData;
2365 mLock.unlock();
2366 // proper acquisition sequence
2367 callbackData->lock();
2368 mLock.lock();
2369 // Caution: it is unlikely that someone deleted our callback or changed our target
2370 if (callbackData != mCallbackData || mNextOutput == NULL || mNextOutput == this) {
2371 // fatal if we are starved out.
2372 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2373 "switchToNextOutput() cannot obtain correct lock sequence");
2374 callbackData->unlock();
2375 continue;
2376 }
2377 callbackData->mSwitching = true; // begin track switch
Wei Jiaadee56a2016-08-05 15:40:34 -07002378 callbackData->setOutput(NULL);
Andy Hungd1c74342015-07-07 16:54:23 -07002379#else
2380 // tryBeginTrackSwitch() returns false if the callback has the lock.
2381 if (!mCallbackData->tryBeginTrackSwitch()) {
2382 // fatal if we are starved out.
2383 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2384 "switchToNextOutput() cannot obtain callback lock");
2385 mLock.unlock();
2386 usleep(5 * 1000 /* usec */); // allow callback to use AudioOutput
2387 mLock.lock();
2388 continue;
2389 }
2390#endif
2391 }
2392
2393 Mutex::Autolock nextLock(mNextOutput->mLock);
2394
2395 // If the next output track is not NULL, then it has been
2396 // opened already for playback.
2397 // This is possible even without the next player being started,
2398 // for example, the next player could be prepared and seeked.
2399 //
2400 // Presuming it isn't advisable to force the track over.
2401 if (mNextOutput->mTrack == NULL) {
2402 ALOGD("Recycling track for gapless playback");
2403 delete mNextOutput->mCallbackData;
2404 mNextOutput->mCallbackData = mCallbackData;
2405 mNextOutput->mRecycledTrack = mTrack;
2406 mNextOutput->mSampleRateHz = mSampleRateHz;
2407 mNextOutput->mMsecsPerFrame = mMsecsPerFrame;
Andy Hungd1c74342015-07-07 16:54:23 -07002408 mNextOutput->mFlags = mFlags;
2409 mNextOutput->mFrameSize = mFrameSize;
2410 close_l();
2411 mCallbackData = NULL; // destruction handled by mNextOutput
2412 } else {
2413 ALOGW("Ignoring gapless playback because next player has already started");
2414 // remove track in case resource needed for future players.
2415 if (mCallbackData != NULL) {
2416 mCallbackData->endTrackSwitch(); // release lock for callbacks before close.
2417 }
2418 close_l();
2419 }
2420 }
2421 break;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002422 }
2423}
2424
Wei Jia7d3f4df2015-03-03 15:28:00 -08002425ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002426{
Andy Hungd1c74342015-07-07 16:54:23 -07002427 Mutex::Autolock lock(mLock);
Glenn Kastenadad3d72014-02-21 14:51:43 -08002428 LOG_ALWAYS_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
Andreas Huber20111aa2009-07-14 16:56:47 -07002429
Steve Block3856b092011-10-20 11:56:00 +01002430 //ALOGV("write(%p, %u)", buffer, size);
Glenn Kasten2799d742013-05-30 14:33:29 -07002431 if (mTrack != 0) {
Andy Hung2f6e73d2016-04-08 12:12:58 -07002432 return mTrack->write(buffer, size, blocking);
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07002433 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002434 return NO_INIT;
2435}
2436
2437void MediaPlayerService::AudioOutput::stop()
2438{
Steve Block3856b092011-10-20 11:56:00 +01002439 ALOGV("stop");
Andy Hungd1c74342015-07-07 16:54:23 -07002440 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002441 if (mTrack != 0) mTrack->stop();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002442}
2443
2444void MediaPlayerService::AudioOutput::flush()
2445{
Steve Block3856b092011-10-20 11:56:00 +01002446 ALOGV("flush");
Andy Hungd1c74342015-07-07 16:54:23 -07002447 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002448 if (mTrack != 0) mTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002449}
2450
2451void MediaPlayerService::AudioOutput::pause()
2452{
Steve Block3856b092011-10-20 11:56:00 +01002453 ALOGV("pause");
Andy Hungd1c74342015-07-07 16:54:23 -07002454 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002455 if (mTrack != 0) mTrack->pause();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002456}
2457
2458void MediaPlayerService::AudioOutput::close()
2459{
Steve Block3856b092011-10-20 11:56:00 +01002460 ALOGV("close");
Erik Wolsheimer7845a1f2015-10-30 12:07:52 -07002461 sp<AudioTrack> track;
2462 {
2463 Mutex::Autolock lock(mLock);
2464 track = mTrack;
2465 close_l(); // clears mTrack
2466 }
2467 // destruction of the track occurs outside of mutex.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002468}
2469
2470void MediaPlayerService::AudioOutput::setVolume(float left, float right)
2471{
Steve Block3856b092011-10-20 11:56:00 +01002472 ALOGV("setVolume(%f, %f)", left, right);
Andy Hungd1c74342015-07-07 16:54:23 -07002473 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002474 mLeftVolume = left;
2475 mRightVolume = right;
Glenn Kasten2799d742013-05-30 14:33:29 -07002476 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002477 mTrack->setVolume(left, right);
2478 }
2479}
2480
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002481status_t MediaPlayerService::AudioOutput::setPlaybackRate(const AudioPlaybackRate &rate)
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002482{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002483 ALOGV("setPlaybackRate(%f %f %d %d)",
2484 rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Andy Hungd1c74342015-07-07 16:54:23 -07002485 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002486 if (mTrack == 0) {
2487 // remember rate so that we can set it when the track is opened
2488 mPlaybackRate = rate;
2489 return OK;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002490 }
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002491 status_t res = mTrack->setPlaybackRate(rate);
2492 if (res != NO_ERROR) {
2493 return res;
2494 }
2495 // rate.mSpeed is always greater than 0 if setPlaybackRate succeeded
2496 CHECK_GT(rate.mSpeed, 0.f);
2497 mPlaybackRate = rate;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002498 if (mSampleRateHz != 0) {
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002499 mMsecsPerFrame = 1E3f / (rate.mSpeed * mSampleRateHz);
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002500 }
2501 return res;
2502}
2503
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002504status_t MediaPlayerService::AudioOutput::getPlaybackRate(AudioPlaybackRate *rate)
2505{
2506 ALOGV("setPlaybackRate");
Andy Hungd1c74342015-07-07 16:54:23 -07002507 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002508 if (mTrack == 0) {
2509 return NO_INIT;
2510 }
2511 *rate = mTrack->getPlaybackRate();
2512 return NO_ERROR;
2513}
2514
Eric Laurent2beeb502010-07-16 07:43:46 -07002515status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
2516{
Steve Block3856b092011-10-20 11:56:00 +01002517 ALOGV("setAuxEffectSendLevel(%f)", level);
Andy Hungd1c74342015-07-07 16:54:23 -07002518 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002519 mSendLevel = level;
Glenn Kasten2799d742013-05-30 14:33:29 -07002520 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002521 return mTrack->setAuxEffectSendLevel(level);
2522 }
2523 return NO_ERROR;
2524}
2525
2526status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
2527{
Steve Block3856b092011-10-20 11:56:00 +01002528 ALOGV("attachAuxEffect(%d)", effectId);
Andy Hungd1c74342015-07-07 16:54:23 -07002529 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002530 mAuxEffectId = effectId;
Glenn Kasten2799d742013-05-30 14:33:29 -07002531 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002532 return mTrack->attachAuxEffect(effectId);
2533 }
2534 return NO_ERROR;
2535}
2536
jiabin156c6872017-10-06 09:47:15 -07002537status_t MediaPlayerService::AudioOutput::setOutputDevice(audio_port_handle_t deviceId)
2538{
2539 ALOGV("setOutputDevice(%d)", deviceId);
2540 Mutex::Autolock lock(mLock);
2541 mSelectedDeviceId = deviceId;
2542 if (mTrack != 0) {
2543 return mTrack->setOutputDevice(deviceId);
2544 }
2545 return NO_ERROR;
2546}
2547
2548status_t MediaPlayerService::AudioOutput::getRoutedDeviceId(audio_port_handle_t* deviceId)
2549{
2550 ALOGV("getRoutedDeviceId");
2551 Mutex::Autolock lock(mLock);
2552 if (mTrack != 0) {
jiabin161b64fc2017-11-17 09:31:48 -08002553 mRoutedDeviceId = mTrack->getRoutedDeviceId();
jiabin156c6872017-10-06 09:47:15 -07002554 }
jiabin161b64fc2017-11-17 09:31:48 -08002555 *deviceId = mRoutedDeviceId;
2556 return NO_ERROR;
jiabin156c6872017-10-06 09:47:15 -07002557}
2558
2559status_t MediaPlayerService::AudioOutput::enableAudioDeviceCallback(bool enabled)
2560{
2561 ALOGV("enableAudioDeviceCallback, %d", enabled);
2562 Mutex::Autolock lock(mLock);
2563 mDeviceCallbackEnabled = enabled;
2564 if (mTrack != 0) {
2565 status_t status;
2566 if (enabled) {
2567 status = mTrack->addAudioDeviceCallback(mDeviceCallback.promote());
2568 } else {
2569 status = mTrack->removeAudioDeviceCallback(mDeviceCallback.promote());
2570 }
2571 return status;
2572 }
2573 return NO_ERROR;
2574}
2575
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002576VolumeShaper::Status MediaPlayerService::AudioOutput::applyVolumeShaper(
2577 const sp<VolumeShaper::Configuration>& configuration,
2578 const sp<VolumeShaper::Operation>& operation)
2579{
2580 Mutex::Autolock lock(mLock);
2581 ALOGV("AudioOutput::applyVolumeShaper");
Andy Hung4ef88d72017-02-21 19:47:53 -08002582
Andy Hung4ef88d72017-02-21 19:47:53 -08002583 mVolumeHandler->setIdIfNecessary(configuration);
Andy Hung39399b62017-04-21 15:07:45 -07002584
2585 VolumeShaper::Status status;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002586 if (mTrack != 0) {
Andy Hung39399b62017-04-21 15:07:45 -07002587 status = mTrack->applyVolumeShaper(configuration, operation);
2588 if (status >= 0) {
2589 (void)mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hungf3702642017-05-05 17:33:32 -07002590 if (mTrack->isPlaying()) { // match local AudioTrack to properly restore.
2591 mVolumeHandler->setStarted();
2592 }
Andy Hung39399b62017-04-21 15:07:45 -07002593 }
Andy Hung4ef88d72017-02-21 19:47:53 -08002594 } else {
Andy Hungc01eddb2017-07-21 16:42:41 -07002595 // VolumeShapers are not affected when a track moves between players for
2596 // gapless playback (setNextMediaPlayer).
2597 // We forward VolumeShaper operations that do not change configuration
2598 // to the new player so that unducking may occur as expected.
2599 // Unducking is an idempotent operation, same if applied back-to-back.
2600 if (configuration->getType() == VolumeShaper::Configuration::TYPE_ID
2601 && mNextOutput != nullptr) {
2602 ALOGV("applyVolumeShaper: Attempting to forward missed operation: %s %s",
2603 configuration->toString().c_str(), operation->toString().c_str());
2604 Mutex::Autolock nextLock(mNextOutput->mLock);
2605
2606 // recycled track should be forwarded from this AudioSink by switchToNextOutput
2607 sp<AudioTrack> track = mNextOutput->mRecycledTrack;
2608 if (track != nullptr) {
2609 ALOGD("Forward VolumeShaper operation to recycled track %p", track.get());
2610 (void)track->applyVolumeShaper(configuration, operation);
2611 } else {
2612 // There is a small chance that the unduck occurs after the next
2613 // player has already started, but before it is registered to receive
2614 // the unduck command.
2615 track = mNextOutput->mTrack;
2616 if (track != nullptr) {
2617 ALOGD("Forward VolumeShaper operation to track %p", track.get());
2618 (void)track->applyVolumeShaper(configuration, operation);
2619 }
2620 }
2621 }
Andy Hung39399b62017-04-21 15:07:45 -07002622 status = mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002623 }
Andy Hung39399b62017-04-21 15:07:45 -07002624 return status;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002625}
2626
2627sp<VolumeShaper::State> MediaPlayerService::AudioOutput::getVolumeShaperState(int id)
2628{
2629 Mutex::Autolock lock(mLock);
2630 if (mTrack != 0) {
2631 return mTrack->getVolumeShaperState(id);
Andy Hung4ef88d72017-02-21 19:47:53 -08002632 } else {
2633 return mVolumeHandler->getVolumeShaperState(id);
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002634 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002635}
2636
Andreas Huber20111aa2009-07-14 16:56:47 -07002637// static
2638void MediaPlayerService::AudioOutput::CallbackWrapper(
Glenn Kastend217a8c2011-06-01 15:20:35 -07002639 int event, void *cookie, void *info) {
Steve Block3856b092011-10-20 11:56:00 +01002640 //ALOGV("callbackwrapper");
Marco Nelissen6b74d672012-02-28 16:07:44 -08002641 CallbackData *data = (CallbackData*)cookie;
Andy Hungd1c74342015-07-07 16:54:23 -07002642 // lock to ensure we aren't caught in the middle of a track switch.
Marco Nelissen6b74d672012-02-28 16:07:44 -08002643 data->lock();
2644 AudioOutput *me = data->getOutput();
Andreas Huber20111aa2009-07-14 16:56:47 -07002645 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002646 if (me == NULL) {
2647 // no output set, likely because the track was scheduled to be reused
2648 // by another player, but the format turned out to be incompatible.
2649 data->unlock();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002650 if (buffer != NULL) {
2651 buffer->size = 0;
2652 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08002653 return;
2654 }
Andreas Huber20111aa2009-07-14 16:56:47 -07002655
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002656 switch(event) {
2657 case AudioTrack::EVENT_MORE_DATA: {
2658 size_t actualSize = (*me->mCallback)(
2659 me, buffer->raw, buffer->size, me->mCallbackCookie,
2660 CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002661
Andy Hung719b46b2015-05-31 22:18:25 -07002662 // Log when no data is returned from the callback.
2663 // (1) We may have no data (especially with network streaming sources).
2664 // (2) We may have reached the EOS and the audio track is not stopped yet.
2665 // Note that AwesomePlayer/AudioPlayer will only return zero size when it reaches the EOS.
2666 // NuPlayerRenderer will return zero when it doesn't have data (it doesn't block to fill).
2667 //
2668 // This is a benign busy-wait, with the next data request generated 10 ms or more later;
2669 // nevertheless for power reasons, we don't want to see too many of these.
Andreas Huber2e8ffaf2010-02-18 16:45:13 -08002670
Andy Hung719b46b2015-05-31 22:18:25 -07002671 ALOGV_IF(actualSize == 0 && buffer->size > 0, "callbackwrapper: empty buffer returned");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002672
2673 buffer->size = actualSize;
2674 } break;
2675
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002676 case AudioTrack::EVENT_STREAM_END:
Andy Hung719b46b2015-05-31 22:18:25 -07002677 // currently only occurs for offloaded callbacks
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002678 ALOGV("callbackwrapper: deliver EVENT_STREAM_END");
2679 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2680 me->mCallbackCookie, CB_EVENT_STREAM_END);
2681 break;
2682
2683 case AudioTrack::EVENT_NEW_IAUDIOTRACK :
2684 ALOGV("callbackwrapper: deliver EVENT_TEAR_DOWN");
2685 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2686 me->mCallbackCookie, CB_EVENT_TEAR_DOWN);
2687 break;
2688
Glenn Kasten421743b2015-06-01 08:18:08 -07002689 case AudioTrack::EVENT_UNDERRUN:
Andy Hung719b46b2015-05-31 22:18:25 -07002690 // This occurs when there is no data available, typically
Glenn Kasten421743b2015-06-01 08:18:08 -07002691 // when there is a failure to supply data to the AudioTrack. It can also
2692 // occur in non-offloaded mode when the audio device comes out of standby.
2693 //
Andy Hung719b46b2015-05-31 22:18:25 -07002694 // If an AudioTrack underruns it outputs silence. Since this happens suddenly
2695 // it may sound like an audible pop or glitch.
2696 //
2697 // The underrun event is sent once per track underrun; the condition is reset
2698 // when more data is sent to the AudioTrack.
Eric Laurente93cc032016-05-05 10:15:10 -07002699 ALOGD("callbackwrapper: EVENT_UNDERRUN (discarded)");
Glenn Kasten421743b2015-06-01 08:18:08 -07002700 break;
2701
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002702 default:
2703 ALOGE("received unknown event type: %d inside CallbackWrapper !", event);
Andreas Huber51c1e0e2011-04-04 11:43:40 -07002704 }
2705
Marco Nelissen6b74d672012-02-28 16:07:44 -08002706 data->unlock();
Andreas Huber20111aa2009-07-14 16:56:47 -07002707}
2708
Glenn Kastend848eb42016-03-08 13:42:11 -08002709audio_session_t MediaPlayerService::AudioOutput::getSessionId() const
Eric Laurent8c563ed2010-10-07 18:23:03 -07002710{
Andy Hungd1c74342015-07-07 16:54:23 -07002711 Mutex::Autolock lock(mLock);
Eric Laurent8c563ed2010-10-07 18:23:03 -07002712 return mSessionId;
2713}
2714
Eric Laurent6f59db12013-07-26 17:16:50 -07002715uint32_t MediaPlayerService::AudioOutput::getSampleRate() const
2716{
Andy Hungd1c74342015-07-07 16:54:23 -07002717 Mutex::Autolock lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -07002718 if (mTrack == 0) return 0;
2719 return mTrack->getSampleRate();
2720}
2721
Andy Hungf2c87b32016-04-07 19:49:29 -07002722int64_t MediaPlayerService::AudioOutput::getBufferDurationInUs() const
2723{
2724 Mutex::Autolock lock(mLock);
2725 if (mTrack == 0) {
2726 return 0;
2727 }
2728 int64_t duration;
2729 if (mTrack->getBufferDurationInUs(&duration) != OK) {
2730 return 0;
2731 }
2732 return duration;
2733}
2734
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002735////////////////////////////////////////////////////////////////////////////////
2736
2737struct CallbackThread : public Thread {
2738 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
2739 MediaPlayerBase::AudioSink::AudioCallback cb,
2740 void *cookie);
2741
2742protected:
2743 virtual ~CallbackThread();
2744
2745 virtual bool threadLoop();
2746
2747private:
2748 wp<MediaPlayerBase::AudioSink> mSink;
2749 MediaPlayerBase::AudioSink::AudioCallback mCallback;
2750 void *mCookie;
2751 void *mBuffer;
2752 size_t mBufferSize;
2753
2754 CallbackThread(const CallbackThread &);
2755 CallbackThread &operator=(const CallbackThread &);
2756};
2757
2758CallbackThread::CallbackThread(
2759 const wp<MediaPlayerBase::AudioSink> &sink,
2760 MediaPlayerBase::AudioSink::AudioCallback cb,
2761 void *cookie)
2762 : mSink(sink),
2763 mCallback(cb),
2764 mCookie(cookie),
2765 mBuffer(NULL),
2766 mBufferSize(0) {
2767}
2768
2769CallbackThread::~CallbackThread() {
2770 if (mBuffer) {
2771 free(mBuffer);
2772 mBuffer = NULL;
2773 }
2774}
2775
2776bool CallbackThread::threadLoop() {
2777 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
2778 if (sink == NULL) {
2779 return false;
2780 }
2781
2782 if (mBuffer == NULL) {
2783 mBufferSize = sink->bufferSize();
2784 mBuffer = malloc(mBufferSize);
2785 }
2786
2787 size_t actualSize =
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002788 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie,
2789 MediaPlayerBase::AudioSink::CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002790
2791 if (actualSize > 0) {
2792 sink->write(mBuffer, actualSize);
Andy Hunga31335a2014-08-20 17:37:59 -07002793 // Could return false on sink->write() error or short count.
2794 // Not necessarily appropriate but would work for AudioCache behavior.
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002795 }
2796
2797 return true;
2798}
2799
2800////////////////////////////////////////////////////////////////////////////////
2801
Chong Zhange5b9b692017-05-11 11:44:56 -07002802void MediaPlayerService::addBatteryData(uint32_t params) {
2803 mBatteryTracker.addBatteryData(params);
2804}
2805
2806status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
2807 return mBatteryTracker.pullBatteryData(reply);
2808}
2809
2810MediaPlayerService::BatteryTracker::BatteryTracker() {
2811 mBatteryAudio.refCount = 0;
2812 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2813 mBatteryAudio.deviceOn[i] = 0;
2814 mBatteryAudio.lastTime[i] = 0;
2815 mBatteryAudio.totalTime[i] = 0;
2816 }
2817 // speaker is on by default
2818 mBatteryAudio.deviceOn[SPEAKER] = 1;
2819
2820 // reset battery stats
2821 // if the mediaserver has crashed, battery stats could be left
2822 // in bad state, reset the state upon service start.
2823 BatteryNotifier::getInstance().noteResetVideo();
2824}
2825
2826void MediaPlayerService::BatteryTracker::addBatteryData(uint32_t params)
Gloria Wang7cf180c2011-02-19 18:37:57 -08002827{
2828 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002829
2830 int32_t time = systemTime() / 1000000L;
2831
2832 // change audio output devices. This notification comes from AudioFlinger
2833 if ((params & kBatteryDataSpeakerOn)
2834 || (params & kBatteryDataOtherAudioDeviceOn)) {
2835
2836 int deviceOn[NUM_AUDIO_DEVICES];
2837 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2838 deviceOn[i] = 0;
2839 }
2840
2841 if ((params & kBatteryDataSpeakerOn)
2842 && (params & kBatteryDataOtherAudioDeviceOn)) {
2843 deviceOn[SPEAKER_AND_OTHER] = 1;
2844 } else if (params & kBatteryDataSpeakerOn) {
2845 deviceOn[SPEAKER] = 1;
2846 } else {
2847 deviceOn[OTHER_AUDIO_DEVICE] = 1;
2848 }
2849
2850 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2851 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
2852
2853 if (mBatteryAudio.refCount > 0) { // if playing audio
2854 if (!deviceOn[i]) {
2855 mBatteryAudio.lastTime[i] += time;
2856 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2857 mBatteryAudio.lastTime[i] = 0;
2858 } else {
2859 mBatteryAudio.lastTime[i] = 0 - time;
2860 }
2861 }
2862
2863 mBatteryAudio.deviceOn[i] = deviceOn[i];
2864 }
2865 }
2866 return;
2867 }
2868
Marco Nelissenb7848f12014-12-04 08:57:56 -08002869 // an audio stream is started
Gloria Wang9ee159b2011-02-24 14:51:45 -08002870 if (params & kBatteryDataAudioFlingerStart) {
2871 // record the start time only if currently no other audio
2872 // is being played
2873 if (mBatteryAudio.refCount == 0) {
2874 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2875 if (mBatteryAudio.deviceOn[i]) {
2876 mBatteryAudio.lastTime[i] -= time;
2877 }
2878 }
2879 }
2880
2881 mBatteryAudio.refCount ++;
2882 return;
2883
2884 } else if (params & kBatteryDataAudioFlingerStop) {
2885 if (mBatteryAudio.refCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002886 ALOGW("Battery track warning: refCount is <= 0");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002887 return;
2888 }
2889
2890 // record the stop time only if currently this is the only
2891 // audio being played
2892 if (mBatteryAudio.refCount == 1) {
2893 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2894 if (mBatteryAudio.deviceOn[i]) {
2895 mBatteryAudio.lastTime[i] += time;
2896 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2897 mBatteryAudio.lastTime[i] = 0;
2898 }
2899 }
2900 }
2901
2902 mBatteryAudio.refCount --;
2903 return;
2904 }
2905
Andy Hung1afd0982016-11-08 16:13:44 -08002906 uid_t uid = IPCThreadState::self()->getCallingUid();
Gloria Wang7cf180c2011-02-19 18:37:57 -08002907 if (uid == AID_MEDIA) {
2908 return;
2909 }
2910 int index = mBatteryData.indexOfKey(uid);
Gloria Wang7cf180c2011-02-19 18:37:57 -08002911
2912 if (index < 0) { // create a new entry for this UID
2913 BatteryUsageInfo info;
2914 info.audioTotalTime = 0;
2915 info.videoTotalTime = 0;
2916 info.audioLastTime = 0;
2917 info.videoLastTime = 0;
2918 info.refCount = 0;
2919
Gloria Wang9ee159b2011-02-24 14:51:45 -08002920 if (mBatteryData.add(uid, info) == NO_MEMORY) {
Steve Block29357bc2012-01-06 19:20:56 +00002921 ALOGE("Battery track error: no memory for new app");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002922 return;
2923 }
Gloria Wang7cf180c2011-02-19 18:37:57 -08002924 }
2925
2926 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
2927
2928 if (params & kBatteryDataCodecStarted) {
2929 if (params & kBatteryDataTrackAudio) {
2930 info.audioLastTime -= time;
2931 info.refCount ++;
2932 }
2933 if (params & kBatteryDataTrackVideo) {
2934 info.videoLastTime -= time;
2935 info.refCount ++;
2936 }
2937 } else {
2938 if (info.refCount == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002939 ALOGW("Battery track warning: refCount is already 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002940 return;
2941 } else if (info.refCount < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00002942 ALOGE("Battery track error: refCount < 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002943 mBatteryData.removeItem(uid);
2944 return;
2945 }
2946
2947 if (params & kBatteryDataTrackAudio) {
2948 info.audioLastTime += time;
2949 info.refCount --;
2950 }
2951 if (params & kBatteryDataTrackVideo) {
2952 info.videoLastTime += time;
2953 info.refCount --;
2954 }
2955
2956 // no stream is being played by this UID
2957 if (info.refCount == 0) {
2958 info.audioTotalTime += info.audioLastTime;
2959 info.audioLastTime = 0;
2960 info.videoTotalTime += info.videoLastTime;
2961 info.videoLastTime = 0;
2962 }
2963 }
2964}
2965
Chong Zhange5b9b692017-05-11 11:44:56 -07002966status_t MediaPlayerService::BatteryTracker::pullBatteryData(Parcel* reply) {
Gloria Wang7cf180c2011-02-19 18:37:57 -08002967 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002968
2969 // audio output devices usage
2970 int32_t time = systemTime() / 1000000L; //in ms
2971 int32_t totalTime;
2972
2973 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2974 totalTime = mBatteryAudio.totalTime[i];
2975
2976 if (mBatteryAudio.deviceOn[i]
2977 && (mBatteryAudio.lastTime[i] != 0)) {
2978 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
2979 totalTime += tmpTime;
2980 }
2981
2982 reply->writeInt32(totalTime);
2983 // reset the total time
2984 mBatteryAudio.totalTime[i] = 0;
2985 }
2986
2987 // codec usage
Gloria Wang7cf180c2011-02-19 18:37:57 -08002988 BatteryUsageInfo info;
2989 int size = mBatteryData.size();
2990
2991 reply->writeInt32(size);
2992 int i = 0;
2993
2994 while (i < size) {
2995 info = mBatteryData.valueAt(i);
2996
2997 reply->writeInt32(mBatteryData.keyAt(i)); //UID
2998 reply->writeInt32(info.audioTotalTime);
2999 reply->writeInt32(info.videoTotalTime);
3000
3001 info.audioTotalTime = 0;
3002 info.videoTotalTime = 0;
3003
3004 // remove the UID entry where no stream is being played
3005 if (info.refCount <= 0) {
3006 mBatteryData.removeItemsAt(i);
3007 size --;
3008 i --;
3009 }
3010 i++;
3011 }
3012 return NO_ERROR;
3013}
nikoa64c8c72009-07-20 15:07:26 -07003014} // namespace android