blob: e5f97897960ac8c6b28948ad3128a8f37fa2e0e8 [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
Andy Hung959b5b82021-09-24 10:46:20 -070024#include <chrono>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080025#include <sys/types.h>
26#include <sys/stat.h>
Gloria Wang7cf180c2011-02-19 18:37:57 -080027#include <sys/time.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080028#include <dirent.h>
29#include <unistd.h>
30
31#include <string.h>
Mathias Agopian6f74b0c2009-06-03 17:32:49 -070032
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080033#include <cutils/atomic.h>
Nicolas Catania14d27472009-07-13 14:37:49 -070034#include <cutils/properties.h> // for property_get
Mathias Agopian6f74b0c2009-06-03 17:32:49 -070035
36#include <utils/misc.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080037
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -070038#include <android/hardware/media/omx/1.0/IOmx.h>
Marco Nelissena0c98412019-03-29 12:10:19 -070039#include <android/hardware/media/c2/1.0/IComponentStore.h>
Mathias Agopian75624082009-05-19 19:08:10 -070040#include <binder/IPCThreadState.h>
41#include <binder/IServiceManager.h>
42#include <binder/MemoryHeapBase.h>
43#include <binder/MemoryBase.h>
Mathias Agopianb1e7cd12013-02-14 17:11:27 -080044#include <gui/Surface.h>
Nicolas Catania1d187f12009-05-12 23:25:55 -070045#include <utils/Errors.h> // for status_t
46#include <utils/String8.h>
Marco Nelissen10dbb8e2009-09-20 10:42:13 -070047#include <utils/SystemClock.h>
Lajos Molnar06ad1522014-08-28 07:27:44 -070048#include <utils/Timers.h>
Nicolas Catania1d187f12009-05-12 23:25:55 -070049#include <utils/Vector.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080050
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -070051#include <codec2/hidl/client.h>
Marco Nelissen42057ce2019-09-23 12:15:57 -070052#include <datasource/HTTPBase.h>
Philip P. Moltmannbda45752020-07-17 16:41:18 -070053#include <media/AidlConversion.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080054#include <media/IMediaHTTPService.h>
Jeff Brown2013a542012-09-04 21:38:42 -070055#include <media/IRemoteDisplay.h>
56#include <media/IRemoteDisplayClient.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080057#include <media/MediaPlayerInterface.h>
58#include <media/mediarecorder.h>
59#include <media/MediaMetadataRetrieverInterface.h>
nikoa64c8c72009-07-20 15:07:26 -070060#include <media/Metadata.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080061#include <media/AudioTrack.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>
Andy Hunge9eb03e2020-04-04 14:08:23 -070072#include <mediautils/MemoryLeakTrackUtil.h>
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"
Ray Essickafca1562022-01-25 09:51: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;
Svet Ganov33761132021-05-13 22:51:08 +000099using android::content::AttributionSourceState;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700100
101// Max number of entries in the filter.
102const int kMaxFilterSize = 64; // I pulled that out of thin air.
103
Andy Hungff874dc2016-04-11 16:49:09 -0700104const float kMaxRequiredSpeed = 8.0f; // for PCM tracks allow up to 8x speedup.
105
nikoa64c8c72009-07-20 15:07:26 -0700106// FIXME: Move all the metadata related function in the Metadata.cpp
nikod608a812009-07-16 16:39:53 -0700107
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700108
109// Unmarshall a filter from a Parcel.
110// Filter format in a parcel:
111//
112// 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
113// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
114// | number of entries (n) |
115// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
116// | metadata type 1 |
117// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
118// | metadata type 2 |
119// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
120// ....
121// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
122// | metadata type n |
123// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
124//
125// @param p Parcel that should start with a filter.
126// @param[out] filter On exit contains the list of metadata type to be
127// filtered.
128// @param[out] status On exit contains the status code to be returned.
129// @return true if the parcel starts with a valid filter.
130bool unmarshallFilter(const Parcel& p,
nikoa64c8c72009-07-20 15:07:26 -0700131 Metadata::Filter *filter,
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700132 status_t *status)
133{
Nicolas Catania48290382009-07-10 13:53:06 -0700134 int32_t val;
135 if (p.readInt32(&val) != OK)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700136 {
Steve Block29357bc2012-01-06 19:20:56 +0000137 ALOGE("Failed to read filter's length");
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700138 *status = NOT_ENOUGH_DATA;
139 return false;
140 }
141
Nicolas Catania48290382009-07-10 13:53:06 -0700142 if( val > kMaxFilterSize || val < 0)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700143 {
Steve Block29357bc2012-01-06 19:20:56 +0000144 ALOGE("Invalid filter len %d", val);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700145 *status = BAD_VALUE;
146 return false;
147 }
148
Nicolas Catania48290382009-07-10 13:53:06 -0700149 const size_t num = val;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700150
151 filter->clear();
Nicolas Catania48290382009-07-10 13:53:06 -0700152 filter->setCapacity(num);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700153
nikoa64c8c72009-07-20 15:07:26 -0700154 size_t size = num * sizeof(Metadata::Type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700155
Nicolas Catania48290382009-07-10 13:53:06 -0700156
157 if (p.dataAvail() < size)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700158 {
Andy Hung833b4752016-04-04 17:15:48 -0700159 ALOGE("Filter too short expected %zu but got %zu", size, p.dataAvail());
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700160 *status = NOT_ENOUGH_DATA;
161 return false;
162 }
163
nikoa64c8c72009-07-20 15:07:26 -0700164 const Metadata::Type *data =
165 static_cast<const Metadata::Type*>(p.readInplace(size));
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700166
Nicolas Catania48290382009-07-10 13:53:06 -0700167 if (NULL == data)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700168 {
Steve Block29357bc2012-01-06 19:20:56 +0000169 ALOGE("Filter had no data");
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700170 *status = BAD_VALUE;
171 return false;
172 }
173
174 // TODO: The stl impl of vector would be more efficient here
175 // because it degenerates into a memcpy on pod types. Try to
176 // replace later or use stl::set.
Nicolas Catania48290382009-07-10 13:53:06 -0700177 for (size_t i = 0; i < num; ++i)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700178 {
Nicolas Catania48290382009-07-10 13:53:06 -0700179 filter->add(*data);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700180 ++data;
181 }
182 *status = OK;
183 return true;
184}
185
Nicolas Catania48290382009-07-10 13:53:06 -0700186// @param filter Of metadata type.
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700187// @param val To be searched.
188// @return true if a match was found.
nikoa64c8c72009-07-20 15:07:26 -0700189bool findMetadata(const Metadata::Filter& filter, const int32_t val)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700190{
191 // Deal with empty and ANY right away
192 if (filter.isEmpty()) return false;
nikoa64c8c72009-07-20 15:07:26 -0700193 if (filter[0] == Metadata::kAny) return true;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700194
Nicolas Catania48290382009-07-10 13:53:06 -0700195 return filter.indexOf(val) >= 0;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700196}
197
198} // anonymous namespace
199
200
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700201namespace {
202using android::Parcel;
203using android::String16;
204
205// marshalling tag indicating flattened utf16 tags
206// keep in sync with frameworks/base/media/java/android/media/AudioAttributes.java
207const int32_t kAudioAttributesMarshallTagFlattenTags = 1;
208
209// Audio attributes format in a parcel:
210//
211// 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
212// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
213// | usage |
214// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
215// | content_type |
216// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Hyejin Kim4f418f92014-09-05 15:50:03 +0900217// | source |
218// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700219// | flags |
220// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
221// | kAudioAttributesMarshallTagFlattenTags | // ignore tags if not found
222// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
223// | flattened tags in UTF16 |
224// | ... |
225// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
226//
227// @param p Parcel that contains audio attributes.
228// @param[out] attributes On exit points to an initialized audio_attributes_t structure
229// @param[out] status On exit contains the status code to be returned.
230void unmarshallAudioAttributes(const Parcel& parcel, audio_attributes_t *attributes)
231{
232 attributes->usage = (audio_usage_t) parcel.readInt32();
233 attributes->content_type = (audio_content_type_t) parcel.readInt32();
Hyejin Kim4f418f92014-09-05 15:50:03 +0900234 attributes->source = (audio_source_t) parcel.readInt32();
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700235 attributes->flags = (audio_flags_mask_t) parcel.readInt32();
236 const bool hasFlattenedTag = (parcel.readInt32() == kAudioAttributesMarshallTagFlattenTags);
237 if (hasFlattenedTag) {
238 // the tags are UTF16, convert to UTF8
239 String16 tags = parcel.readString16();
240 ssize_t realTagSize = utf16_to_utf8_length(tags.string(), tags.size());
241 if (realTagSize <= 0) {
242 strcpy(attributes->tags, "");
243 } else {
244 // copy the flattened string into the attributes as the destination for the conversion:
245 // copying array size -1, array for tags was calloc'd, no need to NULL-terminate it
246 size_t tagSize = realTagSize > AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 ?
247 AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 : realTagSize;
Sergio Giro1d3f4272016-06-28 18:24:52 +0100248 utf16_to_utf8(tags.string(), tagSize, attributes->tags,
249 sizeof(attributes->tags) / sizeof(attributes->tags[0]));
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700250 }
251 } else {
252 ALOGE("unmarshallAudioAttributes() received unflattened tags, ignoring tag values");
253 strcpy(attributes->tags, "");
254 }
255}
256} // anonymous namespace
257
258
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800259namespace android {
260
Marco Nelissenf09611f2015-02-13 14:12:42 -0800261extern ALooperRoster gLooperRoster;
262
263
Dave Burked681bbb2011-08-30 14:39:17 +0100264static bool checkPermission(const char* permissionString) {
Dave Burked681bbb2011-08-30 14:39:17 +0100265 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
266 bool ok = checkCallingPermission(String16(permissionString));
Steve Block29357bc2012-01-06 19:20:56 +0000267 if (!ok) ALOGE("Request requires %s", permissionString);
Dave Burked681bbb2011-08-30 14:39:17 +0100268 return ok;
269}
270
Wonsik Kim6f675772019-08-20 17:06:53 -0700271static void dumpCodecDetails(int fd, const sp<IMediaCodecList> &codecList, bool queryDecoders) {
272 const size_t SIZE = 256;
273 char buffer[SIZE];
274 String8 result;
275
276 const char *codecType = queryDecoders? "Decoder" : "Encoder";
277 snprintf(buffer, SIZE - 1, "\n%s infos by media types:\n"
278 "=============================\n", codecType);
279 result.append(buffer);
280
281 size_t numCodecs = codecList->countCodecs();
282
283 // gather all media types supported by codec class, and link to codecs that support them
284 KeyedVector<AString, Vector<sp<MediaCodecInfo>>> allMediaTypes;
285 for (size_t codec_ix = 0; codec_ix < numCodecs; ++codec_ix) {
286 sp<MediaCodecInfo> info = codecList->getCodecInfo(codec_ix);
287 if (info->isEncoder() == !queryDecoders) {
288 Vector<AString> supportedMediaTypes;
289 info->getSupportedMediaTypes(&supportedMediaTypes);
290 if (!supportedMediaTypes.size()) {
291 snprintf(buffer, SIZE - 1, "warning: %s does not support any media types\n",
292 info->getCodecName());
293 result.append(buffer);
294 } else {
295 for (const AString &mediaType : supportedMediaTypes) {
296 if (allMediaTypes.indexOfKey(mediaType) < 0) {
297 allMediaTypes.add(mediaType, Vector<sp<MediaCodecInfo>>());
298 }
299 allMediaTypes.editValueFor(mediaType).add(info);
300 }
301 }
302 }
303 }
304
305 KeyedVector<AString, bool> visitedCodecs;
306 for (size_t type_ix = 0; type_ix < allMediaTypes.size(); ++type_ix) {
307 const AString &mediaType = allMediaTypes.keyAt(type_ix);
308 snprintf(buffer, SIZE - 1, "\nMedia type '%s':\n", mediaType.c_str());
309 result.append(buffer);
310
311 for (const sp<MediaCodecInfo> &info : allMediaTypes.valueAt(type_ix)) {
312 sp<MediaCodecInfo::Capabilities> caps = info->getCapabilitiesFor(mediaType.c_str());
313 if (caps == NULL) {
314 snprintf(buffer, SIZE - 1, "warning: %s does not have capabilities for type %s\n",
315 info->getCodecName(), mediaType.c_str());
316 result.append(buffer);
317 continue;
318 }
319 snprintf(buffer, SIZE - 1, " %s \"%s\" supports\n",
320 codecType, info->getCodecName());
321 result.append(buffer);
322
323 auto printList = [&](const char *type, const Vector<AString> &values){
324 snprintf(buffer, SIZE - 1, " %s: [", type);
325 result.append(buffer);
326 for (size_t j = 0; j < values.size(); ++j) {
327 snprintf(buffer, SIZE - 1, "\n %s%s", values[j].c_str(),
328 j == values.size() - 1 ? " " : ",");
329 result.append(buffer);
330 }
331 result.append("]\n");
332 };
333
334 if (visitedCodecs.indexOfKey(info->getCodecName()) < 0) {
335 visitedCodecs.add(info->getCodecName(), true);
336 {
337 Vector<AString> aliases;
338 info->getAliases(&aliases);
339 // quote alias
340 for (AString &alias : aliases) {
341 alias.insert("\"", 1, 0);
342 alias.append('"');
343 }
344 printList("aliases", aliases);
345 }
346 {
347 uint32_t attrs = info->getAttributes();
348 Vector<AString> list;
349 list.add(AStringPrintf("encoder: %d",
350 !!(attrs & MediaCodecInfo::kFlagIsEncoder)));
351 list.add(AStringPrintf("vendor: %d",
352 !!(attrs & MediaCodecInfo::kFlagIsVendor)));
353 list.add(AStringPrintf("software-only: %d",
354 !!(attrs & MediaCodecInfo::kFlagIsSoftwareOnly)));
355 list.add(AStringPrintf("hw-accelerated: %d",
356 !!(attrs & MediaCodecInfo::kFlagIsHardwareAccelerated)));
357 printList(AStringPrintf("attributes: %#x", attrs).c_str(), list);
358 }
359
360 snprintf(buffer, SIZE - 1, " owner: \"%s\"\n", info->getOwnerName());
361 result.append(buffer);
362 snprintf(buffer, SIZE - 1, " rank: %u\n", info->getRank());
363 result.append(buffer);
364 } else {
365 result.append(" aliases, attributes, owner, rank: see above\n");
366 }
367
368 {
369 Vector<AString> list;
370 Vector<MediaCodecInfo::ProfileLevel> profileLevels;
371 caps->getSupportedProfileLevels(&profileLevels);
372 for (const MediaCodecInfo::ProfileLevel &pl : profileLevels) {
373 const char *niceProfile =
374 mediaType.equalsIgnoreCase(MIMETYPE_AUDIO_AAC)
375 ? asString_AACObject(pl.mProfile) :
376 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_MPEG2)
377 ? asString_MPEG2Profile(pl.mProfile) :
378 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_H263)
379 ? asString_H263Profile(pl.mProfile) :
380 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_MPEG4)
381 ? asString_MPEG4Profile(pl.mProfile) :
382 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_AVC)
383 ? asString_AVCProfile(pl.mProfile) :
384 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_VP8)
385 ? asString_VP8Profile(pl.mProfile) :
386 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_HEVC)
387 ? asString_HEVCProfile(pl.mProfile) :
388 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_VP9)
389 ? asString_VP9Profile(pl.mProfile) :
390 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_AV1)
ybaia7de57f2023-06-07 14:06:14 +0800391 ? asString_AV1Profile(pl.mProfile) :
392 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_DOLBY_VISION)
393 ? asString_DolbyVisionProfile(pl.mProfile) : "??";
Wonsik Kim6f675772019-08-20 17:06:53 -0700394 const char *niceLevel =
395 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_MPEG2)
396 ? asString_MPEG2Level(pl.mLevel) :
397 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_H263)
398 ? asString_H263Level(pl.mLevel) :
399 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_MPEG4)
400 ? asString_MPEG4Level(pl.mLevel) :
401 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_AVC)
402 ? asString_AVCLevel(pl.mLevel) :
403 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_VP8)
404 ? asString_VP8Level(pl.mLevel) :
405 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_HEVC)
406 ? asString_HEVCTierLevel(pl.mLevel) :
407 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_VP9)
408 ? asString_VP9Level(pl.mLevel) :
409 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_AV1)
ybaia7de57f2023-06-07 14:06:14 +0800410 ? asString_AV1Level(pl.mLevel) :
411 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_DOLBY_VISION)
412 ? asString_DolbyVisionLevel(pl.mLevel) : "??";
Wonsik Kim6f675772019-08-20 17:06:53 -0700413
414 list.add(AStringPrintf("% 5u/% 5u (%s/%s)",
415 pl.mProfile, pl.mLevel, niceProfile, niceLevel));
416 }
417 printList("profile/levels", list);
418 }
419
420 {
421 Vector<AString> list;
422 Vector<uint32_t> colors;
423 caps->getSupportedColorFormats(&colors);
424 for (uint32_t color : colors) {
425 list.add(AStringPrintf("%#x (%s)", color,
426 asString_ColorFormat((int32_t)color)));
427 }
428 printList("colors", list);
429 }
430
Wonsik Kimd579f3e2019-10-07 14:14:09 -0700431 result.append(" details: ");
432 result.append(caps->getDetails()->debugString(6).c_str());
433 result.append("\n");
Wonsik Kim6f675772019-08-20 17:06:53 -0700434 }
435 }
436 result.append("\n");
437 ::write(fd, result.string(), result.size());
438}
439
440
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800441// 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 -0800442/* static */ int MediaPlayerService::AudioOutput::mMinBufferCount = 4;
443/* static */ bool MediaPlayerService::AudioOutput::mIsOnEmulator = false;
444
445void MediaPlayerService::instantiate() {
446 defaultServiceManager()->addService(
447 String16("media.player"), new MediaPlayerService());
448}
449
450MediaPlayerService::MediaPlayerService()
451{
Steve Block3856b092011-10-20 11:56:00 +0100452 ALOGV("MediaPlayerService created");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800453 mNextConnId = 1;
Gloria Wang9ee159b2011-02-24 14:51:45 -0800454
John Grossman44a7e422012-06-21 17:29:24 -0700455 MediaPlayerFactory::registerBuiltinFactories();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800456}
457
458MediaPlayerService::~MediaPlayerService()
459{
Steve Block3856b092011-10-20 11:56:00 +0100460 ALOGV("MediaPlayerService destroyed");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800461}
462
Svet Ganov33761132021-05-13 22:51:08 +0000463sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(
464 const AttributionSourceState& attributionSource)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800465{
Svet Ganov33761132021-05-13 22:51:08 +0000466 // TODO b/182392769: use attribution source util
467 AttributionSourceState verifiedAttributionSource = attributionSource;
468 verifiedAttributionSource.uid = VALUE_OR_FATAL(
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700469 legacy2aidl_uid_t_int32_t(IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +0000470 verifiedAttributionSource.pid = VALUE_OR_FATAL(
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700471 legacy2aidl_pid_t_int32_t(IPCThreadState::self()->getCallingPid()));
472 sp<MediaRecorderClient> recorder =
Svet Ganov33761132021-05-13 22:51:08 +0000473 new MediaRecorderClient(this, verifiedAttributionSource);
Gloria Wangdac6a312009-10-29 15:46:37 -0700474 wp<MediaRecorderClient> w = recorder;
475 Mutex::Autolock lock(mLock);
476 mMediaRecorderClients.add(w);
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700477 ALOGV("Create new media recorder client from pid %s",
Svet Ganov33761132021-05-13 22:51:08 +0000478 verifiedAttributionSource.toString().c_str());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800479 return recorder;
480}
481
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -0700482void MediaPlayerService::removeMediaRecorderClient(const wp<MediaRecorderClient>& client)
Gloria Wangdac6a312009-10-29 15:46:37 -0700483{
484 Mutex::Autolock lock(mLock);
485 mMediaRecorderClients.remove(client);
Steve Block3856b092011-10-20 11:56:00 +0100486 ALOGV("Delete media recorder client");
Gloria Wangdac6a312009-10-29 15:46:37 -0700487}
488
Glenn Kastenf37971f2012-02-03 11:06:53 -0800489sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800490{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800491 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800492 sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
Steve Block3856b092011-10-20 11:56:00 +0100493 ALOGV("Create new media retriever from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800494 return retriever;
495}
496
Glenn Kastenf37971f2012-02-03 11:06:53 -0800497sp<IMediaPlayer> MediaPlayerService::create(const sp<IMediaPlayerClient>& client,
Svet Ganov33761132021-05-13 22:51:08 +0000498 audio_session_t audioSessionId, const AttributionSourceState& attributionSource)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800499{
500 int32_t connId = android_atomic_inc(&mNextConnId);
Svet Ganov33761132021-05-13 22:51:08 +0000501 // TODO b/182392769: use attribution source util
502 AttributionSourceState verifiedAttributionSource = attributionSource;
503 verifiedAttributionSource.pid = VALUE_OR_FATAL(
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700504 legacy2aidl_pid_t_int32_t(IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +0000505 verifiedAttributionSource.uid = VALUE_OR_FATAL(
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700506 legacy2aidl_uid_t_int32_t(IPCThreadState::self()->getCallingUid()));
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700507
508 sp<Client> c = new Client(
Svet Ganov33761132021-05-13 22:51:08 +0000509 this, verifiedAttributionSource, connId, client, audioSessionId);
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700510
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700511 ALOGV("Create new client(%d) from %s, ", connId,
Svet Ganov33761132021-05-13 22:51:08 +0000512 verifiedAttributionSource.toString().c_str());
Dave Burked681bbb2011-08-30 14:39:17 +0100513
514 wp<Client> w = c;
515 {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800516 Mutex::Autolock lock(mLock);
517 mClients.add(w);
518 }
Andreas Hubere2b10282010-11-23 11:41:34 -0800519 return c;
520}
521
Lajos Molnar1381d4b2014-08-07 15:18:35 -0700522sp<IMediaCodecList> MediaPlayerService::getCodecList() const {
523 return MediaCodecList::getLocalInstance();
524}
525
Jeff Brown2013a542012-09-04 21:38:42 -0700526sp<IRemoteDisplay> MediaPlayerService::listenForRemoteDisplay(
Chong Zhangd0a98fa2017-09-14 17:43:10 -0700527 const String16 &/*opPackageName*/,
528 const sp<IRemoteDisplayClient>& /*client*/,
529 const String8& /*iface*/) {
530 ALOGE("listenForRemoteDisplay is no longer supported!");
Jeff Brownaba33d52012-09-07 17:38:58 -0700531
Chong Zhangd0a98fa2017-09-14 17:43:10 -0700532 return NULL;
Jeff Brown2013a542012-09-04 21:38:42 -0700533}
534
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800535status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
536{
537 const size_t SIZE = 256;
538 char buffer[SIZE];
539 String8 result;
540
541 result.append(" AudioOutput\n");
542 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n",
543 mStreamType, mLeftVolume, mRightVolume);
544 result.append(buffer);
545 snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n",
Eric Laurentdb354e52012-03-05 17:27:11 -0800546 mMsecsPerFrame, (mTrack != 0) ? mTrack->latency() : -1);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800547 result.append(buffer);
Eric Laurent2beeb502010-07-16 07:43:46 -0700548 snprintf(buffer, 255, " aux effect id(%d), send level (%f)\n",
549 mAuxEffectId, mSendLevel);
550 result.append(buffer);
551
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800552 ::write(fd, result.string(), result.size());
553 if (mTrack != 0) {
554 mTrack->dump(fd, args);
555 }
556 return NO_ERROR;
557}
558
Lajos Molnar6d339f12015-04-17 16:15:53 -0700559status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800560{
561 const size_t SIZE = 256;
562 char buffer[SIZE];
563 String8 result;
564 result.append(" Client\n");
Svet Ganov33761132021-05-13 22:51:08 +0000565 snprintf(buffer, 255, " AttributionSource(%s), connId(%d), status(%d), looping(%s)\n",
566 mAttributionSource.toString().c_str(), mConnId, mStatus, mLoop?"true": "false");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800567 result.append(buffer);
Wei Jia502c2f42017-07-13 17:47:56 -0700568
569 sp<MediaPlayerBase> p;
570 sp<AudioOutput> audioOutput;
571 bool locked = false;
572 for (int i = 0; i < kDumpLockRetries; ++i) {
573 if (mLock.tryLock() == NO_ERROR) {
574 locked = true;
575 break;
576 }
577 usleep(kDumpLockSleepUs);
Andreas Hubera0b1d4b2011-06-07 15:52:25 -0700578 }
Wei Jia502c2f42017-07-13 17:47:56 -0700579
580 if (locked) {
581 p = mPlayer;
582 audioOutput = mAudioOutput;
583 mLock.unlock();
584 } else {
585 result.append(" lock is taken, no dump from player and audio output\n");
586 }
587 write(fd, result.string(), result.size());
588
589 if (p != NULL) {
590 p->dump(fd, args);
591 }
592 if (audioOutput != 0) {
593 audioOutput->dump(fd, args);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800594 }
595 write(fd, "\n", 1);
596 return NO_ERROR;
597}
598
Marco Nelissenf09611f2015-02-13 14:12:42 -0800599/**
600 * The only arguments this understands right now are -c, -von and -voff,
601 * which are parsed by ALooperRoster::dump()
602 */
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800603status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
604{
605 const size_t SIZE = 256;
606 char buffer[SIZE];
607 String8 result;
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530608 SortedVector< sp<Client> > clients; //to serialise the mutex unlock & client destruction.
609 SortedVector< sp<MediaRecorderClient> > mediaRecorderClients;
610
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800611 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
Wonsik Kim6f675772019-08-20 17:06:53 -0700612 snprintf(buffer, SIZE - 1, "Permission Denial: "
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800613 "can't dump MediaPlayerService from pid=%d, uid=%d\n",
614 IPCThreadState::self()->getCallingPid(),
615 IPCThreadState::self()->getCallingUid());
616 result.append(buffer);
617 } else {
Lajos Molnara42e6cc2022-05-17 15:13:31 -0700618 {
619 // capture clients under lock
620 Mutex::Autolock lock(mLock);
621 for (int i = 0, n = mClients.size(); i < n; ++i) {
622 sp<Client> c = mClients[i].promote();
623 if (c != nullptr) {
624 clients.add(c);
625 }
626 }
627
James Dongb9141222010-07-08 11:16:11 -0700628 for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
629 sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
Lajos Molnara42e6cc2022-05-17 15:13:31 -0700630 if (c != nullptr) {
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530631 mediaRecorderClients.add(c);
James Donge579e282011-10-18 22:29:20 -0700632 }
James Dongb9141222010-07-08 11:16:11 -0700633 }
Gloria Wangdac6a312009-10-29 15:46:37 -0700634 }
635
Lajos Molnara42e6cc2022-05-17 15:13:31 -0700636 // dump clients outside of lock
637 for (const sp<Client> &c : clients) {
638 c->dump(fd, args);
639 }
640 if (mediaRecorderClients.size() == 0) {
641 result.append(" No media recorder client\n\n");
642 } else {
643 for (const sp<MediaRecorderClient> &c : mediaRecorderClients) {
644 snprintf(buffer, 255, " MediaRecorderClient pid(%d)\n",
645 c->mAttributionSource.pid);
646 result.append(buffer);
647 write(fd, result.string(), result.size());
648 result = "\n";
649 c->dump(fd, args);
650
651 }
652 }
653
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800654 result.append(" Files opened and/or mapped:\n");
Wonsik Kim6f675772019-08-20 17:06:53 -0700655 snprintf(buffer, SIZE - 1, "/proc/%d/maps", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800656 FILE *f = fopen(buffer, "r");
657 if (f) {
658 while (!feof(f)) {
Wonsik Kim6f675772019-08-20 17:06:53 -0700659 fgets(buffer, SIZE - 1, f);
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700660 if (strstr(buffer, " /storage/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800661 strstr(buffer, " /system/sounds/") ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700662 strstr(buffer, " /data/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800663 strstr(buffer, " /system/media/")) {
664 result.append(" ");
665 result.append(buffer);
666 }
667 }
668 fclose(f);
669 } else {
670 result.append("couldn't open ");
671 result.append(buffer);
672 result.append("\n");
673 }
674
Wonsik Kim6f675772019-08-20 17:06:53 -0700675 snprintf(buffer, SIZE - 1, "/proc/%d/fd", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800676 DIR *d = opendir(buffer);
677 if (d) {
678 struct dirent *ent;
679 while((ent = readdir(d)) != NULL) {
680 if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
Wonsik Kim6f675772019-08-20 17:06:53 -0700681 snprintf(buffer, SIZE - 1, "/proc/%d/fd/%s", getpid(), ent->d_name);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800682 struct stat s;
683 if (lstat(buffer, &s) == 0) {
684 if ((s.st_mode & S_IFMT) == S_IFLNK) {
685 char linkto[256];
686 int len = readlink(buffer, linkto, sizeof(linkto));
687 if(len > 0) {
688 if(len > 255) {
689 linkto[252] = '.';
690 linkto[253] = '.';
691 linkto[254] = '.';
692 linkto[255] = 0;
693 } else {
694 linkto[len] = 0;
695 }
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700696 if (strstr(linkto, "/storage/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800697 strstr(linkto, "/system/sounds/") == linkto ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700698 strstr(linkto, "/data/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800699 strstr(linkto, "/system/media/") == linkto) {
700 result.append(" ");
701 result.append(buffer);
702 result.append(" -> ");
703 result.append(linkto);
704 result.append("\n");
705 }
706 }
707 } else {
708 result.append(" unexpected type for ");
709 result.append(buffer);
710 result.append("\n");
711 }
712 }
713 }
714 }
715 closedir(d);
716 } else {
717 result.append("couldn't open ");
718 result.append(buffer);
719 result.append("\n");
720 }
721
Marco Nelissenf09611f2015-02-13 14:12:42 -0800722 gLooperRoster.dump(fd, args);
723
Wonsik Kimd579f3e2019-10-07 14:14:09 -0700724 sp<IMediaCodecList> codecList = getCodecList();
725 dumpCodecDetails(fd, codecList, true /* decoders */);
726 dumpCodecDetails(fd, codecList, false /* !decoders */);
727
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800728 bool dumpMem = false;
Andy Hung53541292016-04-13 16:48:51 -0700729 bool unreachableMemory = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800730 for (size_t i = 0; i < args.size(); i++) {
731 if (args[i] == String16("-m")) {
732 dumpMem = true;
Andy Hung53541292016-04-13 16:48:51 -0700733 } else if (args[i] == String16("--unreachable")) {
734 unreachableMemory = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800735 }
736 }
737 if (dumpMem) {
Andy Hung07b745e2016-05-23 16:21:07 -0700738 result.append("\nDumping memory:\n");
739 std::string s = dumpMemoryAddresses(100 /* limit */);
740 result.append(s.c_str(), s.size());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800741 }
Andy Hung53541292016-04-13 16:48:51 -0700742 if (unreachableMemory) {
743 result.append("\nDumping unreachable memory:\n");
744 // TODO - should limit be an argument parameter?
745 std::string s = GetUnreachableMemoryString(true /* contents */, 10000 /* limit */);
746 result.append(s.c_str(), s.size());
747 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800748 }
749 write(fd, result.string(), result.size());
Wonsik Kim6f675772019-08-20 17:06:53 -0700750
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800751 return NO_ERROR;
752}
753
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -0700754void MediaPlayerService::removeClient(const wp<Client>& client)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800755{
756 Mutex::Autolock lock(mLock);
757 mClients.remove(client);
758}
759
Robert Shihee0a0e32016-08-16 16:50:54 -0700760bool MediaPlayerService::hasClient(wp<Client> client)
761{
762 Mutex::Autolock lock(mLock);
763 return mClients.indexOf(client) != NAME_NOT_FOUND;
764}
765
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700766MediaPlayerService::Client::Client(
Svet Ganov33761132021-05-13 22:51:08 +0000767 const sp<MediaPlayerService>& service, const AttributionSourceState& attributionSource,
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700768 int32_t connId, const sp<IMediaPlayerClient>& client,
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700769 audio_session_t audioSessionId)
Svet Ganov33761132021-05-13 22:51:08 +0000770 : mAttributionSource(attributionSource)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800771{
Steve Block3856b092011-10-20 11:56:00 +0100772 ALOGV("Client(%d) constructor", connId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800773 mConnId = connId;
774 mService = service;
775 mClient = client;
776 mLoop = false;
777 mStatus = NO_INIT;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700778 mAudioSessionId = audioSessionId;
John Grossmanc795b642012-02-22 15:38:35 -0800779 mRetransmitEndpointValid = false;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700780 mAudioAttributes = NULL;
Pawin Vongmasa082e4f72017-12-17 02:31:18 -0800781 mListener = new Listener(this);
Eric Laurenta514bdb2010-06-21 09:27:30 -0700782
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800783#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000784 ALOGD("create Antagonizer");
Pawin Vongmasa082e4f72017-12-17 02:31:18 -0800785 mAntagonizer = new Antagonizer(mListener);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800786#endif
787}
788
789MediaPlayerService::Client::~Client()
790{
Svet Ganov33761132021-05-13 22:51:08 +0000791 ALOGV("Client(%d) destructor AttributionSource = %s", mConnId,
792 mAttributionSource.toString().c_str());
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700793 mAudioOutput.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800794 wp<Client> client(this);
795 disconnect();
796 mService->removeClient(client);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700797 if (mAudioAttributes != NULL) {
798 free(mAudioAttributes);
799 }
jiabin156c6872017-10-06 09:47:15 -0700800 mAudioDeviceUpdatedListener.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800801}
802
803void MediaPlayerService::Client::disconnect()
804{
Svet Ganov33761132021-05-13 22:51:08 +0000805 ALOGV("disconnect(%d) from AttributionSource %s", mConnId,
806 mAttributionSource.toString().c_str());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800807 // grab local reference and clear main reference to prevent future
808 // access to object
809 sp<MediaPlayerBase> p;
810 {
811 Mutex::Autolock l(mLock);
812 p = mPlayer;
beanzdcfefde2012-11-05 09:51:43 +0800813 mClient.clear();
Wei Jia502c2f42017-07-13 17:47:56 -0700814 mPlayer.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800815 }
Andreas Huber20111aa2009-07-14 16:56:47 -0700816
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800817 // clear the notification to prevent callbacks to dead client
818 // and reset the player. We assume the player will serialize
819 // access to itself if necessary.
820 if (p != 0) {
Pawin Vongmasa082e4f72017-12-17 02:31:18 -0800821 p->setNotifyCallback(0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800822#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000823 ALOGD("kill Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800824 mAntagonizer->kill();
825#endif
826 p->reset();
827 }
828
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700829 {
830 Mutex::Autolock l(mLock);
831 disconnectNativeWindow_l();
832 }
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700833
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800834 IPCThreadState::self()->flushCommands();
835}
836
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800837sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
838{
839 // determine if we have the right player type
Wei Jia502c2f42017-07-13 17:47:56 -0700840 sp<MediaPlayerBase> p = getPlayer();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800841 if ((p != NULL) && (p->playerType() != playerType)) {
Steve Block3856b092011-10-20 11:56:00 +0100842 ALOGV("delete player");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800843 p.clear();
844 }
845 if (p == NULL) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700846 p = MediaPlayerFactory::createPlayer(playerType, mListener,
Svet Ganov33761132021-05-13 22:51:08 +0000847 VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(mAttributionSource.pid)));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800848 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700849
Jason Simmonsdb29e522011-08-12 13:46:55 -0700850 if (p != NULL) {
Svet Ganov33761132021-05-13 22:51:08 +0000851 p->setUID(VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(mAttributionSource.uid)));
Jason Simmonsdb29e522011-08-12 13:46:55 -0700852 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700853
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800854 return p;
855}
856
jiabin156c6872017-10-06 09:47:15 -0700857void MediaPlayerService::Client::AudioDeviceUpdatedNotifier::onAudioDeviceUpdate(
858 audio_io_handle_t audioIo,
859 audio_port_handle_t deviceId) {
860 sp<MediaPlayerBase> listener = mListener.promote();
861 if (listener != NULL) {
862 listener->sendEvent(MEDIA_AUDIO_ROUTING_CHANGED, audioIo, deviceId);
863 } else {
864 ALOGW("listener for process %d death is gone", MEDIA_AUDIO_ROUTING_CHANGED);
865 }
866}
867
John Grossmanc795b642012-02-22 15:38:35 -0800868sp<MediaPlayerBase> MediaPlayerService::Client::setDataSource_pre(
869 player_type playerType)
870{
871 ALOGV("player type = %d", playerType);
872
873 // create the right type of player
874 sp<MediaPlayerBase> p = createPlayer(playerType);
875 if (p == NULL) {
876 return p;
877 }
878
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700879 std::vector<DeathNotifier> deathNotifiers;
880
881 // Listen to death of media.extractor service
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700882 sp<IServiceManager> sm = defaultServiceManager();
883 sp<IBinder> binder = sm->getService(String16("media.extractor"));
Marco Nelissen1b5a7ee2016-09-30 13:54:30 -0700884 if (binder == NULL) {
885 ALOGE("extractor service not available");
886 return NULL;
887 }
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700888 deathNotifiers.emplace_back(
889 binder, [l = wp<MediaPlayerBase>(p)]() {
890 sp<MediaPlayerBase> listener = l.promote();
891 if (listener) {
892 ALOGI("media.extractor died. Sending death notification.");
893 listener->sendEvent(MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED,
894 MEDIAEXTRACTOR_PROCESS_DEATH);
895 } else {
896 ALOGW("media.extractor died without a death handler.");
897 }
898 });
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700899
Marco Nelissena0c98412019-03-29 12:10:19 -0700900 {
901 using ::android::hidl::base::V1_0::IBase;
902
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700903 // Listen to death of OMX service
Marco Nelissena0c98412019-03-29 12:10:19 -0700904 {
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700905 sp<IBase> base = ::android::hardware::media::omx::V1_0::
906 IOmx::getService();
907 if (base == nullptr) {
Marco Nelissena0c98412019-03-29 12:10:19 -0700908 ALOGD("OMX service is not available");
909 } else {
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700910 deathNotifiers.emplace_back(
911 base, [l = wp<MediaPlayerBase>(p)]() {
912 sp<MediaPlayerBase> listener = l.promote();
913 if (listener) {
914 ALOGI("OMX service died. "
915 "Sending death notification.");
916 listener->sendEvent(
917 MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED,
918 MEDIACODEC_PROCESS_DEATH);
919 } else {
920 ALOGW("OMX service died without a death handler.");
921 }
922 });
Marco Nelissena0c98412019-03-29 12:10:19 -0700923 }
924 }
925
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700926 // Listen to death of Codec2 services
Marco Nelissena0c98412019-03-29 12:10:19 -0700927 {
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700928 for (std::shared_ptr<Codec2Client> const& client :
929 Codec2Client::CreateFromAllServices()) {
930 sp<IBase> base = client->getBase();
931 deathNotifiers.emplace_back(
932 base, [l = wp<MediaPlayerBase>(p),
933 name = std::string(client->getServiceName())]() {
934 sp<MediaPlayerBase> listener = l.promote();
935 if (listener) {
936 ALOGI("Codec2 service \"%s\" died. "
937 "Sending death notification.",
938 name.c_str());
939 listener->sendEvent(
940 MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED,
941 MEDIACODEC_PROCESS_DEATH);
942 } else {
943 ALOGW("Codec2 service \"%s\" died "
944 "without a death handler.",
945 name.c_str());
946 }
947 });
Marco Nelissene4da6c62019-04-01 15:01:41 -0700948 }
Marco Nelissena0c98412019-03-29 12:10:19 -0700949 }
Marco Nelissen1b5a7ee2016-09-30 13:54:30 -0700950 }
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700951
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700952 Mutex::Autolock lock(mLock);
953
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700954 mDeathNotifiers.clear();
955 mDeathNotifiers.swap(deathNotifiers);
jiabin156c6872017-10-06 09:47:15 -0700956 mAudioDeviceUpdatedListener = new AudioDeviceUpdatedNotifier(p);
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700957
John Grossmanc795b642012-02-22 15:38:35 -0800958 if (!p->hardwareOutput()) {
Svet Ganov33761132021-05-13 22:51:08 +0000959 mAudioOutput = new AudioOutput(mAudioSessionId, mAttributionSource,
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700960 mAudioAttributes, mAudioDeviceUpdatedListener);
John Grossmanc795b642012-02-22 15:38:35 -0800961 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
962 }
963
964 return p;
965}
966
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700967status_t MediaPlayerService::Client::setDataSource_post(
John Grossmanc795b642012-02-22 15:38:35 -0800968 const sp<MediaPlayerBase>& p,
969 status_t status)
970{
971 ALOGV(" setDataSource");
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700972 if (status != OK) {
973 ALOGE(" error: %d", status);
974 return status;
John Grossmanc795b642012-02-22 15:38:35 -0800975 }
976
977 // Set the re-transmission endpoint if one was chosen.
978 if (mRetransmitEndpointValid) {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700979 status = p->setRetransmitEndpoint(&mRetransmitEndpoint);
980 if (status != NO_ERROR) {
981 ALOGE("setRetransmitEndpoint error: %d", status);
John Grossmanc795b642012-02-22 15:38:35 -0800982 }
983 }
984
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700985 if (status == OK) {
986 Mutex::Autolock lock(mLock);
John Grossmanc795b642012-02-22 15:38:35 -0800987 mPlayer = p;
988 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700989 return status;
John Grossmanc795b642012-02-22 15:38:35 -0800990}
991
Andreas Huber2db84552010-01-28 11:19:57 -0800992status_t MediaPlayerService::Client::setDataSource(
Andreas Huber1b86fe02014-01-29 11:13:26 -0800993 const sp<IMediaHTTPService> &httpService,
994 const char *url,
995 const KeyedVector<String8, String8> *headers)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800996{
Steve Block3856b092011-10-20 11:56:00 +0100997 ALOGV("setDataSource(%s)", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800998 if (url == NULL)
999 return UNKNOWN_ERROR;
1000
Dave Burked681bbb2011-08-30 14:39:17 +01001001 if ((strncmp(url, "http://", 7) == 0) ||
1002 (strncmp(url, "https://", 8) == 0) ||
1003 (strncmp(url, "rtsp://", 7) == 0)) {
1004 if (!checkPermission("android.permission.INTERNET")) {
1005 return PERMISSION_DENIED;
1006 }
1007 }
1008
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001009 if (strncmp(url, "content://", 10) == 0) {
1010 // get a filedescriptor for the content Uri and
1011 // pass it to the setDataSource(fd) method
1012
1013 String16 url16(url);
1014 int fd = android::openContentProviderFile(url16);
1015 if (fd < 0)
1016 {
Steve Block29357bc2012-01-06 19:20:56 +00001017 ALOGE("Couldn't open fd for %s", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001018 return UNKNOWN_ERROR;
1019 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001020 status_t status = setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001021 close(fd);
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001022 return mStatus = status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001023 } else {
John Grossman44a7e422012-06-21 17:29:24 -07001024 player_type playerType = MediaPlayerFactory::getPlayerType(this, url);
John Grossmanc795b642012-02-22 15:38:35 -08001025 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
1026 if (p == NULL) {
1027 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001028 }
1029
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001030 return mStatus =
1031 setDataSource_post(
1032 p, p->setDataSource(httpService, url, headers));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001033 }
1034}
1035
1036status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
1037{
Marco Nelissen83b0fd92015-09-16 13:48:07 -07001038 ALOGV("setDataSource fd=%d (%s), offset=%lld, length=%lld",
1039 fd, nameForFd(fd).c_str(), (long long) offset, (long long) length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001040 struct stat sb;
1041 int ret = fstat(fd, &sb);
1042 if (ret != 0) {
Steve Block29357bc2012-01-06 19:20:56 +00001043 ALOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001044 return UNKNOWN_ERROR;
1045 }
1046
Andy Hung833b4752016-04-04 17:15:48 -07001047 ALOGV("st_dev = %llu", static_cast<unsigned long long>(sb.st_dev));
Steve Block3856b092011-10-20 11:56:00 +01001048 ALOGV("st_mode = %u", sb.st_mode);
Mark Salyzyn77342f72014-06-18 16:31:32 -07001049 ALOGV("st_uid = %lu", static_cast<unsigned long>(sb.st_uid));
1050 ALOGV("st_gid = %lu", static_cast<unsigned long>(sb.st_gid));
Andy Hung833b4752016-04-04 17:15:48 -07001051 ALOGV("st_size = %llu", static_cast<unsigned long long>(sb.st_size));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001052
1053 if (offset >= sb.st_size) {
Steve Block29357bc2012-01-06 19:20:56 +00001054 ALOGE("offset error");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001055 return UNKNOWN_ERROR;
1056 }
1057 if (offset + length > sb.st_size) {
1058 length = sb.st_size - offset;
Andy Hung833b4752016-04-04 17:15:48 -07001059 ALOGV("calculated length = %lld", (long long)length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001060 }
1061
John Grossman44a7e422012-06-21 17:29:24 -07001062 player_type playerType = MediaPlayerFactory::getPlayerType(this,
1063 fd,
1064 offset,
1065 length);
John Grossmanc795b642012-02-22 15:38:35 -08001066 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
1067 if (p == NULL) {
1068 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001069 }
1070
1071 // now set data source
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001072 return mStatus = setDataSource_post(p, p->setDataSource(fd, offset, length));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001073}
1074
Andreas Hubere2b10282010-11-23 11:41:34 -08001075status_t MediaPlayerService::Client::setDataSource(
1076 const sp<IStreamSource> &source) {
1077 // create the right type of player
John Grossman44a7e422012-06-21 17:29:24 -07001078 player_type playerType = MediaPlayerFactory::getPlayerType(this, source);
John Grossmanc795b642012-02-22 15:38:35 -08001079 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
Andreas Hubere2b10282010-11-23 11:41:34 -08001080 if (p == NULL) {
1081 return NO_INIT;
1082 }
1083
Andreas Hubere2b10282010-11-23 11:41:34 -08001084 // now set data source
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001085 return mStatus = setDataSource_post(p, p->setDataSource(source));
Andreas Hubere2b10282010-11-23 11:41:34 -08001086}
1087
Chris Watkins99f31602015-03-20 13:06:33 -07001088status_t MediaPlayerService::Client::setDataSource(
1089 const sp<IDataSource> &source) {
Dongwon Kangd91dc5a2017-10-10 00:07:09 -07001090 sp<DataSource> dataSource = CreateDataSourceFromIDataSource(source);
Chris Watkins99f31602015-03-20 13:06:33 -07001091 player_type playerType = MediaPlayerFactory::getPlayerType(this, dataSource);
1092 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
1093 if (p == NULL) {
1094 return NO_INIT;
1095 }
1096 // now set data source
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001097 return mStatus = setDataSource_post(p, p->setDataSource(dataSource));
Chris Watkins99f31602015-03-20 13:06:33 -07001098}
1099
Byeongjo Park28225ab2019-01-24 20:31:19 +09001100status_t MediaPlayerService::Client::setDataSource(
1101 const String8& rtpParams) {
1102 player_type playerType = NU_PLAYER;
1103 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
1104 if (p == NULL) {
1105 return NO_INIT;
1106 }
1107 // now set data source
1108 return mStatus = setDataSource_post(p, p->setDataSource(rtpParams));
1109}
1110
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001111void MediaPlayerService::Client::disconnectNativeWindow_l() {
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001112 if (mConnectedWindow != NULL) {
Chong Zhang181fd9b2017-02-16 15:53:03 -08001113 status_t err = nativeWindowDisconnect(
1114 mConnectedWindow.get(), "disconnectNativeWindow");
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001115
1116 if (err != OK) {
Chong Zhang181fd9b2017-02-16 15:53:03 -08001117 ALOGW("nativeWindowDisconnect returned an error: %s (%d)",
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001118 strerror(-err), err);
1119 }
1120 }
1121 mConnectedWindow.clear();
1122}
1123
Glenn Kasten11731182011-02-08 17:26:17 -08001124status_t MediaPlayerService::Client::setVideoSurfaceTexture(
Andy McFadden484566c2012-12-18 09:46:54 -08001125 const sp<IGraphicBufferProducer>& bufferProducer)
Glenn Kasten11731182011-02-08 17:26:17 -08001126{
Andy McFadden484566c2012-12-18 09:46:54 -08001127 ALOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, bufferProducer.get());
Glenn Kasten11731182011-02-08 17:26:17 -08001128 sp<MediaPlayerBase> p = getPlayer();
1129 if (p == 0) return UNKNOWN_ERROR;
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001130
Marco Nelissenf8880202014-11-14 07:58:25 -08001131 sp<IBinder> binder(IInterface::asBinder(bufferProducer));
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001132 if (mConnectedWindowBinder == binder) {
1133 return OK;
1134 }
1135
1136 sp<ANativeWindow> anw;
Andy McFadden484566c2012-12-18 09:46:54 -08001137 if (bufferProducer != NULL) {
Marco Nelissenee08f7e2013-09-16 13:30:01 -07001138 anw = new Surface(bufferProducer, true /* controlledByApp */);
Chong Zhang181fd9b2017-02-16 15:53:03 -08001139 status_t err = nativeWindowConnect(anw.get(), "setVideoSurfaceTexture");
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001140
1141 if (err != OK) {
Steve Block29357bc2012-01-06 19:20:56 +00001142 ALOGE("setVideoSurfaceTexture failed: %d", err);
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001143 // Note that we must do the reset before disconnecting from the ANW.
1144 // Otherwise queue/dequeue calls could be made on the disconnected
1145 // ANW, which may result in errors.
1146 reset();
1147
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001148 Mutex::Autolock lock(mLock);
1149 disconnectNativeWindow_l();
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001150
1151 return err;
1152 }
1153 }
1154
Andy McFadden484566c2012-12-18 09:46:54 -08001155 // Note that we must set the player's new GraphicBufferProducer before
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001156 // disconnecting the old one. Otherwise queue/dequeue calls could be made
1157 // on the disconnected ANW, which may result in errors.
Andy McFadden484566c2012-12-18 09:46:54 -08001158 status_t err = p->setVideoSurfaceTexture(bufferProducer);
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001159
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001160 mLock.lock();
1161 disconnectNativeWindow_l();
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001162
1163 if (err == OK) {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001164 mConnectedWindow = anw;
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001165 mConnectedWindowBinder = binder;
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001166 mLock.unlock();
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001167 } else {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001168 mLock.unlock();
1169 status_t err = nativeWindowDisconnect(
1170 anw.get(), "disconnectNativeWindow");
1171
1172 if (err != OK) {
1173 ALOGW("nativeWindowDisconnect returned an error: %s (%d)",
1174 strerror(-err), err);
1175 }
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001176 }
1177
1178 return err;
Glenn Kasten11731182011-02-08 17:26:17 -08001179}
1180
Nicolas Catania1d187f12009-05-12 23:25:55 -07001181status_t MediaPlayerService::Client::invoke(const Parcel& request,
1182 Parcel *reply)
1183{
1184 sp<MediaPlayerBase> p = getPlayer();
1185 if (p == NULL) return UNKNOWN_ERROR;
1186 return p->invoke(request, reply);
1187}
1188
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001189// This call doesn't need to access the native player.
1190status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
1191{
1192 status_t status;
nikoa64c8c72009-07-20 15:07:26 -07001193 media::Metadata::Filter allow, drop;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001194
Nicolas Catania48290382009-07-10 13:53:06 -07001195 if (unmarshallFilter(filter, &allow, &status) &&
1196 unmarshallFilter(filter, &drop, &status)) {
1197 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001198
1199 mMetadataAllow = allow;
1200 mMetadataDrop = drop;
1201 }
1202 return status;
1203}
1204
Nicolas Catania48290382009-07-10 13:53:06 -07001205status_t MediaPlayerService::Client::getMetadata(
Mark Salyzyn77342f72014-06-18 16:31:32 -07001206 bool update_only, bool /*apply_filter*/, Parcel *reply)
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001207{
nikoa64c8c72009-07-20 15:07:26 -07001208 sp<MediaPlayerBase> player = getPlayer();
1209 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania48290382009-07-10 13:53:06 -07001210
nikod608a812009-07-16 16:39:53 -07001211 status_t status;
1212 // Placeholder for the return code, updated by the caller.
1213 reply->writeInt32(-1);
1214
nikoa64c8c72009-07-20 15:07:26 -07001215 media::Metadata::Filter ids;
Nicolas Catania48290382009-07-10 13:53:06 -07001216
1217 // We don't block notifications while we fetch the data. We clear
1218 // mMetadataUpdated first so we don't lose notifications happening
1219 // during the rest of this call.
1220 {
1221 Mutex::Autolock lock(mLock);
1222 if (update_only) {
nikod608a812009-07-16 16:39:53 -07001223 ids = mMetadataUpdated;
Nicolas Catania48290382009-07-10 13:53:06 -07001224 }
1225 mMetadataUpdated.clear();
1226 }
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001227
nikoa64c8c72009-07-20 15:07:26 -07001228 media::Metadata metadata(reply);
Nicolas Catania48290382009-07-10 13:53:06 -07001229
nikoa64c8c72009-07-20 15:07:26 -07001230 metadata.appendHeader();
1231 status = player->getMetadata(ids, reply);
nikod608a812009-07-16 16:39:53 -07001232
1233 if (status != OK) {
nikoa64c8c72009-07-20 15:07:26 -07001234 metadata.resetParcel();
Steve Block29357bc2012-01-06 19:20:56 +00001235 ALOGE("getMetadata failed %d", status);
nikod608a812009-07-16 16:39:53 -07001236 return status;
1237 }
1238
1239 // FIXME: Implement filtering on the result. Not critical since
1240 // filtering takes place on the update notifications already. This
1241 // would be when all the metadata are fetch and a filter is set.
1242
nikod608a812009-07-16 16:39:53 -07001243 // Everything is fine, update the metadata length.
nikoa64c8c72009-07-20 15:07:26 -07001244 metadata.updateLength();
nikod608a812009-07-16 16:39:53 -07001245 return OK;
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001246}
1247
Wei Jiad399e7e2016-10-26 15:49:11 -07001248status_t MediaPlayerService::Client::setBufferingSettings(
1249 const BufferingSettings& buffering)
1250{
Wei Jiadc6f3402017-01-09 15:04:18 -08001251 ALOGV("[%d] setBufferingSettings{%s}",
1252 mConnId, buffering.toString().string());
Wei Jiad399e7e2016-10-26 15:49:11 -07001253 sp<MediaPlayerBase> p = getPlayer();
1254 if (p == 0) return UNKNOWN_ERROR;
1255 return p->setBufferingSettings(buffering);
1256}
1257
Wei Jia9bb38032017-03-23 18:00:38 -07001258status_t MediaPlayerService::Client::getBufferingSettings(
Wei Jiad399e7e2016-10-26 15:49:11 -07001259 BufferingSettings* buffering /* nonnull */)
1260{
1261 sp<MediaPlayerBase> p = getPlayer();
1262 // TODO: create mPlayer on demand.
1263 if (p == 0) return UNKNOWN_ERROR;
Wei Jia9bb38032017-03-23 18:00:38 -07001264 status_t ret = p->getBufferingSettings(buffering);
Wei Jiad399e7e2016-10-26 15:49:11 -07001265 if (ret == NO_ERROR) {
Wei Jia9bb38032017-03-23 18:00:38 -07001266 ALOGV("[%d] getBufferingSettings{%s}",
Wei Jiadc6f3402017-01-09 15:04:18 -08001267 mConnId, buffering->toString().string());
Wei Jiad399e7e2016-10-26 15:49:11 -07001268 } else {
Wei Jia9bb38032017-03-23 18:00:38 -07001269 ALOGE("[%d] getBufferingSettings returned %d", mConnId, ret);
Wei Jiad399e7e2016-10-26 15:49:11 -07001270 }
1271 return ret;
1272}
1273
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001274status_t MediaPlayerService::Client::prepareAsync()
1275{
Steve Block3856b092011-10-20 11:56:00 +01001276 ALOGV("[%d] prepareAsync", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001277 sp<MediaPlayerBase> p = getPlayer();
1278 if (p == 0) return UNKNOWN_ERROR;
1279 status_t ret = p->prepareAsync();
1280#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +00001281 ALOGD("start Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001282 if (ret == NO_ERROR) mAntagonizer->start();
1283#endif
1284 return ret;
1285}
1286
1287status_t MediaPlayerService::Client::start()
1288{
Steve Block3856b092011-10-20 11:56:00 +01001289 ALOGV("[%d] start", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001290 sp<MediaPlayerBase> p = getPlayer();
1291 if (p == 0) return UNKNOWN_ERROR;
1292 p->setLooping(mLoop);
1293 return p->start();
1294}
1295
1296status_t MediaPlayerService::Client::stop()
1297{
Steve Block3856b092011-10-20 11:56:00 +01001298 ALOGV("[%d] stop", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001299 sp<MediaPlayerBase> p = getPlayer();
1300 if (p == 0) return UNKNOWN_ERROR;
1301 return p->stop();
1302}
1303
1304status_t MediaPlayerService::Client::pause()
1305{
Steve Block3856b092011-10-20 11:56:00 +01001306 ALOGV("[%d] pause", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001307 sp<MediaPlayerBase> p = getPlayer();
1308 if (p == 0) return UNKNOWN_ERROR;
1309 return p->pause();
1310}
1311
1312status_t MediaPlayerService::Client::isPlaying(bool* state)
1313{
1314 *state = false;
1315 sp<MediaPlayerBase> p = getPlayer();
1316 if (p == 0) return UNKNOWN_ERROR;
1317 *state = p->isPlaying();
Steve Block3856b092011-10-20 11:56:00 +01001318 ALOGV("[%d] isPlaying: %d", mConnId, *state);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001319 return NO_ERROR;
1320}
1321
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001322status_t MediaPlayerService::Client::setPlaybackSettings(const AudioPlaybackRate& rate)
Wei Jia98160162015-02-04 17:01:11 -08001323{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001324 ALOGV("[%d] setPlaybackSettings(%f, %f, %d, %d)",
1325 mConnId, rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Wei Jia98160162015-02-04 17:01:11 -08001326 sp<MediaPlayerBase> p = getPlayer();
1327 if (p == 0) return UNKNOWN_ERROR;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001328 return p->setPlaybackSettings(rate);
1329}
1330
1331status_t MediaPlayerService::Client::getPlaybackSettings(AudioPlaybackRate* rate /* nonnull */)
1332{
1333 sp<MediaPlayerBase> p = getPlayer();
1334 if (p == 0) return UNKNOWN_ERROR;
1335 status_t ret = p->getPlaybackSettings(rate);
1336 if (ret == NO_ERROR) {
1337 ALOGV("[%d] getPlaybackSettings(%f, %f, %d, %d)",
1338 mConnId, rate->mSpeed, rate->mPitch, rate->mFallbackMode, rate->mStretchMode);
1339 } else {
1340 ALOGV("[%d] getPlaybackSettings returned %d", mConnId, ret);
1341 }
1342 return ret;
1343}
1344
1345status_t MediaPlayerService::Client::setSyncSettings(
1346 const AVSyncSettings& sync, float videoFpsHint)
1347{
1348 ALOGV("[%d] setSyncSettings(%u, %u, %f, %f)",
1349 mConnId, sync.mSource, sync.mAudioAdjustMode, sync.mTolerance, videoFpsHint);
1350 sp<MediaPlayerBase> p = getPlayer();
1351 if (p == 0) return UNKNOWN_ERROR;
1352 return p->setSyncSettings(sync, videoFpsHint);
1353}
1354
1355status_t MediaPlayerService::Client::getSyncSettings(
1356 AVSyncSettings* sync /* nonnull */, float* videoFps /* nonnull */)
1357{
1358 sp<MediaPlayerBase> p = getPlayer();
1359 if (p == 0) return UNKNOWN_ERROR;
1360 status_t ret = p->getSyncSettings(sync, videoFps);
1361 if (ret == NO_ERROR) {
1362 ALOGV("[%d] getSyncSettings(%u, %u, %f, %f)",
1363 mConnId, sync->mSource, sync->mAudioAdjustMode, sync->mTolerance, *videoFps);
1364 } else {
1365 ALOGV("[%d] getSyncSettings returned %d", mConnId, ret);
1366 }
1367 return ret;
Wei Jia98160162015-02-04 17:01:11 -08001368}
1369
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001370status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
1371{
Steve Block3856b092011-10-20 11:56:00 +01001372 ALOGV("getCurrentPosition");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001373 sp<MediaPlayerBase> p = getPlayer();
1374 if (p == 0) return UNKNOWN_ERROR;
1375 status_t ret = p->getCurrentPosition(msec);
1376 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001377 ALOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001378 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001379 ALOGE("getCurrentPosition returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001380 }
1381 return ret;
1382}
1383
1384status_t MediaPlayerService::Client::getDuration(int *msec)
1385{
Steve Block3856b092011-10-20 11:56:00 +01001386 ALOGV("getDuration");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001387 sp<MediaPlayerBase> p = getPlayer();
1388 if (p == 0) return UNKNOWN_ERROR;
1389 status_t ret = p->getDuration(msec);
1390 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001391 ALOGV("[%d] getDuration = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001392 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001393 ALOGE("getDuration returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001394 }
1395 return ret;
1396}
1397
Marco Nelissen6b74d672012-02-28 16:07:44 -08001398status_t MediaPlayerService::Client::setNextPlayer(const sp<IMediaPlayer>& player) {
1399 ALOGV("setNextPlayer");
1400 Mutex::Autolock l(mLock);
1401 sp<Client> c = static_cast<Client*>(player.get());
Wei Jia28284122016-08-30 13:49:06 -07001402 if (c != NULL && !mService->hasClient(c)) {
Robert Shihee0a0e32016-08-16 16:50:54 -07001403 return BAD_VALUE;
1404 }
1405
Marco Nelissen6b74d672012-02-28 16:07:44 -08001406 mNextClient = c;
John Grossman5f7e55e2012-08-24 14:47:25 -07001407
1408 if (c != NULL) {
1409 if (mAudioOutput != NULL) {
1410 mAudioOutput->setNextOutput(c->mAudioOutput);
1411 } else if ((mPlayer != NULL) && !mPlayer->hardwareOutput()) {
1412 ALOGE("no current audio output");
1413 }
1414
1415 if ((mPlayer != NULL) && (mNextClient->getPlayer() != NULL)) {
1416 mPlayer->setNextPlayer(mNextClient->getPlayer());
1417 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001418 }
John Grossman5f7e55e2012-08-24 14:47:25 -07001419
Marco Nelissen6b74d672012-02-28 16:07:44 -08001420 return OK;
1421}
1422
Andy Hung9fc8b5c2017-01-24 13:36:48 -08001423VolumeShaper::Status MediaPlayerService::Client::applyVolumeShaper(
1424 const sp<VolumeShaper::Configuration>& configuration,
1425 const sp<VolumeShaper::Operation>& operation) {
1426 // for hardware output, call player instead
1427 ALOGV("Client::applyVolumeShaper(%p)", this);
1428 sp<MediaPlayerBase> p = getPlayer();
1429 {
1430 Mutex::Autolock l(mLock);
1431 if (p != 0 && p->hardwareOutput()) {
1432 // TODO: investigate internal implementation
1433 return VolumeShaper::Status(INVALID_OPERATION);
1434 }
1435 if (mAudioOutput.get() != nullptr) {
1436 return mAudioOutput->applyVolumeShaper(configuration, operation);
1437 }
1438 }
1439 return VolumeShaper::Status(INVALID_OPERATION);
1440}
1441
1442sp<VolumeShaper::State> MediaPlayerService::Client::getVolumeShaperState(int id) {
1443 // for hardware output, call player instead
1444 ALOGV("Client::getVolumeShaperState(%p)", this);
1445 sp<MediaPlayerBase> p = getPlayer();
1446 {
1447 Mutex::Autolock l(mLock);
1448 if (p != 0 && p->hardwareOutput()) {
1449 // TODO: investigate internal implementation.
1450 return nullptr;
1451 }
1452 if (mAudioOutput.get() != nullptr) {
1453 return mAudioOutput->getVolumeShaperState(id);
1454 }
1455 }
1456 return nullptr;
1457}
1458
Wei Jiac5de0912016-11-18 10:22:14 -08001459status_t MediaPlayerService::Client::seekTo(int msec, MediaPlayerSeekMode mode)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001460{
Wei Jiac5de0912016-11-18 10:22:14 -08001461 ALOGV("[%d] seekTo(%d, %d)", mConnId, msec, mode);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001462 sp<MediaPlayerBase> p = getPlayer();
1463 if (p == 0) return UNKNOWN_ERROR;
Wei Jiac5de0912016-11-18 10:22:14 -08001464 return p->seekTo(msec, mode);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001465}
1466
1467status_t MediaPlayerService::Client::reset()
1468{
Steve Block3856b092011-10-20 11:56:00 +01001469 ALOGV("[%d] reset", mConnId);
John Grossmanc795b642012-02-22 15:38:35 -08001470 mRetransmitEndpointValid = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001471 sp<MediaPlayerBase> p = getPlayer();
1472 if (p == 0) return UNKNOWN_ERROR;
1473 return p->reset();
1474}
1475
Wei Jia52c28512017-09-13 18:17:51 -07001476status_t MediaPlayerService::Client::notifyAt(int64_t mediaTimeUs)
1477{
1478 ALOGV("[%d] notifyAt(%lld)", mConnId, (long long)mediaTimeUs);
1479 sp<MediaPlayerBase> p = getPlayer();
1480 if (p == 0) return UNKNOWN_ERROR;
1481 return p->notifyAt(mediaTimeUs);
1482}
1483
Glenn Kastenfff6d712012-01-12 16:38:12 -08001484status_t MediaPlayerService::Client::setAudioStreamType(audio_stream_type_t type)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001485{
Steve Block3856b092011-10-20 11:56:00 +01001486 ALOGV("[%d] setAudioStreamType(%d)", mConnId, type);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001487 // TODO: for hardware output, call player instead
1488 Mutex::Autolock l(mLock);
1489 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1490 return NO_ERROR;
1491}
1492
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001493status_t MediaPlayerService::Client::setAudioAttributes_l(const Parcel &parcel)
1494{
1495 if (mAudioAttributes != NULL) { free(mAudioAttributes); }
1496 mAudioAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001497 if (mAudioAttributes == NULL) {
1498 return NO_MEMORY;
1499 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001500 unmarshallAudioAttributes(parcel, mAudioAttributes);
1501
1502 ALOGV("setAudioAttributes_l() usage=%d content=%d flags=0x%x tags=%s",
1503 mAudioAttributes->usage, mAudioAttributes->content_type, mAudioAttributes->flags,
1504 mAudioAttributes->tags);
1505
1506 if (mAudioOutput != 0) {
1507 mAudioOutput->setAudioAttributes(mAudioAttributes);
1508 }
1509 return NO_ERROR;
1510}
1511
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001512status_t MediaPlayerService::Client::setLooping(int loop)
1513{
Steve Block3856b092011-10-20 11:56:00 +01001514 ALOGV("[%d] setLooping(%d)", mConnId, loop);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001515 mLoop = loop;
1516 sp<MediaPlayerBase> p = getPlayer();
1517 if (p != 0) return p->setLooping(loop);
1518 return NO_ERROR;
1519}
1520
1521status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1522{
Steve Block3856b092011-10-20 11:56:00 +01001523 ALOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
John Grossman761defc2012-02-09 15:09:05 -08001524
1525 // for hardware output, call player instead
1526 sp<MediaPlayerBase> p = getPlayer();
1527 {
1528 Mutex::Autolock l(mLock);
1529 if (p != 0 && p->hardwareOutput()) {
1530 MediaPlayerHWInterface* hwp =
1531 reinterpret_cast<MediaPlayerHWInterface*>(p.get());
1532 return hwp->setVolume(leftVolume, rightVolume);
1533 } else {
1534 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1535 return NO_ERROR;
1536 }
1537 }
1538
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001539 return NO_ERROR;
1540}
1541
Eric Laurent2beeb502010-07-16 07:43:46 -07001542status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1543{
Steve Block3856b092011-10-20 11:56:00 +01001544 ALOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
Eric Laurent2beeb502010-07-16 07:43:46 -07001545 Mutex::Autolock l(mLock);
1546 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1547 return NO_ERROR;
1548}
1549
1550status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1551{
Steve Block3856b092011-10-20 11:56:00 +01001552 ALOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
Eric Laurent2beeb502010-07-16 07:43:46 -07001553 Mutex::Autolock l(mLock);
1554 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1555 return NO_ERROR;
1556}
Nicolas Catania48290382009-07-10 13:53:06 -07001557
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001558status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
Steve Block3856b092011-10-20 11:56:00 +01001559 ALOGV("[%d] setParameter(%d)", mConnId, key);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001560 switch (key) {
1561 case KEY_PARAMETER_AUDIO_ATTRIBUTES:
1562 {
1563 Mutex::Autolock l(mLock);
1564 return setAudioAttributes_l(request);
1565 }
1566 default:
1567 sp<MediaPlayerBase> p = getPlayer();
1568 if (p == 0) { return UNKNOWN_ERROR; }
1569 return p->setParameter(key, request);
1570 }
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001571}
1572
1573status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
Steve Block3856b092011-10-20 11:56:00 +01001574 ALOGV("[%d] getParameter(%d)", mConnId, key);
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001575 sp<MediaPlayerBase> p = getPlayer();
1576 if (p == 0) return UNKNOWN_ERROR;
1577 return p->getParameter(key, reply);
1578}
1579
John Grossmanc795b642012-02-22 15:38:35 -08001580status_t MediaPlayerService::Client::setRetransmitEndpoint(
1581 const struct sockaddr_in* endpoint) {
1582
1583 if (NULL != endpoint) {
1584 uint32_t a = ntohl(endpoint->sin_addr.s_addr);
1585 uint16_t p = ntohs(endpoint->sin_port);
1586 ALOGV("[%d] setRetransmitEndpoint(%u.%u.%u.%u:%hu)", mConnId,
1587 (a >> 24), (a >> 16) & 0xFF, (a >> 8) & 0xFF, (a & 0xFF), p);
1588 } else {
1589 ALOGV("[%d] setRetransmitEndpoint = <none>", mConnId);
1590 }
1591
1592 sp<MediaPlayerBase> p = getPlayer();
1593
1594 // Right now, the only valid time to set a retransmit endpoint is before
1595 // player selection has been made (since the presence or absence of a
1596 // retransmit endpoint is going to determine which player is selected during
1597 // setDataSource).
1598 if (p != 0) return INVALID_OPERATION;
1599
1600 if (NULL != endpoint) {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001601 Mutex::Autolock lock(mLock);
John Grossmanc795b642012-02-22 15:38:35 -08001602 mRetransmitEndpoint = *endpoint;
1603 mRetransmitEndpointValid = true;
1604 } else {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001605 Mutex::Autolock lock(mLock);
John Grossmanc795b642012-02-22 15:38:35 -08001606 mRetransmitEndpointValid = false;
1607 }
1608
1609 return NO_ERROR;
1610}
1611
John Grossman44a7e422012-06-21 17:29:24 -07001612status_t MediaPlayerService::Client::getRetransmitEndpoint(
1613 struct sockaddr_in* endpoint)
1614{
1615 if (NULL == endpoint)
1616 return BAD_VALUE;
1617
1618 sp<MediaPlayerBase> p = getPlayer();
1619
1620 if (p != NULL)
1621 return p->getRetransmitEndpoint(endpoint);
1622
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001623 Mutex::Autolock lock(mLock);
John Grossman44a7e422012-06-21 17:29:24 -07001624 if (!mRetransmitEndpointValid)
1625 return NO_INIT;
1626
1627 *endpoint = mRetransmitEndpoint;
1628
1629 return NO_ERROR;
1630}
1631
Gloria Wangb483c472011-04-11 17:23:27 -07001632void MediaPlayerService::Client::notify(
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001633 int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001634{
James Dongb8a98252012-08-26 16:13:03 -07001635 sp<IMediaPlayerClient> c;
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001636 sp<Client> nextClient;
1637 status_t errStartNext = NO_ERROR;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001638 {
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001639 Mutex::Autolock l(mLock);
1640 c = mClient;
1641 if (msg == MEDIA_PLAYBACK_COMPLETE && mNextClient != NULL) {
1642 nextClient = mNextClient;
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001643
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001644 if (mAudioOutput != NULL)
1645 mAudioOutput->switchToNextOutput();
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001646
1647 errStartNext = nextClient->start();
1648 }
1649 }
1650
1651 if (nextClient != NULL) {
1652 sp<IMediaPlayerClient> nc;
1653 {
1654 Mutex::Autolock l(nextClient->mLock);
1655 nc = nextClient->mClient;
1656 }
1657 if (nc != NULL) {
1658 if (errStartNext == NO_ERROR) {
1659 nc->notify(MEDIA_INFO, MEDIA_INFO_STARTED_AS_NEXT, 0, obj);
1660 } else {
1661 nc->notify(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN , 0, obj);
1662 ALOGE("gapless:start playback for next track failed, err(%d)", errStartNext);
Wei Jia2afac0c2016-01-07 12:13:07 -08001663 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001664 }
1665 }
1666
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001667 if (MEDIA_INFO == msg &&
Nicolas Catania48290382009-07-10 13:53:06 -07001668 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikoa64c8c72009-07-20 15:07:26 -07001669 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania48290382009-07-10 13:53:06 -07001670
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001671 if(shouldDropMetadata(metadata_type)) {
Nicolas Catania48290382009-07-10 13:53:06 -07001672 return;
1673 }
1674
1675 // Update the list of metadata that have changed. getMetadata
1676 // also access mMetadataUpdated and clears it.
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001677 addNewMetadataUpdate(metadata_type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001678 }
James Dongb8a98252012-08-26 16:13:03 -07001679
1680 if (c != NULL) {
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001681 ALOGV("[%d] notify (%d, %d, %d)", mConnId, msg, ext1, ext2);
James Dongb8a98252012-08-26 16:13:03 -07001682 c->notify(msg, ext1, ext2, obj);
1683 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001684}
1685
Nicolas Catania48290382009-07-10 13:53:06 -07001686
nikoa64c8c72009-07-20 15:07:26 -07001687bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001688{
Nicolas Catania48290382009-07-10 13:53:06 -07001689 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001690
Nicolas Catania48290382009-07-10 13:53:06 -07001691 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001692 return true;
1693 }
1694
Nicolas Catania48290382009-07-10 13:53:06 -07001695 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001696 return false;
Nicolas Catania48290382009-07-10 13:53:06 -07001697 } else {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001698 return true;
1699 }
1700}
1701
Nicolas Catania48290382009-07-10 13:53:06 -07001702
nikoa64c8c72009-07-20 15:07:26 -07001703void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania48290382009-07-10 13:53:06 -07001704 Mutex::Autolock lock(mLock);
1705 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1706 mMetadataUpdated.add(metadata_type);
1707 }
1708}
1709
Hassan Shojaniacefac142017-02-06 21:02:02 -08001710// Modular DRM
1711status_t MediaPlayerService::Client::prepareDrm(const uint8_t uuid[16],
1712 const Vector<uint8_t>& drmSessionId)
1713{
1714 ALOGV("[%d] prepareDrm", mConnId);
1715 sp<MediaPlayerBase> p = getPlayer();
1716 if (p == 0) return UNKNOWN_ERROR;
1717
1718 status_t ret = p->prepareDrm(uuid, drmSessionId);
1719 ALOGV("prepareDrm ret: %d", ret);
1720
1721 return ret;
1722}
1723
1724status_t MediaPlayerService::Client::releaseDrm()
1725{
1726 ALOGV("[%d] releaseDrm", mConnId);
1727 sp<MediaPlayerBase> p = getPlayer();
1728 if (p == 0) return UNKNOWN_ERROR;
1729
1730 status_t ret = p->releaseDrm();
1731 ALOGV("releaseDrm ret: %d", ret);
1732
1733 return ret;
1734}
1735
jiabin156c6872017-10-06 09:47:15 -07001736status_t MediaPlayerService::Client::setOutputDevice(audio_port_handle_t deviceId)
1737{
1738 ALOGV("[%d] setOutputDevice", mConnId);
1739 {
1740 Mutex::Autolock l(mLock);
1741 if (mAudioOutput.get() != nullptr) {
1742 return mAudioOutput->setOutputDevice(deviceId);
1743 }
1744 }
1745 return NO_INIT;
1746}
1747
1748status_t MediaPlayerService::Client::getRoutedDeviceId(audio_port_handle_t* deviceId)
1749{
1750 ALOGV("[%d] getRoutedDeviceId", mConnId);
1751 {
1752 Mutex::Autolock l(mLock);
1753 if (mAudioOutput.get() != nullptr) {
1754 return mAudioOutput->getRoutedDeviceId(deviceId);
1755 }
1756 }
1757 return NO_INIT;
1758}
1759
1760status_t MediaPlayerService::Client::enableAudioDeviceCallback(bool enabled)
1761{
1762 ALOGV("[%d] enableAudioDeviceCallback, %d", mConnId, enabled);
1763 {
1764 Mutex::Autolock l(mLock);
1765 if (mAudioOutput.get() != nullptr) {
1766 return mAudioOutput->enableAudioDeviceCallback(enabled);
1767 }
1768 }
1769 return NO_INIT;
1770}
1771
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001772#if CALLBACK_ANTAGONIZER
1773const int Antagonizer::interval = 10000; // 10 msecs
1774
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001775Antagonizer::Antagonizer(const sp<MediaPlayerBase::Listener> &listener) :
1776 mExit(false), mActive(false), mListener(listener)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001777{
1778 createThread(callbackThread, this);
1779}
1780
1781void Antagonizer::kill()
1782{
1783 Mutex::Autolock _l(mLock);
1784 mActive = false;
1785 mExit = true;
1786 mCondition.wait(mLock);
1787}
1788
1789int Antagonizer::callbackThread(void* user)
1790{
Steve Blockb8a80522011-12-20 16:23:08 +00001791 ALOGD("Antagonizer started");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001792 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1793 while (!p->mExit) {
1794 if (p->mActive) {
Steve Block3856b092011-10-20 11:56:00 +01001795 ALOGV("send event");
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001796 p->mListener->notify(0, 0, 0, 0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001797 }
1798 usleep(interval);
1799 }
1800 Mutex::Autolock _l(p->mLock);
1801 p->mCondition.signal();
Steve Blockb8a80522011-12-20 16:23:08 +00001802 ALOGD("Antagonizer stopped");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001803 return 0;
1804}
1805#endif
1806
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001807#undef LOG_TAG
1808#define LOG_TAG "AudioSink"
Svet Ganov33761132021-05-13 22:51:08 +00001809MediaPlayerService::AudioOutput::AudioOutput(audio_session_t sessionId,
1810 const AttributionSourceState& attributionSource, const audio_attributes_t* attr,
1811 const sp<AudioSystem::AudioDeviceCallback>& deviceCallback)
Andreas Huber20111aa2009-07-14 16:56:47 -07001812 : mCallback(NULL),
Eric Laurenta514bdb2010-06-21 09:27:30 -07001813 mCallbackCookie(NULL),
Marco Nelissen6b74d672012-02-28 16:07:44 -08001814 mCallbackData(NULL),
Andy Hungd1c74342015-07-07 16:54:23 -07001815 mStreamType(AUDIO_STREAM_MUSIC),
Andy Hungd1c74342015-07-07 16:54:23 -07001816 mLeftVolume(1.0),
1817 mRightVolume(1.0),
1818 mPlaybackRate(AUDIO_PLAYBACK_RATE_DEFAULT),
1819 mSampleRateHz(0),
1820 mMsecsPerFrame(0),
1821 mFrameSize(0),
Eric Laurent1948eb32012-04-13 16:50:19 -07001822 mSessionId(sessionId),
Svet Ganov33761132021-05-13 22:51:08 +00001823 mAttributionSource(attributionSource),
Andy Hungd1c74342015-07-07 16:54:23 -07001824 mSendLevel(0.0),
1825 mAuxEffectId(0),
Andy Hung4ef88d72017-02-21 19:47:53 -08001826 mFlags(AUDIO_OUTPUT_FLAG_NONE),
jiabin156c6872017-10-06 09:47:15 -07001827 mVolumeHandler(new media::VolumeHandler()),
1828 mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE),
jiabin161b64f2017-11-17 09:31:48 -08001829 mRoutedDeviceId(AUDIO_PORT_HANDLE_NONE),
jiabin156c6872017-10-06 09:47:15 -07001830 mDeviceCallbackEnabled(false),
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001831 mDeviceCallback(deviceCallback)
Andy Hungd1c74342015-07-07 16:54:23 -07001832{
Steve Block3856b092011-10-20 11:56:00 +01001833 ALOGV("AudioOutput(%d)", sessionId);
Eric Laurent43562692015-07-15 16:49:07 -07001834 if (attr != NULL) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001835 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1836 if (mAttributes != NULL) {
1837 memcpy(mAttributes, attr, sizeof(audio_attributes_t));
François Gaffie58d4be52018-11-06 15:30:12 +01001838 mStreamType = AudioSystem::attributesToStreamType(*attr);
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001839 }
1840 } else {
1841 mAttributes = NULL;
Eric Laurent43562692015-07-15 16:49:07 -07001842 }
1843
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001844 setMinBufferCount();
1845}
1846
1847MediaPlayerService::AudioOutput::~AudioOutput()
1848{
1849 close();
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001850 free(mAttributes);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001851}
1852
Andy Hungd1c74342015-07-07 16:54:23 -07001853//static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001854void MediaPlayerService::AudioOutput::setMinBufferCount()
1855{
Roman Kiryanova3f34462021-03-10 16:17:24 -08001856 if (property_get_bool("ro.boot.qemu", false)) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001857 mIsOnEmulator = true;
1858 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1859 }
1860}
1861
Andy Hungd1c74342015-07-07 16:54:23 -07001862// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001863bool MediaPlayerService::AudioOutput::isOnEmulator()
1864{
Andy Hungd1c74342015-07-07 16:54:23 -07001865 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001866 return mIsOnEmulator;
1867}
1868
Andy Hungd1c74342015-07-07 16:54:23 -07001869// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001870int MediaPlayerService::AudioOutput::getMinBufferCount()
1871{
Andy Hungd1c74342015-07-07 16:54:23 -07001872 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001873 return mMinBufferCount;
1874}
1875
1876ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1877{
Andy Hungd1c74342015-07-07 16:54:23 -07001878 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001879 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001880 return mTrack->frameCount() * mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001881}
1882
1883ssize_t MediaPlayerService::AudioOutput::frameCount() const
1884{
Andy Hungd1c74342015-07-07 16:54:23 -07001885 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001886 if (mTrack == 0) return NO_INIT;
1887 return mTrack->frameCount();
1888}
1889
1890ssize_t MediaPlayerService::AudioOutput::channelCount() const
1891{
Andy Hungd1c74342015-07-07 16:54:23 -07001892 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001893 if (mTrack == 0) return NO_INIT;
1894 return mTrack->channelCount();
1895}
1896
1897ssize_t MediaPlayerService::AudioOutput::frameSize() const
1898{
Andy Hungd1c74342015-07-07 16:54:23 -07001899 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001900 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001901 return mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001902}
1903
1904uint32_t MediaPlayerService::AudioOutput::latency () const
1905{
Andy Hungd1c74342015-07-07 16:54:23 -07001906 Mutex::Autolock lock(mLock);
Eric Laurentdb354e52012-03-05 17:27:11 -08001907 if (mTrack == 0) return 0;
1908 return mTrack->latency();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001909}
1910
1911float MediaPlayerService::AudioOutput::msecsPerFrame() const
1912{
Andy Hungd1c74342015-07-07 16:54:23 -07001913 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001914 return mMsecsPerFrame;
1915}
1916
Marco Nelissen4110c102012-03-29 09:31:28 -07001917status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position) const
Eric Laurent342e9cf2010-01-19 17:37:09 -08001918{
Andy Hungd1c74342015-07-07 16:54:23 -07001919 Mutex::Autolock lock(mLock);
Eric Laurent342e9cf2010-01-19 17:37:09 -08001920 if (mTrack == 0) return NO_INIT;
1921 return mTrack->getPosition(position);
1922}
1923
Lajos Molnar06ad1522014-08-28 07:27:44 -07001924status_t MediaPlayerService::AudioOutput::getTimestamp(AudioTimestamp &ts) const
1925{
Andy Hungd1c74342015-07-07 16:54:23 -07001926 Mutex::Autolock lock(mLock);
Lajos Molnar06ad1522014-08-28 07:27:44 -07001927 if (mTrack == 0) return NO_INIT;
1928 return mTrack->getTimestamp(ts);
1929}
1930
Wei Jiac4ac8172015-10-21 10:35:48 -07001931// TODO: Remove unnecessary calls to getPlayedOutDurationUs()
1932// as it acquires locks and may query the audio driver.
1933//
1934// Some calls could conceivably retrieve extrapolated data instead of
1935// accessing getTimestamp() or getPosition() every time a data buffer with
1936// a media time is received.
1937//
1938// Calculate duration of played samples if played at normal rate (i.e., 1.0).
1939int64_t MediaPlayerService::AudioOutput::getPlayedOutDurationUs(int64_t nowUs) const
1940{
1941 Mutex::Autolock lock(mLock);
1942 if (mTrack == 0 || mSampleRateHz == 0) {
Wei Jia213f4902015-10-22 08:55:25 -07001943 return 0;
Wei Jiac4ac8172015-10-21 10:35:48 -07001944 }
1945
1946 uint32_t numFramesPlayed;
Andy Hung5d313802016-10-10 15:09:39 -07001947 int64_t numFramesPlayedAtUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001948 AudioTimestamp ts;
Wei Jiac4ac8172015-10-21 10:35:48 -07001949
1950 status_t res = mTrack->getTimestamp(ts);
1951 if (res == OK) { // case 1: mixing audio tracks and offloaded tracks.
1952 numFramesPlayed = ts.mPosition;
Andy Hung5d313802016-10-10 15:09:39 -07001953 numFramesPlayedAtUs = ts.mTime.tv_sec * 1000000LL + ts.mTime.tv_nsec / 1000;
1954 //ALOGD("getTimestamp: OK %d %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001955 } else if (res == WOULD_BLOCK) { // case 2: transitory state on start of a new track
1956 numFramesPlayed = 0;
Andy Hung5d313802016-10-10 15:09:39 -07001957 numFramesPlayedAtUs = nowUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001958 //ALOGD("getTimestamp: WOULD_BLOCK %d %lld",
Andy Hung5d313802016-10-10 15:09:39 -07001959 // numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001960 } else { // case 3: transitory at new track or audio fast tracks.
1961 res = mTrack->getPosition(&numFramesPlayed);
1962 CHECK_EQ(res, (status_t)OK);
Andy Hung5d313802016-10-10 15:09:39 -07001963 numFramesPlayedAtUs = nowUs;
1964 numFramesPlayedAtUs += 1000LL * mTrack->latency() / 2; /* XXX */
1965 //ALOGD("getPosition: %u %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001966 }
1967
1968 // CHECK_EQ(numFramesPlayed & (1 << 31), 0); // can't be negative until 12.4 hrs, test
1969 // TODO: remove the (int32_t) casting below as it may overflow at 12.4 hours.
1970 int64_t durationUs = (int64_t)((int32_t)numFramesPlayed * 1000000LL / mSampleRateHz)
Andy Hung5d313802016-10-10 15:09:39 -07001971 + nowUs - numFramesPlayedAtUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001972 if (durationUs < 0) {
1973 // Occurs when numFramesPlayed position is very small and the following:
1974 // (1) In case 1, the time nowUs is computed before getTimestamp() is called and
Andy Hung5d313802016-10-10 15:09:39 -07001975 // numFramesPlayedAtUs is greater than nowUs by time more than numFramesPlayed.
Wei Jiac4ac8172015-10-21 10:35:48 -07001976 // (2) In case 3, using getPosition and adding mAudioSink->latency() to
Andy Hung5d313802016-10-10 15:09:39 -07001977 // numFramesPlayedAtUs, by a time amount greater than numFramesPlayed.
Wei Jiac4ac8172015-10-21 10:35:48 -07001978 //
1979 // Both of these are transitory conditions.
1980 ALOGV("getPlayedOutDurationUs: negative duration %lld set to zero", (long long)durationUs);
1981 durationUs = 0;
1982 }
1983 ALOGV("getPlayedOutDurationUs(%lld) nowUs(%lld) frames(%u) framesAt(%lld)",
Andy Hung5d313802016-10-10 15:09:39 -07001984 (long long)durationUs, (long long)nowUs,
1985 numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001986 return durationUs;
1987}
1988
Marco Nelissen4110c102012-03-29 09:31:28 -07001989status_t MediaPlayerService::AudioOutput::getFramesWritten(uint32_t *frameswritten) const
1990{
Andy Hungd1c74342015-07-07 16:54:23 -07001991 Mutex::Autolock lock(mLock);
Marco Nelissen4110c102012-03-29 09:31:28 -07001992 if (mTrack == 0) return NO_INIT;
Andy Hung2f6e73d2016-04-08 12:12:58 -07001993 ExtendedTimestamp ets;
1994 status_t status = mTrack->getTimestamp(&ets);
1995 if (status == OK || status == WOULD_BLOCK) {
1996 *frameswritten = (uint32_t)ets.mPosition[ExtendedTimestamp::LOCATION_CLIENT];
1997 }
1998 return status;
Marco Nelissen4110c102012-03-29 09:31:28 -07001999}
2000
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002001status_t MediaPlayerService::AudioOutput::setParameters(const String8& keyValuePairs)
2002{
Andy Hungd1c74342015-07-07 16:54:23 -07002003 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002004 if (mTrack == 0) return NO_INIT;
2005 return mTrack->setParameters(keyValuePairs);
2006}
2007
2008String8 MediaPlayerService::AudioOutput::getParameters(const String8& keys)
2009{
Andy Hungd1c74342015-07-07 16:54:23 -07002010 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002011 if (mTrack == 0) return String8::empty();
2012 return mTrack->getParameters(keys);
2013}
2014
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07002015void MediaPlayerService::AudioOutput::setAudioAttributes(const audio_attributes_t * attributes) {
Andy Hungd1c74342015-07-07 16:54:23 -07002016 Mutex::Autolock lock(mLock);
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07002017 if (attributes == NULL) {
2018 free(mAttributes);
2019 mAttributes = NULL;
2020 } else {
2021 if (mAttributes == NULL) {
2022 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
2023 }
2024 memcpy(mAttributes, attributes, sizeof(audio_attributes_t));
François Gaffie58d4be52018-11-06 15:30:12 +01002025 mStreamType = AudioSystem::attributesToStreamType(*attributes);
Eric Laurent43562692015-07-15 16:49:07 -07002026 }
2027}
2028
2029void MediaPlayerService::AudioOutput::setAudioStreamType(audio_stream_type_t streamType)
2030{
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07002031 Mutex::Autolock lock(mLock);
Eric Laurent43562692015-07-15 16:49:07 -07002032 // do not allow direct stream type modification if attributes have been set
2033 if (mAttributes == NULL) {
2034 mStreamType = streamType;
2035 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07002036}
2037
Andy Hungd1c74342015-07-07 16:54:23 -07002038void MediaPlayerService::AudioOutput::deleteRecycledTrack_l()
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002039{
Andy Hungd1c74342015-07-07 16:54:23 -07002040 ALOGV("deleteRecycledTrack_l");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002041 if (mRecycledTrack != 0) {
2042
2043 if (mCallbackData != NULL) {
2044 mCallbackData->setOutput(NULL);
2045 mCallbackData->endTrackSwitch();
2046 }
2047
2048 if ((mRecycledTrack->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) {
Andy Hunge13f8a62016-03-30 14:20:42 -07002049 int32_t msec = 0;
2050 if (!mRecycledTrack->stopped()) { // check if active
2051 (void)mRecycledTrack->pendingDuration(&msec);
2052 }
2053 mRecycledTrack->stop(); // ensure full data drain
2054 ALOGD("deleting recycled track, waiting for data drain (%d msec)", msec);
2055 if (msec > 0) {
2056 static const int32_t WAIT_LIMIT_MS = 3000;
2057 if (msec > WAIT_LIMIT_MS) {
2058 msec = WAIT_LIMIT_MS;
2059 }
2060 usleep(msec * 1000LL);
2061 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002062 }
2063 // An offloaded track isn't flushed because the STREAM_END is reported
2064 // slightly prematurely to allow time for the gapless track switch
2065 // but this means that if we decide not to recycle the track there
2066 // could be a small amount of residual data still playing. We leave
2067 // AudioFlinger to drain the track.
2068
2069 mRecycledTrack.clear();
Andy Hungd1c74342015-07-07 16:54:23 -07002070 close_l();
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002071 mCallbackData.clear();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002072 }
2073}
2074
Andy Hungd1c74342015-07-07 16:54:23 -07002075void MediaPlayerService::AudioOutput::close_l()
2076{
2077 mTrack.clear();
2078}
2079
Andreas Huber20111aa2009-07-14 16:56:47 -07002080status_t MediaPlayerService::AudioOutput::open(
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08002081 uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
2082 audio_format_t format, int bufferCount,
Eric Laurent1948eb32012-04-13 16:50:19 -07002083 AudioCallback cb, void *cookie,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002084 audio_output_flags_t flags,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07002085 const audio_offload_info_t *offloadInfo,
Andy Hung179652e2015-05-31 22:49:46 -07002086 bool doNotReconnect,
2087 uint32_t suggestedFrameCount)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002088{
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002089 ALOGV("open(%u, %d, 0x%x, 0x%x, %d, %d 0x%x)", sampleRate, channelCount, channelMask,
2090 format, bufferCount, mSessionId, flags);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002091
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002092 // offloading is only supported in callback mode for now.
2093 // offloadInfo must be present if offload flag is set
2094 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) &&
2095 ((cb == NULL) || (offloadInfo == NULL))) {
2096 return BAD_VALUE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002097 }
2098
Andy Hung179652e2015-05-31 22:49:46 -07002099 // compute frame count for the AudioTrack internal buffer
2100 size_t frameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002101 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
2102 frameCount = 0; // AudioTrack will get frame count from AudioFlinger
2103 } else {
Andy Hung179652e2015-05-31 22:49:46 -07002104 // try to estimate the buffer processing fetch size from AudioFlinger.
2105 // framesPerBuffer is approximate and generally correct, except when it's not :-).
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002106 uint32_t afSampleRate;
2107 size_t afFrameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002108 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
2109 return NO_INIT;
2110 }
2111 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
2112 return NO_INIT;
2113 }
Ben Romberger259fb462018-08-07 17:58:53 -07002114 if (afSampleRate == 0) {
2115 return NO_INIT;
2116 }
Andy Hung179652e2015-05-31 22:49:46 -07002117 const size_t framesPerBuffer =
2118 (unsigned long long)sampleRate * afFrameCount / afSampleRate;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002119
Andy Hung179652e2015-05-31 22:49:46 -07002120 if (bufferCount == 0) {
Ben Romberger259fb462018-08-07 17:58:53 -07002121 if (framesPerBuffer == 0) {
2122 return NO_INIT;
2123 }
Andy Hung179652e2015-05-31 22:49:46 -07002124 // use suggestedFrameCount
2125 bufferCount = (suggestedFrameCount + framesPerBuffer - 1) / framesPerBuffer;
2126 }
2127 // Check argument bufferCount against the mininum buffer count
2128 if (bufferCount != 0 && bufferCount < mMinBufferCount) {
2129 ALOGV("bufferCount (%d) increased to %d", bufferCount, mMinBufferCount);
2130 bufferCount = mMinBufferCount;
2131 }
2132 // if frameCount is 0, then AudioTrack will get frame count from AudioFlinger
2133 // which will be the minimum size permitted.
2134 frameCount = bufferCount * framesPerBuffer;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002135 }
Andreas Huber20111aa2009-07-14 16:56:47 -07002136
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08002137 if (channelMask == CHANNEL_MASK_USE_CHANNEL_ORDER) {
Glenn Kastenab334fd2012-03-14 12:56:06 -07002138 channelMask = audio_channel_out_mask_from_count(channelCount);
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08002139 if (0 == channelMask) {
2140 ALOGE("open() error, can\'t derive mask for %d audio channels", channelCount);
2141 return NO_INIT;
2142 }
2143 }
Eric Laurent1948eb32012-04-13 16:50:19 -07002144
Andy Hungd1c74342015-07-07 16:54:23 -07002145 Mutex::Autolock lock(mLock);
Andy Hung179652e2015-05-31 22:49:46 -07002146 mCallback = cb;
2147 mCallbackCookie = cookie;
2148
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002149 // Check whether we can recycle the track
2150 bool reuse = false;
2151 bool bothOffloaded = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07002152
Glenn Kasten2799d742013-05-30 14:33:29 -07002153 if (mRecycledTrack != 0) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002154 // check whether we are switching between two offloaded tracks
2155 bothOffloaded = (flags & mRecycledTrack->getFlags()
2156 & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0;
Marco Nelissen67295b52012-06-11 14:52:53 -07002157
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002158 // check if the existing track can be reused as-is, or if a new track needs to be created.
2159 reuse = true;
2160
Marco Nelissen67295b52012-06-11 14:52:53 -07002161 if ((mCallbackData == NULL && mCallback != NULL) ||
2162 (mCallbackData != NULL && mCallback == NULL)) {
2163 // recycled track uses callbacks but the caller wants to use writes, or vice versa
2164 ALOGV("can't chain callback and write");
2165 reuse = false;
2166 } else if ((mRecycledTrack->getSampleRate() != sampleRate) ||
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002167 (mRecycledTrack->channelCount() != (uint32_t)channelCount) ) {
2168 ALOGV("samplerate, channelcount differ: %u/%u Hz, %u/%d ch",
Marco Nelissen67295b52012-06-11 14:52:53 -07002169 mRecycledTrack->getSampleRate(), sampleRate,
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002170 mRecycledTrack->channelCount(), channelCount);
Marco Nelissen67295b52012-06-11 14:52:53 -07002171 reuse = false;
2172 } else if (flags != mFlags) {
2173 ALOGV("output flags differ %08x/%08x", flags, mFlags);
2174 reuse = false;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002175 } else if (mRecycledTrack->format() != format) {
2176 reuse = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07002177 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002178 } else {
2179 ALOGV("no track available to recycle");
2180 }
2181
2182 ALOGV_IF(bothOffloaded, "both tracks offloaded");
2183
2184 // If we can't recycle and both tracks are offloaded
2185 // we must close the previous output before opening a new one
2186 if (bothOffloaded && !reuse) {
2187 ALOGV("both offloaded and not recycling");
Andy Hungd1c74342015-07-07 16:54:23 -07002188 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002189 }
2190
2191 sp<AudioTrack> t;
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002192 sp<CallbackData> newcbd;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002193
2194 // We don't attempt to create a new track if we are recycling an
2195 // offloaded track. But, if we are recycling a non-offloaded or we
2196 // are switching where one is offloaded and one isn't then we create
2197 // the new track in advance so that we can read additional stream info
2198
2199 if (!(reuse && bothOffloaded)) {
2200 ALOGV("creating new AudioTrack");
2201
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002202 if (mCallback != nullptr) {
2203 newcbd = sp<CallbackData>::make(wp<AudioOutput>::fromExisting(this));
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002204 t = new AudioTrack(
2205 mStreamType,
2206 sampleRate,
2207 format,
2208 channelMask,
2209 frameCount,
2210 flags,
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002211 newcbd,
2212 0, // notification frames
2213 mSessionId,
2214 AudioTrack::TRANSFER_CALLBACK,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002215 offloadInfo,
Svet Ganov33761132021-05-13 22:51:08 +00002216 mAttributionSource,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07002217 mAttributes,
jiabin156c6872017-10-06 09:47:15 -07002218 doNotReconnect,
2219 1.0f, // default value for maxRequiredSpeed
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002220 mSelectedDeviceId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002221 } else {
Andy Hungff874dc2016-04-11 16:49:09 -07002222 // TODO: Due to buffer memory concerns, we use a max target playback speed
2223 // based on mPlaybackRate at the time of open (instead of kMaxRequiredSpeed),
2224 // also clamping the target speed to 1.0 <= targetSpeed <= kMaxRequiredSpeed.
2225 const float targetSpeed =
2226 std::min(std::max(mPlaybackRate.mSpeed, 1.0f), kMaxRequiredSpeed);
2227 ALOGW_IF(targetSpeed != mPlaybackRate.mSpeed,
2228 "track target speed:%f clamped from playback speed:%f",
2229 targetSpeed, mPlaybackRate.mSpeed);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002230 t = new AudioTrack(
2231 mStreamType,
2232 sampleRate,
2233 format,
2234 channelMask,
2235 frameCount,
2236 flags,
Atneya Nairc1bf42b2021-11-29 19:00:54 -05002237 nullptr, // callback
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002238 0, // notification frames
2239 mSessionId,
2240 AudioTrack::TRANSFER_DEFAULT,
2241 NULL, // offload info
Svet Ganov33761132021-05-13 22:51:08 +00002242 mAttributionSource,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07002243 mAttributes,
Andy Hungff874dc2016-04-11 16:49:09 -07002244 doNotReconnect,
jiabin156c6872017-10-06 09:47:15 -07002245 targetSpeed,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002246 mSelectedDeviceId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002247 }
Andy Hunga6b27032020-04-27 10:34:24 -07002248 // Set caller name so it can be logged in destructor.
2249 // MediaMetricsConstants.h: AMEDIAMETRICS_PROP_CALLERNAME_VALUE_MEDIA
2250 t->setCallerName("media");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002251 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
2252 ALOGE("Unable to create audio track");
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002253 // t, newcbd goes out of scope, so reference count drops to zero
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002254 return NO_INIT;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07002255 } else {
2256 // successful AudioTrack initialization implies a legacy stream type was generated
2257 // from the audio attributes
2258 mStreamType = t->streamType();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002259 }
2260 }
2261
2262 if (reuse) {
2263 CHECK(mRecycledTrack != NULL);
2264
2265 if (!bothOffloaded) {
2266 if (mRecycledTrack->frameCount() != t->frameCount()) {
Andy Hung833b4752016-04-04 17:15:48 -07002267 ALOGV("framecount differs: %zu/%zu frames",
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002268 mRecycledTrack->frameCount(), t->frameCount());
2269 reuse = false;
2270 }
Jaideep Sharmab3ce4482020-11-16 11:52:35 +05302271 // If recycled and new tracks are not on the same output,
2272 // don't reuse the recycled one.
2273 if (mRecycledTrack->getOutput() != t->getOutput()) {
2274 ALOGV("output has changed, don't reuse track");
2275 reuse = false;
2276 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002277 }
2278
Marco Nelissen67295b52012-06-11 14:52:53 -07002279 if (reuse) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002280 ALOGV("chaining to next output and recycling track");
Andy Hungd1c74342015-07-07 16:54:23 -07002281 close_l();
Marco Nelissen67295b52012-06-11 14:52:53 -07002282 mTrack = mRecycledTrack;
Glenn Kasten2799d742013-05-30 14:33:29 -07002283 mRecycledTrack.clear();
Marco Nelissen67295b52012-06-11 14:52:53 -07002284 if (mCallbackData != NULL) {
2285 mCallbackData->setOutput(this);
2286 }
Wei Jiae0bbac92016-07-18 16:04:53 -07002287 return updateTrack();
Marco Nelissen67295b52012-06-11 14:52:53 -07002288 }
Marco Nelissen67295b52012-06-11 14:52:53 -07002289 }
2290
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002291 // we're not going to reuse the track, unblock and flush it
2292 // this was done earlier if both tracks are offloaded
2293 if (!bothOffloaded) {
Andy Hungd1c74342015-07-07 16:54:23 -07002294 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002295 }
2296
2297 CHECK((t != NULL) && ((mCallback == NULL) || (newcbd != NULL)));
2298
Marco Nelissen67295b52012-06-11 14:52:53 -07002299 mCallbackData = newcbd;
Steve Block3856b092011-10-20 11:56:00 +01002300 ALOGV("setVolume");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002301 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07002302
Andy Hung39399b62017-04-21 15:07:45 -07002303 // Restore VolumeShapers for the MediaPlayer in case the track was recreated
2304 // due to an output sink error (e.g. offload to non-offload switch).
2305 mVolumeHandler->forall([&t](const VolumeShaper &shaper) -> VolumeShaper::Status {
2306 sp<VolumeShaper::Operation> operationToEnd =
2307 new VolumeShaper::Operation(shaper.mOperation);
2308 // TODO: Ideally we would restore to the exact xOffset position
2309 // as returned by getVolumeShaperState(), but we don't have that
2310 // information when restoring at the client unless we periodically poll
2311 // the server or create shared memory state.
2312 //
2313 // For now, we simply advance to the end of the VolumeShaper effect
2314 // if it has been started.
2315 if (shaper.isStarted()) {
Andy Hungf3702642017-05-05 17:33:32 -07002316 operationToEnd->setNormalizedTime(1.f);
Andy Hung39399b62017-04-21 15:07:45 -07002317 }
2318 return t->applyVolumeShaper(shaper.mConfiguration, operationToEnd);
Andy Hung4ef88d72017-02-21 19:47:53 -08002319 });
Andy Hung4ef88d72017-02-21 19:47:53 -08002320
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002321 mSampleRateHz = sampleRate;
Preetam Singh Ranawat2e17eef2015-08-12 12:11:46 -07002322 mFlags = flags;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002323 mMsecsPerFrame = 1E3f / (mPlaybackRate.mSpeed * sampleRate);
Andy Hungd1c74342015-07-07 16:54:23 -07002324 mFrameSize = t->frameSize();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002325 mTrack = t;
Eric Laurent2beeb502010-07-16 07:43:46 -07002326
Wei Jiae0bbac92016-07-18 16:04:53 -07002327 return updateTrack();
2328}
2329
2330status_t MediaPlayerService::AudioOutput::updateTrack() {
2331 if (mTrack == NULL) {
2332 return NO_ERROR;
2333 }
2334
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002335 status_t res = NO_ERROR;
Wei Jia0162d002015-06-09 11:59:33 -07002336 // Note some output devices may give us a direct track even though we don't specify it.
2337 // Example: Line application b/17459982.
Wei Jiae0bbac92016-07-18 16:04:53 -07002338 if ((mTrack->getFlags()
2339 & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) {
2340 res = mTrack->setPlaybackRate(mPlaybackRate);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002341 if (res == NO_ERROR) {
Wei Jiae0bbac92016-07-18 16:04:53 -07002342 mTrack->setAuxEffectSendLevel(mSendLevel);
2343 res = mTrack->attachAuxEffect(mAuxEffectId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002344 }
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002345 }
jiabin156c6872017-10-06 09:47:15 -07002346 mTrack->setOutputDevice(mSelectedDeviceId);
2347 if (mDeviceCallbackEnabled) {
2348 mTrack->addAudioDeviceCallback(mDeviceCallback.promote());
2349 }
Wei Jiae0bbac92016-07-18 16:04:53 -07002350 ALOGV("updateTrack() DONE status %d", res);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002351 return res;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002352}
2353
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002354status_t MediaPlayerService::AudioOutput::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002355{
Steve Block3856b092011-10-20 11:56:00 +01002356 ALOGV("start");
Andy Hungd1c74342015-07-07 16:54:23 -07002357 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08002358 if (mCallbackData != NULL) {
2359 mCallbackData->endTrackSwitch();
2360 }
Glenn Kasten2799d742013-05-30 14:33:29 -07002361 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002362 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07002363 mTrack->setAuxEffectSendLevel(mSendLevel);
Andy Hung39399b62017-04-21 15:07:45 -07002364 status_t status = mTrack->start();
2365 if (status == NO_ERROR) {
2366 mVolumeHandler->setStarted();
2367 }
2368 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002369 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002370 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002371}
2372
Marco Nelissen6b74d672012-02-28 16:07:44 -08002373void MediaPlayerService::AudioOutput::setNextOutput(const sp<AudioOutput>& nextOutput) {
Andy Hungd1c74342015-07-07 16:54:23 -07002374 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08002375 mNextOutput = nextOutput;
2376}
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08002377
Marco Nelissen6b74d672012-02-28 16:07:44 -08002378void MediaPlayerService::AudioOutput::switchToNextOutput() {
2379 ALOGV("switchToNextOutput");
Andy Hungd1c74342015-07-07 16:54:23 -07002380
2381 // Try to acquire the callback lock before moving track (without incurring deadlock).
2382 const unsigned kMaxSwitchTries = 100;
2383 Mutex::Autolock lock(mLock);
2384 for (unsigned tries = 0;;) {
2385 if (mTrack == 0) {
2386 return;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002387 }
Andy Hungd1c74342015-07-07 16:54:23 -07002388 if (mNextOutput != NULL && mNextOutput != this) {
2389 if (mCallbackData != NULL) {
2390 // two alternative approaches
2391#if 1
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002392 sp<CallbackData> callbackData = mCallbackData;
Andy Hungd1c74342015-07-07 16:54:23 -07002393 mLock.unlock();
2394 // proper acquisition sequence
2395 callbackData->lock();
2396 mLock.lock();
2397 // Caution: it is unlikely that someone deleted our callback or changed our target
2398 if (callbackData != mCallbackData || mNextOutput == NULL || mNextOutput == this) {
2399 // fatal if we are starved out.
2400 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2401 "switchToNextOutput() cannot obtain correct lock sequence");
2402 callbackData->unlock();
2403 continue;
2404 }
2405 callbackData->mSwitching = true; // begin track switch
Wei Jiaadee56a2016-08-05 15:40:34 -07002406 callbackData->setOutput(NULL);
Andy Hungd1c74342015-07-07 16:54:23 -07002407#else
2408 // tryBeginTrackSwitch() returns false if the callback has the lock.
2409 if (!mCallbackData->tryBeginTrackSwitch()) {
2410 // fatal if we are starved out.
2411 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2412 "switchToNextOutput() cannot obtain callback lock");
2413 mLock.unlock();
2414 usleep(5 * 1000 /* usec */); // allow callback to use AudioOutput
2415 mLock.lock();
2416 continue;
2417 }
2418#endif
2419 }
2420
2421 Mutex::Autolock nextLock(mNextOutput->mLock);
2422
2423 // If the next output track is not NULL, then it has been
2424 // opened already for playback.
2425 // This is possible even without the next player being started,
2426 // for example, the next player could be prepared and seeked.
2427 //
2428 // Presuming it isn't advisable to force the track over.
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002429 if (mNextOutput->mTrack == nullptr) {
Andy Hungd1c74342015-07-07 16:54:23 -07002430 ALOGD("Recycling track for gapless playback");
Andy Hungd1c74342015-07-07 16:54:23 -07002431 mNextOutput->mCallbackData = mCallbackData;
2432 mNextOutput->mRecycledTrack = mTrack;
2433 mNextOutput->mSampleRateHz = mSampleRateHz;
2434 mNextOutput->mMsecsPerFrame = mMsecsPerFrame;
Andy Hungd1c74342015-07-07 16:54:23 -07002435 mNextOutput->mFlags = mFlags;
2436 mNextOutput->mFrameSize = mFrameSize;
2437 close_l();
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002438 mCallbackData.clear();
Andy Hungd1c74342015-07-07 16:54:23 -07002439 } else {
2440 ALOGW("Ignoring gapless playback because next player has already started");
2441 // remove track in case resource needed for future players.
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002442 if (mCallbackData != nullptr) {
Andy Hungd1c74342015-07-07 16:54:23 -07002443 mCallbackData->endTrackSwitch(); // release lock for callbacks before close.
2444 }
2445 close_l();
2446 }
2447 }
2448 break;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002449 }
2450}
2451
Wei Jia7d3f4df2015-03-03 15:28:00 -08002452ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002453{
Andy Hungd1c74342015-07-07 16:54:23 -07002454 Mutex::Autolock lock(mLock);
Glenn Kastenadad3d72014-02-21 14:51:43 -08002455 LOG_ALWAYS_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
Andreas Huber20111aa2009-07-14 16:56:47 -07002456
Steve Block3856b092011-10-20 11:56:00 +01002457 //ALOGV("write(%p, %u)", buffer, size);
Glenn Kasten2799d742013-05-30 14:33:29 -07002458 if (mTrack != 0) {
Andy Hung2f6e73d2016-04-08 12:12:58 -07002459 return mTrack->write(buffer, size, blocking);
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07002460 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002461 return NO_INIT;
2462}
2463
2464void MediaPlayerService::AudioOutput::stop()
2465{
Steve Block3856b092011-10-20 11:56:00 +01002466 ALOGV("stop");
Andy Hungd1c74342015-07-07 16:54:23 -07002467 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002468 if (mTrack != 0) mTrack->stop();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002469}
2470
2471void MediaPlayerService::AudioOutput::flush()
2472{
Steve Block3856b092011-10-20 11:56:00 +01002473 ALOGV("flush");
Andy Hungd1c74342015-07-07 16:54:23 -07002474 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002475 if (mTrack != 0) mTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002476}
2477
2478void MediaPlayerService::AudioOutput::pause()
2479{
Steve Block3856b092011-10-20 11:56:00 +01002480 ALOGV("pause");
Andy Hung959b5b82021-09-24 10:46:20 -07002481 // We use pauseAndWait() instead of pause() to ensure tracks ramp to silence before
2482 // any flush. We choose 40 ms timeout to allow 1 deep buffer mixer period
2483 // to occur. Often waiting is 0 - 20 ms.
2484 using namespace std::chrono_literals;
2485 constexpr auto TIMEOUT_MS = 40ms;
Andy Hungd1c74342015-07-07 16:54:23 -07002486 Mutex::Autolock lock(mLock);
Andy Hung959b5b82021-09-24 10:46:20 -07002487 if (mTrack != 0) mTrack->pauseAndWait(TIMEOUT_MS);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002488}
2489
2490void MediaPlayerService::AudioOutput::close()
2491{
Steve Block3856b092011-10-20 11:56:00 +01002492 ALOGV("close");
Erik Wolsheimer7845a1f2015-10-30 12:07:52 -07002493 sp<AudioTrack> track;
2494 {
2495 Mutex::Autolock lock(mLock);
2496 track = mTrack;
2497 close_l(); // clears mTrack
2498 }
2499 // destruction of the track occurs outside of mutex.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002500}
2501
2502void MediaPlayerService::AudioOutput::setVolume(float left, float right)
2503{
Steve Block3856b092011-10-20 11:56:00 +01002504 ALOGV("setVolume(%f, %f)", left, right);
Andy Hungd1c74342015-07-07 16:54:23 -07002505 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002506 mLeftVolume = left;
2507 mRightVolume = right;
Glenn Kasten2799d742013-05-30 14:33:29 -07002508 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002509 mTrack->setVolume(left, right);
2510 }
2511}
2512
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002513status_t MediaPlayerService::AudioOutput::setPlaybackRate(const AudioPlaybackRate &rate)
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002514{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002515 ALOGV("setPlaybackRate(%f %f %d %d)",
2516 rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Andy Hungd1c74342015-07-07 16:54:23 -07002517 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002518 if (mTrack == 0) {
2519 // remember rate so that we can set it when the track is opened
2520 mPlaybackRate = rate;
2521 return OK;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002522 }
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002523 status_t res = mTrack->setPlaybackRate(rate);
2524 if (res != NO_ERROR) {
2525 return res;
2526 }
2527 // rate.mSpeed is always greater than 0 if setPlaybackRate succeeded
2528 CHECK_GT(rate.mSpeed, 0.f);
2529 mPlaybackRate = rate;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002530 if (mSampleRateHz != 0) {
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002531 mMsecsPerFrame = 1E3f / (rate.mSpeed * mSampleRateHz);
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002532 }
2533 return res;
2534}
2535
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002536status_t MediaPlayerService::AudioOutput::getPlaybackRate(AudioPlaybackRate *rate)
2537{
2538 ALOGV("setPlaybackRate");
Andy Hungd1c74342015-07-07 16:54:23 -07002539 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002540 if (mTrack == 0) {
2541 return NO_INIT;
2542 }
2543 *rate = mTrack->getPlaybackRate();
2544 return NO_ERROR;
2545}
2546
Eric Laurent2beeb502010-07-16 07:43:46 -07002547status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
2548{
Steve Block3856b092011-10-20 11:56:00 +01002549 ALOGV("setAuxEffectSendLevel(%f)", level);
Andy Hungd1c74342015-07-07 16:54:23 -07002550 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002551 mSendLevel = level;
Glenn Kasten2799d742013-05-30 14:33:29 -07002552 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002553 return mTrack->setAuxEffectSendLevel(level);
2554 }
2555 return NO_ERROR;
2556}
2557
2558status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
2559{
Steve Block3856b092011-10-20 11:56:00 +01002560 ALOGV("attachAuxEffect(%d)", effectId);
Andy Hungd1c74342015-07-07 16:54:23 -07002561 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002562 mAuxEffectId = effectId;
Glenn Kasten2799d742013-05-30 14:33:29 -07002563 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002564 return mTrack->attachAuxEffect(effectId);
2565 }
2566 return NO_ERROR;
2567}
2568
jiabin156c6872017-10-06 09:47:15 -07002569status_t MediaPlayerService::AudioOutput::setOutputDevice(audio_port_handle_t deviceId)
2570{
2571 ALOGV("setOutputDevice(%d)", deviceId);
2572 Mutex::Autolock lock(mLock);
2573 mSelectedDeviceId = deviceId;
2574 if (mTrack != 0) {
2575 return mTrack->setOutputDevice(deviceId);
2576 }
2577 return NO_ERROR;
2578}
2579
2580status_t MediaPlayerService::AudioOutput::getRoutedDeviceId(audio_port_handle_t* deviceId)
2581{
2582 ALOGV("getRoutedDeviceId");
2583 Mutex::Autolock lock(mLock);
2584 if (mTrack != 0) {
jiabin161b64f2017-11-17 09:31:48 -08002585 mRoutedDeviceId = mTrack->getRoutedDeviceId();
jiabin156c6872017-10-06 09:47:15 -07002586 }
jiabin161b64f2017-11-17 09:31:48 -08002587 *deviceId = mRoutedDeviceId;
2588 return NO_ERROR;
jiabin156c6872017-10-06 09:47:15 -07002589}
2590
2591status_t MediaPlayerService::AudioOutput::enableAudioDeviceCallback(bool enabled)
2592{
2593 ALOGV("enableAudioDeviceCallback, %d", enabled);
2594 Mutex::Autolock lock(mLock);
2595 mDeviceCallbackEnabled = enabled;
2596 if (mTrack != 0) {
2597 status_t status;
2598 if (enabled) {
2599 status = mTrack->addAudioDeviceCallback(mDeviceCallback.promote());
2600 } else {
2601 status = mTrack->removeAudioDeviceCallback(mDeviceCallback.promote());
2602 }
2603 return status;
2604 }
2605 return NO_ERROR;
2606}
2607
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002608VolumeShaper::Status MediaPlayerService::AudioOutput::applyVolumeShaper(
2609 const sp<VolumeShaper::Configuration>& configuration,
2610 const sp<VolumeShaper::Operation>& operation)
2611{
2612 Mutex::Autolock lock(mLock);
2613 ALOGV("AudioOutput::applyVolumeShaper");
Andy Hung4ef88d72017-02-21 19:47:53 -08002614
Andy Hung4ef88d72017-02-21 19:47:53 -08002615 mVolumeHandler->setIdIfNecessary(configuration);
Andy Hung39399b62017-04-21 15:07:45 -07002616
2617 VolumeShaper::Status status;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002618 if (mTrack != 0) {
Andy Hung39399b62017-04-21 15:07:45 -07002619 status = mTrack->applyVolumeShaper(configuration, operation);
2620 if (status >= 0) {
2621 (void)mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hungf3702642017-05-05 17:33:32 -07002622 if (mTrack->isPlaying()) { // match local AudioTrack to properly restore.
2623 mVolumeHandler->setStarted();
2624 }
Andy Hung39399b62017-04-21 15:07:45 -07002625 }
Andy Hung4ef88d72017-02-21 19:47:53 -08002626 } else {
Andy Hungc01eddb2017-07-21 16:42:41 -07002627 // VolumeShapers are not affected when a track moves between players for
2628 // gapless playback (setNextMediaPlayer).
2629 // We forward VolumeShaper operations that do not change configuration
2630 // to the new player so that unducking may occur as expected.
2631 // Unducking is an idempotent operation, same if applied back-to-back.
2632 if (configuration->getType() == VolumeShaper::Configuration::TYPE_ID
2633 && mNextOutput != nullptr) {
2634 ALOGV("applyVolumeShaper: Attempting to forward missed operation: %s %s",
2635 configuration->toString().c_str(), operation->toString().c_str());
2636 Mutex::Autolock nextLock(mNextOutput->mLock);
2637
2638 // recycled track should be forwarded from this AudioSink by switchToNextOutput
2639 sp<AudioTrack> track = mNextOutput->mRecycledTrack;
2640 if (track != nullptr) {
2641 ALOGD("Forward VolumeShaper operation to recycled track %p", track.get());
2642 (void)track->applyVolumeShaper(configuration, operation);
2643 } else {
2644 // There is a small chance that the unduck occurs after the next
2645 // player has already started, but before it is registered to receive
2646 // the unduck command.
2647 track = mNextOutput->mTrack;
2648 if (track != nullptr) {
2649 ALOGD("Forward VolumeShaper operation to track %p", track.get());
2650 (void)track->applyVolumeShaper(configuration, operation);
2651 }
2652 }
2653 }
Andy Hung39399b62017-04-21 15:07:45 -07002654 status = mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002655 }
Andy Hung39399b62017-04-21 15:07:45 -07002656 return status;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002657}
2658
2659sp<VolumeShaper::State> MediaPlayerService::AudioOutput::getVolumeShaperState(int id)
2660{
2661 Mutex::Autolock lock(mLock);
2662 if (mTrack != 0) {
2663 return mTrack->getVolumeShaperState(id);
Andy Hung4ef88d72017-02-21 19:47:53 -08002664 } else {
2665 return mVolumeHandler->getVolumeShaperState(id);
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002666 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002667}
2668
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002669size_t MediaPlayerService::AudioOutput::CallbackData::onMoreData(const AudioTrack::Buffer& buffer) {
2670 ALOGD("data callback");
2671 lock();
2672 sp<AudioOutput> me = getOutput();
2673 if (me == nullptr) {
2674 unlock();
2675 return 0;
2676 }
2677 size_t actualSize = (*me->mCallback)(
Atneya Nair03079272022-01-18 17:03:14 -05002678 me.get(), buffer.data(), buffer.size(), me->mCallbackCookie,
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002679 CB_EVENT_FILL_BUFFER);
2680
2681 // Log when no data is returned from the callback.
2682 // (1) We may have no data (especially with network streaming sources).
2683 // (2) We may have reached the EOS and the audio track is not stopped yet.
2684 // Note that AwesomePlayer/AudioPlayer will only return zero size when it reaches the EOS.
2685 // NuPlayerRenderer will return zero when it doesn't have data (it doesn't block to fill).
2686 //
2687 // This is a benign busy-wait, with the next data request generated 10 ms or more later;
2688 // nevertheless for power reasons, we don't want to see too many of these.
2689
Santiago Seifert578aeb52022-10-24 07:59:12 +00002690 ALOGV_IF(actualSize == 0 && buffer.size() > 0, "callbackwrapper: empty buffer returned");
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002691 unlock();
2692 return actualSize;
2693}
2694
2695void MediaPlayerService::AudioOutput::CallbackData::onStreamEnd() {
2696 lock();
2697 sp<AudioOutput> me = getOutput();
2698 if (me == nullptr) {
2699 unlock();
Marco Nelissen6b74d672012-02-28 16:07:44 -08002700 return;
2701 }
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002702 ALOGV("callbackwrapper: deliver EVENT_STREAM_END");
2703 (*me->mCallback)(me.get(), NULL /* buffer */, 0 /* size */,
2704 me->mCallbackCookie, CB_EVENT_STREAM_END);
2705 unlock();
2706}
Andreas Huber20111aa2009-07-14 16:56:47 -07002707
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002708
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002709void MediaPlayerService::AudioOutput::CallbackData::onNewIAudioTrack() {
2710 lock();
2711 sp<AudioOutput> me = getOutput();
2712 if (me == nullptr) {
2713 unlock();
2714 return;
Andreas Huber51c1e0e2011-04-04 11:43:40 -07002715 }
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002716 ALOGV("callbackwrapper: deliver EVENT_TEAR_DOWN");
2717 (*me->mCallback)(me.get(), NULL /* buffer */, 0 /* size */,
2718 me->mCallbackCookie, CB_EVENT_TEAR_DOWN);
2719 unlock();
2720}
Andreas Huber51c1e0e2011-04-04 11:43:40 -07002721
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002722void MediaPlayerService::AudioOutput::CallbackData::onUnderrun() {
2723 // This occurs when there is no data available, typically
2724 // when there is a failure to supply data to the AudioTrack. It can also
2725 // occur in non-offloaded mode when the audio device comes out of standby.
2726 //
2727 // If an AudioTrack underruns it outputs silence. Since this happens suddenly
2728 // it may sound like an audible pop or glitch.
2729 //
2730 // The underrun event is sent once per track underrun; the condition is reset
2731 // when more data is sent to the AudioTrack.
2732 ALOGD("callbackwrapper: EVENT_UNDERRUN (discarded)");
2733
Andreas Huber20111aa2009-07-14 16:56:47 -07002734}
2735
Glenn Kastend848eb42016-03-08 13:42:11 -08002736audio_session_t MediaPlayerService::AudioOutput::getSessionId() const
Eric Laurent8c563ed2010-10-07 18:23:03 -07002737{
Andy Hungd1c74342015-07-07 16:54:23 -07002738 Mutex::Autolock lock(mLock);
Eric Laurent8c563ed2010-10-07 18:23:03 -07002739 return mSessionId;
2740}
2741
Eric Laurent6f59db12013-07-26 17:16:50 -07002742uint32_t MediaPlayerService::AudioOutput::getSampleRate() const
2743{
Andy Hungd1c74342015-07-07 16:54:23 -07002744 Mutex::Autolock lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -07002745 if (mTrack == 0) return 0;
2746 return mTrack->getSampleRate();
2747}
2748
Andy Hungf2c87b32016-04-07 19:49:29 -07002749int64_t MediaPlayerService::AudioOutput::getBufferDurationInUs() const
2750{
2751 Mutex::Autolock lock(mLock);
2752 if (mTrack == 0) {
2753 return 0;
2754 }
2755 int64_t duration;
2756 if (mTrack->getBufferDurationInUs(&duration) != OK) {
2757 return 0;
2758 }
2759 return duration;
2760}
2761
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002762////////////////////////////////////////////////////////////////////////////////
2763
2764struct CallbackThread : public Thread {
2765 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
2766 MediaPlayerBase::AudioSink::AudioCallback cb,
2767 void *cookie);
2768
2769protected:
2770 virtual ~CallbackThread();
2771
2772 virtual bool threadLoop();
2773
2774private:
2775 wp<MediaPlayerBase::AudioSink> mSink;
2776 MediaPlayerBase::AudioSink::AudioCallback mCallback;
2777 void *mCookie;
2778 void *mBuffer;
2779 size_t mBufferSize;
2780
2781 CallbackThread(const CallbackThread &);
2782 CallbackThread &operator=(const CallbackThread &);
2783};
2784
2785CallbackThread::CallbackThread(
2786 const wp<MediaPlayerBase::AudioSink> &sink,
2787 MediaPlayerBase::AudioSink::AudioCallback cb,
2788 void *cookie)
2789 : mSink(sink),
2790 mCallback(cb),
2791 mCookie(cookie),
2792 mBuffer(NULL),
2793 mBufferSize(0) {
2794}
2795
2796CallbackThread::~CallbackThread() {
2797 if (mBuffer) {
2798 free(mBuffer);
2799 mBuffer = NULL;
2800 }
2801}
2802
2803bool CallbackThread::threadLoop() {
2804 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
2805 if (sink == NULL) {
2806 return false;
2807 }
2808
2809 if (mBuffer == NULL) {
2810 mBufferSize = sink->bufferSize();
2811 mBuffer = malloc(mBufferSize);
2812 }
2813
2814 size_t actualSize =
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002815 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie,
2816 MediaPlayerBase::AudioSink::CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002817
2818 if (actualSize > 0) {
2819 sink->write(mBuffer, actualSize);
Andy Hunga31335a2014-08-20 17:37:59 -07002820 // Could return false on sink->write() error or short count.
2821 // Not necessarily appropriate but would work for AudioCache behavior.
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002822 }
2823
2824 return true;
2825}
2826
2827////////////////////////////////////////////////////////////////////////////////
2828
Chong Zhange5b9b692017-05-11 11:44:56 -07002829void MediaPlayerService::addBatteryData(uint32_t params) {
2830 mBatteryTracker.addBatteryData(params);
2831}
2832
2833status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
2834 return mBatteryTracker.pullBatteryData(reply);
2835}
2836
2837MediaPlayerService::BatteryTracker::BatteryTracker() {
2838 mBatteryAudio.refCount = 0;
2839 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2840 mBatteryAudio.deviceOn[i] = 0;
2841 mBatteryAudio.lastTime[i] = 0;
2842 mBatteryAudio.totalTime[i] = 0;
2843 }
2844 // speaker is on by default
2845 mBatteryAudio.deviceOn[SPEAKER] = 1;
2846
2847 // reset battery stats
2848 // if the mediaserver has crashed, battery stats could be left
2849 // in bad state, reset the state upon service start.
2850 BatteryNotifier::getInstance().noteResetVideo();
2851}
2852
2853void MediaPlayerService::BatteryTracker::addBatteryData(uint32_t params)
Gloria Wang7cf180c2011-02-19 18:37:57 -08002854{
2855 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002856
2857 int32_t time = systemTime() / 1000000L;
2858
2859 // change audio output devices. This notification comes from AudioFlinger
2860 if ((params & kBatteryDataSpeakerOn)
2861 || (params & kBatteryDataOtherAudioDeviceOn)) {
2862
2863 int deviceOn[NUM_AUDIO_DEVICES];
2864 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2865 deviceOn[i] = 0;
2866 }
2867
2868 if ((params & kBatteryDataSpeakerOn)
2869 && (params & kBatteryDataOtherAudioDeviceOn)) {
2870 deviceOn[SPEAKER_AND_OTHER] = 1;
2871 } else if (params & kBatteryDataSpeakerOn) {
2872 deviceOn[SPEAKER] = 1;
2873 } else {
2874 deviceOn[OTHER_AUDIO_DEVICE] = 1;
2875 }
2876
2877 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2878 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
2879
2880 if (mBatteryAudio.refCount > 0) { // if playing audio
2881 if (!deviceOn[i]) {
2882 mBatteryAudio.lastTime[i] += time;
2883 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2884 mBatteryAudio.lastTime[i] = 0;
2885 } else {
2886 mBatteryAudio.lastTime[i] = 0 - time;
2887 }
2888 }
2889
2890 mBatteryAudio.deviceOn[i] = deviceOn[i];
2891 }
2892 }
2893 return;
2894 }
2895
Marco Nelissenb7848f12014-12-04 08:57:56 -08002896 // an audio stream is started
Gloria Wang9ee159b2011-02-24 14:51:45 -08002897 if (params & kBatteryDataAudioFlingerStart) {
2898 // record the start time only if currently no other audio
2899 // is being played
2900 if (mBatteryAudio.refCount == 0) {
2901 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2902 if (mBatteryAudio.deviceOn[i]) {
2903 mBatteryAudio.lastTime[i] -= time;
2904 }
2905 }
2906 }
2907
2908 mBatteryAudio.refCount ++;
2909 return;
2910
2911 } else if (params & kBatteryDataAudioFlingerStop) {
2912 if (mBatteryAudio.refCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002913 ALOGW("Battery track warning: refCount is <= 0");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002914 return;
2915 }
2916
2917 // record the stop time only if currently this is the only
2918 // audio being played
2919 if (mBatteryAudio.refCount == 1) {
2920 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2921 if (mBatteryAudio.deviceOn[i]) {
2922 mBatteryAudio.lastTime[i] += time;
2923 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2924 mBatteryAudio.lastTime[i] = 0;
2925 }
2926 }
2927 }
2928
2929 mBatteryAudio.refCount --;
2930 return;
2931 }
2932
Andy Hung1afd0982016-11-08 16:13:44 -08002933 uid_t uid = IPCThreadState::self()->getCallingUid();
Gloria Wang7cf180c2011-02-19 18:37:57 -08002934 if (uid == AID_MEDIA) {
2935 return;
2936 }
2937 int index = mBatteryData.indexOfKey(uid);
Gloria Wang7cf180c2011-02-19 18:37:57 -08002938
2939 if (index < 0) { // create a new entry for this UID
2940 BatteryUsageInfo info;
2941 info.audioTotalTime = 0;
2942 info.videoTotalTime = 0;
2943 info.audioLastTime = 0;
2944 info.videoLastTime = 0;
2945 info.refCount = 0;
2946
Gloria Wang9ee159b2011-02-24 14:51:45 -08002947 if (mBatteryData.add(uid, info) == NO_MEMORY) {
Steve Block29357bc2012-01-06 19:20:56 +00002948 ALOGE("Battery track error: no memory for new app");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002949 return;
2950 }
Gloria Wang7cf180c2011-02-19 18:37:57 -08002951 }
2952
2953 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
2954
2955 if (params & kBatteryDataCodecStarted) {
2956 if (params & kBatteryDataTrackAudio) {
2957 info.audioLastTime -= time;
2958 info.refCount ++;
2959 }
2960 if (params & kBatteryDataTrackVideo) {
2961 info.videoLastTime -= time;
2962 info.refCount ++;
2963 }
2964 } else {
2965 if (info.refCount == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002966 ALOGW("Battery track warning: refCount is already 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002967 return;
2968 } else if (info.refCount < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00002969 ALOGE("Battery track error: refCount < 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002970 mBatteryData.removeItem(uid);
2971 return;
2972 }
2973
2974 if (params & kBatteryDataTrackAudio) {
2975 info.audioLastTime += time;
2976 info.refCount --;
2977 }
2978 if (params & kBatteryDataTrackVideo) {
2979 info.videoLastTime += time;
2980 info.refCount --;
2981 }
2982
2983 // no stream is being played by this UID
2984 if (info.refCount == 0) {
2985 info.audioTotalTime += info.audioLastTime;
2986 info.audioLastTime = 0;
2987 info.videoTotalTime += info.videoLastTime;
2988 info.videoLastTime = 0;
2989 }
2990 }
2991}
2992
Chong Zhange5b9b692017-05-11 11:44:56 -07002993status_t MediaPlayerService::BatteryTracker::pullBatteryData(Parcel* reply) {
Gloria Wang7cf180c2011-02-19 18:37:57 -08002994 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002995
2996 // audio output devices usage
2997 int32_t time = systemTime() / 1000000L; //in ms
2998 int32_t totalTime;
2999
3000 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
3001 totalTime = mBatteryAudio.totalTime[i];
3002
3003 if (mBatteryAudio.deviceOn[i]
3004 && (mBatteryAudio.lastTime[i] != 0)) {
3005 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
3006 totalTime += tmpTime;
3007 }
3008
3009 reply->writeInt32(totalTime);
3010 // reset the total time
3011 mBatteryAudio.totalTime[i] = 0;
3012 }
3013
3014 // codec usage
Gloria Wang7cf180c2011-02-19 18:37:57 -08003015 BatteryUsageInfo info;
3016 int size = mBatteryData.size();
3017
3018 reply->writeInt32(size);
3019 int i = 0;
3020
3021 while (i < size) {
3022 info = mBatteryData.valueAt(i);
3023
3024 reply->writeInt32(mBatteryData.keyAt(i)); //UID
3025 reply->writeInt32(info.audioTotalTime);
3026 reply->writeInt32(info.videoTotalTime);
3027
3028 info.audioTotalTime = 0;
3029 info.videoTotalTime = 0;
3030
3031 // remove the UID entry where no stream is being played
3032 if (info.refCount <= 0) {
3033 mBatteryData.removeItemsAt(i);
3034 size --;
3035 i --;
3036 }
3037 i++;
3038 }
3039 return NO_ERROR;
3040}
nikoa64c8c72009-07-20 15:07:26 -07003041} // namespace android