blob: b85e13991f72da4dc6addf8aa9d50c6db19497f6 [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;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070098using android::media::permission::Identity;
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
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700458sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(const Identity& identity)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800459{
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700460 // TODO b/182392769: use identity util
461 Identity verifiedIdentity = identity;
462 verifiedIdentity.uid = VALUE_OR_FATAL(
463 legacy2aidl_uid_t_int32_t(IPCThreadState::self()->getCallingUid()));
464 verifiedIdentity.pid = VALUE_OR_FATAL(
465 legacy2aidl_pid_t_int32_t(IPCThreadState::self()->getCallingPid()));
466 sp<MediaRecorderClient> recorder =
467 new MediaRecorderClient(this, verifiedIdentity);
Gloria Wangdac6a312009-10-29 15:46:37 -0700468 wp<MediaRecorderClient> w = recorder;
469 Mutex::Autolock lock(mLock);
470 mMediaRecorderClients.add(w);
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700471 ALOGV("Create new media recorder client from pid %s",
472 verifiedIdentity.toString().c_str());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800473 return recorder;
474}
475
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -0700476void MediaPlayerService::removeMediaRecorderClient(const wp<MediaRecorderClient>& client)
Gloria Wangdac6a312009-10-29 15:46:37 -0700477{
478 Mutex::Autolock lock(mLock);
479 mMediaRecorderClients.remove(client);
Steve Block3856b092011-10-20 11:56:00 +0100480 ALOGV("Delete media recorder client");
Gloria Wangdac6a312009-10-29 15:46:37 -0700481}
482
Glenn Kastenf37971f2012-02-03 11:06:53 -0800483sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800484{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800485 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800486 sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
Steve Block3856b092011-10-20 11:56:00 +0100487 ALOGV("Create new media retriever from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800488 return retriever;
489}
490
Glenn Kastenf37971f2012-02-03 11:06:53 -0800491sp<IMediaPlayer> MediaPlayerService::create(const sp<IMediaPlayerClient>& client,
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700492 audio_session_t audioSessionId, const Identity& identity)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800493{
494 int32_t connId = android_atomic_inc(&mNextConnId);
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700495 // TODO b/182392769: use identity util
496 Identity verifiedIdentity = identity;
497 verifiedIdentity.pid = VALUE_OR_FATAL(
498 legacy2aidl_pid_t_int32_t(IPCThreadState::self()->getCallingPid()));
499 verifiedIdentity.uid = VALUE_OR_FATAL(
500 legacy2aidl_uid_t_int32_t(IPCThreadState::self()->getCallingUid()));
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700501
502 sp<Client> c = new Client(
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700503 this, verifiedIdentity, connId, client, audioSessionId);
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700504
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700505 ALOGV("Create new client(%d) from %s, ", connId,
506 verifiedIdentity.toString().c_str());
Dave Burked681bbb2011-08-30 14:39:17 +0100507
508 wp<Client> w = c;
509 {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800510 Mutex::Autolock lock(mLock);
511 mClients.add(w);
512 }
Andreas Hubere2b10282010-11-23 11:41:34 -0800513 return c;
514}
515
Lajos Molnar1381d4b2014-08-07 15:18:35 -0700516sp<IMediaCodecList> MediaPlayerService::getCodecList() const {
517 return MediaCodecList::getLocalInstance();
518}
519
Jeff Brown2013a542012-09-04 21:38:42 -0700520sp<IRemoteDisplay> MediaPlayerService::listenForRemoteDisplay(
Chong Zhangd0a98fa2017-09-14 17:43:10 -0700521 const String16 &/*opPackageName*/,
522 const sp<IRemoteDisplayClient>& /*client*/,
523 const String8& /*iface*/) {
524 ALOGE("listenForRemoteDisplay is no longer supported!");
Jeff Brownaba33d52012-09-07 17:38:58 -0700525
Chong Zhangd0a98fa2017-09-14 17:43:10 -0700526 return NULL;
Jeff Brown2013a542012-09-04 21:38:42 -0700527}
528
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800529status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
530{
531 const size_t SIZE = 256;
532 char buffer[SIZE];
533 String8 result;
534
535 result.append(" AudioOutput\n");
536 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n",
537 mStreamType, mLeftVolume, mRightVolume);
538 result.append(buffer);
539 snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n",
Eric Laurentdb354e52012-03-05 17:27:11 -0800540 mMsecsPerFrame, (mTrack != 0) ? mTrack->latency() : -1);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800541 result.append(buffer);
Eric Laurent2beeb502010-07-16 07:43:46 -0700542 snprintf(buffer, 255, " aux effect id(%d), send level (%f)\n",
543 mAuxEffectId, mSendLevel);
544 result.append(buffer);
545
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800546 ::write(fd, result.string(), result.size());
547 if (mTrack != 0) {
548 mTrack->dump(fd, args);
549 }
550 return NO_ERROR;
551}
552
Lajos Molnar6d339f12015-04-17 16:15:53 -0700553status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800554{
555 const size_t SIZE = 256;
556 char buffer[SIZE];
557 String8 result;
558 result.append(" Client\n");
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700559 snprintf(buffer, 255, " Identity(%s), connId(%d), status(%d), looping(%s)\n",
560 mIdentity.toString().c_str(), mConnId, mStatus, mLoop?"true": "false");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800561 result.append(buffer);
Wei Jia502c2f42017-07-13 17:47:56 -0700562
563 sp<MediaPlayerBase> p;
564 sp<AudioOutput> audioOutput;
565 bool locked = false;
566 for (int i = 0; i < kDumpLockRetries; ++i) {
567 if (mLock.tryLock() == NO_ERROR) {
568 locked = true;
569 break;
570 }
571 usleep(kDumpLockSleepUs);
Andreas Hubera0b1d4b2011-06-07 15:52:25 -0700572 }
Wei Jia502c2f42017-07-13 17:47:56 -0700573
574 if (locked) {
575 p = mPlayer;
576 audioOutput = mAudioOutput;
577 mLock.unlock();
578 } else {
579 result.append(" lock is taken, no dump from player and audio output\n");
580 }
581 write(fd, result.string(), result.size());
582
583 if (p != NULL) {
584 p->dump(fd, args);
585 }
586 if (audioOutput != 0) {
587 audioOutput->dump(fd, args);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800588 }
589 write(fd, "\n", 1);
590 return NO_ERROR;
591}
592
Marco Nelissenf09611f2015-02-13 14:12:42 -0800593/**
594 * The only arguments this understands right now are -c, -von and -voff,
595 * which are parsed by ALooperRoster::dump()
596 */
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800597status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
598{
599 const size_t SIZE = 256;
600 char buffer[SIZE];
601 String8 result;
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530602 SortedVector< sp<Client> > clients; //to serialise the mutex unlock & client destruction.
603 SortedVector< sp<MediaRecorderClient> > mediaRecorderClients;
604
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800605 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
Wonsik Kim6f675772019-08-20 17:06:53 -0700606 snprintf(buffer, SIZE - 1, "Permission Denial: "
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800607 "can't dump MediaPlayerService from pid=%d, uid=%d\n",
608 IPCThreadState::self()->getCallingPid(),
609 IPCThreadState::self()->getCallingUid());
610 result.append(buffer);
611 } else {
612 Mutex::Autolock lock(mLock);
613 for (int i = 0, n = mClients.size(); i < n; ++i) {
614 sp<Client> c = mClients[i].promote();
615 if (c != 0) c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530616 clients.add(c);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800617 }
James Dongb9141222010-07-08 11:16:11 -0700618 if (mMediaRecorderClients.size() == 0) {
619 result.append(" No media recorder client\n\n");
620 } else {
621 for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
622 sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
James Donge579e282011-10-18 22:29:20 -0700623 if (c != 0) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700624 snprintf(buffer, 255, " MediaRecorderClient pid(%d)\n", c->mIdentity.pid);
James Donge579e282011-10-18 22:29:20 -0700625 result.append(buffer);
626 write(fd, result.string(), result.size());
627 result = "\n";
628 c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530629 mediaRecorderClients.add(c);
James Donge579e282011-10-18 22:29:20 -0700630 }
James Dongb9141222010-07-08 11:16:11 -0700631 }
Gloria Wangdac6a312009-10-29 15:46:37 -0700632 }
633
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800634 result.append(" Files opened and/or mapped:\n");
Wonsik Kim6f675772019-08-20 17:06:53 -0700635 snprintf(buffer, SIZE - 1, "/proc/%d/maps", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800636 FILE *f = fopen(buffer, "r");
637 if (f) {
638 while (!feof(f)) {
Wonsik Kim6f675772019-08-20 17:06:53 -0700639 fgets(buffer, SIZE - 1, f);
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700640 if (strstr(buffer, " /storage/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800641 strstr(buffer, " /system/sounds/") ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700642 strstr(buffer, " /data/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800643 strstr(buffer, " /system/media/")) {
644 result.append(" ");
645 result.append(buffer);
646 }
647 }
648 fclose(f);
649 } else {
650 result.append("couldn't open ");
651 result.append(buffer);
652 result.append("\n");
653 }
654
Wonsik Kim6f675772019-08-20 17:06:53 -0700655 snprintf(buffer, SIZE - 1, "/proc/%d/fd", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800656 DIR *d = opendir(buffer);
657 if (d) {
658 struct dirent *ent;
659 while((ent = readdir(d)) != NULL) {
660 if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
Wonsik Kim6f675772019-08-20 17:06:53 -0700661 snprintf(buffer, SIZE - 1, "/proc/%d/fd/%s", getpid(), ent->d_name);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800662 struct stat s;
663 if (lstat(buffer, &s) == 0) {
664 if ((s.st_mode & S_IFMT) == S_IFLNK) {
665 char linkto[256];
666 int len = readlink(buffer, linkto, sizeof(linkto));
667 if(len > 0) {
668 if(len > 255) {
669 linkto[252] = '.';
670 linkto[253] = '.';
671 linkto[254] = '.';
672 linkto[255] = 0;
673 } else {
674 linkto[len] = 0;
675 }
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700676 if (strstr(linkto, "/storage/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800677 strstr(linkto, "/system/sounds/") == linkto ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700678 strstr(linkto, "/data/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800679 strstr(linkto, "/system/media/") == linkto) {
680 result.append(" ");
681 result.append(buffer);
682 result.append(" -> ");
683 result.append(linkto);
684 result.append("\n");
685 }
686 }
687 } else {
688 result.append(" unexpected type for ");
689 result.append(buffer);
690 result.append("\n");
691 }
692 }
693 }
694 }
695 closedir(d);
696 } else {
697 result.append("couldn't open ");
698 result.append(buffer);
699 result.append("\n");
700 }
701
Marco Nelissenf09611f2015-02-13 14:12:42 -0800702 gLooperRoster.dump(fd, args);
703
Wonsik Kimd579f3e2019-10-07 14:14:09 -0700704 sp<IMediaCodecList> codecList = getCodecList();
705 dumpCodecDetails(fd, codecList, true /* decoders */);
706 dumpCodecDetails(fd, codecList, false /* !decoders */);
707
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800708 bool dumpMem = false;
Andy Hung53541292016-04-13 16:48:51 -0700709 bool unreachableMemory = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800710 for (size_t i = 0; i < args.size(); i++) {
711 if (args[i] == String16("-m")) {
712 dumpMem = true;
Andy Hung53541292016-04-13 16:48:51 -0700713 } else if (args[i] == String16("--unreachable")) {
714 unreachableMemory = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800715 }
716 }
717 if (dumpMem) {
Andy Hung07b745e2016-05-23 16:21:07 -0700718 result.append("\nDumping memory:\n");
719 std::string s = dumpMemoryAddresses(100 /* limit */);
720 result.append(s.c_str(), s.size());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800721 }
Andy Hung53541292016-04-13 16:48:51 -0700722 if (unreachableMemory) {
723 result.append("\nDumping unreachable memory:\n");
724 // TODO - should limit be an argument parameter?
725 std::string s = GetUnreachableMemoryString(true /* contents */, 10000 /* limit */);
726 result.append(s.c_str(), s.size());
727 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800728 }
729 write(fd, result.string(), result.size());
Wonsik Kim6f675772019-08-20 17:06:53 -0700730
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800731 return NO_ERROR;
732}
733
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -0700734void MediaPlayerService::removeClient(const wp<Client>& client)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800735{
736 Mutex::Autolock lock(mLock);
737 mClients.remove(client);
738}
739
Robert Shihee0a0e32016-08-16 16:50:54 -0700740bool MediaPlayerService::hasClient(wp<Client> client)
741{
742 Mutex::Autolock lock(mLock);
743 return mClients.indexOf(client) != NAME_NOT_FOUND;
744}
745
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700746MediaPlayerService::Client::Client(
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700747 const sp<MediaPlayerService>& service, const Identity& identity,
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700748 int32_t connId, const sp<IMediaPlayerClient>& client,
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700749 audio_session_t audioSessionId)
750 : mIdentity(identity)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800751{
Steve Block3856b092011-10-20 11:56:00 +0100752 ALOGV("Client(%d) constructor", connId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800753 mConnId = connId;
754 mService = service;
755 mClient = client;
756 mLoop = false;
757 mStatus = NO_INIT;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700758 mAudioSessionId = audioSessionId;
John Grossmanc795b642012-02-22 15:38:35 -0800759 mRetransmitEndpointValid = false;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700760 mAudioAttributes = NULL;
Pawin Vongmasa082e4f72017-12-17 02:31:18 -0800761 mListener = new Listener(this);
Eric Laurenta514bdb2010-06-21 09:27:30 -0700762
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800763#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000764 ALOGD("create Antagonizer");
Pawin Vongmasa082e4f72017-12-17 02:31:18 -0800765 mAntagonizer = new Antagonizer(mListener);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800766#endif
767}
768
769MediaPlayerService::Client::~Client()
770{
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700771 ALOGV("Client(%d) destructor identity = %s", mConnId, mIdentity.toString().c_str());
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700772 mAudioOutput.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800773 wp<Client> client(this);
774 disconnect();
775 mService->removeClient(client);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700776 if (mAudioAttributes != NULL) {
777 free(mAudioAttributes);
778 }
jiabin156c6872017-10-06 09:47:15 -0700779 mAudioDeviceUpdatedListener.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800780}
781
782void MediaPlayerService::Client::disconnect()
783{
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700784 ALOGV("disconnect(%d) from identity %s", mConnId, mIdentity.toString().c_str());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800785 // grab local reference and clear main reference to prevent future
786 // access to object
787 sp<MediaPlayerBase> p;
788 {
789 Mutex::Autolock l(mLock);
790 p = mPlayer;
beanzdcfefde2012-11-05 09:51:43 +0800791 mClient.clear();
Wei Jia502c2f42017-07-13 17:47:56 -0700792 mPlayer.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800793 }
Andreas Huber20111aa2009-07-14 16:56:47 -0700794
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800795 // clear the notification to prevent callbacks to dead client
796 // and reset the player. We assume the player will serialize
797 // access to itself if necessary.
798 if (p != 0) {
Pawin Vongmasa082e4f72017-12-17 02:31:18 -0800799 p->setNotifyCallback(0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800800#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000801 ALOGD("kill Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800802 mAntagonizer->kill();
803#endif
804 p->reset();
805 }
806
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700807 {
808 Mutex::Autolock l(mLock);
809 disconnectNativeWindow_l();
810 }
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700811
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800812 IPCThreadState::self()->flushCommands();
813}
814
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800815sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
816{
817 // determine if we have the right player type
Wei Jia502c2f42017-07-13 17:47:56 -0700818 sp<MediaPlayerBase> p = getPlayer();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800819 if ((p != NULL) && (p->playerType() != playerType)) {
Steve Block3856b092011-10-20 11:56:00 +0100820 ALOGV("delete player");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800821 p.clear();
822 }
823 if (p == NULL) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700824 p = MediaPlayerFactory::createPlayer(playerType, mListener,
825 VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(mIdentity.pid)));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800826 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700827
Jason Simmonsdb29e522011-08-12 13:46:55 -0700828 if (p != NULL) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700829 p->setUID(VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(mIdentity.uid)));
Jason Simmonsdb29e522011-08-12 13:46:55 -0700830 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700831
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800832 return p;
833}
834
jiabin156c6872017-10-06 09:47:15 -0700835void MediaPlayerService::Client::AudioDeviceUpdatedNotifier::onAudioDeviceUpdate(
836 audio_io_handle_t audioIo,
837 audio_port_handle_t deviceId) {
838 sp<MediaPlayerBase> listener = mListener.promote();
839 if (listener != NULL) {
840 listener->sendEvent(MEDIA_AUDIO_ROUTING_CHANGED, audioIo, deviceId);
841 } else {
842 ALOGW("listener for process %d death is gone", MEDIA_AUDIO_ROUTING_CHANGED);
843 }
844}
845
John Grossmanc795b642012-02-22 15:38:35 -0800846sp<MediaPlayerBase> MediaPlayerService::Client::setDataSource_pre(
847 player_type playerType)
848{
849 ALOGV("player type = %d", playerType);
850
851 // create the right type of player
852 sp<MediaPlayerBase> p = createPlayer(playerType);
853 if (p == NULL) {
854 return p;
855 }
856
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700857 std::vector<DeathNotifier> deathNotifiers;
858
859 // Listen to death of media.extractor service
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700860 sp<IServiceManager> sm = defaultServiceManager();
861 sp<IBinder> binder = sm->getService(String16("media.extractor"));
Marco Nelissen1b5a7ee2016-09-30 13:54:30 -0700862 if (binder == NULL) {
863 ALOGE("extractor service not available");
864 return NULL;
865 }
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700866 deathNotifiers.emplace_back(
867 binder, [l = wp<MediaPlayerBase>(p)]() {
868 sp<MediaPlayerBase> listener = l.promote();
869 if (listener) {
870 ALOGI("media.extractor died. Sending death notification.");
871 listener->sendEvent(MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED,
872 MEDIAEXTRACTOR_PROCESS_DEATH);
873 } else {
874 ALOGW("media.extractor died without a death handler.");
875 }
876 });
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700877
Marco Nelissena0c98412019-03-29 12:10:19 -0700878 {
879 using ::android::hidl::base::V1_0::IBase;
880
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700881 // Listen to death of OMX service
Marco Nelissena0c98412019-03-29 12:10:19 -0700882 {
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700883 sp<IBase> base = ::android::hardware::media::omx::V1_0::
884 IOmx::getService();
885 if (base == nullptr) {
Marco Nelissena0c98412019-03-29 12:10:19 -0700886 ALOGD("OMX service is not available");
887 } else {
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700888 deathNotifiers.emplace_back(
889 base, [l = wp<MediaPlayerBase>(p)]() {
890 sp<MediaPlayerBase> listener = l.promote();
891 if (listener) {
892 ALOGI("OMX service died. "
893 "Sending death notification.");
894 listener->sendEvent(
895 MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED,
896 MEDIACODEC_PROCESS_DEATH);
897 } else {
898 ALOGW("OMX service died without a death handler.");
899 }
900 });
Marco Nelissena0c98412019-03-29 12:10:19 -0700901 }
902 }
903
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700904 // Listen to death of Codec2 services
Marco Nelissena0c98412019-03-29 12:10:19 -0700905 {
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700906 for (std::shared_ptr<Codec2Client> const& client :
907 Codec2Client::CreateFromAllServices()) {
908 sp<IBase> base = client->getBase();
909 deathNotifiers.emplace_back(
910 base, [l = wp<MediaPlayerBase>(p),
911 name = std::string(client->getServiceName())]() {
912 sp<MediaPlayerBase> listener = l.promote();
913 if (listener) {
914 ALOGI("Codec2 service \"%s\" died. "
915 "Sending death notification.",
916 name.c_str());
917 listener->sendEvent(
918 MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED,
919 MEDIACODEC_PROCESS_DEATH);
920 } else {
921 ALOGW("Codec2 service \"%s\" died "
922 "without a death handler.",
923 name.c_str());
924 }
925 });
Marco Nelissene4da6c62019-04-01 15:01:41 -0700926 }
Marco Nelissena0c98412019-03-29 12:10:19 -0700927 }
Marco Nelissen1b5a7ee2016-09-30 13:54:30 -0700928 }
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700929
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700930 Mutex::Autolock lock(mLock);
931
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700932 mDeathNotifiers.clear();
933 mDeathNotifiers.swap(deathNotifiers);
jiabin156c6872017-10-06 09:47:15 -0700934 mAudioDeviceUpdatedListener = new AudioDeviceUpdatedNotifier(p);
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700935
John Grossmanc795b642012-02-22 15:38:35 -0800936 if (!p->hardwareOutput()) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700937 mAudioOutput = new AudioOutput(mAudioSessionId, mIdentity,
938 mAudioAttributes, mAudioDeviceUpdatedListener);
John Grossmanc795b642012-02-22 15:38:35 -0800939 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
940 }
941
942 return p;
943}
944
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700945status_t MediaPlayerService::Client::setDataSource_post(
John Grossmanc795b642012-02-22 15:38:35 -0800946 const sp<MediaPlayerBase>& p,
947 status_t status)
948{
949 ALOGV(" setDataSource");
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700950 if (status != OK) {
951 ALOGE(" error: %d", status);
952 return status;
John Grossmanc795b642012-02-22 15:38:35 -0800953 }
954
955 // Set the re-transmission endpoint if one was chosen.
956 if (mRetransmitEndpointValid) {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700957 status = p->setRetransmitEndpoint(&mRetransmitEndpoint);
958 if (status != NO_ERROR) {
959 ALOGE("setRetransmitEndpoint error: %d", status);
John Grossmanc795b642012-02-22 15:38:35 -0800960 }
961 }
962
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700963 if (status == OK) {
964 Mutex::Autolock lock(mLock);
John Grossmanc795b642012-02-22 15:38:35 -0800965 mPlayer = p;
966 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700967 return status;
John Grossmanc795b642012-02-22 15:38:35 -0800968}
969
Andreas Huber2db84552010-01-28 11:19:57 -0800970status_t MediaPlayerService::Client::setDataSource(
Andreas Huber1b86fe02014-01-29 11:13:26 -0800971 const sp<IMediaHTTPService> &httpService,
972 const char *url,
973 const KeyedVector<String8, String8> *headers)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800974{
Steve Block3856b092011-10-20 11:56:00 +0100975 ALOGV("setDataSource(%s)", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800976 if (url == NULL)
977 return UNKNOWN_ERROR;
978
Dave Burked681bbb2011-08-30 14:39:17 +0100979 if ((strncmp(url, "http://", 7) == 0) ||
980 (strncmp(url, "https://", 8) == 0) ||
981 (strncmp(url, "rtsp://", 7) == 0)) {
982 if (!checkPermission("android.permission.INTERNET")) {
983 return PERMISSION_DENIED;
984 }
985 }
986
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800987 if (strncmp(url, "content://", 10) == 0) {
988 // get a filedescriptor for the content Uri and
989 // pass it to the setDataSource(fd) method
990
991 String16 url16(url);
992 int fd = android::openContentProviderFile(url16);
993 if (fd < 0)
994 {
Steve Block29357bc2012-01-06 19:20:56 +0000995 ALOGE("Couldn't open fd for %s", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800996 return UNKNOWN_ERROR;
997 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700998 status_t status = setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800999 close(fd);
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001000 return mStatus = status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001001 } else {
John Grossman44a7e422012-06-21 17:29:24 -07001002 player_type playerType = MediaPlayerFactory::getPlayerType(this, url);
John Grossmanc795b642012-02-22 15:38:35 -08001003 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
1004 if (p == NULL) {
1005 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001006 }
1007
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001008 return mStatus =
1009 setDataSource_post(
1010 p, p->setDataSource(httpService, url, headers));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001011 }
1012}
1013
1014status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
1015{
Marco Nelissen83b0fd92015-09-16 13:48:07 -07001016 ALOGV("setDataSource fd=%d (%s), offset=%lld, length=%lld",
1017 fd, nameForFd(fd).c_str(), (long long) offset, (long long) length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001018 struct stat sb;
1019 int ret = fstat(fd, &sb);
1020 if (ret != 0) {
Steve Block29357bc2012-01-06 19:20:56 +00001021 ALOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001022 return UNKNOWN_ERROR;
1023 }
1024
Andy Hung833b4752016-04-04 17:15:48 -07001025 ALOGV("st_dev = %llu", static_cast<unsigned long long>(sb.st_dev));
Steve Block3856b092011-10-20 11:56:00 +01001026 ALOGV("st_mode = %u", sb.st_mode);
Mark Salyzyn77342f72014-06-18 16:31:32 -07001027 ALOGV("st_uid = %lu", static_cast<unsigned long>(sb.st_uid));
1028 ALOGV("st_gid = %lu", static_cast<unsigned long>(sb.st_gid));
Andy Hung833b4752016-04-04 17:15:48 -07001029 ALOGV("st_size = %llu", static_cast<unsigned long long>(sb.st_size));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001030
1031 if (offset >= sb.st_size) {
Steve Block29357bc2012-01-06 19:20:56 +00001032 ALOGE("offset error");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001033 return UNKNOWN_ERROR;
1034 }
1035 if (offset + length > sb.st_size) {
1036 length = sb.st_size - offset;
Andy Hung833b4752016-04-04 17:15:48 -07001037 ALOGV("calculated length = %lld", (long long)length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001038 }
1039
John Grossman44a7e422012-06-21 17:29:24 -07001040 player_type playerType = MediaPlayerFactory::getPlayerType(this,
1041 fd,
1042 offset,
1043 length);
John Grossmanc795b642012-02-22 15:38:35 -08001044 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
1045 if (p == NULL) {
1046 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001047 }
1048
1049 // now set data source
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001050 return mStatus = setDataSource_post(p, p->setDataSource(fd, offset, length));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001051}
1052
Andreas Hubere2b10282010-11-23 11:41:34 -08001053status_t MediaPlayerService::Client::setDataSource(
1054 const sp<IStreamSource> &source) {
1055 // create the right type of player
John Grossman44a7e422012-06-21 17:29:24 -07001056 player_type playerType = MediaPlayerFactory::getPlayerType(this, source);
John Grossmanc795b642012-02-22 15:38:35 -08001057 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
Andreas Hubere2b10282010-11-23 11:41:34 -08001058 if (p == NULL) {
1059 return NO_INIT;
1060 }
1061
Andreas Hubere2b10282010-11-23 11:41:34 -08001062 // now set data source
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001063 return mStatus = setDataSource_post(p, p->setDataSource(source));
Andreas Hubere2b10282010-11-23 11:41:34 -08001064}
1065
Chris Watkins99f31602015-03-20 13:06:33 -07001066status_t MediaPlayerService::Client::setDataSource(
1067 const sp<IDataSource> &source) {
Dongwon Kangd91dc5a2017-10-10 00:07:09 -07001068 sp<DataSource> dataSource = CreateDataSourceFromIDataSource(source);
Chris Watkins99f31602015-03-20 13:06:33 -07001069 player_type playerType = MediaPlayerFactory::getPlayerType(this, dataSource);
1070 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
1071 if (p == NULL) {
1072 return NO_INIT;
1073 }
1074 // now set data source
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001075 return mStatus = setDataSource_post(p, p->setDataSource(dataSource));
Chris Watkins99f31602015-03-20 13:06:33 -07001076}
1077
Byeongjo Park28225ab2019-01-24 20:31:19 +09001078status_t MediaPlayerService::Client::setDataSource(
1079 const String8& rtpParams) {
1080 player_type playerType = NU_PLAYER;
1081 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
1082 if (p == NULL) {
1083 return NO_INIT;
1084 }
1085 // now set data source
1086 return mStatus = setDataSource_post(p, p->setDataSource(rtpParams));
1087}
1088
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001089void MediaPlayerService::Client::disconnectNativeWindow_l() {
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001090 if (mConnectedWindow != NULL) {
Chong Zhang181fd9b2017-02-16 15:53:03 -08001091 status_t err = nativeWindowDisconnect(
1092 mConnectedWindow.get(), "disconnectNativeWindow");
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001093
1094 if (err != OK) {
Chong Zhang181fd9b2017-02-16 15:53:03 -08001095 ALOGW("nativeWindowDisconnect returned an error: %s (%d)",
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001096 strerror(-err), err);
1097 }
1098 }
1099 mConnectedWindow.clear();
1100}
1101
Glenn Kasten11731182011-02-08 17:26:17 -08001102status_t MediaPlayerService::Client::setVideoSurfaceTexture(
Andy McFadden484566c2012-12-18 09:46:54 -08001103 const sp<IGraphicBufferProducer>& bufferProducer)
Glenn Kasten11731182011-02-08 17:26:17 -08001104{
Andy McFadden484566c2012-12-18 09:46:54 -08001105 ALOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, bufferProducer.get());
Glenn Kasten11731182011-02-08 17:26:17 -08001106 sp<MediaPlayerBase> p = getPlayer();
1107 if (p == 0) return UNKNOWN_ERROR;
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001108
Marco Nelissenf8880202014-11-14 07:58:25 -08001109 sp<IBinder> binder(IInterface::asBinder(bufferProducer));
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001110 if (mConnectedWindowBinder == binder) {
1111 return OK;
1112 }
1113
1114 sp<ANativeWindow> anw;
Andy McFadden484566c2012-12-18 09:46:54 -08001115 if (bufferProducer != NULL) {
Marco Nelissenee08f7e2013-09-16 13:30:01 -07001116 anw = new Surface(bufferProducer, true /* controlledByApp */);
Chong Zhang181fd9b2017-02-16 15:53:03 -08001117 status_t err = nativeWindowConnect(anw.get(), "setVideoSurfaceTexture");
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001118
1119 if (err != OK) {
Steve Block29357bc2012-01-06 19:20:56 +00001120 ALOGE("setVideoSurfaceTexture failed: %d", err);
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001121 // Note that we must do the reset before disconnecting from the ANW.
1122 // Otherwise queue/dequeue calls could be made on the disconnected
1123 // ANW, which may result in errors.
1124 reset();
1125
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001126 Mutex::Autolock lock(mLock);
1127 disconnectNativeWindow_l();
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001128
1129 return err;
1130 }
1131 }
1132
Andy McFadden484566c2012-12-18 09:46:54 -08001133 // Note that we must set the player's new GraphicBufferProducer before
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001134 // disconnecting the old one. Otherwise queue/dequeue calls could be made
1135 // on the disconnected ANW, which may result in errors.
Andy McFadden484566c2012-12-18 09:46:54 -08001136 status_t err = p->setVideoSurfaceTexture(bufferProducer);
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001137
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001138 mLock.lock();
1139 disconnectNativeWindow_l();
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001140
1141 if (err == OK) {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001142 mConnectedWindow = anw;
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001143 mConnectedWindowBinder = binder;
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001144 mLock.unlock();
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001145 } else {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001146 mLock.unlock();
1147 status_t err = nativeWindowDisconnect(
1148 anw.get(), "disconnectNativeWindow");
1149
1150 if (err != OK) {
1151 ALOGW("nativeWindowDisconnect returned an error: %s (%d)",
1152 strerror(-err), err);
1153 }
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001154 }
1155
1156 return err;
Glenn Kasten11731182011-02-08 17:26:17 -08001157}
1158
Nicolas Catania1d187f12009-05-12 23:25:55 -07001159status_t MediaPlayerService::Client::invoke(const Parcel& request,
1160 Parcel *reply)
1161{
1162 sp<MediaPlayerBase> p = getPlayer();
1163 if (p == NULL) return UNKNOWN_ERROR;
1164 return p->invoke(request, reply);
1165}
1166
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001167// This call doesn't need to access the native player.
1168status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
1169{
1170 status_t status;
nikoa64c8c72009-07-20 15:07:26 -07001171 media::Metadata::Filter allow, drop;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001172
Nicolas Catania48290382009-07-10 13:53:06 -07001173 if (unmarshallFilter(filter, &allow, &status) &&
1174 unmarshallFilter(filter, &drop, &status)) {
1175 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001176
1177 mMetadataAllow = allow;
1178 mMetadataDrop = drop;
1179 }
1180 return status;
1181}
1182
Nicolas Catania48290382009-07-10 13:53:06 -07001183status_t MediaPlayerService::Client::getMetadata(
Mark Salyzyn77342f72014-06-18 16:31:32 -07001184 bool update_only, bool /*apply_filter*/, Parcel *reply)
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001185{
nikoa64c8c72009-07-20 15:07:26 -07001186 sp<MediaPlayerBase> player = getPlayer();
1187 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania48290382009-07-10 13:53:06 -07001188
nikod608a812009-07-16 16:39:53 -07001189 status_t status;
1190 // Placeholder for the return code, updated by the caller.
1191 reply->writeInt32(-1);
1192
nikoa64c8c72009-07-20 15:07:26 -07001193 media::Metadata::Filter ids;
Nicolas Catania48290382009-07-10 13:53:06 -07001194
1195 // We don't block notifications while we fetch the data. We clear
1196 // mMetadataUpdated first so we don't lose notifications happening
1197 // during the rest of this call.
1198 {
1199 Mutex::Autolock lock(mLock);
1200 if (update_only) {
nikod608a812009-07-16 16:39:53 -07001201 ids = mMetadataUpdated;
Nicolas Catania48290382009-07-10 13:53:06 -07001202 }
1203 mMetadataUpdated.clear();
1204 }
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001205
nikoa64c8c72009-07-20 15:07:26 -07001206 media::Metadata metadata(reply);
Nicolas Catania48290382009-07-10 13:53:06 -07001207
nikoa64c8c72009-07-20 15:07:26 -07001208 metadata.appendHeader();
1209 status = player->getMetadata(ids, reply);
nikod608a812009-07-16 16:39:53 -07001210
1211 if (status != OK) {
nikoa64c8c72009-07-20 15:07:26 -07001212 metadata.resetParcel();
Steve Block29357bc2012-01-06 19:20:56 +00001213 ALOGE("getMetadata failed %d", status);
nikod608a812009-07-16 16:39:53 -07001214 return status;
1215 }
1216
1217 // FIXME: Implement filtering on the result. Not critical since
1218 // filtering takes place on the update notifications already. This
1219 // would be when all the metadata are fetch and a filter is set.
1220
nikod608a812009-07-16 16:39:53 -07001221 // Everything is fine, update the metadata length.
nikoa64c8c72009-07-20 15:07:26 -07001222 metadata.updateLength();
nikod608a812009-07-16 16:39:53 -07001223 return OK;
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001224}
1225
Wei Jiad399e7e2016-10-26 15:49:11 -07001226status_t MediaPlayerService::Client::setBufferingSettings(
1227 const BufferingSettings& buffering)
1228{
Wei Jiadc6f3402017-01-09 15:04:18 -08001229 ALOGV("[%d] setBufferingSettings{%s}",
1230 mConnId, buffering.toString().string());
Wei Jiad399e7e2016-10-26 15:49:11 -07001231 sp<MediaPlayerBase> p = getPlayer();
1232 if (p == 0) return UNKNOWN_ERROR;
1233 return p->setBufferingSettings(buffering);
1234}
1235
Wei Jia9bb38032017-03-23 18:00:38 -07001236status_t MediaPlayerService::Client::getBufferingSettings(
Wei Jiad399e7e2016-10-26 15:49:11 -07001237 BufferingSettings* buffering /* nonnull */)
1238{
1239 sp<MediaPlayerBase> p = getPlayer();
1240 // TODO: create mPlayer on demand.
1241 if (p == 0) return UNKNOWN_ERROR;
Wei Jia9bb38032017-03-23 18:00:38 -07001242 status_t ret = p->getBufferingSettings(buffering);
Wei Jiad399e7e2016-10-26 15:49:11 -07001243 if (ret == NO_ERROR) {
Wei Jia9bb38032017-03-23 18:00:38 -07001244 ALOGV("[%d] getBufferingSettings{%s}",
Wei Jiadc6f3402017-01-09 15:04:18 -08001245 mConnId, buffering->toString().string());
Wei Jiad399e7e2016-10-26 15:49:11 -07001246 } else {
Wei Jia9bb38032017-03-23 18:00:38 -07001247 ALOGE("[%d] getBufferingSettings returned %d", mConnId, ret);
Wei Jiad399e7e2016-10-26 15:49:11 -07001248 }
1249 return ret;
1250}
1251
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001252status_t MediaPlayerService::Client::prepareAsync()
1253{
Steve Block3856b092011-10-20 11:56:00 +01001254 ALOGV("[%d] prepareAsync", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001255 sp<MediaPlayerBase> p = getPlayer();
1256 if (p == 0) return UNKNOWN_ERROR;
1257 status_t ret = p->prepareAsync();
1258#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +00001259 ALOGD("start Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001260 if (ret == NO_ERROR) mAntagonizer->start();
1261#endif
1262 return ret;
1263}
1264
1265status_t MediaPlayerService::Client::start()
1266{
Steve Block3856b092011-10-20 11:56:00 +01001267 ALOGV("[%d] start", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001268 sp<MediaPlayerBase> p = getPlayer();
1269 if (p == 0) return UNKNOWN_ERROR;
1270 p->setLooping(mLoop);
1271 return p->start();
1272}
1273
1274status_t MediaPlayerService::Client::stop()
1275{
Steve Block3856b092011-10-20 11:56:00 +01001276 ALOGV("[%d] stop", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001277 sp<MediaPlayerBase> p = getPlayer();
1278 if (p == 0) return UNKNOWN_ERROR;
1279 return p->stop();
1280}
1281
1282status_t MediaPlayerService::Client::pause()
1283{
Steve Block3856b092011-10-20 11:56:00 +01001284 ALOGV("[%d] pause", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001285 sp<MediaPlayerBase> p = getPlayer();
1286 if (p == 0) return UNKNOWN_ERROR;
1287 return p->pause();
1288}
1289
1290status_t MediaPlayerService::Client::isPlaying(bool* state)
1291{
1292 *state = false;
1293 sp<MediaPlayerBase> p = getPlayer();
1294 if (p == 0) return UNKNOWN_ERROR;
1295 *state = p->isPlaying();
Steve Block3856b092011-10-20 11:56:00 +01001296 ALOGV("[%d] isPlaying: %d", mConnId, *state);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001297 return NO_ERROR;
1298}
1299
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001300status_t MediaPlayerService::Client::setPlaybackSettings(const AudioPlaybackRate& rate)
Wei Jia98160162015-02-04 17:01:11 -08001301{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001302 ALOGV("[%d] setPlaybackSettings(%f, %f, %d, %d)",
1303 mConnId, rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Wei Jia98160162015-02-04 17:01:11 -08001304 sp<MediaPlayerBase> p = getPlayer();
1305 if (p == 0) return UNKNOWN_ERROR;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001306 return p->setPlaybackSettings(rate);
1307}
1308
1309status_t MediaPlayerService::Client::getPlaybackSettings(AudioPlaybackRate* rate /* nonnull */)
1310{
1311 sp<MediaPlayerBase> p = getPlayer();
1312 if (p == 0) return UNKNOWN_ERROR;
1313 status_t ret = p->getPlaybackSettings(rate);
1314 if (ret == NO_ERROR) {
1315 ALOGV("[%d] getPlaybackSettings(%f, %f, %d, %d)",
1316 mConnId, rate->mSpeed, rate->mPitch, rate->mFallbackMode, rate->mStretchMode);
1317 } else {
1318 ALOGV("[%d] getPlaybackSettings returned %d", mConnId, ret);
1319 }
1320 return ret;
1321}
1322
1323status_t MediaPlayerService::Client::setSyncSettings(
1324 const AVSyncSettings& sync, float videoFpsHint)
1325{
1326 ALOGV("[%d] setSyncSettings(%u, %u, %f, %f)",
1327 mConnId, sync.mSource, sync.mAudioAdjustMode, sync.mTolerance, videoFpsHint);
1328 sp<MediaPlayerBase> p = getPlayer();
1329 if (p == 0) return UNKNOWN_ERROR;
1330 return p->setSyncSettings(sync, videoFpsHint);
1331}
1332
1333status_t MediaPlayerService::Client::getSyncSettings(
1334 AVSyncSettings* sync /* nonnull */, float* videoFps /* nonnull */)
1335{
1336 sp<MediaPlayerBase> p = getPlayer();
1337 if (p == 0) return UNKNOWN_ERROR;
1338 status_t ret = p->getSyncSettings(sync, videoFps);
1339 if (ret == NO_ERROR) {
1340 ALOGV("[%d] getSyncSettings(%u, %u, %f, %f)",
1341 mConnId, sync->mSource, sync->mAudioAdjustMode, sync->mTolerance, *videoFps);
1342 } else {
1343 ALOGV("[%d] getSyncSettings returned %d", mConnId, ret);
1344 }
1345 return ret;
Wei Jia98160162015-02-04 17:01:11 -08001346}
1347
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001348status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
1349{
Steve Block3856b092011-10-20 11:56:00 +01001350 ALOGV("getCurrentPosition");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001351 sp<MediaPlayerBase> p = getPlayer();
1352 if (p == 0) return UNKNOWN_ERROR;
1353 status_t ret = p->getCurrentPosition(msec);
1354 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001355 ALOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001356 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001357 ALOGE("getCurrentPosition returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001358 }
1359 return ret;
1360}
1361
1362status_t MediaPlayerService::Client::getDuration(int *msec)
1363{
Steve Block3856b092011-10-20 11:56:00 +01001364 ALOGV("getDuration");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001365 sp<MediaPlayerBase> p = getPlayer();
1366 if (p == 0) return UNKNOWN_ERROR;
1367 status_t ret = p->getDuration(msec);
1368 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001369 ALOGV("[%d] getDuration = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001370 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001371 ALOGE("getDuration returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001372 }
1373 return ret;
1374}
1375
Marco Nelissen6b74d672012-02-28 16:07:44 -08001376status_t MediaPlayerService::Client::setNextPlayer(const sp<IMediaPlayer>& player) {
1377 ALOGV("setNextPlayer");
1378 Mutex::Autolock l(mLock);
1379 sp<Client> c = static_cast<Client*>(player.get());
Wei Jia28284122016-08-30 13:49:06 -07001380 if (c != NULL && !mService->hasClient(c)) {
Robert Shihee0a0e32016-08-16 16:50:54 -07001381 return BAD_VALUE;
1382 }
1383
Marco Nelissen6b74d672012-02-28 16:07:44 -08001384 mNextClient = c;
John Grossman5f7e55e2012-08-24 14:47:25 -07001385
1386 if (c != NULL) {
1387 if (mAudioOutput != NULL) {
1388 mAudioOutput->setNextOutput(c->mAudioOutput);
1389 } else if ((mPlayer != NULL) && !mPlayer->hardwareOutput()) {
1390 ALOGE("no current audio output");
1391 }
1392
1393 if ((mPlayer != NULL) && (mNextClient->getPlayer() != NULL)) {
1394 mPlayer->setNextPlayer(mNextClient->getPlayer());
1395 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001396 }
John Grossman5f7e55e2012-08-24 14:47:25 -07001397
Marco Nelissen6b74d672012-02-28 16:07:44 -08001398 return OK;
1399}
1400
Andy Hung9fc8b5c2017-01-24 13:36:48 -08001401VolumeShaper::Status MediaPlayerService::Client::applyVolumeShaper(
1402 const sp<VolumeShaper::Configuration>& configuration,
1403 const sp<VolumeShaper::Operation>& operation) {
1404 // for hardware output, call player instead
1405 ALOGV("Client::applyVolumeShaper(%p)", this);
1406 sp<MediaPlayerBase> p = getPlayer();
1407 {
1408 Mutex::Autolock l(mLock);
1409 if (p != 0 && p->hardwareOutput()) {
1410 // TODO: investigate internal implementation
1411 return VolumeShaper::Status(INVALID_OPERATION);
1412 }
1413 if (mAudioOutput.get() != nullptr) {
1414 return mAudioOutput->applyVolumeShaper(configuration, operation);
1415 }
1416 }
1417 return VolumeShaper::Status(INVALID_OPERATION);
1418}
1419
1420sp<VolumeShaper::State> MediaPlayerService::Client::getVolumeShaperState(int id) {
1421 // for hardware output, call player instead
1422 ALOGV("Client::getVolumeShaperState(%p)", this);
1423 sp<MediaPlayerBase> p = getPlayer();
1424 {
1425 Mutex::Autolock l(mLock);
1426 if (p != 0 && p->hardwareOutput()) {
1427 // TODO: investigate internal implementation.
1428 return nullptr;
1429 }
1430 if (mAudioOutput.get() != nullptr) {
1431 return mAudioOutput->getVolumeShaperState(id);
1432 }
1433 }
1434 return nullptr;
1435}
1436
Wei Jiac5de0912016-11-18 10:22:14 -08001437status_t MediaPlayerService::Client::seekTo(int msec, MediaPlayerSeekMode mode)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001438{
Wei Jiac5de0912016-11-18 10:22:14 -08001439 ALOGV("[%d] seekTo(%d, %d)", mConnId, msec, mode);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001440 sp<MediaPlayerBase> p = getPlayer();
1441 if (p == 0) return UNKNOWN_ERROR;
Wei Jiac5de0912016-11-18 10:22:14 -08001442 return p->seekTo(msec, mode);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001443}
1444
1445status_t MediaPlayerService::Client::reset()
1446{
Steve Block3856b092011-10-20 11:56:00 +01001447 ALOGV("[%d] reset", mConnId);
John Grossmanc795b642012-02-22 15:38:35 -08001448 mRetransmitEndpointValid = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001449 sp<MediaPlayerBase> p = getPlayer();
1450 if (p == 0) return UNKNOWN_ERROR;
1451 return p->reset();
1452}
1453
Wei Jia52c28512017-09-13 18:17:51 -07001454status_t MediaPlayerService::Client::notifyAt(int64_t mediaTimeUs)
1455{
1456 ALOGV("[%d] notifyAt(%lld)", mConnId, (long long)mediaTimeUs);
1457 sp<MediaPlayerBase> p = getPlayer();
1458 if (p == 0) return UNKNOWN_ERROR;
1459 return p->notifyAt(mediaTimeUs);
1460}
1461
Glenn Kastenfff6d712012-01-12 16:38:12 -08001462status_t MediaPlayerService::Client::setAudioStreamType(audio_stream_type_t type)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001463{
Steve Block3856b092011-10-20 11:56:00 +01001464 ALOGV("[%d] setAudioStreamType(%d)", mConnId, type);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001465 // TODO: for hardware output, call player instead
1466 Mutex::Autolock l(mLock);
1467 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1468 return NO_ERROR;
1469}
1470
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001471status_t MediaPlayerService::Client::setAudioAttributes_l(const Parcel &parcel)
1472{
1473 if (mAudioAttributes != NULL) { free(mAudioAttributes); }
1474 mAudioAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001475 if (mAudioAttributes == NULL) {
1476 return NO_MEMORY;
1477 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001478 unmarshallAudioAttributes(parcel, mAudioAttributes);
1479
1480 ALOGV("setAudioAttributes_l() usage=%d content=%d flags=0x%x tags=%s",
1481 mAudioAttributes->usage, mAudioAttributes->content_type, mAudioAttributes->flags,
1482 mAudioAttributes->tags);
1483
1484 if (mAudioOutput != 0) {
1485 mAudioOutput->setAudioAttributes(mAudioAttributes);
1486 }
1487 return NO_ERROR;
1488}
1489
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001490status_t MediaPlayerService::Client::setLooping(int loop)
1491{
Steve Block3856b092011-10-20 11:56:00 +01001492 ALOGV("[%d] setLooping(%d)", mConnId, loop);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001493 mLoop = loop;
1494 sp<MediaPlayerBase> p = getPlayer();
1495 if (p != 0) return p->setLooping(loop);
1496 return NO_ERROR;
1497}
1498
1499status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1500{
Steve Block3856b092011-10-20 11:56:00 +01001501 ALOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
John Grossman761defc2012-02-09 15:09:05 -08001502
1503 // for hardware output, call player instead
1504 sp<MediaPlayerBase> p = getPlayer();
1505 {
1506 Mutex::Autolock l(mLock);
1507 if (p != 0 && p->hardwareOutput()) {
1508 MediaPlayerHWInterface* hwp =
1509 reinterpret_cast<MediaPlayerHWInterface*>(p.get());
1510 return hwp->setVolume(leftVolume, rightVolume);
1511 } else {
1512 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1513 return NO_ERROR;
1514 }
1515 }
1516
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001517 return NO_ERROR;
1518}
1519
Eric Laurent2beeb502010-07-16 07:43:46 -07001520status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1521{
Steve Block3856b092011-10-20 11:56:00 +01001522 ALOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
Eric Laurent2beeb502010-07-16 07:43:46 -07001523 Mutex::Autolock l(mLock);
1524 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1525 return NO_ERROR;
1526}
1527
1528status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1529{
Steve Block3856b092011-10-20 11:56:00 +01001530 ALOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
Eric Laurent2beeb502010-07-16 07:43:46 -07001531 Mutex::Autolock l(mLock);
1532 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1533 return NO_ERROR;
1534}
Nicolas Catania48290382009-07-10 13:53:06 -07001535
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001536status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
Steve Block3856b092011-10-20 11:56:00 +01001537 ALOGV("[%d] setParameter(%d)", mConnId, key);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001538 switch (key) {
1539 case KEY_PARAMETER_AUDIO_ATTRIBUTES:
1540 {
1541 Mutex::Autolock l(mLock);
1542 return setAudioAttributes_l(request);
1543 }
1544 default:
1545 sp<MediaPlayerBase> p = getPlayer();
1546 if (p == 0) { return UNKNOWN_ERROR; }
1547 return p->setParameter(key, request);
1548 }
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001549}
1550
1551status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
Steve Block3856b092011-10-20 11:56:00 +01001552 ALOGV("[%d] getParameter(%d)", mConnId, key);
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001553 sp<MediaPlayerBase> p = getPlayer();
1554 if (p == 0) return UNKNOWN_ERROR;
1555 return p->getParameter(key, reply);
1556}
1557
John Grossmanc795b642012-02-22 15:38:35 -08001558status_t MediaPlayerService::Client::setRetransmitEndpoint(
1559 const struct sockaddr_in* endpoint) {
1560
1561 if (NULL != endpoint) {
1562 uint32_t a = ntohl(endpoint->sin_addr.s_addr);
1563 uint16_t p = ntohs(endpoint->sin_port);
1564 ALOGV("[%d] setRetransmitEndpoint(%u.%u.%u.%u:%hu)", mConnId,
1565 (a >> 24), (a >> 16) & 0xFF, (a >> 8) & 0xFF, (a & 0xFF), p);
1566 } else {
1567 ALOGV("[%d] setRetransmitEndpoint = <none>", mConnId);
1568 }
1569
1570 sp<MediaPlayerBase> p = getPlayer();
1571
1572 // Right now, the only valid time to set a retransmit endpoint is before
1573 // player selection has been made (since the presence or absence of a
1574 // retransmit endpoint is going to determine which player is selected during
1575 // setDataSource).
1576 if (p != 0) return INVALID_OPERATION;
1577
1578 if (NULL != endpoint) {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001579 Mutex::Autolock lock(mLock);
John Grossmanc795b642012-02-22 15:38:35 -08001580 mRetransmitEndpoint = *endpoint;
1581 mRetransmitEndpointValid = true;
1582 } else {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001583 Mutex::Autolock lock(mLock);
John Grossmanc795b642012-02-22 15:38:35 -08001584 mRetransmitEndpointValid = false;
1585 }
1586
1587 return NO_ERROR;
1588}
1589
John Grossman44a7e422012-06-21 17:29:24 -07001590status_t MediaPlayerService::Client::getRetransmitEndpoint(
1591 struct sockaddr_in* endpoint)
1592{
1593 if (NULL == endpoint)
1594 return BAD_VALUE;
1595
1596 sp<MediaPlayerBase> p = getPlayer();
1597
1598 if (p != NULL)
1599 return p->getRetransmitEndpoint(endpoint);
1600
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001601 Mutex::Autolock lock(mLock);
John Grossman44a7e422012-06-21 17:29:24 -07001602 if (!mRetransmitEndpointValid)
1603 return NO_INIT;
1604
1605 *endpoint = mRetransmitEndpoint;
1606
1607 return NO_ERROR;
1608}
1609
Gloria Wangb483c472011-04-11 17:23:27 -07001610void MediaPlayerService::Client::notify(
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001611 int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001612{
James Dongb8a98252012-08-26 16:13:03 -07001613 sp<IMediaPlayerClient> c;
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001614 sp<Client> nextClient;
1615 status_t errStartNext = NO_ERROR;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001616 {
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001617 Mutex::Autolock l(mLock);
1618 c = mClient;
1619 if (msg == MEDIA_PLAYBACK_COMPLETE && mNextClient != NULL) {
1620 nextClient = mNextClient;
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001621
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001622 if (mAudioOutput != NULL)
1623 mAudioOutput->switchToNextOutput();
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001624
1625 errStartNext = nextClient->start();
1626 }
1627 }
1628
1629 if (nextClient != NULL) {
1630 sp<IMediaPlayerClient> nc;
1631 {
1632 Mutex::Autolock l(nextClient->mLock);
1633 nc = nextClient->mClient;
1634 }
1635 if (nc != NULL) {
1636 if (errStartNext == NO_ERROR) {
1637 nc->notify(MEDIA_INFO, MEDIA_INFO_STARTED_AS_NEXT, 0, obj);
1638 } else {
1639 nc->notify(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN , 0, obj);
1640 ALOGE("gapless:start playback for next track failed, err(%d)", errStartNext);
Wei Jia2afac0c2016-01-07 12:13:07 -08001641 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001642 }
1643 }
1644
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001645 if (MEDIA_INFO == msg &&
Nicolas Catania48290382009-07-10 13:53:06 -07001646 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikoa64c8c72009-07-20 15:07:26 -07001647 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania48290382009-07-10 13:53:06 -07001648
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001649 if(shouldDropMetadata(metadata_type)) {
Nicolas Catania48290382009-07-10 13:53:06 -07001650 return;
1651 }
1652
1653 // Update the list of metadata that have changed. getMetadata
1654 // also access mMetadataUpdated and clears it.
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001655 addNewMetadataUpdate(metadata_type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001656 }
James Dongb8a98252012-08-26 16:13:03 -07001657
1658 if (c != NULL) {
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001659 ALOGV("[%d] notify (%d, %d, %d)", mConnId, msg, ext1, ext2);
James Dongb8a98252012-08-26 16:13:03 -07001660 c->notify(msg, ext1, ext2, obj);
1661 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001662}
1663
Nicolas Catania48290382009-07-10 13:53:06 -07001664
nikoa64c8c72009-07-20 15:07:26 -07001665bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001666{
Nicolas Catania48290382009-07-10 13:53:06 -07001667 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001668
Nicolas Catania48290382009-07-10 13:53:06 -07001669 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001670 return true;
1671 }
1672
Nicolas Catania48290382009-07-10 13:53:06 -07001673 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001674 return false;
Nicolas Catania48290382009-07-10 13:53:06 -07001675 } else {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001676 return true;
1677 }
1678}
1679
Nicolas Catania48290382009-07-10 13:53:06 -07001680
nikoa64c8c72009-07-20 15:07:26 -07001681void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania48290382009-07-10 13:53:06 -07001682 Mutex::Autolock lock(mLock);
1683 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1684 mMetadataUpdated.add(metadata_type);
1685 }
1686}
1687
Hassan Shojaniacefac142017-02-06 21:02:02 -08001688// Modular DRM
1689status_t MediaPlayerService::Client::prepareDrm(const uint8_t uuid[16],
1690 const Vector<uint8_t>& drmSessionId)
1691{
1692 ALOGV("[%d] prepareDrm", mConnId);
1693 sp<MediaPlayerBase> p = getPlayer();
1694 if (p == 0) return UNKNOWN_ERROR;
1695
1696 status_t ret = p->prepareDrm(uuid, drmSessionId);
1697 ALOGV("prepareDrm ret: %d", ret);
1698
1699 return ret;
1700}
1701
1702status_t MediaPlayerService::Client::releaseDrm()
1703{
1704 ALOGV("[%d] releaseDrm", mConnId);
1705 sp<MediaPlayerBase> p = getPlayer();
1706 if (p == 0) return UNKNOWN_ERROR;
1707
1708 status_t ret = p->releaseDrm();
1709 ALOGV("releaseDrm ret: %d", ret);
1710
1711 return ret;
1712}
1713
jiabin156c6872017-10-06 09:47:15 -07001714status_t MediaPlayerService::Client::setOutputDevice(audio_port_handle_t deviceId)
1715{
1716 ALOGV("[%d] setOutputDevice", mConnId);
1717 {
1718 Mutex::Autolock l(mLock);
1719 if (mAudioOutput.get() != nullptr) {
1720 return mAudioOutput->setOutputDevice(deviceId);
1721 }
1722 }
1723 return NO_INIT;
1724}
1725
1726status_t MediaPlayerService::Client::getRoutedDeviceId(audio_port_handle_t* deviceId)
1727{
1728 ALOGV("[%d] getRoutedDeviceId", mConnId);
1729 {
1730 Mutex::Autolock l(mLock);
1731 if (mAudioOutput.get() != nullptr) {
1732 return mAudioOutput->getRoutedDeviceId(deviceId);
1733 }
1734 }
1735 return NO_INIT;
1736}
1737
1738status_t MediaPlayerService::Client::enableAudioDeviceCallback(bool enabled)
1739{
1740 ALOGV("[%d] enableAudioDeviceCallback, %d", mConnId, enabled);
1741 {
1742 Mutex::Autolock l(mLock);
1743 if (mAudioOutput.get() != nullptr) {
1744 return mAudioOutput->enableAudioDeviceCallback(enabled);
1745 }
1746 }
1747 return NO_INIT;
1748}
1749
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001750#if CALLBACK_ANTAGONIZER
1751const int Antagonizer::interval = 10000; // 10 msecs
1752
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001753Antagonizer::Antagonizer(const sp<MediaPlayerBase::Listener> &listener) :
1754 mExit(false), mActive(false), mListener(listener)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001755{
1756 createThread(callbackThread, this);
1757}
1758
1759void Antagonizer::kill()
1760{
1761 Mutex::Autolock _l(mLock);
1762 mActive = false;
1763 mExit = true;
1764 mCondition.wait(mLock);
1765}
1766
1767int Antagonizer::callbackThread(void* user)
1768{
Steve Blockb8a80522011-12-20 16:23:08 +00001769 ALOGD("Antagonizer started");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001770 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1771 while (!p->mExit) {
1772 if (p->mActive) {
Steve Block3856b092011-10-20 11:56:00 +01001773 ALOGV("send event");
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001774 p->mListener->notify(0, 0, 0, 0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001775 }
1776 usleep(interval);
1777 }
1778 Mutex::Autolock _l(p->mLock);
1779 p->mCondition.signal();
Steve Blockb8a80522011-12-20 16:23:08 +00001780 ALOGD("Antagonizer stopped");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001781 return 0;
1782}
1783#endif
1784
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001785#undef LOG_TAG
1786#define LOG_TAG "AudioSink"
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001787MediaPlayerService::AudioOutput::AudioOutput(audio_session_t sessionId, const Identity& identity,
1788 const audio_attributes_t* attr, const sp<AudioSystem::AudioDeviceCallback>& deviceCallback)
Andreas Huber20111aa2009-07-14 16:56:47 -07001789 : mCallback(NULL),
Eric Laurenta514bdb2010-06-21 09:27:30 -07001790 mCallbackCookie(NULL),
Marco Nelissen6b74d672012-02-28 16:07:44 -08001791 mCallbackData(NULL),
Andy Hungd1c74342015-07-07 16:54:23 -07001792 mStreamType(AUDIO_STREAM_MUSIC),
Andy Hungd1c74342015-07-07 16:54:23 -07001793 mLeftVolume(1.0),
1794 mRightVolume(1.0),
1795 mPlaybackRate(AUDIO_PLAYBACK_RATE_DEFAULT),
1796 mSampleRateHz(0),
1797 mMsecsPerFrame(0),
1798 mFrameSize(0),
Eric Laurent1948eb32012-04-13 16:50:19 -07001799 mSessionId(sessionId),
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001800 mIdentity(identity),
Andy Hungd1c74342015-07-07 16:54:23 -07001801 mSendLevel(0.0),
1802 mAuxEffectId(0),
Andy Hung4ef88d72017-02-21 19:47:53 -08001803 mFlags(AUDIO_OUTPUT_FLAG_NONE),
jiabin156c6872017-10-06 09:47:15 -07001804 mVolumeHandler(new media::VolumeHandler()),
1805 mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE),
jiabin161b64fc2017-11-17 09:31:48 -08001806 mRoutedDeviceId(AUDIO_PORT_HANDLE_NONE),
jiabin156c6872017-10-06 09:47:15 -07001807 mDeviceCallbackEnabled(false),
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001808 mDeviceCallback(deviceCallback)
Andy Hungd1c74342015-07-07 16:54:23 -07001809{
Steve Block3856b092011-10-20 11:56:00 +01001810 ALOGV("AudioOutput(%d)", sessionId);
Eric Laurent43562692015-07-15 16:49:07 -07001811 if (attr != NULL) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001812 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1813 if (mAttributes != NULL) {
1814 memcpy(mAttributes, attr, sizeof(audio_attributes_t));
François Gaffie58d4be52018-11-06 15:30:12 +01001815 mStreamType = AudioSystem::attributesToStreamType(*attr);
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001816 }
1817 } else {
1818 mAttributes = NULL;
Eric Laurent43562692015-07-15 16:49:07 -07001819 }
1820
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001821 setMinBufferCount();
1822}
1823
1824MediaPlayerService::AudioOutput::~AudioOutput()
1825{
1826 close();
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001827 free(mAttributes);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001828 delete mCallbackData;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001829}
1830
Andy Hungd1c74342015-07-07 16:54:23 -07001831//static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001832void MediaPlayerService::AudioOutput::setMinBufferCount()
1833{
1834 char value[PROPERTY_VALUE_MAX];
1835 if (property_get("ro.kernel.qemu", value, 0)) {
1836 mIsOnEmulator = true;
1837 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1838 }
1839}
1840
Andy Hungd1c74342015-07-07 16:54:23 -07001841// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001842bool MediaPlayerService::AudioOutput::isOnEmulator()
1843{
Andy Hungd1c74342015-07-07 16:54:23 -07001844 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001845 return mIsOnEmulator;
1846}
1847
Andy Hungd1c74342015-07-07 16:54:23 -07001848// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001849int MediaPlayerService::AudioOutput::getMinBufferCount()
1850{
Andy Hungd1c74342015-07-07 16:54:23 -07001851 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001852 return mMinBufferCount;
1853}
1854
1855ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1856{
Andy Hungd1c74342015-07-07 16:54:23 -07001857 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001858 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001859 return mTrack->frameCount() * mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001860}
1861
1862ssize_t MediaPlayerService::AudioOutput::frameCount() const
1863{
Andy Hungd1c74342015-07-07 16:54:23 -07001864 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001865 if (mTrack == 0) return NO_INIT;
1866 return mTrack->frameCount();
1867}
1868
1869ssize_t MediaPlayerService::AudioOutput::channelCount() const
1870{
Andy Hungd1c74342015-07-07 16:54:23 -07001871 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001872 if (mTrack == 0) return NO_INIT;
1873 return mTrack->channelCount();
1874}
1875
1876ssize_t MediaPlayerService::AudioOutput::frameSize() const
1877{
Andy Hungd1c74342015-07-07 16:54:23 -07001878 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001879 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001880 return mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001881}
1882
1883uint32_t MediaPlayerService::AudioOutput::latency () const
1884{
Andy Hungd1c74342015-07-07 16:54:23 -07001885 Mutex::Autolock lock(mLock);
Eric Laurentdb354e52012-03-05 17:27:11 -08001886 if (mTrack == 0) return 0;
1887 return mTrack->latency();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001888}
1889
1890float MediaPlayerService::AudioOutput::msecsPerFrame() const
1891{
Andy Hungd1c74342015-07-07 16:54:23 -07001892 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001893 return mMsecsPerFrame;
1894}
1895
Marco Nelissen4110c102012-03-29 09:31:28 -07001896status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position) const
Eric Laurent342e9cf2010-01-19 17:37:09 -08001897{
Andy Hungd1c74342015-07-07 16:54:23 -07001898 Mutex::Autolock lock(mLock);
Eric Laurent342e9cf2010-01-19 17:37:09 -08001899 if (mTrack == 0) return NO_INIT;
1900 return mTrack->getPosition(position);
1901}
1902
Lajos Molnar06ad1522014-08-28 07:27:44 -07001903status_t MediaPlayerService::AudioOutput::getTimestamp(AudioTimestamp &ts) const
1904{
Andy Hungd1c74342015-07-07 16:54:23 -07001905 Mutex::Autolock lock(mLock);
Lajos Molnar06ad1522014-08-28 07:27:44 -07001906 if (mTrack == 0) return NO_INIT;
1907 return mTrack->getTimestamp(ts);
1908}
1909
Wei Jiac4ac8172015-10-21 10:35:48 -07001910// TODO: Remove unnecessary calls to getPlayedOutDurationUs()
1911// as it acquires locks and may query the audio driver.
1912//
1913// Some calls could conceivably retrieve extrapolated data instead of
1914// accessing getTimestamp() or getPosition() every time a data buffer with
1915// a media time is received.
1916//
1917// Calculate duration of played samples if played at normal rate (i.e., 1.0).
1918int64_t MediaPlayerService::AudioOutput::getPlayedOutDurationUs(int64_t nowUs) const
1919{
1920 Mutex::Autolock lock(mLock);
1921 if (mTrack == 0 || mSampleRateHz == 0) {
Wei Jia213f4902015-10-22 08:55:25 -07001922 return 0;
Wei Jiac4ac8172015-10-21 10:35:48 -07001923 }
1924
1925 uint32_t numFramesPlayed;
Andy Hung5d313802016-10-10 15:09:39 -07001926 int64_t numFramesPlayedAtUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001927 AudioTimestamp ts;
Wei Jiac4ac8172015-10-21 10:35:48 -07001928
1929 status_t res = mTrack->getTimestamp(ts);
1930 if (res == OK) { // case 1: mixing audio tracks and offloaded tracks.
1931 numFramesPlayed = ts.mPosition;
Andy Hung5d313802016-10-10 15:09:39 -07001932 numFramesPlayedAtUs = ts.mTime.tv_sec * 1000000LL + ts.mTime.tv_nsec / 1000;
1933 //ALOGD("getTimestamp: OK %d %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001934 } else if (res == WOULD_BLOCK) { // case 2: transitory state on start of a new track
1935 numFramesPlayed = 0;
Andy Hung5d313802016-10-10 15:09:39 -07001936 numFramesPlayedAtUs = nowUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001937 //ALOGD("getTimestamp: WOULD_BLOCK %d %lld",
Andy Hung5d313802016-10-10 15:09:39 -07001938 // numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001939 } else { // case 3: transitory at new track or audio fast tracks.
1940 res = mTrack->getPosition(&numFramesPlayed);
1941 CHECK_EQ(res, (status_t)OK);
Andy Hung5d313802016-10-10 15:09:39 -07001942 numFramesPlayedAtUs = nowUs;
1943 numFramesPlayedAtUs += 1000LL * mTrack->latency() / 2; /* XXX */
1944 //ALOGD("getPosition: %u %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001945 }
1946
1947 // CHECK_EQ(numFramesPlayed & (1 << 31), 0); // can't be negative until 12.4 hrs, test
1948 // TODO: remove the (int32_t) casting below as it may overflow at 12.4 hours.
1949 int64_t durationUs = (int64_t)((int32_t)numFramesPlayed * 1000000LL / mSampleRateHz)
Andy Hung5d313802016-10-10 15:09:39 -07001950 + nowUs - numFramesPlayedAtUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001951 if (durationUs < 0) {
1952 // Occurs when numFramesPlayed position is very small and the following:
1953 // (1) In case 1, the time nowUs is computed before getTimestamp() is called and
Andy Hung5d313802016-10-10 15:09:39 -07001954 // numFramesPlayedAtUs is greater than nowUs by time more than numFramesPlayed.
Wei Jiac4ac8172015-10-21 10:35:48 -07001955 // (2) In case 3, using getPosition and adding mAudioSink->latency() to
Andy Hung5d313802016-10-10 15:09:39 -07001956 // numFramesPlayedAtUs, by a time amount greater than numFramesPlayed.
Wei Jiac4ac8172015-10-21 10:35:48 -07001957 //
1958 // Both of these are transitory conditions.
1959 ALOGV("getPlayedOutDurationUs: negative duration %lld set to zero", (long long)durationUs);
1960 durationUs = 0;
1961 }
1962 ALOGV("getPlayedOutDurationUs(%lld) nowUs(%lld) frames(%u) framesAt(%lld)",
Andy Hung5d313802016-10-10 15:09:39 -07001963 (long long)durationUs, (long long)nowUs,
1964 numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001965 return durationUs;
1966}
1967
Marco Nelissen4110c102012-03-29 09:31:28 -07001968status_t MediaPlayerService::AudioOutput::getFramesWritten(uint32_t *frameswritten) const
1969{
Andy Hungd1c74342015-07-07 16:54:23 -07001970 Mutex::Autolock lock(mLock);
Marco Nelissen4110c102012-03-29 09:31:28 -07001971 if (mTrack == 0) return NO_INIT;
Andy Hung2f6e73d2016-04-08 12:12:58 -07001972 ExtendedTimestamp ets;
1973 status_t status = mTrack->getTimestamp(&ets);
1974 if (status == OK || status == WOULD_BLOCK) {
1975 *frameswritten = (uint32_t)ets.mPosition[ExtendedTimestamp::LOCATION_CLIENT];
1976 }
1977 return status;
Marco Nelissen4110c102012-03-29 09:31:28 -07001978}
1979
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001980status_t MediaPlayerService::AudioOutput::setParameters(const String8& keyValuePairs)
1981{
Andy Hungd1c74342015-07-07 16:54:23 -07001982 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001983 if (mTrack == 0) return NO_INIT;
1984 return mTrack->setParameters(keyValuePairs);
1985}
1986
1987String8 MediaPlayerService::AudioOutput::getParameters(const String8& keys)
1988{
Andy Hungd1c74342015-07-07 16:54:23 -07001989 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001990 if (mTrack == 0) return String8::empty();
1991 return mTrack->getParameters(keys);
1992}
1993
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001994void MediaPlayerService::AudioOutput::setAudioAttributes(const audio_attributes_t * attributes) {
Andy Hungd1c74342015-07-07 16:54:23 -07001995 Mutex::Autolock lock(mLock);
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001996 if (attributes == NULL) {
1997 free(mAttributes);
1998 mAttributes = NULL;
1999 } else {
2000 if (mAttributes == NULL) {
2001 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
2002 }
2003 memcpy(mAttributes, attributes, sizeof(audio_attributes_t));
François Gaffie58d4be52018-11-06 15:30:12 +01002004 mStreamType = AudioSystem::attributesToStreamType(*attributes);
Eric Laurent43562692015-07-15 16:49:07 -07002005 }
2006}
2007
2008void MediaPlayerService::AudioOutput::setAudioStreamType(audio_stream_type_t streamType)
2009{
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07002010 Mutex::Autolock lock(mLock);
Eric Laurent43562692015-07-15 16:49:07 -07002011 // do not allow direct stream type modification if attributes have been set
2012 if (mAttributes == NULL) {
2013 mStreamType = streamType;
2014 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07002015}
2016
Andy Hungd1c74342015-07-07 16:54:23 -07002017void MediaPlayerService::AudioOutput::deleteRecycledTrack_l()
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002018{
Andy Hungd1c74342015-07-07 16:54:23 -07002019 ALOGV("deleteRecycledTrack_l");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002020 if (mRecycledTrack != 0) {
2021
2022 if (mCallbackData != NULL) {
2023 mCallbackData->setOutput(NULL);
2024 mCallbackData->endTrackSwitch();
2025 }
2026
2027 if ((mRecycledTrack->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) {
Andy Hunge13f8a62016-03-30 14:20:42 -07002028 int32_t msec = 0;
2029 if (!mRecycledTrack->stopped()) { // check if active
2030 (void)mRecycledTrack->pendingDuration(&msec);
2031 }
2032 mRecycledTrack->stop(); // ensure full data drain
2033 ALOGD("deleting recycled track, waiting for data drain (%d msec)", msec);
2034 if (msec > 0) {
2035 static const int32_t WAIT_LIMIT_MS = 3000;
2036 if (msec > WAIT_LIMIT_MS) {
2037 msec = WAIT_LIMIT_MS;
2038 }
2039 usleep(msec * 1000LL);
2040 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002041 }
2042 // An offloaded track isn't flushed because the STREAM_END is reported
2043 // slightly prematurely to allow time for the gapless track switch
2044 // but this means that if we decide not to recycle the track there
2045 // could be a small amount of residual data still playing. We leave
2046 // AudioFlinger to drain the track.
2047
2048 mRecycledTrack.clear();
Andy Hungd1c74342015-07-07 16:54:23 -07002049 close_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002050 delete mCallbackData;
2051 mCallbackData = NULL;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002052 }
2053}
2054
Andy Hungd1c74342015-07-07 16:54:23 -07002055void MediaPlayerService::AudioOutput::close_l()
2056{
2057 mTrack.clear();
2058}
2059
Andreas Huber20111aa2009-07-14 16:56:47 -07002060status_t MediaPlayerService::AudioOutput::open(
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08002061 uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
2062 audio_format_t format, int bufferCount,
Eric Laurent1948eb32012-04-13 16:50:19 -07002063 AudioCallback cb, void *cookie,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002064 audio_output_flags_t flags,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07002065 const audio_offload_info_t *offloadInfo,
Andy Hung179652e2015-05-31 22:49:46 -07002066 bool doNotReconnect,
2067 uint32_t suggestedFrameCount)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002068{
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002069 ALOGV("open(%u, %d, 0x%x, 0x%x, %d, %d 0x%x)", sampleRate, channelCount, channelMask,
2070 format, bufferCount, mSessionId, flags);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002071
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002072 // offloading is only supported in callback mode for now.
2073 // offloadInfo must be present if offload flag is set
2074 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) &&
2075 ((cb == NULL) || (offloadInfo == NULL))) {
2076 return BAD_VALUE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002077 }
2078
Andy Hung179652e2015-05-31 22:49:46 -07002079 // compute frame count for the AudioTrack internal buffer
2080 size_t frameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002081 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
2082 frameCount = 0; // AudioTrack will get frame count from AudioFlinger
2083 } else {
Andy Hung179652e2015-05-31 22:49:46 -07002084 // try to estimate the buffer processing fetch size from AudioFlinger.
2085 // framesPerBuffer is approximate and generally correct, except when it's not :-).
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002086 uint32_t afSampleRate;
2087 size_t afFrameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002088 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
2089 return NO_INIT;
2090 }
2091 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
2092 return NO_INIT;
2093 }
Ben Romberger259fb462018-08-07 17:58:53 -07002094 if (afSampleRate == 0) {
2095 return NO_INIT;
2096 }
Andy Hung179652e2015-05-31 22:49:46 -07002097 const size_t framesPerBuffer =
2098 (unsigned long long)sampleRate * afFrameCount / afSampleRate;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002099
Andy Hung179652e2015-05-31 22:49:46 -07002100 if (bufferCount == 0) {
Ben Romberger259fb462018-08-07 17:58:53 -07002101 if (framesPerBuffer == 0) {
2102 return NO_INIT;
2103 }
Andy Hung179652e2015-05-31 22:49:46 -07002104 // use suggestedFrameCount
2105 bufferCount = (suggestedFrameCount + framesPerBuffer - 1) / framesPerBuffer;
2106 }
2107 // Check argument bufferCount against the mininum buffer count
2108 if (bufferCount != 0 && bufferCount < mMinBufferCount) {
2109 ALOGV("bufferCount (%d) increased to %d", bufferCount, mMinBufferCount);
2110 bufferCount = mMinBufferCount;
2111 }
2112 // if frameCount is 0, then AudioTrack will get frame count from AudioFlinger
2113 // which will be the minimum size permitted.
2114 frameCount = bufferCount * framesPerBuffer;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002115 }
Andreas Huber20111aa2009-07-14 16:56:47 -07002116
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08002117 if (channelMask == CHANNEL_MASK_USE_CHANNEL_ORDER) {
Glenn Kastenab334fd2012-03-14 12:56:06 -07002118 channelMask = audio_channel_out_mask_from_count(channelCount);
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08002119 if (0 == channelMask) {
2120 ALOGE("open() error, can\'t derive mask for %d audio channels", channelCount);
2121 return NO_INIT;
2122 }
2123 }
Eric Laurent1948eb32012-04-13 16:50:19 -07002124
Andy Hungd1c74342015-07-07 16:54:23 -07002125 Mutex::Autolock lock(mLock);
Andy Hung179652e2015-05-31 22:49:46 -07002126 mCallback = cb;
2127 mCallbackCookie = cookie;
2128
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002129 // Check whether we can recycle the track
2130 bool reuse = false;
2131 bool bothOffloaded = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07002132
Glenn Kasten2799d742013-05-30 14:33:29 -07002133 if (mRecycledTrack != 0) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002134 // check whether we are switching between two offloaded tracks
2135 bothOffloaded = (flags & mRecycledTrack->getFlags()
2136 & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0;
Marco Nelissen67295b52012-06-11 14:52:53 -07002137
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002138 // check if the existing track can be reused as-is, or if a new track needs to be created.
2139 reuse = true;
2140
Marco Nelissen67295b52012-06-11 14:52:53 -07002141 if ((mCallbackData == NULL && mCallback != NULL) ||
2142 (mCallbackData != NULL && mCallback == NULL)) {
2143 // recycled track uses callbacks but the caller wants to use writes, or vice versa
2144 ALOGV("can't chain callback and write");
2145 reuse = false;
2146 } else if ((mRecycledTrack->getSampleRate() != sampleRate) ||
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002147 (mRecycledTrack->channelCount() != (uint32_t)channelCount) ) {
2148 ALOGV("samplerate, channelcount differ: %u/%u Hz, %u/%d ch",
Marco Nelissen67295b52012-06-11 14:52:53 -07002149 mRecycledTrack->getSampleRate(), sampleRate,
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002150 mRecycledTrack->channelCount(), channelCount);
Marco Nelissen67295b52012-06-11 14:52:53 -07002151 reuse = false;
2152 } else if (flags != mFlags) {
2153 ALOGV("output flags differ %08x/%08x", flags, mFlags);
2154 reuse = false;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002155 } else if (mRecycledTrack->format() != format) {
2156 reuse = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07002157 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002158 } else {
2159 ALOGV("no track available to recycle");
2160 }
2161
2162 ALOGV_IF(bothOffloaded, "both tracks offloaded");
2163
2164 // If we can't recycle and both tracks are offloaded
2165 // we must close the previous output before opening a new one
2166 if (bothOffloaded && !reuse) {
2167 ALOGV("both offloaded and not recycling");
Andy Hungd1c74342015-07-07 16:54:23 -07002168 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002169 }
2170
2171 sp<AudioTrack> t;
2172 CallbackData *newcbd = NULL;
2173
2174 // We don't attempt to create a new track if we are recycling an
2175 // offloaded track. But, if we are recycling a non-offloaded or we
2176 // are switching where one is offloaded and one isn't then we create
2177 // the new track in advance so that we can read additional stream info
2178
2179 if (!(reuse && bothOffloaded)) {
2180 ALOGV("creating new AudioTrack");
2181
2182 if (mCallback != NULL) {
2183 newcbd = new CallbackData(this);
2184 t = new AudioTrack(
2185 mStreamType,
2186 sampleRate,
2187 format,
2188 channelMask,
2189 frameCount,
2190 flags,
2191 CallbackWrapper,
2192 newcbd,
2193 0, // notification frames
2194 mSessionId,
2195 AudioTrack::TRANSFER_CALLBACK,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002196 offloadInfo,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002197 mIdentity,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07002198 mAttributes,
jiabin156c6872017-10-06 09:47:15 -07002199 doNotReconnect,
2200 1.0f, // default value for maxRequiredSpeed
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002201 mSelectedDeviceId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002202 } else {
Andy Hungff874dc2016-04-11 16:49:09 -07002203 // TODO: Due to buffer memory concerns, we use a max target playback speed
2204 // based on mPlaybackRate at the time of open (instead of kMaxRequiredSpeed),
2205 // also clamping the target speed to 1.0 <= targetSpeed <= kMaxRequiredSpeed.
2206 const float targetSpeed =
2207 std::min(std::max(mPlaybackRate.mSpeed, 1.0f), kMaxRequiredSpeed);
2208 ALOGW_IF(targetSpeed != mPlaybackRate.mSpeed,
2209 "track target speed:%f clamped from playback speed:%f",
2210 targetSpeed, mPlaybackRate.mSpeed);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002211 t = new AudioTrack(
2212 mStreamType,
2213 sampleRate,
2214 format,
2215 channelMask,
2216 frameCount,
2217 flags,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002218 NULL, // callback
2219 NULL, // user data
2220 0, // notification frames
2221 mSessionId,
2222 AudioTrack::TRANSFER_DEFAULT,
2223 NULL, // offload info
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002224 mIdentity,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07002225 mAttributes,
Andy Hungff874dc2016-04-11 16:49:09 -07002226 doNotReconnect,
jiabin156c6872017-10-06 09:47:15 -07002227 targetSpeed,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002228 mSelectedDeviceId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002229 }
Andy Hunga6b27032020-04-27 10:34:24 -07002230 // Set caller name so it can be logged in destructor.
2231 // MediaMetricsConstants.h: AMEDIAMETRICS_PROP_CALLERNAME_VALUE_MEDIA
2232 t->setCallerName("media");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002233 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
2234 ALOGE("Unable to create audio track");
2235 delete newcbd;
Glenn Kasten3e98ecd2015-05-18 13:13:24 -07002236 // t goes out of scope, so reference count drops to zero
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002237 return NO_INIT;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07002238 } else {
2239 // successful AudioTrack initialization implies a legacy stream type was generated
2240 // from the audio attributes
2241 mStreamType = t->streamType();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002242 }
2243 }
2244
2245 if (reuse) {
2246 CHECK(mRecycledTrack != NULL);
2247
2248 if (!bothOffloaded) {
2249 if (mRecycledTrack->frameCount() != t->frameCount()) {
Andy Hung833b4752016-04-04 17:15:48 -07002250 ALOGV("framecount differs: %zu/%zu frames",
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002251 mRecycledTrack->frameCount(), t->frameCount());
2252 reuse = false;
2253 }
Jaideep Sharmab3ce4482020-11-16 11:52:35 +05302254 // If recycled and new tracks are not on the same output,
2255 // don't reuse the recycled one.
2256 if (mRecycledTrack->getOutput() != t->getOutput()) {
2257 ALOGV("output has changed, don't reuse track");
2258 reuse = false;
2259 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002260 }
2261
Marco Nelissen67295b52012-06-11 14:52:53 -07002262 if (reuse) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002263 ALOGV("chaining to next output and recycling track");
Andy Hungd1c74342015-07-07 16:54:23 -07002264 close_l();
Marco Nelissen67295b52012-06-11 14:52:53 -07002265 mTrack = mRecycledTrack;
Glenn Kasten2799d742013-05-30 14:33:29 -07002266 mRecycledTrack.clear();
Marco Nelissen67295b52012-06-11 14:52:53 -07002267 if (mCallbackData != NULL) {
2268 mCallbackData->setOutput(this);
2269 }
Marco Nelissen67295b52012-06-11 14:52:53 -07002270 delete newcbd;
Wei Jiae0bbac92016-07-18 16:04:53 -07002271 return updateTrack();
Marco Nelissen67295b52012-06-11 14:52:53 -07002272 }
Marco Nelissen67295b52012-06-11 14:52:53 -07002273 }
2274
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002275 // we're not going to reuse the track, unblock and flush it
2276 // this was done earlier if both tracks are offloaded
2277 if (!bothOffloaded) {
Andy Hungd1c74342015-07-07 16:54:23 -07002278 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002279 }
2280
2281 CHECK((t != NULL) && ((mCallback == NULL) || (newcbd != NULL)));
2282
Marco Nelissen67295b52012-06-11 14:52:53 -07002283 mCallbackData = newcbd;
Steve Block3856b092011-10-20 11:56:00 +01002284 ALOGV("setVolume");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002285 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07002286
Andy Hung39399b62017-04-21 15:07:45 -07002287 // Restore VolumeShapers for the MediaPlayer in case the track was recreated
2288 // due to an output sink error (e.g. offload to non-offload switch).
2289 mVolumeHandler->forall([&t](const VolumeShaper &shaper) -> VolumeShaper::Status {
2290 sp<VolumeShaper::Operation> operationToEnd =
2291 new VolumeShaper::Operation(shaper.mOperation);
2292 // TODO: Ideally we would restore to the exact xOffset position
2293 // as returned by getVolumeShaperState(), but we don't have that
2294 // information when restoring at the client unless we periodically poll
2295 // the server or create shared memory state.
2296 //
2297 // For now, we simply advance to the end of the VolumeShaper effect
2298 // if it has been started.
2299 if (shaper.isStarted()) {
Andy Hungf3702642017-05-05 17:33:32 -07002300 operationToEnd->setNormalizedTime(1.f);
Andy Hung39399b62017-04-21 15:07:45 -07002301 }
2302 return t->applyVolumeShaper(shaper.mConfiguration, operationToEnd);
Andy Hung4ef88d72017-02-21 19:47:53 -08002303 });
Andy Hung4ef88d72017-02-21 19:47:53 -08002304
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002305 mSampleRateHz = sampleRate;
Preetam Singh Ranawat2e17eef2015-08-12 12:11:46 -07002306 mFlags = flags;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002307 mMsecsPerFrame = 1E3f / (mPlaybackRate.mSpeed * sampleRate);
Andy Hungd1c74342015-07-07 16:54:23 -07002308 mFrameSize = t->frameSize();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002309 mTrack = t;
Eric Laurent2beeb502010-07-16 07:43:46 -07002310
Wei Jiae0bbac92016-07-18 16:04:53 -07002311 return updateTrack();
2312}
2313
2314status_t MediaPlayerService::AudioOutput::updateTrack() {
2315 if (mTrack == NULL) {
2316 return NO_ERROR;
2317 }
2318
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002319 status_t res = NO_ERROR;
Wei Jia0162d002015-06-09 11:59:33 -07002320 // Note some output devices may give us a direct track even though we don't specify it.
2321 // Example: Line application b/17459982.
Wei Jiae0bbac92016-07-18 16:04:53 -07002322 if ((mTrack->getFlags()
2323 & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) {
2324 res = mTrack->setPlaybackRate(mPlaybackRate);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002325 if (res == NO_ERROR) {
Wei Jiae0bbac92016-07-18 16:04:53 -07002326 mTrack->setAuxEffectSendLevel(mSendLevel);
2327 res = mTrack->attachAuxEffect(mAuxEffectId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002328 }
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002329 }
jiabin156c6872017-10-06 09:47:15 -07002330 mTrack->setOutputDevice(mSelectedDeviceId);
2331 if (mDeviceCallbackEnabled) {
2332 mTrack->addAudioDeviceCallback(mDeviceCallback.promote());
2333 }
Wei Jiae0bbac92016-07-18 16:04:53 -07002334 ALOGV("updateTrack() DONE status %d", res);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002335 return res;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002336}
2337
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002338status_t MediaPlayerService::AudioOutput::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002339{
Steve Block3856b092011-10-20 11:56:00 +01002340 ALOGV("start");
Andy Hungd1c74342015-07-07 16:54:23 -07002341 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08002342 if (mCallbackData != NULL) {
2343 mCallbackData->endTrackSwitch();
2344 }
Glenn Kasten2799d742013-05-30 14:33:29 -07002345 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002346 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07002347 mTrack->setAuxEffectSendLevel(mSendLevel);
Andy Hung39399b62017-04-21 15:07:45 -07002348 status_t status = mTrack->start();
2349 if (status == NO_ERROR) {
2350 mVolumeHandler->setStarted();
2351 }
2352 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002353 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002354 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002355}
2356
Marco Nelissen6b74d672012-02-28 16:07:44 -08002357void MediaPlayerService::AudioOutput::setNextOutput(const sp<AudioOutput>& nextOutput) {
Andy Hungd1c74342015-07-07 16:54:23 -07002358 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08002359 mNextOutput = nextOutput;
2360}
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08002361
Marco Nelissen6b74d672012-02-28 16:07:44 -08002362void MediaPlayerService::AudioOutput::switchToNextOutput() {
2363 ALOGV("switchToNextOutput");
Andy Hungd1c74342015-07-07 16:54:23 -07002364
2365 // Try to acquire the callback lock before moving track (without incurring deadlock).
2366 const unsigned kMaxSwitchTries = 100;
2367 Mutex::Autolock lock(mLock);
2368 for (unsigned tries = 0;;) {
2369 if (mTrack == 0) {
2370 return;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002371 }
Andy Hungd1c74342015-07-07 16:54:23 -07002372 if (mNextOutput != NULL && mNextOutput != this) {
2373 if (mCallbackData != NULL) {
2374 // two alternative approaches
2375#if 1
2376 CallbackData *callbackData = mCallbackData;
2377 mLock.unlock();
2378 // proper acquisition sequence
2379 callbackData->lock();
2380 mLock.lock();
2381 // Caution: it is unlikely that someone deleted our callback or changed our target
2382 if (callbackData != mCallbackData || mNextOutput == NULL || mNextOutput == this) {
2383 // fatal if we are starved out.
2384 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2385 "switchToNextOutput() cannot obtain correct lock sequence");
2386 callbackData->unlock();
2387 continue;
2388 }
2389 callbackData->mSwitching = true; // begin track switch
Wei Jiaadee56a2016-08-05 15:40:34 -07002390 callbackData->setOutput(NULL);
Andy Hungd1c74342015-07-07 16:54:23 -07002391#else
2392 // tryBeginTrackSwitch() returns false if the callback has the lock.
2393 if (!mCallbackData->tryBeginTrackSwitch()) {
2394 // fatal if we are starved out.
2395 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2396 "switchToNextOutput() cannot obtain callback lock");
2397 mLock.unlock();
2398 usleep(5 * 1000 /* usec */); // allow callback to use AudioOutput
2399 mLock.lock();
2400 continue;
2401 }
2402#endif
2403 }
2404
2405 Mutex::Autolock nextLock(mNextOutput->mLock);
2406
2407 // If the next output track is not NULL, then it has been
2408 // opened already for playback.
2409 // This is possible even without the next player being started,
2410 // for example, the next player could be prepared and seeked.
2411 //
2412 // Presuming it isn't advisable to force the track over.
2413 if (mNextOutput->mTrack == NULL) {
2414 ALOGD("Recycling track for gapless playback");
2415 delete mNextOutput->mCallbackData;
2416 mNextOutput->mCallbackData = mCallbackData;
2417 mNextOutput->mRecycledTrack = mTrack;
2418 mNextOutput->mSampleRateHz = mSampleRateHz;
2419 mNextOutput->mMsecsPerFrame = mMsecsPerFrame;
Andy Hungd1c74342015-07-07 16:54:23 -07002420 mNextOutput->mFlags = mFlags;
2421 mNextOutput->mFrameSize = mFrameSize;
2422 close_l();
2423 mCallbackData = NULL; // destruction handled by mNextOutput
2424 } else {
2425 ALOGW("Ignoring gapless playback because next player has already started");
2426 // remove track in case resource needed for future players.
2427 if (mCallbackData != NULL) {
2428 mCallbackData->endTrackSwitch(); // release lock for callbacks before close.
2429 }
2430 close_l();
2431 }
2432 }
2433 break;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002434 }
2435}
2436
Wei Jia7d3f4df2015-03-03 15:28:00 -08002437ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002438{
Andy Hungd1c74342015-07-07 16:54:23 -07002439 Mutex::Autolock lock(mLock);
Glenn Kastenadad3d72014-02-21 14:51:43 -08002440 LOG_ALWAYS_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
Andreas Huber20111aa2009-07-14 16:56:47 -07002441
Steve Block3856b092011-10-20 11:56:00 +01002442 //ALOGV("write(%p, %u)", buffer, size);
Glenn Kasten2799d742013-05-30 14:33:29 -07002443 if (mTrack != 0) {
Andy Hung2f6e73d2016-04-08 12:12:58 -07002444 return mTrack->write(buffer, size, blocking);
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07002445 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002446 return NO_INIT;
2447}
2448
2449void MediaPlayerService::AudioOutput::stop()
2450{
Steve Block3856b092011-10-20 11:56:00 +01002451 ALOGV("stop");
Andy Hungd1c74342015-07-07 16:54:23 -07002452 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002453 if (mTrack != 0) mTrack->stop();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002454}
2455
2456void MediaPlayerService::AudioOutput::flush()
2457{
Steve Block3856b092011-10-20 11:56:00 +01002458 ALOGV("flush");
Andy Hungd1c74342015-07-07 16:54:23 -07002459 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002460 if (mTrack != 0) mTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002461}
2462
2463void MediaPlayerService::AudioOutput::pause()
2464{
Steve Block3856b092011-10-20 11:56:00 +01002465 ALOGV("pause");
Andy Hungd1c74342015-07-07 16:54:23 -07002466 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002467 if (mTrack != 0) mTrack->pause();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002468}
2469
2470void MediaPlayerService::AudioOutput::close()
2471{
Steve Block3856b092011-10-20 11:56:00 +01002472 ALOGV("close");
Erik Wolsheimer7845a1f2015-10-30 12:07:52 -07002473 sp<AudioTrack> track;
2474 {
2475 Mutex::Autolock lock(mLock);
2476 track = mTrack;
2477 close_l(); // clears mTrack
2478 }
2479 // destruction of the track occurs outside of mutex.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002480}
2481
2482void MediaPlayerService::AudioOutput::setVolume(float left, float right)
2483{
Steve Block3856b092011-10-20 11:56:00 +01002484 ALOGV("setVolume(%f, %f)", left, right);
Andy Hungd1c74342015-07-07 16:54:23 -07002485 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002486 mLeftVolume = left;
2487 mRightVolume = right;
Glenn Kasten2799d742013-05-30 14:33:29 -07002488 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002489 mTrack->setVolume(left, right);
2490 }
2491}
2492
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002493status_t MediaPlayerService::AudioOutput::setPlaybackRate(const AudioPlaybackRate &rate)
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002494{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002495 ALOGV("setPlaybackRate(%f %f %d %d)",
2496 rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Andy Hungd1c74342015-07-07 16:54:23 -07002497 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002498 if (mTrack == 0) {
2499 // remember rate so that we can set it when the track is opened
2500 mPlaybackRate = rate;
2501 return OK;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002502 }
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002503 status_t res = mTrack->setPlaybackRate(rate);
2504 if (res != NO_ERROR) {
2505 return res;
2506 }
2507 // rate.mSpeed is always greater than 0 if setPlaybackRate succeeded
2508 CHECK_GT(rate.mSpeed, 0.f);
2509 mPlaybackRate = rate;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002510 if (mSampleRateHz != 0) {
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002511 mMsecsPerFrame = 1E3f / (rate.mSpeed * mSampleRateHz);
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002512 }
2513 return res;
2514}
2515
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002516status_t MediaPlayerService::AudioOutput::getPlaybackRate(AudioPlaybackRate *rate)
2517{
2518 ALOGV("setPlaybackRate");
Andy Hungd1c74342015-07-07 16:54:23 -07002519 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002520 if (mTrack == 0) {
2521 return NO_INIT;
2522 }
2523 *rate = mTrack->getPlaybackRate();
2524 return NO_ERROR;
2525}
2526
Eric Laurent2beeb502010-07-16 07:43:46 -07002527status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
2528{
Steve Block3856b092011-10-20 11:56:00 +01002529 ALOGV("setAuxEffectSendLevel(%f)", level);
Andy Hungd1c74342015-07-07 16:54:23 -07002530 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002531 mSendLevel = level;
Glenn Kasten2799d742013-05-30 14:33:29 -07002532 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002533 return mTrack->setAuxEffectSendLevel(level);
2534 }
2535 return NO_ERROR;
2536}
2537
2538status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
2539{
Steve Block3856b092011-10-20 11:56:00 +01002540 ALOGV("attachAuxEffect(%d)", effectId);
Andy Hungd1c74342015-07-07 16:54:23 -07002541 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002542 mAuxEffectId = effectId;
Glenn Kasten2799d742013-05-30 14:33:29 -07002543 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002544 return mTrack->attachAuxEffect(effectId);
2545 }
2546 return NO_ERROR;
2547}
2548
jiabin156c6872017-10-06 09:47:15 -07002549status_t MediaPlayerService::AudioOutput::setOutputDevice(audio_port_handle_t deviceId)
2550{
2551 ALOGV("setOutputDevice(%d)", deviceId);
2552 Mutex::Autolock lock(mLock);
2553 mSelectedDeviceId = deviceId;
2554 if (mTrack != 0) {
2555 return mTrack->setOutputDevice(deviceId);
2556 }
2557 return NO_ERROR;
2558}
2559
2560status_t MediaPlayerService::AudioOutput::getRoutedDeviceId(audio_port_handle_t* deviceId)
2561{
2562 ALOGV("getRoutedDeviceId");
2563 Mutex::Autolock lock(mLock);
2564 if (mTrack != 0) {
jiabin161b64fc2017-11-17 09:31:48 -08002565 mRoutedDeviceId = mTrack->getRoutedDeviceId();
jiabin156c6872017-10-06 09:47:15 -07002566 }
jiabin161b64fc2017-11-17 09:31:48 -08002567 *deviceId = mRoutedDeviceId;
2568 return NO_ERROR;
jiabin156c6872017-10-06 09:47:15 -07002569}
2570
2571status_t MediaPlayerService::AudioOutput::enableAudioDeviceCallback(bool enabled)
2572{
2573 ALOGV("enableAudioDeviceCallback, %d", enabled);
2574 Mutex::Autolock lock(mLock);
2575 mDeviceCallbackEnabled = enabled;
2576 if (mTrack != 0) {
2577 status_t status;
2578 if (enabled) {
2579 status = mTrack->addAudioDeviceCallback(mDeviceCallback.promote());
2580 } else {
2581 status = mTrack->removeAudioDeviceCallback(mDeviceCallback.promote());
2582 }
2583 return status;
2584 }
2585 return NO_ERROR;
2586}
2587
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002588VolumeShaper::Status MediaPlayerService::AudioOutput::applyVolumeShaper(
2589 const sp<VolumeShaper::Configuration>& configuration,
2590 const sp<VolumeShaper::Operation>& operation)
2591{
2592 Mutex::Autolock lock(mLock);
2593 ALOGV("AudioOutput::applyVolumeShaper");
Andy Hung4ef88d72017-02-21 19:47:53 -08002594
Andy Hung4ef88d72017-02-21 19:47:53 -08002595 mVolumeHandler->setIdIfNecessary(configuration);
Andy Hung39399b62017-04-21 15:07:45 -07002596
2597 VolumeShaper::Status status;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002598 if (mTrack != 0) {
Andy Hung39399b62017-04-21 15:07:45 -07002599 status = mTrack->applyVolumeShaper(configuration, operation);
2600 if (status >= 0) {
2601 (void)mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hungf3702642017-05-05 17:33:32 -07002602 if (mTrack->isPlaying()) { // match local AudioTrack to properly restore.
2603 mVolumeHandler->setStarted();
2604 }
Andy Hung39399b62017-04-21 15:07:45 -07002605 }
Andy Hung4ef88d72017-02-21 19:47:53 -08002606 } else {
Andy Hungc01eddb2017-07-21 16:42:41 -07002607 // VolumeShapers are not affected when a track moves between players for
2608 // gapless playback (setNextMediaPlayer).
2609 // We forward VolumeShaper operations that do not change configuration
2610 // to the new player so that unducking may occur as expected.
2611 // Unducking is an idempotent operation, same if applied back-to-back.
2612 if (configuration->getType() == VolumeShaper::Configuration::TYPE_ID
2613 && mNextOutput != nullptr) {
2614 ALOGV("applyVolumeShaper: Attempting to forward missed operation: %s %s",
2615 configuration->toString().c_str(), operation->toString().c_str());
2616 Mutex::Autolock nextLock(mNextOutput->mLock);
2617
2618 // recycled track should be forwarded from this AudioSink by switchToNextOutput
2619 sp<AudioTrack> track = mNextOutput->mRecycledTrack;
2620 if (track != nullptr) {
2621 ALOGD("Forward VolumeShaper operation to recycled track %p", track.get());
2622 (void)track->applyVolumeShaper(configuration, operation);
2623 } else {
2624 // There is a small chance that the unduck occurs after the next
2625 // player has already started, but before it is registered to receive
2626 // the unduck command.
2627 track = mNextOutput->mTrack;
2628 if (track != nullptr) {
2629 ALOGD("Forward VolumeShaper operation to track %p", track.get());
2630 (void)track->applyVolumeShaper(configuration, operation);
2631 }
2632 }
2633 }
Andy Hung39399b62017-04-21 15:07:45 -07002634 status = mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002635 }
Andy Hung39399b62017-04-21 15:07:45 -07002636 return status;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002637}
2638
2639sp<VolumeShaper::State> MediaPlayerService::AudioOutput::getVolumeShaperState(int id)
2640{
2641 Mutex::Autolock lock(mLock);
2642 if (mTrack != 0) {
2643 return mTrack->getVolumeShaperState(id);
Andy Hung4ef88d72017-02-21 19:47:53 -08002644 } else {
2645 return mVolumeHandler->getVolumeShaperState(id);
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002646 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002647}
2648
Andreas Huber20111aa2009-07-14 16:56:47 -07002649// static
2650void MediaPlayerService::AudioOutput::CallbackWrapper(
Glenn Kastend217a8c2011-06-01 15:20:35 -07002651 int event, void *cookie, void *info) {
Steve Block3856b092011-10-20 11:56:00 +01002652 //ALOGV("callbackwrapper");
Marco Nelissen6b74d672012-02-28 16:07:44 -08002653 CallbackData *data = (CallbackData*)cookie;
Andy Hungd1c74342015-07-07 16:54:23 -07002654 // lock to ensure we aren't caught in the middle of a track switch.
Marco Nelissen6b74d672012-02-28 16:07:44 -08002655 data->lock();
2656 AudioOutput *me = data->getOutput();
Andreas Huber20111aa2009-07-14 16:56:47 -07002657 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002658 if (me == NULL) {
2659 // no output set, likely because the track was scheduled to be reused
2660 // by another player, but the format turned out to be incompatible.
2661 data->unlock();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002662 if (buffer != NULL) {
2663 buffer->size = 0;
2664 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08002665 return;
2666 }
Andreas Huber20111aa2009-07-14 16:56:47 -07002667
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002668 switch(event) {
2669 case AudioTrack::EVENT_MORE_DATA: {
2670 size_t actualSize = (*me->mCallback)(
2671 me, buffer->raw, buffer->size, me->mCallbackCookie,
2672 CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002673
Andy Hung719b46b2015-05-31 22:18:25 -07002674 // Log when no data is returned from the callback.
2675 // (1) We may have no data (especially with network streaming sources).
2676 // (2) We may have reached the EOS and the audio track is not stopped yet.
2677 // Note that AwesomePlayer/AudioPlayer will only return zero size when it reaches the EOS.
2678 // NuPlayerRenderer will return zero when it doesn't have data (it doesn't block to fill).
2679 //
2680 // This is a benign busy-wait, with the next data request generated 10 ms or more later;
2681 // nevertheless for power reasons, we don't want to see too many of these.
Andreas Huber2e8ffaf2010-02-18 16:45:13 -08002682
Andy Hung719b46b2015-05-31 22:18:25 -07002683 ALOGV_IF(actualSize == 0 && buffer->size > 0, "callbackwrapper: empty buffer returned");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002684
2685 buffer->size = actualSize;
2686 } break;
2687
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002688 case AudioTrack::EVENT_STREAM_END:
Andy Hung719b46b2015-05-31 22:18:25 -07002689 // currently only occurs for offloaded callbacks
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002690 ALOGV("callbackwrapper: deliver EVENT_STREAM_END");
2691 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2692 me->mCallbackCookie, CB_EVENT_STREAM_END);
2693 break;
2694
2695 case AudioTrack::EVENT_NEW_IAUDIOTRACK :
2696 ALOGV("callbackwrapper: deliver EVENT_TEAR_DOWN");
2697 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2698 me->mCallbackCookie, CB_EVENT_TEAR_DOWN);
2699 break;
2700
Glenn Kasten421743b2015-06-01 08:18:08 -07002701 case AudioTrack::EVENT_UNDERRUN:
Andy Hung719b46b2015-05-31 22:18:25 -07002702 // This occurs when there is no data available, typically
Glenn Kasten421743b2015-06-01 08:18:08 -07002703 // when there is a failure to supply data to the AudioTrack. It can also
2704 // occur in non-offloaded mode when the audio device comes out of standby.
2705 //
Andy Hung719b46b2015-05-31 22:18:25 -07002706 // If an AudioTrack underruns it outputs silence. Since this happens suddenly
2707 // it may sound like an audible pop or glitch.
2708 //
2709 // The underrun event is sent once per track underrun; the condition is reset
2710 // when more data is sent to the AudioTrack.
Eric Laurente93cc032016-05-05 10:15:10 -07002711 ALOGD("callbackwrapper: EVENT_UNDERRUN (discarded)");
Glenn Kasten421743b2015-06-01 08:18:08 -07002712 break;
2713
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002714 default:
2715 ALOGE("received unknown event type: %d inside CallbackWrapper !", event);
Andreas Huber51c1e0e2011-04-04 11:43:40 -07002716 }
2717
Marco Nelissen6b74d672012-02-28 16:07:44 -08002718 data->unlock();
Andreas Huber20111aa2009-07-14 16:56:47 -07002719}
2720
Glenn Kastend848eb42016-03-08 13:42:11 -08002721audio_session_t MediaPlayerService::AudioOutput::getSessionId() const
Eric Laurent8c563ed2010-10-07 18:23:03 -07002722{
Andy Hungd1c74342015-07-07 16:54:23 -07002723 Mutex::Autolock lock(mLock);
Eric Laurent8c563ed2010-10-07 18:23:03 -07002724 return mSessionId;
2725}
2726
Eric Laurent6f59db12013-07-26 17:16:50 -07002727uint32_t MediaPlayerService::AudioOutput::getSampleRate() const
2728{
Andy Hungd1c74342015-07-07 16:54:23 -07002729 Mutex::Autolock lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -07002730 if (mTrack == 0) return 0;
2731 return mTrack->getSampleRate();
2732}
2733
Andy Hungf2c87b32016-04-07 19:49:29 -07002734int64_t MediaPlayerService::AudioOutput::getBufferDurationInUs() const
2735{
2736 Mutex::Autolock lock(mLock);
2737 if (mTrack == 0) {
2738 return 0;
2739 }
2740 int64_t duration;
2741 if (mTrack->getBufferDurationInUs(&duration) != OK) {
2742 return 0;
2743 }
2744 return duration;
2745}
2746
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002747////////////////////////////////////////////////////////////////////////////////
2748
2749struct CallbackThread : public Thread {
2750 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
2751 MediaPlayerBase::AudioSink::AudioCallback cb,
2752 void *cookie);
2753
2754protected:
2755 virtual ~CallbackThread();
2756
2757 virtual bool threadLoop();
2758
2759private:
2760 wp<MediaPlayerBase::AudioSink> mSink;
2761 MediaPlayerBase::AudioSink::AudioCallback mCallback;
2762 void *mCookie;
2763 void *mBuffer;
2764 size_t mBufferSize;
2765
2766 CallbackThread(const CallbackThread &);
2767 CallbackThread &operator=(const CallbackThread &);
2768};
2769
2770CallbackThread::CallbackThread(
2771 const wp<MediaPlayerBase::AudioSink> &sink,
2772 MediaPlayerBase::AudioSink::AudioCallback cb,
2773 void *cookie)
2774 : mSink(sink),
2775 mCallback(cb),
2776 mCookie(cookie),
2777 mBuffer(NULL),
2778 mBufferSize(0) {
2779}
2780
2781CallbackThread::~CallbackThread() {
2782 if (mBuffer) {
2783 free(mBuffer);
2784 mBuffer = NULL;
2785 }
2786}
2787
2788bool CallbackThread::threadLoop() {
2789 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
2790 if (sink == NULL) {
2791 return false;
2792 }
2793
2794 if (mBuffer == NULL) {
2795 mBufferSize = sink->bufferSize();
2796 mBuffer = malloc(mBufferSize);
2797 }
2798
2799 size_t actualSize =
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002800 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie,
2801 MediaPlayerBase::AudioSink::CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002802
2803 if (actualSize > 0) {
2804 sink->write(mBuffer, actualSize);
Andy Hunga31335a2014-08-20 17:37:59 -07002805 // Could return false on sink->write() error or short count.
2806 // Not necessarily appropriate but would work for AudioCache behavior.
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002807 }
2808
2809 return true;
2810}
2811
2812////////////////////////////////////////////////////////////////////////////////
2813
Chong Zhange5b9b692017-05-11 11:44:56 -07002814void MediaPlayerService::addBatteryData(uint32_t params) {
2815 mBatteryTracker.addBatteryData(params);
2816}
2817
2818status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
2819 return mBatteryTracker.pullBatteryData(reply);
2820}
2821
2822MediaPlayerService::BatteryTracker::BatteryTracker() {
2823 mBatteryAudio.refCount = 0;
2824 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2825 mBatteryAudio.deviceOn[i] = 0;
2826 mBatteryAudio.lastTime[i] = 0;
2827 mBatteryAudio.totalTime[i] = 0;
2828 }
2829 // speaker is on by default
2830 mBatteryAudio.deviceOn[SPEAKER] = 1;
2831
2832 // reset battery stats
2833 // if the mediaserver has crashed, battery stats could be left
2834 // in bad state, reset the state upon service start.
2835 BatteryNotifier::getInstance().noteResetVideo();
2836}
2837
2838void MediaPlayerService::BatteryTracker::addBatteryData(uint32_t params)
Gloria Wang7cf180c2011-02-19 18:37:57 -08002839{
2840 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002841
2842 int32_t time = systemTime() / 1000000L;
2843
2844 // change audio output devices. This notification comes from AudioFlinger
2845 if ((params & kBatteryDataSpeakerOn)
2846 || (params & kBatteryDataOtherAudioDeviceOn)) {
2847
2848 int deviceOn[NUM_AUDIO_DEVICES];
2849 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2850 deviceOn[i] = 0;
2851 }
2852
2853 if ((params & kBatteryDataSpeakerOn)
2854 && (params & kBatteryDataOtherAudioDeviceOn)) {
2855 deviceOn[SPEAKER_AND_OTHER] = 1;
2856 } else if (params & kBatteryDataSpeakerOn) {
2857 deviceOn[SPEAKER] = 1;
2858 } else {
2859 deviceOn[OTHER_AUDIO_DEVICE] = 1;
2860 }
2861
2862 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2863 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
2864
2865 if (mBatteryAudio.refCount > 0) { // if playing audio
2866 if (!deviceOn[i]) {
2867 mBatteryAudio.lastTime[i] += time;
2868 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2869 mBatteryAudio.lastTime[i] = 0;
2870 } else {
2871 mBatteryAudio.lastTime[i] = 0 - time;
2872 }
2873 }
2874
2875 mBatteryAudio.deviceOn[i] = deviceOn[i];
2876 }
2877 }
2878 return;
2879 }
2880
Marco Nelissenb7848f12014-12-04 08:57:56 -08002881 // an audio stream is started
Gloria Wang9ee159b2011-02-24 14:51:45 -08002882 if (params & kBatteryDataAudioFlingerStart) {
2883 // record the start time only if currently no other audio
2884 // is being played
2885 if (mBatteryAudio.refCount == 0) {
2886 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2887 if (mBatteryAudio.deviceOn[i]) {
2888 mBatteryAudio.lastTime[i] -= time;
2889 }
2890 }
2891 }
2892
2893 mBatteryAudio.refCount ++;
2894 return;
2895
2896 } else if (params & kBatteryDataAudioFlingerStop) {
2897 if (mBatteryAudio.refCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002898 ALOGW("Battery track warning: refCount is <= 0");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002899 return;
2900 }
2901
2902 // record the stop time only if currently this is the only
2903 // audio being played
2904 if (mBatteryAudio.refCount == 1) {
2905 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2906 if (mBatteryAudio.deviceOn[i]) {
2907 mBatteryAudio.lastTime[i] += time;
2908 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2909 mBatteryAudio.lastTime[i] = 0;
2910 }
2911 }
2912 }
2913
2914 mBatteryAudio.refCount --;
2915 return;
2916 }
2917
Andy Hung1afd0982016-11-08 16:13:44 -08002918 uid_t uid = IPCThreadState::self()->getCallingUid();
Gloria Wang7cf180c2011-02-19 18:37:57 -08002919 if (uid == AID_MEDIA) {
2920 return;
2921 }
2922 int index = mBatteryData.indexOfKey(uid);
Gloria Wang7cf180c2011-02-19 18:37:57 -08002923
2924 if (index < 0) { // create a new entry for this UID
2925 BatteryUsageInfo info;
2926 info.audioTotalTime = 0;
2927 info.videoTotalTime = 0;
2928 info.audioLastTime = 0;
2929 info.videoLastTime = 0;
2930 info.refCount = 0;
2931
Gloria Wang9ee159b2011-02-24 14:51:45 -08002932 if (mBatteryData.add(uid, info) == NO_MEMORY) {
Steve Block29357bc2012-01-06 19:20:56 +00002933 ALOGE("Battery track error: no memory for new app");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002934 return;
2935 }
Gloria Wang7cf180c2011-02-19 18:37:57 -08002936 }
2937
2938 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
2939
2940 if (params & kBatteryDataCodecStarted) {
2941 if (params & kBatteryDataTrackAudio) {
2942 info.audioLastTime -= time;
2943 info.refCount ++;
2944 }
2945 if (params & kBatteryDataTrackVideo) {
2946 info.videoLastTime -= time;
2947 info.refCount ++;
2948 }
2949 } else {
2950 if (info.refCount == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002951 ALOGW("Battery track warning: refCount is already 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002952 return;
2953 } else if (info.refCount < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00002954 ALOGE("Battery track error: refCount < 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002955 mBatteryData.removeItem(uid);
2956 return;
2957 }
2958
2959 if (params & kBatteryDataTrackAudio) {
2960 info.audioLastTime += time;
2961 info.refCount --;
2962 }
2963 if (params & kBatteryDataTrackVideo) {
2964 info.videoLastTime += time;
2965 info.refCount --;
2966 }
2967
2968 // no stream is being played by this UID
2969 if (info.refCount == 0) {
2970 info.audioTotalTime += info.audioLastTime;
2971 info.audioLastTime = 0;
2972 info.videoTotalTime += info.videoLastTime;
2973 info.videoLastTime = 0;
2974 }
2975 }
2976}
2977
Chong Zhange5b9b692017-05-11 11:44:56 -07002978status_t MediaPlayerService::BatteryTracker::pullBatteryData(Parcel* reply) {
Gloria Wang7cf180c2011-02-19 18:37:57 -08002979 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002980
2981 // audio output devices usage
2982 int32_t time = systemTime() / 1000000L; //in ms
2983 int32_t totalTime;
2984
2985 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2986 totalTime = mBatteryAudio.totalTime[i];
2987
2988 if (mBatteryAudio.deviceOn[i]
2989 && (mBatteryAudio.lastTime[i] != 0)) {
2990 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
2991 totalTime += tmpTime;
2992 }
2993
2994 reply->writeInt32(totalTime);
2995 // reset the total time
2996 mBatteryAudio.totalTime[i] = 0;
2997 }
2998
2999 // codec usage
Gloria Wang7cf180c2011-02-19 18:37:57 -08003000 BatteryUsageInfo info;
3001 int size = mBatteryData.size();
3002
3003 reply->writeInt32(size);
3004 int i = 0;
3005
3006 while (i < size) {
3007 info = mBatteryData.valueAt(i);
3008
3009 reply->writeInt32(mBatteryData.keyAt(i)); //UID
3010 reply->writeInt32(info.audioTotalTime);
3011 reply->writeInt32(info.videoTotalTime);
3012
3013 info.audioTotalTime = 0;
3014 info.videoTotalTime = 0;
3015
3016 // remove the UID entry where no stream is being played
3017 if (info.refCount <= 0) {
3018 mBatteryData.removeItemsAt(i);
3019 size --;
3020 i --;
3021 }
3022 i++;
3023 }
3024 return NO_ERROR;
3025}
nikoa64c8c72009-07-20 15:07:26 -07003026} // namespace android