blob: d278a0197696ee2b3f24f3b2b93290e65f70629e [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>
Philip P. Moltmannbda45752020-07-17 16:41:18 -070052#include <media/AidlConversion.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080053#include <media/IMediaHTTPService.h>
Jeff Brown2013a542012-09-04 21:38:42 -070054#include <media/IRemoteDisplay.h>
55#include <media/IRemoteDisplayClient.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080056#include <media/MediaPlayerInterface.h>
57#include <media/mediarecorder.h>
58#include <media/MediaMetadataRetrieverInterface.h>
nikoa64c8c72009-07-20 15:07:26 -070059#include <media/Metadata.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080060#include <media/AudioTrack.h>
Dongwon Kangd91dc5a2017-10-10 00:07:09 -070061#include <media/stagefright/InterfaceUtils.h>
Wonsik Kim6f675772019-08-20 17:06:53 -070062#include <media/stagefright/MediaCodecConstants.h>
Lajos Molnar1381d4b2014-08-07 15:18:35 -070063#include <media/stagefright/MediaCodecList.h>
Eric Laurent9cb839a2011-09-27 09:48:56 -070064#include <media/stagefright/MediaErrors.h>
Marco Nelissen83b0fd92015-09-16 13:48:07 -070065#include <media/stagefright/Utils.h>
Marco Nelissen42057ce2019-09-23 12:15:57 -070066#include <media/stagefright/FoundationUtils.h>
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +010067#include <media/stagefright/foundation/ADebug.h>
Marco Nelissenf09611f2015-02-13 14:12:42 -080068#include <media/stagefright/foundation/ALooperRoster.h>
Chong Zhang181fd9b2017-02-16 15:53:03 -080069#include <media/stagefright/SurfaceUtils.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070070#include <mediautils/BatteryNotifier.h>
Andy Hunge9eb03e2020-04-04 14:08:23 -070071#include <mediautils/MemoryLeakTrackUtil.h>
Andy Hung53541292016-04-13 16:48:51 -070072#include <memunreachable/memunreachable.h>
Dima Zavin64760242011-05-11 14:15:23 -070073#include <system/audio.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070074
Gloria Wang7cf180c2011-02-19 18:37:57 -080075#include <private/android_filesystem_config.h>
76
James Dong559bf282012-03-28 10:29:14 -070077#include "ActivityManager.h"
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080078#include "MediaRecorderClient.h"
79#include "MediaPlayerService.h"
80#include "MetadataRetrieverClient.h"
John Grossman44a7e422012-06-21 17:29:24 -070081#include "MediaPlayerFactory.h"
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080082
Nicolas Catania14d27472009-07-13 14:37:49 -070083#include "TestPlayerStub.h"
Andreas Huberf9334412010-12-15 15:17:42 -080084#include "nuplayer/NuPlayerDriver.h"
Andreas Huber20111aa2009-07-14 16:56:47 -070085
Andreas Hubered3e3e02012-03-26 11:13:27 -070086
Wei Jia502c2f42017-07-13 17:47:56 -070087static const int kDumpLockRetries = 50;
88static const int kDumpLockSleepUs = 20000;
89
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070090namespace {
nikoa64c8c72009-07-20 15:07:26 -070091using android::media::Metadata;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070092using android::status_t;
93using android::OK;
94using android::BAD_VALUE;
95using android::NOT_ENOUGH_DATA;
96using android::Parcel;
Ivan Lozano8cf3a072017-08-09 09:01:33 -070097using android::media::VolumeShaper;
Svet Ganov33761132021-05-13 22:51:08 +000098using android::content::AttributionSourceState;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070099
100// Max number of entries in the filter.
101const int kMaxFilterSize = 64; // I pulled that out of thin air.
102
Andy Hungff874dc2016-04-11 16:49:09 -0700103const float kMaxRequiredSpeed = 8.0f; // for PCM tracks allow up to 8x speedup.
104
nikoa64c8c72009-07-20 15:07:26 -0700105// FIXME: Move all the metadata related function in the Metadata.cpp
nikod608a812009-07-16 16:39:53 -0700106
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700107
108// Unmarshall a filter from a Parcel.
109// Filter format in a parcel:
110//
111// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
112// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
113// | number of entries (n) |
114// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
115// | metadata type 1 |
116// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
117// | metadata type 2 |
118// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
119// ....
120// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
121// | metadata type n |
122// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
123//
124// @param p Parcel that should start with a filter.
125// @param[out] filter On exit contains the list of metadata type to be
126// filtered.
127// @param[out] status On exit contains the status code to be returned.
128// @return true if the parcel starts with a valid filter.
129bool unmarshallFilter(const Parcel& p,
nikoa64c8c72009-07-20 15:07:26 -0700130 Metadata::Filter *filter,
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700131 status_t *status)
132{
Nicolas Catania48290382009-07-10 13:53:06 -0700133 int32_t val;
134 if (p.readInt32(&val) != OK)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700135 {
Steve Block29357bc2012-01-06 19:20:56 +0000136 ALOGE("Failed to read filter's length");
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700137 *status = NOT_ENOUGH_DATA;
138 return false;
139 }
140
Nicolas Catania48290382009-07-10 13:53:06 -0700141 if( val > kMaxFilterSize || val < 0)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700142 {
Steve Block29357bc2012-01-06 19:20:56 +0000143 ALOGE("Invalid filter len %d", val);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700144 *status = BAD_VALUE;
145 return false;
146 }
147
Nicolas Catania48290382009-07-10 13:53:06 -0700148 const size_t num = val;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700149
150 filter->clear();
Nicolas Catania48290382009-07-10 13:53:06 -0700151 filter->setCapacity(num);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700152
nikoa64c8c72009-07-20 15:07:26 -0700153 size_t size = num * sizeof(Metadata::Type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700154
Nicolas Catania48290382009-07-10 13:53:06 -0700155
156 if (p.dataAvail() < size)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700157 {
Andy Hung833b4752016-04-04 17:15:48 -0700158 ALOGE("Filter too short expected %zu but got %zu", size, p.dataAvail());
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700159 *status = NOT_ENOUGH_DATA;
160 return false;
161 }
162
nikoa64c8c72009-07-20 15:07:26 -0700163 const Metadata::Type *data =
164 static_cast<const Metadata::Type*>(p.readInplace(size));
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700165
Nicolas Catania48290382009-07-10 13:53:06 -0700166 if (NULL == data)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700167 {
Steve Block29357bc2012-01-06 19:20:56 +0000168 ALOGE("Filter had no data");
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700169 *status = BAD_VALUE;
170 return false;
171 }
172
173 // TODO: The stl impl of vector would be more efficient here
174 // because it degenerates into a memcpy on pod types. Try to
175 // replace later or use stl::set.
Nicolas Catania48290382009-07-10 13:53:06 -0700176 for (size_t i = 0; i < num; ++i)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700177 {
Nicolas Catania48290382009-07-10 13:53:06 -0700178 filter->add(*data);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700179 ++data;
180 }
181 *status = OK;
182 return true;
183}
184
Nicolas Catania48290382009-07-10 13:53:06 -0700185// @param filter Of metadata type.
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700186// @param val To be searched.
187// @return true if a match was found.
nikoa64c8c72009-07-20 15:07:26 -0700188bool findMetadata(const Metadata::Filter& filter, const int32_t val)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700189{
190 // Deal with empty and ANY right away
191 if (filter.isEmpty()) return false;
nikoa64c8c72009-07-20 15:07:26 -0700192 if (filter[0] == Metadata::kAny) return true;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700193
Nicolas Catania48290382009-07-10 13:53:06 -0700194 return filter.indexOf(val) >= 0;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700195}
196
197} // anonymous namespace
198
199
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700200namespace {
201using android::Parcel;
202using android::String16;
203
204// marshalling tag indicating flattened utf16 tags
205// keep in sync with frameworks/base/media/java/android/media/AudioAttributes.java
206const int32_t kAudioAttributesMarshallTagFlattenTags = 1;
207
208// Audio attributes format in a parcel:
209//
210// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
211// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
212// | usage |
213// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
214// | content_type |
215// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Hyejin Kim4f418f92014-09-05 15:50:03 +0900216// | source |
217// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700218// | flags |
219// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
220// | kAudioAttributesMarshallTagFlattenTags | // ignore tags if not found
221// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
222// | flattened tags in UTF16 |
223// | ... |
224// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
225//
226// @param p Parcel that contains audio attributes.
227// @param[out] attributes On exit points to an initialized audio_attributes_t structure
228// @param[out] status On exit contains the status code to be returned.
229void unmarshallAudioAttributes(const Parcel& parcel, audio_attributes_t *attributes)
230{
231 attributes->usage = (audio_usage_t) parcel.readInt32();
232 attributes->content_type = (audio_content_type_t) parcel.readInt32();
Hyejin Kim4f418f92014-09-05 15:50:03 +0900233 attributes->source = (audio_source_t) parcel.readInt32();
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700234 attributes->flags = (audio_flags_mask_t) parcel.readInt32();
235 const bool hasFlattenedTag = (parcel.readInt32() == kAudioAttributesMarshallTagFlattenTags);
236 if (hasFlattenedTag) {
237 // the tags are UTF16, convert to UTF8
238 String16 tags = parcel.readString16();
239 ssize_t realTagSize = utf16_to_utf8_length(tags.string(), tags.size());
240 if (realTagSize <= 0) {
241 strcpy(attributes->tags, "");
242 } else {
243 // copy the flattened string into the attributes as the destination for the conversion:
244 // copying array size -1, array for tags was calloc'd, no need to NULL-terminate it
245 size_t tagSize = realTagSize > AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 ?
246 AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 : realTagSize;
Sergio Giro1d3f4272016-06-28 18:24:52 +0100247 utf16_to_utf8(tags.string(), tagSize, attributes->tags,
248 sizeof(attributes->tags) / sizeof(attributes->tags[0]));
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700249 }
250 } else {
251 ALOGE("unmarshallAudioAttributes() received unflattened tags, ignoring tag values");
252 strcpy(attributes->tags, "");
253 }
254}
255} // anonymous namespace
256
257
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800258namespace android {
259
Marco Nelissenf09611f2015-02-13 14:12:42 -0800260extern ALooperRoster gLooperRoster;
261
262
Dave Burked681bbb2011-08-30 14:39:17 +0100263static bool checkPermission(const char* permissionString) {
Dave Burked681bbb2011-08-30 14:39:17 +0100264 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
265 bool ok = checkCallingPermission(String16(permissionString));
Steve Block29357bc2012-01-06 19:20:56 +0000266 if (!ok) ALOGE("Request requires %s", permissionString);
Dave Burked681bbb2011-08-30 14:39:17 +0100267 return ok;
268}
269
Wonsik Kim6f675772019-08-20 17:06:53 -0700270static void dumpCodecDetails(int fd, const sp<IMediaCodecList> &codecList, bool queryDecoders) {
271 const size_t SIZE = 256;
272 char buffer[SIZE];
273 String8 result;
274
275 const char *codecType = queryDecoders? "Decoder" : "Encoder";
276 snprintf(buffer, SIZE - 1, "\n%s infos by media types:\n"
277 "=============================\n", codecType);
278 result.append(buffer);
279
280 size_t numCodecs = codecList->countCodecs();
281
282 // gather all media types supported by codec class, and link to codecs that support them
283 KeyedVector<AString, Vector<sp<MediaCodecInfo>>> allMediaTypes;
284 for (size_t codec_ix = 0; codec_ix < numCodecs; ++codec_ix) {
285 sp<MediaCodecInfo> info = codecList->getCodecInfo(codec_ix);
286 if (info->isEncoder() == !queryDecoders) {
287 Vector<AString> supportedMediaTypes;
288 info->getSupportedMediaTypes(&supportedMediaTypes);
289 if (!supportedMediaTypes.size()) {
290 snprintf(buffer, SIZE - 1, "warning: %s does not support any media types\n",
291 info->getCodecName());
292 result.append(buffer);
293 } else {
294 for (const AString &mediaType : supportedMediaTypes) {
295 if (allMediaTypes.indexOfKey(mediaType) < 0) {
296 allMediaTypes.add(mediaType, Vector<sp<MediaCodecInfo>>());
297 }
298 allMediaTypes.editValueFor(mediaType).add(info);
299 }
300 }
301 }
302 }
303
304 KeyedVector<AString, bool> visitedCodecs;
305 for (size_t type_ix = 0; type_ix < allMediaTypes.size(); ++type_ix) {
306 const AString &mediaType = allMediaTypes.keyAt(type_ix);
307 snprintf(buffer, SIZE - 1, "\nMedia type '%s':\n", mediaType.c_str());
308 result.append(buffer);
309
310 for (const sp<MediaCodecInfo> &info : allMediaTypes.valueAt(type_ix)) {
311 sp<MediaCodecInfo::Capabilities> caps = info->getCapabilitiesFor(mediaType.c_str());
312 if (caps == NULL) {
313 snprintf(buffer, SIZE - 1, "warning: %s does not have capabilities for type %s\n",
314 info->getCodecName(), mediaType.c_str());
315 result.append(buffer);
316 continue;
317 }
318 snprintf(buffer, SIZE - 1, " %s \"%s\" supports\n",
319 codecType, info->getCodecName());
320 result.append(buffer);
321
322 auto printList = [&](const char *type, const Vector<AString> &values){
323 snprintf(buffer, SIZE - 1, " %s: [", type);
324 result.append(buffer);
325 for (size_t j = 0; j < values.size(); ++j) {
326 snprintf(buffer, SIZE - 1, "\n %s%s", values[j].c_str(),
327 j == values.size() - 1 ? " " : ",");
328 result.append(buffer);
329 }
330 result.append("]\n");
331 };
332
333 if (visitedCodecs.indexOfKey(info->getCodecName()) < 0) {
334 visitedCodecs.add(info->getCodecName(), true);
335 {
336 Vector<AString> aliases;
337 info->getAliases(&aliases);
338 // quote alias
339 for (AString &alias : aliases) {
340 alias.insert("\"", 1, 0);
341 alias.append('"');
342 }
343 printList("aliases", aliases);
344 }
345 {
346 uint32_t attrs = info->getAttributes();
347 Vector<AString> list;
348 list.add(AStringPrintf("encoder: %d",
349 !!(attrs & MediaCodecInfo::kFlagIsEncoder)));
350 list.add(AStringPrintf("vendor: %d",
351 !!(attrs & MediaCodecInfo::kFlagIsVendor)));
352 list.add(AStringPrintf("software-only: %d",
353 !!(attrs & MediaCodecInfo::kFlagIsSoftwareOnly)));
354 list.add(AStringPrintf("hw-accelerated: %d",
355 !!(attrs & MediaCodecInfo::kFlagIsHardwareAccelerated)));
356 printList(AStringPrintf("attributes: %#x", attrs).c_str(), list);
357 }
358
359 snprintf(buffer, SIZE - 1, " owner: \"%s\"\n", info->getOwnerName());
360 result.append(buffer);
361 snprintf(buffer, SIZE - 1, " rank: %u\n", info->getRank());
362 result.append(buffer);
363 } else {
364 result.append(" aliases, attributes, owner, rank: see above\n");
365 }
366
367 {
368 Vector<AString> list;
369 Vector<MediaCodecInfo::ProfileLevel> profileLevels;
370 caps->getSupportedProfileLevels(&profileLevels);
371 for (const MediaCodecInfo::ProfileLevel &pl : profileLevels) {
372 const char *niceProfile =
373 mediaType.equalsIgnoreCase(MIMETYPE_AUDIO_AAC)
374 ? asString_AACObject(pl.mProfile) :
375 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_MPEG2)
376 ? asString_MPEG2Profile(pl.mProfile) :
377 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_H263)
378 ? asString_H263Profile(pl.mProfile) :
379 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_MPEG4)
380 ? asString_MPEG4Profile(pl.mProfile) :
381 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_AVC)
382 ? asString_AVCProfile(pl.mProfile) :
383 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_VP8)
384 ? asString_VP8Profile(pl.mProfile) :
385 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_HEVC)
386 ? asString_HEVCProfile(pl.mProfile) :
387 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_VP9)
388 ? asString_VP9Profile(pl.mProfile) :
389 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_AV1)
390 ? asString_AV1Profile(pl.mProfile) : "??";
391 const char *niceLevel =
392 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_MPEG2)
393 ? asString_MPEG2Level(pl.mLevel) :
394 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_H263)
395 ? asString_H263Level(pl.mLevel) :
396 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_MPEG4)
397 ? asString_MPEG4Level(pl.mLevel) :
398 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_AVC)
399 ? asString_AVCLevel(pl.mLevel) :
400 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_VP8)
401 ? asString_VP8Level(pl.mLevel) :
402 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_HEVC)
403 ? asString_HEVCTierLevel(pl.mLevel) :
404 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_VP9)
405 ? asString_VP9Level(pl.mLevel) :
406 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_AV1)
407 ? asString_AV1Level(pl.mLevel) : "??";
408
409 list.add(AStringPrintf("% 5u/% 5u (%s/%s)",
410 pl.mProfile, pl.mLevel, niceProfile, niceLevel));
411 }
412 printList("profile/levels", list);
413 }
414
415 {
416 Vector<AString> list;
417 Vector<uint32_t> colors;
418 caps->getSupportedColorFormats(&colors);
419 for (uint32_t color : colors) {
420 list.add(AStringPrintf("%#x (%s)", color,
421 asString_ColorFormat((int32_t)color)));
422 }
423 printList("colors", list);
424 }
425
Wonsik Kimd579f3e2019-10-07 14:14:09 -0700426 result.append(" details: ");
427 result.append(caps->getDetails()->debugString(6).c_str());
428 result.append("\n");
Wonsik Kim6f675772019-08-20 17:06:53 -0700429 }
430 }
431 result.append("\n");
432 ::write(fd, result.string(), result.size());
433}
434
435
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800436// 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 -0800437/* static */ int MediaPlayerService::AudioOutput::mMinBufferCount = 4;
438/* static */ bool MediaPlayerService::AudioOutput::mIsOnEmulator = false;
439
440void MediaPlayerService::instantiate() {
441 defaultServiceManager()->addService(
442 String16("media.player"), new MediaPlayerService());
443}
444
445MediaPlayerService::MediaPlayerService()
446{
Steve Block3856b092011-10-20 11:56:00 +0100447 ALOGV("MediaPlayerService created");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800448 mNextConnId = 1;
Gloria Wang9ee159b2011-02-24 14:51:45 -0800449
John Grossman44a7e422012-06-21 17:29:24 -0700450 MediaPlayerFactory::registerBuiltinFactories();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800451}
452
453MediaPlayerService::~MediaPlayerService()
454{
Steve Block3856b092011-10-20 11:56:00 +0100455 ALOGV("MediaPlayerService destroyed");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800456}
457
Svet Ganov33761132021-05-13 22:51:08 +0000458sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(
459 const AttributionSourceState& attributionSource)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800460{
Svet Ganov33761132021-05-13 22:51:08 +0000461 // TODO b/182392769: use attribution source util
462 AttributionSourceState verifiedAttributionSource = attributionSource;
463 verifiedAttributionSource.uid = VALUE_OR_FATAL(
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700464 legacy2aidl_uid_t_int32_t(IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +0000465 verifiedAttributionSource.pid = VALUE_OR_FATAL(
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700466 legacy2aidl_pid_t_int32_t(IPCThreadState::self()->getCallingPid()));
467 sp<MediaRecorderClient> recorder =
Svet Ganov33761132021-05-13 22:51:08 +0000468 new MediaRecorderClient(this, verifiedAttributionSource);
Gloria Wangdac6a312009-10-29 15:46:37 -0700469 wp<MediaRecorderClient> w = recorder;
470 Mutex::Autolock lock(mLock);
471 mMediaRecorderClients.add(w);
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700472 ALOGV("Create new media recorder client from pid %s",
Svet Ganov33761132021-05-13 22:51:08 +0000473 verifiedAttributionSource.toString().c_str());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800474 return recorder;
475}
476
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -0700477void MediaPlayerService::removeMediaRecorderClient(const wp<MediaRecorderClient>& client)
Gloria Wangdac6a312009-10-29 15:46:37 -0700478{
479 Mutex::Autolock lock(mLock);
480 mMediaRecorderClients.remove(client);
Steve Block3856b092011-10-20 11:56:00 +0100481 ALOGV("Delete media recorder client");
Gloria Wangdac6a312009-10-29 15:46:37 -0700482}
483
Glenn Kastenf37971f2012-02-03 11:06:53 -0800484sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800485{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800486 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800487 sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
Steve Block3856b092011-10-20 11:56:00 +0100488 ALOGV("Create new media retriever from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800489 return retriever;
490}
491
Glenn Kastenf37971f2012-02-03 11:06:53 -0800492sp<IMediaPlayer> MediaPlayerService::create(const sp<IMediaPlayerClient>& client,
Svet Ganov33761132021-05-13 22:51:08 +0000493 audio_session_t audioSessionId, const AttributionSourceState& attributionSource)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800494{
495 int32_t connId = android_atomic_inc(&mNextConnId);
Svet Ganov33761132021-05-13 22:51:08 +0000496 // TODO b/182392769: use attribution source util
497 AttributionSourceState verifiedAttributionSource = attributionSource;
498 verifiedAttributionSource.pid = VALUE_OR_FATAL(
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700499 legacy2aidl_pid_t_int32_t(IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +0000500 verifiedAttributionSource.uid = VALUE_OR_FATAL(
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700501 legacy2aidl_uid_t_int32_t(IPCThreadState::self()->getCallingUid()));
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700502
503 sp<Client> c = new Client(
Svet Ganov33761132021-05-13 22:51:08 +0000504 this, verifiedAttributionSource, connId, client, audioSessionId);
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700505
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700506 ALOGV("Create new client(%d) from %s, ", connId,
Svet Ganov33761132021-05-13 22:51:08 +0000507 verifiedAttributionSource.toString().c_str());
Dave Burked681bbb2011-08-30 14:39:17 +0100508
509 wp<Client> w = c;
510 {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800511 Mutex::Autolock lock(mLock);
512 mClients.add(w);
513 }
Andreas Hubere2b10282010-11-23 11:41:34 -0800514 return c;
515}
516
Lajos Molnar1381d4b2014-08-07 15:18:35 -0700517sp<IMediaCodecList> MediaPlayerService::getCodecList() const {
518 return MediaCodecList::getLocalInstance();
519}
520
Jeff Brown2013a542012-09-04 21:38:42 -0700521sp<IRemoteDisplay> MediaPlayerService::listenForRemoteDisplay(
Chong Zhangd0a98fa2017-09-14 17:43:10 -0700522 const String16 &/*opPackageName*/,
523 const sp<IRemoteDisplayClient>& /*client*/,
524 const String8& /*iface*/) {
525 ALOGE("listenForRemoteDisplay is no longer supported!");
Jeff Brownaba33d52012-09-07 17:38:58 -0700526
Chong Zhangd0a98fa2017-09-14 17:43:10 -0700527 return NULL;
Jeff Brown2013a542012-09-04 21:38:42 -0700528}
529
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800530status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
531{
532 const size_t SIZE = 256;
533 char buffer[SIZE];
534 String8 result;
535
536 result.append(" AudioOutput\n");
537 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n",
538 mStreamType, mLeftVolume, mRightVolume);
539 result.append(buffer);
540 snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n",
Eric Laurentdb354e52012-03-05 17:27:11 -0800541 mMsecsPerFrame, (mTrack != 0) ? mTrack->latency() : -1);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800542 result.append(buffer);
Eric Laurent2beeb502010-07-16 07:43:46 -0700543 snprintf(buffer, 255, " aux effect id(%d), send level (%f)\n",
544 mAuxEffectId, mSendLevel);
545 result.append(buffer);
546
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800547 ::write(fd, result.string(), result.size());
548 if (mTrack != 0) {
549 mTrack->dump(fd, args);
550 }
551 return NO_ERROR;
552}
553
Lajos Molnar6d339f12015-04-17 16:15:53 -0700554status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800555{
556 const size_t SIZE = 256;
557 char buffer[SIZE];
558 String8 result;
559 result.append(" Client\n");
Svet Ganov33761132021-05-13 22:51:08 +0000560 snprintf(buffer, 255, " AttributionSource(%s), connId(%d), status(%d), looping(%s)\n",
561 mAttributionSource.toString().c_str(), mConnId, mStatus, mLoop?"true": "false");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800562 result.append(buffer);
Wei Jia502c2f42017-07-13 17:47:56 -0700563
564 sp<MediaPlayerBase> p;
565 sp<AudioOutput> audioOutput;
566 bool locked = false;
567 for (int i = 0; i < kDumpLockRetries; ++i) {
568 if (mLock.tryLock() == NO_ERROR) {
569 locked = true;
570 break;
571 }
572 usleep(kDumpLockSleepUs);
Andreas Hubera0b1d4b2011-06-07 15:52:25 -0700573 }
Wei Jia502c2f42017-07-13 17:47:56 -0700574
575 if (locked) {
576 p = mPlayer;
577 audioOutput = mAudioOutput;
578 mLock.unlock();
579 } else {
580 result.append(" lock is taken, no dump from player and audio output\n");
581 }
582 write(fd, result.string(), result.size());
583
584 if (p != NULL) {
585 p->dump(fd, args);
586 }
587 if (audioOutput != 0) {
588 audioOutput->dump(fd, args);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800589 }
590 write(fd, "\n", 1);
591 return NO_ERROR;
592}
593
Marco Nelissenf09611f2015-02-13 14:12:42 -0800594/**
595 * The only arguments this understands right now are -c, -von and -voff,
596 * which are parsed by ALooperRoster::dump()
597 */
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800598status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
599{
600 const size_t SIZE = 256;
601 char buffer[SIZE];
602 String8 result;
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530603 SortedVector< sp<Client> > clients; //to serialise the mutex unlock & client destruction.
604 SortedVector< sp<MediaRecorderClient> > mediaRecorderClients;
605
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800606 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
Wonsik Kim6f675772019-08-20 17:06:53 -0700607 snprintf(buffer, SIZE - 1, "Permission Denial: "
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800608 "can't dump MediaPlayerService from pid=%d, uid=%d\n",
609 IPCThreadState::self()->getCallingPid(),
610 IPCThreadState::self()->getCallingUid());
611 result.append(buffer);
612 } else {
613 Mutex::Autolock lock(mLock);
614 for (int i = 0, n = mClients.size(); i < n; ++i) {
615 sp<Client> c = mClients[i].promote();
616 if (c != 0) c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530617 clients.add(c);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800618 }
James Dongb9141222010-07-08 11:16:11 -0700619 if (mMediaRecorderClients.size() == 0) {
620 result.append(" No media recorder client\n\n");
621 } else {
622 for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
623 sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
James Donge579e282011-10-18 22:29:20 -0700624 if (c != 0) {
Svet Ganov33761132021-05-13 22:51:08 +0000625 snprintf(buffer, 255, " MediaRecorderClient pid(%d)\n",
626 c->mAttributionSource.pid);
James Donge579e282011-10-18 22:29:20 -0700627 result.append(buffer);
628 write(fd, result.string(), result.size());
629 result = "\n";
630 c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530631 mediaRecorderClients.add(c);
James Donge579e282011-10-18 22:29:20 -0700632 }
James Dongb9141222010-07-08 11:16:11 -0700633 }
Gloria Wangdac6a312009-10-29 15:46:37 -0700634 }
635
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800636 result.append(" Files opened and/or mapped:\n");
Wonsik Kim6f675772019-08-20 17:06:53 -0700637 snprintf(buffer, SIZE - 1, "/proc/%d/maps", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800638 FILE *f = fopen(buffer, "r");
639 if (f) {
640 while (!feof(f)) {
Wonsik Kim6f675772019-08-20 17:06:53 -0700641 fgets(buffer, SIZE - 1, f);
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700642 if (strstr(buffer, " /storage/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800643 strstr(buffer, " /system/sounds/") ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700644 strstr(buffer, " /data/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800645 strstr(buffer, " /system/media/")) {
646 result.append(" ");
647 result.append(buffer);
648 }
649 }
650 fclose(f);
651 } else {
652 result.append("couldn't open ");
653 result.append(buffer);
654 result.append("\n");
655 }
656
Wonsik Kim6f675772019-08-20 17:06:53 -0700657 snprintf(buffer, SIZE - 1, "/proc/%d/fd", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800658 DIR *d = opendir(buffer);
659 if (d) {
660 struct dirent *ent;
661 while((ent = readdir(d)) != NULL) {
662 if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
Wonsik Kim6f675772019-08-20 17:06:53 -0700663 snprintf(buffer, SIZE - 1, "/proc/%d/fd/%s", getpid(), ent->d_name);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800664 struct stat s;
665 if (lstat(buffer, &s) == 0) {
666 if ((s.st_mode & S_IFMT) == S_IFLNK) {
667 char linkto[256];
668 int len = readlink(buffer, linkto, sizeof(linkto));
669 if(len > 0) {
670 if(len > 255) {
671 linkto[252] = '.';
672 linkto[253] = '.';
673 linkto[254] = '.';
674 linkto[255] = 0;
675 } else {
676 linkto[len] = 0;
677 }
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700678 if (strstr(linkto, "/storage/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800679 strstr(linkto, "/system/sounds/") == linkto ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700680 strstr(linkto, "/data/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800681 strstr(linkto, "/system/media/") == linkto) {
682 result.append(" ");
683 result.append(buffer);
684 result.append(" -> ");
685 result.append(linkto);
686 result.append("\n");
687 }
688 }
689 } else {
690 result.append(" unexpected type for ");
691 result.append(buffer);
692 result.append("\n");
693 }
694 }
695 }
696 }
697 closedir(d);
698 } else {
699 result.append("couldn't open ");
700 result.append(buffer);
701 result.append("\n");
702 }
703
Marco Nelissenf09611f2015-02-13 14:12:42 -0800704 gLooperRoster.dump(fd, args);
705
Wonsik Kimd579f3e2019-10-07 14:14:09 -0700706 sp<IMediaCodecList> codecList = getCodecList();
707 dumpCodecDetails(fd, codecList, true /* decoders */);
708 dumpCodecDetails(fd, codecList, false /* !decoders */);
709
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800710 bool dumpMem = false;
Andy Hung53541292016-04-13 16:48:51 -0700711 bool unreachableMemory = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800712 for (size_t i = 0; i < args.size(); i++) {
713 if (args[i] == String16("-m")) {
714 dumpMem = true;
Andy Hung53541292016-04-13 16:48:51 -0700715 } else if (args[i] == String16("--unreachable")) {
716 unreachableMemory = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800717 }
718 }
719 if (dumpMem) {
Andy Hung07b745e2016-05-23 16:21:07 -0700720 result.append("\nDumping memory:\n");
721 std::string s = dumpMemoryAddresses(100 /* limit */);
722 result.append(s.c_str(), s.size());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800723 }
Andy Hung53541292016-04-13 16:48:51 -0700724 if (unreachableMemory) {
725 result.append("\nDumping unreachable memory:\n");
726 // TODO - should limit be an argument parameter?
727 std::string s = GetUnreachableMemoryString(true /* contents */, 10000 /* limit */);
728 result.append(s.c_str(), s.size());
729 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800730 }
731 write(fd, result.string(), result.size());
Wonsik Kim6f675772019-08-20 17:06:53 -0700732
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800733 return NO_ERROR;
734}
735
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -0700736void MediaPlayerService::removeClient(const wp<Client>& client)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800737{
738 Mutex::Autolock lock(mLock);
739 mClients.remove(client);
740}
741
Robert Shihee0a0e32016-08-16 16:50:54 -0700742bool MediaPlayerService::hasClient(wp<Client> client)
743{
744 Mutex::Autolock lock(mLock);
745 return mClients.indexOf(client) != NAME_NOT_FOUND;
746}
747
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700748MediaPlayerService::Client::Client(
Svet Ganov33761132021-05-13 22:51:08 +0000749 const sp<MediaPlayerService>& service, const AttributionSourceState& attributionSource,
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700750 int32_t connId, const sp<IMediaPlayerClient>& client,
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700751 audio_session_t audioSessionId)
Svet Ganov33761132021-05-13 22:51:08 +0000752 : mAttributionSource(attributionSource)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800753{
Steve Block3856b092011-10-20 11:56:00 +0100754 ALOGV("Client(%d) constructor", connId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800755 mConnId = connId;
756 mService = service;
757 mClient = client;
758 mLoop = false;
759 mStatus = NO_INIT;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700760 mAudioSessionId = audioSessionId;
John Grossmanc795b642012-02-22 15:38:35 -0800761 mRetransmitEndpointValid = false;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700762 mAudioAttributes = NULL;
Pawin Vongmasa082e4f72017-12-17 02:31:18 -0800763 mListener = new Listener(this);
Eric Laurenta514bdb2010-06-21 09:27:30 -0700764
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800765#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000766 ALOGD("create Antagonizer");
Pawin Vongmasa082e4f72017-12-17 02:31:18 -0800767 mAntagonizer = new Antagonizer(mListener);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800768#endif
769}
770
771MediaPlayerService::Client::~Client()
772{
Svet Ganov33761132021-05-13 22:51:08 +0000773 ALOGV("Client(%d) destructor AttributionSource = %s", mConnId,
774 mAttributionSource.toString().c_str());
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700775 mAudioOutput.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800776 wp<Client> client(this);
777 disconnect();
778 mService->removeClient(client);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700779 if (mAudioAttributes != NULL) {
780 free(mAudioAttributes);
781 }
jiabin156c6872017-10-06 09:47:15 -0700782 mAudioDeviceUpdatedListener.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800783}
784
785void MediaPlayerService::Client::disconnect()
786{
Svet Ganov33761132021-05-13 22:51:08 +0000787 ALOGV("disconnect(%d) from AttributionSource %s", mConnId,
788 mAttributionSource.toString().c_str());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800789 // grab local reference and clear main reference to prevent future
790 // access to object
791 sp<MediaPlayerBase> p;
792 {
793 Mutex::Autolock l(mLock);
794 p = mPlayer;
beanzdcfefde2012-11-05 09:51:43 +0800795 mClient.clear();
Wei Jia502c2f42017-07-13 17:47:56 -0700796 mPlayer.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800797 }
Andreas Huber20111aa2009-07-14 16:56:47 -0700798
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800799 // clear the notification to prevent callbacks to dead client
800 // and reset the player. We assume the player will serialize
801 // access to itself if necessary.
802 if (p != 0) {
Pawin Vongmasa082e4f72017-12-17 02:31:18 -0800803 p->setNotifyCallback(0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800804#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000805 ALOGD("kill Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800806 mAntagonizer->kill();
807#endif
808 p->reset();
809 }
810
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700811 {
812 Mutex::Autolock l(mLock);
813 disconnectNativeWindow_l();
814 }
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700815
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800816 IPCThreadState::self()->flushCommands();
817}
818
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800819sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
820{
821 // determine if we have the right player type
Wei Jia502c2f42017-07-13 17:47:56 -0700822 sp<MediaPlayerBase> p = getPlayer();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800823 if ((p != NULL) && (p->playerType() != playerType)) {
Steve Block3856b092011-10-20 11:56:00 +0100824 ALOGV("delete player");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800825 p.clear();
826 }
827 if (p == NULL) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700828 p = MediaPlayerFactory::createPlayer(playerType, mListener,
Svet Ganov33761132021-05-13 22:51:08 +0000829 VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(mAttributionSource.pid)));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800830 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700831
Jason Simmonsdb29e522011-08-12 13:46:55 -0700832 if (p != NULL) {
Svet Ganov33761132021-05-13 22:51:08 +0000833 p->setUID(VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(mAttributionSource.uid)));
Jason Simmonsdb29e522011-08-12 13:46:55 -0700834 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700835
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800836 return p;
837}
838
jiabin156c6872017-10-06 09:47:15 -0700839void MediaPlayerService::Client::AudioDeviceUpdatedNotifier::onAudioDeviceUpdate(
840 audio_io_handle_t audioIo,
841 audio_port_handle_t deviceId) {
842 sp<MediaPlayerBase> listener = mListener.promote();
843 if (listener != NULL) {
844 listener->sendEvent(MEDIA_AUDIO_ROUTING_CHANGED, audioIo, deviceId);
845 } else {
846 ALOGW("listener for process %d death is gone", MEDIA_AUDIO_ROUTING_CHANGED);
847 }
848}
849
John Grossmanc795b642012-02-22 15:38:35 -0800850sp<MediaPlayerBase> MediaPlayerService::Client::setDataSource_pre(
851 player_type playerType)
852{
853 ALOGV("player type = %d", playerType);
854
855 // create the right type of player
856 sp<MediaPlayerBase> p = createPlayer(playerType);
857 if (p == NULL) {
858 return p;
859 }
860
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700861 std::vector<DeathNotifier> deathNotifiers;
862
863 // Listen to death of media.extractor service
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700864 sp<IServiceManager> sm = defaultServiceManager();
865 sp<IBinder> binder = sm->getService(String16("media.extractor"));
Marco Nelissen1b5a7ee2016-09-30 13:54:30 -0700866 if (binder == NULL) {
867 ALOGE("extractor service not available");
868 return NULL;
869 }
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700870 deathNotifiers.emplace_back(
871 binder, [l = wp<MediaPlayerBase>(p)]() {
872 sp<MediaPlayerBase> listener = l.promote();
873 if (listener) {
874 ALOGI("media.extractor died. Sending death notification.");
875 listener->sendEvent(MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED,
876 MEDIAEXTRACTOR_PROCESS_DEATH);
877 } else {
878 ALOGW("media.extractor died without a death handler.");
879 }
880 });
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700881
Marco Nelissena0c98412019-03-29 12:10:19 -0700882 {
883 using ::android::hidl::base::V1_0::IBase;
884
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700885 // Listen to death of OMX service
Marco Nelissena0c98412019-03-29 12:10:19 -0700886 {
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700887 sp<IBase> base = ::android::hardware::media::omx::V1_0::
888 IOmx::getService();
889 if (base == nullptr) {
Marco Nelissena0c98412019-03-29 12:10:19 -0700890 ALOGD("OMX service is not available");
891 } else {
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700892 deathNotifiers.emplace_back(
893 base, [l = wp<MediaPlayerBase>(p)]() {
894 sp<MediaPlayerBase> listener = l.promote();
895 if (listener) {
896 ALOGI("OMX service died. "
897 "Sending death notification.");
898 listener->sendEvent(
899 MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED,
900 MEDIACODEC_PROCESS_DEATH);
901 } else {
902 ALOGW("OMX service died without a death handler.");
903 }
904 });
Marco Nelissena0c98412019-03-29 12:10:19 -0700905 }
906 }
907
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700908 // Listen to death of Codec2 services
Marco Nelissena0c98412019-03-29 12:10:19 -0700909 {
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700910 for (std::shared_ptr<Codec2Client> const& client :
911 Codec2Client::CreateFromAllServices()) {
912 sp<IBase> base = client->getBase();
913 deathNotifiers.emplace_back(
914 base, [l = wp<MediaPlayerBase>(p),
915 name = std::string(client->getServiceName())]() {
916 sp<MediaPlayerBase> listener = l.promote();
917 if (listener) {
918 ALOGI("Codec2 service \"%s\" died. "
919 "Sending death notification.",
920 name.c_str());
921 listener->sendEvent(
922 MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED,
923 MEDIACODEC_PROCESS_DEATH);
924 } else {
925 ALOGW("Codec2 service \"%s\" died "
926 "without a death handler.",
927 name.c_str());
928 }
929 });
Marco Nelissene4da6c62019-04-01 15:01:41 -0700930 }
Marco Nelissena0c98412019-03-29 12:10:19 -0700931 }
Marco Nelissen1b5a7ee2016-09-30 13:54:30 -0700932 }
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700933
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700934 Mutex::Autolock lock(mLock);
935
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700936 mDeathNotifiers.clear();
937 mDeathNotifiers.swap(deathNotifiers);
jiabin156c6872017-10-06 09:47:15 -0700938 mAudioDeviceUpdatedListener = new AudioDeviceUpdatedNotifier(p);
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700939
John Grossmanc795b642012-02-22 15:38:35 -0800940 if (!p->hardwareOutput()) {
Svet Ganov33761132021-05-13 22:51:08 +0000941 mAudioOutput = new AudioOutput(mAudioSessionId, mAttributionSource,
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700942 mAudioAttributes, mAudioDeviceUpdatedListener);
John Grossmanc795b642012-02-22 15:38:35 -0800943 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
944 }
945
946 return p;
947}
948
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700949status_t MediaPlayerService::Client::setDataSource_post(
John Grossmanc795b642012-02-22 15:38:35 -0800950 const sp<MediaPlayerBase>& p,
951 status_t status)
952{
953 ALOGV(" setDataSource");
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700954 if (status != OK) {
955 ALOGE(" error: %d", status);
956 return status;
John Grossmanc795b642012-02-22 15:38:35 -0800957 }
958
959 // Set the re-transmission endpoint if one was chosen.
960 if (mRetransmitEndpointValid) {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700961 status = p->setRetransmitEndpoint(&mRetransmitEndpoint);
962 if (status != NO_ERROR) {
963 ALOGE("setRetransmitEndpoint error: %d", status);
John Grossmanc795b642012-02-22 15:38:35 -0800964 }
965 }
966
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700967 if (status == OK) {
968 Mutex::Autolock lock(mLock);
John Grossmanc795b642012-02-22 15:38:35 -0800969 mPlayer = p;
970 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700971 return status;
John Grossmanc795b642012-02-22 15:38:35 -0800972}
973
Andreas Huber2db84552010-01-28 11:19:57 -0800974status_t MediaPlayerService::Client::setDataSource(
Andreas Huber1b86fe02014-01-29 11:13:26 -0800975 const sp<IMediaHTTPService> &httpService,
976 const char *url,
977 const KeyedVector<String8, String8> *headers)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800978{
Steve Block3856b092011-10-20 11:56:00 +0100979 ALOGV("setDataSource(%s)", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800980 if (url == NULL)
981 return UNKNOWN_ERROR;
982
Dave Burked681bbb2011-08-30 14:39:17 +0100983 if ((strncmp(url, "http://", 7) == 0) ||
984 (strncmp(url, "https://", 8) == 0) ||
985 (strncmp(url, "rtsp://", 7) == 0)) {
986 if (!checkPermission("android.permission.INTERNET")) {
987 return PERMISSION_DENIED;
988 }
989 }
990
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800991 if (strncmp(url, "content://", 10) == 0) {
992 // get a filedescriptor for the content Uri and
993 // pass it to the setDataSource(fd) method
994
995 String16 url16(url);
996 int fd = android::openContentProviderFile(url16);
997 if (fd < 0)
998 {
Steve Block29357bc2012-01-06 19:20:56 +0000999 ALOGE("Couldn't open fd for %s", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001000 return UNKNOWN_ERROR;
1001 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001002 status_t status = setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001003 close(fd);
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001004 return mStatus = status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001005 } else {
John Grossman44a7e422012-06-21 17:29:24 -07001006 player_type playerType = MediaPlayerFactory::getPlayerType(this, url);
John Grossmanc795b642012-02-22 15:38:35 -08001007 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
1008 if (p == NULL) {
1009 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001010 }
1011
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001012 return mStatus =
1013 setDataSource_post(
1014 p, p->setDataSource(httpService, url, headers));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001015 }
1016}
1017
1018status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
1019{
Marco Nelissen83b0fd92015-09-16 13:48:07 -07001020 ALOGV("setDataSource fd=%d (%s), offset=%lld, length=%lld",
1021 fd, nameForFd(fd).c_str(), (long long) offset, (long long) length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001022 struct stat sb;
1023 int ret = fstat(fd, &sb);
1024 if (ret != 0) {
Steve Block29357bc2012-01-06 19:20:56 +00001025 ALOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001026 return UNKNOWN_ERROR;
1027 }
1028
Andy Hung833b4752016-04-04 17:15:48 -07001029 ALOGV("st_dev = %llu", static_cast<unsigned long long>(sb.st_dev));
Steve Block3856b092011-10-20 11:56:00 +01001030 ALOGV("st_mode = %u", sb.st_mode);
Mark Salyzyn77342f72014-06-18 16:31:32 -07001031 ALOGV("st_uid = %lu", static_cast<unsigned long>(sb.st_uid));
1032 ALOGV("st_gid = %lu", static_cast<unsigned long>(sb.st_gid));
Andy Hung833b4752016-04-04 17:15:48 -07001033 ALOGV("st_size = %llu", static_cast<unsigned long long>(sb.st_size));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001034
1035 if (offset >= sb.st_size) {
Steve Block29357bc2012-01-06 19:20:56 +00001036 ALOGE("offset error");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001037 return UNKNOWN_ERROR;
1038 }
1039 if (offset + length > sb.st_size) {
1040 length = sb.st_size - offset;
Andy Hung833b4752016-04-04 17:15:48 -07001041 ALOGV("calculated length = %lld", (long long)length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001042 }
1043
John Grossman44a7e422012-06-21 17:29:24 -07001044 player_type playerType = MediaPlayerFactory::getPlayerType(this,
1045 fd,
1046 offset,
1047 length);
John Grossmanc795b642012-02-22 15:38:35 -08001048 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
1049 if (p == NULL) {
1050 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001051 }
1052
1053 // now set data source
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001054 return mStatus = setDataSource_post(p, p->setDataSource(fd, offset, length));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001055}
1056
Andreas Hubere2b10282010-11-23 11:41:34 -08001057status_t MediaPlayerService::Client::setDataSource(
1058 const sp<IStreamSource> &source) {
1059 // create the right type of player
John Grossman44a7e422012-06-21 17:29:24 -07001060 player_type playerType = MediaPlayerFactory::getPlayerType(this, source);
John Grossmanc795b642012-02-22 15:38:35 -08001061 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
Andreas Hubere2b10282010-11-23 11:41:34 -08001062 if (p == NULL) {
1063 return NO_INIT;
1064 }
1065
Andreas Hubere2b10282010-11-23 11:41:34 -08001066 // now set data source
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001067 return mStatus = setDataSource_post(p, p->setDataSource(source));
Andreas Hubere2b10282010-11-23 11:41:34 -08001068}
1069
Chris Watkins99f31602015-03-20 13:06:33 -07001070status_t MediaPlayerService::Client::setDataSource(
1071 const sp<IDataSource> &source) {
Dongwon Kangd91dc5a2017-10-10 00:07:09 -07001072 sp<DataSource> dataSource = CreateDataSourceFromIDataSource(source);
Chris Watkins99f31602015-03-20 13:06:33 -07001073 player_type playerType = MediaPlayerFactory::getPlayerType(this, dataSource);
1074 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
1075 if (p == NULL) {
1076 return NO_INIT;
1077 }
1078 // now set data source
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001079 return mStatus = setDataSource_post(p, p->setDataSource(dataSource));
Chris Watkins99f31602015-03-20 13:06:33 -07001080}
1081
Byeongjo Park28225ab2019-01-24 20:31:19 +09001082status_t MediaPlayerService::Client::setDataSource(
1083 const String8& rtpParams) {
1084 player_type playerType = NU_PLAYER;
1085 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
1086 if (p == NULL) {
1087 return NO_INIT;
1088 }
1089 // now set data source
1090 return mStatus = setDataSource_post(p, p->setDataSource(rtpParams));
1091}
1092
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001093void MediaPlayerService::Client::disconnectNativeWindow_l() {
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001094 if (mConnectedWindow != NULL) {
Chong Zhang181fd9b2017-02-16 15:53:03 -08001095 status_t err = nativeWindowDisconnect(
1096 mConnectedWindow.get(), "disconnectNativeWindow");
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001097
1098 if (err != OK) {
Chong Zhang181fd9b2017-02-16 15:53:03 -08001099 ALOGW("nativeWindowDisconnect returned an error: %s (%d)",
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001100 strerror(-err), err);
1101 }
1102 }
1103 mConnectedWindow.clear();
1104}
1105
Glenn Kasten11731182011-02-08 17:26:17 -08001106status_t MediaPlayerService::Client::setVideoSurfaceTexture(
Andy McFadden484566c2012-12-18 09:46:54 -08001107 const sp<IGraphicBufferProducer>& bufferProducer)
Glenn Kasten11731182011-02-08 17:26:17 -08001108{
Andy McFadden484566c2012-12-18 09:46:54 -08001109 ALOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, bufferProducer.get());
Glenn Kasten11731182011-02-08 17:26:17 -08001110 sp<MediaPlayerBase> p = getPlayer();
1111 if (p == 0) return UNKNOWN_ERROR;
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001112
Marco Nelissenf8880202014-11-14 07:58:25 -08001113 sp<IBinder> binder(IInterface::asBinder(bufferProducer));
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001114 if (mConnectedWindowBinder == binder) {
1115 return OK;
1116 }
1117
1118 sp<ANativeWindow> anw;
Andy McFadden484566c2012-12-18 09:46:54 -08001119 if (bufferProducer != NULL) {
Marco Nelissenee08f7e2013-09-16 13:30:01 -07001120 anw = new Surface(bufferProducer, true /* controlledByApp */);
Chong Zhang181fd9b2017-02-16 15:53:03 -08001121 status_t err = nativeWindowConnect(anw.get(), "setVideoSurfaceTexture");
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001122
1123 if (err != OK) {
Steve Block29357bc2012-01-06 19:20:56 +00001124 ALOGE("setVideoSurfaceTexture failed: %d", err);
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001125 // Note that we must do the reset before disconnecting from the ANW.
1126 // Otherwise queue/dequeue calls could be made on the disconnected
1127 // ANW, which may result in errors.
1128 reset();
1129
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001130 Mutex::Autolock lock(mLock);
1131 disconnectNativeWindow_l();
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001132
1133 return err;
1134 }
1135 }
1136
Andy McFadden484566c2012-12-18 09:46:54 -08001137 // Note that we must set the player's new GraphicBufferProducer before
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001138 // disconnecting the old one. Otherwise queue/dequeue calls could be made
1139 // on the disconnected ANW, which may result in errors.
Andy McFadden484566c2012-12-18 09:46:54 -08001140 status_t err = p->setVideoSurfaceTexture(bufferProducer);
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001141
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001142 mLock.lock();
1143 disconnectNativeWindow_l();
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001144
1145 if (err == OK) {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001146 mConnectedWindow = anw;
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001147 mConnectedWindowBinder = binder;
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001148 mLock.unlock();
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001149 } else {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001150 mLock.unlock();
1151 status_t err = nativeWindowDisconnect(
1152 anw.get(), "disconnectNativeWindow");
1153
1154 if (err != OK) {
1155 ALOGW("nativeWindowDisconnect returned an error: %s (%d)",
1156 strerror(-err), err);
1157 }
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001158 }
1159
1160 return err;
Glenn Kasten11731182011-02-08 17:26:17 -08001161}
1162
Nicolas Catania1d187f12009-05-12 23:25:55 -07001163status_t MediaPlayerService::Client::invoke(const Parcel& request,
1164 Parcel *reply)
1165{
1166 sp<MediaPlayerBase> p = getPlayer();
1167 if (p == NULL) return UNKNOWN_ERROR;
1168 return p->invoke(request, reply);
1169}
1170
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001171// This call doesn't need to access the native player.
1172status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
1173{
1174 status_t status;
nikoa64c8c72009-07-20 15:07:26 -07001175 media::Metadata::Filter allow, drop;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001176
Nicolas Catania48290382009-07-10 13:53:06 -07001177 if (unmarshallFilter(filter, &allow, &status) &&
1178 unmarshallFilter(filter, &drop, &status)) {
1179 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001180
1181 mMetadataAllow = allow;
1182 mMetadataDrop = drop;
1183 }
1184 return status;
1185}
1186
Nicolas Catania48290382009-07-10 13:53:06 -07001187status_t MediaPlayerService::Client::getMetadata(
Mark Salyzyn77342f72014-06-18 16:31:32 -07001188 bool update_only, bool /*apply_filter*/, Parcel *reply)
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001189{
nikoa64c8c72009-07-20 15:07:26 -07001190 sp<MediaPlayerBase> player = getPlayer();
1191 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania48290382009-07-10 13:53:06 -07001192
nikod608a812009-07-16 16:39:53 -07001193 status_t status;
1194 // Placeholder for the return code, updated by the caller.
1195 reply->writeInt32(-1);
1196
nikoa64c8c72009-07-20 15:07:26 -07001197 media::Metadata::Filter ids;
Nicolas Catania48290382009-07-10 13:53:06 -07001198
1199 // We don't block notifications while we fetch the data. We clear
1200 // mMetadataUpdated first so we don't lose notifications happening
1201 // during the rest of this call.
1202 {
1203 Mutex::Autolock lock(mLock);
1204 if (update_only) {
nikod608a812009-07-16 16:39:53 -07001205 ids = mMetadataUpdated;
Nicolas Catania48290382009-07-10 13:53:06 -07001206 }
1207 mMetadataUpdated.clear();
1208 }
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001209
nikoa64c8c72009-07-20 15:07:26 -07001210 media::Metadata metadata(reply);
Nicolas Catania48290382009-07-10 13:53:06 -07001211
nikoa64c8c72009-07-20 15:07:26 -07001212 metadata.appendHeader();
1213 status = player->getMetadata(ids, reply);
nikod608a812009-07-16 16:39:53 -07001214
1215 if (status != OK) {
nikoa64c8c72009-07-20 15:07:26 -07001216 metadata.resetParcel();
Steve Block29357bc2012-01-06 19:20:56 +00001217 ALOGE("getMetadata failed %d", status);
nikod608a812009-07-16 16:39:53 -07001218 return status;
1219 }
1220
1221 // FIXME: Implement filtering on the result. Not critical since
1222 // filtering takes place on the update notifications already. This
1223 // would be when all the metadata are fetch and a filter is set.
1224
nikod608a812009-07-16 16:39:53 -07001225 // Everything is fine, update the metadata length.
nikoa64c8c72009-07-20 15:07:26 -07001226 metadata.updateLength();
nikod608a812009-07-16 16:39:53 -07001227 return OK;
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001228}
1229
Wei Jiad399e7e2016-10-26 15:49:11 -07001230status_t MediaPlayerService::Client::setBufferingSettings(
1231 const BufferingSettings& buffering)
1232{
Wei Jiadc6f3402017-01-09 15:04:18 -08001233 ALOGV("[%d] setBufferingSettings{%s}",
1234 mConnId, buffering.toString().string());
Wei Jiad399e7e2016-10-26 15:49:11 -07001235 sp<MediaPlayerBase> p = getPlayer();
1236 if (p == 0) return UNKNOWN_ERROR;
1237 return p->setBufferingSettings(buffering);
1238}
1239
Wei Jia9bb38032017-03-23 18:00:38 -07001240status_t MediaPlayerService::Client::getBufferingSettings(
Wei Jiad399e7e2016-10-26 15:49:11 -07001241 BufferingSettings* buffering /* nonnull */)
1242{
1243 sp<MediaPlayerBase> p = getPlayer();
1244 // TODO: create mPlayer on demand.
1245 if (p == 0) return UNKNOWN_ERROR;
Wei Jia9bb38032017-03-23 18:00:38 -07001246 status_t ret = p->getBufferingSettings(buffering);
Wei Jiad399e7e2016-10-26 15:49:11 -07001247 if (ret == NO_ERROR) {
Wei Jia9bb38032017-03-23 18:00:38 -07001248 ALOGV("[%d] getBufferingSettings{%s}",
Wei Jiadc6f3402017-01-09 15:04:18 -08001249 mConnId, buffering->toString().string());
Wei Jiad399e7e2016-10-26 15:49:11 -07001250 } else {
Wei Jia9bb38032017-03-23 18:00:38 -07001251 ALOGE("[%d] getBufferingSettings returned %d", mConnId, ret);
Wei Jiad399e7e2016-10-26 15:49:11 -07001252 }
1253 return ret;
1254}
1255
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001256status_t MediaPlayerService::Client::prepareAsync()
1257{
Steve Block3856b092011-10-20 11:56:00 +01001258 ALOGV("[%d] prepareAsync", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001259 sp<MediaPlayerBase> p = getPlayer();
1260 if (p == 0) return UNKNOWN_ERROR;
1261 status_t ret = p->prepareAsync();
1262#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +00001263 ALOGD("start Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001264 if (ret == NO_ERROR) mAntagonizer->start();
1265#endif
1266 return ret;
1267}
1268
1269status_t MediaPlayerService::Client::start()
1270{
Steve Block3856b092011-10-20 11:56:00 +01001271 ALOGV("[%d] start", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001272 sp<MediaPlayerBase> p = getPlayer();
1273 if (p == 0) return UNKNOWN_ERROR;
1274 p->setLooping(mLoop);
1275 return p->start();
1276}
1277
1278status_t MediaPlayerService::Client::stop()
1279{
Steve Block3856b092011-10-20 11:56:00 +01001280 ALOGV("[%d] stop", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001281 sp<MediaPlayerBase> p = getPlayer();
1282 if (p == 0) return UNKNOWN_ERROR;
1283 return p->stop();
1284}
1285
1286status_t MediaPlayerService::Client::pause()
1287{
Steve Block3856b092011-10-20 11:56:00 +01001288 ALOGV("[%d] pause", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001289 sp<MediaPlayerBase> p = getPlayer();
1290 if (p == 0) return UNKNOWN_ERROR;
1291 return p->pause();
1292}
1293
1294status_t MediaPlayerService::Client::isPlaying(bool* state)
1295{
1296 *state = false;
1297 sp<MediaPlayerBase> p = getPlayer();
1298 if (p == 0) return UNKNOWN_ERROR;
1299 *state = p->isPlaying();
Steve Block3856b092011-10-20 11:56:00 +01001300 ALOGV("[%d] isPlaying: %d", mConnId, *state);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001301 return NO_ERROR;
1302}
1303
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001304status_t MediaPlayerService::Client::setPlaybackSettings(const AudioPlaybackRate& rate)
Wei Jia98160162015-02-04 17:01:11 -08001305{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001306 ALOGV("[%d] setPlaybackSettings(%f, %f, %d, %d)",
1307 mConnId, rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Wei Jia98160162015-02-04 17:01:11 -08001308 sp<MediaPlayerBase> p = getPlayer();
1309 if (p == 0) return UNKNOWN_ERROR;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001310 return p->setPlaybackSettings(rate);
1311}
1312
1313status_t MediaPlayerService::Client::getPlaybackSettings(AudioPlaybackRate* rate /* nonnull */)
1314{
1315 sp<MediaPlayerBase> p = getPlayer();
1316 if (p == 0) return UNKNOWN_ERROR;
1317 status_t ret = p->getPlaybackSettings(rate);
1318 if (ret == NO_ERROR) {
1319 ALOGV("[%d] getPlaybackSettings(%f, %f, %d, %d)",
1320 mConnId, rate->mSpeed, rate->mPitch, rate->mFallbackMode, rate->mStretchMode);
1321 } else {
1322 ALOGV("[%d] getPlaybackSettings returned %d", mConnId, ret);
1323 }
1324 return ret;
1325}
1326
1327status_t MediaPlayerService::Client::setSyncSettings(
1328 const AVSyncSettings& sync, float videoFpsHint)
1329{
1330 ALOGV("[%d] setSyncSettings(%u, %u, %f, %f)",
1331 mConnId, sync.mSource, sync.mAudioAdjustMode, sync.mTolerance, videoFpsHint);
1332 sp<MediaPlayerBase> p = getPlayer();
1333 if (p == 0) return UNKNOWN_ERROR;
1334 return p->setSyncSettings(sync, videoFpsHint);
1335}
1336
1337status_t MediaPlayerService::Client::getSyncSettings(
1338 AVSyncSettings* sync /* nonnull */, float* videoFps /* nonnull */)
1339{
1340 sp<MediaPlayerBase> p = getPlayer();
1341 if (p == 0) return UNKNOWN_ERROR;
1342 status_t ret = p->getSyncSettings(sync, videoFps);
1343 if (ret == NO_ERROR) {
1344 ALOGV("[%d] getSyncSettings(%u, %u, %f, %f)",
1345 mConnId, sync->mSource, sync->mAudioAdjustMode, sync->mTolerance, *videoFps);
1346 } else {
1347 ALOGV("[%d] getSyncSettings returned %d", mConnId, ret);
1348 }
1349 return ret;
Wei Jia98160162015-02-04 17:01:11 -08001350}
1351
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001352status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
1353{
Steve Block3856b092011-10-20 11:56:00 +01001354 ALOGV("getCurrentPosition");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001355 sp<MediaPlayerBase> p = getPlayer();
1356 if (p == 0) return UNKNOWN_ERROR;
1357 status_t ret = p->getCurrentPosition(msec);
1358 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001359 ALOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001360 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001361 ALOGE("getCurrentPosition returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001362 }
1363 return ret;
1364}
1365
1366status_t MediaPlayerService::Client::getDuration(int *msec)
1367{
Steve Block3856b092011-10-20 11:56:00 +01001368 ALOGV("getDuration");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001369 sp<MediaPlayerBase> p = getPlayer();
1370 if (p == 0) return UNKNOWN_ERROR;
1371 status_t ret = p->getDuration(msec);
1372 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001373 ALOGV("[%d] getDuration = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001374 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001375 ALOGE("getDuration returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001376 }
1377 return ret;
1378}
1379
Marco Nelissen6b74d672012-02-28 16:07:44 -08001380status_t MediaPlayerService::Client::setNextPlayer(const sp<IMediaPlayer>& player) {
1381 ALOGV("setNextPlayer");
1382 Mutex::Autolock l(mLock);
1383 sp<Client> c = static_cast<Client*>(player.get());
Wei Jia28284122016-08-30 13:49:06 -07001384 if (c != NULL && !mService->hasClient(c)) {
Robert Shihee0a0e32016-08-16 16:50:54 -07001385 return BAD_VALUE;
1386 }
1387
Marco Nelissen6b74d672012-02-28 16:07:44 -08001388 mNextClient = c;
John Grossman5f7e55e2012-08-24 14:47:25 -07001389
1390 if (c != NULL) {
1391 if (mAudioOutput != NULL) {
1392 mAudioOutput->setNextOutput(c->mAudioOutput);
1393 } else if ((mPlayer != NULL) && !mPlayer->hardwareOutput()) {
1394 ALOGE("no current audio output");
1395 }
1396
1397 if ((mPlayer != NULL) && (mNextClient->getPlayer() != NULL)) {
1398 mPlayer->setNextPlayer(mNextClient->getPlayer());
1399 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001400 }
John Grossman5f7e55e2012-08-24 14:47:25 -07001401
Marco Nelissen6b74d672012-02-28 16:07:44 -08001402 return OK;
1403}
1404
Andy Hung9fc8b5c2017-01-24 13:36:48 -08001405VolumeShaper::Status MediaPlayerService::Client::applyVolumeShaper(
1406 const sp<VolumeShaper::Configuration>& configuration,
1407 const sp<VolumeShaper::Operation>& operation) {
1408 // for hardware output, call player instead
1409 ALOGV("Client::applyVolumeShaper(%p)", this);
1410 sp<MediaPlayerBase> p = getPlayer();
1411 {
1412 Mutex::Autolock l(mLock);
1413 if (p != 0 && p->hardwareOutput()) {
1414 // TODO: investigate internal implementation
1415 return VolumeShaper::Status(INVALID_OPERATION);
1416 }
1417 if (mAudioOutput.get() != nullptr) {
1418 return mAudioOutput->applyVolumeShaper(configuration, operation);
1419 }
1420 }
1421 return VolumeShaper::Status(INVALID_OPERATION);
1422}
1423
1424sp<VolumeShaper::State> MediaPlayerService::Client::getVolumeShaperState(int id) {
1425 // for hardware output, call player instead
1426 ALOGV("Client::getVolumeShaperState(%p)", this);
1427 sp<MediaPlayerBase> p = getPlayer();
1428 {
1429 Mutex::Autolock l(mLock);
1430 if (p != 0 && p->hardwareOutput()) {
1431 // TODO: investigate internal implementation.
1432 return nullptr;
1433 }
1434 if (mAudioOutput.get() != nullptr) {
1435 return mAudioOutput->getVolumeShaperState(id);
1436 }
1437 }
1438 return nullptr;
1439}
1440
Wei Jiac5de0912016-11-18 10:22:14 -08001441status_t MediaPlayerService::Client::seekTo(int msec, MediaPlayerSeekMode mode)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001442{
Wei Jiac5de0912016-11-18 10:22:14 -08001443 ALOGV("[%d] seekTo(%d, %d)", mConnId, msec, mode);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001444 sp<MediaPlayerBase> p = getPlayer();
1445 if (p == 0) return UNKNOWN_ERROR;
Wei Jiac5de0912016-11-18 10:22:14 -08001446 return p->seekTo(msec, mode);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001447}
1448
1449status_t MediaPlayerService::Client::reset()
1450{
Steve Block3856b092011-10-20 11:56:00 +01001451 ALOGV("[%d] reset", mConnId);
John Grossmanc795b642012-02-22 15:38:35 -08001452 mRetransmitEndpointValid = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001453 sp<MediaPlayerBase> p = getPlayer();
1454 if (p == 0) return UNKNOWN_ERROR;
1455 return p->reset();
1456}
1457
Wei Jia52c28512017-09-13 18:17:51 -07001458status_t MediaPlayerService::Client::notifyAt(int64_t mediaTimeUs)
1459{
1460 ALOGV("[%d] notifyAt(%lld)", mConnId, (long long)mediaTimeUs);
1461 sp<MediaPlayerBase> p = getPlayer();
1462 if (p == 0) return UNKNOWN_ERROR;
1463 return p->notifyAt(mediaTimeUs);
1464}
1465
Glenn Kastenfff6d712012-01-12 16:38:12 -08001466status_t MediaPlayerService::Client::setAudioStreamType(audio_stream_type_t type)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001467{
Steve Block3856b092011-10-20 11:56:00 +01001468 ALOGV("[%d] setAudioStreamType(%d)", mConnId, type);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001469 // TODO: for hardware output, call player instead
1470 Mutex::Autolock l(mLock);
1471 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1472 return NO_ERROR;
1473}
1474
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001475status_t MediaPlayerService::Client::setAudioAttributes_l(const Parcel &parcel)
1476{
1477 if (mAudioAttributes != NULL) { free(mAudioAttributes); }
1478 mAudioAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001479 if (mAudioAttributes == NULL) {
1480 return NO_MEMORY;
1481 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001482 unmarshallAudioAttributes(parcel, mAudioAttributes);
1483
1484 ALOGV("setAudioAttributes_l() usage=%d content=%d flags=0x%x tags=%s",
1485 mAudioAttributes->usage, mAudioAttributes->content_type, mAudioAttributes->flags,
1486 mAudioAttributes->tags);
1487
1488 if (mAudioOutput != 0) {
1489 mAudioOutput->setAudioAttributes(mAudioAttributes);
1490 }
1491 return NO_ERROR;
1492}
1493
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001494status_t MediaPlayerService::Client::setLooping(int loop)
1495{
Steve Block3856b092011-10-20 11:56:00 +01001496 ALOGV("[%d] setLooping(%d)", mConnId, loop);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001497 mLoop = loop;
1498 sp<MediaPlayerBase> p = getPlayer();
1499 if (p != 0) return p->setLooping(loop);
1500 return NO_ERROR;
1501}
1502
1503status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1504{
Steve Block3856b092011-10-20 11:56:00 +01001505 ALOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
John Grossman761defc2012-02-09 15:09:05 -08001506
1507 // for hardware output, call player instead
1508 sp<MediaPlayerBase> p = getPlayer();
1509 {
1510 Mutex::Autolock l(mLock);
1511 if (p != 0 && p->hardwareOutput()) {
1512 MediaPlayerHWInterface* hwp =
1513 reinterpret_cast<MediaPlayerHWInterface*>(p.get());
1514 return hwp->setVolume(leftVolume, rightVolume);
1515 } else {
1516 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1517 return NO_ERROR;
1518 }
1519 }
1520
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001521 return NO_ERROR;
1522}
1523
Eric Laurent2beeb502010-07-16 07:43:46 -07001524status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1525{
Steve Block3856b092011-10-20 11:56:00 +01001526 ALOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
Eric Laurent2beeb502010-07-16 07:43:46 -07001527 Mutex::Autolock l(mLock);
1528 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1529 return NO_ERROR;
1530}
1531
1532status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1533{
Steve Block3856b092011-10-20 11:56:00 +01001534 ALOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
Eric Laurent2beeb502010-07-16 07:43:46 -07001535 Mutex::Autolock l(mLock);
1536 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1537 return NO_ERROR;
1538}
Nicolas Catania48290382009-07-10 13:53:06 -07001539
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001540status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
Steve Block3856b092011-10-20 11:56:00 +01001541 ALOGV("[%d] setParameter(%d)", mConnId, key);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001542 switch (key) {
1543 case KEY_PARAMETER_AUDIO_ATTRIBUTES:
1544 {
1545 Mutex::Autolock l(mLock);
1546 return setAudioAttributes_l(request);
1547 }
1548 default:
1549 sp<MediaPlayerBase> p = getPlayer();
1550 if (p == 0) { return UNKNOWN_ERROR; }
1551 return p->setParameter(key, request);
1552 }
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001553}
1554
1555status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
Steve Block3856b092011-10-20 11:56:00 +01001556 ALOGV("[%d] getParameter(%d)", mConnId, key);
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001557 sp<MediaPlayerBase> p = getPlayer();
1558 if (p == 0) return UNKNOWN_ERROR;
1559 return p->getParameter(key, reply);
1560}
1561
John Grossmanc795b642012-02-22 15:38:35 -08001562status_t MediaPlayerService::Client::setRetransmitEndpoint(
1563 const struct sockaddr_in* endpoint) {
1564
1565 if (NULL != endpoint) {
1566 uint32_t a = ntohl(endpoint->sin_addr.s_addr);
1567 uint16_t p = ntohs(endpoint->sin_port);
1568 ALOGV("[%d] setRetransmitEndpoint(%u.%u.%u.%u:%hu)", mConnId,
1569 (a >> 24), (a >> 16) & 0xFF, (a >> 8) & 0xFF, (a & 0xFF), p);
1570 } else {
1571 ALOGV("[%d] setRetransmitEndpoint = <none>", mConnId);
1572 }
1573
1574 sp<MediaPlayerBase> p = getPlayer();
1575
1576 // Right now, the only valid time to set a retransmit endpoint is before
1577 // player selection has been made (since the presence or absence of a
1578 // retransmit endpoint is going to determine which player is selected during
1579 // setDataSource).
1580 if (p != 0) return INVALID_OPERATION;
1581
1582 if (NULL != endpoint) {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001583 Mutex::Autolock lock(mLock);
John Grossmanc795b642012-02-22 15:38:35 -08001584 mRetransmitEndpoint = *endpoint;
1585 mRetransmitEndpointValid = true;
1586 } else {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001587 Mutex::Autolock lock(mLock);
John Grossmanc795b642012-02-22 15:38:35 -08001588 mRetransmitEndpointValid = false;
1589 }
1590
1591 return NO_ERROR;
1592}
1593
John Grossman44a7e422012-06-21 17:29:24 -07001594status_t MediaPlayerService::Client::getRetransmitEndpoint(
1595 struct sockaddr_in* endpoint)
1596{
1597 if (NULL == endpoint)
1598 return BAD_VALUE;
1599
1600 sp<MediaPlayerBase> p = getPlayer();
1601
1602 if (p != NULL)
1603 return p->getRetransmitEndpoint(endpoint);
1604
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001605 Mutex::Autolock lock(mLock);
John Grossman44a7e422012-06-21 17:29:24 -07001606 if (!mRetransmitEndpointValid)
1607 return NO_INIT;
1608
1609 *endpoint = mRetransmitEndpoint;
1610
1611 return NO_ERROR;
1612}
1613
Gloria Wangb483c472011-04-11 17:23:27 -07001614void MediaPlayerService::Client::notify(
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001615 int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001616{
James Dongb8a98252012-08-26 16:13:03 -07001617 sp<IMediaPlayerClient> c;
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001618 sp<Client> nextClient;
1619 status_t errStartNext = NO_ERROR;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001620 {
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001621 Mutex::Autolock l(mLock);
1622 c = mClient;
1623 if (msg == MEDIA_PLAYBACK_COMPLETE && mNextClient != NULL) {
1624 nextClient = mNextClient;
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001625
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001626 if (mAudioOutput != NULL)
1627 mAudioOutput->switchToNextOutput();
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001628
1629 errStartNext = nextClient->start();
1630 }
1631 }
1632
1633 if (nextClient != NULL) {
1634 sp<IMediaPlayerClient> nc;
1635 {
1636 Mutex::Autolock l(nextClient->mLock);
1637 nc = nextClient->mClient;
1638 }
1639 if (nc != NULL) {
1640 if (errStartNext == NO_ERROR) {
1641 nc->notify(MEDIA_INFO, MEDIA_INFO_STARTED_AS_NEXT, 0, obj);
1642 } else {
1643 nc->notify(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN , 0, obj);
1644 ALOGE("gapless:start playback for next track failed, err(%d)", errStartNext);
Wei Jia2afac0c2016-01-07 12:13:07 -08001645 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001646 }
1647 }
1648
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001649 if (MEDIA_INFO == msg &&
Nicolas Catania48290382009-07-10 13:53:06 -07001650 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikoa64c8c72009-07-20 15:07:26 -07001651 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania48290382009-07-10 13:53:06 -07001652
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001653 if(shouldDropMetadata(metadata_type)) {
Nicolas Catania48290382009-07-10 13:53:06 -07001654 return;
1655 }
1656
1657 // Update the list of metadata that have changed. getMetadata
1658 // also access mMetadataUpdated and clears it.
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001659 addNewMetadataUpdate(metadata_type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001660 }
James Dongb8a98252012-08-26 16:13:03 -07001661
1662 if (c != NULL) {
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001663 ALOGV("[%d] notify (%d, %d, %d)", mConnId, msg, ext1, ext2);
James Dongb8a98252012-08-26 16:13:03 -07001664 c->notify(msg, ext1, ext2, obj);
1665 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001666}
1667
Nicolas Catania48290382009-07-10 13:53:06 -07001668
nikoa64c8c72009-07-20 15:07:26 -07001669bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001670{
Nicolas Catania48290382009-07-10 13:53:06 -07001671 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001672
Nicolas Catania48290382009-07-10 13:53:06 -07001673 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001674 return true;
1675 }
1676
Nicolas Catania48290382009-07-10 13:53:06 -07001677 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001678 return false;
Nicolas Catania48290382009-07-10 13:53:06 -07001679 } else {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001680 return true;
1681 }
1682}
1683
Nicolas Catania48290382009-07-10 13:53:06 -07001684
nikoa64c8c72009-07-20 15:07:26 -07001685void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania48290382009-07-10 13:53:06 -07001686 Mutex::Autolock lock(mLock);
1687 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1688 mMetadataUpdated.add(metadata_type);
1689 }
1690}
1691
Hassan Shojaniacefac142017-02-06 21:02:02 -08001692// Modular DRM
1693status_t MediaPlayerService::Client::prepareDrm(const uint8_t uuid[16],
1694 const Vector<uint8_t>& drmSessionId)
1695{
1696 ALOGV("[%d] prepareDrm", mConnId);
1697 sp<MediaPlayerBase> p = getPlayer();
1698 if (p == 0) return UNKNOWN_ERROR;
1699
1700 status_t ret = p->prepareDrm(uuid, drmSessionId);
1701 ALOGV("prepareDrm ret: %d", ret);
1702
1703 return ret;
1704}
1705
1706status_t MediaPlayerService::Client::releaseDrm()
1707{
1708 ALOGV("[%d] releaseDrm", mConnId);
1709 sp<MediaPlayerBase> p = getPlayer();
1710 if (p == 0) return UNKNOWN_ERROR;
1711
1712 status_t ret = p->releaseDrm();
1713 ALOGV("releaseDrm ret: %d", ret);
1714
1715 return ret;
1716}
1717
jiabin156c6872017-10-06 09:47:15 -07001718status_t MediaPlayerService::Client::setOutputDevice(audio_port_handle_t deviceId)
1719{
1720 ALOGV("[%d] setOutputDevice", mConnId);
1721 {
1722 Mutex::Autolock l(mLock);
1723 if (mAudioOutput.get() != nullptr) {
1724 return mAudioOutput->setOutputDevice(deviceId);
1725 }
1726 }
1727 return NO_INIT;
1728}
1729
1730status_t MediaPlayerService::Client::getRoutedDeviceId(audio_port_handle_t* deviceId)
1731{
1732 ALOGV("[%d] getRoutedDeviceId", mConnId);
1733 {
1734 Mutex::Autolock l(mLock);
1735 if (mAudioOutput.get() != nullptr) {
1736 return mAudioOutput->getRoutedDeviceId(deviceId);
1737 }
1738 }
1739 return NO_INIT;
1740}
1741
1742status_t MediaPlayerService::Client::enableAudioDeviceCallback(bool enabled)
1743{
1744 ALOGV("[%d] enableAudioDeviceCallback, %d", mConnId, enabled);
1745 {
1746 Mutex::Autolock l(mLock);
1747 if (mAudioOutput.get() != nullptr) {
1748 return mAudioOutput->enableAudioDeviceCallback(enabled);
1749 }
1750 }
1751 return NO_INIT;
1752}
1753
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001754#if CALLBACK_ANTAGONIZER
1755const int Antagonizer::interval = 10000; // 10 msecs
1756
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001757Antagonizer::Antagonizer(const sp<MediaPlayerBase::Listener> &listener) :
1758 mExit(false), mActive(false), mListener(listener)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001759{
1760 createThread(callbackThread, this);
1761}
1762
1763void Antagonizer::kill()
1764{
1765 Mutex::Autolock _l(mLock);
1766 mActive = false;
1767 mExit = true;
1768 mCondition.wait(mLock);
1769}
1770
1771int Antagonizer::callbackThread(void* user)
1772{
Steve Blockb8a80522011-12-20 16:23:08 +00001773 ALOGD("Antagonizer started");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001774 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1775 while (!p->mExit) {
1776 if (p->mActive) {
Steve Block3856b092011-10-20 11:56:00 +01001777 ALOGV("send event");
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001778 p->mListener->notify(0, 0, 0, 0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001779 }
1780 usleep(interval);
1781 }
1782 Mutex::Autolock _l(p->mLock);
1783 p->mCondition.signal();
Steve Blockb8a80522011-12-20 16:23:08 +00001784 ALOGD("Antagonizer stopped");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001785 return 0;
1786}
1787#endif
1788
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001789#undef LOG_TAG
1790#define LOG_TAG "AudioSink"
Svet Ganov33761132021-05-13 22:51:08 +00001791MediaPlayerService::AudioOutput::AudioOutput(audio_session_t sessionId,
1792 const AttributionSourceState& attributionSource, const audio_attributes_t* attr,
1793 const sp<AudioSystem::AudioDeviceCallback>& deviceCallback)
Andreas Huber20111aa2009-07-14 16:56:47 -07001794 : mCallback(NULL),
Eric Laurenta514bdb2010-06-21 09:27:30 -07001795 mCallbackCookie(NULL),
Marco Nelissen6b74d672012-02-28 16:07:44 -08001796 mCallbackData(NULL),
Andy Hungd1c74342015-07-07 16:54:23 -07001797 mStreamType(AUDIO_STREAM_MUSIC),
Andy Hungd1c74342015-07-07 16:54:23 -07001798 mLeftVolume(1.0),
1799 mRightVolume(1.0),
1800 mPlaybackRate(AUDIO_PLAYBACK_RATE_DEFAULT),
1801 mSampleRateHz(0),
1802 mMsecsPerFrame(0),
1803 mFrameSize(0),
Eric Laurent1948eb32012-04-13 16:50:19 -07001804 mSessionId(sessionId),
Svet Ganov33761132021-05-13 22:51:08 +00001805 mAttributionSource(attributionSource),
Andy Hungd1c74342015-07-07 16:54:23 -07001806 mSendLevel(0.0),
1807 mAuxEffectId(0),
Andy Hung4ef88d72017-02-21 19:47:53 -08001808 mFlags(AUDIO_OUTPUT_FLAG_NONE),
jiabin156c6872017-10-06 09:47:15 -07001809 mVolumeHandler(new media::VolumeHandler()),
1810 mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE),
jiabin161b64fc2017-11-17 09:31:48 -08001811 mRoutedDeviceId(AUDIO_PORT_HANDLE_NONE),
jiabin156c6872017-10-06 09:47:15 -07001812 mDeviceCallbackEnabled(false),
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001813 mDeviceCallback(deviceCallback)
Andy Hungd1c74342015-07-07 16:54:23 -07001814{
Steve Block3856b092011-10-20 11:56:00 +01001815 ALOGV("AudioOutput(%d)", sessionId);
Eric Laurent43562692015-07-15 16:49:07 -07001816 if (attr != NULL) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001817 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1818 if (mAttributes != NULL) {
1819 memcpy(mAttributes, attr, sizeof(audio_attributes_t));
François Gaffie58d4be52018-11-06 15:30:12 +01001820 mStreamType = AudioSystem::attributesToStreamType(*attr);
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001821 }
1822 } else {
1823 mAttributes = NULL;
Eric Laurent43562692015-07-15 16:49:07 -07001824 }
1825
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001826 setMinBufferCount();
1827}
1828
1829MediaPlayerService::AudioOutput::~AudioOutput()
1830{
1831 close();
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001832 free(mAttributes);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001833 delete mCallbackData;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001834}
1835
Andy Hungd1c74342015-07-07 16:54:23 -07001836//static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001837void MediaPlayerService::AudioOutput::setMinBufferCount()
1838{
Roman Kiryanova3f34462021-03-10 16:17:24 -08001839 if (property_get_bool("ro.boot.qemu", false)) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001840 mIsOnEmulator = true;
1841 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1842 }
1843}
1844
Andy Hungd1c74342015-07-07 16:54:23 -07001845// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001846bool MediaPlayerService::AudioOutput::isOnEmulator()
1847{
Andy Hungd1c74342015-07-07 16:54:23 -07001848 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001849 return mIsOnEmulator;
1850}
1851
Andy Hungd1c74342015-07-07 16:54:23 -07001852// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001853int MediaPlayerService::AudioOutput::getMinBufferCount()
1854{
Andy Hungd1c74342015-07-07 16:54:23 -07001855 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001856 return mMinBufferCount;
1857}
1858
1859ssize_t MediaPlayerService::AudioOutput::bufferSize() 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;
Andy Hungd1c74342015-07-07 16:54:23 -07001863 return mTrack->frameCount() * mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001864}
1865
1866ssize_t MediaPlayerService::AudioOutput::frameCount() 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;
1870 return mTrack->frameCount();
1871}
1872
1873ssize_t MediaPlayerService::AudioOutput::channelCount() const
1874{
Andy Hungd1c74342015-07-07 16:54:23 -07001875 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001876 if (mTrack == 0) return NO_INIT;
1877 return mTrack->channelCount();
1878}
1879
1880ssize_t MediaPlayerService::AudioOutput::frameSize() 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 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001884 return mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001885}
1886
1887uint32_t MediaPlayerService::AudioOutput::latency () const
1888{
Andy Hungd1c74342015-07-07 16:54:23 -07001889 Mutex::Autolock lock(mLock);
Eric Laurentdb354e52012-03-05 17:27:11 -08001890 if (mTrack == 0) return 0;
1891 return mTrack->latency();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001892}
1893
1894float MediaPlayerService::AudioOutput::msecsPerFrame() const
1895{
Andy Hungd1c74342015-07-07 16:54:23 -07001896 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001897 return mMsecsPerFrame;
1898}
1899
Marco Nelissen4110c102012-03-29 09:31:28 -07001900status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position) const
Eric Laurent342e9cf2010-01-19 17:37:09 -08001901{
Andy Hungd1c74342015-07-07 16:54:23 -07001902 Mutex::Autolock lock(mLock);
Eric Laurent342e9cf2010-01-19 17:37:09 -08001903 if (mTrack == 0) return NO_INIT;
1904 return mTrack->getPosition(position);
1905}
1906
Lajos Molnar06ad1522014-08-28 07:27:44 -07001907status_t MediaPlayerService::AudioOutput::getTimestamp(AudioTimestamp &ts) const
1908{
Andy Hungd1c74342015-07-07 16:54:23 -07001909 Mutex::Autolock lock(mLock);
Lajos Molnar06ad1522014-08-28 07:27:44 -07001910 if (mTrack == 0) return NO_INIT;
1911 return mTrack->getTimestamp(ts);
1912}
1913
Wei Jiac4ac8172015-10-21 10:35:48 -07001914// TODO: Remove unnecessary calls to getPlayedOutDurationUs()
1915// as it acquires locks and may query the audio driver.
1916//
1917// Some calls could conceivably retrieve extrapolated data instead of
1918// accessing getTimestamp() or getPosition() every time a data buffer with
1919// a media time is received.
1920//
1921// Calculate duration of played samples if played at normal rate (i.e., 1.0).
1922int64_t MediaPlayerService::AudioOutput::getPlayedOutDurationUs(int64_t nowUs) const
1923{
1924 Mutex::Autolock lock(mLock);
1925 if (mTrack == 0 || mSampleRateHz == 0) {
Wei Jia213f4902015-10-22 08:55:25 -07001926 return 0;
Wei Jiac4ac8172015-10-21 10:35:48 -07001927 }
1928
1929 uint32_t numFramesPlayed;
Andy Hung5d313802016-10-10 15:09:39 -07001930 int64_t numFramesPlayedAtUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001931 AudioTimestamp ts;
Wei Jiac4ac8172015-10-21 10:35:48 -07001932
1933 status_t res = mTrack->getTimestamp(ts);
1934 if (res == OK) { // case 1: mixing audio tracks and offloaded tracks.
1935 numFramesPlayed = ts.mPosition;
Andy Hung5d313802016-10-10 15:09:39 -07001936 numFramesPlayedAtUs = ts.mTime.tv_sec * 1000000LL + ts.mTime.tv_nsec / 1000;
1937 //ALOGD("getTimestamp: OK %d %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001938 } else if (res == WOULD_BLOCK) { // case 2: transitory state on start of a new track
1939 numFramesPlayed = 0;
Andy Hung5d313802016-10-10 15:09:39 -07001940 numFramesPlayedAtUs = nowUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001941 //ALOGD("getTimestamp: WOULD_BLOCK %d %lld",
Andy Hung5d313802016-10-10 15:09:39 -07001942 // numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001943 } else { // case 3: transitory at new track or audio fast tracks.
1944 res = mTrack->getPosition(&numFramesPlayed);
1945 CHECK_EQ(res, (status_t)OK);
Andy Hung5d313802016-10-10 15:09:39 -07001946 numFramesPlayedAtUs = nowUs;
1947 numFramesPlayedAtUs += 1000LL * mTrack->latency() / 2; /* XXX */
1948 //ALOGD("getPosition: %u %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001949 }
1950
1951 // CHECK_EQ(numFramesPlayed & (1 << 31), 0); // can't be negative until 12.4 hrs, test
1952 // TODO: remove the (int32_t) casting below as it may overflow at 12.4 hours.
1953 int64_t durationUs = (int64_t)((int32_t)numFramesPlayed * 1000000LL / mSampleRateHz)
Andy Hung5d313802016-10-10 15:09:39 -07001954 + nowUs - numFramesPlayedAtUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001955 if (durationUs < 0) {
1956 // Occurs when numFramesPlayed position is very small and the following:
1957 // (1) In case 1, the time nowUs is computed before getTimestamp() is called and
Andy Hung5d313802016-10-10 15:09:39 -07001958 // numFramesPlayedAtUs is greater than nowUs by time more than numFramesPlayed.
Wei Jiac4ac8172015-10-21 10:35:48 -07001959 // (2) In case 3, using getPosition and adding mAudioSink->latency() to
Andy Hung5d313802016-10-10 15:09:39 -07001960 // numFramesPlayedAtUs, by a time amount greater than numFramesPlayed.
Wei Jiac4ac8172015-10-21 10:35:48 -07001961 //
1962 // Both of these are transitory conditions.
1963 ALOGV("getPlayedOutDurationUs: negative duration %lld set to zero", (long long)durationUs);
1964 durationUs = 0;
1965 }
1966 ALOGV("getPlayedOutDurationUs(%lld) nowUs(%lld) frames(%u) framesAt(%lld)",
Andy Hung5d313802016-10-10 15:09:39 -07001967 (long long)durationUs, (long long)nowUs,
1968 numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001969 return durationUs;
1970}
1971
Marco Nelissen4110c102012-03-29 09:31:28 -07001972status_t MediaPlayerService::AudioOutput::getFramesWritten(uint32_t *frameswritten) const
1973{
Andy Hungd1c74342015-07-07 16:54:23 -07001974 Mutex::Autolock lock(mLock);
Marco Nelissen4110c102012-03-29 09:31:28 -07001975 if (mTrack == 0) return NO_INIT;
Andy Hung2f6e73d2016-04-08 12:12:58 -07001976 ExtendedTimestamp ets;
1977 status_t status = mTrack->getTimestamp(&ets);
1978 if (status == OK || status == WOULD_BLOCK) {
1979 *frameswritten = (uint32_t)ets.mPosition[ExtendedTimestamp::LOCATION_CLIENT];
1980 }
1981 return status;
Marco Nelissen4110c102012-03-29 09:31:28 -07001982}
1983
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001984status_t MediaPlayerService::AudioOutput::setParameters(const String8& keyValuePairs)
1985{
Andy Hungd1c74342015-07-07 16:54:23 -07001986 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001987 if (mTrack == 0) return NO_INIT;
1988 return mTrack->setParameters(keyValuePairs);
1989}
1990
1991String8 MediaPlayerService::AudioOutput::getParameters(const String8& keys)
1992{
Andy Hungd1c74342015-07-07 16:54:23 -07001993 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001994 if (mTrack == 0) return String8::empty();
1995 return mTrack->getParameters(keys);
1996}
1997
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001998void MediaPlayerService::AudioOutput::setAudioAttributes(const audio_attributes_t * attributes) {
Andy Hungd1c74342015-07-07 16:54:23 -07001999 Mutex::Autolock lock(mLock);
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07002000 if (attributes == NULL) {
2001 free(mAttributes);
2002 mAttributes = NULL;
2003 } else {
2004 if (mAttributes == NULL) {
2005 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
2006 }
2007 memcpy(mAttributes, attributes, sizeof(audio_attributes_t));
François Gaffie58d4be52018-11-06 15:30:12 +01002008 mStreamType = AudioSystem::attributesToStreamType(*attributes);
Eric Laurent43562692015-07-15 16:49:07 -07002009 }
2010}
2011
2012void MediaPlayerService::AudioOutput::setAudioStreamType(audio_stream_type_t streamType)
2013{
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07002014 Mutex::Autolock lock(mLock);
Eric Laurent43562692015-07-15 16:49:07 -07002015 // do not allow direct stream type modification if attributes have been set
2016 if (mAttributes == NULL) {
2017 mStreamType = streamType;
2018 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07002019}
2020
Andy Hungd1c74342015-07-07 16:54:23 -07002021void MediaPlayerService::AudioOutput::deleteRecycledTrack_l()
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002022{
Andy Hungd1c74342015-07-07 16:54:23 -07002023 ALOGV("deleteRecycledTrack_l");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002024 if (mRecycledTrack != 0) {
2025
2026 if (mCallbackData != NULL) {
2027 mCallbackData->setOutput(NULL);
2028 mCallbackData->endTrackSwitch();
2029 }
2030
2031 if ((mRecycledTrack->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) {
Andy Hunge13f8a62016-03-30 14:20:42 -07002032 int32_t msec = 0;
2033 if (!mRecycledTrack->stopped()) { // check if active
2034 (void)mRecycledTrack->pendingDuration(&msec);
2035 }
2036 mRecycledTrack->stop(); // ensure full data drain
2037 ALOGD("deleting recycled track, waiting for data drain (%d msec)", msec);
2038 if (msec > 0) {
2039 static const int32_t WAIT_LIMIT_MS = 3000;
2040 if (msec > WAIT_LIMIT_MS) {
2041 msec = WAIT_LIMIT_MS;
2042 }
2043 usleep(msec * 1000LL);
2044 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002045 }
2046 // An offloaded track isn't flushed because the STREAM_END is reported
2047 // slightly prematurely to allow time for the gapless track switch
2048 // but this means that if we decide not to recycle the track there
2049 // could be a small amount of residual data still playing. We leave
2050 // AudioFlinger to drain the track.
2051
2052 mRecycledTrack.clear();
Andy Hungd1c74342015-07-07 16:54:23 -07002053 close_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002054 delete mCallbackData;
2055 mCallbackData = NULL;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002056 }
2057}
2058
Andy Hungd1c74342015-07-07 16:54:23 -07002059void MediaPlayerService::AudioOutput::close_l()
2060{
2061 mTrack.clear();
2062}
2063
Andreas Huber20111aa2009-07-14 16:56:47 -07002064status_t MediaPlayerService::AudioOutput::open(
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08002065 uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
2066 audio_format_t format, int bufferCount,
Eric Laurent1948eb32012-04-13 16:50:19 -07002067 AudioCallback cb, void *cookie,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002068 audio_output_flags_t flags,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07002069 const audio_offload_info_t *offloadInfo,
Andy Hung179652e2015-05-31 22:49:46 -07002070 bool doNotReconnect,
2071 uint32_t suggestedFrameCount)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002072{
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002073 ALOGV("open(%u, %d, 0x%x, 0x%x, %d, %d 0x%x)", sampleRate, channelCount, channelMask,
2074 format, bufferCount, mSessionId, flags);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002075
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002076 // offloading is only supported in callback mode for now.
2077 // offloadInfo must be present if offload flag is set
2078 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) &&
2079 ((cb == NULL) || (offloadInfo == NULL))) {
2080 return BAD_VALUE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002081 }
2082
Andy Hung179652e2015-05-31 22:49:46 -07002083 // compute frame count for the AudioTrack internal buffer
2084 size_t frameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002085 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
2086 frameCount = 0; // AudioTrack will get frame count from AudioFlinger
2087 } else {
Andy Hung179652e2015-05-31 22:49:46 -07002088 // try to estimate the buffer processing fetch size from AudioFlinger.
2089 // framesPerBuffer is approximate and generally correct, except when it's not :-).
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002090 uint32_t afSampleRate;
2091 size_t afFrameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002092 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
2093 return NO_INIT;
2094 }
2095 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
2096 return NO_INIT;
2097 }
Ben Romberger259fb462018-08-07 17:58:53 -07002098 if (afSampleRate == 0) {
2099 return NO_INIT;
2100 }
Andy Hung179652e2015-05-31 22:49:46 -07002101 const size_t framesPerBuffer =
2102 (unsigned long long)sampleRate * afFrameCount / afSampleRate;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002103
Andy Hung179652e2015-05-31 22:49:46 -07002104 if (bufferCount == 0) {
Ben Romberger259fb462018-08-07 17:58:53 -07002105 if (framesPerBuffer == 0) {
2106 return NO_INIT;
2107 }
Andy Hung179652e2015-05-31 22:49:46 -07002108 // use suggestedFrameCount
2109 bufferCount = (suggestedFrameCount + framesPerBuffer - 1) / framesPerBuffer;
2110 }
2111 // Check argument bufferCount against the mininum buffer count
2112 if (bufferCount != 0 && bufferCount < mMinBufferCount) {
2113 ALOGV("bufferCount (%d) increased to %d", bufferCount, mMinBufferCount);
2114 bufferCount = mMinBufferCount;
2115 }
2116 // if frameCount is 0, then AudioTrack will get frame count from AudioFlinger
2117 // which will be the minimum size permitted.
2118 frameCount = bufferCount * framesPerBuffer;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002119 }
Andreas Huber20111aa2009-07-14 16:56:47 -07002120
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08002121 if (channelMask == CHANNEL_MASK_USE_CHANNEL_ORDER) {
Glenn Kastenab334fd2012-03-14 12:56:06 -07002122 channelMask = audio_channel_out_mask_from_count(channelCount);
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08002123 if (0 == channelMask) {
2124 ALOGE("open() error, can\'t derive mask for %d audio channels", channelCount);
2125 return NO_INIT;
2126 }
2127 }
Eric Laurent1948eb32012-04-13 16:50:19 -07002128
Andy Hungd1c74342015-07-07 16:54:23 -07002129 Mutex::Autolock lock(mLock);
Andy Hung179652e2015-05-31 22:49:46 -07002130 mCallback = cb;
2131 mCallbackCookie = cookie;
2132
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002133 // Check whether we can recycle the track
2134 bool reuse = false;
2135 bool bothOffloaded = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07002136
Glenn Kasten2799d742013-05-30 14:33:29 -07002137 if (mRecycledTrack != 0) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002138 // check whether we are switching between two offloaded tracks
2139 bothOffloaded = (flags & mRecycledTrack->getFlags()
2140 & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0;
Marco Nelissen67295b52012-06-11 14:52:53 -07002141
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002142 // check if the existing track can be reused as-is, or if a new track needs to be created.
2143 reuse = true;
2144
Marco Nelissen67295b52012-06-11 14:52:53 -07002145 if ((mCallbackData == NULL && mCallback != NULL) ||
2146 (mCallbackData != NULL && mCallback == NULL)) {
2147 // recycled track uses callbacks but the caller wants to use writes, or vice versa
2148 ALOGV("can't chain callback and write");
2149 reuse = false;
2150 } else if ((mRecycledTrack->getSampleRate() != sampleRate) ||
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002151 (mRecycledTrack->channelCount() != (uint32_t)channelCount) ) {
2152 ALOGV("samplerate, channelcount differ: %u/%u Hz, %u/%d ch",
Marco Nelissen67295b52012-06-11 14:52:53 -07002153 mRecycledTrack->getSampleRate(), sampleRate,
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002154 mRecycledTrack->channelCount(), channelCount);
Marco Nelissen67295b52012-06-11 14:52:53 -07002155 reuse = false;
2156 } else if (flags != mFlags) {
2157 ALOGV("output flags differ %08x/%08x", flags, mFlags);
2158 reuse = false;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002159 } else if (mRecycledTrack->format() != format) {
2160 reuse = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07002161 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002162 } else {
2163 ALOGV("no track available to recycle");
2164 }
2165
2166 ALOGV_IF(bothOffloaded, "both tracks offloaded");
2167
2168 // If we can't recycle and both tracks are offloaded
2169 // we must close the previous output before opening a new one
2170 if (bothOffloaded && !reuse) {
2171 ALOGV("both offloaded and not recycling");
Andy Hungd1c74342015-07-07 16:54:23 -07002172 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002173 }
2174
2175 sp<AudioTrack> t;
2176 CallbackData *newcbd = NULL;
2177
2178 // We don't attempt to create a new track if we are recycling an
2179 // offloaded track. But, if we are recycling a non-offloaded or we
2180 // are switching where one is offloaded and one isn't then we create
2181 // the new track in advance so that we can read additional stream info
2182
2183 if (!(reuse && bothOffloaded)) {
2184 ALOGV("creating new AudioTrack");
2185
2186 if (mCallback != NULL) {
2187 newcbd = new CallbackData(this);
2188 t = new AudioTrack(
2189 mStreamType,
2190 sampleRate,
2191 format,
2192 channelMask,
2193 frameCount,
2194 flags,
2195 CallbackWrapper,
2196 newcbd,
2197 0, // notification frames
2198 mSessionId,
2199 AudioTrack::TRANSFER_CALLBACK,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002200 offloadInfo,
Svet Ganov33761132021-05-13 22:51:08 +00002201 mAttributionSource,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07002202 mAttributes,
jiabin156c6872017-10-06 09:47:15 -07002203 doNotReconnect,
2204 1.0f, // default value for maxRequiredSpeed
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002205 mSelectedDeviceId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002206 } else {
Andy Hungff874dc2016-04-11 16:49:09 -07002207 // TODO: Due to buffer memory concerns, we use a max target playback speed
2208 // based on mPlaybackRate at the time of open (instead of kMaxRequiredSpeed),
2209 // also clamping the target speed to 1.0 <= targetSpeed <= kMaxRequiredSpeed.
2210 const float targetSpeed =
2211 std::min(std::max(mPlaybackRate.mSpeed, 1.0f), kMaxRequiredSpeed);
2212 ALOGW_IF(targetSpeed != mPlaybackRate.mSpeed,
2213 "track target speed:%f clamped from playback speed:%f",
2214 targetSpeed, mPlaybackRate.mSpeed);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002215 t = new AudioTrack(
2216 mStreamType,
2217 sampleRate,
2218 format,
2219 channelMask,
2220 frameCount,
2221 flags,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002222 NULL, // callback
2223 NULL, // user data
2224 0, // notification frames
2225 mSessionId,
2226 AudioTrack::TRANSFER_DEFAULT,
2227 NULL, // offload info
Svet Ganov33761132021-05-13 22:51:08 +00002228 mAttributionSource,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07002229 mAttributes,
Andy Hungff874dc2016-04-11 16:49:09 -07002230 doNotReconnect,
jiabin156c6872017-10-06 09:47:15 -07002231 targetSpeed,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002232 mSelectedDeviceId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002233 }
Andy Hunga6b27032020-04-27 10:34:24 -07002234 // Set caller name so it can be logged in destructor.
2235 // MediaMetricsConstants.h: AMEDIAMETRICS_PROP_CALLERNAME_VALUE_MEDIA
2236 t->setCallerName("media");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002237 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
2238 ALOGE("Unable to create audio track");
2239 delete newcbd;
Glenn Kasten3e98ecd2015-05-18 13:13:24 -07002240 // t goes out of scope, so reference count drops to zero
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002241 return NO_INIT;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07002242 } else {
2243 // successful AudioTrack initialization implies a legacy stream type was generated
2244 // from the audio attributes
2245 mStreamType = t->streamType();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002246 }
2247 }
2248
2249 if (reuse) {
2250 CHECK(mRecycledTrack != NULL);
2251
2252 if (!bothOffloaded) {
2253 if (mRecycledTrack->frameCount() != t->frameCount()) {
Andy Hung833b4752016-04-04 17:15:48 -07002254 ALOGV("framecount differs: %zu/%zu frames",
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002255 mRecycledTrack->frameCount(), t->frameCount());
2256 reuse = false;
2257 }
Jaideep Sharmab3ce4482020-11-16 11:52:35 +05302258 // If recycled and new tracks are not on the same output,
2259 // don't reuse the recycled one.
2260 if (mRecycledTrack->getOutput() != t->getOutput()) {
2261 ALOGV("output has changed, don't reuse track");
2262 reuse = false;
2263 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002264 }
2265
Marco Nelissen67295b52012-06-11 14:52:53 -07002266 if (reuse) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002267 ALOGV("chaining to next output and recycling track");
Andy Hungd1c74342015-07-07 16:54:23 -07002268 close_l();
Marco Nelissen67295b52012-06-11 14:52:53 -07002269 mTrack = mRecycledTrack;
Glenn Kasten2799d742013-05-30 14:33:29 -07002270 mRecycledTrack.clear();
Marco Nelissen67295b52012-06-11 14:52:53 -07002271 if (mCallbackData != NULL) {
2272 mCallbackData->setOutput(this);
2273 }
Marco Nelissen67295b52012-06-11 14:52:53 -07002274 delete newcbd;
Wei Jiae0bbac92016-07-18 16:04:53 -07002275 return updateTrack();
Marco Nelissen67295b52012-06-11 14:52:53 -07002276 }
Marco Nelissen67295b52012-06-11 14:52:53 -07002277 }
2278
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002279 // we're not going to reuse the track, unblock and flush it
2280 // this was done earlier if both tracks are offloaded
2281 if (!bothOffloaded) {
Andy Hungd1c74342015-07-07 16:54:23 -07002282 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002283 }
2284
2285 CHECK((t != NULL) && ((mCallback == NULL) || (newcbd != NULL)));
2286
Marco Nelissen67295b52012-06-11 14:52:53 -07002287 mCallbackData = newcbd;
Steve Block3856b092011-10-20 11:56:00 +01002288 ALOGV("setVolume");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002289 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07002290
Andy Hung39399b62017-04-21 15:07:45 -07002291 // Restore VolumeShapers for the MediaPlayer in case the track was recreated
2292 // due to an output sink error (e.g. offload to non-offload switch).
2293 mVolumeHandler->forall([&t](const VolumeShaper &shaper) -> VolumeShaper::Status {
2294 sp<VolumeShaper::Operation> operationToEnd =
2295 new VolumeShaper::Operation(shaper.mOperation);
2296 // TODO: Ideally we would restore to the exact xOffset position
2297 // as returned by getVolumeShaperState(), but we don't have that
2298 // information when restoring at the client unless we periodically poll
2299 // the server or create shared memory state.
2300 //
2301 // For now, we simply advance to the end of the VolumeShaper effect
2302 // if it has been started.
2303 if (shaper.isStarted()) {
Andy Hungf3702642017-05-05 17:33:32 -07002304 operationToEnd->setNormalizedTime(1.f);
Andy Hung39399b62017-04-21 15:07:45 -07002305 }
2306 return t->applyVolumeShaper(shaper.mConfiguration, operationToEnd);
Andy Hung4ef88d72017-02-21 19:47:53 -08002307 });
Andy Hung4ef88d72017-02-21 19:47:53 -08002308
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002309 mSampleRateHz = sampleRate;
Preetam Singh Ranawat2e17eef2015-08-12 12:11:46 -07002310 mFlags = flags;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002311 mMsecsPerFrame = 1E3f / (mPlaybackRate.mSpeed * sampleRate);
Andy Hungd1c74342015-07-07 16:54:23 -07002312 mFrameSize = t->frameSize();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002313 mTrack = t;
Eric Laurent2beeb502010-07-16 07:43:46 -07002314
Wei Jiae0bbac92016-07-18 16:04:53 -07002315 return updateTrack();
2316}
2317
2318status_t MediaPlayerService::AudioOutput::updateTrack() {
2319 if (mTrack == NULL) {
2320 return NO_ERROR;
2321 }
2322
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002323 status_t res = NO_ERROR;
Wei Jia0162d002015-06-09 11:59:33 -07002324 // Note some output devices may give us a direct track even though we don't specify it.
2325 // Example: Line application b/17459982.
Wei Jiae0bbac92016-07-18 16:04:53 -07002326 if ((mTrack->getFlags()
2327 & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) {
2328 res = mTrack->setPlaybackRate(mPlaybackRate);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002329 if (res == NO_ERROR) {
Wei Jiae0bbac92016-07-18 16:04:53 -07002330 mTrack->setAuxEffectSendLevel(mSendLevel);
2331 res = mTrack->attachAuxEffect(mAuxEffectId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002332 }
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002333 }
jiabin156c6872017-10-06 09:47:15 -07002334 mTrack->setOutputDevice(mSelectedDeviceId);
2335 if (mDeviceCallbackEnabled) {
2336 mTrack->addAudioDeviceCallback(mDeviceCallback.promote());
2337 }
Wei Jiae0bbac92016-07-18 16:04:53 -07002338 ALOGV("updateTrack() DONE status %d", res);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002339 return res;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002340}
2341
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002342status_t MediaPlayerService::AudioOutput::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002343{
Steve Block3856b092011-10-20 11:56:00 +01002344 ALOGV("start");
Andy Hungd1c74342015-07-07 16:54:23 -07002345 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08002346 if (mCallbackData != NULL) {
2347 mCallbackData->endTrackSwitch();
2348 }
Glenn Kasten2799d742013-05-30 14:33:29 -07002349 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002350 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07002351 mTrack->setAuxEffectSendLevel(mSendLevel);
Andy Hung39399b62017-04-21 15:07:45 -07002352 status_t status = mTrack->start();
2353 if (status == NO_ERROR) {
2354 mVolumeHandler->setStarted();
2355 }
2356 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002357 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002358 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002359}
2360
Marco Nelissen6b74d672012-02-28 16:07:44 -08002361void MediaPlayerService::AudioOutput::setNextOutput(const sp<AudioOutput>& nextOutput) {
Andy Hungd1c74342015-07-07 16:54:23 -07002362 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08002363 mNextOutput = nextOutput;
2364}
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08002365
Marco Nelissen6b74d672012-02-28 16:07:44 -08002366void MediaPlayerService::AudioOutput::switchToNextOutput() {
2367 ALOGV("switchToNextOutput");
Andy Hungd1c74342015-07-07 16:54:23 -07002368
2369 // Try to acquire the callback lock before moving track (without incurring deadlock).
2370 const unsigned kMaxSwitchTries = 100;
2371 Mutex::Autolock lock(mLock);
2372 for (unsigned tries = 0;;) {
2373 if (mTrack == 0) {
2374 return;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002375 }
Andy Hungd1c74342015-07-07 16:54:23 -07002376 if (mNextOutput != NULL && mNextOutput != this) {
2377 if (mCallbackData != NULL) {
2378 // two alternative approaches
2379#if 1
2380 CallbackData *callbackData = mCallbackData;
2381 mLock.unlock();
2382 // proper acquisition sequence
2383 callbackData->lock();
2384 mLock.lock();
2385 // Caution: it is unlikely that someone deleted our callback or changed our target
2386 if (callbackData != mCallbackData || mNextOutput == NULL || mNextOutput == this) {
2387 // fatal if we are starved out.
2388 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2389 "switchToNextOutput() cannot obtain correct lock sequence");
2390 callbackData->unlock();
2391 continue;
2392 }
2393 callbackData->mSwitching = true; // begin track switch
Wei Jiaadee56a2016-08-05 15:40:34 -07002394 callbackData->setOutput(NULL);
Andy Hungd1c74342015-07-07 16:54:23 -07002395#else
2396 // tryBeginTrackSwitch() returns false if the callback has the lock.
2397 if (!mCallbackData->tryBeginTrackSwitch()) {
2398 // fatal if we are starved out.
2399 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2400 "switchToNextOutput() cannot obtain callback lock");
2401 mLock.unlock();
2402 usleep(5 * 1000 /* usec */); // allow callback to use AudioOutput
2403 mLock.lock();
2404 continue;
2405 }
2406#endif
2407 }
2408
2409 Mutex::Autolock nextLock(mNextOutput->mLock);
2410
2411 // If the next output track is not NULL, then it has been
2412 // opened already for playback.
2413 // This is possible even without the next player being started,
2414 // for example, the next player could be prepared and seeked.
2415 //
2416 // Presuming it isn't advisable to force the track over.
2417 if (mNextOutput->mTrack == NULL) {
2418 ALOGD("Recycling track for gapless playback");
2419 delete mNextOutput->mCallbackData;
2420 mNextOutput->mCallbackData = mCallbackData;
2421 mNextOutput->mRecycledTrack = mTrack;
2422 mNextOutput->mSampleRateHz = mSampleRateHz;
2423 mNextOutput->mMsecsPerFrame = mMsecsPerFrame;
Andy Hungd1c74342015-07-07 16:54:23 -07002424 mNextOutput->mFlags = mFlags;
2425 mNextOutput->mFrameSize = mFrameSize;
2426 close_l();
2427 mCallbackData = NULL; // destruction handled by mNextOutput
2428 } else {
2429 ALOGW("Ignoring gapless playback because next player has already started");
2430 // remove track in case resource needed for future players.
2431 if (mCallbackData != NULL) {
2432 mCallbackData->endTrackSwitch(); // release lock for callbacks before close.
2433 }
2434 close_l();
2435 }
2436 }
2437 break;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002438 }
2439}
2440
Wei Jia7d3f4df2015-03-03 15:28:00 -08002441ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002442{
Andy Hungd1c74342015-07-07 16:54:23 -07002443 Mutex::Autolock lock(mLock);
Glenn Kastenadad3d72014-02-21 14:51:43 -08002444 LOG_ALWAYS_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
Andreas Huber20111aa2009-07-14 16:56:47 -07002445
Steve Block3856b092011-10-20 11:56:00 +01002446 //ALOGV("write(%p, %u)", buffer, size);
Glenn Kasten2799d742013-05-30 14:33:29 -07002447 if (mTrack != 0) {
Andy Hung2f6e73d2016-04-08 12:12:58 -07002448 return mTrack->write(buffer, size, blocking);
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07002449 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002450 return NO_INIT;
2451}
2452
2453void MediaPlayerService::AudioOutput::stop()
2454{
Steve Block3856b092011-10-20 11:56:00 +01002455 ALOGV("stop");
Andy Hungd1c74342015-07-07 16:54:23 -07002456 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002457 if (mTrack != 0) mTrack->stop();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002458}
2459
2460void MediaPlayerService::AudioOutput::flush()
2461{
Steve Block3856b092011-10-20 11:56:00 +01002462 ALOGV("flush");
Andy Hungd1c74342015-07-07 16:54:23 -07002463 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002464 if (mTrack != 0) mTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002465}
2466
2467void MediaPlayerService::AudioOutput::pause()
2468{
Steve Block3856b092011-10-20 11:56:00 +01002469 ALOGV("pause");
Andy Hungd1c74342015-07-07 16:54:23 -07002470 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002471 if (mTrack != 0) mTrack->pause();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002472}
2473
2474void MediaPlayerService::AudioOutput::close()
2475{
Steve Block3856b092011-10-20 11:56:00 +01002476 ALOGV("close");
Erik Wolsheimer7845a1f2015-10-30 12:07:52 -07002477 sp<AudioTrack> track;
2478 {
2479 Mutex::Autolock lock(mLock);
2480 track = mTrack;
2481 close_l(); // clears mTrack
2482 }
2483 // destruction of the track occurs outside of mutex.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002484}
2485
2486void MediaPlayerService::AudioOutput::setVolume(float left, float right)
2487{
Steve Block3856b092011-10-20 11:56:00 +01002488 ALOGV("setVolume(%f, %f)", left, right);
Andy Hungd1c74342015-07-07 16:54:23 -07002489 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002490 mLeftVolume = left;
2491 mRightVolume = right;
Glenn Kasten2799d742013-05-30 14:33:29 -07002492 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002493 mTrack->setVolume(left, right);
2494 }
2495}
2496
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002497status_t MediaPlayerService::AudioOutput::setPlaybackRate(const AudioPlaybackRate &rate)
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002498{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002499 ALOGV("setPlaybackRate(%f %f %d %d)",
2500 rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Andy Hungd1c74342015-07-07 16:54:23 -07002501 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002502 if (mTrack == 0) {
2503 // remember rate so that we can set it when the track is opened
2504 mPlaybackRate = rate;
2505 return OK;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002506 }
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002507 status_t res = mTrack->setPlaybackRate(rate);
2508 if (res != NO_ERROR) {
2509 return res;
2510 }
2511 // rate.mSpeed is always greater than 0 if setPlaybackRate succeeded
2512 CHECK_GT(rate.mSpeed, 0.f);
2513 mPlaybackRate = rate;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002514 if (mSampleRateHz != 0) {
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002515 mMsecsPerFrame = 1E3f / (rate.mSpeed * mSampleRateHz);
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002516 }
2517 return res;
2518}
2519
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002520status_t MediaPlayerService::AudioOutput::getPlaybackRate(AudioPlaybackRate *rate)
2521{
2522 ALOGV("setPlaybackRate");
Andy Hungd1c74342015-07-07 16:54:23 -07002523 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002524 if (mTrack == 0) {
2525 return NO_INIT;
2526 }
2527 *rate = mTrack->getPlaybackRate();
2528 return NO_ERROR;
2529}
2530
Eric Laurent2beeb502010-07-16 07:43:46 -07002531status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
2532{
Steve Block3856b092011-10-20 11:56:00 +01002533 ALOGV("setAuxEffectSendLevel(%f)", level);
Andy Hungd1c74342015-07-07 16:54:23 -07002534 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002535 mSendLevel = level;
Glenn Kasten2799d742013-05-30 14:33:29 -07002536 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002537 return mTrack->setAuxEffectSendLevel(level);
2538 }
2539 return NO_ERROR;
2540}
2541
2542status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
2543{
Steve Block3856b092011-10-20 11:56:00 +01002544 ALOGV("attachAuxEffect(%d)", effectId);
Andy Hungd1c74342015-07-07 16:54:23 -07002545 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002546 mAuxEffectId = effectId;
Glenn Kasten2799d742013-05-30 14:33:29 -07002547 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002548 return mTrack->attachAuxEffect(effectId);
2549 }
2550 return NO_ERROR;
2551}
2552
jiabin156c6872017-10-06 09:47:15 -07002553status_t MediaPlayerService::AudioOutput::setOutputDevice(audio_port_handle_t deviceId)
2554{
2555 ALOGV("setOutputDevice(%d)", deviceId);
2556 Mutex::Autolock lock(mLock);
2557 mSelectedDeviceId = deviceId;
2558 if (mTrack != 0) {
2559 return mTrack->setOutputDevice(deviceId);
2560 }
2561 return NO_ERROR;
2562}
2563
2564status_t MediaPlayerService::AudioOutput::getRoutedDeviceId(audio_port_handle_t* deviceId)
2565{
2566 ALOGV("getRoutedDeviceId");
2567 Mutex::Autolock lock(mLock);
2568 if (mTrack != 0) {
jiabin161b64fc2017-11-17 09:31:48 -08002569 mRoutedDeviceId = mTrack->getRoutedDeviceId();
jiabin156c6872017-10-06 09:47:15 -07002570 }
jiabin161b64fc2017-11-17 09:31:48 -08002571 *deviceId = mRoutedDeviceId;
2572 return NO_ERROR;
jiabin156c6872017-10-06 09:47:15 -07002573}
2574
2575status_t MediaPlayerService::AudioOutput::enableAudioDeviceCallback(bool enabled)
2576{
2577 ALOGV("enableAudioDeviceCallback, %d", enabled);
2578 Mutex::Autolock lock(mLock);
2579 mDeviceCallbackEnabled = enabled;
2580 if (mTrack != 0) {
2581 status_t status;
2582 if (enabled) {
2583 status = mTrack->addAudioDeviceCallback(mDeviceCallback.promote());
2584 } else {
2585 status = mTrack->removeAudioDeviceCallback(mDeviceCallback.promote());
2586 }
2587 return status;
2588 }
2589 return NO_ERROR;
2590}
2591
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002592VolumeShaper::Status MediaPlayerService::AudioOutput::applyVolumeShaper(
2593 const sp<VolumeShaper::Configuration>& configuration,
2594 const sp<VolumeShaper::Operation>& operation)
2595{
2596 Mutex::Autolock lock(mLock);
2597 ALOGV("AudioOutput::applyVolumeShaper");
Andy Hung4ef88d72017-02-21 19:47:53 -08002598
Andy Hung4ef88d72017-02-21 19:47:53 -08002599 mVolumeHandler->setIdIfNecessary(configuration);
Andy Hung39399b62017-04-21 15:07:45 -07002600
2601 VolumeShaper::Status status;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002602 if (mTrack != 0) {
Andy Hung39399b62017-04-21 15:07:45 -07002603 status = mTrack->applyVolumeShaper(configuration, operation);
2604 if (status >= 0) {
2605 (void)mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hungf3702642017-05-05 17:33:32 -07002606 if (mTrack->isPlaying()) { // match local AudioTrack to properly restore.
2607 mVolumeHandler->setStarted();
2608 }
Andy Hung39399b62017-04-21 15:07:45 -07002609 }
Andy Hung4ef88d72017-02-21 19:47:53 -08002610 } else {
Andy Hungc01eddb2017-07-21 16:42:41 -07002611 // VolumeShapers are not affected when a track moves between players for
2612 // gapless playback (setNextMediaPlayer).
2613 // We forward VolumeShaper operations that do not change configuration
2614 // to the new player so that unducking may occur as expected.
2615 // Unducking is an idempotent operation, same if applied back-to-back.
2616 if (configuration->getType() == VolumeShaper::Configuration::TYPE_ID
2617 && mNextOutput != nullptr) {
2618 ALOGV("applyVolumeShaper: Attempting to forward missed operation: %s %s",
2619 configuration->toString().c_str(), operation->toString().c_str());
2620 Mutex::Autolock nextLock(mNextOutput->mLock);
2621
2622 // recycled track should be forwarded from this AudioSink by switchToNextOutput
2623 sp<AudioTrack> track = mNextOutput->mRecycledTrack;
2624 if (track != nullptr) {
2625 ALOGD("Forward VolumeShaper operation to recycled track %p", track.get());
2626 (void)track->applyVolumeShaper(configuration, operation);
2627 } else {
2628 // There is a small chance that the unduck occurs after the next
2629 // player has already started, but before it is registered to receive
2630 // the unduck command.
2631 track = mNextOutput->mTrack;
2632 if (track != nullptr) {
2633 ALOGD("Forward VolumeShaper operation to track %p", track.get());
2634 (void)track->applyVolumeShaper(configuration, operation);
2635 }
2636 }
2637 }
Andy Hung39399b62017-04-21 15:07:45 -07002638 status = mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002639 }
Andy Hung39399b62017-04-21 15:07:45 -07002640 return status;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002641}
2642
2643sp<VolumeShaper::State> MediaPlayerService::AudioOutput::getVolumeShaperState(int id)
2644{
2645 Mutex::Autolock lock(mLock);
2646 if (mTrack != 0) {
2647 return mTrack->getVolumeShaperState(id);
Andy Hung4ef88d72017-02-21 19:47:53 -08002648 } else {
2649 return mVolumeHandler->getVolumeShaperState(id);
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002650 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002651}
2652
Andreas Huber20111aa2009-07-14 16:56:47 -07002653// static
2654void MediaPlayerService::AudioOutput::CallbackWrapper(
Glenn Kastend217a8c2011-06-01 15:20:35 -07002655 int event, void *cookie, void *info) {
Steve Block3856b092011-10-20 11:56:00 +01002656 //ALOGV("callbackwrapper");
Marco Nelissen6b74d672012-02-28 16:07:44 -08002657 CallbackData *data = (CallbackData*)cookie;
Andy Hungd1c74342015-07-07 16:54:23 -07002658 // lock to ensure we aren't caught in the middle of a track switch.
Marco Nelissen6b74d672012-02-28 16:07:44 -08002659 data->lock();
2660 AudioOutput *me = data->getOutput();
Andreas Huber20111aa2009-07-14 16:56:47 -07002661 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002662 if (me == NULL) {
2663 // no output set, likely because the track was scheduled to be reused
2664 // by another player, but the format turned out to be incompatible.
2665 data->unlock();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002666 if (buffer != NULL) {
2667 buffer->size = 0;
2668 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08002669 return;
2670 }
Andreas Huber20111aa2009-07-14 16:56:47 -07002671
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002672 switch(event) {
2673 case AudioTrack::EVENT_MORE_DATA: {
2674 size_t actualSize = (*me->mCallback)(
2675 me, buffer->raw, buffer->size, me->mCallbackCookie,
2676 CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002677
Andy Hung719b46b2015-05-31 22:18:25 -07002678 // Log when no data is returned from the callback.
2679 // (1) We may have no data (especially with network streaming sources).
2680 // (2) We may have reached the EOS and the audio track is not stopped yet.
2681 // Note that AwesomePlayer/AudioPlayer will only return zero size when it reaches the EOS.
2682 // NuPlayerRenderer will return zero when it doesn't have data (it doesn't block to fill).
2683 //
2684 // This is a benign busy-wait, with the next data request generated 10 ms or more later;
2685 // nevertheless for power reasons, we don't want to see too many of these.
Andreas Huber2e8ffaf2010-02-18 16:45:13 -08002686
Andy Hung719b46b2015-05-31 22:18:25 -07002687 ALOGV_IF(actualSize == 0 && buffer->size > 0, "callbackwrapper: empty buffer returned");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002688
2689 buffer->size = actualSize;
2690 } break;
2691
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002692 case AudioTrack::EVENT_STREAM_END:
Andy Hung719b46b2015-05-31 22:18:25 -07002693 // currently only occurs for offloaded callbacks
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002694 ALOGV("callbackwrapper: deliver EVENT_STREAM_END");
2695 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2696 me->mCallbackCookie, CB_EVENT_STREAM_END);
2697 break;
2698
2699 case AudioTrack::EVENT_NEW_IAUDIOTRACK :
2700 ALOGV("callbackwrapper: deliver EVENT_TEAR_DOWN");
2701 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2702 me->mCallbackCookie, CB_EVENT_TEAR_DOWN);
2703 break;
2704
Glenn Kasten421743b2015-06-01 08:18:08 -07002705 case AudioTrack::EVENT_UNDERRUN:
Andy Hung719b46b2015-05-31 22:18:25 -07002706 // This occurs when there is no data available, typically
Glenn Kasten421743b2015-06-01 08:18:08 -07002707 // when there is a failure to supply data to the AudioTrack. It can also
2708 // occur in non-offloaded mode when the audio device comes out of standby.
2709 //
Andy Hung719b46b2015-05-31 22:18:25 -07002710 // If an AudioTrack underruns it outputs silence. Since this happens suddenly
2711 // it may sound like an audible pop or glitch.
2712 //
2713 // The underrun event is sent once per track underrun; the condition is reset
2714 // when more data is sent to the AudioTrack.
Eric Laurente93cc032016-05-05 10:15:10 -07002715 ALOGD("callbackwrapper: EVENT_UNDERRUN (discarded)");
Glenn Kasten421743b2015-06-01 08:18:08 -07002716 break;
2717
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002718 default:
2719 ALOGE("received unknown event type: %d inside CallbackWrapper !", event);
Andreas Huber51c1e0e2011-04-04 11:43:40 -07002720 }
2721
Marco Nelissen6b74d672012-02-28 16:07:44 -08002722 data->unlock();
Andreas Huber20111aa2009-07-14 16:56:47 -07002723}
2724
Glenn Kastend848eb42016-03-08 13:42:11 -08002725audio_session_t MediaPlayerService::AudioOutput::getSessionId() const
Eric Laurent8c563ed2010-10-07 18:23:03 -07002726{
Andy Hungd1c74342015-07-07 16:54:23 -07002727 Mutex::Autolock lock(mLock);
Eric Laurent8c563ed2010-10-07 18:23:03 -07002728 return mSessionId;
2729}
2730
Eric Laurent6f59db12013-07-26 17:16:50 -07002731uint32_t MediaPlayerService::AudioOutput::getSampleRate() const
2732{
Andy Hungd1c74342015-07-07 16:54:23 -07002733 Mutex::Autolock lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -07002734 if (mTrack == 0) return 0;
2735 return mTrack->getSampleRate();
2736}
2737
Andy Hungf2c87b32016-04-07 19:49:29 -07002738int64_t MediaPlayerService::AudioOutput::getBufferDurationInUs() const
2739{
2740 Mutex::Autolock lock(mLock);
2741 if (mTrack == 0) {
2742 return 0;
2743 }
2744 int64_t duration;
2745 if (mTrack->getBufferDurationInUs(&duration) != OK) {
2746 return 0;
2747 }
2748 return duration;
2749}
2750
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002751////////////////////////////////////////////////////////////////////////////////
2752
2753struct CallbackThread : public Thread {
2754 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
2755 MediaPlayerBase::AudioSink::AudioCallback cb,
2756 void *cookie);
2757
2758protected:
2759 virtual ~CallbackThread();
2760
2761 virtual bool threadLoop();
2762
2763private:
2764 wp<MediaPlayerBase::AudioSink> mSink;
2765 MediaPlayerBase::AudioSink::AudioCallback mCallback;
2766 void *mCookie;
2767 void *mBuffer;
2768 size_t mBufferSize;
2769
2770 CallbackThread(const CallbackThread &);
2771 CallbackThread &operator=(const CallbackThread &);
2772};
2773
2774CallbackThread::CallbackThread(
2775 const wp<MediaPlayerBase::AudioSink> &sink,
2776 MediaPlayerBase::AudioSink::AudioCallback cb,
2777 void *cookie)
2778 : mSink(sink),
2779 mCallback(cb),
2780 mCookie(cookie),
2781 mBuffer(NULL),
2782 mBufferSize(0) {
2783}
2784
2785CallbackThread::~CallbackThread() {
2786 if (mBuffer) {
2787 free(mBuffer);
2788 mBuffer = NULL;
2789 }
2790}
2791
2792bool CallbackThread::threadLoop() {
2793 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
2794 if (sink == NULL) {
2795 return false;
2796 }
2797
2798 if (mBuffer == NULL) {
2799 mBufferSize = sink->bufferSize();
2800 mBuffer = malloc(mBufferSize);
2801 }
2802
2803 size_t actualSize =
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002804 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie,
2805 MediaPlayerBase::AudioSink::CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002806
2807 if (actualSize > 0) {
2808 sink->write(mBuffer, actualSize);
Andy Hunga31335a2014-08-20 17:37:59 -07002809 // Could return false on sink->write() error or short count.
2810 // Not necessarily appropriate but would work for AudioCache behavior.
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002811 }
2812
2813 return true;
2814}
2815
2816////////////////////////////////////////////////////////////////////////////////
2817
Chong Zhange5b9b692017-05-11 11:44:56 -07002818void MediaPlayerService::addBatteryData(uint32_t params) {
2819 mBatteryTracker.addBatteryData(params);
2820}
2821
2822status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
2823 return mBatteryTracker.pullBatteryData(reply);
2824}
2825
2826MediaPlayerService::BatteryTracker::BatteryTracker() {
2827 mBatteryAudio.refCount = 0;
2828 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2829 mBatteryAudio.deviceOn[i] = 0;
2830 mBatteryAudio.lastTime[i] = 0;
2831 mBatteryAudio.totalTime[i] = 0;
2832 }
2833 // speaker is on by default
2834 mBatteryAudio.deviceOn[SPEAKER] = 1;
2835
2836 // reset battery stats
2837 // if the mediaserver has crashed, battery stats could be left
2838 // in bad state, reset the state upon service start.
2839 BatteryNotifier::getInstance().noteResetVideo();
2840}
2841
2842void MediaPlayerService::BatteryTracker::addBatteryData(uint32_t params)
Gloria Wang7cf180c2011-02-19 18:37:57 -08002843{
2844 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002845
2846 int32_t time = systemTime() / 1000000L;
2847
2848 // change audio output devices. This notification comes from AudioFlinger
2849 if ((params & kBatteryDataSpeakerOn)
2850 || (params & kBatteryDataOtherAudioDeviceOn)) {
2851
2852 int deviceOn[NUM_AUDIO_DEVICES];
2853 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2854 deviceOn[i] = 0;
2855 }
2856
2857 if ((params & kBatteryDataSpeakerOn)
2858 && (params & kBatteryDataOtherAudioDeviceOn)) {
2859 deviceOn[SPEAKER_AND_OTHER] = 1;
2860 } else if (params & kBatteryDataSpeakerOn) {
2861 deviceOn[SPEAKER] = 1;
2862 } else {
2863 deviceOn[OTHER_AUDIO_DEVICE] = 1;
2864 }
2865
2866 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2867 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
2868
2869 if (mBatteryAudio.refCount > 0) { // if playing audio
2870 if (!deviceOn[i]) {
2871 mBatteryAudio.lastTime[i] += time;
2872 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2873 mBatteryAudio.lastTime[i] = 0;
2874 } else {
2875 mBatteryAudio.lastTime[i] = 0 - time;
2876 }
2877 }
2878
2879 mBatteryAudio.deviceOn[i] = deviceOn[i];
2880 }
2881 }
2882 return;
2883 }
2884
Marco Nelissenb7848f12014-12-04 08:57:56 -08002885 // an audio stream is started
Gloria Wang9ee159b2011-02-24 14:51:45 -08002886 if (params & kBatteryDataAudioFlingerStart) {
2887 // record the start time only if currently no other audio
2888 // is being played
2889 if (mBatteryAudio.refCount == 0) {
2890 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2891 if (mBatteryAudio.deviceOn[i]) {
2892 mBatteryAudio.lastTime[i] -= time;
2893 }
2894 }
2895 }
2896
2897 mBatteryAudio.refCount ++;
2898 return;
2899
2900 } else if (params & kBatteryDataAudioFlingerStop) {
2901 if (mBatteryAudio.refCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002902 ALOGW("Battery track warning: refCount is <= 0");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002903 return;
2904 }
2905
2906 // record the stop time only if currently this is the only
2907 // audio being played
2908 if (mBatteryAudio.refCount == 1) {
2909 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2910 if (mBatteryAudio.deviceOn[i]) {
2911 mBatteryAudio.lastTime[i] += time;
2912 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2913 mBatteryAudio.lastTime[i] = 0;
2914 }
2915 }
2916 }
2917
2918 mBatteryAudio.refCount --;
2919 return;
2920 }
2921
Andy Hung1afd0982016-11-08 16:13:44 -08002922 uid_t uid = IPCThreadState::self()->getCallingUid();
Gloria Wang7cf180c2011-02-19 18:37:57 -08002923 if (uid == AID_MEDIA) {
2924 return;
2925 }
2926 int index = mBatteryData.indexOfKey(uid);
Gloria Wang7cf180c2011-02-19 18:37:57 -08002927
2928 if (index < 0) { // create a new entry for this UID
2929 BatteryUsageInfo info;
2930 info.audioTotalTime = 0;
2931 info.videoTotalTime = 0;
2932 info.audioLastTime = 0;
2933 info.videoLastTime = 0;
2934 info.refCount = 0;
2935
Gloria Wang9ee159b2011-02-24 14:51:45 -08002936 if (mBatteryData.add(uid, info) == NO_MEMORY) {
Steve Block29357bc2012-01-06 19:20:56 +00002937 ALOGE("Battery track error: no memory for new app");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002938 return;
2939 }
Gloria Wang7cf180c2011-02-19 18:37:57 -08002940 }
2941
2942 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
2943
2944 if (params & kBatteryDataCodecStarted) {
2945 if (params & kBatteryDataTrackAudio) {
2946 info.audioLastTime -= time;
2947 info.refCount ++;
2948 }
2949 if (params & kBatteryDataTrackVideo) {
2950 info.videoLastTime -= time;
2951 info.refCount ++;
2952 }
2953 } else {
2954 if (info.refCount == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002955 ALOGW("Battery track warning: refCount is already 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002956 return;
2957 } else if (info.refCount < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00002958 ALOGE("Battery track error: refCount < 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002959 mBatteryData.removeItem(uid);
2960 return;
2961 }
2962
2963 if (params & kBatteryDataTrackAudio) {
2964 info.audioLastTime += time;
2965 info.refCount --;
2966 }
2967 if (params & kBatteryDataTrackVideo) {
2968 info.videoLastTime += time;
2969 info.refCount --;
2970 }
2971
2972 // no stream is being played by this UID
2973 if (info.refCount == 0) {
2974 info.audioTotalTime += info.audioLastTime;
2975 info.audioLastTime = 0;
2976 info.videoTotalTime += info.videoLastTime;
2977 info.videoLastTime = 0;
2978 }
2979 }
2980}
2981
Chong Zhange5b9b692017-05-11 11:44:56 -07002982status_t MediaPlayerService::BatteryTracker::pullBatteryData(Parcel* reply) {
Gloria Wang7cf180c2011-02-19 18:37:57 -08002983 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002984
2985 // audio output devices usage
2986 int32_t time = systemTime() / 1000000L; //in ms
2987 int32_t totalTime;
2988
2989 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2990 totalTime = mBatteryAudio.totalTime[i];
2991
2992 if (mBatteryAudio.deviceOn[i]
2993 && (mBatteryAudio.lastTime[i] != 0)) {
2994 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
2995 totalTime += tmpTime;
2996 }
2997
2998 reply->writeInt32(totalTime);
2999 // reset the total time
3000 mBatteryAudio.totalTime[i] = 0;
3001 }
3002
3003 // codec usage
Gloria Wang7cf180c2011-02-19 18:37:57 -08003004 BatteryUsageInfo info;
3005 int size = mBatteryData.size();
3006
3007 reply->writeInt32(size);
3008 int i = 0;
3009
3010 while (i < size) {
3011 info = mBatteryData.valueAt(i);
3012
3013 reply->writeInt32(mBatteryData.keyAt(i)); //UID
3014 reply->writeInt32(info.audioTotalTime);
3015 reply->writeInt32(info.videoTotalTime);
3016
3017 info.audioTotalTime = 0;
3018 info.videoTotalTime = 0;
3019
3020 // remove the UID entry where no stream is being played
3021 if (info.refCount <= 0) {
3022 mBatteryData.removeItemsAt(i);
3023 size --;
3024 i --;
3025 }
3026 i++;
3027 }
3028 return NO_ERROR;
3029}
nikoa64c8c72009-07-20 15:07:26 -07003030} // namespace android