blob: f2a38dd60f93272401e4aa60496a71839b47fb1c [file] [log] [blame]
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001/*
2**
3** Copyright 2008, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18// Proxy for media player implementations
19
20//#define LOG_NDEBUG 0
21#define LOG_TAG "MediaPlayerService"
22#include <utils/Log.h>
23
24#include <sys/types.h>
25#include <sys/stat.h>
Gloria Wang7cf180c2011-02-19 18:37:57 -080026#include <sys/time.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080027#include <dirent.h>
28#include <unistd.h>
29
30#include <string.h>
Mathias Agopian6f74b0c2009-06-03 17:32:49 -070031
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080032#include <cutils/atomic.h>
Nicolas Catania14d27472009-07-13 14:37:49 -070033#include <cutils/properties.h> // for property_get
Mathias Agopian6f74b0c2009-06-03 17:32:49 -070034
35#include <utils/misc.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080036
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -070037#include <android/hardware/media/omx/1.0/IOmx.h>
Marco Nelissena0c98412019-03-29 12:10:19 -070038#include <android/hardware/media/c2/1.0/IComponentStore.h>
Mathias Agopian75624082009-05-19 19:08:10 -070039#include <binder/IPCThreadState.h>
40#include <binder/IServiceManager.h>
41#include <binder/MemoryHeapBase.h>
42#include <binder/MemoryBase.h>
Mathias Agopianb1e7cd12013-02-14 17:11:27 -080043#include <gui/Surface.h>
Nicolas Catania1d187f12009-05-12 23:25:55 -070044#include <utils/Errors.h> // for status_t
45#include <utils/String8.h>
Marco Nelissen10dbb8e2009-09-20 10:42:13 -070046#include <utils/SystemClock.h>
Lajos Molnar06ad1522014-08-28 07:27:44 -070047#include <utils/Timers.h>
Nicolas Catania1d187f12009-05-12 23:25:55 -070048#include <utils/Vector.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080049
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -070050#include <codec2/hidl/client.h>
Marco Nelissen42057ce2019-09-23 12:15:57 -070051#include <datasource/HTTPBase.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080052#include <media/IMediaHTTPService.h>
Jeff Brown2013a542012-09-04 21:38:42 -070053#include <media/IRemoteDisplay.h>
54#include <media/IRemoteDisplayClient.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080055#include <media/MediaPlayerInterface.h>
56#include <media/mediarecorder.h>
57#include <media/MediaMetadataRetrieverInterface.h>
nikoa64c8c72009-07-20 15:07:26 -070058#include <media/Metadata.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080059#include <media/AudioTrack.h>
James Dong8635b7b2011-03-14 17:01:38 -070060#include <media/MemoryLeakTrackUtil.h>
Chong Zhangd4fe6b12019-10-02 14:29:18 -070061#include <media/stagefright/FrameCaptureProcessor.h>
Dongwon Kangd91dc5a2017-10-10 00:07:09 -070062#include <media/stagefright/InterfaceUtils.h>
Wonsik Kim6f675772019-08-20 17:06:53 -070063#include <media/stagefright/MediaCodecConstants.h>
Lajos Molnar1381d4b2014-08-07 15:18:35 -070064#include <media/stagefright/MediaCodecList.h>
Eric Laurent9cb839a2011-09-27 09:48:56 -070065#include <media/stagefright/MediaErrors.h>
Marco Nelissen83b0fd92015-09-16 13:48:07 -070066#include <media/stagefright/Utils.h>
Marco Nelissen42057ce2019-09-23 12:15:57 -070067#include <media/stagefright/FoundationUtils.h>
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +010068#include <media/stagefright/foundation/ADebug.h>
Marco Nelissenf09611f2015-02-13 14:12:42 -080069#include <media/stagefright/foundation/ALooperRoster.h>
Chong Zhang181fd9b2017-02-16 15:53:03 -080070#include <media/stagefright/SurfaceUtils.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070071#include <mediautils/BatteryNotifier.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080072
Andy Hung53541292016-04-13 16:48:51 -070073#include <memunreachable/memunreachable.h>
Dima Zavin64760242011-05-11 14:15:23 -070074#include <system/audio.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070075
Gloria Wang7cf180c2011-02-19 18:37:57 -080076#include <private/android_filesystem_config.h>
77
James Dong559bf282012-03-28 10:29:14 -070078#include "ActivityManager.h"
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080079#include "MediaRecorderClient.h"
80#include "MediaPlayerService.h"
81#include "MetadataRetrieverClient.h"
John Grossman44a7e422012-06-21 17:29:24 -070082#include "MediaPlayerFactory.h"
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080083
Nicolas Catania14d27472009-07-13 14:37:49 -070084#include "TestPlayerStub.h"
Andreas Huberf9334412010-12-15 15:17:42 -080085#include "nuplayer/NuPlayerDriver.h"
Andreas Huber20111aa2009-07-14 16:56:47 -070086
Andreas Hubered3e3e02012-03-26 11:13:27 -070087
Wei Jia502c2f42017-07-13 17:47:56 -070088static const int kDumpLockRetries = 50;
89static const int kDumpLockSleepUs = 20000;
90
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070091namespace {
nikoa64c8c72009-07-20 15:07:26 -070092using android::media::Metadata;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070093using android::status_t;
94using android::OK;
95using android::BAD_VALUE;
96using android::NOT_ENOUGH_DATA;
97using android::Parcel;
Ivan Lozano8cf3a072017-08-09 09:01:33 -070098using android::media::VolumeShaper;
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();
Chong Zhangd4fe6b12019-10-02 14:29:18 -0700451 // initialize the frame capture utilities
452 (void)FrameCaptureProcessor::getInstance();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800453}
454
455MediaPlayerService::~MediaPlayerService()
456{
Steve Block3856b092011-10-20 11:56:00 +0100457 ALOGV("MediaPlayerService destroyed");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800458}
459
Svet Ganovbe71aa22015-04-28 12:06:02 -0700460sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(const String16 &opPackageName)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800461{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800462 pid_t pid = IPCThreadState::self()->getCallingPid();
Svet Ganovbe71aa22015-04-28 12:06:02 -0700463 sp<MediaRecorderClient> recorder = new MediaRecorderClient(this, pid, opPackageName);
Gloria Wangdac6a312009-10-29 15:46:37 -0700464 wp<MediaRecorderClient> w = recorder;
465 Mutex::Autolock lock(mLock);
466 mMediaRecorderClients.add(w);
Steve Block3856b092011-10-20 11:56:00 +0100467 ALOGV("Create new media recorder client from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800468 return recorder;
469}
470
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -0700471void MediaPlayerService::removeMediaRecorderClient(const wp<MediaRecorderClient>& client)
Gloria Wangdac6a312009-10-29 15:46:37 -0700472{
473 Mutex::Autolock lock(mLock);
474 mMediaRecorderClients.remove(client);
Steve Block3856b092011-10-20 11:56:00 +0100475 ALOGV("Delete media recorder client");
Gloria Wangdac6a312009-10-29 15:46:37 -0700476}
477
Glenn Kastenf37971f2012-02-03 11:06:53 -0800478sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800479{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800480 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800481 sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
Steve Block3856b092011-10-20 11:56:00 +0100482 ALOGV("Create new media retriever from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800483 return retriever;
484}
485
Glenn Kastenf37971f2012-02-03 11:06:53 -0800486sp<IMediaPlayer> MediaPlayerService::create(const sp<IMediaPlayerClient>& client,
Glenn Kastend848eb42016-03-08 13:42:11 -0800487 audio_session_t audioSessionId)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800488{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800489 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800490 int32_t connId = android_atomic_inc(&mNextConnId);
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700491
492 sp<Client> c = new Client(
493 this, pid, connId, client, audioSessionId,
494 IPCThreadState::self()->getCallingUid());
495
Steve Block3856b092011-10-20 11:56:00 +0100496 ALOGV("Create new client(%d) from pid %d, uid %d, ", connId, pid,
Dave Burked681bbb2011-08-30 14:39:17 +0100497 IPCThreadState::self()->getCallingUid());
498
499 wp<Client> w = c;
500 {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800501 Mutex::Autolock lock(mLock);
502 mClients.add(w);
503 }
Andreas Hubere2b10282010-11-23 11:41:34 -0800504 return c;
505}
506
Lajos Molnar1381d4b2014-08-07 15:18:35 -0700507sp<IMediaCodecList> MediaPlayerService::getCodecList() const {
508 return MediaCodecList::getLocalInstance();
509}
510
Jeff Brown2013a542012-09-04 21:38:42 -0700511sp<IRemoteDisplay> MediaPlayerService::listenForRemoteDisplay(
Chong Zhangd0a98fa2017-09-14 17:43:10 -0700512 const String16 &/*opPackageName*/,
513 const sp<IRemoteDisplayClient>& /*client*/,
514 const String8& /*iface*/) {
515 ALOGE("listenForRemoteDisplay is no longer supported!");
Jeff Brownaba33d52012-09-07 17:38:58 -0700516
Chong Zhangd0a98fa2017-09-14 17:43:10 -0700517 return NULL;
Jeff Brown2013a542012-09-04 21:38:42 -0700518}
519
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800520status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
521{
522 const size_t SIZE = 256;
523 char buffer[SIZE];
524 String8 result;
525
526 result.append(" AudioOutput\n");
527 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n",
528 mStreamType, mLeftVolume, mRightVolume);
529 result.append(buffer);
530 snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n",
Eric Laurentdb354e52012-03-05 17:27:11 -0800531 mMsecsPerFrame, (mTrack != 0) ? mTrack->latency() : -1);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800532 result.append(buffer);
Eric Laurent2beeb502010-07-16 07:43:46 -0700533 snprintf(buffer, 255, " aux effect id(%d), send level (%f)\n",
534 mAuxEffectId, mSendLevel);
535 result.append(buffer);
536
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800537 ::write(fd, result.string(), result.size());
538 if (mTrack != 0) {
539 mTrack->dump(fd, args);
540 }
541 return NO_ERROR;
542}
543
Lajos Molnar6d339f12015-04-17 16:15:53 -0700544status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800545{
546 const size_t SIZE = 256;
547 char buffer[SIZE];
548 String8 result;
549 result.append(" Client\n");
550 snprintf(buffer, 255, " pid(%d), connId(%d), status(%d), looping(%s)\n",
551 mPid, mConnId, mStatus, mLoop?"true": "false");
552 result.append(buffer);
Wei Jia502c2f42017-07-13 17:47:56 -0700553
554 sp<MediaPlayerBase> p;
555 sp<AudioOutput> audioOutput;
556 bool locked = false;
557 for (int i = 0; i < kDumpLockRetries; ++i) {
558 if (mLock.tryLock() == NO_ERROR) {
559 locked = true;
560 break;
561 }
562 usleep(kDumpLockSleepUs);
Andreas Hubera0b1d4b2011-06-07 15:52:25 -0700563 }
Wei Jia502c2f42017-07-13 17:47:56 -0700564
565 if (locked) {
566 p = mPlayer;
567 audioOutput = mAudioOutput;
568 mLock.unlock();
569 } else {
570 result.append(" lock is taken, no dump from player and audio output\n");
571 }
572 write(fd, result.string(), result.size());
573
574 if (p != NULL) {
575 p->dump(fd, args);
576 }
577 if (audioOutput != 0) {
578 audioOutput->dump(fd, args);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800579 }
580 write(fd, "\n", 1);
581 return NO_ERROR;
582}
583
Marco Nelissenf09611f2015-02-13 14:12:42 -0800584/**
585 * The only arguments this understands right now are -c, -von and -voff,
586 * which are parsed by ALooperRoster::dump()
587 */
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800588status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
589{
590 const size_t SIZE = 256;
591 char buffer[SIZE];
592 String8 result;
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530593 SortedVector< sp<Client> > clients; //to serialise the mutex unlock & client destruction.
594 SortedVector< sp<MediaRecorderClient> > mediaRecorderClients;
595
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800596 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
Wonsik Kim6f675772019-08-20 17:06:53 -0700597 snprintf(buffer, SIZE - 1, "Permission Denial: "
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800598 "can't dump MediaPlayerService from pid=%d, uid=%d\n",
599 IPCThreadState::self()->getCallingPid(),
600 IPCThreadState::self()->getCallingUid());
601 result.append(buffer);
602 } else {
603 Mutex::Autolock lock(mLock);
604 for (int i = 0, n = mClients.size(); i < n; ++i) {
605 sp<Client> c = mClients[i].promote();
606 if (c != 0) c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530607 clients.add(c);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800608 }
James Dongb9141222010-07-08 11:16:11 -0700609 if (mMediaRecorderClients.size() == 0) {
610 result.append(" No media recorder client\n\n");
611 } else {
612 for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
613 sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
James Donge579e282011-10-18 22:29:20 -0700614 if (c != 0) {
615 snprintf(buffer, 255, " MediaRecorderClient pid(%d)\n", c->mPid);
616 result.append(buffer);
617 write(fd, result.string(), result.size());
618 result = "\n";
619 c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530620 mediaRecorderClients.add(c);
James Donge579e282011-10-18 22:29:20 -0700621 }
James Dongb9141222010-07-08 11:16:11 -0700622 }
Gloria Wangdac6a312009-10-29 15:46:37 -0700623 }
624
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800625 result.append(" Files opened and/or mapped:\n");
Wonsik Kim6f675772019-08-20 17:06:53 -0700626 snprintf(buffer, SIZE - 1, "/proc/%d/maps", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800627 FILE *f = fopen(buffer, "r");
628 if (f) {
629 while (!feof(f)) {
Wonsik Kim6f675772019-08-20 17:06:53 -0700630 fgets(buffer, SIZE - 1, f);
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700631 if (strstr(buffer, " /storage/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800632 strstr(buffer, " /system/sounds/") ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700633 strstr(buffer, " /data/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800634 strstr(buffer, " /system/media/")) {
635 result.append(" ");
636 result.append(buffer);
637 }
638 }
639 fclose(f);
640 } else {
641 result.append("couldn't open ");
642 result.append(buffer);
643 result.append("\n");
644 }
645
Wonsik Kim6f675772019-08-20 17:06:53 -0700646 snprintf(buffer, SIZE - 1, "/proc/%d/fd", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800647 DIR *d = opendir(buffer);
648 if (d) {
649 struct dirent *ent;
650 while((ent = readdir(d)) != NULL) {
651 if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
Wonsik Kim6f675772019-08-20 17:06:53 -0700652 snprintf(buffer, SIZE - 1, "/proc/%d/fd/%s", getpid(), ent->d_name);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800653 struct stat s;
654 if (lstat(buffer, &s) == 0) {
655 if ((s.st_mode & S_IFMT) == S_IFLNK) {
656 char linkto[256];
657 int len = readlink(buffer, linkto, sizeof(linkto));
658 if(len > 0) {
659 if(len > 255) {
660 linkto[252] = '.';
661 linkto[253] = '.';
662 linkto[254] = '.';
663 linkto[255] = 0;
664 } else {
665 linkto[len] = 0;
666 }
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700667 if (strstr(linkto, "/storage/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800668 strstr(linkto, "/system/sounds/") == linkto ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700669 strstr(linkto, "/data/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800670 strstr(linkto, "/system/media/") == linkto) {
671 result.append(" ");
672 result.append(buffer);
673 result.append(" -> ");
674 result.append(linkto);
675 result.append("\n");
676 }
677 }
678 } else {
679 result.append(" unexpected type for ");
680 result.append(buffer);
681 result.append("\n");
682 }
683 }
684 }
685 }
686 closedir(d);
687 } else {
688 result.append("couldn't open ");
689 result.append(buffer);
690 result.append("\n");
691 }
692
Marco Nelissenf09611f2015-02-13 14:12:42 -0800693 gLooperRoster.dump(fd, args);
694
Wonsik Kimd579f3e2019-10-07 14:14:09 -0700695 sp<IMediaCodecList> codecList = getCodecList();
696 dumpCodecDetails(fd, codecList, true /* decoders */);
697 dumpCodecDetails(fd, codecList, false /* !decoders */);
698
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800699 bool dumpMem = false;
Andy Hung53541292016-04-13 16:48:51 -0700700 bool unreachableMemory = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800701 for (size_t i = 0; i < args.size(); i++) {
702 if (args[i] == String16("-m")) {
703 dumpMem = true;
Andy Hung53541292016-04-13 16:48:51 -0700704 } else if (args[i] == String16("--unreachable")) {
705 unreachableMemory = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800706 }
707 }
708 if (dumpMem) {
Andy Hung07b745e2016-05-23 16:21:07 -0700709 result.append("\nDumping memory:\n");
710 std::string s = dumpMemoryAddresses(100 /* limit */);
711 result.append(s.c_str(), s.size());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800712 }
Andy Hung53541292016-04-13 16:48:51 -0700713 if (unreachableMemory) {
714 result.append("\nDumping unreachable memory:\n");
715 // TODO - should limit be an argument parameter?
716 std::string s = GetUnreachableMemoryString(true /* contents */, 10000 /* limit */);
717 result.append(s.c_str(), s.size());
718 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800719 }
720 write(fd, result.string(), result.size());
Wonsik Kim6f675772019-08-20 17:06:53 -0700721
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800722 return NO_ERROR;
723}
724
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -0700725void MediaPlayerService::removeClient(const wp<Client>& client)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800726{
727 Mutex::Autolock lock(mLock);
728 mClients.remove(client);
729}
730
Robert Shihee0a0e32016-08-16 16:50:54 -0700731bool MediaPlayerService::hasClient(wp<Client> client)
732{
733 Mutex::Autolock lock(mLock);
734 return mClients.indexOf(client) != NAME_NOT_FOUND;
735}
736
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700737MediaPlayerService::Client::Client(
738 const sp<MediaPlayerService>& service, pid_t pid,
739 int32_t connId, const sp<IMediaPlayerClient>& client,
Glenn Kastend848eb42016-03-08 13:42:11 -0800740 audio_session_t audioSessionId, uid_t uid)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800741{
Steve Block3856b092011-10-20 11:56:00 +0100742 ALOGV("Client(%d) constructor", connId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800743 mPid = pid;
744 mConnId = connId;
745 mService = service;
746 mClient = client;
747 mLoop = false;
748 mStatus = NO_INIT;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700749 mAudioSessionId = audioSessionId;
Andy Hung1afd0982016-11-08 16:13:44 -0800750 mUid = uid;
John Grossmanc795b642012-02-22 15:38:35 -0800751 mRetransmitEndpointValid = false;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700752 mAudioAttributes = NULL;
Pawin Vongmasa082e4f72017-12-17 02:31:18 -0800753 mListener = new Listener(this);
Eric Laurenta514bdb2010-06-21 09:27:30 -0700754
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800755#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000756 ALOGD("create Antagonizer");
Pawin Vongmasa082e4f72017-12-17 02:31:18 -0800757 mAntagonizer = new Antagonizer(mListener);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800758#endif
759}
760
761MediaPlayerService::Client::~Client()
762{
Steve Block3856b092011-10-20 11:56:00 +0100763 ALOGV("Client(%d) destructor pid = %d", mConnId, mPid);
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700764 mAudioOutput.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800765 wp<Client> client(this);
766 disconnect();
767 mService->removeClient(client);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700768 if (mAudioAttributes != NULL) {
769 free(mAudioAttributes);
770 }
jiabin156c6872017-10-06 09:47:15 -0700771 mAudioDeviceUpdatedListener.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800772}
773
774void MediaPlayerService::Client::disconnect()
775{
Steve Block3856b092011-10-20 11:56:00 +0100776 ALOGV("disconnect(%d) from pid %d", mConnId, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800777 // grab local reference and clear main reference to prevent future
778 // access to object
779 sp<MediaPlayerBase> p;
780 {
781 Mutex::Autolock l(mLock);
782 p = mPlayer;
beanzdcfefde2012-11-05 09:51:43 +0800783 mClient.clear();
Wei Jia502c2f42017-07-13 17:47:56 -0700784 mPlayer.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800785 }
Andreas Huber20111aa2009-07-14 16:56:47 -0700786
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800787 // clear the notification to prevent callbacks to dead client
788 // and reset the player. We assume the player will serialize
789 // access to itself if necessary.
790 if (p != 0) {
Pawin Vongmasa082e4f72017-12-17 02:31:18 -0800791 p->setNotifyCallback(0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800792#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000793 ALOGD("kill Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800794 mAntagonizer->kill();
795#endif
796 p->reset();
797 }
798
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700799 {
800 Mutex::Autolock l(mLock);
801 disconnectNativeWindow_l();
802 }
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700803
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800804 IPCThreadState::self()->flushCommands();
805}
806
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800807sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
808{
809 // determine if we have the right player type
Wei Jia502c2f42017-07-13 17:47:56 -0700810 sp<MediaPlayerBase> p = getPlayer();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800811 if ((p != NULL) && (p->playerType() != playerType)) {
Steve Block3856b092011-10-20 11:56:00 +0100812 ALOGV("delete player");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800813 p.clear();
814 }
815 if (p == NULL) {
Pawin Vongmasa082e4f72017-12-17 02:31:18 -0800816 p = MediaPlayerFactory::createPlayer(playerType, mListener, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800817 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700818
Jason Simmonsdb29e522011-08-12 13:46:55 -0700819 if (p != NULL) {
Andy Hung1afd0982016-11-08 16:13:44 -0800820 p->setUID(mUid);
Jason Simmonsdb29e522011-08-12 13:46:55 -0700821 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700822
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800823 return p;
824}
825
jiabin156c6872017-10-06 09:47:15 -0700826void MediaPlayerService::Client::AudioDeviceUpdatedNotifier::onAudioDeviceUpdate(
827 audio_io_handle_t audioIo,
828 audio_port_handle_t deviceId) {
829 sp<MediaPlayerBase> listener = mListener.promote();
830 if (listener != NULL) {
831 listener->sendEvent(MEDIA_AUDIO_ROUTING_CHANGED, audioIo, deviceId);
832 } else {
833 ALOGW("listener for process %d death is gone", MEDIA_AUDIO_ROUTING_CHANGED);
834 }
835}
836
John Grossmanc795b642012-02-22 15:38:35 -0800837sp<MediaPlayerBase> MediaPlayerService::Client::setDataSource_pre(
838 player_type playerType)
839{
840 ALOGV("player type = %d", playerType);
841
842 // create the right type of player
843 sp<MediaPlayerBase> p = createPlayer(playerType);
844 if (p == NULL) {
845 return p;
846 }
847
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700848 std::vector<DeathNotifier> deathNotifiers;
849
850 // Listen to death of media.extractor service
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700851 sp<IServiceManager> sm = defaultServiceManager();
852 sp<IBinder> binder = sm->getService(String16("media.extractor"));
Marco Nelissen1b5a7ee2016-09-30 13:54:30 -0700853 if (binder == NULL) {
854 ALOGE("extractor service not available");
855 return NULL;
856 }
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700857 deathNotifiers.emplace_back(
858 binder, [l = wp<MediaPlayerBase>(p)]() {
859 sp<MediaPlayerBase> listener = l.promote();
860 if (listener) {
861 ALOGI("media.extractor died. Sending death notification.");
862 listener->sendEvent(MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED,
863 MEDIAEXTRACTOR_PROCESS_DEATH);
864 } else {
865 ALOGW("media.extractor died without a death handler.");
866 }
867 });
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700868
Marco Nelissena0c98412019-03-29 12:10:19 -0700869 {
870 using ::android::hidl::base::V1_0::IBase;
871
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700872 // Listen to death of OMX service
Marco Nelissena0c98412019-03-29 12:10:19 -0700873 {
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700874 sp<IBase> base = ::android::hardware::media::omx::V1_0::
875 IOmx::getService();
876 if (base == nullptr) {
Marco Nelissena0c98412019-03-29 12:10:19 -0700877 ALOGD("OMX service is not available");
878 } else {
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700879 deathNotifiers.emplace_back(
880 base, [l = wp<MediaPlayerBase>(p)]() {
881 sp<MediaPlayerBase> listener = l.promote();
882 if (listener) {
883 ALOGI("OMX service died. "
884 "Sending death notification.");
885 listener->sendEvent(
886 MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED,
887 MEDIACODEC_PROCESS_DEATH);
888 } else {
889 ALOGW("OMX service died without a death handler.");
890 }
891 });
Marco Nelissena0c98412019-03-29 12:10:19 -0700892 }
893 }
894
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700895 // Listen to death of Codec2 services
Marco Nelissena0c98412019-03-29 12:10:19 -0700896 {
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700897 for (std::shared_ptr<Codec2Client> const& client :
898 Codec2Client::CreateFromAllServices()) {
899 sp<IBase> base = client->getBase();
900 deathNotifiers.emplace_back(
901 base, [l = wp<MediaPlayerBase>(p),
902 name = std::string(client->getServiceName())]() {
903 sp<MediaPlayerBase> listener = l.promote();
904 if (listener) {
905 ALOGI("Codec2 service \"%s\" died. "
906 "Sending death notification.",
907 name.c_str());
908 listener->sendEvent(
909 MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED,
910 MEDIACODEC_PROCESS_DEATH);
911 } else {
912 ALOGW("Codec2 service \"%s\" died "
913 "without a death handler.",
914 name.c_str());
915 }
916 });
Marco Nelissene4da6c62019-04-01 15:01:41 -0700917 }
Marco Nelissena0c98412019-03-29 12:10:19 -0700918 }
Marco Nelissen1b5a7ee2016-09-30 13:54:30 -0700919 }
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700920
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700921 Mutex::Autolock lock(mLock);
922
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700923 mDeathNotifiers.clear();
924 mDeathNotifiers.swap(deathNotifiers);
jiabin156c6872017-10-06 09:47:15 -0700925 mAudioDeviceUpdatedListener = new AudioDeviceUpdatedNotifier(p);
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700926
John Grossmanc795b642012-02-22 15:38:35 -0800927 if (!p->hardwareOutput()) {
Marco Nelissend457c972014-02-11 08:47:07 -0800928 mAudioOutput = new AudioOutput(mAudioSessionId, IPCThreadState::self()->getCallingUid(),
jiabin156c6872017-10-06 09:47:15 -0700929 mPid, mAudioAttributes, mAudioDeviceUpdatedListener);
John Grossmanc795b642012-02-22 15:38:35 -0800930 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
931 }
932
933 return p;
934}
935
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700936status_t MediaPlayerService::Client::setDataSource_post(
John Grossmanc795b642012-02-22 15:38:35 -0800937 const sp<MediaPlayerBase>& p,
938 status_t status)
939{
940 ALOGV(" setDataSource");
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700941 if (status != OK) {
942 ALOGE(" error: %d", status);
943 return status;
John Grossmanc795b642012-02-22 15:38:35 -0800944 }
945
946 // Set the re-transmission endpoint if one was chosen.
947 if (mRetransmitEndpointValid) {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700948 status = p->setRetransmitEndpoint(&mRetransmitEndpoint);
949 if (status != NO_ERROR) {
950 ALOGE("setRetransmitEndpoint error: %d", status);
John Grossmanc795b642012-02-22 15:38:35 -0800951 }
952 }
953
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700954 if (status == OK) {
955 Mutex::Autolock lock(mLock);
John Grossmanc795b642012-02-22 15:38:35 -0800956 mPlayer = p;
957 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700958 return status;
John Grossmanc795b642012-02-22 15:38:35 -0800959}
960
Andreas Huber2db84552010-01-28 11:19:57 -0800961status_t MediaPlayerService::Client::setDataSource(
Andreas Huber1b86fe02014-01-29 11:13:26 -0800962 const sp<IMediaHTTPService> &httpService,
963 const char *url,
964 const KeyedVector<String8, String8> *headers)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800965{
Steve Block3856b092011-10-20 11:56:00 +0100966 ALOGV("setDataSource(%s)", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800967 if (url == NULL)
968 return UNKNOWN_ERROR;
969
Dave Burked681bbb2011-08-30 14:39:17 +0100970 if ((strncmp(url, "http://", 7) == 0) ||
971 (strncmp(url, "https://", 8) == 0) ||
972 (strncmp(url, "rtsp://", 7) == 0)) {
973 if (!checkPermission("android.permission.INTERNET")) {
974 return PERMISSION_DENIED;
975 }
976 }
977
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800978 if (strncmp(url, "content://", 10) == 0) {
979 // get a filedescriptor for the content Uri and
980 // pass it to the setDataSource(fd) method
981
982 String16 url16(url);
983 int fd = android::openContentProviderFile(url16);
984 if (fd < 0)
985 {
Steve Block29357bc2012-01-06 19:20:56 +0000986 ALOGE("Couldn't open fd for %s", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800987 return UNKNOWN_ERROR;
988 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700989 status_t status = setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800990 close(fd);
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700991 return mStatus = status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800992 } else {
John Grossman44a7e422012-06-21 17:29:24 -0700993 player_type playerType = MediaPlayerFactory::getPlayerType(this, url);
John Grossmanc795b642012-02-22 15:38:35 -0800994 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
995 if (p == NULL) {
996 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800997 }
998
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700999 return mStatus =
1000 setDataSource_post(
1001 p, p->setDataSource(httpService, url, headers));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001002 }
1003}
1004
1005status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
1006{
Marco Nelissen83b0fd92015-09-16 13:48:07 -07001007 ALOGV("setDataSource fd=%d (%s), offset=%lld, length=%lld",
1008 fd, nameForFd(fd).c_str(), (long long) offset, (long long) length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001009 struct stat sb;
1010 int ret = fstat(fd, &sb);
1011 if (ret != 0) {
Steve Block29357bc2012-01-06 19:20:56 +00001012 ALOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001013 return UNKNOWN_ERROR;
1014 }
1015
Andy Hung833b4752016-04-04 17:15:48 -07001016 ALOGV("st_dev = %llu", static_cast<unsigned long long>(sb.st_dev));
Steve Block3856b092011-10-20 11:56:00 +01001017 ALOGV("st_mode = %u", sb.st_mode);
Mark Salyzyn77342f72014-06-18 16:31:32 -07001018 ALOGV("st_uid = %lu", static_cast<unsigned long>(sb.st_uid));
1019 ALOGV("st_gid = %lu", static_cast<unsigned long>(sb.st_gid));
Andy Hung833b4752016-04-04 17:15:48 -07001020 ALOGV("st_size = %llu", static_cast<unsigned long long>(sb.st_size));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001021
1022 if (offset >= sb.st_size) {
Steve Block29357bc2012-01-06 19:20:56 +00001023 ALOGE("offset error");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001024 return UNKNOWN_ERROR;
1025 }
1026 if (offset + length > sb.st_size) {
1027 length = sb.st_size - offset;
Andy Hung833b4752016-04-04 17:15:48 -07001028 ALOGV("calculated length = %lld", (long long)length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001029 }
1030
John Grossman44a7e422012-06-21 17:29:24 -07001031 player_type playerType = MediaPlayerFactory::getPlayerType(this,
1032 fd,
1033 offset,
1034 length);
John Grossmanc795b642012-02-22 15:38:35 -08001035 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
1036 if (p == NULL) {
1037 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001038 }
1039
1040 // now set data source
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001041 return mStatus = setDataSource_post(p, p->setDataSource(fd, offset, length));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001042}
1043
Andreas Hubere2b10282010-11-23 11:41:34 -08001044status_t MediaPlayerService::Client::setDataSource(
1045 const sp<IStreamSource> &source) {
1046 // create the right type of player
John Grossman44a7e422012-06-21 17:29:24 -07001047 player_type playerType = MediaPlayerFactory::getPlayerType(this, source);
John Grossmanc795b642012-02-22 15:38:35 -08001048 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
Andreas Hubere2b10282010-11-23 11:41:34 -08001049 if (p == NULL) {
1050 return NO_INIT;
1051 }
1052
Andreas Hubere2b10282010-11-23 11:41:34 -08001053 // now set data source
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001054 return mStatus = setDataSource_post(p, p->setDataSource(source));
Andreas Hubere2b10282010-11-23 11:41:34 -08001055}
1056
Chris Watkins99f31602015-03-20 13:06:33 -07001057status_t MediaPlayerService::Client::setDataSource(
1058 const sp<IDataSource> &source) {
Dongwon Kangd91dc5a2017-10-10 00:07:09 -07001059 sp<DataSource> dataSource = CreateDataSourceFromIDataSource(source);
Chris Watkins99f31602015-03-20 13:06:33 -07001060 player_type playerType = MediaPlayerFactory::getPlayerType(this, dataSource);
1061 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
1062 if (p == NULL) {
1063 return NO_INIT;
1064 }
1065 // now set data source
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001066 return mStatus = setDataSource_post(p, p->setDataSource(dataSource));
Chris Watkins99f31602015-03-20 13:06:33 -07001067}
1068
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001069void MediaPlayerService::Client::disconnectNativeWindow_l() {
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001070 if (mConnectedWindow != NULL) {
Chong Zhang181fd9b2017-02-16 15:53:03 -08001071 status_t err = nativeWindowDisconnect(
1072 mConnectedWindow.get(), "disconnectNativeWindow");
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001073
1074 if (err != OK) {
Chong Zhang181fd9b2017-02-16 15:53:03 -08001075 ALOGW("nativeWindowDisconnect returned an error: %s (%d)",
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001076 strerror(-err), err);
1077 }
1078 }
1079 mConnectedWindow.clear();
1080}
1081
Glenn Kasten11731182011-02-08 17:26:17 -08001082status_t MediaPlayerService::Client::setVideoSurfaceTexture(
Andy McFadden484566c2012-12-18 09:46:54 -08001083 const sp<IGraphicBufferProducer>& bufferProducer)
Glenn Kasten11731182011-02-08 17:26:17 -08001084{
Andy McFadden484566c2012-12-18 09:46:54 -08001085 ALOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, bufferProducer.get());
Glenn Kasten11731182011-02-08 17:26:17 -08001086 sp<MediaPlayerBase> p = getPlayer();
1087 if (p == 0) return UNKNOWN_ERROR;
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001088
Marco Nelissenf8880202014-11-14 07:58:25 -08001089 sp<IBinder> binder(IInterface::asBinder(bufferProducer));
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001090 if (mConnectedWindowBinder == binder) {
1091 return OK;
1092 }
1093
1094 sp<ANativeWindow> anw;
Andy McFadden484566c2012-12-18 09:46:54 -08001095 if (bufferProducer != NULL) {
Marco Nelissenee08f7e2013-09-16 13:30:01 -07001096 anw = new Surface(bufferProducer, true /* controlledByApp */);
Chong Zhang181fd9b2017-02-16 15:53:03 -08001097 status_t err = nativeWindowConnect(anw.get(), "setVideoSurfaceTexture");
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001098
1099 if (err != OK) {
Steve Block29357bc2012-01-06 19:20:56 +00001100 ALOGE("setVideoSurfaceTexture failed: %d", err);
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001101 // Note that we must do the reset before disconnecting from the ANW.
1102 // Otherwise queue/dequeue calls could be made on the disconnected
1103 // ANW, which may result in errors.
1104 reset();
1105
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001106 Mutex::Autolock lock(mLock);
1107 disconnectNativeWindow_l();
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001108
1109 return err;
1110 }
1111 }
1112
Andy McFadden484566c2012-12-18 09:46:54 -08001113 // Note that we must set the player's new GraphicBufferProducer before
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001114 // disconnecting the old one. Otherwise queue/dequeue calls could be made
1115 // on the disconnected ANW, which may result in errors.
Andy McFadden484566c2012-12-18 09:46:54 -08001116 status_t err = p->setVideoSurfaceTexture(bufferProducer);
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001117
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001118 mLock.lock();
1119 disconnectNativeWindow_l();
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001120
1121 if (err == OK) {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001122 mConnectedWindow = anw;
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001123 mConnectedWindowBinder = binder;
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001124 mLock.unlock();
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001125 } else {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001126 mLock.unlock();
1127 status_t err = nativeWindowDisconnect(
1128 anw.get(), "disconnectNativeWindow");
1129
1130 if (err != OK) {
1131 ALOGW("nativeWindowDisconnect returned an error: %s (%d)",
1132 strerror(-err), err);
1133 }
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001134 }
1135
1136 return err;
Glenn Kasten11731182011-02-08 17:26:17 -08001137}
1138
Nicolas Catania1d187f12009-05-12 23:25:55 -07001139status_t MediaPlayerService::Client::invoke(const Parcel& request,
1140 Parcel *reply)
1141{
1142 sp<MediaPlayerBase> p = getPlayer();
1143 if (p == NULL) return UNKNOWN_ERROR;
1144 return p->invoke(request, reply);
1145}
1146
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001147// This call doesn't need to access the native player.
1148status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
1149{
1150 status_t status;
nikoa64c8c72009-07-20 15:07:26 -07001151 media::Metadata::Filter allow, drop;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001152
Nicolas Catania48290382009-07-10 13:53:06 -07001153 if (unmarshallFilter(filter, &allow, &status) &&
1154 unmarshallFilter(filter, &drop, &status)) {
1155 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001156
1157 mMetadataAllow = allow;
1158 mMetadataDrop = drop;
1159 }
1160 return status;
1161}
1162
Nicolas Catania48290382009-07-10 13:53:06 -07001163status_t MediaPlayerService::Client::getMetadata(
Mark Salyzyn77342f72014-06-18 16:31:32 -07001164 bool update_only, bool /*apply_filter*/, Parcel *reply)
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001165{
nikoa64c8c72009-07-20 15:07:26 -07001166 sp<MediaPlayerBase> player = getPlayer();
1167 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania48290382009-07-10 13:53:06 -07001168
nikod608a812009-07-16 16:39:53 -07001169 status_t status;
1170 // Placeholder for the return code, updated by the caller.
1171 reply->writeInt32(-1);
1172
nikoa64c8c72009-07-20 15:07:26 -07001173 media::Metadata::Filter ids;
Nicolas Catania48290382009-07-10 13:53:06 -07001174
1175 // We don't block notifications while we fetch the data. We clear
1176 // mMetadataUpdated first so we don't lose notifications happening
1177 // during the rest of this call.
1178 {
1179 Mutex::Autolock lock(mLock);
1180 if (update_only) {
nikod608a812009-07-16 16:39:53 -07001181 ids = mMetadataUpdated;
Nicolas Catania48290382009-07-10 13:53:06 -07001182 }
1183 mMetadataUpdated.clear();
1184 }
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001185
nikoa64c8c72009-07-20 15:07:26 -07001186 media::Metadata metadata(reply);
Nicolas Catania48290382009-07-10 13:53:06 -07001187
nikoa64c8c72009-07-20 15:07:26 -07001188 metadata.appendHeader();
1189 status = player->getMetadata(ids, reply);
nikod608a812009-07-16 16:39:53 -07001190
1191 if (status != OK) {
nikoa64c8c72009-07-20 15:07:26 -07001192 metadata.resetParcel();
Steve Block29357bc2012-01-06 19:20:56 +00001193 ALOGE("getMetadata failed %d", status);
nikod608a812009-07-16 16:39:53 -07001194 return status;
1195 }
1196
1197 // FIXME: Implement filtering on the result. Not critical since
1198 // filtering takes place on the update notifications already. This
1199 // would be when all the metadata are fetch and a filter is set.
1200
nikod608a812009-07-16 16:39:53 -07001201 // Everything is fine, update the metadata length.
nikoa64c8c72009-07-20 15:07:26 -07001202 metadata.updateLength();
nikod608a812009-07-16 16:39:53 -07001203 return OK;
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001204}
1205
Wei Jiad399e7e2016-10-26 15:49:11 -07001206status_t MediaPlayerService::Client::setBufferingSettings(
1207 const BufferingSettings& buffering)
1208{
Wei Jiadc6f3402017-01-09 15:04:18 -08001209 ALOGV("[%d] setBufferingSettings{%s}",
1210 mConnId, buffering.toString().string());
Wei Jiad399e7e2016-10-26 15:49:11 -07001211 sp<MediaPlayerBase> p = getPlayer();
1212 if (p == 0) return UNKNOWN_ERROR;
1213 return p->setBufferingSettings(buffering);
1214}
1215
Wei Jia9bb38032017-03-23 18:00:38 -07001216status_t MediaPlayerService::Client::getBufferingSettings(
Wei Jiad399e7e2016-10-26 15:49:11 -07001217 BufferingSettings* buffering /* nonnull */)
1218{
1219 sp<MediaPlayerBase> p = getPlayer();
1220 // TODO: create mPlayer on demand.
1221 if (p == 0) return UNKNOWN_ERROR;
Wei Jia9bb38032017-03-23 18:00:38 -07001222 status_t ret = p->getBufferingSettings(buffering);
Wei Jiad399e7e2016-10-26 15:49:11 -07001223 if (ret == NO_ERROR) {
Wei Jia9bb38032017-03-23 18:00:38 -07001224 ALOGV("[%d] getBufferingSettings{%s}",
Wei Jiadc6f3402017-01-09 15:04:18 -08001225 mConnId, buffering->toString().string());
Wei Jiad399e7e2016-10-26 15:49:11 -07001226 } else {
Wei Jia9bb38032017-03-23 18:00:38 -07001227 ALOGE("[%d] getBufferingSettings returned %d", mConnId, ret);
Wei Jiad399e7e2016-10-26 15:49:11 -07001228 }
1229 return ret;
1230}
1231
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001232status_t MediaPlayerService::Client::prepareAsync()
1233{
Steve Block3856b092011-10-20 11:56:00 +01001234 ALOGV("[%d] prepareAsync", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001235 sp<MediaPlayerBase> p = getPlayer();
1236 if (p == 0) return UNKNOWN_ERROR;
1237 status_t ret = p->prepareAsync();
1238#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +00001239 ALOGD("start Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001240 if (ret == NO_ERROR) mAntagonizer->start();
1241#endif
1242 return ret;
1243}
1244
1245status_t MediaPlayerService::Client::start()
1246{
Steve Block3856b092011-10-20 11:56:00 +01001247 ALOGV("[%d] start", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001248 sp<MediaPlayerBase> p = getPlayer();
1249 if (p == 0) return UNKNOWN_ERROR;
1250 p->setLooping(mLoop);
1251 return p->start();
1252}
1253
1254status_t MediaPlayerService::Client::stop()
1255{
Steve Block3856b092011-10-20 11:56:00 +01001256 ALOGV("[%d] stop", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001257 sp<MediaPlayerBase> p = getPlayer();
1258 if (p == 0) return UNKNOWN_ERROR;
1259 return p->stop();
1260}
1261
1262status_t MediaPlayerService::Client::pause()
1263{
Steve Block3856b092011-10-20 11:56:00 +01001264 ALOGV("[%d] pause", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001265 sp<MediaPlayerBase> p = getPlayer();
1266 if (p == 0) return UNKNOWN_ERROR;
1267 return p->pause();
1268}
1269
1270status_t MediaPlayerService::Client::isPlaying(bool* state)
1271{
1272 *state = false;
1273 sp<MediaPlayerBase> p = getPlayer();
1274 if (p == 0) return UNKNOWN_ERROR;
1275 *state = p->isPlaying();
Steve Block3856b092011-10-20 11:56:00 +01001276 ALOGV("[%d] isPlaying: %d", mConnId, *state);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001277 return NO_ERROR;
1278}
1279
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001280status_t MediaPlayerService::Client::setPlaybackSettings(const AudioPlaybackRate& rate)
Wei Jia98160162015-02-04 17:01:11 -08001281{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001282 ALOGV("[%d] setPlaybackSettings(%f, %f, %d, %d)",
1283 mConnId, rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Wei Jia98160162015-02-04 17:01:11 -08001284 sp<MediaPlayerBase> p = getPlayer();
1285 if (p == 0) return UNKNOWN_ERROR;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001286 return p->setPlaybackSettings(rate);
1287}
1288
1289status_t MediaPlayerService::Client::getPlaybackSettings(AudioPlaybackRate* rate /* nonnull */)
1290{
1291 sp<MediaPlayerBase> p = getPlayer();
1292 if (p == 0) return UNKNOWN_ERROR;
1293 status_t ret = p->getPlaybackSettings(rate);
1294 if (ret == NO_ERROR) {
1295 ALOGV("[%d] getPlaybackSettings(%f, %f, %d, %d)",
1296 mConnId, rate->mSpeed, rate->mPitch, rate->mFallbackMode, rate->mStretchMode);
1297 } else {
1298 ALOGV("[%d] getPlaybackSettings returned %d", mConnId, ret);
1299 }
1300 return ret;
1301}
1302
1303status_t MediaPlayerService::Client::setSyncSettings(
1304 const AVSyncSettings& sync, float videoFpsHint)
1305{
1306 ALOGV("[%d] setSyncSettings(%u, %u, %f, %f)",
1307 mConnId, sync.mSource, sync.mAudioAdjustMode, sync.mTolerance, videoFpsHint);
1308 sp<MediaPlayerBase> p = getPlayer();
1309 if (p == 0) return UNKNOWN_ERROR;
1310 return p->setSyncSettings(sync, videoFpsHint);
1311}
1312
1313status_t MediaPlayerService::Client::getSyncSettings(
1314 AVSyncSettings* sync /* nonnull */, float* videoFps /* nonnull */)
1315{
1316 sp<MediaPlayerBase> p = getPlayer();
1317 if (p == 0) return UNKNOWN_ERROR;
1318 status_t ret = p->getSyncSettings(sync, videoFps);
1319 if (ret == NO_ERROR) {
1320 ALOGV("[%d] getSyncSettings(%u, %u, %f, %f)",
1321 mConnId, sync->mSource, sync->mAudioAdjustMode, sync->mTolerance, *videoFps);
1322 } else {
1323 ALOGV("[%d] getSyncSettings returned %d", mConnId, ret);
1324 }
1325 return ret;
Wei Jia98160162015-02-04 17:01:11 -08001326}
1327
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001328status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
1329{
Steve Block3856b092011-10-20 11:56:00 +01001330 ALOGV("getCurrentPosition");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001331 sp<MediaPlayerBase> p = getPlayer();
1332 if (p == 0) return UNKNOWN_ERROR;
1333 status_t ret = p->getCurrentPosition(msec);
1334 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001335 ALOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001336 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001337 ALOGE("getCurrentPosition returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001338 }
1339 return ret;
1340}
1341
1342status_t MediaPlayerService::Client::getDuration(int *msec)
1343{
Steve Block3856b092011-10-20 11:56:00 +01001344 ALOGV("getDuration");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001345 sp<MediaPlayerBase> p = getPlayer();
1346 if (p == 0) return UNKNOWN_ERROR;
1347 status_t ret = p->getDuration(msec);
1348 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001349 ALOGV("[%d] getDuration = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001350 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001351 ALOGE("getDuration returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001352 }
1353 return ret;
1354}
1355
Marco Nelissen6b74d672012-02-28 16:07:44 -08001356status_t MediaPlayerService::Client::setNextPlayer(const sp<IMediaPlayer>& player) {
1357 ALOGV("setNextPlayer");
1358 Mutex::Autolock l(mLock);
1359 sp<Client> c = static_cast<Client*>(player.get());
Wei Jia28284122016-08-30 13:49:06 -07001360 if (c != NULL && !mService->hasClient(c)) {
Robert Shihee0a0e32016-08-16 16:50:54 -07001361 return BAD_VALUE;
1362 }
1363
Marco Nelissen6b74d672012-02-28 16:07:44 -08001364 mNextClient = c;
John Grossman5f7e55e2012-08-24 14:47:25 -07001365
1366 if (c != NULL) {
1367 if (mAudioOutput != NULL) {
1368 mAudioOutput->setNextOutput(c->mAudioOutput);
1369 } else if ((mPlayer != NULL) && !mPlayer->hardwareOutput()) {
1370 ALOGE("no current audio output");
1371 }
1372
1373 if ((mPlayer != NULL) && (mNextClient->getPlayer() != NULL)) {
1374 mPlayer->setNextPlayer(mNextClient->getPlayer());
1375 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001376 }
John Grossman5f7e55e2012-08-24 14:47:25 -07001377
Marco Nelissen6b74d672012-02-28 16:07:44 -08001378 return OK;
1379}
1380
Andy Hung9fc8b5c2017-01-24 13:36:48 -08001381VolumeShaper::Status MediaPlayerService::Client::applyVolumeShaper(
1382 const sp<VolumeShaper::Configuration>& configuration,
1383 const sp<VolumeShaper::Operation>& operation) {
1384 // for hardware output, call player instead
1385 ALOGV("Client::applyVolumeShaper(%p)", this);
1386 sp<MediaPlayerBase> p = getPlayer();
1387 {
1388 Mutex::Autolock l(mLock);
1389 if (p != 0 && p->hardwareOutput()) {
1390 // TODO: investigate internal implementation
1391 return VolumeShaper::Status(INVALID_OPERATION);
1392 }
1393 if (mAudioOutput.get() != nullptr) {
1394 return mAudioOutput->applyVolumeShaper(configuration, operation);
1395 }
1396 }
1397 return VolumeShaper::Status(INVALID_OPERATION);
1398}
1399
1400sp<VolumeShaper::State> MediaPlayerService::Client::getVolumeShaperState(int id) {
1401 // for hardware output, call player instead
1402 ALOGV("Client::getVolumeShaperState(%p)", this);
1403 sp<MediaPlayerBase> p = getPlayer();
1404 {
1405 Mutex::Autolock l(mLock);
1406 if (p != 0 && p->hardwareOutput()) {
1407 // TODO: investigate internal implementation.
1408 return nullptr;
1409 }
1410 if (mAudioOutput.get() != nullptr) {
1411 return mAudioOutput->getVolumeShaperState(id);
1412 }
1413 }
1414 return nullptr;
1415}
1416
Wei Jiac5de0912016-11-18 10:22:14 -08001417status_t MediaPlayerService::Client::seekTo(int msec, MediaPlayerSeekMode mode)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001418{
Wei Jiac5de0912016-11-18 10:22:14 -08001419 ALOGV("[%d] seekTo(%d, %d)", mConnId, msec, mode);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001420 sp<MediaPlayerBase> p = getPlayer();
1421 if (p == 0) return UNKNOWN_ERROR;
Wei Jiac5de0912016-11-18 10:22:14 -08001422 return p->seekTo(msec, mode);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001423}
1424
1425status_t MediaPlayerService::Client::reset()
1426{
Steve Block3856b092011-10-20 11:56:00 +01001427 ALOGV("[%d] reset", mConnId);
John Grossmanc795b642012-02-22 15:38:35 -08001428 mRetransmitEndpointValid = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001429 sp<MediaPlayerBase> p = getPlayer();
1430 if (p == 0) return UNKNOWN_ERROR;
1431 return p->reset();
1432}
1433
Wei Jia52c28512017-09-13 18:17:51 -07001434status_t MediaPlayerService::Client::notifyAt(int64_t mediaTimeUs)
1435{
1436 ALOGV("[%d] notifyAt(%lld)", mConnId, (long long)mediaTimeUs);
1437 sp<MediaPlayerBase> p = getPlayer();
1438 if (p == 0) return UNKNOWN_ERROR;
1439 return p->notifyAt(mediaTimeUs);
1440}
1441
Glenn Kastenfff6d712012-01-12 16:38:12 -08001442status_t MediaPlayerService::Client::setAudioStreamType(audio_stream_type_t type)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001443{
Steve Block3856b092011-10-20 11:56:00 +01001444 ALOGV("[%d] setAudioStreamType(%d)", mConnId, type);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001445 // TODO: for hardware output, call player instead
1446 Mutex::Autolock l(mLock);
1447 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1448 return NO_ERROR;
1449}
1450
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001451status_t MediaPlayerService::Client::setAudioAttributes_l(const Parcel &parcel)
1452{
1453 if (mAudioAttributes != NULL) { free(mAudioAttributes); }
1454 mAudioAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001455 if (mAudioAttributes == NULL) {
1456 return NO_MEMORY;
1457 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001458 unmarshallAudioAttributes(parcel, mAudioAttributes);
1459
1460 ALOGV("setAudioAttributes_l() usage=%d content=%d flags=0x%x tags=%s",
1461 mAudioAttributes->usage, mAudioAttributes->content_type, mAudioAttributes->flags,
1462 mAudioAttributes->tags);
1463
1464 if (mAudioOutput != 0) {
1465 mAudioOutput->setAudioAttributes(mAudioAttributes);
1466 }
1467 return NO_ERROR;
1468}
1469
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001470status_t MediaPlayerService::Client::setLooping(int loop)
1471{
Steve Block3856b092011-10-20 11:56:00 +01001472 ALOGV("[%d] setLooping(%d)", mConnId, loop);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001473 mLoop = loop;
1474 sp<MediaPlayerBase> p = getPlayer();
1475 if (p != 0) return p->setLooping(loop);
1476 return NO_ERROR;
1477}
1478
1479status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1480{
Steve Block3856b092011-10-20 11:56:00 +01001481 ALOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
John Grossman761defc2012-02-09 15:09:05 -08001482
1483 // for hardware output, call player instead
1484 sp<MediaPlayerBase> p = getPlayer();
1485 {
1486 Mutex::Autolock l(mLock);
1487 if (p != 0 && p->hardwareOutput()) {
1488 MediaPlayerHWInterface* hwp =
1489 reinterpret_cast<MediaPlayerHWInterface*>(p.get());
1490 return hwp->setVolume(leftVolume, rightVolume);
1491 } else {
1492 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1493 return NO_ERROR;
1494 }
1495 }
1496
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001497 return NO_ERROR;
1498}
1499
Eric Laurent2beeb502010-07-16 07:43:46 -07001500status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1501{
Steve Block3856b092011-10-20 11:56:00 +01001502 ALOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
Eric Laurent2beeb502010-07-16 07:43:46 -07001503 Mutex::Autolock l(mLock);
1504 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1505 return NO_ERROR;
1506}
1507
1508status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1509{
Steve Block3856b092011-10-20 11:56:00 +01001510 ALOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
Eric Laurent2beeb502010-07-16 07:43:46 -07001511 Mutex::Autolock l(mLock);
1512 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1513 return NO_ERROR;
1514}
Nicolas Catania48290382009-07-10 13:53:06 -07001515
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001516status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
Steve Block3856b092011-10-20 11:56:00 +01001517 ALOGV("[%d] setParameter(%d)", mConnId, key);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001518 switch (key) {
1519 case KEY_PARAMETER_AUDIO_ATTRIBUTES:
1520 {
1521 Mutex::Autolock l(mLock);
1522 return setAudioAttributes_l(request);
1523 }
1524 default:
1525 sp<MediaPlayerBase> p = getPlayer();
1526 if (p == 0) { return UNKNOWN_ERROR; }
1527 return p->setParameter(key, request);
1528 }
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001529}
1530
1531status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
Steve Block3856b092011-10-20 11:56:00 +01001532 ALOGV("[%d] getParameter(%d)", mConnId, key);
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001533 sp<MediaPlayerBase> p = getPlayer();
1534 if (p == 0) return UNKNOWN_ERROR;
1535 return p->getParameter(key, reply);
1536}
1537
John Grossmanc795b642012-02-22 15:38:35 -08001538status_t MediaPlayerService::Client::setRetransmitEndpoint(
1539 const struct sockaddr_in* endpoint) {
1540
1541 if (NULL != endpoint) {
1542 uint32_t a = ntohl(endpoint->sin_addr.s_addr);
1543 uint16_t p = ntohs(endpoint->sin_port);
1544 ALOGV("[%d] setRetransmitEndpoint(%u.%u.%u.%u:%hu)", mConnId,
1545 (a >> 24), (a >> 16) & 0xFF, (a >> 8) & 0xFF, (a & 0xFF), p);
1546 } else {
1547 ALOGV("[%d] setRetransmitEndpoint = <none>", mConnId);
1548 }
1549
1550 sp<MediaPlayerBase> p = getPlayer();
1551
1552 // Right now, the only valid time to set a retransmit endpoint is before
1553 // player selection has been made (since the presence or absence of a
1554 // retransmit endpoint is going to determine which player is selected during
1555 // setDataSource).
1556 if (p != 0) return INVALID_OPERATION;
1557
1558 if (NULL != endpoint) {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001559 Mutex::Autolock lock(mLock);
John Grossmanc795b642012-02-22 15:38:35 -08001560 mRetransmitEndpoint = *endpoint;
1561 mRetransmitEndpointValid = true;
1562 } else {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001563 Mutex::Autolock lock(mLock);
John Grossmanc795b642012-02-22 15:38:35 -08001564 mRetransmitEndpointValid = false;
1565 }
1566
1567 return NO_ERROR;
1568}
1569
John Grossman44a7e422012-06-21 17:29:24 -07001570status_t MediaPlayerService::Client::getRetransmitEndpoint(
1571 struct sockaddr_in* endpoint)
1572{
1573 if (NULL == endpoint)
1574 return BAD_VALUE;
1575
1576 sp<MediaPlayerBase> p = getPlayer();
1577
1578 if (p != NULL)
1579 return p->getRetransmitEndpoint(endpoint);
1580
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001581 Mutex::Autolock lock(mLock);
John Grossman44a7e422012-06-21 17:29:24 -07001582 if (!mRetransmitEndpointValid)
1583 return NO_INIT;
1584
1585 *endpoint = mRetransmitEndpoint;
1586
1587 return NO_ERROR;
1588}
1589
Gloria Wangb483c472011-04-11 17:23:27 -07001590void MediaPlayerService::Client::notify(
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001591 int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001592{
James Dongb8a98252012-08-26 16:13:03 -07001593 sp<IMediaPlayerClient> c;
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001594 sp<Client> nextClient;
1595 status_t errStartNext = NO_ERROR;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001596 {
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001597 Mutex::Autolock l(mLock);
1598 c = mClient;
1599 if (msg == MEDIA_PLAYBACK_COMPLETE && mNextClient != NULL) {
1600 nextClient = mNextClient;
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001601
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001602 if (mAudioOutput != NULL)
1603 mAudioOutput->switchToNextOutput();
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001604
1605 errStartNext = nextClient->start();
1606 }
1607 }
1608
1609 if (nextClient != NULL) {
1610 sp<IMediaPlayerClient> nc;
1611 {
1612 Mutex::Autolock l(nextClient->mLock);
1613 nc = nextClient->mClient;
1614 }
1615 if (nc != NULL) {
1616 if (errStartNext == NO_ERROR) {
1617 nc->notify(MEDIA_INFO, MEDIA_INFO_STARTED_AS_NEXT, 0, obj);
1618 } else {
1619 nc->notify(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN , 0, obj);
1620 ALOGE("gapless:start playback for next track failed, err(%d)", errStartNext);
Wei Jia2afac0c2016-01-07 12:13:07 -08001621 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001622 }
1623 }
1624
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001625 if (MEDIA_INFO == msg &&
Nicolas Catania48290382009-07-10 13:53:06 -07001626 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikoa64c8c72009-07-20 15:07:26 -07001627 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania48290382009-07-10 13:53:06 -07001628
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001629 if(shouldDropMetadata(metadata_type)) {
Nicolas Catania48290382009-07-10 13:53:06 -07001630 return;
1631 }
1632
1633 // Update the list of metadata that have changed. getMetadata
1634 // also access mMetadataUpdated and clears it.
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001635 addNewMetadataUpdate(metadata_type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001636 }
James Dongb8a98252012-08-26 16:13:03 -07001637
1638 if (c != NULL) {
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001639 ALOGV("[%d] notify (%d, %d, %d)", mConnId, msg, ext1, ext2);
James Dongb8a98252012-08-26 16:13:03 -07001640 c->notify(msg, ext1, ext2, obj);
1641 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001642}
1643
Nicolas Catania48290382009-07-10 13:53:06 -07001644
nikoa64c8c72009-07-20 15:07:26 -07001645bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001646{
Nicolas Catania48290382009-07-10 13:53:06 -07001647 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001648
Nicolas Catania48290382009-07-10 13:53:06 -07001649 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001650 return true;
1651 }
1652
Nicolas Catania48290382009-07-10 13:53:06 -07001653 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001654 return false;
Nicolas Catania48290382009-07-10 13:53:06 -07001655 } else {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001656 return true;
1657 }
1658}
1659
Nicolas Catania48290382009-07-10 13:53:06 -07001660
nikoa64c8c72009-07-20 15:07:26 -07001661void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania48290382009-07-10 13:53:06 -07001662 Mutex::Autolock lock(mLock);
1663 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1664 mMetadataUpdated.add(metadata_type);
1665 }
1666}
1667
Hassan Shojaniacefac142017-02-06 21:02:02 -08001668// Modular DRM
1669status_t MediaPlayerService::Client::prepareDrm(const uint8_t uuid[16],
1670 const Vector<uint8_t>& drmSessionId)
1671{
1672 ALOGV("[%d] prepareDrm", mConnId);
1673 sp<MediaPlayerBase> p = getPlayer();
1674 if (p == 0) return UNKNOWN_ERROR;
1675
1676 status_t ret = p->prepareDrm(uuid, drmSessionId);
1677 ALOGV("prepareDrm ret: %d", ret);
1678
1679 return ret;
1680}
1681
1682status_t MediaPlayerService::Client::releaseDrm()
1683{
1684 ALOGV("[%d] releaseDrm", mConnId);
1685 sp<MediaPlayerBase> p = getPlayer();
1686 if (p == 0) return UNKNOWN_ERROR;
1687
1688 status_t ret = p->releaseDrm();
1689 ALOGV("releaseDrm ret: %d", ret);
1690
1691 return ret;
1692}
1693
jiabin156c6872017-10-06 09:47:15 -07001694status_t MediaPlayerService::Client::setOutputDevice(audio_port_handle_t deviceId)
1695{
1696 ALOGV("[%d] setOutputDevice", mConnId);
1697 {
1698 Mutex::Autolock l(mLock);
1699 if (mAudioOutput.get() != nullptr) {
1700 return mAudioOutput->setOutputDevice(deviceId);
1701 }
1702 }
1703 return NO_INIT;
1704}
1705
1706status_t MediaPlayerService::Client::getRoutedDeviceId(audio_port_handle_t* deviceId)
1707{
1708 ALOGV("[%d] getRoutedDeviceId", mConnId);
1709 {
1710 Mutex::Autolock l(mLock);
1711 if (mAudioOutput.get() != nullptr) {
1712 return mAudioOutput->getRoutedDeviceId(deviceId);
1713 }
1714 }
1715 return NO_INIT;
1716}
1717
1718status_t MediaPlayerService::Client::enableAudioDeviceCallback(bool enabled)
1719{
1720 ALOGV("[%d] enableAudioDeviceCallback, %d", mConnId, enabled);
1721 {
1722 Mutex::Autolock l(mLock);
1723 if (mAudioOutput.get() != nullptr) {
1724 return mAudioOutput->enableAudioDeviceCallback(enabled);
1725 }
1726 }
1727 return NO_INIT;
1728}
1729
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001730#if CALLBACK_ANTAGONIZER
1731const int Antagonizer::interval = 10000; // 10 msecs
1732
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001733Antagonizer::Antagonizer(const sp<MediaPlayerBase::Listener> &listener) :
1734 mExit(false), mActive(false), mListener(listener)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001735{
1736 createThread(callbackThread, this);
1737}
1738
1739void Antagonizer::kill()
1740{
1741 Mutex::Autolock _l(mLock);
1742 mActive = false;
1743 mExit = true;
1744 mCondition.wait(mLock);
1745}
1746
1747int Antagonizer::callbackThread(void* user)
1748{
Steve Blockb8a80522011-12-20 16:23:08 +00001749 ALOGD("Antagonizer started");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001750 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1751 while (!p->mExit) {
1752 if (p->mActive) {
Steve Block3856b092011-10-20 11:56:00 +01001753 ALOGV("send event");
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001754 p->mListener->notify(0, 0, 0, 0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001755 }
1756 usleep(interval);
1757 }
1758 Mutex::Autolock _l(p->mLock);
1759 p->mCondition.signal();
Steve Blockb8a80522011-12-20 16:23:08 +00001760 ALOGD("Antagonizer stopped");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001761 return 0;
1762}
1763#endif
1764
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001765#undef LOG_TAG
1766#define LOG_TAG "AudioSink"
Andy Hung1afd0982016-11-08 16:13:44 -08001767MediaPlayerService::AudioOutput::AudioOutput(audio_session_t sessionId, uid_t uid, int pid,
jiabin156c6872017-10-06 09:47:15 -07001768 const audio_attributes_t* attr, const sp<AudioSystem::AudioDeviceCallback>& deviceCallback)
Andreas Huber20111aa2009-07-14 16:56:47 -07001769 : mCallback(NULL),
Eric Laurenta514bdb2010-06-21 09:27:30 -07001770 mCallbackCookie(NULL),
Marco Nelissen6b74d672012-02-28 16:07:44 -08001771 mCallbackData(NULL),
Andy Hungd1c74342015-07-07 16:54:23 -07001772 mStreamType(AUDIO_STREAM_MUSIC),
Andy Hungd1c74342015-07-07 16:54:23 -07001773 mLeftVolume(1.0),
1774 mRightVolume(1.0),
1775 mPlaybackRate(AUDIO_PLAYBACK_RATE_DEFAULT),
1776 mSampleRateHz(0),
1777 mMsecsPerFrame(0),
1778 mFrameSize(0),
Eric Laurent1948eb32012-04-13 16:50:19 -07001779 mSessionId(sessionId),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001780 mUid(uid),
Marco Nelissend457c972014-02-11 08:47:07 -08001781 mPid(pid),
Andy Hungd1c74342015-07-07 16:54:23 -07001782 mSendLevel(0.0),
1783 mAuxEffectId(0),
Andy Hung4ef88d72017-02-21 19:47:53 -08001784 mFlags(AUDIO_OUTPUT_FLAG_NONE),
jiabin156c6872017-10-06 09:47:15 -07001785 mVolumeHandler(new media::VolumeHandler()),
1786 mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE),
jiabin161b64fc2017-11-17 09:31:48 -08001787 mRoutedDeviceId(AUDIO_PORT_HANDLE_NONE),
jiabin156c6872017-10-06 09:47:15 -07001788 mDeviceCallbackEnabled(false),
1789 mDeviceCallback(deviceCallback)
Andy Hungd1c74342015-07-07 16:54:23 -07001790{
Steve Block3856b092011-10-20 11:56:00 +01001791 ALOGV("AudioOutput(%d)", sessionId);
Eric Laurent43562692015-07-15 16:49:07 -07001792 if (attr != NULL) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001793 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1794 if (mAttributes != NULL) {
1795 memcpy(mAttributes, attr, sizeof(audio_attributes_t));
François Gaffie58d4be52018-11-06 15:30:12 +01001796 mStreamType = AudioSystem::attributesToStreamType(*attr);
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001797 }
1798 } else {
1799 mAttributes = NULL;
Eric Laurent43562692015-07-15 16:49:07 -07001800 }
1801
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001802 setMinBufferCount();
1803}
1804
1805MediaPlayerService::AudioOutput::~AudioOutput()
1806{
1807 close();
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001808 free(mAttributes);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001809 delete mCallbackData;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001810}
1811
Andy Hungd1c74342015-07-07 16:54:23 -07001812//static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001813void MediaPlayerService::AudioOutput::setMinBufferCount()
1814{
1815 char value[PROPERTY_VALUE_MAX];
1816 if (property_get("ro.kernel.qemu", value, 0)) {
1817 mIsOnEmulator = true;
1818 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1819 }
1820}
1821
Andy Hungd1c74342015-07-07 16:54:23 -07001822// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001823bool MediaPlayerService::AudioOutput::isOnEmulator()
1824{
Andy Hungd1c74342015-07-07 16:54:23 -07001825 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001826 return mIsOnEmulator;
1827}
1828
Andy Hungd1c74342015-07-07 16:54:23 -07001829// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001830int MediaPlayerService::AudioOutput::getMinBufferCount()
1831{
Andy Hungd1c74342015-07-07 16:54:23 -07001832 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001833 return mMinBufferCount;
1834}
1835
1836ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1837{
Andy Hungd1c74342015-07-07 16:54:23 -07001838 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001839 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001840 return mTrack->frameCount() * mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001841}
1842
1843ssize_t MediaPlayerService::AudioOutput::frameCount() const
1844{
Andy Hungd1c74342015-07-07 16:54:23 -07001845 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001846 if (mTrack == 0) return NO_INIT;
1847 return mTrack->frameCount();
1848}
1849
1850ssize_t MediaPlayerService::AudioOutput::channelCount() const
1851{
Andy Hungd1c74342015-07-07 16:54:23 -07001852 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001853 if (mTrack == 0) return NO_INIT;
1854 return mTrack->channelCount();
1855}
1856
1857ssize_t MediaPlayerService::AudioOutput::frameSize() const
1858{
Andy Hungd1c74342015-07-07 16:54:23 -07001859 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001860 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001861 return mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001862}
1863
1864uint32_t MediaPlayerService::AudioOutput::latency () const
1865{
Andy Hungd1c74342015-07-07 16:54:23 -07001866 Mutex::Autolock lock(mLock);
Eric Laurentdb354e52012-03-05 17:27:11 -08001867 if (mTrack == 0) return 0;
1868 return mTrack->latency();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001869}
1870
1871float MediaPlayerService::AudioOutput::msecsPerFrame() const
1872{
Andy Hungd1c74342015-07-07 16:54:23 -07001873 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001874 return mMsecsPerFrame;
1875}
1876
Marco Nelissen4110c102012-03-29 09:31:28 -07001877status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position) const
Eric Laurent342e9cf2010-01-19 17:37:09 -08001878{
Andy Hungd1c74342015-07-07 16:54:23 -07001879 Mutex::Autolock lock(mLock);
Eric Laurent342e9cf2010-01-19 17:37:09 -08001880 if (mTrack == 0) return NO_INIT;
1881 return mTrack->getPosition(position);
1882}
1883
Lajos Molnar06ad1522014-08-28 07:27:44 -07001884status_t MediaPlayerService::AudioOutput::getTimestamp(AudioTimestamp &ts) const
1885{
Andy Hungd1c74342015-07-07 16:54:23 -07001886 Mutex::Autolock lock(mLock);
Lajos Molnar06ad1522014-08-28 07:27:44 -07001887 if (mTrack == 0) return NO_INIT;
1888 return mTrack->getTimestamp(ts);
1889}
1890
Wei Jiac4ac8172015-10-21 10:35:48 -07001891// TODO: Remove unnecessary calls to getPlayedOutDurationUs()
1892// as it acquires locks and may query the audio driver.
1893//
1894// Some calls could conceivably retrieve extrapolated data instead of
1895// accessing getTimestamp() or getPosition() every time a data buffer with
1896// a media time is received.
1897//
1898// Calculate duration of played samples if played at normal rate (i.e., 1.0).
1899int64_t MediaPlayerService::AudioOutput::getPlayedOutDurationUs(int64_t nowUs) const
1900{
1901 Mutex::Autolock lock(mLock);
1902 if (mTrack == 0 || mSampleRateHz == 0) {
Wei Jia213f4902015-10-22 08:55:25 -07001903 return 0;
Wei Jiac4ac8172015-10-21 10:35:48 -07001904 }
1905
1906 uint32_t numFramesPlayed;
Andy Hung5d313802016-10-10 15:09:39 -07001907 int64_t numFramesPlayedAtUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001908 AudioTimestamp ts;
Wei Jiac4ac8172015-10-21 10:35:48 -07001909
1910 status_t res = mTrack->getTimestamp(ts);
1911 if (res == OK) { // case 1: mixing audio tracks and offloaded tracks.
1912 numFramesPlayed = ts.mPosition;
Andy Hung5d313802016-10-10 15:09:39 -07001913 numFramesPlayedAtUs = ts.mTime.tv_sec * 1000000LL + ts.mTime.tv_nsec / 1000;
1914 //ALOGD("getTimestamp: OK %d %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001915 } else if (res == WOULD_BLOCK) { // case 2: transitory state on start of a new track
1916 numFramesPlayed = 0;
Andy Hung5d313802016-10-10 15:09:39 -07001917 numFramesPlayedAtUs = nowUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001918 //ALOGD("getTimestamp: WOULD_BLOCK %d %lld",
Andy Hung5d313802016-10-10 15:09:39 -07001919 // numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001920 } else { // case 3: transitory at new track or audio fast tracks.
1921 res = mTrack->getPosition(&numFramesPlayed);
1922 CHECK_EQ(res, (status_t)OK);
Andy Hung5d313802016-10-10 15:09:39 -07001923 numFramesPlayedAtUs = nowUs;
1924 numFramesPlayedAtUs += 1000LL * mTrack->latency() / 2; /* XXX */
1925 //ALOGD("getPosition: %u %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001926 }
1927
1928 // CHECK_EQ(numFramesPlayed & (1 << 31), 0); // can't be negative until 12.4 hrs, test
1929 // TODO: remove the (int32_t) casting below as it may overflow at 12.4 hours.
1930 int64_t durationUs = (int64_t)((int32_t)numFramesPlayed * 1000000LL / mSampleRateHz)
Andy Hung5d313802016-10-10 15:09:39 -07001931 + nowUs - numFramesPlayedAtUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001932 if (durationUs < 0) {
1933 // Occurs when numFramesPlayed position is very small and the following:
1934 // (1) In case 1, the time nowUs is computed before getTimestamp() is called and
Andy Hung5d313802016-10-10 15:09:39 -07001935 // numFramesPlayedAtUs is greater than nowUs by time more than numFramesPlayed.
Wei Jiac4ac8172015-10-21 10:35:48 -07001936 // (2) In case 3, using getPosition and adding mAudioSink->latency() to
Andy Hung5d313802016-10-10 15:09:39 -07001937 // numFramesPlayedAtUs, by a time amount greater than numFramesPlayed.
Wei Jiac4ac8172015-10-21 10:35:48 -07001938 //
1939 // Both of these are transitory conditions.
1940 ALOGV("getPlayedOutDurationUs: negative duration %lld set to zero", (long long)durationUs);
1941 durationUs = 0;
1942 }
1943 ALOGV("getPlayedOutDurationUs(%lld) nowUs(%lld) frames(%u) framesAt(%lld)",
Andy Hung5d313802016-10-10 15:09:39 -07001944 (long long)durationUs, (long long)nowUs,
1945 numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001946 return durationUs;
1947}
1948
Marco Nelissen4110c102012-03-29 09:31:28 -07001949status_t MediaPlayerService::AudioOutput::getFramesWritten(uint32_t *frameswritten) const
1950{
Andy Hungd1c74342015-07-07 16:54:23 -07001951 Mutex::Autolock lock(mLock);
Marco Nelissen4110c102012-03-29 09:31:28 -07001952 if (mTrack == 0) return NO_INIT;
Andy Hung2f6e73d2016-04-08 12:12:58 -07001953 ExtendedTimestamp ets;
1954 status_t status = mTrack->getTimestamp(&ets);
1955 if (status == OK || status == WOULD_BLOCK) {
1956 *frameswritten = (uint32_t)ets.mPosition[ExtendedTimestamp::LOCATION_CLIENT];
1957 }
1958 return status;
Marco Nelissen4110c102012-03-29 09:31:28 -07001959}
1960
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001961status_t MediaPlayerService::AudioOutput::setParameters(const String8& keyValuePairs)
1962{
Andy Hungd1c74342015-07-07 16:54:23 -07001963 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001964 if (mTrack == 0) return NO_INIT;
1965 return mTrack->setParameters(keyValuePairs);
1966}
1967
1968String8 MediaPlayerService::AudioOutput::getParameters(const String8& keys)
1969{
Andy Hungd1c74342015-07-07 16:54:23 -07001970 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001971 if (mTrack == 0) return String8::empty();
1972 return mTrack->getParameters(keys);
1973}
1974
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001975void MediaPlayerService::AudioOutput::setAudioAttributes(const audio_attributes_t * attributes) {
Andy Hungd1c74342015-07-07 16:54:23 -07001976 Mutex::Autolock lock(mLock);
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001977 if (attributes == NULL) {
1978 free(mAttributes);
1979 mAttributes = NULL;
1980 } else {
1981 if (mAttributes == NULL) {
1982 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1983 }
1984 memcpy(mAttributes, attributes, sizeof(audio_attributes_t));
François Gaffie58d4be52018-11-06 15:30:12 +01001985 mStreamType = AudioSystem::attributesToStreamType(*attributes);
Eric Laurent43562692015-07-15 16:49:07 -07001986 }
1987}
1988
1989void MediaPlayerService::AudioOutput::setAudioStreamType(audio_stream_type_t streamType)
1990{
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001991 Mutex::Autolock lock(mLock);
Eric Laurent43562692015-07-15 16:49:07 -07001992 // do not allow direct stream type modification if attributes have been set
1993 if (mAttributes == NULL) {
1994 mStreamType = streamType;
1995 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001996}
1997
Andy Hungd1c74342015-07-07 16:54:23 -07001998void MediaPlayerService::AudioOutput::deleteRecycledTrack_l()
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001999{
Andy Hungd1c74342015-07-07 16:54:23 -07002000 ALOGV("deleteRecycledTrack_l");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002001 if (mRecycledTrack != 0) {
2002
2003 if (mCallbackData != NULL) {
2004 mCallbackData->setOutput(NULL);
2005 mCallbackData->endTrackSwitch();
2006 }
2007
2008 if ((mRecycledTrack->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) {
Andy Hunge13f8a62016-03-30 14:20:42 -07002009 int32_t msec = 0;
2010 if (!mRecycledTrack->stopped()) { // check if active
2011 (void)mRecycledTrack->pendingDuration(&msec);
2012 }
2013 mRecycledTrack->stop(); // ensure full data drain
2014 ALOGD("deleting recycled track, waiting for data drain (%d msec)", msec);
2015 if (msec > 0) {
2016 static const int32_t WAIT_LIMIT_MS = 3000;
2017 if (msec > WAIT_LIMIT_MS) {
2018 msec = WAIT_LIMIT_MS;
2019 }
2020 usleep(msec * 1000LL);
2021 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002022 }
2023 // An offloaded track isn't flushed because the STREAM_END is reported
2024 // slightly prematurely to allow time for the gapless track switch
2025 // but this means that if we decide not to recycle the track there
2026 // could be a small amount of residual data still playing. We leave
2027 // AudioFlinger to drain the track.
2028
2029 mRecycledTrack.clear();
Andy Hungd1c74342015-07-07 16:54:23 -07002030 close_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002031 delete mCallbackData;
2032 mCallbackData = NULL;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002033 }
2034}
2035
Andy Hungd1c74342015-07-07 16:54:23 -07002036void MediaPlayerService::AudioOutput::close_l()
2037{
2038 mTrack.clear();
2039}
2040
Andreas Huber20111aa2009-07-14 16:56:47 -07002041status_t MediaPlayerService::AudioOutput::open(
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08002042 uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
2043 audio_format_t format, int bufferCount,
Eric Laurent1948eb32012-04-13 16:50:19 -07002044 AudioCallback cb, void *cookie,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002045 audio_output_flags_t flags,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07002046 const audio_offload_info_t *offloadInfo,
Andy Hung179652e2015-05-31 22:49:46 -07002047 bool doNotReconnect,
2048 uint32_t suggestedFrameCount)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002049{
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002050 ALOGV("open(%u, %d, 0x%x, 0x%x, %d, %d 0x%x)", sampleRate, channelCount, channelMask,
2051 format, bufferCount, mSessionId, flags);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002052
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002053 // offloading is only supported in callback mode for now.
2054 // offloadInfo must be present if offload flag is set
2055 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) &&
2056 ((cb == NULL) || (offloadInfo == NULL))) {
2057 return BAD_VALUE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002058 }
2059
Andy Hung179652e2015-05-31 22:49:46 -07002060 // compute frame count for the AudioTrack internal buffer
2061 size_t frameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002062 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
2063 frameCount = 0; // AudioTrack will get frame count from AudioFlinger
2064 } else {
Andy Hung179652e2015-05-31 22:49:46 -07002065 // try to estimate the buffer processing fetch size from AudioFlinger.
2066 // framesPerBuffer is approximate and generally correct, except when it's not :-).
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002067 uint32_t afSampleRate;
2068 size_t afFrameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002069 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
2070 return NO_INIT;
2071 }
2072 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
2073 return NO_INIT;
2074 }
Ben Romberger259fb462018-08-07 17:58:53 -07002075 if (afSampleRate == 0) {
2076 return NO_INIT;
2077 }
Andy Hung179652e2015-05-31 22:49:46 -07002078 const size_t framesPerBuffer =
2079 (unsigned long long)sampleRate * afFrameCount / afSampleRate;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002080
Andy Hung179652e2015-05-31 22:49:46 -07002081 if (bufferCount == 0) {
Ben Romberger259fb462018-08-07 17:58:53 -07002082 if (framesPerBuffer == 0) {
2083 return NO_INIT;
2084 }
Andy Hung179652e2015-05-31 22:49:46 -07002085 // use suggestedFrameCount
2086 bufferCount = (suggestedFrameCount + framesPerBuffer - 1) / framesPerBuffer;
2087 }
2088 // Check argument bufferCount against the mininum buffer count
2089 if (bufferCount != 0 && bufferCount < mMinBufferCount) {
2090 ALOGV("bufferCount (%d) increased to %d", bufferCount, mMinBufferCount);
2091 bufferCount = mMinBufferCount;
2092 }
2093 // if frameCount is 0, then AudioTrack will get frame count from AudioFlinger
2094 // which will be the minimum size permitted.
2095 frameCount = bufferCount * framesPerBuffer;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002096 }
Andreas Huber20111aa2009-07-14 16:56:47 -07002097
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08002098 if (channelMask == CHANNEL_MASK_USE_CHANNEL_ORDER) {
Glenn Kastenab334fd2012-03-14 12:56:06 -07002099 channelMask = audio_channel_out_mask_from_count(channelCount);
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08002100 if (0 == channelMask) {
2101 ALOGE("open() error, can\'t derive mask for %d audio channels", channelCount);
2102 return NO_INIT;
2103 }
2104 }
Eric Laurent1948eb32012-04-13 16:50:19 -07002105
Andy Hungd1c74342015-07-07 16:54:23 -07002106 Mutex::Autolock lock(mLock);
Andy Hung179652e2015-05-31 22:49:46 -07002107 mCallback = cb;
2108 mCallbackCookie = cookie;
2109
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002110 // Check whether we can recycle the track
2111 bool reuse = false;
2112 bool bothOffloaded = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07002113
Glenn Kasten2799d742013-05-30 14:33:29 -07002114 if (mRecycledTrack != 0) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002115 // check whether we are switching between two offloaded tracks
2116 bothOffloaded = (flags & mRecycledTrack->getFlags()
2117 & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0;
Marco Nelissen67295b52012-06-11 14:52:53 -07002118
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002119 // check if the existing track can be reused as-is, or if a new track needs to be created.
2120 reuse = true;
2121
Marco Nelissen67295b52012-06-11 14:52:53 -07002122 if ((mCallbackData == NULL && mCallback != NULL) ||
2123 (mCallbackData != NULL && mCallback == NULL)) {
2124 // recycled track uses callbacks but the caller wants to use writes, or vice versa
2125 ALOGV("can't chain callback and write");
2126 reuse = false;
2127 } else if ((mRecycledTrack->getSampleRate() != sampleRate) ||
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002128 (mRecycledTrack->channelCount() != (uint32_t)channelCount) ) {
2129 ALOGV("samplerate, channelcount differ: %u/%u Hz, %u/%d ch",
Marco Nelissen67295b52012-06-11 14:52:53 -07002130 mRecycledTrack->getSampleRate(), sampleRate,
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002131 mRecycledTrack->channelCount(), channelCount);
Marco Nelissen67295b52012-06-11 14:52:53 -07002132 reuse = false;
2133 } else if (flags != mFlags) {
2134 ALOGV("output flags differ %08x/%08x", flags, mFlags);
2135 reuse = false;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002136 } else if (mRecycledTrack->format() != format) {
2137 reuse = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07002138 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002139 } else {
2140 ALOGV("no track available to recycle");
2141 }
2142
2143 ALOGV_IF(bothOffloaded, "both tracks offloaded");
2144
2145 // If we can't recycle and both tracks are offloaded
2146 // we must close the previous output before opening a new one
2147 if (bothOffloaded && !reuse) {
2148 ALOGV("both offloaded and not recycling");
Andy Hungd1c74342015-07-07 16:54:23 -07002149 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002150 }
2151
2152 sp<AudioTrack> t;
2153 CallbackData *newcbd = NULL;
2154
2155 // We don't attempt to create a new track if we are recycling an
2156 // offloaded track. But, if we are recycling a non-offloaded or we
2157 // are switching where one is offloaded and one isn't then we create
2158 // the new track in advance so that we can read additional stream info
2159
2160 if (!(reuse && bothOffloaded)) {
2161 ALOGV("creating new AudioTrack");
2162
2163 if (mCallback != NULL) {
2164 newcbd = new CallbackData(this);
2165 t = new AudioTrack(
2166 mStreamType,
2167 sampleRate,
2168 format,
2169 channelMask,
2170 frameCount,
2171 flags,
2172 CallbackWrapper,
2173 newcbd,
2174 0, // notification frames
2175 mSessionId,
2176 AudioTrack::TRANSFER_CALLBACK,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002177 offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -08002178 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07002179 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07002180 mAttributes,
jiabin156c6872017-10-06 09:47:15 -07002181 doNotReconnect,
2182 1.0f, // default value for maxRequiredSpeed
2183 mSelectedDeviceId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002184 } else {
Andy Hungff874dc2016-04-11 16:49:09 -07002185 // TODO: Due to buffer memory concerns, we use a max target playback speed
2186 // based on mPlaybackRate at the time of open (instead of kMaxRequiredSpeed),
2187 // also clamping the target speed to 1.0 <= targetSpeed <= kMaxRequiredSpeed.
2188 const float targetSpeed =
2189 std::min(std::max(mPlaybackRate.mSpeed, 1.0f), kMaxRequiredSpeed);
2190 ALOGW_IF(targetSpeed != mPlaybackRate.mSpeed,
2191 "track target speed:%f clamped from playback speed:%f",
2192 targetSpeed, mPlaybackRate.mSpeed);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002193 t = new AudioTrack(
2194 mStreamType,
2195 sampleRate,
2196 format,
2197 channelMask,
2198 frameCount,
2199 flags,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002200 NULL, // callback
2201 NULL, // user data
2202 0, // notification frames
2203 mSessionId,
2204 AudioTrack::TRANSFER_DEFAULT,
2205 NULL, // offload info
Marco Nelissend457c972014-02-11 08:47:07 -08002206 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07002207 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07002208 mAttributes,
Andy Hungff874dc2016-04-11 16:49:09 -07002209 doNotReconnect,
jiabin156c6872017-10-06 09:47:15 -07002210 targetSpeed,
2211 mSelectedDeviceId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002212 }
2213
2214 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
2215 ALOGE("Unable to create audio track");
2216 delete newcbd;
Glenn Kasten3e98ecd2015-05-18 13:13:24 -07002217 // t goes out of scope, so reference count drops to zero
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002218 return NO_INIT;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07002219 } else {
2220 // successful AudioTrack initialization implies a legacy stream type was generated
2221 // from the audio attributes
2222 mStreamType = t->streamType();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002223 }
2224 }
2225
2226 if (reuse) {
2227 CHECK(mRecycledTrack != NULL);
2228
2229 if (!bothOffloaded) {
2230 if (mRecycledTrack->frameCount() != t->frameCount()) {
Andy Hung833b4752016-04-04 17:15:48 -07002231 ALOGV("framecount differs: %zu/%zu frames",
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002232 mRecycledTrack->frameCount(), t->frameCount());
2233 reuse = false;
2234 }
2235 }
2236
Marco Nelissen67295b52012-06-11 14:52:53 -07002237 if (reuse) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002238 ALOGV("chaining to next output and recycling track");
Andy Hungd1c74342015-07-07 16:54:23 -07002239 close_l();
Marco Nelissen67295b52012-06-11 14:52:53 -07002240 mTrack = mRecycledTrack;
Glenn Kasten2799d742013-05-30 14:33:29 -07002241 mRecycledTrack.clear();
Marco Nelissen67295b52012-06-11 14:52:53 -07002242 if (mCallbackData != NULL) {
2243 mCallbackData->setOutput(this);
2244 }
Marco Nelissen67295b52012-06-11 14:52:53 -07002245 delete newcbd;
Wei Jiae0bbac92016-07-18 16:04:53 -07002246 return updateTrack();
Marco Nelissen67295b52012-06-11 14:52:53 -07002247 }
Marco Nelissen67295b52012-06-11 14:52:53 -07002248 }
2249
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002250 // we're not going to reuse the track, unblock and flush it
2251 // this was done earlier if both tracks are offloaded
2252 if (!bothOffloaded) {
Andy Hungd1c74342015-07-07 16:54:23 -07002253 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002254 }
2255
2256 CHECK((t != NULL) && ((mCallback == NULL) || (newcbd != NULL)));
2257
Marco Nelissen67295b52012-06-11 14:52:53 -07002258 mCallbackData = newcbd;
Steve Block3856b092011-10-20 11:56:00 +01002259 ALOGV("setVolume");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002260 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07002261
Andy Hung39399b62017-04-21 15:07:45 -07002262 // Restore VolumeShapers for the MediaPlayer in case the track was recreated
2263 // due to an output sink error (e.g. offload to non-offload switch).
2264 mVolumeHandler->forall([&t](const VolumeShaper &shaper) -> VolumeShaper::Status {
2265 sp<VolumeShaper::Operation> operationToEnd =
2266 new VolumeShaper::Operation(shaper.mOperation);
2267 // TODO: Ideally we would restore to the exact xOffset position
2268 // as returned by getVolumeShaperState(), but we don't have that
2269 // information when restoring at the client unless we periodically poll
2270 // the server or create shared memory state.
2271 //
2272 // For now, we simply advance to the end of the VolumeShaper effect
2273 // if it has been started.
2274 if (shaper.isStarted()) {
Andy Hungf3702642017-05-05 17:33:32 -07002275 operationToEnd->setNormalizedTime(1.f);
Andy Hung39399b62017-04-21 15:07:45 -07002276 }
2277 return t->applyVolumeShaper(shaper.mConfiguration, operationToEnd);
Andy Hung4ef88d72017-02-21 19:47:53 -08002278 });
Andy Hung4ef88d72017-02-21 19:47:53 -08002279
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002280 mSampleRateHz = sampleRate;
Preetam Singh Ranawat2e17eef2015-08-12 12:11:46 -07002281 mFlags = flags;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002282 mMsecsPerFrame = 1E3f / (mPlaybackRate.mSpeed * sampleRate);
Andy Hungd1c74342015-07-07 16:54:23 -07002283 mFrameSize = t->frameSize();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002284 mTrack = t;
Eric Laurent2beeb502010-07-16 07:43:46 -07002285
Wei Jiae0bbac92016-07-18 16:04:53 -07002286 return updateTrack();
2287}
2288
2289status_t MediaPlayerService::AudioOutput::updateTrack() {
2290 if (mTrack == NULL) {
2291 return NO_ERROR;
2292 }
2293
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002294 status_t res = NO_ERROR;
Wei Jia0162d002015-06-09 11:59:33 -07002295 // Note some output devices may give us a direct track even though we don't specify it.
2296 // Example: Line application b/17459982.
Wei Jiae0bbac92016-07-18 16:04:53 -07002297 if ((mTrack->getFlags()
2298 & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) {
2299 res = mTrack->setPlaybackRate(mPlaybackRate);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002300 if (res == NO_ERROR) {
Wei Jiae0bbac92016-07-18 16:04:53 -07002301 mTrack->setAuxEffectSendLevel(mSendLevel);
2302 res = mTrack->attachAuxEffect(mAuxEffectId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002303 }
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002304 }
jiabin156c6872017-10-06 09:47:15 -07002305 mTrack->setOutputDevice(mSelectedDeviceId);
2306 if (mDeviceCallbackEnabled) {
2307 mTrack->addAudioDeviceCallback(mDeviceCallback.promote());
2308 }
Wei Jiae0bbac92016-07-18 16:04:53 -07002309 ALOGV("updateTrack() DONE status %d", res);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002310 return res;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002311}
2312
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002313status_t MediaPlayerService::AudioOutput::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002314{
Steve Block3856b092011-10-20 11:56:00 +01002315 ALOGV("start");
Andy Hungd1c74342015-07-07 16:54:23 -07002316 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08002317 if (mCallbackData != NULL) {
2318 mCallbackData->endTrackSwitch();
2319 }
Glenn Kasten2799d742013-05-30 14:33:29 -07002320 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002321 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07002322 mTrack->setAuxEffectSendLevel(mSendLevel);
Andy Hung39399b62017-04-21 15:07:45 -07002323 status_t status = mTrack->start();
2324 if (status == NO_ERROR) {
2325 mVolumeHandler->setStarted();
2326 }
2327 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002328 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002329 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002330}
2331
Marco Nelissen6b74d672012-02-28 16:07:44 -08002332void MediaPlayerService::AudioOutput::setNextOutput(const sp<AudioOutput>& nextOutput) {
Andy Hungd1c74342015-07-07 16:54:23 -07002333 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08002334 mNextOutput = nextOutput;
2335}
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08002336
Marco Nelissen6b74d672012-02-28 16:07:44 -08002337void MediaPlayerService::AudioOutput::switchToNextOutput() {
2338 ALOGV("switchToNextOutput");
Andy Hungd1c74342015-07-07 16:54:23 -07002339
2340 // Try to acquire the callback lock before moving track (without incurring deadlock).
2341 const unsigned kMaxSwitchTries = 100;
2342 Mutex::Autolock lock(mLock);
2343 for (unsigned tries = 0;;) {
2344 if (mTrack == 0) {
2345 return;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002346 }
Andy Hungd1c74342015-07-07 16:54:23 -07002347 if (mNextOutput != NULL && mNextOutput != this) {
2348 if (mCallbackData != NULL) {
2349 // two alternative approaches
2350#if 1
2351 CallbackData *callbackData = mCallbackData;
2352 mLock.unlock();
2353 // proper acquisition sequence
2354 callbackData->lock();
2355 mLock.lock();
2356 // Caution: it is unlikely that someone deleted our callback or changed our target
2357 if (callbackData != mCallbackData || mNextOutput == NULL || mNextOutput == this) {
2358 // fatal if we are starved out.
2359 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2360 "switchToNextOutput() cannot obtain correct lock sequence");
2361 callbackData->unlock();
2362 continue;
2363 }
2364 callbackData->mSwitching = true; // begin track switch
Wei Jiaadee56a2016-08-05 15:40:34 -07002365 callbackData->setOutput(NULL);
Andy Hungd1c74342015-07-07 16:54:23 -07002366#else
2367 // tryBeginTrackSwitch() returns false if the callback has the lock.
2368 if (!mCallbackData->tryBeginTrackSwitch()) {
2369 // fatal if we are starved out.
2370 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2371 "switchToNextOutput() cannot obtain callback lock");
2372 mLock.unlock();
2373 usleep(5 * 1000 /* usec */); // allow callback to use AudioOutput
2374 mLock.lock();
2375 continue;
2376 }
2377#endif
2378 }
2379
2380 Mutex::Autolock nextLock(mNextOutput->mLock);
2381
2382 // If the next output track is not NULL, then it has been
2383 // opened already for playback.
2384 // This is possible even without the next player being started,
2385 // for example, the next player could be prepared and seeked.
2386 //
2387 // Presuming it isn't advisable to force the track over.
2388 if (mNextOutput->mTrack == NULL) {
2389 ALOGD("Recycling track for gapless playback");
2390 delete mNextOutput->mCallbackData;
2391 mNextOutput->mCallbackData = mCallbackData;
2392 mNextOutput->mRecycledTrack = mTrack;
2393 mNextOutput->mSampleRateHz = mSampleRateHz;
2394 mNextOutput->mMsecsPerFrame = mMsecsPerFrame;
Andy Hungd1c74342015-07-07 16:54:23 -07002395 mNextOutput->mFlags = mFlags;
2396 mNextOutput->mFrameSize = mFrameSize;
2397 close_l();
2398 mCallbackData = NULL; // destruction handled by mNextOutput
2399 } else {
2400 ALOGW("Ignoring gapless playback because next player has already started");
2401 // remove track in case resource needed for future players.
2402 if (mCallbackData != NULL) {
2403 mCallbackData->endTrackSwitch(); // release lock for callbacks before close.
2404 }
2405 close_l();
2406 }
2407 }
2408 break;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002409 }
2410}
2411
Wei Jia7d3f4df2015-03-03 15:28:00 -08002412ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002413{
Andy Hungd1c74342015-07-07 16:54:23 -07002414 Mutex::Autolock lock(mLock);
Glenn Kastenadad3d72014-02-21 14:51:43 -08002415 LOG_ALWAYS_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
Andreas Huber20111aa2009-07-14 16:56:47 -07002416
Steve Block3856b092011-10-20 11:56:00 +01002417 //ALOGV("write(%p, %u)", buffer, size);
Glenn Kasten2799d742013-05-30 14:33:29 -07002418 if (mTrack != 0) {
Andy Hung2f6e73d2016-04-08 12:12:58 -07002419 return mTrack->write(buffer, size, blocking);
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07002420 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002421 return NO_INIT;
2422}
2423
2424void MediaPlayerService::AudioOutput::stop()
2425{
Steve Block3856b092011-10-20 11:56:00 +01002426 ALOGV("stop");
Andy Hungd1c74342015-07-07 16:54:23 -07002427 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002428 if (mTrack != 0) mTrack->stop();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002429}
2430
2431void MediaPlayerService::AudioOutput::flush()
2432{
Steve Block3856b092011-10-20 11:56:00 +01002433 ALOGV("flush");
Andy Hungd1c74342015-07-07 16:54:23 -07002434 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002435 if (mTrack != 0) mTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002436}
2437
2438void MediaPlayerService::AudioOutput::pause()
2439{
Steve Block3856b092011-10-20 11:56:00 +01002440 ALOGV("pause");
Andy Hungd1c74342015-07-07 16:54:23 -07002441 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002442 if (mTrack != 0) mTrack->pause();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002443}
2444
2445void MediaPlayerService::AudioOutput::close()
2446{
Steve Block3856b092011-10-20 11:56:00 +01002447 ALOGV("close");
Erik Wolsheimer7845a1f2015-10-30 12:07:52 -07002448 sp<AudioTrack> track;
2449 {
2450 Mutex::Autolock lock(mLock);
2451 track = mTrack;
2452 close_l(); // clears mTrack
2453 }
2454 // destruction of the track occurs outside of mutex.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002455}
2456
2457void MediaPlayerService::AudioOutput::setVolume(float left, float right)
2458{
Steve Block3856b092011-10-20 11:56:00 +01002459 ALOGV("setVolume(%f, %f)", left, right);
Andy Hungd1c74342015-07-07 16:54:23 -07002460 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002461 mLeftVolume = left;
2462 mRightVolume = right;
Glenn Kasten2799d742013-05-30 14:33:29 -07002463 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002464 mTrack->setVolume(left, right);
2465 }
2466}
2467
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002468status_t MediaPlayerService::AudioOutput::setPlaybackRate(const AudioPlaybackRate &rate)
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002469{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002470 ALOGV("setPlaybackRate(%f %f %d %d)",
2471 rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Andy Hungd1c74342015-07-07 16:54:23 -07002472 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002473 if (mTrack == 0) {
2474 // remember rate so that we can set it when the track is opened
2475 mPlaybackRate = rate;
2476 return OK;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002477 }
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002478 status_t res = mTrack->setPlaybackRate(rate);
2479 if (res != NO_ERROR) {
2480 return res;
2481 }
2482 // rate.mSpeed is always greater than 0 if setPlaybackRate succeeded
2483 CHECK_GT(rate.mSpeed, 0.f);
2484 mPlaybackRate = rate;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002485 if (mSampleRateHz != 0) {
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002486 mMsecsPerFrame = 1E3f / (rate.mSpeed * mSampleRateHz);
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002487 }
2488 return res;
2489}
2490
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002491status_t MediaPlayerService::AudioOutput::getPlaybackRate(AudioPlaybackRate *rate)
2492{
2493 ALOGV("setPlaybackRate");
Andy Hungd1c74342015-07-07 16:54:23 -07002494 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002495 if (mTrack == 0) {
2496 return NO_INIT;
2497 }
2498 *rate = mTrack->getPlaybackRate();
2499 return NO_ERROR;
2500}
2501
Eric Laurent2beeb502010-07-16 07:43:46 -07002502status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
2503{
Steve Block3856b092011-10-20 11:56:00 +01002504 ALOGV("setAuxEffectSendLevel(%f)", level);
Andy Hungd1c74342015-07-07 16:54:23 -07002505 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002506 mSendLevel = level;
Glenn Kasten2799d742013-05-30 14:33:29 -07002507 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002508 return mTrack->setAuxEffectSendLevel(level);
2509 }
2510 return NO_ERROR;
2511}
2512
2513status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
2514{
Steve Block3856b092011-10-20 11:56:00 +01002515 ALOGV("attachAuxEffect(%d)", effectId);
Andy Hungd1c74342015-07-07 16:54:23 -07002516 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002517 mAuxEffectId = effectId;
Glenn Kasten2799d742013-05-30 14:33:29 -07002518 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002519 return mTrack->attachAuxEffect(effectId);
2520 }
2521 return NO_ERROR;
2522}
2523
jiabin156c6872017-10-06 09:47:15 -07002524status_t MediaPlayerService::AudioOutput::setOutputDevice(audio_port_handle_t deviceId)
2525{
2526 ALOGV("setOutputDevice(%d)", deviceId);
2527 Mutex::Autolock lock(mLock);
2528 mSelectedDeviceId = deviceId;
2529 if (mTrack != 0) {
2530 return mTrack->setOutputDevice(deviceId);
2531 }
2532 return NO_ERROR;
2533}
2534
2535status_t MediaPlayerService::AudioOutput::getRoutedDeviceId(audio_port_handle_t* deviceId)
2536{
2537 ALOGV("getRoutedDeviceId");
2538 Mutex::Autolock lock(mLock);
2539 if (mTrack != 0) {
jiabin161b64fc2017-11-17 09:31:48 -08002540 mRoutedDeviceId = mTrack->getRoutedDeviceId();
jiabin156c6872017-10-06 09:47:15 -07002541 }
jiabin161b64fc2017-11-17 09:31:48 -08002542 *deviceId = mRoutedDeviceId;
2543 return NO_ERROR;
jiabin156c6872017-10-06 09:47:15 -07002544}
2545
2546status_t MediaPlayerService::AudioOutput::enableAudioDeviceCallback(bool enabled)
2547{
2548 ALOGV("enableAudioDeviceCallback, %d", enabled);
2549 Mutex::Autolock lock(mLock);
2550 mDeviceCallbackEnabled = enabled;
2551 if (mTrack != 0) {
2552 status_t status;
2553 if (enabled) {
2554 status = mTrack->addAudioDeviceCallback(mDeviceCallback.promote());
2555 } else {
2556 status = mTrack->removeAudioDeviceCallback(mDeviceCallback.promote());
2557 }
2558 return status;
2559 }
2560 return NO_ERROR;
2561}
2562
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002563VolumeShaper::Status MediaPlayerService::AudioOutput::applyVolumeShaper(
2564 const sp<VolumeShaper::Configuration>& configuration,
2565 const sp<VolumeShaper::Operation>& operation)
2566{
2567 Mutex::Autolock lock(mLock);
2568 ALOGV("AudioOutput::applyVolumeShaper");
Andy Hung4ef88d72017-02-21 19:47:53 -08002569
Andy Hung4ef88d72017-02-21 19:47:53 -08002570 mVolumeHandler->setIdIfNecessary(configuration);
Andy Hung39399b62017-04-21 15:07:45 -07002571
2572 VolumeShaper::Status status;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002573 if (mTrack != 0) {
Andy Hung39399b62017-04-21 15:07:45 -07002574 status = mTrack->applyVolumeShaper(configuration, operation);
2575 if (status >= 0) {
2576 (void)mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hungf3702642017-05-05 17:33:32 -07002577 if (mTrack->isPlaying()) { // match local AudioTrack to properly restore.
2578 mVolumeHandler->setStarted();
2579 }
Andy Hung39399b62017-04-21 15:07:45 -07002580 }
Andy Hung4ef88d72017-02-21 19:47:53 -08002581 } else {
Andy Hungc01eddb2017-07-21 16:42:41 -07002582 // VolumeShapers are not affected when a track moves between players for
2583 // gapless playback (setNextMediaPlayer).
2584 // We forward VolumeShaper operations that do not change configuration
2585 // to the new player so that unducking may occur as expected.
2586 // Unducking is an idempotent operation, same if applied back-to-back.
2587 if (configuration->getType() == VolumeShaper::Configuration::TYPE_ID
2588 && mNextOutput != nullptr) {
2589 ALOGV("applyVolumeShaper: Attempting to forward missed operation: %s %s",
2590 configuration->toString().c_str(), operation->toString().c_str());
2591 Mutex::Autolock nextLock(mNextOutput->mLock);
2592
2593 // recycled track should be forwarded from this AudioSink by switchToNextOutput
2594 sp<AudioTrack> track = mNextOutput->mRecycledTrack;
2595 if (track != nullptr) {
2596 ALOGD("Forward VolumeShaper operation to recycled track %p", track.get());
2597 (void)track->applyVolumeShaper(configuration, operation);
2598 } else {
2599 // There is a small chance that the unduck occurs after the next
2600 // player has already started, but before it is registered to receive
2601 // the unduck command.
2602 track = mNextOutput->mTrack;
2603 if (track != nullptr) {
2604 ALOGD("Forward VolumeShaper operation to track %p", track.get());
2605 (void)track->applyVolumeShaper(configuration, operation);
2606 }
2607 }
2608 }
Andy Hung39399b62017-04-21 15:07:45 -07002609 status = mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002610 }
Andy Hung39399b62017-04-21 15:07:45 -07002611 return status;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002612}
2613
2614sp<VolumeShaper::State> MediaPlayerService::AudioOutput::getVolumeShaperState(int id)
2615{
2616 Mutex::Autolock lock(mLock);
2617 if (mTrack != 0) {
2618 return mTrack->getVolumeShaperState(id);
Andy Hung4ef88d72017-02-21 19:47:53 -08002619 } else {
2620 return mVolumeHandler->getVolumeShaperState(id);
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002621 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002622}
2623
Andreas Huber20111aa2009-07-14 16:56:47 -07002624// static
2625void MediaPlayerService::AudioOutput::CallbackWrapper(
Glenn Kastend217a8c2011-06-01 15:20:35 -07002626 int event, void *cookie, void *info) {
Steve Block3856b092011-10-20 11:56:00 +01002627 //ALOGV("callbackwrapper");
Marco Nelissen6b74d672012-02-28 16:07:44 -08002628 CallbackData *data = (CallbackData*)cookie;
Andy Hungd1c74342015-07-07 16:54:23 -07002629 // lock to ensure we aren't caught in the middle of a track switch.
Marco Nelissen6b74d672012-02-28 16:07:44 -08002630 data->lock();
2631 AudioOutput *me = data->getOutput();
Andreas Huber20111aa2009-07-14 16:56:47 -07002632 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002633 if (me == NULL) {
2634 // no output set, likely because the track was scheduled to be reused
2635 // by another player, but the format turned out to be incompatible.
2636 data->unlock();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002637 if (buffer != NULL) {
2638 buffer->size = 0;
2639 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08002640 return;
2641 }
Andreas Huber20111aa2009-07-14 16:56:47 -07002642
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002643 switch(event) {
2644 case AudioTrack::EVENT_MORE_DATA: {
2645 size_t actualSize = (*me->mCallback)(
2646 me, buffer->raw, buffer->size, me->mCallbackCookie,
2647 CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002648
Andy Hung719b46b2015-05-31 22:18:25 -07002649 // Log when no data is returned from the callback.
2650 // (1) We may have no data (especially with network streaming sources).
2651 // (2) We may have reached the EOS and the audio track is not stopped yet.
2652 // Note that AwesomePlayer/AudioPlayer will only return zero size when it reaches the EOS.
2653 // NuPlayerRenderer will return zero when it doesn't have data (it doesn't block to fill).
2654 //
2655 // This is a benign busy-wait, with the next data request generated 10 ms or more later;
2656 // nevertheless for power reasons, we don't want to see too many of these.
Andreas Huber2e8ffaf2010-02-18 16:45:13 -08002657
Andy Hung719b46b2015-05-31 22:18:25 -07002658 ALOGV_IF(actualSize == 0 && buffer->size > 0, "callbackwrapper: empty buffer returned");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002659
2660 buffer->size = actualSize;
2661 } break;
2662
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002663 case AudioTrack::EVENT_STREAM_END:
Andy Hung719b46b2015-05-31 22:18:25 -07002664 // currently only occurs for offloaded callbacks
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002665 ALOGV("callbackwrapper: deliver EVENT_STREAM_END");
2666 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2667 me->mCallbackCookie, CB_EVENT_STREAM_END);
2668 break;
2669
2670 case AudioTrack::EVENT_NEW_IAUDIOTRACK :
2671 ALOGV("callbackwrapper: deliver EVENT_TEAR_DOWN");
2672 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2673 me->mCallbackCookie, CB_EVENT_TEAR_DOWN);
2674 break;
2675
Glenn Kasten421743b2015-06-01 08:18:08 -07002676 case AudioTrack::EVENT_UNDERRUN:
Andy Hung719b46b2015-05-31 22:18:25 -07002677 // This occurs when there is no data available, typically
Glenn Kasten421743b2015-06-01 08:18:08 -07002678 // when there is a failure to supply data to the AudioTrack. It can also
2679 // occur in non-offloaded mode when the audio device comes out of standby.
2680 //
Andy Hung719b46b2015-05-31 22:18:25 -07002681 // If an AudioTrack underruns it outputs silence. Since this happens suddenly
2682 // it may sound like an audible pop or glitch.
2683 //
2684 // The underrun event is sent once per track underrun; the condition is reset
2685 // when more data is sent to the AudioTrack.
Eric Laurente93cc032016-05-05 10:15:10 -07002686 ALOGD("callbackwrapper: EVENT_UNDERRUN (discarded)");
Glenn Kasten421743b2015-06-01 08:18:08 -07002687 break;
2688
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002689 default:
2690 ALOGE("received unknown event type: %d inside CallbackWrapper !", event);
Andreas Huber51c1e0e2011-04-04 11:43:40 -07002691 }
2692
Marco Nelissen6b74d672012-02-28 16:07:44 -08002693 data->unlock();
Andreas Huber20111aa2009-07-14 16:56:47 -07002694}
2695
Glenn Kastend848eb42016-03-08 13:42:11 -08002696audio_session_t MediaPlayerService::AudioOutput::getSessionId() const
Eric Laurent8c563ed2010-10-07 18:23:03 -07002697{
Andy Hungd1c74342015-07-07 16:54:23 -07002698 Mutex::Autolock lock(mLock);
Eric Laurent8c563ed2010-10-07 18:23:03 -07002699 return mSessionId;
2700}
2701
Eric Laurent6f59db12013-07-26 17:16:50 -07002702uint32_t MediaPlayerService::AudioOutput::getSampleRate() const
2703{
Andy Hungd1c74342015-07-07 16:54:23 -07002704 Mutex::Autolock lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -07002705 if (mTrack == 0) return 0;
2706 return mTrack->getSampleRate();
2707}
2708
Andy Hungf2c87b32016-04-07 19:49:29 -07002709int64_t MediaPlayerService::AudioOutput::getBufferDurationInUs() const
2710{
2711 Mutex::Autolock lock(mLock);
2712 if (mTrack == 0) {
2713 return 0;
2714 }
2715 int64_t duration;
2716 if (mTrack->getBufferDurationInUs(&duration) != OK) {
2717 return 0;
2718 }
2719 return duration;
2720}
2721
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002722////////////////////////////////////////////////////////////////////////////////
2723
2724struct CallbackThread : public Thread {
2725 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
2726 MediaPlayerBase::AudioSink::AudioCallback cb,
2727 void *cookie);
2728
2729protected:
2730 virtual ~CallbackThread();
2731
2732 virtual bool threadLoop();
2733
2734private:
2735 wp<MediaPlayerBase::AudioSink> mSink;
2736 MediaPlayerBase::AudioSink::AudioCallback mCallback;
2737 void *mCookie;
2738 void *mBuffer;
2739 size_t mBufferSize;
2740
2741 CallbackThread(const CallbackThread &);
2742 CallbackThread &operator=(const CallbackThread &);
2743};
2744
2745CallbackThread::CallbackThread(
2746 const wp<MediaPlayerBase::AudioSink> &sink,
2747 MediaPlayerBase::AudioSink::AudioCallback cb,
2748 void *cookie)
2749 : mSink(sink),
2750 mCallback(cb),
2751 mCookie(cookie),
2752 mBuffer(NULL),
2753 mBufferSize(0) {
2754}
2755
2756CallbackThread::~CallbackThread() {
2757 if (mBuffer) {
2758 free(mBuffer);
2759 mBuffer = NULL;
2760 }
2761}
2762
2763bool CallbackThread::threadLoop() {
2764 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
2765 if (sink == NULL) {
2766 return false;
2767 }
2768
2769 if (mBuffer == NULL) {
2770 mBufferSize = sink->bufferSize();
2771 mBuffer = malloc(mBufferSize);
2772 }
2773
2774 size_t actualSize =
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002775 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie,
2776 MediaPlayerBase::AudioSink::CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002777
2778 if (actualSize > 0) {
2779 sink->write(mBuffer, actualSize);
Andy Hunga31335a2014-08-20 17:37:59 -07002780 // Could return false on sink->write() error or short count.
2781 // Not necessarily appropriate but would work for AudioCache behavior.
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002782 }
2783
2784 return true;
2785}
2786
2787////////////////////////////////////////////////////////////////////////////////
2788
Chong Zhange5b9b692017-05-11 11:44:56 -07002789void MediaPlayerService::addBatteryData(uint32_t params) {
2790 mBatteryTracker.addBatteryData(params);
2791}
2792
2793status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
2794 return mBatteryTracker.pullBatteryData(reply);
2795}
2796
2797MediaPlayerService::BatteryTracker::BatteryTracker() {
2798 mBatteryAudio.refCount = 0;
2799 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2800 mBatteryAudio.deviceOn[i] = 0;
2801 mBatteryAudio.lastTime[i] = 0;
2802 mBatteryAudio.totalTime[i] = 0;
2803 }
2804 // speaker is on by default
2805 mBatteryAudio.deviceOn[SPEAKER] = 1;
2806
2807 // reset battery stats
2808 // if the mediaserver has crashed, battery stats could be left
2809 // in bad state, reset the state upon service start.
2810 BatteryNotifier::getInstance().noteResetVideo();
2811}
2812
2813void MediaPlayerService::BatteryTracker::addBatteryData(uint32_t params)
Gloria Wang7cf180c2011-02-19 18:37:57 -08002814{
2815 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002816
2817 int32_t time = systemTime() / 1000000L;
2818
2819 // change audio output devices. This notification comes from AudioFlinger
2820 if ((params & kBatteryDataSpeakerOn)
2821 || (params & kBatteryDataOtherAudioDeviceOn)) {
2822
2823 int deviceOn[NUM_AUDIO_DEVICES];
2824 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2825 deviceOn[i] = 0;
2826 }
2827
2828 if ((params & kBatteryDataSpeakerOn)
2829 && (params & kBatteryDataOtherAudioDeviceOn)) {
2830 deviceOn[SPEAKER_AND_OTHER] = 1;
2831 } else if (params & kBatteryDataSpeakerOn) {
2832 deviceOn[SPEAKER] = 1;
2833 } else {
2834 deviceOn[OTHER_AUDIO_DEVICE] = 1;
2835 }
2836
2837 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2838 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
2839
2840 if (mBatteryAudio.refCount > 0) { // if playing audio
2841 if (!deviceOn[i]) {
2842 mBatteryAudio.lastTime[i] += time;
2843 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2844 mBatteryAudio.lastTime[i] = 0;
2845 } else {
2846 mBatteryAudio.lastTime[i] = 0 - time;
2847 }
2848 }
2849
2850 mBatteryAudio.deviceOn[i] = deviceOn[i];
2851 }
2852 }
2853 return;
2854 }
2855
Marco Nelissenb7848f12014-12-04 08:57:56 -08002856 // an audio stream is started
Gloria Wang9ee159b2011-02-24 14:51:45 -08002857 if (params & kBatteryDataAudioFlingerStart) {
2858 // record the start time only if currently no other audio
2859 // is being played
2860 if (mBatteryAudio.refCount == 0) {
2861 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2862 if (mBatteryAudio.deviceOn[i]) {
2863 mBatteryAudio.lastTime[i] -= time;
2864 }
2865 }
2866 }
2867
2868 mBatteryAudio.refCount ++;
2869 return;
2870
2871 } else if (params & kBatteryDataAudioFlingerStop) {
2872 if (mBatteryAudio.refCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002873 ALOGW("Battery track warning: refCount is <= 0");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002874 return;
2875 }
2876
2877 // record the stop time only if currently this is the only
2878 // audio being played
2879 if (mBatteryAudio.refCount == 1) {
2880 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2881 if (mBatteryAudio.deviceOn[i]) {
2882 mBatteryAudio.lastTime[i] += time;
2883 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2884 mBatteryAudio.lastTime[i] = 0;
2885 }
2886 }
2887 }
2888
2889 mBatteryAudio.refCount --;
2890 return;
2891 }
2892
Andy Hung1afd0982016-11-08 16:13:44 -08002893 uid_t uid = IPCThreadState::self()->getCallingUid();
Gloria Wang7cf180c2011-02-19 18:37:57 -08002894 if (uid == AID_MEDIA) {
2895 return;
2896 }
2897 int index = mBatteryData.indexOfKey(uid);
Gloria Wang7cf180c2011-02-19 18:37:57 -08002898
2899 if (index < 0) { // create a new entry for this UID
2900 BatteryUsageInfo info;
2901 info.audioTotalTime = 0;
2902 info.videoTotalTime = 0;
2903 info.audioLastTime = 0;
2904 info.videoLastTime = 0;
2905 info.refCount = 0;
2906
Gloria Wang9ee159b2011-02-24 14:51:45 -08002907 if (mBatteryData.add(uid, info) == NO_MEMORY) {
Steve Block29357bc2012-01-06 19:20:56 +00002908 ALOGE("Battery track error: no memory for new app");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002909 return;
2910 }
Gloria Wang7cf180c2011-02-19 18:37:57 -08002911 }
2912
2913 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
2914
2915 if (params & kBatteryDataCodecStarted) {
2916 if (params & kBatteryDataTrackAudio) {
2917 info.audioLastTime -= time;
2918 info.refCount ++;
2919 }
2920 if (params & kBatteryDataTrackVideo) {
2921 info.videoLastTime -= time;
2922 info.refCount ++;
2923 }
2924 } else {
2925 if (info.refCount == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002926 ALOGW("Battery track warning: refCount is already 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002927 return;
2928 } else if (info.refCount < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00002929 ALOGE("Battery track error: refCount < 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002930 mBatteryData.removeItem(uid);
2931 return;
2932 }
2933
2934 if (params & kBatteryDataTrackAudio) {
2935 info.audioLastTime += time;
2936 info.refCount --;
2937 }
2938 if (params & kBatteryDataTrackVideo) {
2939 info.videoLastTime += time;
2940 info.refCount --;
2941 }
2942
2943 // no stream is being played by this UID
2944 if (info.refCount == 0) {
2945 info.audioTotalTime += info.audioLastTime;
2946 info.audioLastTime = 0;
2947 info.videoTotalTime += info.videoLastTime;
2948 info.videoLastTime = 0;
2949 }
2950 }
2951}
2952
Chong Zhange5b9b692017-05-11 11:44:56 -07002953status_t MediaPlayerService::BatteryTracker::pullBatteryData(Parcel* reply) {
Gloria Wang7cf180c2011-02-19 18:37:57 -08002954 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002955
2956 // audio output devices usage
2957 int32_t time = systemTime() / 1000000L; //in ms
2958 int32_t totalTime;
2959
2960 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2961 totalTime = mBatteryAudio.totalTime[i];
2962
2963 if (mBatteryAudio.deviceOn[i]
2964 && (mBatteryAudio.lastTime[i] != 0)) {
2965 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
2966 totalTime += tmpTime;
2967 }
2968
2969 reply->writeInt32(totalTime);
2970 // reset the total time
2971 mBatteryAudio.totalTime[i] = 0;
2972 }
2973
2974 // codec usage
Gloria Wang7cf180c2011-02-19 18:37:57 -08002975 BatteryUsageInfo info;
2976 int size = mBatteryData.size();
2977
2978 reply->writeInt32(size);
2979 int i = 0;
2980
2981 while (i < size) {
2982 info = mBatteryData.valueAt(i);
2983
2984 reply->writeInt32(mBatteryData.keyAt(i)); //UID
2985 reply->writeInt32(info.audioTotalTime);
2986 reply->writeInt32(info.videoTotalTime);
2987
2988 info.audioTotalTime = 0;
2989 info.videoTotalTime = 0;
2990
2991 // remove the UID entry where no stream is being played
2992 if (info.refCount <= 0) {
2993 mBatteryData.removeItemsAt(i);
2994 size --;
2995 i --;
2996 }
2997 i++;
2998 }
2999 return NO_ERROR;
3000}
nikoa64c8c72009-07-20 15:07:26 -07003001} // namespace android