blob: 0067344dcc48a38a095a56a1be257c851593c580 [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,
Robert Wub7f8edc2024-11-04 19:54:38 +0000859 const DeviceIdVector& deviceIds) {
860 ALOGD("onAudioDeviceUpdate deviceIds: %s", toString(deviceIds).c_str());
jiabin156c6872017-10-06 09:47:15 -0700861 sp<MediaPlayerBase> listener = mListener.promote();
862 if (listener != NULL) {
Robert Wub7f8edc2024-11-04 19:54:38 +0000863 // Java should query the new device ids once it gets the event.
864 // TODO(b/378505346): Pass the deviceIds to Java to avoid race conditions.
865 listener->sendEvent(MEDIA_AUDIO_ROUTING_CHANGED, audioIo);
jiabin156c6872017-10-06 09:47:15 -0700866 } else {
867 ALOGW("listener for process %d death is gone", MEDIA_AUDIO_ROUTING_CHANGED);
868 }
869}
870
John Grossmanc795b642012-02-22 15:38:35 -0800871sp<MediaPlayerBase> MediaPlayerService::Client::setDataSource_pre(
872 player_type playerType)
873{
874 ALOGV("player type = %d", playerType);
875
876 // create the right type of player
877 sp<MediaPlayerBase> p = createPlayer(playerType);
878 if (p == NULL) {
879 return p;
880 }
881
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700882 std::vector<DeathNotifier> deathNotifiers;
883
884 // Listen to death of media.extractor service
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700885 sp<IServiceManager> sm = defaultServiceManager();
886 sp<IBinder> binder = sm->getService(String16("media.extractor"));
Marco Nelissen1b5a7ee2016-09-30 13:54:30 -0700887 if (binder == NULL) {
888 ALOGE("extractor service not available");
889 return NULL;
890 }
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700891 deathNotifiers.emplace_back(
892 binder, [l = wp<MediaPlayerBase>(p)]() {
893 sp<MediaPlayerBase> listener = l.promote();
894 if (listener) {
895 ALOGI("media.extractor died. Sending death notification.");
896 listener->sendEvent(MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED,
897 MEDIAEXTRACTOR_PROCESS_DEATH);
898 } else {
899 ALOGW("media.extractor died without a death handler.");
900 }
901 });
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700902
Marco Nelissena0c98412019-03-29 12:10:19 -0700903 {
904 using ::android::hidl::base::V1_0::IBase;
905
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700906 // Listen to death of OMX service
Marco Nelissena0c98412019-03-29 12:10:19 -0700907 {
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700908 sp<IBase> base = ::android::hardware::media::omx::V1_0::
909 IOmx::getService();
910 if (base == nullptr) {
Marco Nelissena0c98412019-03-29 12:10:19 -0700911 ALOGD("OMX service is not available");
912 } else {
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700913 deathNotifiers.emplace_back(
914 base, [l = wp<MediaPlayerBase>(p)]() {
915 sp<MediaPlayerBase> listener = l.promote();
916 if (listener) {
917 ALOGI("OMX service died. "
918 "Sending death notification.");
919 listener->sendEvent(
920 MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED,
921 MEDIACODEC_PROCESS_DEATH);
922 } else {
923 ALOGW("OMX service died without a death handler.");
924 }
925 });
Marco Nelissena0c98412019-03-29 12:10:19 -0700926 }
927 }
928
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700929 // Listen to death of Codec2 services
Marco Nelissena0c98412019-03-29 12:10:19 -0700930 {
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700931 for (std::shared_ptr<Codec2Client> const& client :
932 Codec2Client::CreateFromAllServices()) {
Wonsik Kime8e98152022-12-16 16:04:17 -0800933 sp<IBase> hidlBase = client->getHidlBase();
934 ::ndk::SpAIBinder aidlBase = client->getAidlBase();
935 auto onBinderDied = [l = wp<MediaPlayerBase>(p),
936 name = std::string(client->getServiceName())]() {
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700937 sp<MediaPlayerBase> listener = l.promote();
938 if (listener) {
939 ALOGI("Codec2 service \"%s\" died. "
940 "Sending death notification.",
941 name.c_str());
942 listener->sendEvent(
943 MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED,
944 MEDIACODEC_PROCESS_DEATH);
945 } else {
946 ALOGW("Codec2 service \"%s\" died "
947 "without a death handler.",
948 name.c_str());
949 }
Wonsik Kime8e98152022-12-16 16:04:17 -0800950 };
951 if (hidlBase) {
952 deathNotifiers.emplace_back(hidlBase, onBinderDied);
953 } else if (aidlBase.get() != nullptr) {
954 deathNotifiers.emplace_back(aidlBase, onBinderDied);
955 }
Marco Nelissene4da6c62019-04-01 15:01:41 -0700956 }
Marco Nelissena0c98412019-03-29 12:10:19 -0700957 }
Marco Nelissen1b5a7ee2016-09-30 13:54:30 -0700958 }
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700959
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700960 Mutex::Autolock lock(mLock);
961
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700962 mDeathNotifiers.clear();
963 mDeathNotifiers.swap(deathNotifiers);
jiabin156c6872017-10-06 09:47:15 -0700964 mAudioDeviceUpdatedListener = new AudioDeviceUpdatedNotifier(p);
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700965
John Grossmanc795b642012-02-22 15:38:35 -0800966 if (!p->hardwareOutput()) {
Svet Ganov33761132021-05-13 22:51:08 +0000967 mAudioOutput = new AudioOutput(mAudioSessionId, mAttributionSource,
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700968 mAudioAttributes, mAudioDeviceUpdatedListener);
John Grossmanc795b642012-02-22 15:38:35 -0800969 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
970 }
971
972 return p;
973}
974
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700975status_t MediaPlayerService::Client::setDataSource_post(
John Grossmanc795b642012-02-22 15:38:35 -0800976 const sp<MediaPlayerBase>& p,
977 status_t status)
978{
979 ALOGV(" setDataSource");
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700980 if (status != OK) {
981 ALOGE(" error: %d", status);
982 return status;
John Grossmanc795b642012-02-22 15:38:35 -0800983 }
984
985 // Set the re-transmission endpoint if one was chosen.
986 if (mRetransmitEndpointValid) {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700987 status = p->setRetransmitEndpoint(&mRetransmitEndpoint);
988 if (status != NO_ERROR) {
989 ALOGE("setRetransmitEndpoint error: %d", status);
John Grossmanc795b642012-02-22 15:38:35 -0800990 }
991 }
992
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700993 if (status == OK) {
994 Mutex::Autolock lock(mLock);
John Grossmanc795b642012-02-22 15:38:35 -0800995 mPlayer = p;
996 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700997 return status;
John Grossmanc795b642012-02-22 15:38:35 -0800998}
999
Andreas Huber2db84552010-01-28 11:19:57 -08001000status_t MediaPlayerService::Client::setDataSource(
Andreas Huber1b86fe02014-01-29 11:13:26 -08001001 const sp<IMediaHTTPService> &httpService,
1002 const char *url,
1003 const KeyedVector<String8, String8> *headers)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001004{
Steve Block3856b092011-10-20 11:56:00 +01001005 ALOGV("setDataSource(%s)", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001006 if (url == NULL)
1007 return UNKNOWN_ERROR;
1008
Dave Burked681bbb2011-08-30 14:39:17 +01001009 if ((strncmp(url, "http://", 7) == 0) ||
1010 (strncmp(url, "https://", 8) == 0) ||
1011 (strncmp(url, "rtsp://", 7) == 0)) {
1012 if (!checkPermission("android.permission.INTERNET")) {
1013 return PERMISSION_DENIED;
1014 }
1015 }
1016
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001017 if (strncmp(url, "content://", 10) == 0) {
1018 // get a filedescriptor for the content Uri and
1019 // pass it to the setDataSource(fd) method
1020
1021 String16 url16(url);
1022 int fd = android::openContentProviderFile(url16);
1023 if (fd < 0)
1024 {
Steve Block29357bc2012-01-06 19:20:56 +00001025 ALOGE("Couldn't open fd for %s", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001026 return UNKNOWN_ERROR;
1027 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001028 status_t status = setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001029 close(fd);
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001030 return mStatus = status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001031 } else {
John Grossman44a7e422012-06-21 17:29:24 -07001032 player_type playerType = MediaPlayerFactory::getPlayerType(this, url);
John Grossmanc795b642012-02-22 15:38:35 -08001033 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
1034 if (p == NULL) {
1035 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001036 }
1037
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001038 return mStatus =
1039 setDataSource_post(
1040 p, p->setDataSource(httpService, url, headers));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001041 }
1042}
1043
1044status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
1045{
Marco Nelissen83b0fd92015-09-16 13:48:07 -07001046 ALOGV("setDataSource fd=%d (%s), offset=%lld, length=%lld",
1047 fd, nameForFd(fd).c_str(), (long long) offset, (long long) length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001048 struct stat sb;
1049 int ret = fstat(fd, &sb);
1050 if (ret != 0) {
Steve Block29357bc2012-01-06 19:20:56 +00001051 ALOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001052 return UNKNOWN_ERROR;
1053 }
1054
Andy Hung833b4752016-04-04 17:15:48 -07001055 ALOGV("st_dev = %llu", static_cast<unsigned long long>(sb.st_dev));
Steve Block3856b092011-10-20 11:56:00 +01001056 ALOGV("st_mode = %u", sb.st_mode);
Mark Salyzyn77342f72014-06-18 16:31:32 -07001057 ALOGV("st_uid = %lu", static_cast<unsigned long>(sb.st_uid));
1058 ALOGV("st_gid = %lu", static_cast<unsigned long>(sb.st_gid));
Andy Hung833b4752016-04-04 17:15:48 -07001059 ALOGV("st_size = %llu", static_cast<unsigned long long>(sb.st_size));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001060
1061 if (offset >= sb.st_size) {
Steve Block29357bc2012-01-06 19:20:56 +00001062 ALOGE("offset error");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001063 return UNKNOWN_ERROR;
1064 }
1065 if (offset + length > sb.st_size) {
1066 length = sb.st_size - offset;
Andy Hung833b4752016-04-04 17:15:48 -07001067 ALOGV("calculated length = %lld", (long long)length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001068 }
1069
John Grossman44a7e422012-06-21 17:29:24 -07001070 player_type playerType = MediaPlayerFactory::getPlayerType(this,
1071 fd,
1072 offset,
1073 length);
John Grossmanc795b642012-02-22 15:38:35 -08001074 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
1075 if (p == NULL) {
1076 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001077 }
1078
1079 // now set data source
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001080 return mStatus = setDataSource_post(p, p->setDataSource(fd, offset, length));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001081}
1082
Andreas Hubere2b10282010-11-23 11:41:34 -08001083status_t MediaPlayerService::Client::setDataSource(
1084 const sp<IStreamSource> &source) {
1085 // create the right type of player
John Grossman44a7e422012-06-21 17:29:24 -07001086 player_type playerType = MediaPlayerFactory::getPlayerType(this, source);
John Grossmanc795b642012-02-22 15:38:35 -08001087 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
Andreas Hubere2b10282010-11-23 11:41:34 -08001088 if (p == NULL) {
1089 return NO_INIT;
1090 }
1091
Andreas Hubere2b10282010-11-23 11:41:34 -08001092 // now set data source
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001093 return mStatus = setDataSource_post(p, p->setDataSource(source));
Andreas Hubere2b10282010-11-23 11:41:34 -08001094}
1095
Chris Watkins99f31602015-03-20 13:06:33 -07001096status_t MediaPlayerService::Client::setDataSource(
1097 const sp<IDataSource> &source) {
Dongwon Kangd91dc5a2017-10-10 00:07:09 -07001098 sp<DataSource> dataSource = CreateDataSourceFromIDataSource(source);
Chris Watkins99f31602015-03-20 13:06:33 -07001099 player_type playerType = MediaPlayerFactory::getPlayerType(this, dataSource);
1100 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
1101 if (p == NULL) {
1102 return NO_INIT;
1103 }
1104 // now set data source
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001105 return mStatus = setDataSource_post(p, p->setDataSource(dataSource));
Chris Watkins99f31602015-03-20 13:06:33 -07001106}
1107
Byeongjo Park28225ab2019-01-24 20:31:19 +09001108status_t MediaPlayerService::Client::setDataSource(
1109 const String8& rtpParams) {
1110 player_type playerType = NU_PLAYER;
1111 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
1112 if (p == NULL) {
1113 return NO_INIT;
1114 }
1115 // now set data source
1116 return mStatus = setDataSource_post(p, p->setDataSource(rtpParams));
1117}
1118
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001119void MediaPlayerService::Client::disconnectNativeWindow_l() {
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001120 if (mConnectedWindow != NULL) {
Chong Zhang181fd9b2017-02-16 15:53:03 -08001121 status_t err = nativeWindowDisconnect(
1122 mConnectedWindow.get(), "disconnectNativeWindow");
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001123
1124 if (err != OK) {
Chong Zhang181fd9b2017-02-16 15:53:03 -08001125 ALOGW("nativeWindowDisconnect returned an error: %s (%d)",
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001126 strerror(-err), err);
1127 }
1128 }
1129 mConnectedWindow.clear();
1130}
1131
Glenn Kasten11731182011-02-08 17:26:17 -08001132status_t MediaPlayerService::Client::setVideoSurfaceTexture(
Andy McFadden484566c2012-12-18 09:46:54 -08001133 const sp<IGraphicBufferProducer>& bufferProducer)
Glenn Kasten11731182011-02-08 17:26:17 -08001134{
Andy McFadden484566c2012-12-18 09:46:54 -08001135 ALOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, bufferProducer.get());
Glenn Kasten11731182011-02-08 17:26:17 -08001136 sp<MediaPlayerBase> p = getPlayer();
1137 if (p == 0) return UNKNOWN_ERROR;
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001138
Marco Nelissenf8880202014-11-14 07:58:25 -08001139 sp<IBinder> binder(IInterface::asBinder(bufferProducer));
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001140 if (mConnectedWindowBinder == binder) {
1141 return OK;
1142 }
1143
1144 sp<ANativeWindow> anw;
Andy McFadden484566c2012-12-18 09:46:54 -08001145 if (bufferProducer != NULL) {
Marco Nelissenee08f7e2013-09-16 13:30:01 -07001146 anw = new Surface(bufferProducer, true /* controlledByApp */);
Chong Zhang181fd9b2017-02-16 15:53:03 -08001147 status_t err = nativeWindowConnect(anw.get(), "setVideoSurfaceTexture");
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001148
1149 if (err != OK) {
Steve Block29357bc2012-01-06 19:20:56 +00001150 ALOGE("setVideoSurfaceTexture failed: %d", err);
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001151 // Note that we must do the reset before disconnecting from the ANW.
1152 // Otherwise queue/dequeue calls could be made on the disconnected
1153 // ANW, which may result in errors.
1154 reset();
1155
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001156 Mutex::Autolock lock(mLock);
1157 disconnectNativeWindow_l();
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001158
1159 return err;
1160 }
1161 }
1162
Andy McFadden484566c2012-12-18 09:46:54 -08001163 // Note that we must set the player's new GraphicBufferProducer before
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001164 // disconnecting the old one. Otherwise queue/dequeue calls could be made
1165 // on the disconnected ANW, which may result in errors.
Andy McFadden484566c2012-12-18 09:46:54 -08001166 status_t err = p->setVideoSurfaceTexture(bufferProducer);
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001167
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001168 mLock.lock();
1169 disconnectNativeWindow_l();
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001170
1171 if (err == OK) {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001172 mConnectedWindow = anw;
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001173 mConnectedWindowBinder = binder;
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001174 mLock.unlock();
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001175 } else {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001176 mLock.unlock();
1177 status_t err = nativeWindowDisconnect(
1178 anw.get(), "disconnectNativeWindow");
1179
1180 if (err != OK) {
1181 ALOGW("nativeWindowDisconnect returned an error: %s (%d)",
1182 strerror(-err), err);
1183 }
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001184 }
1185
1186 return err;
Glenn Kasten11731182011-02-08 17:26:17 -08001187}
1188
Nicolas Catania1d187f12009-05-12 23:25:55 -07001189status_t MediaPlayerService::Client::invoke(const Parcel& request,
1190 Parcel *reply)
1191{
1192 sp<MediaPlayerBase> p = getPlayer();
1193 if (p == NULL) return UNKNOWN_ERROR;
1194 return p->invoke(request, reply);
1195}
1196
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001197// This call doesn't need to access the native player.
1198status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
1199{
1200 status_t status;
nikoa64c8c72009-07-20 15:07:26 -07001201 media::Metadata::Filter allow, drop;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001202
Nicolas Catania48290382009-07-10 13:53:06 -07001203 if (unmarshallFilter(filter, &allow, &status) &&
1204 unmarshallFilter(filter, &drop, &status)) {
1205 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001206
1207 mMetadataAllow = allow;
1208 mMetadataDrop = drop;
1209 }
1210 return status;
1211}
1212
Nicolas Catania48290382009-07-10 13:53:06 -07001213status_t MediaPlayerService::Client::getMetadata(
Mark Salyzyn77342f72014-06-18 16:31:32 -07001214 bool update_only, bool /*apply_filter*/, Parcel *reply)
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001215{
nikoa64c8c72009-07-20 15:07:26 -07001216 sp<MediaPlayerBase> player = getPlayer();
1217 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania48290382009-07-10 13:53:06 -07001218
nikod608a812009-07-16 16:39:53 -07001219 status_t status;
1220 // Placeholder for the return code, updated by the caller.
1221 reply->writeInt32(-1);
1222
nikoa64c8c72009-07-20 15:07:26 -07001223 media::Metadata::Filter ids;
Nicolas Catania48290382009-07-10 13:53:06 -07001224
1225 // We don't block notifications while we fetch the data. We clear
1226 // mMetadataUpdated first so we don't lose notifications happening
1227 // during the rest of this call.
1228 {
1229 Mutex::Autolock lock(mLock);
1230 if (update_only) {
nikod608a812009-07-16 16:39:53 -07001231 ids = mMetadataUpdated;
Nicolas Catania48290382009-07-10 13:53:06 -07001232 }
1233 mMetadataUpdated.clear();
1234 }
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001235
nikoa64c8c72009-07-20 15:07:26 -07001236 media::Metadata metadata(reply);
Nicolas Catania48290382009-07-10 13:53:06 -07001237
nikoa64c8c72009-07-20 15:07:26 -07001238 metadata.appendHeader();
1239 status = player->getMetadata(ids, reply);
nikod608a812009-07-16 16:39:53 -07001240
1241 if (status != OK) {
nikoa64c8c72009-07-20 15:07:26 -07001242 metadata.resetParcel();
Steve Block29357bc2012-01-06 19:20:56 +00001243 ALOGE("getMetadata failed %d", status);
nikod608a812009-07-16 16:39:53 -07001244 return status;
1245 }
1246
1247 // FIXME: Implement filtering on the result. Not critical since
1248 // filtering takes place on the update notifications already. This
1249 // would be when all the metadata are fetch and a filter is set.
1250
nikod608a812009-07-16 16:39:53 -07001251 // Everything is fine, update the metadata length.
nikoa64c8c72009-07-20 15:07:26 -07001252 metadata.updateLength();
nikod608a812009-07-16 16:39:53 -07001253 return OK;
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001254}
1255
Wei Jiad399e7e2016-10-26 15:49:11 -07001256status_t MediaPlayerService::Client::setBufferingSettings(
1257 const BufferingSettings& buffering)
1258{
Wei Jiadc6f3402017-01-09 15:04:18 -08001259 ALOGV("[%d] setBufferingSettings{%s}",
Tomasz Wasilczyk09977ff2023-08-11 15:52:22 +00001260 mConnId, buffering.toString().c_str());
Wei Jiad399e7e2016-10-26 15:49:11 -07001261 sp<MediaPlayerBase> p = getPlayer();
1262 if (p == 0) return UNKNOWN_ERROR;
1263 return p->setBufferingSettings(buffering);
1264}
1265
Wei Jia9bb38032017-03-23 18:00:38 -07001266status_t MediaPlayerService::Client::getBufferingSettings(
Wei Jiad399e7e2016-10-26 15:49:11 -07001267 BufferingSettings* buffering /* nonnull */)
1268{
1269 sp<MediaPlayerBase> p = getPlayer();
1270 // TODO: create mPlayer on demand.
1271 if (p == 0) return UNKNOWN_ERROR;
Wei Jia9bb38032017-03-23 18:00:38 -07001272 status_t ret = p->getBufferingSettings(buffering);
Wei Jiad399e7e2016-10-26 15:49:11 -07001273 if (ret == NO_ERROR) {
Wei Jia9bb38032017-03-23 18:00:38 -07001274 ALOGV("[%d] getBufferingSettings{%s}",
Tomasz Wasilczyk09977ff2023-08-11 15:52:22 +00001275 mConnId, buffering->toString().c_str());
Wei Jiad399e7e2016-10-26 15:49:11 -07001276 } else {
Wei Jia9bb38032017-03-23 18:00:38 -07001277 ALOGE("[%d] getBufferingSettings returned %d", mConnId, ret);
Wei Jiad399e7e2016-10-26 15:49:11 -07001278 }
1279 return ret;
1280}
1281
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001282status_t MediaPlayerService::Client::prepareAsync()
1283{
Steve Block3856b092011-10-20 11:56:00 +01001284 ALOGV("[%d] prepareAsync", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001285 sp<MediaPlayerBase> p = getPlayer();
1286 if (p == 0) return UNKNOWN_ERROR;
1287 status_t ret = p->prepareAsync();
1288#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +00001289 ALOGD("start Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001290 if (ret == NO_ERROR) mAntagonizer->start();
1291#endif
1292 return ret;
1293}
1294
1295status_t MediaPlayerService::Client::start()
1296{
Steve Block3856b092011-10-20 11:56:00 +01001297 ALOGV("[%d] start", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001298 sp<MediaPlayerBase> p = getPlayer();
1299 if (p == 0) return UNKNOWN_ERROR;
1300 p->setLooping(mLoop);
1301 return p->start();
1302}
1303
1304status_t MediaPlayerService::Client::stop()
1305{
Steve Block3856b092011-10-20 11:56:00 +01001306 ALOGV("[%d] stop", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001307 sp<MediaPlayerBase> p = getPlayer();
1308 if (p == 0) return UNKNOWN_ERROR;
1309 return p->stop();
1310}
1311
1312status_t MediaPlayerService::Client::pause()
1313{
Steve Block3856b092011-10-20 11:56:00 +01001314 ALOGV("[%d] pause", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001315 sp<MediaPlayerBase> p = getPlayer();
1316 if (p == 0) return UNKNOWN_ERROR;
1317 return p->pause();
1318}
1319
1320status_t MediaPlayerService::Client::isPlaying(bool* state)
1321{
1322 *state = false;
1323 sp<MediaPlayerBase> p = getPlayer();
1324 if (p == 0) return UNKNOWN_ERROR;
1325 *state = p->isPlaying();
Steve Block3856b092011-10-20 11:56:00 +01001326 ALOGV("[%d] isPlaying: %d", mConnId, *state);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001327 return NO_ERROR;
1328}
1329
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001330status_t MediaPlayerService::Client::setPlaybackSettings(const AudioPlaybackRate& rate)
Wei Jia98160162015-02-04 17:01:11 -08001331{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001332 ALOGV("[%d] setPlaybackSettings(%f, %f, %d, %d)",
1333 mConnId, rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Wei Jia98160162015-02-04 17:01:11 -08001334 sp<MediaPlayerBase> p = getPlayer();
1335 if (p == 0) return UNKNOWN_ERROR;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001336 return p->setPlaybackSettings(rate);
1337}
1338
1339status_t MediaPlayerService::Client::getPlaybackSettings(AudioPlaybackRate* rate /* nonnull */)
1340{
1341 sp<MediaPlayerBase> p = getPlayer();
1342 if (p == 0) return UNKNOWN_ERROR;
1343 status_t ret = p->getPlaybackSettings(rate);
1344 if (ret == NO_ERROR) {
1345 ALOGV("[%d] getPlaybackSettings(%f, %f, %d, %d)",
1346 mConnId, rate->mSpeed, rate->mPitch, rate->mFallbackMode, rate->mStretchMode);
1347 } else {
1348 ALOGV("[%d] getPlaybackSettings returned %d", mConnId, ret);
1349 }
1350 return ret;
1351}
1352
1353status_t MediaPlayerService::Client::setSyncSettings(
1354 const AVSyncSettings& sync, float videoFpsHint)
1355{
1356 ALOGV("[%d] setSyncSettings(%u, %u, %f, %f)",
1357 mConnId, sync.mSource, sync.mAudioAdjustMode, sync.mTolerance, videoFpsHint);
1358 sp<MediaPlayerBase> p = getPlayer();
1359 if (p == 0) return UNKNOWN_ERROR;
1360 return p->setSyncSettings(sync, videoFpsHint);
1361}
1362
1363status_t MediaPlayerService::Client::getSyncSettings(
1364 AVSyncSettings* sync /* nonnull */, float* videoFps /* nonnull */)
1365{
1366 sp<MediaPlayerBase> p = getPlayer();
1367 if (p == 0) return UNKNOWN_ERROR;
1368 status_t ret = p->getSyncSettings(sync, videoFps);
1369 if (ret == NO_ERROR) {
1370 ALOGV("[%d] getSyncSettings(%u, %u, %f, %f)",
1371 mConnId, sync->mSource, sync->mAudioAdjustMode, sync->mTolerance, *videoFps);
1372 } else {
1373 ALOGV("[%d] getSyncSettings returned %d", mConnId, ret);
1374 }
1375 return ret;
Wei Jia98160162015-02-04 17:01:11 -08001376}
1377
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001378status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
1379{
Steve Block3856b092011-10-20 11:56:00 +01001380 ALOGV("getCurrentPosition");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001381 sp<MediaPlayerBase> p = getPlayer();
1382 if (p == 0) return UNKNOWN_ERROR;
1383 status_t ret = p->getCurrentPosition(msec);
1384 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001385 ALOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001386 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001387 ALOGE("getCurrentPosition returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001388 }
1389 return ret;
1390}
1391
1392status_t MediaPlayerService::Client::getDuration(int *msec)
1393{
Steve Block3856b092011-10-20 11:56:00 +01001394 ALOGV("getDuration");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001395 sp<MediaPlayerBase> p = getPlayer();
1396 if (p == 0) return UNKNOWN_ERROR;
1397 status_t ret = p->getDuration(msec);
1398 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001399 ALOGV("[%d] getDuration = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001400 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001401 ALOGE("getDuration returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001402 }
1403 return ret;
1404}
1405
Marco Nelissen6b74d672012-02-28 16:07:44 -08001406status_t MediaPlayerService::Client::setNextPlayer(const sp<IMediaPlayer>& player) {
1407 ALOGV("setNextPlayer");
1408 Mutex::Autolock l(mLock);
1409 sp<Client> c = static_cast<Client*>(player.get());
Wei Jia28284122016-08-30 13:49:06 -07001410 if (c != NULL && !mService->hasClient(c)) {
Robert Shihee0a0e32016-08-16 16:50:54 -07001411 return BAD_VALUE;
1412 }
1413
Marco Nelissen6b74d672012-02-28 16:07:44 -08001414 mNextClient = c;
John Grossman5f7e55e2012-08-24 14:47:25 -07001415
1416 if (c != NULL) {
1417 if (mAudioOutput != NULL) {
1418 mAudioOutput->setNextOutput(c->mAudioOutput);
1419 } else if ((mPlayer != NULL) && !mPlayer->hardwareOutput()) {
1420 ALOGE("no current audio output");
1421 }
1422
1423 if ((mPlayer != NULL) && (mNextClient->getPlayer() != NULL)) {
1424 mPlayer->setNextPlayer(mNextClient->getPlayer());
1425 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001426 }
John Grossman5f7e55e2012-08-24 14:47:25 -07001427
Marco Nelissen6b74d672012-02-28 16:07:44 -08001428 return OK;
1429}
1430
Andy Hung9fc8b5c2017-01-24 13:36:48 -08001431VolumeShaper::Status MediaPlayerService::Client::applyVolumeShaper(
1432 const sp<VolumeShaper::Configuration>& configuration,
1433 const sp<VolumeShaper::Operation>& operation) {
1434 // for hardware output, call player instead
1435 ALOGV("Client::applyVolumeShaper(%p)", this);
1436 sp<MediaPlayerBase> p = getPlayer();
1437 {
1438 Mutex::Autolock l(mLock);
1439 if (p != 0 && p->hardwareOutput()) {
1440 // TODO: investigate internal implementation
1441 return VolumeShaper::Status(INVALID_OPERATION);
1442 }
1443 if (mAudioOutput.get() != nullptr) {
1444 return mAudioOutput->applyVolumeShaper(configuration, operation);
1445 }
1446 }
1447 return VolumeShaper::Status(INVALID_OPERATION);
1448}
1449
1450sp<VolumeShaper::State> MediaPlayerService::Client::getVolumeShaperState(int id) {
1451 // for hardware output, call player instead
1452 ALOGV("Client::getVolumeShaperState(%p)", this);
1453 sp<MediaPlayerBase> p = getPlayer();
1454 {
1455 Mutex::Autolock l(mLock);
1456 if (p != 0 && p->hardwareOutput()) {
1457 // TODO: investigate internal implementation.
1458 return nullptr;
1459 }
1460 if (mAudioOutput.get() != nullptr) {
1461 return mAudioOutput->getVolumeShaperState(id);
1462 }
1463 }
1464 return nullptr;
1465}
1466
Wei Jiac5de0912016-11-18 10:22:14 -08001467status_t MediaPlayerService::Client::seekTo(int msec, MediaPlayerSeekMode mode)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001468{
Wei Jiac5de0912016-11-18 10:22:14 -08001469 ALOGV("[%d] seekTo(%d, %d)", mConnId, msec, mode);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001470 sp<MediaPlayerBase> p = getPlayer();
1471 if (p == 0) return UNKNOWN_ERROR;
Wei Jiac5de0912016-11-18 10:22:14 -08001472 return p->seekTo(msec, mode);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001473}
1474
1475status_t MediaPlayerService::Client::reset()
1476{
Steve Block3856b092011-10-20 11:56:00 +01001477 ALOGV("[%d] reset", mConnId);
John Grossmanc795b642012-02-22 15:38:35 -08001478 mRetransmitEndpointValid = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001479 sp<MediaPlayerBase> p = getPlayer();
1480 if (p == 0) return UNKNOWN_ERROR;
1481 return p->reset();
1482}
1483
Wei Jia52c28512017-09-13 18:17:51 -07001484status_t MediaPlayerService::Client::notifyAt(int64_t mediaTimeUs)
1485{
1486 ALOGV("[%d] notifyAt(%lld)", mConnId, (long long)mediaTimeUs);
1487 sp<MediaPlayerBase> p = getPlayer();
1488 if (p == 0) return UNKNOWN_ERROR;
1489 return p->notifyAt(mediaTimeUs);
1490}
1491
Glenn Kastenfff6d712012-01-12 16:38:12 -08001492status_t MediaPlayerService::Client::setAudioStreamType(audio_stream_type_t type)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001493{
Steve Block3856b092011-10-20 11:56:00 +01001494 ALOGV("[%d] setAudioStreamType(%d)", mConnId, type);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001495 // TODO: for hardware output, call player instead
1496 Mutex::Autolock l(mLock);
1497 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1498 return NO_ERROR;
1499}
1500
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001501status_t MediaPlayerService::Client::setAudioAttributes_l(const Parcel &parcel)
1502{
1503 if (mAudioAttributes != NULL) { free(mAudioAttributes); }
1504 mAudioAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001505 if (mAudioAttributes == NULL) {
1506 return NO_MEMORY;
1507 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001508 unmarshallAudioAttributes(parcel, mAudioAttributes);
1509
1510 ALOGV("setAudioAttributes_l() usage=%d content=%d flags=0x%x tags=%s",
1511 mAudioAttributes->usage, mAudioAttributes->content_type, mAudioAttributes->flags,
1512 mAudioAttributes->tags);
1513
1514 if (mAudioOutput != 0) {
1515 mAudioOutput->setAudioAttributes(mAudioAttributes);
1516 }
1517 return NO_ERROR;
1518}
1519
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001520status_t MediaPlayerService::Client::setLooping(int loop)
1521{
Steve Block3856b092011-10-20 11:56:00 +01001522 ALOGV("[%d] setLooping(%d)", mConnId, loop);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001523 mLoop = loop;
1524 sp<MediaPlayerBase> p = getPlayer();
1525 if (p != 0) return p->setLooping(loop);
1526 return NO_ERROR;
1527}
1528
1529status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1530{
Steve Block3856b092011-10-20 11:56:00 +01001531 ALOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
John Grossman761defc2012-02-09 15:09:05 -08001532
1533 // for hardware output, call player instead
1534 sp<MediaPlayerBase> p = getPlayer();
1535 {
1536 Mutex::Autolock l(mLock);
1537 if (p != 0 && p->hardwareOutput()) {
1538 MediaPlayerHWInterface* hwp =
1539 reinterpret_cast<MediaPlayerHWInterface*>(p.get());
1540 return hwp->setVolume(leftVolume, rightVolume);
1541 } else {
1542 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1543 return NO_ERROR;
1544 }
1545 }
1546
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001547 return NO_ERROR;
1548}
1549
Eric Laurent2beeb502010-07-16 07:43:46 -07001550status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1551{
Steve Block3856b092011-10-20 11:56:00 +01001552 ALOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
Eric Laurent2beeb502010-07-16 07:43:46 -07001553 Mutex::Autolock l(mLock);
1554 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1555 return NO_ERROR;
1556}
1557
1558status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1559{
Steve Block3856b092011-10-20 11:56:00 +01001560 ALOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
Eric Laurent2beeb502010-07-16 07:43:46 -07001561 Mutex::Autolock l(mLock);
1562 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1563 return NO_ERROR;
1564}
Nicolas Catania48290382009-07-10 13:53:06 -07001565
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001566status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
Steve Block3856b092011-10-20 11:56:00 +01001567 ALOGV("[%d] setParameter(%d)", mConnId, key);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001568 switch (key) {
1569 case KEY_PARAMETER_AUDIO_ATTRIBUTES:
1570 {
1571 Mutex::Autolock l(mLock);
1572 return setAudioAttributes_l(request);
1573 }
1574 default:
1575 sp<MediaPlayerBase> p = getPlayer();
1576 if (p == 0) { return UNKNOWN_ERROR; }
1577 return p->setParameter(key, request);
1578 }
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001579}
1580
1581status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
Steve Block3856b092011-10-20 11:56:00 +01001582 ALOGV("[%d] getParameter(%d)", mConnId, key);
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001583 sp<MediaPlayerBase> p = getPlayer();
1584 if (p == 0) return UNKNOWN_ERROR;
1585 return p->getParameter(key, reply);
1586}
1587
John Grossmanc795b642012-02-22 15:38:35 -08001588status_t MediaPlayerService::Client::setRetransmitEndpoint(
1589 const struct sockaddr_in* endpoint) {
1590
1591 if (NULL != endpoint) {
1592 uint32_t a = ntohl(endpoint->sin_addr.s_addr);
1593 uint16_t p = ntohs(endpoint->sin_port);
1594 ALOGV("[%d] setRetransmitEndpoint(%u.%u.%u.%u:%hu)", mConnId,
1595 (a >> 24), (a >> 16) & 0xFF, (a >> 8) & 0xFF, (a & 0xFF), p);
1596 } else {
1597 ALOGV("[%d] setRetransmitEndpoint = <none>", mConnId);
1598 }
1599
1600 sp<MediaPlayerBase> p = getPlayer();
1601
1602 // Right now, the only valid time to set a retransmit endpoint is before
1603 // player selection has been made (since the presence or absence of a
1604 // retransmit endpoint is going to determine which player is selected during
1605 // setDataSource).
1606 if (p != 0) return INVALID_OPERATION;
1607
1608 if (NULL != endpoint) {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001609 Mutex::Autolock lock(mLock);
John Grossmanc795b642012-02-22 15:38:35 -08001610 mRetransmitEndpoint = *endpoint;
1611 mRetransmitEndpointValid = true;
1612 } else {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001613 Mutex::Autolock lock(mLock);
John Grossmanc795b642012-02-22 15:38:35 -08001614 mRetransmitEndpointValid = false;
1615 }
1616
1617 return NO_ERROR;
1618}
1619
John Grossman44a7e422012-06-21 17:29:24 -07001620status_t MediaPlayerService::Client::getRetransmitEndpoint(
1621 struct sockaddr_in* endpoint)
1622{
1623 if (NULL == endpoint)
1624 return BAD_VALUE;
1625
1626 sp<MediaPlayerBase> p = getPlayer();
1627
1628 if (p != NULL)
1629 return p->getRetransmitEndpoint(endpoint);
1630
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001631 Mutex::Autolock lock(mLock);
John Grossman44a7e422012-06-21 17:29:24 -07001632 if (!mRetransmitEndpointValid)
1633 return NO_INIT;
1634
1635 *endpoint = mRetransmitEndpoint;
1636
1637 return NO_ERROR;
1638}
1639
Gloria Wangb483c472011-04-11 17:23:27 -07001640void MediaPlayerService::Client::notify(
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001641 int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001642{
James Dongb8a98252012-08-26 16:13:03 -07001643 sp<IMediaPlayerClient> c;
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001644 sp<Client> nextClient;
1645 status_t errStartNext = NO_ERROR;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001646 {
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001647 Mutex::Autolock l(mLock);
1648 c = mClient;
1649 if (msg == MEDIA_PLAYBACK_COMPLETE && mNextClient != NULL) {
1650 nextClient = mNextClient;
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001651
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001652 if (mAudioOutput != NULL)
1653 mAudioOutput->switchToNextOutput();
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001654
1655 errStartNext = nextClient->start();
1656 }
1657 }
1658
1659 if (nextClient != NULL) {
1660 sp<IMediaPlayerClient> nc;
1661 {
1662 Mutex::Autolock l(nextClient->mLock);
1663 nc = nextClient->mClient;
1664 }
1665 if (nc != NULL) {
1666 if (errStartNext == NO_ERROR) {
1667 nc->notify(MEDIA_INFO, MEDIA_INFO_STARTED_AS_NEXT, 0, obj);
1668 } else {
1669 nc->notify(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN , 0, obj);
1670 ALOGE("gapless:start playback for next track failed, err(%d)", errStartNext);
Wei Jia2afac0c2016-01-07 12:13:07 -08001671 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001672 }
1673 }
1674
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001675 if (MEDIA_INFO == msg &&
Nicolas Catania48290382009-07-10 13:53:06 -07001676 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikoa64c8c72009-07-20 15:07:26 -07001677 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania48290382009-07-10 13:53:06 -07001678
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001679 if(shouldDropMetadata(metadata_type)) {
Nicolas Catania48290382009-07-10 13:53:06 -07001680 return;
1681 }
1682
1683 // Update the list of metadata that have changed. getMetadata
1684 // also access mMetadataUpdated and clears it.
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001685 addNewMetadataUpdate(metadata_type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001686 }
James Dongb8a98252012-08-26 16:13:03 -07001687
1688 if (c != NULL) {
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001689 ALOGV("[%d] notify (%d, %d, %d)", mConnId, msg, ext1, ext2);
James Dongb8a98252012-08-26 16:13:03 -07001690 c->notify(msg, ext1, ext2, obj);
1691 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001692}
1693
Nicolas Catania48290382009-07-10 13:53:06 -07001694
nikoa64c8c72009-07-20 15:07:26 -07001695bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001696{
Nicolas Catania48290382009-07-10 13:53:06 -07001697 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001698
Nicolas Catania48290382009-07-10 13:53:06 -07001699 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001700 return true;
1701 }
1702
Nicolas Catania48290382009-07-10 13:53:06 -07001703 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001704 return false;
Nicolas Catania48290382009-07-10 13:53:06 -07001705 } else {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001706 return true;
1707 }
1708}
1709
Nicolas Catania48290382009-07-10 13:53:06 -07001710
nikoa64c8c72009-07-20 15:07:26 -07001711void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania48290382009-07-10 13:53:06 -07001712 Mutex::Autolock lock(mLock);
1713 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1714 mMetadataUpdated.add(metadata_type);
1715 }
1716}
1717
Hassan Shojaniacefac142017-02-06 21:02:02 -08001718// Modular DRM
1719status_t MediaPlayerService::Client::prepareDrm(const uint8_t uuid[16],
1720 const Vector<uint8_t>& drmSessionId)
1721{
1722 ALOGV("[%d] prepareDrm", mConnId);
1723 sp<MediaPlayerBase> p = getPlayer();
1724 if (p == 0) return UNKNOWN_ERROR;
1725
1726 status_t ret = p->prepareDrm(uuid, drmSessionId);
1727 ALOGV("prepareDrm ret: %d", ret);
1728
1729 return ret;
1730}
1731
1732status_t MediaPlayerService::Client::releaseDrm()
1733{
1734 ALOGV("[%d] releaseDrm", mConnId);
1735 sp<MediaPlayerBase> p = getPlayer();
1736 if (p == 0) return UNKNOWN_ERROR;
1737
1738 status_t ret = p->releaseDrm();
1739 ALOGV("releaseDrm ret: %d", ret);
1740
1741 return ret;
1742}
1743
jiabin156c6872017-10-06 09:47:15 -07001744status_t MediaPlayerService::Client::setOutputDevice(audio_port_handle_t deviceId)
1745{
1746 ALOGV("[%d] setOutputDevice", mConnId);
1747 {
1748 Mutex::Autolock l(mLock);
1749 if (mAudioOutput.get() != nullptr) {
1750 return mAudioOutput->setOutputDevice(deviceId);
1751 }
1752 }
1753 return NO_INIT;
1754}
1755
Robert Wub7f8edc2024-11-04 19:54:38 +00001756status_t MediaPlayerService::Client::getRoutedDeviceIds(DeviceIdVector& deviceIds)
jiabin156c6872017-10-06 09:47:15 -07001757{
Robert Wub7f8edc2024-11-04 19:54:38 +00001758 ALOGV("[%d] getRoutedDeviceIds", mConnId);
jiabin156c6872017-10-06 09:47:15 -07001759 {
1760 Mutex::Autolock l(mLock);
1761 if (mAudioOutput.get() != nullptr) {
Robert Wub7f8edc2024-11-04 19:54:38 +00001762 return mAudioOutput->getRoutedDeviceIds(deviceIds);
jiabin156c6872017-10-06 09:47:15 -07001763 }
1764 }
1765 return NO_INIT;
1766}
1767
1768status_t MediaPlayerService::Client::enableAudioDeviceCallback(bool enabled)
1769{
1770 ALOGV("[%d] enableAudioDeviceCallback, %d", mConnId, enabled);
1771 {
1772 Mutex::Autolock l(mLock);
1773 if (mAudioOutput.get() != nullptr) {
1774 return mAudioOutput->enableAudioDeviceCallback(enabled);
1775 }
1776 }
1777 return NO_INIT;
1778}
1779
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001780#if CALLBACK_ANTAGONIZER
1781const int Antagonizer::interval = 10000; // 10 msecs
1782
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001783Antagonizer::Antagonizer(const sp<MediaPlayerBase::Listener> &listener) :
1784 mExit(false), mActive(false), mListener(listener)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001785{
1786 createThread(callbackThread, this);
1787}
1788
1789void Antagonizer::kill()
1790{
1791 Mutex::Autolock _l(mLock);
1792 mActive = false;
1793 mExit = true;
1794 mCondition.wait(mLock);
1795}
1796
1797int Antagonizer::callbackThread(void* user)
1798{
Steve Blockb8a80522011-12-20 16:23:08 +00001799 ALOGD("Antagonizer started");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001800 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1801 while (!p->mExit) {
1802 if (p->mActive) {
Steve Block3856b092011-10-20 11:56:00 +01001803 ALOGV("send event");
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001804 p->mListener->notify(0, 0, 0, 0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001805 }
1806 usleep(interval);
1807 }
1808 Mutex::Autolock _l(p->mLock);
1809 p->mCondition.signal();
Steve Blockb8a80522011-12-20 16:23:08 +00001810 ALOGD("Antagonizer stopped");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001811 return 0;
1812}
1813#endif
1814
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001815#undef LOG_TAG
1816#define LOG_TAG "AudioSink"
Svet Ganov33761132021-05-13 22:51:08 +00001817MediaPlayerService::AudioOutput::AudioOutput(audio_session_t sessionId,
1818 const AttributionSourceState& attributionSource, const audio_attributes_t* attr,
1819 const sp<AudioSystem::AudioDeviceCallback>& deviceCallback)
Vlad Popab4f5b012022-08-12 15:53:09 +02001820 : mCachedPlayerIId(PLAYER_PIID_INVALID),
1821 mCallback(NULL),
Andy Hungd1c74342015-07-07 16:54:23 -07001822 mStreamType(AUDIO_STREAM_MUSIC),
Andy Hungd1c74342015-07-07 16:54:23 -07001823 mLeftVolume(1.0),
1824 mRightVolume(1.0),
1825 mPlaybackRate(AUDIO_PLAYBACK_RATE_DEFAULT),
1826 mSampleRateHz(0),
1827 mMsecsPerFrame(0),
1828 mFrameSize(0),
Eric Laurent1948eb32012-04-13 16:50:19 -07001829 mSessionId(sessionId),
Svet Ganov33761132021-05-13 22:51:08 +00001830 mAttributionSource(attributionSource),
Andy Hungd1c74342015-07-07 16:54:23 -07001831 mSendLevel(0.0),
1832 mAuxEffectId(0),
Andy Hung4ef88d72017-02-21 19:47:53 -08001833 mFlags(AUDIO_OUTPUT_FLAG_NONE),
jiabin156c6872017-10-06 09:47:15 -07001834 mVolumeHandler(new media::VolumeHandler()),
1835 mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE),
1836 mDeviceCallbackEnabled(false),
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001837 mDeviceCallback(deviceCallback)
Andy Hungd1c74342015-07-07 16:54:23 -07001838{
Steve Block3856b092011-10-20 11:56:00 +01001839 ALOGV("AudioOutput(%d)", sessionId);
Eric Laurent43562692015-07-15 16:49:07 -07001840 if (attr != NULL) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001841 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1842 if (mAttributes != NULL) {
1843 memcpy(mAttributes, attr, sizeof(audio_attributes_t));
François Gaffie58d4be52018-11-06 15:30:12 +01001844 mStreamType = AudioSystem::attributesToStreamType(*attr);
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001845 }
1846 } else {
1847 mAttributes = NULL;
Eric Laurent43562692015-07-15 16:49:07 -07001848 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001849 setMinBufferCount();
1850}
1851
1852MediaPlayerService::AudioOutput::~AudioOutput()
1853{
1854 close();
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001855 free(mAttributes);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001856}
1857
Andy Hungd1c74342015-07-07 16:54:23 -07001858//static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001859void MediaPlayerService::AudioOutput::setMinBufferCount()
1860{
Roman Kiryanova3f34462021-03-10 16:17:24 -08001861 if (property_get_bool("ro.boot.qemu", false)) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001862 mIsOnEmulator = true;
1863 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1864 }
1865}
1866
Andy Hungd1c74342015-07-07 16:54:23 -07001867// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001868bool MediaPlayerService::AudioOutput::isOnEmulator()
1869{
Andy Hungd1c74342015-07-07 16:54:23 -07001870 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001871 return mIsOnEmulator;
1872}
1873
Andy Hungd1c74342015-07-07 16:54:23 -07001874// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001875int MediaPlayerService::AudioOutput::getMinBufferCount()
1876{
Andy Hungd1c74342015-07-07 16:54:23 -07001877 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001878 return mMinBufferCount;
1879}
1880
1881ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1882{
Andy Hungd1c74342015-07-07 16:54:23 -07001883 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001884 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001885 return mTrack->frameCount() * mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001886}
1887
1888ssize_t MediaPlayerService::AudioOutput::frameCount() const
1889{
Andy Hungd1c74342015-07-07 16:54:23 -07001890 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001891 if (mTrack == 0) return NO_INIT;
1892 return mTrack->frameCount();
1893}
1894
1895ssize_t MediaPlayerService::AudioOutput::channelCount() const
1896{
Andy Hungd1c74342015-07-07 16:54:23 -07001897 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001898 if (mTrack == 0) return NO_INIT;
1899 return mTrack->channelCount();
1900}
1901
1902ssize_t MediaPlayerService::AudioOutput::frameSize() const
1903{
Andy Hungd1c74342015-07-07 16:54:23 -07001904 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001905 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001906 return mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001907}
1908
1909uint32_t MediaPlayerService::AudioOutput::latency () const
1910{
Andy Hungd1c74342015-07-07 16:54:23 -07001911 Mutex::Autolock lock(mLock);
Eric Laurentdb354e52012-03-05 17:27:11 -08001912 if (mTrack == 0) return 0;
1913 return mTrack->latency();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001914}
1915
1916float MediaPlayerService::AudioOutput::msecsPerFrame() const
1917{
Andy Hungd1c74342015-07-07 16:54:23 -07001918 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001919 return mMsecsPerFrame;
1920}
1921
Marco Nelissen4110c102012-03-29 09:31:28 -07001922status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position) const
Eric Laurent342e9cf2010-01-19 17:37:09 -08001923{
Andy Hungd1c74342015-07-07 16:54:23 -07001924 Mutex::Autolock lock(mLock);
Eric Laurent342e9cf2010-01-19 17:37:09 -08001925 if (mTrack == 0) return NO_INIT;
1926 return mTrack->getPosition(position);
1927}
1928
Lajos Molnar06ad1522014-08-28 07:27:44 -07001929status_t MediaPlayerService::AudioOutput::getTimestamp(AudioTimestamp &ts) const
1930{
Andy Hungd1c74342015-07-07 16:54:23 -07001931 Mutex::Autolock lock(mLock);
Lajos Molnar06ad1522014-08-28 07:27:44 -07001932 if (mTrack == 0) return NO_INIT;
1933 return mTrack->getTimestamp(ts);
1934}
1935
Wei Jiac4ac8172015-10-21 10:35:48 -07001936// TODO: Remove unnecessary calls to getPlayedOutDurationUs()
1937// as it acquires locks and may query the audio driver.
1938//
1939// Some calls could conceivably retrieve extrapolated data instead of
1940// accessing getTimestamp() or getPosition() every time a data buffer with
1941// a media time is received.
1942//
1943// Calculate duration of played samples if played at normal rate (i.e., 1.0).
1944int64_t MediaPlayerService::AudioOutput::getPlayedOutDurationUs(int64_t nowUs) const
1945{
1946 Mutex::Autolock lock(mLock);
1947 if (mTrack == 0 || mSampleRateHz == 0) {
Wei Jia213f4902015-10-22 08:55:25 -07001948 return 0;
Wei Jiac4ac8172015-10-21 10:35:48 -07001949 }
1950
1951 uint32_t numFramesPlayed;
Andy Hung5d313802016-10-10 15:09:39 -07001952 int64_t numFramesPlayedAtUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001953 AudioTimestamp ts;
Wei Jiac4ac8172015-10-21 10:35:48 -07001954
1955 status_t res = mTrack->getTimestamp(ts);
1956 if (res == OK) { // case 1: mixing audio tracks and offloaded tracks.
1957 numFramesPlayed = ts.mPosition;
Andy Hung5d313802016-10-10 15:09:39 -07001958 numFramesPlayedAtUs = ts.mTime.tv_sec * 1000000LL + ts.mTime.tv_nsec / 1000;
1959 //ALOGD("getTimestamp: OK %d %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001960 } else if (res == WOULD_BLOCK) { // case 2: transitory state on start of a new track
1961 numFramesPlayed = 0;
Andy Hung5d313802016-10-10 15:09:39 -07001962 numFramesPlayedAtUs = nowUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001963 //ALOGD("getTimestamp: WOULD_BLOCK %d %lld",
Andy Hung5d313802016-10-10 15:09:39 -07001964 // numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001965 } else { // case 3: transitory at new track or audio fast tracks.
1966 res = mTrack->getPosition(&numFramesPlayed);
1967 CHECK_EQ(res, (status_t)OK);
Andy Hung5d313802016-10-10 15:09:39 -07001968 numFramesPlayedAtUs = nowUs;
1969 numFramesPlayedAtUs += 1000LL * mTrack->latency() / 2; /* XXX */
1970 //ALOGD("getPosition: %u %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001971 }
1972
1973 // CHECK_EQ(numFramesPlayed & (1 << 31), 0); // can't be negative until 12.4 hrs, test
1974 // TODO: remove the (int32_t) casting below as it may overflow at 12.4 hours.
1975 int64_t durationUs = (int64_t)((int32_t)numFramesPlayed * 1000000LL / mSampleRateHz)
Andy Hung5d313802016-10-10 15:09:39 -07001976 + nowUs - numFramesPlayedAtUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001977 if (durationUs < 0) {
1978 // Occurs when numFramesPlayed position is very small and the following:
1979 // (1) In case 1, the time nowUs is computed before getTimestamp() is called and
Andy Hung5d313802016-10-10 15:09:39 -07001980 // numFramesPlayedAtUs is greater than nowUs by time more than numFramesPlayed.
Wei Jiac4ac8172015-10-21 10:35:48 -07001981 // (2) In case 3, using getPosition and adding mAudioSink->latency() to
Andy Hung5d313802016-10-10 15:09:39 -07001982 // numFramesPlayedAtUs, by a time amount greater than numFramesPlayed.
Wei Jiac4ac8172015-10-21 10:35:48 -07001983 //
1984 // Both of these are transitory conditions.
1985 ALOGV("getPlayedOutDurationUs: negative duration %lld set to zero", (long long)durationUs);
1986 durationUs = 0;
1987 }
1988 ALOGV("getPlayedOutDurationUs(%lld) nowUs(%lld) frames(%u) framesAt(%lld)",
Andy Hung5d313802016-10-10 15:09:39 -07001989 (long long)durationUs, (long long)nowUs,
1990 numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001991 return durationUs;
1992}
1993
Marco Nelissen4110c102012-03-29 09:31:28 -07001994status_t MediaPlayerService::AudioOutput::getFramesWritten(uint32_t *frameswritten) const
1995{
Andy Hungd1c74342015-07-07 16:54:23 -07001996 Mutex::Autolock lock(mLock);
Marco Nelissen4110c102012-03-29 09:31:28 -07001997 if (mTrack == 0) return NO_INIT;
Andy Hung2f6e73d2016-04-08 12:12:58 -07001998 ExtendedTimestamp ets;
1999 status_t status = mTrack->getTimestamp(&ets);
2000 if (status == OK || status == WOULD_BLOCK) {
2001 *frameswritten = (uint32_t)ets.mPosition[ExtendedTimestamp::LOCATION_CLIENT];
2002 }
2003 return status;
Marco Nelissen4110c102012-03-29 09:31:28 -07002004}
2005
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002006status_t MediaPlayerService::AudioOutput::setParameters(const String8& keyValuePairs)
2007{
Andy Hungd1c74342015-07-07 16:54:23 -07002008 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002009 if (mTrack == 0) return NO_INIT;
2010 return mTrack->setParameters(keyValuePairs);
2011}
2012
2013String8 MediaPlayerService::AudioOutput::getParameters(const String8& keys)
2014{
Andy Hungd1c74342015-07-07 16:54:23 -07002015 Mutex::Autolock lock(mLock);
Tomasz Wasilczyk53ce3af2023-08-14 16:16:55 +00002016 if (mTrack == 0) return String8();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002017 return mTrack->getParameters(keys);
2018}
2019
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07002020void MediaPlayerService::AudioOutput::setAudioAttributes(const audio_attributes_t * attributes) {
Andy Hungd1c74342015-07-07 16:54:23 -07002021 Mutex::Autolock lock(mLock);
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07002022 if (attributes == NULL) {
2023 free(mAttributes);
2024 mAttributes = NULL;
2025 } else {
2026 if (mAttributes == NULL) {
2027 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
2028 }
2029 memcpy(mAttributes, attributes, sizeof(audio_attributes_t));
François Gaffie58d4be52018-11-06 15:30:12 +01002030 mStreamType = AudioSystem::attributesToStreamType(*attributes);
Eric Laurent43562692015-07-15 16:49:07 -07002031 }
2032}
2033
2034void MediaPlayerService::AudioOutput::setAudioStreamType(audio_stream_type_t streamType)
2035{
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07002036 Mutex::Autolock lock(mLock);
Eric Laurent43562692015-07-15 16:49:07 -07002037 // do not allow direct stream type modification if attributes have been set
2038 if (mAttributes == NULL) {
2039 mStreamType = streamType;
2040 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07002041}
2042
Andy Hungd1c74342015-07-07 16:54:23 -07002043void MediaPlayerService::AudioOutput::deleteRecycledTrack_l()
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002044{
Andy Hungd1c74342015-07-07 16:54:23 -07002045 ALOGV("deleteRecycledTrack_l");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002046 if (mRecycledTrack != 0) {
2047
2048 if (mCallbackData != NULL) {
2049 mCallbackData->setOutput(NULL);
2050 mCallbackData->endTrackSwitch();
2051 }
2052
2053 if ((mRecycledTrack->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) {
Andy Hunge13f8a62016-03-30 14:20:42 -07002054 int32_t msec = 0;
2055 if (!mRecycledTrack->stopped()) { // check if active
2056 (void)mRecycledTrack->pendingDuration(&msec);
2057 }
2058 mRecycledTrack->stop(); // ensure full data drain
2059 ALOGD("deleting recycled track, waiting for data drain (%d msec)", msec);
2060 if (msec > 0) {
2061 static const int32_t WAIT_LIMIT_MS = 3000;
2062 if (msec > WAIT_LIMIT_MS) {
2063 msec = WAIT_LIMIT_MS;
2064 }
2065 usleep(msec * 1000LL);
2066 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002067 }
2068 // An offloaded track isn't flushed because the STREAM_END is reported
2069 // slightly prematurely to allow time for the gapless track switch
2070 // but this means that if we decide not to recycle the track there
2071 // could be a small amount of residual data still playing. We leave
2072 // AudioFlinger to drain the track.
2073
2074 mRecycledTrack.clear();
Andy Hungd1c74342015-07-07 16:54:23 -07002075 close_l();
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002076 mCallbackData.clear();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002077 }
2078}
2079
Andy Hungd1c74342015-07-07 16:54:23 -07002080void MediaPlayerService::AudioOutput::close_l()
2081{
2082 mTrack.clear();
2083}
2084
Andreas Huber20111aa2009-07-14 16:56:47 -07002085status_t MediaPlayerService::AudioOutput::open(
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08002086 uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
2087 audio_format_t format, int bufferCount,
Andy Hunge42b6482024-10-16 19:16:50 -07002088 AudioCallback cb, const wp<RefBase>& cookie,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002089 audio_output_flags_t flags,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07002090 const audio_offload_info_t *offloadInfo,
Andy Hung179652e2015-05-31 22:49:46 -07002091 bool doNotReconnect,
2092 uint32_t suggestedFrameCount)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002093{
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002094 ALOGV("open(%u, %d, 0x%x, 0x%x, %d, %d 0x%x)", sampleRate, channelCount, channelMask,
2095 format, bufferCount, mSessionId, flags);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002096
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002097 // offloading is only supported in callback mode for now.
2098 // offloadInfo must be present if offload flag is set
2099 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) &&
2100 ((cb == NULL) || (offloadInfo == NULL))) {
2101 return BAD_VALUE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002102 }
2103
Andy Hung179652e2015-05-31 22:49:46 -07002104 // compute frame count for the AudioTrack internal buffer
2105 size_t frameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002106 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
2107 frameCount = 0; // AudioTrack will get frame count from AudioFlinger
2108 } else {
Andy Hung179652e2015-05-31 22:49:46 -07002109 // try to estimate the buffer processing fetch size from AudioFlinger.
2110 // framesPerBuffer is approximate and generally correct, except when it's not :-).
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002111 uint32_t afSampleRate;
2112 size_t afFrameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002113 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
2114 return NO_INIT;
2115 }
2116 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
2117 return NO_INIT;
2118 }
Ben Romberger259fb462018-08-07 17:58:53 -07002119 if (afSampleRate == 0) {
2120 return NO_INIT;
2121 }
Andy Hung179652e2015-05-31 22:49:46 -07002122 const size_t framesPerBuffer =
2123 (unsigned long long)sampleRate * afFrameCount / afSampleRate;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002124
Andy Hung179652e2015-05-31 22:49:46 -07002125 if (bufferCount == 0) {
Ben Romberger259fb462018-08-07 17:58:53 -07002126 if (framesPerBuffer == 0) {
2127 return NO_INIT;
2128 }
Andy Hung179652e2015-05-31 22:49:46 -07002129 // use suggestedFrameCount
2130 bufferCount = (suggestedFrameCount + framesPerBuffer - 1) / framesPerBuffer;
2131 }
2132 // Check argument bufferCount against the mininum buffer count
2133 if (bufferCount != 0 && bufferCount < mMinBufferCount) {
2134 ALOGV("bufferCount (%d) increased to %d", bufferCount, mMinBufferCount);
2135 bufferCount = mMinBufferCount;
2136 }
2137 // if frameCount is 0, then AudioTrack will get frame count from AudioFlinger
2138 // which will be the minimum size permitted.
2139 frameCount = bufferCount * framesPerBuffer;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002140 }
Andreas Huber20111aa2009-07-14 16:56:47 -07002141
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08002142 if (channelMask == CHANNEL_MASK_USE_CHANNEL_ORDER) {
Glenn Kastenab334fd2012-03-14 12:56:06 -07002143 channelMask = audio_channel_out_mask_from_count(channelCount);
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08002144 if (0 == channelMask) {
2145 ALOGE("open() error, can\'t derive mask for %d audio channels", channelCount);
2146 return NO_INIT;
2147 }
2148 }
Eric Laurent1948eb32012-04-13 16:50:19 -07002149
Andy Hungd1c74342015-07-07 16:54:23 -07002150 Mutex::Autolock lock(mLock);
Andy Hung179652e2015-05-31 22:49:46 -07002151 mCallback = cb;
2152 mCallbackCookie = cookie;
2153
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002154 // Check whether we can recycle the track
2155 bool reuse = false;
2156 bool bothOffloaded = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07002157
Glenn Kasten2799d742013-05-30 14:33:29 -07002158 if (mRecycledTrack != 0) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002159 // check whether we are switching between two offloaded tracks
2160 bothOffloaded = (flags & mRecycledTrack->getFlags()
2161 & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0;
Marco Nelissen67295b52012-06-11 14:52:53 -07002162
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002163 // check if the existing track can be reused as-is, or if a new track needs to be created.
2164 reuse = true;
2165
Marco Nelissen67295b52012-06-11 14:52:53 -07002166 if ((mCallbackData == NULL && mCallback != NULL) ||
2167 (mCallbackData != NULL && mCallback == NULL)) {
2168 // recycled track uses callbacks but the caller wants to use writes, or vice versa
2169 ALOGV("can't chain callback and write");
2170 reuse = false;
2171 } else if ((mRecycledTrack->getSampleRate() != sampleRate) ||
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002172 (mRecycledTrack->channelCount() != (uint32_t)channelCount) ) {
2173 ALOGV("samplerate, channelcount differ: %u/%u Hz, %u/%d ch",
Marco Nelissen67295b52012-06-11 14:52:53 -07002174 mRecycledTrack->getSampleRate(), sampleRate,
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002175 mRecycledTrack->channelCount(), channelCount);
Marco Nelissen67295b52012-06-11 14:52:53 -07002176 reuse = false;
2177 } else if (flags != mFlags) {
2178 ALOGV("output flags differ %08x/%08x", flags, mFlags);
2179 reuse = false;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002180 } else if (mRecycledTrack->format() != format) {
2181 reuse = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07002182 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002183 } else {
2184 ALOGV("no track available to recycle");
2185 }
2186
2187 ALOGV_IF(bothOffloaded, "both tracks offloaded");
2188
2189 // If we can't recycle and both tracks are offloaded
2190 // we must close the previous output before opening a new one
2191 if (bothOffloaded && !reuse) {
2192 ALOGV("both offloaded and not recycling");
Andy Hungd1c74342015-07-07 16:54:23 -07002193 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002194 }
2195
2196 sp<AudioTrack> t;
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002197 sp<CallbackData> newcbd;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002198
2199 // We don't attempt to create a new track if we are recycling an
2200 // offloaded track. But, if we are recycling a non-offloaded or we
2201 // are switching where one is offloaded and one isn't then we create
2202 // the new track in advance so that we can read additional stream info
2203
2204 if (!(reuse && bothOffloaded)) {
2205 ALOGV("creating new AudioTrack");
2206
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002207 if (mCallback != nullptr) {
2208 newcbd = sp<CallbackData>::make(wp<AudioOutput>::fromExisting(this));
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002209 t = new AudioTrack(
2210 mStreamType,
2211 sampleRate,
2212 format,
2213 channelMask,
2214 frameCount,
2215 flags,
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002216 newcbd,
2217 0, // notification frames
2218 mSessionId,
2219 AudioTrack::TRANSFER_CALLBACK,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002220 offloadInfo,
Svet Ganov33761132021-05-13 22:51:08 +00002221 mAttributionSource,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07002222 mAttributes,
jiabin156c6872017-10-06 09:47:15 -07002223 doNotReconnect,
2224 1.0f, // default value for maxRequiredSpeed
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002225 mSelectedDeviceId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002226 } else {
Andy Hungff874dc2016-04-11 16:49:09 -07002227 // TODO: Due to buffer memory concerns, we use a max target playback speed
2228 // based on mPlaybackRate at the time of open (instead of kMaxRequiredSpeed),
2229 // also clamping the target speed to 1.0 <= targetSpeed <= kMaxRequiredSpeed.
2230 const float targetSpeed =
2231 std::min(std::max(mPlaybackRate.mSpeed, 1.0f), kMaxRequiredSpeed);
2232 ALOGW_IF(targetSpeed != mPlaybackRate.mSpeed,
2233 "track target speed:%f clamped from playback speed:%f",
2234 targetSpeed, mPlaybackRate.mSpeed);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002235 t = new AudioTrack(
2236 mStreamType,
2237 sampleRate,
2238 format,
2239 channelMask,
2240 frameCount,
2241 flags,
Atneya Nairc1bf42b2021-11-29 19:00:54 -05002242 nullptr, // callback
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002243 0, // notification frames
2244 mSessionId,
2245 AudioTrack::TRANSFER_DEFAULT,
2246 NULL, // offload info
Svet Ganov33761132021-05-13 22:51:08 +00002247 mAttributionSource,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07002248 mAttributes,
Andy Hungff874dc2016-04-11 16:49:09 -07002249 doNotReconnect,
jiabin156c6872017-10-06 09:47:15 -07002250 targetSpeed,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002251 mSelectedDeviceId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002252 }
Andy Hunga6b27032020-04-27 10:34:24 -07002253 // Set caller name so it can be logged in destructor.
2254 // MediaMetricsConstants.h: AMEDIAMETRICS_PROP_CALLERNAME_VALUE_MEDIA
2255 t->setCallerName("media");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002256 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
2257 ALOGE("Unable to create audio track");
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002258 // t, newcbd goes out of scope, so reference count drops to zero
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002259 return NO_INIT;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07002260 } else {
2261 // successful AudioTrack initialization implies a legacy stream type was generated
2262 // from the audio attributes
2263 mStreamType = t->streamType();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002264 }
2265 }
2266
2267 if (reuse) {
2268 CHECK(mRecycledTrack != NULL);
2269
2270 if (!bothOffloaded) {
2271 if (mRecycledTrack->frameCount() != t->frameCount()) {
Andy Hung833b4752016-04-04 17:15:48 -07002272 ALOGV("framecount differs: %zu/%zu frames",
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002273 mRecycledTrack->frameCount(), t->frameCount());
2274 reuse = false;
2275 }
Jaideep Sharmab3ce4482020-11-16 11:52:35 +05302276 // If recycled and new tracks are not on the same output,
2277 // don't reuse the recycled one.
2278 if (mRecycledTrack->getOutput() != t->getOutput()) {
2279 ALOGV("output has changed, don't reuse track");
2280 reuse = false;
2281 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002282 }
2283
Marco Nelissen67295b52012-06-11 14:52:53 -07002284 if (reuse) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002285 ALOGV("chaining to next output and recycling track");
Andy Hungd1c74342015-07-07 16:54:23 -07002286 close_l();
Marco Nelissen67295b52012-06-11 14:52:53 -07002287 mTrack = mRecycledTrack;
Glenn Kasten2799d742013-05-30 14:33:29 -07002288 mRecycledTrack.clear();
Marco Nelissen67295b52012-06-11 14:52:53 -07002289 if (mCallbackData != NULL) {
2290 mCallbackData->setOutput(this);
2291 }
Wei Jiae0bbac92016-07-18 16:04:53 -07002292 return updateTrack();
Marco Nelissen67295b52012-06-11 14:52:53 -07002293 }
Marco Nelissen67295b52012-06-11 14:52:53 -07002294 }
2295
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002296 // we're not going to reuse the track, unblock and flush it
2297 // this was done earlier if both tracks are offloaded
2298 if (!bothOffloaded) {
Andy Hungd1c74342015-07-07 16:54:23 -07002299 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002300 }
2301
2302 CHECK((t != NULL) && ((mCallback == NULL) || (newcbd != NULL)));
2303
Marco Nelissen67295b52012-06-11 14:52:53 -07002304 mCallbackData = newcbd;
Steve Block3856b092011-10-20 11:56:00 +01002305 ALOGV("setVolume");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002306 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07002307
Andy Hung39399b62017-04-21 15:07:45 -07002308 // Restore VolumeShapers for the MediaPlayer in case the track was recreated
2309 // due to an output sink error (e.g. offload to non-offload switch).
2310 mVolumeHandler->forall([&t](const VolumeShaper &shaper) -> VolumeShaper::Status {
2311 sp<VolumeShaper::Operation> operationToEnd =
2312 new VolumeShaper::Operation(shaper.mOperation);
2313 // TODO: Ideally we would restore to the exact xOffset position
2314 // as returned by getVolumeShaperState(), but we don't have that
2315 // information when restoring at the client unless we periodically poll
2316 // the server or create shared memory state.
2317 //
2318 // For now, we simply advance to the end of the VolumeShaper effect
2319 // if it has been started.
2320 if (shaper.isStarted()) {
Andy Hungf3702642017-05-05 17:33:32 -07002321 operationToEnd->setNormalizedTime(1.f);
Andy Hung39399b62017-04-21 15:07:45 -07002322 }
2323 return t->applyVolumeShaper(shaper.mConfiguration, operationToEnd);
Andy Hung4ef88d72017-02-21 19:47:53 -08002324 });
Andy Hung4ef88d72017-02-21 19:47:53 -08002325
Vlad Popab4f5b012022-08-12 15:53:09 +02002326 if (mCachedPlayerIId != PLAYER_PIID_INVALID) {
2327 t->setPlayerIId(mCachedPlayerIId);
2328 }
2329
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002330 mSampleRateHz = sampleRate;
Preetam Singh Ranawat2e17eef2015-08-12 12:11:46 -07002331 mFlags = flags;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002332 mMsecsPerFrame = 1E3f / (mPlaybackRate.mSpeed * sampleRate);
Andy Hungd1c74342015-07-07 16:54:23 -07002333 mFrameSize = t->frameSize();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002334 mTrack = t;
Eric Laurent2beeb502010-07-16 07:43:46 -07002335
Wei Jiae0bbac92016-07-18 16:04:53 -07002336 return updateTrack();
2337}
2338
2339status_t MediaPlayerService::AudioOutput::updateTrack() {
2340 if (mTrack == NULL) {
2341 return NO_ERROR;
2342 }
2343
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002344 status_t res = NO_ERROR;
Wei Jia0162d002015-06-09 11:59:33 -07002345 // Note some output devices may give us a direct track even though we don't specify it.
2346 // Example: Line application b/17459982.
Wei Jiae0bbac92016-07-18 16:04:53 -07002347 if ((mTrack->getFlags()
2348 & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) {
2349 res = mTrack->setPlaybackRate(mPlaybackRate);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002350 if (res == NO_ERROR) {
Wei Jiae0bbac92016-07-18 16:04:53 -07002351 mTrack->setAuxEffectSendLevel(mSendLevel);
2352 res = mTrack->attachAuxEffect(mAuxEffectId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002353 }
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002354 }
jiabin156c6872017-10-06 09:47:15 -07002355 mTrack->setOutputDevice(mSelectedDeviceId);
2356 if (mDeviceCallbackEnabled) {
2357 mTrack->addAudioDeviceCallback(mDeviceCallback.promote());
2358 }
Wei Jiae0bbac92016-07-18 16:04:53 -07002359 ALOGV("updateTrack() DONE status %d", res);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002360 return res;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002361}
2362
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002363status_t MediaPlayerService::AudioOutput::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002364{
Steve Block3856b092011-10-20 11:56:00 +01002365 ALOGV("start");
Andy Hungd1c74342015-07-07 16:54:23 -07002366 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08002367 if (mCallbackData != NULL) {
2368 mCallbackData->endTrackSwitch();
2369 }
Glenn Kasten2799d742013-05-30 14:33:29 -07002370 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002371 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07002372 mTrack->setAuxEffectSendLevel(mSendLevel);
Andy Hung39399b62017-04-21 15:07:45 -07002373 status_t status = mTrack->start();
2374 if (status == NO_ERROR) {
2375 mVolumeHandler->setStarted();
2376 }
2377 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002378 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002379 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002380}
2381
Vlad Popab4f5b012022-08-12 15:53:09 +02002382void MediaPlayerService::AudioOutput::setPlayerIId(int32_t playerIId)
2383{
2384 ALOGV("setPlayerIId(%d)", playerIId);
2385 Mutex::Autolock lock(mLock);
2386 mCachedPlayerIId = playerIId;
2387
2388 if (mTrack != nullptr) {
2389 mTrack->setPlayerIId(mCachedPlayerIId);
2390 }
2391}
2392
Marco Nelissen6b74d672012-02-28 16:07:44 -08002393void MediaPlayerService::AudioOutput::setNextOutput(const sp<AudioOutput>& nextOutput) {
Andy Hungd1c74342015-07-07 16:54:23 -07002394 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08002395 mNextOutput = nextOutput;
2396}
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08002397
Marco Nelissen6b74d672012-02-28 16:07:44 -08002398void MediaPlayerService::AudioOutput::switchToNextOutput() {
2399 ALOGV("switchToNextOutput");
Andy Hungd1c74342015-07-07 16:54:23 -07002400
2401 // Try to acquire the callback lock before moving track (without incurring deadlock).
2402 const unsigned kMaxSwitchTries = 100;
2403 Mutex::Autolock lock(mLock);
2404 for (unsigned tries = 0;;) {
2405 if (mTrack == 0) {
2406 return;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002407 }
Andy Hungd1c74342015-07-07 16:54:23 -07002408 if (mNextOutput != NULL && mNextOutput != this) {
2409 if (mCallbackData != NULL) {
2410 // two alternative approaches
2411#if 1
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002412 sp<CallbackData> callbackData = mCallbackData;
Andy Hungd1c74342015-07-07 16:54:23 -07002413 mLock.unlock();
2414 // proper acquisition sequence
2415 callbackData->lock();
2416 mLock.lock();
2417 // Caution: it is unlikely that someone deleted our callback or changed our target
2418 if (callbackData != mCallbackData || mNextOutput == NULL || mNextOutput == this) {
2419 // fatal if we are starved out.
2420 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2421 "switchToNextOutput() cannot obtain correct lock sequence");
2422 callbackData->unlock();
2423 continue;
2424 }
2425 callbackData->mSwitching = true; // begin track switch
Wei Jiaadee56a2016-08-05 15:40:34 -07002426 callbackData->setOutput(NULL);
Andy Hungd1c74342015-07-07 16:54:23 -07002427#else
2428 // tryBeginTrackSwitch() returns false if the callback has the lock.
2429 if (!mCallbackData->tryBeginTrackSwitch()) {
2430 // fatal if we are starved out.
2431 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2432 "switchToNextOutput() cannot obtain callback lock");
2433 mLock.unlock();
2434 usleep(5 * 1000 /* usec */); // allow callback to use AudioOutput
2435 mLock.lock();
2436 continue;
2437 }
2438#endif
2439 }
2440
2441 Mutex::Autolock nextLock(mNextOutput->mLock);
2442
2443 // If the next output track is not NULL, then it has been
2444 // opened already for playback.
2445 // This is possible even without the next player being started,
2446 // for example, the next player could be prepared and seeked.
2447 //
2448 // Presuming it isn't advisable to force the track over.
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002449 if (mNextOutput->mTrack == nullptr) {
Andy Hungd1c74342015-07-07 16:54:23 -07002450 ALOGD("Recycling track for gapless playback");
Andy Hungd1c74342015-07-07 16:54:23 -07002451 mNextOutput->mCallbackData = mCallbackData;
2452 mNextOutput->mRecycledTrack = mTrack;
2453 mNextOutput->mSampleRateHz = mSampleRateHz;
2454 mNextOutput->mMsecsPerFrame = mMsecsPerFrame;
Andy Hungd1c74342015-07-07 16:54:23 -07002455 mNextOutput->mFlags = mFlags;
2456 mNextOutput->mFrameSize = mFrameSize;
2457 close_l();
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002458 mCallbackData.clear();
Andy Hungd1c74342015-07-07 16:54:23 -07002459 } else {
2460 ALOGW("Ignoring gapless playback because next player has already started");
2461 // remove track in case resource needed for future players.
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002462 if (mCallbackData != nullptr) {
Andy Hungd1c74342015-07-07 16:54:23 -07002463 mCallbackData->endTrackSwitch(); // release lock for callbacks before close.
2464 }
2465 close_l();
2466 }
2467 }
2468 break;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002469 }
2470}
2471
Wei Jia7d3f4df2015-03-03 15:28:00 -08002472ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002473{
Andy Hungd1c74342015-07-07 16:54:23 -07002474 Mutex::Autolock lock(mLock);
Glenn Kastenadad3d72014-02-21 14:51:43 -08002475 LOG_ALWAYS_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
Andreas Huber20111aa2009-07-14 16:56:47 -07002476
Steve Block3856b092011-10-20 11:56:00 +01002477 //ALOGV("write(%p, %u)", buffer, size);
Glenn Kasten2799d742013-05-30 14:33:29 -07002478 if (mTrack != 0) {
Andy Hung2f6e73d2016-04-08 12:12:58 -07002479 return mTrack->write(buffer, size, blocking);
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07002480 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002481 return NO_INIT;
2482}
2483
2484void MediaPlayerService::AudioOutput::stop()
2485{
Steve Block3856b092011-10-20 11:56:00 +01002486 ALOGV("stop");
Andy Hungd1c74342015-07-07 16:54:23 -07002487 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002488 if (mTrack != 0) mTrack->stop();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002489}
2490
2491void MediaPlayerService::AudioOutput::flush()
2492{
Steve Block3856b092011-10-20 11:56:00 +01002493 ALOGV("flush");
Andy Hungd1c74342015-07-07 16:54:23 -07002494 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002495 if (mTrack != 0) mTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002496}
2497
2498void MediaPlayerService::AudioOutput::pause()
2499{
Steve Block3856b092011-10-20 11:56:00 +01002500 ALOGV("pause");
Andy Hung959b5b82021-09-24 10:46:20 -07002501 // We use pauseAndWait() instead of pause() to ensure tracks ramp to silence before
2502 // any flush. We choose 40 ms timeout to allow 1 deep buffer mixer period
2503 // to occur. Often waiting is 0 - 20 ms.
2504 using namespace std::chrono_literals;
2505 constexpr auto TIMEOUT_MS = 40ms;
Andy Hungd1c74342015-07-07 16:54:23 -07002506 Mutex::Autolock lock(mLock);
Andy Hung959b5b82021-09-24 10:46:20 -07002507 if (mTrack != 0) mTrack->pauseAndWait(TIMEOUT_MS);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002508}
2509
2510void MediaPlayerService::AudioOutput::close()
2511{
Steve Block3856b092011-10-20 11:56:00 +01002512 ALOGV("close");
Erik Wolsheimer7845a1f2015-10-30 12:07:52 -07002513 sp<AudioTrack> track;
2514 {
2515 Mutex::Autolock lock(mLock);
2516 track = mTrack;
Jaideep Sharma511599f2022-01-06 13:38:57 +05302517 }
2518
2519 // do not hold lock while joining.
2520 if (track) {
2521 track->stopAndJoinCallbacks();
2522 }
2523
2524 {
2525 Mutex::Autolock lock(mLock);
Erik Wolsheimer7845a1f2015-10-30 12:07:52 -07002526 close_l(); // clears mTrack
2527 }
2528 // destruction of the track occurs outside of mutex.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002529}
2530
2531void MediaPlayerService::AudioOutput::setVolume(float left, float right)
2532{
Steve Block3856b092011-10-20 11:56:00 +01002533 ALOGV("setVolume(%f, %f)", left, right);
Andy Hungd1c74342015-07-07 16:54:23 -07002534 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002535 mLeftVolume = left;
2536 mRightVolume = right;
Glenn Kasten2799d742013-05-30 14:33:29 -07002537 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002538 mTrack->setVolume(left, right);
2539 }
2540}
2541
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002542status_t MediaPlayerService::AudioOutput::setPlaybackRate(const AudioPlaybackRate &rate)
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002543{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002544 ALOGV("setPlaybackRate(%f %f %d %d)",
2545 rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Andy Hungd1c74342015-07-07 16:54:23 -07002546 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002547 if (mTrack == 0) {
2548 // remember rate so that we can set it when the track is opened
2549 mPlaybackRate = rate;
2550 return OK;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002551 }
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002552 status_t res = mTrack->setPlaybackRate(rate);
2553 if (res != NO_ERROR) {
2554 return res;
2555 }
2556 // rate.mSpeed is always greater than 0 if setPlaybackRate succeeded
2557 CHECK_GT(rate.mSpeed, 0.f);
2558 mPlaybackRate = rate;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002559 if (mSampleRateHz != 0) {
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002560 mMsecsPerFrame = 1E3f / (rate.mSpeed * mSampleRateHz);
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002561 }
2562 return res;
2563}
2564
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002565status_t MediaPlayerService::AudioOutput::getPlaybackRate(AudioPlaybackRate *rate)
2566{
2567 ALOGV("setPlaybackRate");
Andy Hungd1c74342015-07-07 16:54:23 -07002568 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002569 if (mTrack == 0) {
2570 return NO_INIT;
2571 }
2572 *rate = mTrack->getPlaybackRate();
2573 return NO_ERROR;
2574}
2575
Eric Laurent2beeb502010-07-16 07:43:46 -07002576status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
2577{
Steve Block3856b092011-10-20 11:56:00 +01002578 ALOGV("setAuxEffectSendLevel(%f)", level);
Andy Hungd1c74342015-07-07 16:54:23 -07002579 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002580 mSendLevel = level;
Glenn Kasten2799d742013-05-30 14:33:29 -07002581 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002582 return mTrack->setAuxEffectSendLevel(level);
2583 }
2584 return NO_ERROR;
2585}
2586
2587status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
2588{
Steve Block3856b092011-10-20 11:56:00 +01002589 ALOGV("attachAuxEffect(%d)", effectId);
Andy Hungd1c74342015-07-07 16:54:23 -07002590 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002591 mAuxEffectId = effectId;
Glenn Kasten2799d742013-05-30 14:33:29 -07002592 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002593 return mTrack->attachAuxEffect(effectId);
2594 }
2595 return NO_ERROR;
2596}
2597
jiabin156c6872017-10-06 09:47:15 -07002598status_t MediaPlayerService::AudioOutput::setOutputDevice(audio_port_handle_t deviceId)
2599{
2600 ALOGV("setOutputDevice(%d)", deviceId);
2601 Mutex::Autolock lock(mLock);
2602 mSelectedDeviceId = deviceId;
2603 if (mTrack != 0) {
2604 return mTrack->setOutputDevice(deviceId);
2605 }
2606 return NO_ERROR;
2607}
2608
Robert Wub7f8edc2024-11-04 19:54:38 +00002609status_t MediaPlayerService::AudioOutput::getRoutedDeviceIds(DeviceIdVector& deviceIds)
jiabin156c6872017-10-06 09:47:15 -07002610{
Robert Wub7f8edc2024-11-04 19:54:38 +00002611 ALOGV("getRoutedDeviceIds");
jiabin156c6872017-10-06 09:47:15 -07002612 Mutex::Autolock lock(mLock);
2613 if (mTrack != 0) {
Robert Wub7f8edc2024-11-04 19:54:38 +00002614 mRoutedDeviceIds = mTrack->getRoutedDeviceIds();
jiabin156c6872017-10-06 09:47:15 -07002615 }
Robert Wub7f8edc2024-11-04 19:54:38 +00002616 deviceIds = mRoutedDeviceIds;
jiabin161b64f2017-11-17 09:31:48 -08002617 return NO_ERROR;
jiabin156c6872017-10-06 09:47:15 -07002618}
2619
2620status_t MediaPlayerService::AudioOutput::enableAudioDeviceCallback(bool enabled)
2621{
2622 ALOGV("enableAudioDeviceCallback, %d", enabled);
2623 Mutex::Autolock lock(mLock);
2624 mDeviceCallbackEnabled = enabled;
2625 if (mTrack != 0) {
2626 status_t status;
2627 if (enabled) {
2628 status = mTrack->addAudioDeviceCallback(mDeviceCallback.promote());
2629 } else {
2630 status = mTrack->removeAudioDeviceCallback(mDeviceCallback.promote());
2631 }
2632 return status;
2633 }
2634 return NO_ERROR;
2635}
2636
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002637VolumeShaper::Status MediaPlayerService::AudioOutput::applyVolumeShaper(
2638 const sp<VolumeShaper::Configuration>& configuration,
2639 const sp<VolumeShaper::Operation>& operation)
2640{
2641 Mutex::Autolock lock(mLock);
2642 ALOGV("AudioOutput::applyVolumeShaper");
Andy Hung4ef88d72017-02-21 19:47:53 -08002643
Pawan Wagh8282bb42023-07-05 23:01:17 +00002644 if (configuration == nullptr) {
2645 ALOGE("AudioOutput::applyVolumeShaper Null configuration parameter");
2646 return VolumeShaper::Status(BAD_VALUE);
2647 }
2648
2649 if (operation == nullptr) {
2650 ALOGE("AudioOutput::applyVolumeShaper Null operation parameter");
2651 return VolumeShaper::Status(BAD_VALUE);
2652 }
2653
Andy Hung4ef88d72017-02-21 19:47:53 -08002654 mVolumeHandler->setIdIfNecessary(configuration);
Andy Hung39399b62017-04-21 15:07:45 -07002655
2656 VolumeShaper::Status status;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002657 if (mTrack != 0) {
Andy Hung39399b62017-04-21 15:07:45 -07002658 status = mTrack->applyVolumeShaper(configuration, operation);
2659 if (status >= 0) {
2660 (void)mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hungf3702642017-05-05 17:33:32 -07002661 if (mTrack->isPlaying()) { // match local AudioTrack to properly restore.
2662 mVolumeHandler->setStarted();
2663 }
Andy Hung39399b62017-04-21 15:07:45 -07002664 }
Andy Hung4ef88d72017-02-21 19:47:53 -08002665 } else {
Andy Hungc01eddb2017-07-21 16:42:41 -07002666 // VolumeShapers are not affected when a track moves between players for
2667 // gapless playback (setNextMediaPlayer).
2668 // We forward VolumeShaper operations that do not change configuration
2669 // to the new player so that unducking may occur as expected.
2670 // Unducking is an idempotent operation, same if applied back-to-back.
2671 if (configuration->getType() == VolumeShaper::Configuration::TYPE_ID
2672 && mNextOutput != nullptr) {
2673 ALOGV("applyVolumeShaper: Attempting to forward missed operation: %s %s",
2674 configuration->toString().c_str(), operation->toString().c_str());
2675 Mutex::Autolock nextLock(mNextOutput->mLock);
2676
2677 // recycled track should be forwarded from this AudioSink by switchToNextOutput
2678 sp<AudioTrack> track = mNextOutput->mRecycledTrack;
2679 if (track != nullptr) {
2680 ALOGD("Forward VolumeShaper operation to recycled track %p", track.get());
2681 (void)track->applyVolumeShaper(configuration, operation);
2682 } else {
2683 // There is a small chance that the unduck occurs after the next
2684 // player has already started, but before it is registered to receive
2685 // the unduck command.
2686 track = mNextOutput->mTrack;
2687 if (track != nullptr) {
2688 ALOGD("Forward VolumeShaper operation to track %p", track.get());
2689 (void)track->applyVolumeShaper(configuration, operation);
2690 }
2691 }
2692 }
Andy Hung39399b62017-04-21 15:07:45 -07002693 status = mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002694 }
Andy Hung39399b62017-04-21 15:07:45 -07002695 return status;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002696}
2697
2698sp<VolumeShaper::State> MediaPlayerService::AudioOutput::getVolumeShaperState(int id)
2699{
2700 Mutex::Autolock lock(mLock);
2701 if (mTrack != 0) {
2702 return mTrack->getVolumeShaperState(id);
Andy Hung4ef88d72017-02-21 19:47:53 -08002703 } else {
2704 return mVolumeHandler->getVolumeShaperState(id);
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002705 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002706}
2707
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002708size_t MediaPlayerService::AudioOutput::CallbackData::onMoreData(const AudioTrack::Buffer& buffer) {
2709 ALOGD("data callback");
2710 lock();
2711 sp<AudioOutput> me = getOutput();
2712 if (me == nullptr) {
2713 unlock();
2714 return 0;
2715 }
2716 size_t actualSize = (*me->mCallback)(
Andy Hunge42b6482024-10-16 19:16:50 -07002717 me, buffer.data(), buffer.size(), me->mCallbackCookie,
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002718 CB_EVENT_FILL_BUFFER);
2719
2720 // Log when no data is returned from the callback.
2721 // (1) We may have no data (especially with network streaming sources).
2722 // (2) We may have reached the EOS and the audio track is not stopped yet.
2723 // Note that AwesomePlayer/AudioPlayer will only return zero size when it reaches the EOS.
2724 // NuPlayerRenderer will return zero when it doesn't have data (it doesn't block to fill).
2725 //
2726 // This is a benign busy-wait, with the next data request generated 10 ms or more later;
2727 // nevertheless for power reasons, we don't want to see too many of these.
2728
Santiago Seifert578aeb52022-10-24 07:59:12 +00002729 ALOGV_IF(actualSize == 0 && buffer.size() > 0, "callbackwrapper: empty buffer returned");
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002730 unlock();
2731 return actualSize;
2732}
2733
2734void MediaPlayerService::AudioOutput::CallbackData::onStreamEnd() {
2735 lock();
2736 sp<AudioOutput> me = getOutput();
2737 if (me == nullptr) {
2738 unlock();
Marco Nelissen6b74d672012-02-28 16:07:44 -08002739 return;
2740 }
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002741 ALOGV("callbackwrapper: deliver EVENT_STREAM_END");
Andy Hunge42b6482024-10-16 19:16:50 -07002742 (*me->mCallback)(me, nullptr /* buffer */, 0 /* size */,
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002743 me->mCallbackCookie, CB_EVENT_STREAM_END);
2744 unlock();
2745}
Andreas Huber20111aa2009-07-14 16:56:47 -07002746
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002747
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002748void MediaPlayerService::AudioOutput::CallbackData::onNewIAudioTrack() {
2749 lock();
2750 sp<AudioOutput> me = getOutput();
2751 if (me == nullptr) {
2752 unlock();
2753 return;
Andreas Huber51c1e0e2011-04-04 11:43:40 -07002754 }
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002755 ALOGV("callbackwrapper: deliver EVENT_TEAR_DOWN");
Andy Hunge42b6482024-10-16 19:16:50 -07002756 (*me->mCallback)(me, nullptr /* buffer */, 0 /* size */,
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002757 me->mCallbackCookie, CB_EVENT_TEAR_DOWN);
2758 unlock();
2759}
Andreas Huber51c1e0e2011-04-04 11:43:40 -07002760
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002761void MediaPlayerService::AudioOutput::CallbackData::onUnderrun() {
2762 // This occurs when there is no data available, typically
2763 // when there is a failure to supply data to the AudioTrack. It can also
2764 // occur in non-offloaded mode when the audio device comes out of standby.
2765 //
2766 // If an AudioTrack underruns it outputs silence. Since this happens suddenly
2767 // it may sound like an audible pop or glitch.
2768 //
2769 // The underrun event is sent once per track underrun; the condition is reset
2770 // when more data is sent to the AudioTrack.
2771 ALOGD("callbackwrapper: EVENT_UNDERRUN (discarded)");
2772
Andreas Huber20111aa2009-07-14 16:56:47 -07002773}
2774
Glenn Kastend848eb42016-03-08 13:42:11 -08002775audio_session_t MediaPlayerService::AudioOutput::getSessionId() const
Eric Laurent8c563ed2010-10-07 18:23:03 -07002776{
Andy Hungd1c74342015-07-07 16:54:23 -07002777 Mutex::Autolock lock(mLock);
Eric Laurent8c563ed2010-10-07 18:23:03 -07002778 return mSessionId;
2779}
2780
Eric Laurent6f59db12013-07-26 17:16:50 -07002781uint32_t MediaPlayerService::AudioOutput::getSampleRate() const
2782{
Andy Hungd1c74342015-07-07 16:54:23 -07002783 Mutex::Autolock lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -07002784 if (mTrack == 0) return 0;
2785 return mTrack->getSampleRate();
2786}
2787
Andy Hungf2c87b32016-04-07 19:49:29 -07002788int64_t MediaPlayerService::AudioOutput::getBufferDurationInUs() const
2789{
2790 Mutex::Autolock lock(mLock);
2791 if (mTrack == 0) {
2792 return 0;
2793 }
2794 int64_t duration;
2795 if (mTrack->getBufferDurationInUs(&duration) != OK) {
2796 return 0;
2797 }
2798 return duration;
2799}
2800
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002801////////////////////////////////////////////////////////////////////////////////
2802
2803struct CallbackThread : public Thread {
2804 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
2805 MediaPlayerBase::AudioSink::AudioCallback cb,
Andy Hunge42b6482024-10-16 19:16:50 -07002806 const wp<RefBase>& cookie);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002807
2808protected:
2809 virtual ~CallbackThread();
2810
2811 virtual bool threadLoop();
2812
2813private:
2814 wp<MediaPlayerBase::AudioSink> mSink;
2815 MediaPlayerBase::AudioSink::AudioCallback mCallback;
Andy Hunge42b6482024-10-16 19:16:50 -07002816 wp<RefBase> mCookie;
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002817 void *mBuffer;
2818 size_t mBufferSize;
2819
2820 CallbackThread(const CallbackThread &);
2821 CallbackThread &operator=(const CallbackThread &);
2822};
2823
2824CallbackThread::CallbackThread(
2825 const wp<MediaPlayerBase::AudioSink> &sink,
2826 MediaPlayerBase::AudioSink::AudioCallback cb,
Andy Hunge42b6482024-10-16 19:16:50 -07002827 const wp<RefBase>& cookie)
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002828 : mSink(sink),
2829 mCallback(cb),
2830 mCookie(cookie),
2831 mBuffer(NULL),
2832 mBufferSize(0) {
2833}
2834
2835CallbackThread::~CallbackThread() {
2836 if (mBuffer) {
2837 free(mBuffer);
2838 mBuffer = NULL;
2839 }
2840}
2841
2842bool CallbackThread::threadLoop() {
2843 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
2844 if (sink == NULL) {
2845 return false;
2846 }
2847
2848 if (mBuffer == NULL) {
2849 mBufferSize = sink->bufferSize();
2850 mBuffer = malloc(mBufferSize);
2851 }
2852
2853 size_t actualSize =
Andy Hunge42b6482024-10-16 19:16:50 -07002854 (*mCallback)(sink, mBuffer, mBufferSize, mCookie,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002855 MediaPlayerBase::AudioSink::CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002856
2857 if (actualSize > 0) {
2858 sink->write(mBuffer, actualSize);
Andy Hunga31335a2014-08-20 17:37:59 -07002859 // Could return false on sink->write() error or short count.
2860 // Not necessarily appropriate but would work for AudioCache behavior.
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002861 }
2862
2863 return true;
2864}
2865
2866////////////////////////////////////////////////////////////////////////////////
2867
Chong Zhange5b9b692017-05-11 11:44:56 -07002868void MediaPlayerService::addBatteryData(uint32_t params) {
2869 mBatteryTracker.addBatteryData(params);
2870}
2871
2872status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
2873 return mBatteryTracker.pullBatteryData(reply);
2874}
2875
2876MediaPlayerService::BatteryTracker::BatteryTracker() {
2877 mBatteryAudio.refCount = 0;
2878 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2879 mBatteryAudio.deviceOn[i] = 0;
2880 mBatteryAudio.lastTime[i] = 0;
2881 mBatteryAudio.totalTime[i] = 0;
2882 }
2883 // speaker is on by default
2884 mBatteryAudio.deviceOn[SPEAKER] = 1;
2885
2886 // reset battery stats
2887 // if the mediaserver has crashed, battery stats could be left
2888 // in bad state, reset the state upon service start.
2889 BatteryNotifier::getInstance().noteResetVideo();
2890}
2891
2892void MediaPlayerService::BatteryTracker::addBatteryData(uint32_t params)
Gloria Wang7cf180c2011-02-19 18:37:57 -08002893{
2894 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002895
2896 int32_t time = systemTime() / 1000000L;
2897
2898 // change audio output devices. This notification comes from AudioFlinger
2899 if ((params & kBatteryDataSpeakerOn)
2900 || (params & kBatteryDataOtherAudioDeviceOn)) {
2901
2902 int deviceOn[NUM_AUDIO_DEVICES];
2903 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2904 deviceOn[i] = 0;
2905 }
2906
2907 if ((params & kBatteryDataSpeakerOn)
2908 && (params & kBatteryDataOtherAudioDeviceOn)) {
2909 deviceOn[SPEAKER_AND_OTHER] = 1;
2910 } else if (params & kBatteryDataSpeakerOn) {
2911 deviceOn[SPEAKER] = 1;
2912 } else {
2913 deviceOn[OTHER_AUDIO_DEVICE] = 1;
2914 }
2915
2916 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2917 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
2918
2919 if (mBatteryAudio.refCount > 0) { // if playing audio
2920 if (!deviceOn[i]) {
2921 mBatteryAudio.lastTime[i] += time;
2922 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2923 mBatteryAudio.lastTime[i] = 0;
2924 } else {
2925 mBatteryAudio.lastTime[i] = 0 - time;
2926 }
2927 }
2928
2929 mBatteryAudio.deviceOn[i] = deviceOn[i];
2930 }
2931 }
2932 return;
2933 }
2934
Marco Nelissenb7848f12014-12-04 08:57:56 -08002935 // an audio stream is started
Gloria Wang9ee159b2011-02-24 14:51:45 -08002936 if (params & kBatteryDataAudioFlingerStart) {
2937 // record the start time only if currently no other audio
2938 // is being played
2939 if (mBatteryAudio.refCount == 0) {
2940 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2941 if (mBatteryAudio.deviceOn[i]) {
2942 mBatteryAudio.lastTime[i] -= time;
2943 }
2944 }
2945 }
2946
2947 mBatteryAudio.refCount ++;
2948 return;
2949
2950 } else if (params & kBatteryDataAudioFlingerStop) {
2951 if (mBatteryAudio.refCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002952 ALOGW("Battery track warning: refCount is <= 0");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002953 return;
2954 }
2955
2956 // record the stop time only if currently this is the only
2957 // audio being played
2958 if (mBatteryAudio.refCount == 1) {
2959 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2960 if (mBatteryAudio.deviceOn[i]) {
2961 mBatteryAudio.lastTime[i] += time;
2962 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2963 mBatteryAudio.lastTime[i] = 0;
2964 }
2965 }
2966 }
2967
2968 mBatteryAudio.refCount --;
2969 return;
2970 }
2971
Andy Hung1afd0982016-11-08 16:13:44 -08002972 uid_t uid = IPCThreadState::self()->getCallingUid();
Gloria Wang7cf180c2011-02-19 18:37:57 -08002973 if (uid == AID_MEDIA) {
2974 return;
2975 }
2976 int index = mBatteryData.indexOfKey(uid);
Gloria Wang7cf180c2011-02-19 18:37:57 -08002977
2978 if (index < 0) { // create a new entry for this UID
2979 BatteryUsageInfo info;
2980 info.audioTotalTime = 0;
2981 info.videoTotalTime = 0;
2982 info.audioLastTime = 0;
2983 info.videoLastTime = 0;
2984 info.refCount = 0;
2985
Gloria Wang9ee159b2011-02-24 14:51:45 -08002986 if (mBatteryData.add(uid, info) == NO_MEMORY) {
Steve Block29357bc2012-01-06 19:20:56 +00002987 ALOGE("Battery track error: no memory for new app");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002988 return;
2989 }
Gloria Wang7cf180c2011-02-19 18:37:57 -08002990 }
2991
2992 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
2993
2994 if (params & kBatteryDataCodecStarted) {
2995 if (params & kBatteryDataTrackAudio) {
2996 info.audioLastTime -= time;
2997 info.refCount ++;
2998 }
2999 if (params & kBatteryDataTrackVideo) {
3000 info.videoLastTime -= time;
3001 info.refCount ++;
3002 }
3003 } else {
3004 if (info.refCount == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003005 ALOGW("Battery track warning: refCount is already 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08003006 return;
3007 } else if (info.refCount < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00003008 ALOGE("Battery track error: refCount < 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08003009 mBatteryData.removeItem(uid);
3010 return;
3011 }
3012
3013 if (params & kBatteryDataTrackAudio) {
3014 info.audioLastTime += time;
3015 info.refCount --;
3016 }
3017 if (params & kBatteryDataTrackVideo) {
3018 info.videoLastTime += time;
3019 info.refCount --;
3020 }
3021
3022 // no stream is being played by this UID
3023 if (info.refCount == 0) {
3024 info.audioTotalTime += info.audioLastTime;
3025 info.audioLastTime = 0;
3026 info.videoTotalTime += info.videoLastTime;
3027 info.videoLastTime = 0;
3028 }
3029 }
3030}
3031
Chong Zhange5b9b692017-05-11 11:44:56 -07003032status_t MediaPlayerService::BatteryTracker::pullBatteryData(Parcel* reply) {
Gloria Wang7cf180c2011-02-19 18:37:57 -08003033 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08003034
3035 // audio output devices usage
3036 int32_t time = systemTime() / 1000000L; //in ms
3037 int32_t totalTime;
3038
3039 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
3040 totalTime = mBatteryAudio.totalTime[i];
3041
3042 if (mBatteryAudio.deviceOn[i]
3043 && (mBatteryAudio.lastTime[i] != 0)) {
3044 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
3045 totalTime += tmpTime;
3046 }
3047
3048 reply->writeInt32(totalTime);
3049 // reset the total time
3050 mBatteryAudio.totalTime[i] = 0;
3051 }
3052
3053 // codec usage
Gloria Wang7cf180c2011-02-19 18:37:57 -08003054 BatteryUsageInfo info;
3055 int size = mBatteryData.size();
3056
3057 reply->writeInt32(size);
3058 int i = 0;
3059
3060 while (i < size) {
3061 info = mBatteryData.valueAt(i);
3062
3063 reply->writeInt32(mBatteryData.keyAt(i)); //UID
3064 reply->writeInt32(info.audioTotalTime);
3065 reply->writeInt32(info.videoTotalTime);
3066
3067 info.audioTotalTime = 0;
3068 info.videoTotalTime = 0;
3069
3070 // remove the UID entry where no stream is being played
3071 if (info.refCount <= 0) {
3072 mBatteryData.removeItemsAt(i);
3073 size --;
3074 i --;
3075 }
3076 i++;
3077 }
3078 return NO_ERROR;
3079}
Pawan Wagh074e53c2023-06-20 22:06:43 +00003080
3081#ifdef FUZZ_MODE_MEDIA_PLAYER_SERVICE
3082sp<MediaPlayerService> MediaPlayerService::createForFuzzTesting() {
3083 return sp<MediaPlayerService>::make();
3084}
3085#endif // FUZZ_MODE_MEDIA_PLAYER_SERVICE
3086
nikoa64c8c72009-07-20 15:07:26 -07003087} // namespace android