blob: b267c08f0fc7ece4c737a73669885a61d865c588 [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();
Tomasz Wasilczyk09977ff2023-08-11 15:52:22 +0000240 ssize_t realTagSize = utf16_to_utf8_length(tags.c_str(), tags.size());
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700241 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;
Tomasz Wasilczyk09977ff2023-08-11 15:52:22 +0000248 utf16_to_utf8(tags.c_str(), tagSize, attributes->tags,
Sergio Giro1d3f4272016-06-28 18:24:52 +0100249 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");
Tomasz Wasilczyk09977ff2023-08-11 15:52:22 +0000437 ::write(fd, result.c_str(), result.size());
Wonsik Kim6f675772019-08-20 17:06:53 -0700438}
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
Tomasz Wasilczyk09977ff2023-08-11 15:52:22 +0000552 ::write(fd, result.c_str(), result.size());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800553 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 }
Tomasz Wasilczyk09977ff2023-08-11 15:52:22 +0000587 write(fd, result.c_str(), result.size());
Wei Jia502c2f42017-07-13 17:47:56 -0700588
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);
Tomasz Wasilczyk09977ff2023-08-11 15:52:22 +0000647 write(fd, result.c_str(), result.size());
Lajos Molnara42e6cc2022-05-17 15:13:31 -0700648 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 }
Tomasz Wasilczyk09977ff2023-08-11 15:52:22 +0000749 write(fd, result.c_str(), 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()) {
Wonsik Kime8e98152022-12-16 16:04:17 -0800930 sp<IBase> hidlBase = client->getHidlBase();
931 ::ndk::SpAIBinder aidlBase = client->getAidlBase();
932 auto onBinderDied = [l = wp<MediaPlayerBase>(p),
933 name = std::string(client->getServiceName())]() {
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700934 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 }
Wonsik Kime8e98152022-12-16 16:04:17 -0800947 };
948 if (hidlBase) {
949 deathNotifiers.emplace_back(hidlBase, onBinderDied);
950 } else if (aidlBase.get() != nullptr) {
951 deathNotifiers.emplace_back(aidlBase, onBinderDied);
952 }
Marco Nelissene4da6c62019-04-01 15:01:41 -0700953 }
Marco Nelissena0c98412019-03-29 12:10:19 -0700954 }
Marco Nelissen1b5a7ee2016-09-30 13:54:30 -0700955 }
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700956
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700957 Mutex::Autolock lock(mLock);
958
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700959 mDeathNotifiers.clear();
960 mDeathNotifiers.swap(deathNotifiers);
jiabin156c6872017-10-06 09:47:15 -0700961 mAudioDeviceUpdatedListener = new AudioDeviceUpdatedNotifier(p);
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700962
John Grossmanc795b642012-02-22 15:38:35 -0800963 if (!p->hardwareOutput()) {
Svet Ganov33761132021-05-13 22:51:08 +0000964 mAudioOutput = new AudioOutput(mAudioSessionId, mAttributionSource,
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700965 mAudioAttributes, mAudioDeviceUpdatedListener);
John Grossmanc795b642012-02-22 15:38:35 -0800966 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
967 }
968
969 return p;
970}
971
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700972status_t MediaPlayerService::Client::setDataSource_post(
John Grossmanc795b642012-02-22 15:38:35 -0800973 const sp<MediaPlayerBase>& p,
974 status_t status)
975{
976 ALOGV(" setDataSource");
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700977 if (status != OK) {
978 ALOGE(" error: %d", status);
979 return status;
John Grossmanc795b642012-02-22 15:38:35 -0800980 }
981
982 // Set the re-transmission endpoint if one was chosen.
983 if (mRetransmitEndpointValid) {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700984 status = p->setRetransmitEndpoint(&mRetransmitEndpoint);
985 if (status != NO_ERROR) {
986 ALOGE("setRetransmitEndpoint error: %d", status);
John Grossmanc795b642012-02-22 15:38:35 -0800987 }
988 }
989
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700990 if (status == OK) {
991 Mutex::Autolock lock(mLock);
John Grossmanc795b642012-02-22 15:38:35 -0800992 mPlayer = p;
993 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700994 return status;
John Grossmanc795b642012-02-22 15:38:35 -0800995}
996
Andreas Huber2db84552010-01-28 11:19:57 -0800997status_t MediaPlayerService::Client::setDataSource(
Andreas Huber1b86fe02014-01-29 11:13:26 -0800998 const sp<IMediaHTTPService> &httpService,
999 const char *url,
1000 const KeyedVector<String8, String8> *headers)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001001{
Steve Block3856b092011-10-20 11:56:00 +01001002 ALOGV("setDataSource(%s)", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001003 if (url == NULL)
1004 return UNKNOWN_ERROR;
1005
Dave Burked681bbb2011-08-30 14:39:17 +01001006 if ((strncmp(url, "http://", 7) == 0) ||
1007 (strncmp(url, "https://", 8) == 0) ||
1008 (strncmp(url, "rtsp://", 7) == 0)) {
1009 if (!checkPermission("android.permission.INTERNET")) {
1010 return PERMISSION_DENIED;
1011 }
1012 }
1013
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001014 if (strncmp(url, "content://", 10) == 0) {
1015 // get a filedescriptor for the content Uri and
1016 // pass it to the setDataSource(fd) method
1017
1018 String16 url16(url);
1019 int fd = android::openContentProviderFile(url16);
1020 if (fd < 0)
1021 {
Steve Block29357bc2012-01-06 19:20:56 +00001022 ALOGE("Couldn't open fd for %s", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001023 return UNKNOWN_ERROR;
1024 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001025 status_t status = setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001026 close(fd);
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001027 return mStatus = status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001028 } else {
John Grossman44a7e422012-06-21 17:29:24 -07001029 player_type playerType = MediaPlayerFactory::getPlayerType(this, url);
John Grossmanc795b642012-02-22 15:38:35 -08001030 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
1031 if (p == NULL) {
1032 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001033 }
1034
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001035 return mStatus =
1036 setDataSource_post(
1037 p, p->setDataSource(httpService, url, headers));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001038 }
1039}
1040
1041status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
1042{
Marco Nelissen83b0fd92015-09-16 13:48:07 -07001043 ALOGV("setDataSource fd=%d (%s), offset=%lld, length=%lld",
1044 fd, nameForFd(fd).c_str(), (long long) offset, (long long) length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001045 struct stat sb;
1046 int ret = fstat(fd, &sb);
1047 if (ret != 0) {
Steve Block29357bc2012-01-06 19:20:56 +00001048 ALOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001049 return UNKNOWN_ERROR;
1050 }
1051
Andy Hung833b4752016-04-04 17:15:48 -07001052 ALOGV("st_dev = %llu", static_cast<unsigned long long>(sb.st_dev));
Steve Block3856b092011-10-20 11:56:00 +01001053 ALOGV("st_mode = %u", sb.st_mode);
Mark Salyzyn77342f72014-06-18 16:31:32 -07001054 ALOGV("st_uid = %lu", static_cast<unsigned long>(sb.st_uid));
1055 ALOGV("st_gid = %lu", static_cast<unsigned long>(sb.st_gid));
Andy Hung833b4752016-04-04 17:15:48 -07001056 ALOGV("st_size = %llu", static_cast<unsigned long long>(sb.st_size));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001057
1058 if (offset >= sb.st_size) {
Steve Block29357bc2012-01-06 19:20:56 +00001059 ALOGE("offset error");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001060 return UNKNOWN_ERROR;
1061 }
1062 if (offset + length > sb.st_size) {
1063 length = sb.st_size - offset;
Andy Hung833b4752016-04-04 17:15:48 -07001064 ALOGV("calculated length = %lld", (long long)length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001065 }
1066
John Grossman44a7e422012-06-21 17:29:24 -07001067 player_type playerType = MediaPlayerFactory::getPlayerType(this,
1068 fd,
1069 offset,
1070 length);
John Grossmanc795b642012-02-22 15:38:35 -08001071 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
1072 if (p == NULL) {
1073 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001074 }
1075
1076 // now set data source
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001077 return mStatus = setDataSource_post(p, p->setDataSource(fd, offset, length));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001078}
1079
Andreas Hubere2b10282010-11-23 11:41:34 -08001080status_t MediaPlayerService::Client::setDataSource(
1081 const sp<IStreamSource> &source) {
1082 // create the right type of player
John Grossman44a7e422012-06-21 17:29:24 -07001083 player_type playerType = MediaPlayerFactory::getPlayerType(this, source);
John Grossmanc795b642012-02-22 15:38:35 -08001084 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
Andreas Hubere2b10282010-11-23 11:41:34 -08001085 if (p == NULL) {
1086 return NO_INIT;
1087 }
1088
Andreas Hubere2b10282010-11-23 11:41:34 -08001089 // now set data source
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001090 return mStatus = setDataSource_post(p, p->setDataSource(source));
Andreas Hubere2b10282010-11-23 11:41:34 -08001091}
1092
Chris Watkins99f31602015-03-20 13:06:33 -07001093status_t MediaPlayerService::Client::setDataSource(
1094 const sp<IDataSource> &source) {
Dongwon Kangd91dc5a2017-10-10 00:07:09 -07001095 sp<DataSource> dataSource = CreateDataSourceFromIDataSource(source);
Chris Watkins99f31602015-03-20 13:06:33 -07001096 player_type playerType = MediaPlayerFactory::getPlayerType(this, dataSource);
1097 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
1098 if (p == NULL) {
1099 return NO_INIT;
1100 }
1101 // now set data source
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001102 return mStatus = setDataSource_post(p, p->setDataSource(dataSource));
Chris Watkins99f31602015-03-20 13:06:33 -07001103}
1104
Byeongjo Park28225ab2019-01-24 20:31:19 +09001105status_t MediaPlayerService::Client::setDataSource(
1106 const String8& rtpParams) {
1107 player_type playerType = NU_PLAYER;
1108 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
1109 if (p == NULL) {
1110 return NO_INIT;
1111 }
1112 // now set data source
1113 return mStatus = setDataSource_post(p, p->setDataSource(rtpParams));
1114}
1115
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001116void MediaPlayerService::Client::disconnectNativeWindow_l() {
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001117 if (mConnectedWindow != NULL) {
Chong Zhang181fd9b2017-02-16 15:53:03 -08001118 status_t err = nativeWindowDisconnect(
1119 mConnectedWindow.get(), "disconnectNativeWindow");
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001120
1121 if (err != OK) {
Chong Zhang181fd9b2017-02-16 15:53:03 -08001122 ALOGW("nativeWindowDisconnect returned an error: %s (%d)",
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001123 strerror(-err), err);
1124 }
1125 }
1126 mConnectedWindow.clear();
1127}
1128
Glenn Kasten11731182011-02-08 17:26:17 -08001129status_t MediaPlayerService::Client::setVideoSurfaceTexture(
Andy McFadden484566c2012-12-18 09:46:54 -08001130 const sp<IGraphicBufferProducer>& bufferProducer)
Glenn Kasten11731182011-02-08 17:26:17 -08001131{
Andy McFadden484566c2012-12-18 09:46:54 -08001132 ALOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, bufferProducer.get());
Glenn Kasten11731182011-02-08 17:26:17 -08001133 sp<MediaPlayerBase> p = getPlayer();
1134 if (p == 0) return UNKNOWN_ERROR;
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001135
Marco Nelissenf8880202014-11-14 07:58:25 -08001136 sp<IBinder> binder(IInterface::asBinder(bufferProducer));
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001137 if (mConnectedWindowBinder == binder) {
1138 return OK;
1139 }
1140
1141 sp<ANativeWindow> anw;
Andy McFadden484566c2012-12-18 09:46:54 -08001142 if (bufferProducer != NULL) {
Marco Nelissenee08f7e2013-09-16 13:30:01 -07001143 anw = new Surface(bufferProducer, true /* controlledByApp */);
Chong Zhang181fd9b2017-02-16 15:53:03 -08001144 status_t err = nativeWindowConnect(anw.get(), "setVideoSurfaceTexture");
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001145
1146 if (err != OK) {
Steve Block29357bc2012-01-06 19:20:56 +00001147 ALOGE("setVideoSurfaceTexture failed: %d", err);
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001148 // Note that we must do the reset before disconnecting from the ANW.
1149 // Otherwise queue/dequeue calls could be made on the disconnected
1150 // ANW, which may result in errors.
1151 reset();
1152
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001153 Mutex::Autolock lock(mLock);
1154 disconnectNativeWindow_l();
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001155
1156 return err;
1157 }
1158 }
1159
Andy McFadden484566c2012-12-18 09:46:54 -08001160 // Note that we must set the player's new GraphicBufferProducer before
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001161 // disconnecting the old one. Otherwise queue/dequeue calls could be made
1162 // on the disconnected ANW, which may result in errors.
Andy McFadden484566c2012-12-18 09:46:54 -08001163 status_t err = p->setVideoSurfaceTexture(bufferProducer);
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001164
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001165 mLock.lock();
1166 disconnectNativeWindow_l();
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001167
1168 if (err == OK) {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001169 mConnectedWindow = anw;
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001170 mConnectedWindowBinder = binder;
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001171 mLock.unlock();
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001172 } else {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001173 mLock.unlock();
1174 status_t err = nativeWindowDisconnect(
1175 anw.get(), "disconnectNativeWindow");
1176
1177 if (err != OK) {
1178 ALOGW("nativeWindowDisconnect returned an error: %s (%d)",
1179 strerror(-err), err);
1180 }
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001181 }
1182
1183 return err;
Glenn Kasten11731182011-02-08 17:26:17 -08001184}
1185
Nicolas Catania1d187f12009-05-12 23:25:55 -07001186status_t MediaPlayerService::Client::invoke(const Parcel& request,
1187 Parcel *reply)
1188{
1189 sp<MediaPlayerBase> p = getPlayer();
1190 if (p == NULL) return UNKNOWN_ERROR;
1191 return p->invoke(request, reply);
1192}
1193
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001194// This call doesn't need to access the native player.
1195status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
1196{
1197 status_t status;
nikoa64c8c72009-07-20 15:07:26 -07001198 media::Metadata::Filter allow, drop;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001199
Nicolas Catania48290382009-07-10 13:53:06 -07001200 if (unmarshallFilter(filter, &allow, &status) &&
1201 unmarshallFilter(filter, &drop, &status)) {
1202 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001203
1204 mMetadataAllow = allow;
1205 mMetadataDrop = drop;
1206 }
1207 return status;
1208}
1209
Nicolas Catania48290382009-07-10 13:53:06 -07001210status_t MediaPlayerService::Client::getMetadata(
Mark Salyzyn77342f72014-06-18 16:31:32 -07001211 bool update_only, bool /*apply_filter*/, Parcel *reply)
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001212{
nikoa64c8c72009-07-20 15:07:26 -07001213 sp<MediaPlayerBase> player = getPlayer();
1214 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania48290382009-07-10 13:53:06 -07001215
nikod608a812009-07-16 16:39:53 -07001216 status_t status;
1217 // Placeholder for the return code, updated by the caller.
1218 reply->writeInt32(-1);
1219
nikoa64c8c72009-07-20 15:07:26 -07001220 media::Metadata::Filter ids;
Nicolas Catania48290382009-07-10 13:53:06 -07001221
1222 // We don't block notifications while we fetch the data. We clear
1223 // mMetadataUpdated first so we don't lose notifications happening
1224 // during the rest of this call.
1225 {
1226 Mutex::Autolock lock(mLock);
1227 if (update_only) {
nikod608a812009-07-16 16:39:53 -07001228 ids = mMetadataUpdated;
Nicolas Catania48290382009-07-10 13:53:06 -07001229 }
1230 mMetadataUpdated.clear();
1231 }
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001232
nikoa64c8c72009-07-20 15:07:26 -07001233 media::Metadata metadata(reply);
Nicolas Catania48290382009-07-10 13:53:06 -07001234
nikoa64c8c72009-07-20 15:07:26 -07001235 metadata.appendHeader();
1236 status = player->getMetadata(ids, reply);
nikod608a812009-07-16 16:39:53 -07001237
1238 if (status != OK) {
nikoa64c8c72009-07-20 15:07:26 -07001239 metadata.resetParcel();
Steve Block29357bc2012-01-06 19:20:56 +00001240 ALOGE("getMetadata failed %d", status);
nikod608a812009-07-16 16:39:53 -07001241 return status;
1242 }
1243
1244 // FIXME: Implement filtering on the result. Not critical since
1245 // filtering takes place on the update notifications already. This
1246 // would be when all the metadata are fetch and a filter is set.
1247
nikod608a812009-07-16 16:39:53 -07001248 // Everything is fine, update the metadata length.
nikoa64c8c72009-07-20 15:07:26 -07001249 metadata.updateLength();
nikod608a812009-07-16 16:39:53 -07001250 return OK;
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001251}
1252
Wei Jiad399e7e2016-10-26 15:49:11 -07001253status_t MediaPlayerService::Client::setBufferingSettings(
1254 const BufferingSettings& buffering)
1255{
Wei Jiadc6f3402017-01-09 15:04:18 -08001256 ALOGV("[%d] setBufferingSettings{%s}",
Tomasz Wasilczyk09977ff2023-08-11 15:52:22 +00001257 mConnId, buffering.toString().c_str());
Wei Jiad399e7e2016-10-26 15:49:11 -07001258 sp<MediaPlayerBase> p = getPlayer();
1259 if (p == 0) return UNKNOWN_ERROR;
1260 return p->setBufferingSettings(buffering);
1261}
1262
Wei Jia9bb38032017-03-23 18:00:38 -07001263status_t MediaPlayerService::Client::getBufferingSettings(
Wei Jiad399e7e2016-10-26 15:49:11 -07001264 BufferingSettings* buffering /* nonnull */)
1265{
1266 sp<MediaPlayerBase> p = getPlayer();
1267 // TODO: create mPlayer on demand.
1268 if (p == 0) return UNKNOWN_ERROR;
Wei Jia9bb38032017-03-23 18:00:38 -07001269 status_t ret = p->getBufferingSettings(buffering);
Wei Jiad399e7e2016-10-26 15:49:11 -07001270 if (ret == NO_ERROR) {
Wei Jia9bb38032017-03-23 18:00:38 -07001271 ALOGV("[%d] getBufferingSettings{%s}",
Tomasz Wasilczyk09977ff2023-08-11 15:52:22 +00001272 mConnId, buffering->toString().c_str());
Wei Jiad399e7e2016-10-26 15:49:11 -07001273 } else {
Wei Jia9bb38032017-03-23 18:00:38 -07001274 ALOGE("[%d] getBufferingSettings returned %d", mConnId, ret);
Wei Jiad399e7e2016-10-26 15:49:11 -07001275 }
1276 return ret;
1277}
1278
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001279status_t MediaPlayerService::Client::prepareAsync()
1280{
Steve Block3856b092011-10-20 11:56:00 +01001281 ALOGV("[%d] prepareAsync", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001282 sp<MediaPlayerBase> p = getPlayer();
1283 if (p == 0) return UNKNOWN_ERROR;
1284 status_t ret = p->prepareAsync();
1285#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +00001286 ALOGD("start Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001287 if (ret == NO_ERROR) mAntagonizer->start();
1288#endif
1289 return ret;
1290}
1291
1292status_t MediaPlayerService::Client::start()
1293{
Steve Block3856b092011-10-20 11:56:00 +01001294 ALOGV("[%d] start", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001295 sp<MediaPlayerBase> p = getPlayer();
1296 if (p == 0) return UNKNOWN_ERROR;
1297 p->setLooping(mLoop);
1298 return p->start();
1299}
1300
1301status_t MediaPlayerService::Client::stop()
1302{
Steve Block3856b092011-10-20 11:56:00 +01001303 ALOGV("[%d] stop", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001304 sp<MediaPlayerBase> p = getPlayer();
1305 if (p == 0) return UNKNOWN_ERROR;
1306 return p->stop();
1307}
1308
1309status_t MediaPlayerService::Client::pause()
1310{
Steve Block3856b092011-10-20 11:56:00 +01001311 ALOGV("[%d] pause", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001312 sp<MediaPlayerBase> p = getPlayer();
1313 if (p == 0) return UNKNOWN_ERROR;
1314 return p->pause();
1315}
1316
1317status_t MediaPlayerService::Client::isPlaying(bool* state)
1318{
1319 *state = false;
1320 sp<MediaPlayerBase> p = getPlayer();
1321 if (p == 0) return UNKNOWN_ERROR;
1322 *state = p->isPlaying();
Steve Block3856b092011-10-20 11:56:00 +01001323 ALOGV("[%d] isPlaying: %d", mConnId, *state);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001324 return NO_ERROR;
1325}
1326
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001327status_t MediaPlayerService::Client::setPlaybackSettings(const AudioPlaybackRate& rate)
Wei Jia98160162015-02-04 17:01:11 -08001328{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001329 ALOGV("[%d] setPlaybackSettings(%f, %f, %d, %d)",
1330 mConnId, rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Wei Jia98160162015-02-04 17:01:11 -08001331 sp<MediaPlayerBase> p = getPlayer();
1332 if (p == 0) return UNKNOWN_ERROR;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001333 return p->setPlaybackSettings(rate);
1334}
1335
1336status_t MediaPlayerService::Client::getPlaybackSettings(AudioPlaybackRate* rate /* nonnull */)
1337{
1338 sp<MediaPlayerBase> p = getPlayer();
1339 if (p == 0) return UNKNOWN_ERROR;
1340 status_t ret = p->getPlaybackSettings(rate);
1341 if (ret == NO_ERROR) {
1342 ALOGV("[%d] getPlaybackSettings(%f, %f, %d, %d)",
1343 mConnId, rate->mSpeed, rate->mPitch, rate->mFallbackMode, rate->mStretchMode);
1344 } else {
1345 ALOGV("[%d] getPlaybackSettings returned %d", mConnId, ret);
1346 }
1347 return ret;
1348}
1349
1350status_t MediaPlayerService::Client::setSyncSettings(
1351 const AVSyncSettings& sync, float videoFpsHint)
1352{
1353 ALOGV("[%d] setSyncSettings(%u, %u, %f, %f)",
1354 mConnId, sync.mSource, sync.mAudioAdjustMode, sync.mTolerance, videoFpsHint);
1355 sp<MediaPlayerBase> p = getPlayer();
1356 if (p == 0) return UNKNOWN_ERROR;
1357 return p->setSyncSettings(sync, videoFpsHint);
1358}
1359
1360status_t MediaPlayerService::Client::getSyncSettings(
1361 AVSyncSettings* sync /* nonnull */, float* videoFps /* nonnull */)
1362{
1363 sp<MediaPlayerBase> p = getPlayer();
1364 if (p == 0) return UNKNOWN_ERROR;
1365 status_t ret = p->getSyncSettings(sync, videoFps);
1366 if (ret == NO_ERROR) {
1367 ALOGV("[%d] getSyncSettings(%u, %u, %f, %f)",
1368 mConnId, sync->mSource, sync->mAudioAdjustMode, sync->mTolerance, *videoFps);
1369 } else {
1370 ALOGV("[%d] getSyncSettings returned %d", mConnId, ret);
1371 }
1372 return ret;
Wei Jia98160162015-02-04 17:01:11 -08001373}
1374
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001375status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
1376{
Steve Block3856b092011-10-20 11:56:00 +01001377 ALOGV("getCurrentPosition");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001378 sp<MediaPlayerBase> p = getPlayer();
1379 if (p == 0) return UNKNOWN_ERROR;
1380 status_t ret = p->getCurrentPosition(msec);
1381 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001382 ALOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001383 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001384 ALOGE("getCurrentPosition returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001385 }
1386 return ret;
1387}
1388
1389status_t MediaPlayerService::Client::getDuration(int *msec)
1390{
Steve Block3856b092011-10-20 11:56:00 +01001391 ALOGV("getDuration");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001392 sp<MediaPlayerBase> p = getPlayer();
1393 if (p == 0) return UNKNOWN_ERROR;
1394 status_t ret = p->getDuration(msec);
1395 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001396 ALOGV("[%d] getDuration = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001397 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001398 ALOGE("getDuration returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001399 }
1400 return ret;
1401}
1402
Marco Nelissen6b74d672012-02-28 16:07:44 -08001403status_t MediaPlayerService::Client::setNextPlayer(const sp<IMediaPlayer>& player) {
1404 ALOGV("setNextPlayer");
1405 Mutex::Autolock l(mLock);
1406 sp<Client> c = static_cast<Client*>(player.get());
Wei Jia28284122016-08-30 13:49:06 -07001407 if (c != NULL && !mService->hasClient(c)) {
Robert Shihee0a0e32016-08-16 16:50:54 -07001408 return BAD_VALUE;
1409 }
1410
Marco Nelissen6b74d672012-02-28 16:07:44 -08001411 mNextClient = c;
John Grossman5f7e55e2012-08-24 14:47:25 -07001412
1413 if (c != NULL) {
1414 if (mAudioOutput != NULL) {
1415 mAudioOutput->setNextOutput(c->mAudioOutput);
1416 } else if ((mPlayer != NULL) && !mPlayer->hardwareOutput()) {
1417 ALOGE("no current audio output");
1418 }
1419
1420 if ((mPlayer != NULL) && (mNextClient->getPlayer() != NULL)) {
1421 mPlayer->setNextPlayer(mNextClient->getPlayer());
1422 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001423 }
John Grossman5f7e55e2012-08-24 14:47:25 -07001424
Marco Nelissen6b74d672012-02-28 16:07:44 -08001425 return OK;
1426}
1427
Andy Hung9fc8b5c2017-01-24 13:36:48 -08001428VolumeShaper::Status MediaPlayerService::Client::applyVolumeShaper(
1429 const sp<VolumeShaper::Configuration>& configuration,
1430 const sp<VolumeShaper::Operation>& operation) {
1431 // for hardware output, call player instead
1432 ALOGV("Client::applyVolumeShaper(%p)", this);
1433 sp<MediaPlayerBase> p = getPlayer();
1434 {
1435 Mutex::Autolock l(mLock);
1436 if (p != 0 && p->hardwareOutput()) {
1437 // TODO: investigate internal implementation
1438 return VolumeShaper::Status(INVALID_OPERATION);
1439 }
1440 if (mAudioOutput.get() != nullptr) {
1441 return mAudioOutput->applyVolumeShaper(configuration, operation);
1442 }
1443 }
1444 return VolumeShaper::Status(INVALID_OPERATION);
1445}
1446
1447sp<VolumeShaper::State> MediaPlayerService::Client::getVolumeShaperState(int id) {
1448 // for hardware output, call player instead
1449 ALOGV("Client::getVolumeShaperState(%p)", this);
1450 sp<MediaPlayerBase> p = getPlayer();
1451 {
1452 Mutex::Autolock l(mLock);
1453 if (p != 0 && p->hardwareOutput()) {
1454 // TODO: investigate internal implementation.
1455 return nullptr;
1456 }
1457 if (mAudioOutput.get() != nullptr) {
1458 return mAudioOutput->getVolumeShaperState(id);
1459 }
1460 }
1461 return nullptr;
1462}
1463
Wei Jiac5de0912016-11-18 10:22:14 -08001464status_t MediaPlayerService::Client::seekTo(int msec, MediaPlayerSeekMode mode)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001465{
Wei Jiac5de0912016-11-18 10:22:14 -08001466 ALOGV("[%d] seekTo(%d, %d)", mConnId, msec, mode);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001467 sp<MediaPlayerBase> p = getPlayer();
1468 if (p == 0) return UNKNOWN_ERROR;
Wei Jiac5de0912016-11-18 10:22:14 -08001469 return p->seekTo(msec, mode);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001470}
1471
1472status_t MediaPlayerService::Client::reset()
1473{
Steve Block3856b092011-10-20 11:56:00 +01001474 ALOGV("[%d] reset", mConnId);
John Grossmanc795b642012-02-22 15:38:35 -08001475 mRetransmitEndpointValid = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001476 sp<MediaPlayerBase> p = getPlayer();
1477 if (p == 0) return UNKNOWN_ERROR;
1478 return p->reset();
1479}
1480
Wei Jia52c28512017-09-13 18:17:51 -07001481status_t MediaPlayerService::Client::notifyAt(int64_t mediaTimeUs)
1482{
1483 ALOGV("[%d] notifyAt(%lld)", mConnId, (long long)mediaTimeUs);
1484 sp<MediaPlayerBase> p = getPlayer();
1485 if (p == 0) return UNKNOWN_ERROR;
1486 return p->notifyAt(mediaTimeUs);
1487}
1488
Glenn Kastenfff6d712012-01-12 16:38:12 -08001489status_t MediaPlayerService::Client::setAudioStreamType(audio_stream_type_t type)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001490{
Steve Block3856b092011-10-20 11:56:00 +01001491 ALOGV("[%d] setAudioStreamType(%d)", mConnId, type);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001492 // TODO: for hardware output, call player instead
1493 Mutex::Autolock l(mLock);
1494 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1495 return NO_ERROR;
1496}
1497
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001498status_t MediaPlayerService::Client::setAudioAttributes_l(const Parcel &parcel)
1499{
1500 if (mAudioAttributes != NULL) { free(mAudioAttributes); }
1501 mAudioAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001502 if (mAudioAttributes == NULL) {
1503 return NO_MEMORY;
1504 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001505 unmarshallAudioAttributes(parcel, mAudioAttributes);
1506
1507 ALOGV("setAudioAttributes_l() usage=%d content=%d flags=0x%x tags=%s",
1508 mAudioAttributes->usage, mAudioAttributes->content_type, mAudioAttributes->flags,
1509 mAudioAttributes->tags);
1510
1511 if (mAudioOutput != 0) {
1512 mAudioOutput->setAudioAttributes(mAudioAttributes);
1513 }
1514 return NO_ERROR;
1515}
1516
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001517status_t MediaPlayerService::Client::setLooping(int loop)
1518{
Steve Block3856b092011-10-20 11:56:00 +01001519 ALOGV("[%d] setLooping(%d)", mConnId, loop);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001520 mLoop = loop;
1521 sp<MediaPlayerBase> p = getPlayer();
1522 if (p != 0) return p->setLooping(loop);
1523 return NO_ERROR;
1524}
1525
1526status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1527{
Steve Block3856b092011-10-20 11:56:00 +01001528 ALOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
John Grossman761defc2012-02-09 15:09:05 -08001529
1530 // for hardware output, call player instead
1531 sp<MediaPlayerBase> p = getPlayer();
1532 {
1533 Mutex::Autolock l(mLock);
1534 if (p != 0 && p->hardwareOutput()) {
1535 MediaPlayerHWInterface* hwp =
1536 reinterpret_cast<MediaPlayerHWInterface*>(p.get());
1537 return hwp->setVolume(leftVolume, rightVolume);
1538 } else {
1539 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1540 return NO_ERROR;
1541 }
1542 }
1543
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001544 return NO_ERROR;
1545}
1546
Eric Laurent2beeb502010-07-16 07:43:46 -07001547status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1548{
Steve Block3856b092011-10-20 11:56:00 +01001549 ALOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
Eric Laurent2beeb502010-07-16 07:43:46 -07001550 Mutex::Autolock l(mLock);
1551 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1552 return NO_ERROR;
1553}
1554
1555status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1556{
Steve Block3856b092011-10-20 11:56:00 +01001557 ALOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
Eric Laurent2beeb502010-07-16 07:43:46 -07001558 Mutex::Autolock l(mLock);
1559 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1560 return NO_ERROR;
1561}
Nicolas Catania48290382009-07-10 13:53:06 -07001562
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001563status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
Steve Block3856b092011-10-20 11:56:00 +01001564 ALOGV("[%d] setParameter(%d)", mConnId, key);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001565 switch (key) {
1566 case KEY_PARAMETER_AUDIO_ATTRIBUTES:
1567 {
1568 Mutex::Autolock l(mLock);
1569 return setAudioAttributes_l(request);
1570 }
1571 default:
1572 sp<MediaPlayerBase> p = getPlayer();
1573 if (p == 0) { return UNKNOWN_ERROR; }
1574 return p->setParameter(key, request);
1575 }
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001576}
1577
1578status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
Steve Block3856b092011-10-20 11:56:00 +01001579 ALOGV("[%d] getParameter(%d)", mConnId, key);
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001580 sp<MediaPlayerBase> p = getPlayer();
1581 if (p == 0) return UNKNOWN_ERROR;
1582 return p->getParameter(key, reply);
1583}
1584
John Grossmanc795b642012-02-22 15:38:35 -08001585status_t MediaPlayerService::Client::setRetransmitEndpoint(
1586 const struct sockaddr_in* endpoint) {
1587
1588 if (NULL != endpoint) {
1589 uint32_t a = ntohl(endpoint->sin_addr.s_addr);
1590 uint16_t p = ntohs(endpoint->sin_port);
1591 ALOGV("[%d] setRetransmitEndpoint(%u.%u.%u.%u:%hu)", mConnId,
1592 (a >> 24), (a >> 16) & 0xFF, (a >> 8) & 0xFF, (a & 0xFF), p);
1593 } else {
1594 ALOGV("[%d] setRetransmitEndpoint = <none>", mConnId);
1595 }
1596
1597 sp<MediaPlayerBase> p = getPlayer();
1598
1599 // Right now, the only valid time to set a retransmit endpoint is before
1600 // player selection has been made (since the presence or absence of a
1601 // retransmit endpoint is going to determine which player is selected during
1602 // setDataSource).
1603 if (p != 0) return INVALID_OPERATION;
1604
1605 if (NULL != endpoint) {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001606 Mutex::Autolock lock(mLock);
John Grossmanc795b642012-02-22 15:38:35 -08001607 mRetransmitEndpoint = *endpoint;
1608 mRetransmitEndpointValid = true;
1609 } else {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001610 Mutex::Autolock lock(mLock);
John Grossmanc795b642012-02-22 15:38:35 -08001611 mRetransmitEndpointValid = false;
1612 }
1613
1614 return NO_ERROR;
1615}
1616
John Grossman44a7e422012-06-21 17:29:24 -07001617status_t MediaPlayerService::Client::getRetransmitEndpoint(
1618 struct sockaddr_in* endpoint)
1619{
1620 if (NULL == endpoint)
1621 return BAD_VALUE;
1622
1623 sp<MediaPlayerBase> p = getPlayer();
1624
1625 if (p != NULL)
1626 return p->getRetransmitEndpoint(endpoint);
1627
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001628 Mutex::Autolock lock(mLock);
John Grossman44a7e422012-06-21 17:29:24 -07001629 if (!mRetransmitEndpointValid)
1630 return NO_INIT;
1631
1632 *endpoint = mRetransmitEndpoint;
1633
1634 return NO_ERROR;
1635}
1636
Gloria Wangb483c472011-04-11 17:23:27 -07001637void MediaPlayerService::Client::notify(
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001638 int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001639{
James Dongb8a98252012-08-26 16:13:03 -07001640 sp<IMediaPlayerClient> c;
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001641 sp<Client> nextClient;
1642 status_t errStartNext = NO_ERROR;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001643 {
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001644 Mutex::Autolock l(mLock);
1645 c = mClient;
1646 if (msg == MEDIA_PLAYBACK_COMPLETE && mNextClient != NULL) {
1647 nextClient = mNextClient;
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001648
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001649 if (mAudioOutput != NULL)
1650 mAudioOutput->switchToNextOutput();
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001651
1652 errStartNext = nextClient->start();
1653 }
1654 }
1655
1656 if (nextClient != NULL) {
1657 sp<IMediaPlayerClient> nc;
1658 {
1659 Mutex::Autolock l(nextClient->mLock);
1660 nc = nextClient->mClient;
1661 }
1662 if (nc != NULL) {
1663 if (errStartNext == NO_ERROR) {
1664 nc->notify(MEDIA_INFO, MEDIA_INFO_STARTED_AS_NEXT, 0, obj);
1665 } else {
1666 nc->notify(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN , 0, obj);
1667 ALOGE("gapless:start playback for next track failed, err(%d)", errStartNext);
Wei Jia2afac0c2016-01-07 12:13:07 -08001668 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001669 }
1670 }
1671
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001672 if (MEDIA_INFO == msg &&
Nicolas Catania48290382009-07-10 13:53:06 -07001673 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikoa64c8c72009-07-20 15:07:26 -07001674 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania48290382009-07-10 13:53:06 -07001675
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001676 if(shouldDropMetadata(metadata_type)) {
Nicolas Catania48290382009-07-10 13:53:06 -07001677 return;
1678 }
1679
1680 // Update the list of metadata that have changed. getMetadata
1681 // also access mMetadataUpdated and clears it.
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001682 addNewMetadataUpdate(metadata_type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001683 }
James Dongb8a98252012-08-26 16:13:03 -07001684
1685 if (c != NULL) {
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001686 ALOGV("[%d] notify (%d, %d, %d)", mConnId, msg, ext1, ext2);
James Dongb8a98252012-08-26 16:13:03 -07001687 c->notify(msg, ext1, ext2, obj);
1688 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001689}
1690
Nicolas Catania48290382009-07-10 13:53:06 -07001691
nikoa64c8c72009-07-20 15:07:26 -07001692bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001693{
Nicolas Catania48290382009-07-10 13:53:06 -07001694 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001695
Nicolas Catania48290382009-07-10 13:53:06 -07001696 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001697 return true;
1698 }
1699
Nicolas Catania48290382009-07-10 13:53:06 -07001700 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001701 return false;
Nicolas Catania48290382009-07-10 13:53:06 -07001702 } else {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001703 return true;
1704 }
1705}
1706
Nicolas Catania48290382009-07-10 13:53:06 -07001707
nikoa64c8c72009-07-20 15:07:26 -07001708void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania48290382009-07-10 13:53:06 -07001709 Mutex::Autolock lock(mLock);
1710 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1711 mMetadataUpdated.add(metadata_type);
1712 }
1713}
1714
Hassan Shojaniacefac142017-02-06 21:02:02 -08001715// Modular DRM
1716status_t MediaPlayerService::Client::prepareDrm(const uint8_t uuid[16],
1717 const Vector<uint8_t>& drmSessionId)
1718{
1719 ALOGV("[%d] prepareDrm", mConnId);
1720 sp<MediaPlayerBase> p = getPlayer();
1721 if (p == 0) return UNKNOWN_ERROR;
1722
1723 status_t ret = p->prepareDrm(uuid, drmSessionId);
1724 ALOGV("prepareDrm ret: %d", ret);
1725
1726 return ret;
1727}
1728
1729status_t MediaPlayerService::Client::releaseDrm()
1730{
1731 ALOGV("[%d] releaseDrm", mConnId);
1732 sp<MediaPlayerBase> p = getPlayer();
1733 if (p == 0) return UNKNOWN_ERROR;
1734
1735 status_t ret = p->releaseDrm();
1736 ALOGV("releaseDrm ret: %d", ret);
1737
1738 return ret;
1739}
1740
jiabin156c6872017-10-06 09:47:15 -07001741status_t MediaPlayerService::Client::setOutputDevice(audio_port_handle_t deviceId)
1742{
1743 ALOGV("[%d] setOutputDevice", mConnId);
1744 {
1745 Mutex::Autolock l(mLock);
1746 if (mAudioOutput.get() != nullptr) {
1747 return mAudioOutput->setOutputDevice(deviceId);
1748 }
1749 }
1750 return NO_INIT;
1751}
1752
1753status_t MediaPlayerService::Client::getRoutedDeviceId(audio_port_handle_t* deviceId)
1754{
1755 ALOGV("[%d] getRoutedDeviceId", mConnId);
1756 {
1757 Mutex::Autolock l(mLock);
1758 if (mAudioOutput.get() != nullptr) {
1759 return mAudioOutput->getRoutedDeviceId(deviceId);
1760 }
1761 }
1762 return NO_INIT;
1763}
1764
1765status_t MediaPlayerService::Client::enableAudioDeviceCallback(bool enabled)
1766{
1767 ALOGV("[%d] enableAudioDeviceCallback, %d", mConnId, enabled);
1768 {
1769 Mutex::Autolock l(mLock);
1770 if (mAudioOutput.get() != nullptr) {
1771 return mAudioOutput->enableAudioDeviceCallback(enabled);
1772 }
1773 }
1774 return NO_INIT;
1775}
1776
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001777#if CALLBACK_ANTAGONIZER
1778const int Antagonizer::interval = 10000; // 10 msecs
1779
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001780Antagonizer::Antagonizer(const sp<MediaPlayerBase::Listener> &listener) :
1781 mExit(false), mActive(false), mListener(listener)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001782{
1783 createThread(callbackThread, this);
1784}
1785
1786void Antagonizer::kill()
1787{
1788 Mutex::Autolock _l(mLock);
1789 mActive = false;
1790 mExit = true;
1791 mCondition.wait(mLock);
1792}
1793
1794int Antagonizer::callbackThread(void* user)
1795{
Steve Blockb8a80522011-12-20 16:23:08 +00001796 ALOGD("Antagonizer started");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001797 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1798 while (!p->mExit) {
1799 if (p->mActive) {
Steve Block3856b092011-10-20 11:56:00 +01001800 ALOGV("send event");
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001801 p->mListener->notify(0, 0, 0, 0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001802 }
1803 usleep(interval);
1804 }
1805 Mutex::Autolock _l(p->mLock);
1806 p->mCondition.signal();
Steve Blockb8a80522011-12-20 16:23:08 +00001807 ALOGD("Antagonizer stopped");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001808 return 0;
1809}
1810#endif
1811
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001812#undef LOG_TAG
1813#define LOG_TAG "AudioSink"
Svet Ganov33761132021-05-13 22:51:08 +00001814MediaPlayerService::AudioOutput::AudioOutput(audio_session_t sessionId,
1815 const AttributionSourceState& attributionSource, const audio_attributes_t* attr,
1816 const sp<AudioSystem::AudioDeviceCallback>& deviceCallback)
Vlad Popab4f5b012022-08-12 15:53:09 +02001817 : mCachedPlayerIId(PLAYER_PIID_INVALID),
1818 mCallback(NULL),
Andy Hungd1c74342015-07-07 16:54:23 -07001819 mStreamType(AUDIO_STREAM_MUSIC),
Andy Hungd1c74342015-07-07 16:54:23 -07001820 mLeftVolume(1.0),
1821 mRightVolume(1.0),
1822 mPlaybackRate(AUDIO_PLAYBACK_RATE_DEFAULT),
1823 mSampleRateHz(0),
1824 mMsecsPerFrame(0),
1825 mFrameSize(0),
Eric Laurent1948eb32012-04-13 16:50:19 -07001826 mSessionId(sessionId),
Svet Ganov33761132021-05-13 22:51:08 +00001827 mAttributionSource(attributionSource),
Andy Hungd1c74342015-07-07 16:54:23 -07001828 mSendLevel(0.0),
1829 mAuxEffectId(0),
Andy Hung4ef88d72017-02-21 19:47:53 -08001830 mFlags(AUDIO_OUTPUT_FLAG_NONE),
jiabin156c6872017-10-06 09:47:15 -07001831 mVolumeHandler(new media::VolumeHandler()),
1832 mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE),
jiabin161b64f2017-11-17 09:31:48 -08001833 mRoutedDeviceId(AUDIO_PORT_HANDLE_NONE),
jiabin156c6872017-10-06 09:47:15 -07001834 mDeviceCallbackEnabled(false),
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001835 mDeviceCallback(deviceCallback)
Andy Hungd1c74342015-07-07 16:54:23 -07001836{
Steve Block3856b092011-10-20 11:56:00 +01001837 ALOGV("AudioOutput(%d)", sessionId);
Eric Laurent43562692015-07-15 16:49:07 -07001838 if (attr != NULL) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001839 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1840 if (mAttributes != NULL) {
1841 memcpy(mAttributes, attr, sizeof(audio_attributes_t));
François Gaffie58d4be52018-11-06 15:30:12 +01001842 mStreamType = AudioSystem::attributesToStreamType(*attr);
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001843 }
1844 } else {
1845 mAttributes = NULL;
Eric Laurent43562692015-07-15 16:49:07 -07001846 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001847 setMinBufferCount();
1848}
1849
1850MediaPlayerService::AudioOutput::~AudioOutput()
1851{
1852 close();
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001853 free(mAttributes);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001854}
1855
Andy Hungd1c74342015-07-07 16:54:23 -07001856//static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001857void MediaPlayerService::AudioOutput::setMinBufferCount()
1858{
Roman Kiryanova3f34462021-03-10 16:17:24 -08001859 if (property_get_bool("ro.boot.qemu", false)) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001860 mIsOnEmulator = true;
1861 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1862 }
1863}
1864
Andy Hungd1c74342015-07-07 16:54:23 -07001865// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001866bool MediaPlayerService::AudioOutput::isOnEmulator()
1867{
Andy Hungd1c74342015-07-07 16:54:23 -07001868 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001869 return mIsOnEmulator;
1870}
1871
Andy Hungd1c74342015-07-07 16:54:23 -07001872// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001873int MediaPlayerService::AudioOutput::getMinBufferCount()
1874{
Andy Hungd1c74342015-07-07 16:54:23 -07001875 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001876 return mMinBufferCount;
1877}
1878
1879ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1880{
Andy Hungd1c74342015-07-07 16:54:23 -07001881 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001882 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001883 return mTrack->frameCount() * mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001884}
1885
1886ssize_t MediaPlayerService::AudioOutput::frameCount() const
1887{
Andy Hungd1c74342015-07-07 16:54:23 -07001888 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001889 if (mTrack == 0) return NO_INIT;
1890 return mTrack->frameCount();
1891}
1892
1893ssize_t MediaPlayerService::AudioOutput::channelCount() const
1894{
Andy Hungd1c74342015-07-07 16:54:23 -07001895 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001896 if (mTrack == 0) return NO_INIT;
1897 return mTrack->channelCount();
1898}
1899
1900ssize_t MediaPlayerService::AudioOutput::frameSize() const
1901{
Andy Hungd1c74342015-07-07 16:54:23 -07001902 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001903 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001904 return mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001905}
1906
1907uint32_t MediaPlayerService::AudioOutput::latency () const
1908{
Andy Hungd1c74342015-07-07 16:54:23 -07001909 Mutex::Autolock lock(mLock);
Eric Laurentdb354e52012-03-05 17:27:11 -08001910 if (mTrack == 0) return 0;
1911 return mTrack->latency();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001912}
1913
1914float MediaPlayerService::AudioOutput::msecsPerFrame() const
1915{
Andy Hungd1c74342015-07-07 16:54:23 -07001916 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001917 return mMsecsPerFrame;
1918}
1919
Marco Nelissen4110c102012-03-29 09:31:28 -07001920status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position) const
Eric Laurent342e9cf2010-01-19 17:37:09 -08001921{
Andy Hungd1c74342015-07-07 16:54:23 -07001922 Mutex::Autolock lock(mLock);
Eric Laurent342e9cf2010-01-19 17:37:09 -08001923 if (mTrack == 0) return NO_INIT;
1924 return mTrack->getPosition(position);
1925}
1926
Lajos Molnar06ad1522014-08-28 07:27:44 -07001927status_t MediaPlayerService::AudioOutput::getTimestamp(AudioTimestamp &ts) const
1928{
Andy Hungd1c74342015-07-07 16:54:23 -07001929 Mutex::Autolock lock(mLock);
Lajos Molnar06ad1522014-08-28 07:27:44 -07001930 if (mTrack == 0) return NO_INIT;
1931 return mTrack->getTimestamp(ts);
1932}
1933
Wei Jiac4ac8172015-10-21 10:35:48 -07001934// TODO: Remove unnecessary calls to getPlayedOutDurationUs()
1935// as it acquires locks and may query the audio driver.
1936//
1937// Some calls could conceivably retrieve extrapolated data instead of
1938// accessing getTimestamp() or getPosition() every time a data buffer with
1939// a media time is received.
1940//
1941// Calculate duration of played samples if played at normal rate (i.e., 1.0).
1942int64_t MediaPlayerService::AudioOutput::getPlayedOutDurationUs(int64_t nowUs) const
1943{
1944 Mutex::Autolock lock(mLock);
1945 if (mTrack == 0 || mSampleRateHz == 0) {
Wei Jia213f4902015-10-22 08:55:25 -07001946 return 0;
Wei Jiac4ac8172015-10-21 10:35:48 -07001947 }
1948
1949 uint32_t numFramesPlayed;
Andy Hung5d313802016-10-10 15:09:39 -07001950 int64_t numFramesPlayedAtUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001951 AudioTimestamp ts;
Wei Jiac4ac8172015-10-21 10:35:48 -07001952
1953 status_t res = mTrack->getTimestamp(ts);
1954 if (res == OK) { // case 1: mixing audio tracks and offloaded tracks.
1955 numFramesPlayed = ts.mPosition;
Andy Hung5d313802016-10-10 15:09:39 -07001956 numFramesPlayedAtUs = ts.mTime.tv_sec * 1000000LL + ts.mTime.tv_nsec / 1000;
1957 //ALOGD("getTimestamp: OK %d %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001958 } else if (res == WOULD_BLOCK) { // case 2: transitory state on start of a new track
1959 numFramesPlayed = 0;
Andy Hung5d313802016-10-10 15:09:39 -07001960 numFramesPlayedAtUs = nowUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001961 //ALOGD("getTimestamp: WOULD_BLOCK %d %lld",
Andy Hung5d313802016-10-10 15:09:39 -07001962 // numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001963 } else { // case 3: transitory at new track or audio fast tracks.
1964 res = mTrack->getPosition(&numFramesPlayed);
1965 CHECK_EQ(res, (status_t)OK);
Andy Hung5d313802016-10-10 15:09:39 -07001966 numFramesPlayedAtUs = nowUs;
1967 numFramesPlayedAtUs += 1000LL * mTrack->latency() / 2; /* XXX */
1968 //ALOGD("getPosition: %u %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001969 }
1970
1971 // CHECK_EQ(numFramesPlayed & (1 << 31), 0); // can't be negative until 12.4 hrs, test
1972 // TODO: remove the (int32_t) casting below as it may overflow at 12.4 hours.
1973 int64_t durationUs = (int64_t)((int32_t)numFramesPlayed * 1000000LL / mSampleRateHz)
Andy Hung5d313802016-10-10 15:09:39 -07001974 + nowUs - numFramesPlayedAtUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001975 if (durationUs < 0) {
1976 // Occurs when numFramesPlayed position is very small and the following:
1977 // (1) In case 1, the time nowUs is computed before getTimestamp() is called and
Andy Hung5d313802016-10-10 15:09:39 -07001978 // numFramesPlayedAtUs is greater than nowUs by time more than numFramesPlayed.
Wei Jiac4ac8172015-10-21 10:35:48 -07001979 // (2) In case 3, using getPosition and adding mAudioSink->latency() to
Andy Hung5d313802016-10-10 15:09:39 -07001980 // numFramesPlayedAtUs, by a time amount greater than numFramesPlayed.
Wei Jiac4ac8172015-10-21 10:35:48 -07001981 //
1982 // Both of these are transitory conditions.
1983 ALOGV("getPlayedOutDurationUs: negative duration %lld set to zero", (long long)durationUs);
1984 durationUs = 0;
1985 }
1986 ALOGV("getPlayedOutDurationUs(%lld) nowUs(%lld) frames(%u) framesAt(%lld)",
Andy Hung5d313802016-10-10 15:09:39 -07001987 (long long)durationUs, (long long)nowUs,
1988 numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001989 return durationUs;
1990}
1991
Marco Nelissen4110c102012-03-29 09:31:28 -07001992status_t MediaPlayerService::AudioOutput::getFramesWritten(uint32_t *frameswritten) const
1993{
Andy Hungd1c74342015-07-07 16:54:23 -07001994 Mutex::Autolock lock(mLock);
Marco Nelissen4110c102012-03-29 09:31:28 -07001995 if (mTrack == 0) return NO_INIT;
Andy Hung2f6e73d2016-04-08 12:12:58 -07001996 ExtendedTimestamp ets;
1997 status_t status = mTrack->getTimestamp(&ets);
1998 if (status == OK || status == WOULD_BLOCK) {
1999 *frameswritten = (uint32_t)ets.mPosition[ExtendedTimestamp::LOCATION_CLIENT];
2000 }
2001 return status;
Marco Nelissen4110c102012-03-29 09:31:28 -07002002}
2003
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002004status_t MediaPlayerService::AudioOutput::setParameters(const String8& keyValuePairs)
2005{
Andy Hungd1c74342015-07-07 16:54:23 -07002006 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002007 if (mTrack == 0) return NO_INIT;
2008 return mTrack->setParameters(keyValuePairs);
2009}
2010
2011String8 MediaPlayerService::AudioOutput::getParameters(const String8& keys)
2012{
Andy Hungd1c74342015-07-07 16:54:23 -07002013 Mutex::Autolock lock(mLock);
Tomasz Wasilczyk53ce3af2023-08-14 16:16:55 +00002014 if (mTrack == 0) return String8();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002015 return mTrack->getParameters(keys);
2016}
2017
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07002018void MediaPlayerService::AudioOutput::setAudioAttributes(const audio_attributes_t * attributes) {
Andy Hungd1c74342015-07-07 16:54:23 -07002019 Mutex::Autolock lock(mLock);
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07002020 if (attributes == NULL) {
2021 free(mAttributes);
2022 mAttributes = NULL;
2023 } else {
2024 if (mAttributes == NULL) {
2025 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
2026 }
2027 memcpy(mAttributes, attributes, sizeof(audio_attributes_t));
François Gaffie58d4be52018-11-06 15:30:12 +01002028 mStreamType = AudioSystem::attributesToStreamType(*attributes);
Eric Laurent43562692015-07-15 16:49:07 -07002029 }
2030}
2031
2032void MediaPlayerService::AudioOutput::setAudioStreamType(audio_stream_type_t streamType)
2033{
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07002034 Mutex::Autolock lock(mLock);
Eric Laurent43562692015-07-15 16:49:07 -07002035 // do not allow direct stream type modification if attributes have been set
2036 if (mAttributes == NULL) {
2037 mStreamType = streamType;
2038 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07002039}
2040
Andy Hungd1c74342015-07-07 16:54:23 -07002041void MediaPlayerService::AudioOutput::deleteRecycledTrack_l()
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002042{
Andy Hungd1c74342015-07-07 16:54:23 -07002043 ALOGV("deleteRecycledTrack_l");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002044 if (mRecycledTrack != 0) {
2045
2046 if (mCallbackData != NULL) {
2047 mCallbackData->setOutput(NULL);
2048 mCallbackData->endTrackSwitch();
2049 }
2050
2051 if ((mRecycledTrack->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) {
Andy Hunge13f8a62016-03-30 14:20:42 -07002052 int32_t msec = 0;
2053 if (!mRecycledTrack->stopped()) { // check if active
2054 (void)mRecycledTrack->pendingDuration(&msec);
2055 }
2056 mRecycledTrack->stop(); // ensure full data drain
2057 ALOGD("deleting recycled track, waiting for data drain (%d msec)", msec);
2058 if (msec > 0) {
2059 static const int32_t WAIT_LIMIT_MS = 3000;
2060 if (msec > WAIT_LIMIT_MS) {
2061 msec = WAIT_LIMIT_MS;
2062 }
2063 usleep(msec * 1000LL);
2064 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002065 }
2066 // An offloaded track isn't flushed because the STREAM_END is reported
2067 // slightly prematurely to allow time for the gapless track switch
2068 // but this means that if we decide not to recycle the track there
2069 // could be a small amount of residual data still playing. We leave
2070 // AudioFlinger to drain the track.
2071
2072 mRecycledTrack.clear();
Andy Hungd1c74342015-07-07 16:54:23 -07002073 close_l();
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002074 mCallbackData.clear();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002075 }
2076}
2077
Andy Hungd1c74342015-07-07 16:54:23 -07002078void MediaPlayerService::AudioOutput::close_l()
2079{
2080 mTrack.clear();
2081}
2082
Andreas Huber20111aa2009-07-14 16:56:47 -07002083status_t MediaPlayerService::AudioOutput::open(
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08002084 uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
2085 audio_format_t format, int bufferCount,
Andy Hunge42b6482024-10-16 19:16:50 -07002086 AudioCallback cb, const wp<RefBase>& cookie,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002087 audio_output_flags_t flags,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07002088 const audio_offload_info_t *offloadInfo,
Andy Hung179652e2015-05-31 22:49:46 -07002089 bool doNotReconnect,
2090 uint32_t suggestedFrameCount)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002091{
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002092 ALOGV("open(%u, %d, 0x%x, 0x%x, %d, %d 0x%x)", sampleRate, channelCount, channelMask,
2093 format, bufferCount, mSessionId, flags);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002094
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002095 // offloading is only supported in callback mode for now.
2096 // offloadInfo must be present if offload flag is set
2097 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) &&
2098 ((cb == NULL) || (offloadInfo == NULL))) {
2099 return BAD_VALUE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002100 }
2101
Andy Hung179652e2015-05-31 22:49:46 -07002102 // compute frame count for the AudioTrack internal buffer
2103 size_t frameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002104 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
2105 frameCount = 0; // AudioTrack will get frame count from AudioFlinger
2106 } else {
Andy Hung179652e2015-05-31 22:49:46 -07002107 // try to estimate the buffer processing fetch size from AudioFlinger.
2108 // framesPerBuffer is approximate and generally correct, except when it's not :-).
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002109 uint32_t afSampleRate;
2110 size_t afFrameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002111 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
2112 return NO_INIT;
2113 }
2114 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
2115 return NO_INIT;
2116 }
Ben Romberger259fb462018-08-07 17:58:53 -07002117 if (afSampleRate == 0) {
2118 return NO_INIT;
2119 }
Andy Hung179652e2015-05-31 22:49:46 -07002120 const size_t framesPerBuffer =
2121 (unsigned long long)sampleRate * afFrameCount / afSampleRate;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002122
Andy Hung179652e2015-05-31 22:49:46 -07002123 if (bufferCount == 0) {
Ben Romberger259fb462018-08-07 17:58:53 -07002124 if (framesPerBuffer == 0) {
2125 return NO_INIT;
2126 }
Andy Hung179652e2015-05-31 22:49:46 -07002127 // use suggestedFrameCount
2128 bufferCount = (suggestedFrameCount + framesPerBuffer - 1) / framesPerBuffer;
2129 }
2130 // Check argument bufferCount against the mininum buffer count
2131 if (bufferCount != 0 && bufferCount < mMinBufferCount) {
2132 ALOGV("bufferCount (%d) increased to %d", bufferCount, mMinBufferCount);
2133 bufferCount = mMinBufferCount;
2134 }
2135 // if frameCount is 0, then AudioTrack will get frame count from AudioFlinger
2136 // which will be the minimum size permitted.
2137 frameCount = bufferCount * framesPerBuffer;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002138 }
Andreas Huber20111aa2009-07-14 16:56:47 -07002139
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08002140 if (channelMask == CHANNEL_MASK_USE_CHANNEL_ORDER) {
Glenn Kastenab334fd2012-03-14 12:56:06 -07002141 channelMask = audio_channel_out_mask_from_count(channelCount);
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08002142 if (0 == channelMask) {
2143 ALOGE("open() error, can\'t derive mask for %d audio channels", channelCount);
2144 return NO_INIT;
2145 }
2146 }
Eric Laurent1948eb32012-04-13 16:50:19 -07002147
Andy Hungd1c74342015-07-07 16:54:23 -07002148 Mutex::Autolock lock(mLock);
Andy Hung179652e2015-05-31 22:49:46 -07002149 mCallback = cb;
2150 mCallbackCookie = cookie;
2151
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002152 // Check whether we can recycle the track
2153 bool reuse = false;
2154 bool bothOffloaded = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07002155
Glenn Kasten2799d742013-05-30 14:33:29 -07002156 if (mRecycledTrack != 0) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002157 // check whether we are switching between two offloaded tracks
2158 bothOffloaded = (flags & mRecycledTrack->getFlags()
2159 & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0;
Marco Nelissen67295b52012-06-11 14:52:53 -07002160
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002161 // check if the existing track can be reused as-is, or if a new track needs to be created.
2162 reuse = true;
2163
Marco Nelissen67295b52012-06-11 14:52:53 -07002164 if ((mCallbackData == NULL && mCallback != NULL) ||
2165 (mCallbackData != NULL && mCallback == NULL)) {
2166 // recycled track uses callbacks but the caller wants to use writes, or vice versa
2167 ALOGV("can't chain callback and write");
2168 reuse = false;
2169 } else if ((mRecycledTrack->getSampleRate() != sampleRate) ||
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002170 (mRecycledTrack->channelCount() != (uint32_t)channelCount) ) {
2171 ALOGV("samplerate, channelcount differ: %u/%u Hz, %u/%d ch",
Marco Nelissen67295b52012-06-11 14:52:53 -07002172 mRecycledTrack->getSampleRate(), sampleRate,
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002173 mRecycledTrack->channelCount(), channelCount);
Marco Nelissen67295b52012-06-11 14:52:53 -07002174 reuse = false;
2175 } else if (flags != mFlags) {
2176 ALOGV("output flags differ %08x/%08x", flags, mFlags);
2177 reuse = false;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002178 } else if (mRecycledTrack->format() != format) {
2179 reuse = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07002180 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002181 } else {
2182 ALOGV("no track available to recycle");
2183 }
2184
2185 ALOGV_IF(bothOffloaded, "both tracks offloaded");
2186
2187 // If we can't recycle and both tracks are offloaded
2188 // we must close the previous output before opening a new one
2189 if (bothOffloaded && !reuse) {
2190 ALOGV("both offloaded and not recycling");
Andy Hungd1c74342015-07-07 16:54:23 -07002191 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002192 }
2193
2194 sp<AudioTrack> t;
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002195 sp<CallbackData> newcbd;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002196
2197 // We don't attempt to create a new track if we are recycling an
2198 // offloaded track. But, if we are recycling a non-offloaded or we
2199 // are switching where one is offloaded and one isn't then we create
2200 // the new track in advance so that we can read additional stream info
2201
2202 if (!(reuse && bothOffloaded)) {
2203 ALOGV("creating new AudioTrack");
2204
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002205 if (mCallback != nullptr) {
2206 newcbd = sp<CallbackData>::make(wp<AudioOutput>::fromExisting(this));
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002207 t = new AudioTrack(
2208 mStreamType,
2209 sampleRate,
2210 format,
2211 channelMask,
2212 frameCount,
2213 flags,
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002214 newcbd,
2215 0, // notification frames
2216 mSessionId,
2217 AudioTrack::TRANSFER_CALLBACK,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002218 offloadInfo,
Svet Ganov33761132021-05-13 22:51:08 +00002219 mAttributionSource,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07002220 mAttributes,
jiabin156c6872017-10-06 09:47:15 -07002221 doNotReconnect,
2222 1.0f, // default value for maxRequiredSpeed
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002223 mSelectedDeviceId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002224 } else {
Andy Hungff874dc2016-04-11 16:49:09 -07002225 // TODO: Due to buffer memory concerns, we use a max target playback speed
2226 // based on mPlaybackRate at the time of open (instead of kMaxRequiredSpeed),
2227 // also clamping the target speed to 1.0 <= targetSpeed <= kMaxRequiredSpeed.
2228 const float targetSpeed =
2229 std::min(std::max(mPlaybackRate.mSpeed, 1.0f), kMaxRequiredSpeed);
2230 ALOGW_IF(targetSpeed != mPlaybackRate.mSpeed,
2231 "track target speed:%f clamped from playback speed:%f",
2232 targetSpeed, mPlaybackRate.mSpeed);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002233 t = new AudioTrack(
2234 mStreamType,
2235 sampleRate,
2236 format,
2237 channelMask,
2238 frameCount,
2239 flags,
Atneya Nairc1bf42b2021-11-29 19:00:54 -05002240 nullptr, // callback
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002241 0, // notification frames
2242 mSessionId,
2243 AudioTrack::TRANSFER_DEFAULT,
2244 NULL, // offload info
Svet Ganov33761132021-05-13 22:51:08 +00002245 mAttributionSource,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07002246 mAttributes,
Andy Hungff874dc2016-04-11 16:49:09 -07002247 doNotReconnect,
jiabin156c6872017-10-06 09:47:15 -07002248 targetSpeed,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002249 mSelectedDeviceId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002250 }
Andy Hunga6b27032020-04-27 10:34:24 -07002251 // Set caller name so it can be logged in destructor.
2252 // MediaMetricsConstants.h: AMEDIAMETRICS_PROP_CALLERNAME_VALUE_MEDIA
2253 t->setCallerName("media");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002254 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
2255 ALOGE("Unable to create audio track");
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002256 // t, newcbd goes out of scope, so reference count drops to zero
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002257 return NO_INIT;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07002258 } else {
2259 // successful AudioTrack initialization implies a legacy stream type was generated
2260 // from the audio attributes
2261 mStreamType = t->streamType();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002262 }
2263 }
2264
2265 if (reuse) {
2266 CHECK(mRecycledTrack != NULL);
2267
2268 if (!bothOffloaded) {
2269 if (mRecycledTrack->frameCount() != t->frameCount()) {
Andy Hung833b4752016-04-04 17:15:48 -07002270 ALOGV("framecount differs: %zu/%zu frames",
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002271 mRecycledTrack->frameCount(), t->frameCount());
2272 reuse = false;
2273 }
Jaideep Sharmab3ce4482020-11-16 11:52:35 +05302274 // If recycled and new tracks are not on the same output,
2275 // don't reuse the recycled one.
2276 if (mRecycledTrack->getOutput() != t->getOutput()) {
2277 ALOGV("output has changed, don't reuse track");
2278 reuse = false;
2279 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002280 }
2281
Marco Nelissen67295b52012-06-11 14:52:53 -07002282 if (reuse) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002283 ALOGV("chaining to next output and recycling track");
Andy Hungd1c74342015-07-07 16:54:23 -07002284 close_l();
Marco Nelissen67295b52012-06-11 14:52:53 -07002285 mTrack = mRecycledTrack;
Glenn Kasten2799d742013-05-30 14:33:29 -07002286 mRecycledTrack.clear();
Marco Nelissen67295b52012-06-11 14:52:53 -07002287 if (mCallbackData != NULL) {
2288 mCallbackData->setOutput(this);
2289 }
Wei Jiae0bbac92016-07-18 16:04:53 -07002290 return updateTrack();
Marco Nelissen67295b52012-06-11 14:52:53 -07002291 }
Marco Nelissen67295b52012-06-11 14:52:53 -07002292 }
2293
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002294 // we're not going to reuse the track, unblock and flush it
2295 // this was done earlier if both tracks are offloaded
2296 if (!bothOffloaded) {
Andy Hungd1c74342015-07-07 16:54:23 -07002297 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002298 }
2299
2300 CHECK((t != NULL) && ((mCallback == NULL) || (newcbd != NULL)));
2301
Marco Nelissen67295b52012-06-11 14:52:53 -07002302 mCallbackData = newcbd;
Steve Block3856b092011-10-20 11:56:00 +01002303 ALOGV("setVolume");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002304 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07002305
Andy Hung39399b62017-04-21 15:07:45 -07002306 // Restore VolumeShapers for the MediaPlayer in case the track was recreated
2307 // due to an output sink error (e.g. offload to non-offload switch).
2308 mVolumeHandler->forall([&t](const VolumeShaper &shaper) -> VolumeShaper::Status {
2309 sp<VolumeShaper::Operation> operationToEnd =
2310 new VolumeShaper::Operation(shaper.mOperation);
2311 // TODO: Ideally we would restore to the exact xOffset position
2312 // as returned by getVolumeShaperState(), but we don't have that
2313 // information when restoring at the client unless we periodically poll
2314 // the server or create shared memory state.
2315 //
2316 // For now, we simply advance to the end of the VolumeShaper effect
2317 // if it has been started.
2318 if (shaper.isStarted()) {
Andy Hungf3702642017-05-05 17:33:32 -07002319 operationToEnd->setNormalizedTime(1.f);
Andy Hung39399b62017-04-21 15:07:45 -07002320 }
2321 return t->applyVolumeShaper(shaper.mConfiguration, operationToEnd);
Andy Hung4ef88d72017-02-21 19:47:53 -08002322 });
Andy Hung4ef88d72017-02-21 19:47:53 -08002323
Vlad Popab4f5b012022-08-12 15:53:09 +02002324 if (mCachedPlayerIId != PLAYER_PIID_INVALID) {
2325 t->setPlayerIId(mCachedPlayerIId);
2326 }
2327
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002328 mSampleRateHz = sampleRate;
Preetam Singh Ranawat2e17eef2015-08-12 12:11:46 -07002329 mFlags = flags;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002330 mMsecsPerFrame = 1E3f / (mPlaybackRate.mSpeed * sampleRate);
Andy Hungd1c74342015-07-07 16:54:23 -07002331 mFrameSize = t->frameSize();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002332 mTrack = t;
Eric Laurent2beeb502010-07-16 07:43:46 -07002333
Wei Jiae0bbac92016-07-18 16:04:53 -07002334 return updateTrack();
2335}
2336
2337status_t MediaPlayerService::AudioOutput::updateTrack() {
2338 if (mTrack == NULL) {
2339 return NO_ERROR;
2340 }
2341
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002342 status_t res = NO_ERROR;
Wei Jia0162d002015-06-09 11:59:33 -07002343 // Note some output devices may give us a direct track even though we don't specify it.
2344 // Example: Line application b/17459982.
Wei Jiae0bbac92016-07-18 16:04:53 -07002345 if ((mTrack->getFlags()
2346 & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) {
2347 res = mTrack->setPlaybackRate(mPlaybackRate);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002348 if (res == NO_ERROR) {
Wei Jiae0bbac92016-07-18 16:04:53 -07002349 mTrack->setAuxEffectSendLevel(mSendLevel);
2350 res = mTrack->attachAuxEffect(mAuxEffectId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002351 }
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002352 }
jiabin156c6872017-10-06 09:47:15 -07002353 mTrack->setOutputDevice(mSelectedDeviceId);
2354 if (mDeviceCallbackEnabled) {
2355 mTrack->addAudioDeviceCallback(mDeviceCallback.promote());
2356 }
Wei Jiae0bbac92016-07-18 16:04:53 -07002357 ALOGV("updateTrack() DONE status %d", res);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002358 return res;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002359}
2360
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002361status_t MediaPlayerService::AudioOutput::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002362{
Steve Block3856b092011-10-20 11:56:00 +01002363 ALOGV("start");
Andy Hungd1c74342015-07-07 16:54:23 -07002364 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08002365 if (mCallbackData != NULL) {
2366 mCallbackData->endTrackSwitch();
2367 }
Glenn Kasten2799d742013-05-30 14:33:29 -07002368 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002369 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07002370 mTrack->setAuxEffectSendLevel(mSendLevel);
Andy Hung39399b62017-04-21 15:07:45 -07002371 status_t status = mTrack->start();
2372 if (status == NO_ERROR) {
2373 mVolumeHandler->setStarted();
2374 }
2375 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002376 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002377 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002378}
2379
Vlad Popab4f5b012022-08-12 15:53:09 +02002380void MediaPlayerService::AudioOutput::setPlayerIId(int32_t playerIId)
2381{
2382 ALOGV("setPlayerIId(%d)", playerIId);
2383 Mutex::Autolock lock(mLock);
2384 mCachedPlayerIId = playerIId;
2385
2386 if (mTrack != nullptr) {
2387 mTrack->setPlayerIId(mCachedPlayerIId);
2388 }
2389}
2390
Marco Nelissen6b74d672012-02-28 16:07:44 -08002391void MediaPlayerService::AudioOutput::setNextOutput(const sp<AudioOutput>& nextOutput) {
Andy Hungd1c74342015-07-07 16:54:23 -07002392 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08002393 mNextOutput = nextOutput;
2394}
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08002395
Marco Nelissen6b74d672012-02-28 16:07:44 -08002396void MediaPlayerService::AudioOutput::switchToNextOutput() {
2397 ALOGV("switchToNextOutput");
Andy Hungd1c74342015-07-07 16:54:23 -07002398
2399 // Try to acquire the callback lock before moving track (without incurring deadlock).
2400 const unsigned kMaxSwitchTries = 100;
2401 Mutex::Autolock lock(mLock);
2402 for (unsigned tries = 0;;) {
2403 if (mTrack == 0) {
2404 return;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002405 }
Andy Hungd1c74342015-07-07 16:54:23 -07002406 if (mNextOutput != NULL && mNextOutput != this) {
2407 if (mCallbackData != NULL) {
2408 // two alternative approaches
2409#if 1
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002410 sp<CallbackData> callbackData = mCallbackData;
Andy Hungd1c74342015-07-07 16:54:23 -07002411 mLock.unlock();
2412 // proper acquisition sequence
2413 callbackData->lock();
2414 mLock.lock();
2415 // Caution: it is unlikely that someone deleted our callback or changed our target
2416 if (callbackData != mCallbackData || mNextOutput == NULL || mNextOutput == this) {
2417 // fatal if we are starved out.
2418 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2419 "switchToNextOutput() cannot obtain correct lock sequence");
2420 callbackData->unlock();
2421 continue;
2422 }
2423 callbackData->mSwitching = true; // begin track switch
Wei Jiaadee56a2016-08-05 15:40:34 -07002424 callbackData->setOutput(NULL);
Andy Hungd1c74342015-07-07 16:54:23 -07002425#else
2426 // tryBeginTrackSwitch() returns false if the callback has the lock.
2427 if (!mCallbackData->tryBeginTrackSwitch()) {
2428 // fatal if we are starved out.
2429 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2430 "switchToNextOutput() cannot obtain callback lock");
2431 mLock.unlock();
2432 usleep(5 * 1000 /* usec */); // allow callback to use AudioOutput
2433 mLock.lock();
2434 continue;
2435 }
2436#endif
2437 }
2438
2439 Mutex::Autolock nextLock(mNextOutput->mLock);
2440
2441 // If the next output track is not NULL, then it has been
2442 // opened already for playback.
2443 // This is possible even without the next player being started,
2444 // for example, the next player could be prepared and seeked.
2445 //
2446 // Presuming it isn't advisable to force the track over.
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002447 if (mNextOutput->mTrack == nullptr) {
Andy Hungd1c74342015-07-07 16:54:23 -07002448 ALOGD("Recycling track for gapless playback");
Andy Hungd1c74342015-07-07 16:54:23 -07002449 mNextOutput->mCallbackData = mCallbackData;
2450 mNextOutput->mRecycledTrack = mTrack;
2451 mNextOutput->mSampleRateHz = mSampleRateHz;
2452 mNextOutput->mMsecsPerFrame = mMsecsPerFrame;
Andy Hungd1c74342015-07-07 16:54:23 -07002453 mNextOutput->mFlags = mFlags;
2454 mNextOutput->mFrameSize = mFrameSize;
2455 close_l();
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002456 mCallbackData.clear();
Andy Hungd1c74342015-07-07 16:54:23 -07002457 } else {
2458 ALOGW("Ignoring gapless playback because next player has already started");
2459 // remove track in case resource needed for future players.
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002460 if (mCallbackData != nullptr) {
Andy Hungd1c74342015-07-07 16:54:23 -07002461 mCallbackData->endTrackSwitch(); // release lock for callbacks before close.
2462 }
2463 close_l();
2464 }
2465 }
2466 break;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002467 }
2468}
2469
Wei Jia7d3f4df2015-03-03 15:28:00 -08002470ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002471{
Andy Hungd1c74342015-07-07 16:54:23 -07002472 Mutex::Autolock lock(mLock);
Glenn Kastenadad3d72014-02-21 14:51:43 -08002473 LOG_ALWAYS_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
Andreas Huber20111aa2009-07-14 16:56:47 -07002474
Steve Block3856b092011-10-20 11:56:00 +01002475 //ALOGV("write(%p, %u)", buffer, size);
Glenn Kasten2799d742013-05-30 14:33:29 -07002476 if (mTrack != 0) {
Andy Hung2f6e73d2016-04-08 12:12:58 -07002477 return mTrack->write(buffer, size, blocking);
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07002478 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002479 return NO_INIT;
2480}
2481
2482void MediaPlayerService::AudioOutput::stop()
2483{
Steve Block3856b092011-10-20 11:56:00 +01002484 ALOGV("stop");
Andy Hungd1c74342015-07-07 16:54:23 -07002485 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002486 if (mTrack != 0) mTrack->stop();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002487}
2488
2489void MediaPlayerService::AudioOutput::flush()
2490{
Steve Block3856b092011-10-20 11:56:00 +01002491 ALOGV("flush");
Andy Hungd1c74342015-07-07 16:54:23 -07002492 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002493 if (mTrack != 0) mTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002494}
2495
2496void MediaPlayerService::AudioOutput::pause()
2497{
Steve Block3856b092011-10-20 11:56:00 +01002498 ALOGV("pause");
Andy Hung959b5b82021-09-24 10:46:20 -07002499 // We use pauseAndWait() instead of pause() to ensure tracks ramp to silence before
2500 // any flush. We choose 40 ms timeout to allow 1 deep buffer mixer period
2501 // to occur. Often waiting is 0 - 20 ms.
2502 using namespace std::chrono_literals;
2503 constexpr auto TIMEOUT_MS = 40ms;
Andy Hungd1c74342015-07-07 16:54:23 -07002504 Mutex::Autolock lock(mLock);
Andy Hung959b5b82021-09-24 10:46:20 -07002505 if (mTrack != 0) mTrack->pauseAndWait(TIMEOUT_MS);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002506}
2507
2508void MediaPlayerService::AudioOutput::close()
2509{
Steve Block3856b092011-10-20 11:56:00 +01002510 ALOGV("close");
Erik Wolsheimer7845a1f2015-10-30 12:07:52 -07002511 sp<AudioTrack> track;
2512 {
2513 Mutex::Autolock lock(mLock);
2514 track = mTrack;
Jaideep Sharma511599f2022-01-06 13:38:57 +05302515 }
2516
2517 // do not hold lock while joining.
2518 if (track) {
2519 track->stopAndJoinCallbacks();
2520 }
2521
2522 {
2523 Mutex::Autolock lock(mLock);
Erik Wolsheimer7845a1f2015-10-30 12:07:52 -07002524 close_l(); // clears mTrack
2525 }
2526 // destruction of the track occurs outside of mutex.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002527}
2528
2529void MediaPlayerService::AudioOutput::setVolume(float left, float right)
2530{
Steve Block3856b092011-10-20 11:56:00 +01002531 ALOGV("setVolume(%f, %f)", left, right);
Andy Hungd1c74342015-07-07 16:54:23 -07002532 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002533 mLeftVolume = left;
2534 mRightVolume = right;
Glenn Kasten2799d742013-05-30 14:33:29 -07002535 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002536 mTrack->setVolume(left, right);
2537 }
2538}
2539
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002540status_t MediaPlayerService::AudioOutput::setPlaybackRate(const AudioPlaybackRate &rate)
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002541{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002542 ALOGV("setPlaybackRate(%f %f %d %d)",
2543 rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Andy Hungd1c74342015-07-07 16:54:23 -07002544 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002545 if (mTrack == 0) {
2546 // remember rate so that we can set it when the track is opened
2547 mPlaybackRate = rate;
2548 return OK;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002549 }
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002550 status_t res = mTrack->setPlaybackRate(rate);
2551 if (res != NO_ERROR) {
2552 return res;
2553 }
2554 // rate.mSpeed is always greater than 0 if setPlaybackRate succeeded
2555 CHECK_GT(rate.mSpeed, 0.f);
2556 mPlaybackRate = rate;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002557 if (mSampleRateHz != 0) {
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002558 mMsecsPerFrame = 1E3f / (rate.mSpeed * mSampleRateHz);
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002559 }
2560 return res;
2561}
2562
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002563status_t MediaPlayerService::AudioOutput::getPlaybackRate(AudioPlaybackRate *rate)
2564{
2565 ALOGV("setPlaybackRate");
Andy Hungd1c74342015-07-07 16:54:23 -07002566 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002567 if (mTrack == 0) {
2568 return NO_INIT;
2569 }
2570 *rate = mTrack->getPlaybackRate();
2571 return NO_ERROR;
2572}
2573
Eric Laurent2beeb502010-07-16 07:43:46 -07002574status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
2575{
Steve Block3856b092011-10-20 11:56:00 +01002576 ALOGV("setAuxEffectSendLevel(%f)", level);
Andy Hungd1c74342015-07-07 16:54:23 -07002577 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002578 mSendLevel = level;
Glenn Kasten2799d742013-05-30 14:33:29 -07002579 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002580 return mTrack->setAuxEffectSendLevel(level);
2581 }
2582 return NO_ERROR;
2583}
2584
2585status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
2586{
Steve Block3856b092011-10-20 11:56:00 +01002587 ALOGV("attachAuxEffect(%d)", effectId);
Andy Hungd1c74342015-07-07 16:54:23 -07002588 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002589 mAuxEffectId = effectId;
Glenn Kasten2799d742013-05-30 14:33:29 -07002590 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002591 return mTrack->attachAuxEffect(effectId);
2592 }
2593 return NO_ERROR;
2594}
2595
jiabin156c6872017-10-06 09:47:15 -07002596status_t MediaPlayerService::AudioOutput::setOutputDevice(audio_port_handle_t deviceId)
2597{
2598 ALOGV("setOutputDevice(%d)", deviceId);
2599 Mutex::Autolock lock(mLock);
2600 mSelectedDeviceId = deviceId;
2601 if (mTrack != 0) {
2602 return mTrack->setOutputDevice(deviceId);
2603 }
2604 return NO_ERROR;
2605}
2606
2607status_t MediaPlayerService::AudioOutput::getRoutedDeviceId(audio_port_handle_t* deviceId)
2608{
2609 ALOGV("getRoutedDeviceId");
2610 Mutex::Autolock lock(mLock);
2611 if (mTrack != 0) {
jiabin161b64f2017-11-17 09:31:48 -08002612 mRoutedDeviceId = mTrack->getRoutedDeviceId();
jiabin156c6872017-10-06 09:47:15 -07002613 }
jiabin161b64f2017-11-17 09:31:48 -08002614 *deviceId = mRoutedDeviceId;
2615 return NO_ERROR;
jiabin156c6872017-10-06 09:47:15 -07002616}
2617
2618status_t MediaPlayerService::AudioOutput::enableAudioDeviceCallback(bool enabled)
2619{
2620 ALOGV("enableAudioDeviceCallback, %d", enabled);
2621 Mutex::Autolock lock(mLock);
2622 mDeviceCallbackEnabled = enabled;
2623 if (mTrack != 0) {
2624 status_t status;
2625 if (enabled) {
2626 status = mTrack->addAudioDeviceCallback(mDeviceCallback.promote());
2627 } else {
2628 status = mTrack->removeAudioDeviceCallback(mDeviceCallback.promote());
2629 }
2630 return status;
2631 }
2632 return NO_ERROR;
2633}
2634
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002635VolumeShaper::Status MediaPlayerService::AudioOutput::applyVolumeShaper(
2636 const sp<VolumeShaper::Configuration>& configuration,
2637 const sp<VolumeShaper::Operation>& operation)
2638{
2639 Mutex::Autolock lock(mLock);
2640 ALOGV("AudioOutput::applyVolumeShaper");
Andy Hung4ef88d72017-02-21 19:47:53 -08002641
Pawan Wagh8282bb42023-07-05 23:01:17 +00002642 if (configuration == nullptr) {
2643 ALOGE("AudioOutput::applyVolumeShaper Null configuration parameter");
2644 return VolumeShaper::Status(BAD_VALUE);
2645 }
2646
2647 if (operation == nullptr) {
2648 ALOGE("AudioOutput::applyVolumeShaper Null operation parameter");
2649 return VolumeShaper::Status(BAD_VALUE);
2650 }
2651
Andy Hung4ef88d72017-02-21 19:47:53 -08002652 mVolumeHandler->setIdIfNecessary(configuration);
Andy Hung39399b62017-04-21 15:07:45 -07002653
2654 VolumeShaper::Status status;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002655 if (mTrack != 0) {
Andy Hung39399b62017-04-21 15:07:45 -07002656 status = mTrack->applyVolumeShaper(configuration, operation);
2657 if (status >= 0) {
2658 (void)mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hungf3702642017-05-05 17:33:32 -07002659 if (mTrack->isPlaying()) { // match local AudioTrack to properly restore.
2660 mVolumeHandler->setStarted();
2661 }
Andy Hung39399b62017-04-21 15:07:45 -07002662 }
Andy Hung4ef88d72017-02-21 19:47:53 -08002663 } else {
Andy Hungc01eddb2017-07-21 16:42:41 -07002664 // VolumeShapers are not affected when a track moves between players for
2665 // gapless playback (setNextMediaPlayer).
2666 // We forward VolumeShaper operations that do not change configuration
2667 // to the new player so that unducking may occur as expected.
2668 // Unducking is an idempotent operation, same if applied back-to-back.
2669 if (configuration->getType() == VolumeShaper::Configuration::TYPE_ID
2670 && mNextOutput != nullptr) {
2671 ALOGV("applyVolumeShaper: Attempting to forward missed operation: %s %s",
2672 configuration->toString().c_str(), operation->toString().c_str());
2673 Mutex::Autolock nextLock(mNextOutput->mLock);
2674
2675 // recycled track should be forwarded from this AudioSink by switchToNextOutput
2676 sp<AudioTrack> track = mNextOutput->mRecycledTrack;
2677 if (track != nullptr) {
2678 ALOGD("Forward VolumeShaper operation to recycled track %p", track.get());
2679 (void)track->applyVolumeShaper(configuration, operation);
2680 } else {
2681 // There is a small chance that the unduck occurs after the next
2682 // player has already started, but before it is registered to receive
2683 // the unduck command.
2684 track = mNextOutput->mTrack;
2685 if (track != nullptr) {
2686 ALOGD("Forward VolumeShaper operation to track %p", track.get());
2687 (void)track->applyVolumeShaper(configuration, operation);
2688 }
2689 }
2690 }
Andy Hung39399b62017-04-21 15:07:45 -07002691 status = mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002692 }
Andy Hung39399b62017-04-21 15:07:45 -07002693 return status;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002694}
2695
2696sp<VolumeShaper::State> MediaPlayerService::AudioOutput::getVolumeShaperState(int id)
2697{
2698 Mutex::Autolock lock(mLock);
2699 if (mTrack != 0) {
2700 return mTrack->getVolumeShaperState(id);
Andy Hung4ef88d72017-02-21 19:47:53 -08002701 } else {
2702 return mVolumeHandler->getVolumeShaperState(id);
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002703 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002704}
2705
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002706size_t MediaPlayerService::AudioOutput::CallbackData::onMoreData(const AudioTrack::Buffer& buffer) {
2707 ALOGD("data callback");
2708 lock();
2709 sp<AudioOutput> me = getOutput();
2710 if (me == nullptr) {
2711 unlock();
2712 return 0;
2713 }
2714 size_t actualSize = (*me->mCallback)(
Andy Hunge42b6482024-10-16 19:16:50 -07002715 me, buffer.data(), buffer.size(), me->mCallbackCookie,
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002716 CB_EVENT_FILL_BUFFER);
2717
2718 // Log when no data is returned from the callback.
2719 // (1) We may have no data (especially with network streaming sources).
2720 // (2) We may have reached the EOS and the audio track is not stopped yet.
2721 // Note that AwesomePlayer/AudioPlayer will only return zero size when it reaches the EOS.
2722 // NuPlayerRenderer will return zero when it doesn't have data (it doesn't block to fill).
2723 //
2724 // This is a benign busy-wait, with the next data request generated 10 ms or more later;
2725 // nevertheless for power reasons, we don't want to see too many of these.
2726
Santiago Seifert578aeb52022-10-24 07:59:12 +00002727 ALOGV_IF(actualSize == 0 && buffer.size() > 0, "callbackwrapper: empty buffer returned");
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002728 unlock();
2729 return actualSize;
2730}
2731
2732void MediaPlayerService::AudioOutput::CallbackData::onStreamEnd() {
2733 lock();
2734 sp<AudioOutput> me = getOutput();
2735 if (me == nullptr) {
2736 unlock();
Marco Nelissen6b74d672012-02-28 16:07:44 -08002737 return;
2738 }
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002739 ALOGV("callbackwrapper: deliver EVENT_STREAM_END");
Andy Hunge42b6482024-10-16 19:16:50 -07002740 (*me->mCallback)(me, nullptr /* buffer */, 0 /* size */,
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002741 me->mCallbackCookie, CB_EVENT_STREAM_END);
2742 unlock();
2743}
Andreas Huber20111aa2009-07-14 16:56:47 -07002744
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002745
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002746void MediaPlayerService::AudioOutput::CallbackData::onNewIAudioTrack() {
2747 lock();
2748 sp<AudioOutput> me = getOutput();
2749 if (me == nullptr) {
2750 unlock();
2751 return;
Andreas Huber51c1e0e2011-04-04 11:43:40 -07002752 }
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002753 ALOGV("callbackwrapper: deliver EVENT_TEAR_DOWN");
Andy Hunge42b6482024-10-16 19:16:50 -07002754 (*me->mCallback)(me, nullptr /* buffer */, 0 /* size */,
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002755 me->mCallbackCookie, CB_EVENT_TEAR_DOWN);
2756 unlock();
2757}
Andreas Huber51c1e0e2011-04-04 11:43:40 -07002758
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002759void MediaPlayerService::AudioOutput::CallbackData::onUnderrun() {
2760 // This occurs when there is no data available, typically
2761 // when there is a failure to supply data to the AudioTrack. It can also
2762 // occur in non-offloaded mode when the audio device comes out of standby.
2763 //
2764 // If an AudioTrack underruns it outputs silence. Since this happens suddenly
2765 // it may sound like an audible pop or glitch.
2766 //
2767 // The underrun event is sent once per track underrun; the condition is reset
2768 // when more data is sent to the AudioTrack.
2769 ALOGD("callbackwrapper: EVENT_UNDERRUN (discarded)");
2770
Andreas Huber20111aa2009-07-14 16:56:47 -07002771}
2772
Glenn Kastend848eb42016-03-08 13:42:11 -08002773audio_session_t MediaPlayerService::AudioOutput::getSessionId() const
Eric Laurent8c563ed2010-10-07 18:23:03 -07002774{
Andy Hungd1c74342015-07-07 16:54:23 -07002775 Mutex::Autolock lock(mLock);
Eric Laurent8c563ed2010-10-07 18:23:03 -07002776 return mSessionId;
2777}
2778
Eric Laurent6f59db12013-07-26 17:16:50 -07002779uint32_t MediaPlayerService::AudioOutput::getSampleRate() const
2780{
Andy Hungd1c74342015-07-07 16:54:23 -07002781 Mutex::Autolock lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -07002782 if (mTrack == 0) return 0;
2783 return mTrack->getSampleRate();
2784}
2785
Andy Hungf2c87b32016-04-07 19:49:29 -07002786int64_t MediaPlayerService::AudioOutput::getBufferDurationInUs() const
2787{
2788 Mutex::Autolock lock(mLock);
2789 if (mTrack == 0) {
2790 return 0;
2791 }
2792 int64_t duration;
2793 if (mTrack->getBufferDurationInUs(&duration) != OK) {
2794 return 0;
2795 }
2796 return duration;
2797}
2798
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002799////////////////////////////////////////////////////////////////////////////////
2800
2801struct CallbackThread : public Thread {
2802 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
2803 MediaPlayerBase::AudioSink::AudioCallback cb,
Andy Hunge42b6482024-10-16 19:16:50 -07002804 const wp<RefBase>& cookie);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002805
2806protected:
2807 virtual ~CallbackThread();
2808
2809 virtual bool threadLoop();
2810
2811private:
2812 wp<MediaPlayerBase::AudioSink> mSink;
2813 MediaPlayerBase::AudioSink::AudioCallback mCallback;
Andy Hunge42b6482024-10-16 19:16:50 -07002814 wp<RefBase> mCookie;
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002815 void *mBuffer;
2816 size_t mBufferSize;
2817
2818 CallbackThread(const CallbackThread &);
2819 CallbackThread &operator=(const CallbackThread &);
2820};
2821
2822CallbackThread::CallbackThread(
2823 const wp<MediaPlayerBase::AudioSink> &sink,
2824 MediaPlayerBase::AudioSink::AudioCallback cb,
Andy Hunge42b6482024-10-16 19:16:50 -07002825 const wp<RefBase>& cookie)
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002826 : mSink(sink),
2827 mCallback(cb),
2828 mCookie(cookie),
2829 mBuffer(NULL),
2830 mBufferSize(0) {
2831}
2832
2833CallbackThread::~CallbackThread() {
2834 if (mBuffer) {
2835 free(mBuffer);
2836 mBuffer = NULL;
2837 }
2838}
2839
2840bool CallbackThread::threadLoop() {
2841 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
2842 if (sink == NULL) {
2843 return false;
2844 }
2845
2846 if (mBuffer == NULL) {
2847 mBufferSize = sink->bufferSize();
2848 mBuffer = malloc(mBufferSize);
2849 }
2850
2851 size_t actualSize =
Andy Hunge42b6482024-10-16 19:16:50 -07002852 (*mCallback)(sink, mBuffer, mBufferSize, mCookie,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002853 MediaPlayerBase::AudioSink::CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002854
2855 if (actualSize > 0) {
2856 sink->write(mBuffer, actualSize);
Andy Hunga31335a2014-08-20 17:37:59 -07002857 // Could return false on sink->write() error or short count.
2858 // Not necessarily appropriate but would work for AudioCache behavior.
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002859 }
2860
2861 return true;
2862}
2863
2864////////////////////////////////////////////////////////////////////////////////
2865
Chong Zhange5b9b692017-05-11 11:44:56 -07002866void MediaPlayerService::addBatteryData(uint32_t params) {
2867 mBatteryTracker.addBatteryData(params);
2868}
2869
2870status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
2871 return mBatteryTracker.pullBatteryData(reply);
2872}
2873
2874MediaPlayerService::BatteryTracker::BatteryTracker() {
2875 mBatteryAudio.refCount = 0;
2876 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2877 mBatteryAudio.deviceOn[i] = 0;
2878 mBatteryAudio.lastTime[i] = 0;
2879 mBatteryAudio.totalTime[i] = 0;
2880 }
2881 // speaker is on by default
2882 mBatteryAudio.deviceOn[SPEAKER] = 1;
2883
2884 // reset battery stats
2885 // if the mediaserver has crashed, battery stats could be left
2886 // in bad state, reset the state upon service start.
2887 BatteryNotifier::getInstance().noteResetVideo();
2888}
2889
2890void MediaPlayerService::BatteryTracker::addBatteryData(uint32_t params)
Gloria Wang7cf180c2011-02-19 18:37:57 -08002891{
2892 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002893
2894 int32_t time = systemTime() / 1000000L;
2895
2896 // change audio output devices. This notification comes from AudioFlinger
2897 if ((params & kBatteryDataSpeakerOn)
2898 || (params & kBatteryDataOtherAudioDeviceOn)) {
2899
2900 int deviceOn[NUM_AUDIO_DEVICES];
2901 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2902 deviceOn[i] = 0;
2903 }
2904
2905 if ((params & kBatteryDataSpeakerOn)
2906 && (params & kBatteryDataOtherAudioDeviceOn)) {
2907 deviceOn[SPEAKER_AND_OTHER] = 1;
2908 } else if (params & kBatteryDataSpeakerOn) {
2909 deviceOn[SPEAKER] = 1;
2910 } else {
2911 deviceOn[OTHER_AUDIO_DEVICE] = 1;
2912 }
2913
2914 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2915 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
2916
2917 if (mBatteryAudio.refCount > 0) { // if playing audio
2918 if (!deviceOn[i]) {
2919 mBatteryAudio.lastTime[i] += time;
2920 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2921 mBatteryAudio.lastTime[i] = 0;
2922 } else {
2923 mBatteryAudio.lastTime[i] = 0 - time;
2924 }
2925 }
2926
2927 mBatteryAudio.deviceOn[i] = deviceOn[i];
2928 }
2929 }
2930 return;
2931 }
2932
Marco Nelissenb7848f12014-12-04 08:57:56 -08002933 // an audio stream is started
Gloria Wang9ee159b2011-02-24 14:51:45 -08002934 if (params & kBatteryDataAudioFlingerStart) {
2935 // record the start time only if currently no other audio
2936 // is being played
2937 if (mBatteryAudio.refCount == 0) {
2938 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2939 if (mBatteryAudio.deviceOn[i]) {
2940 mBatteryAudio.lastTime[i] -= time;
2941 }
2942 }
2943 }
2944
2945 mBatteryAudio.refCount ++;
2946 return;
2947
2948 } else if (params & kBatteryDataAudioFlingerStop) {
2949 if (mBatteryAudio.refCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002950 ALOGW("Battery track warning: refCount is <= 0");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002951 return;
2952 }
2953
2954 // record the stop time only if currently this is the only
2955 // audio being played
2956 if (mBatteryAudio.refCount == 1) {
2957 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2958 if (mBatteryAudio.deviceOn[i]) {
2959 mBatteryAudio.lastTime[i] += time;
2960 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2961 mBatteryAudio.lastTime[i] = 0;
2962 }
2963 }
2964 }
2965
2966 mBatteryAudio.refCount --;
2967 return;
2968 }
2969
Andy Hung1afd0982016-11-08 16:13:44 -08002970 uid_t uid = IPCThreadState::self()->getCallingUid();
Gloria Wang7cf180c2011-02-19 18:37:57 -08002971 if (uid == AID_MEDIA) {
2972 return;
2973 }
2974 int index = mBatteryData.indexOfKey(uid);
Gloria Wang7cf180c2011-02-19 18:37:57 -08002975
2976 if (index < 0) { // create a new entry for this UID
2977 BatteryUsageInfo info;
2978 info.audioTotalTime = 0;
2979 info.videoTotalTime = 0;
2980 info.audioLastTime = 0;
2981 info.videoLastTime = 0;
2982 info.refCount = 0;
2983
Gloria Wang9ee159b2011-02-24 14:51:45 -08002984 if (mBatteryData.add(uid, info) == NO_MEMORY) {
Steve Block29357bc2012-01-06 19:20:56 +00002985 ALOGE("Battery track error: no memory for new app");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002986 return;
2987 }
Gloria Wang7cf180c2011-02-19 18:37:57 -08002988 }
2989
2990 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
2991
2992 if (params & kBatteryDataCodecStarted) {
2993 if (params & kBatteryDataTrackAudio) {
2994 info.audioLastTime -= time;
2995 info.refCount ++;
2996 }
2997 if (params & kBatteryDataTrackVideo) {
2998 info.videoLastTime -= time;
2999 info.refCount ++;
3000 }
3001 } else {
3002 if (info.refCount == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003003 ALOGW("Battery track warning: refCount is already 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08003004 return;
3005 } else if (info.refCount < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00003006 ALOGE("Battery track error: refCount < 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08003007 mBatteryData.removeItem(uid);
3008 return;
3009 }
3010
3011 if (params & kBatteryDataTrackAudio) {
3012 info.audioLastTime += time;
3013 info.refCount --;
3014 }
3015 if (params & kBatteryDataTrackVideo) {
3016 info.videoLastTime += time;
3017 info.refCount --;
3018 }
3019
3020 // no stream is being played by this UID
3021 if (info.refCount == 0) {
3022 info.audioTotalTime += info.audioLastTime;
3023 info.audioLastTime = 0;
3024 info.videoTotalTime += info.videoLastTime;
3025 info.videoLastTime = 0;
3026 }
3027 }
3028}
3029
Chong Zhange5b9b692017-05-11 11:44:56 -07003030status_t MediaPlayerService::BatteryTracker::pullBatteryData(Parcel* reply) {
Gloria Wang7cf180c2011-02-19 18:37:57 -08003031 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08003032
3033 // audio output devices usage
3034 int32_t time = systemTime() / 1000000L; //in ms
3035 int32_t totalTime;
3036
3037 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
3038 totalTime = mBatteryAudio.totalTime[i];
3039
3040 if (mBatteryAudio.deviceOn[i]
3041 && (mBatteryAudio.lastTime[i] != 0)) {
3042 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
3043 totalTime += tmpTime;
3044 }
3045
3046 reply->writeInt32(totalTime);
3047 // reset the total time
3048 mBatteryAudio.totalTime[i] = 0;
3049 }
3050
3051 // codec usage
Gloria Wang7cf180c2011-02-19 18:37:57 -08003052 BatteryUsageInfo info;
3053 int size = mBatteryData.size();
3054
3055 reply->writeInt32(size);
3056 int i = 0;
3057
3058 while (i < size) {
3059 info = mBatteryData.valueAt(i);
3060
3061 reply->writeInt32(mBatteryData.keyAt(i)); //UID
3062 reply->writeInt32(info.audioTotalTime);
3063 reply->writeInt32(info.videoTotalTime);
3064
3065 info.audioTotalTime = 0;
3066 info.videoTotalTime = 0;
3067
3068 // remove the UID entry where no stream is being played
3069 if (info.refCount <= 0) {
3070 mBatteryData.removeItemsAt(i);
3071 size --;
3072 i --;
3073 }
3074 i++;
3075 }
3076 return NO_ERROR;
3077}
Pawan Wagh074e53c2023-06-20 22:06:43 +00003078
3079#ifdef FUZZ_MODE_MEDIA_PLAYER_SERVICE
3080sp<MediaPlayerService> MediaPlayerService::createForFuzzTesting() {
3081 return sp<MediaPlayerService>::make();
3082}
3083#endif // FUZZ_MODE_MEDIA_PLAYER_SERVICE
3084
nikoa64c8c72009-07-20 15:07:26 -07003085} // namespace android