blob: fdcf2469b76f16901d3b9e4e4c251784bc80d704 [file] [log] [blame]
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001/*
2**
3** Copyright 2008, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18// Proxy for media player implementations
19
20//#define LOG_NDEBUG 0
21#define LOG_TAG "MediaPlayerService"
22#include <utils/Log.h>
23
Andy Hung959b5b82021-09-24 10:46:20 -070024#include <chrono>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080025#include <sys/types.h>
26#include <sys/stat.h>
Gloria Wang7cf180c2011-02-19 18:37:57 -080027#include <sys/time.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080028#include <dirent.h>
29#include <unistd.h>
30
31#include <string.h>
Mathias Agopian6f74b0c2009-06-03 17:32:49 -070032
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080033#include <cutils/atomic.h>
Nicolas Catania14d27472009-07-13 14:37:49 -070034#include <cutils/properties.h> // for property_get
Mathias Agopian6f74b0c2009-06-03 17:32:49 -070035
36#include <utils/misc.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080037
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -070038#include <android/hardware/media/omx/1.0/IOmx.h>
Marco Nelissena0c98412019-03-29 12:10:19 -070039#include <android/hardware/media/c2/1.0/IComponentStore.h>
Mathias Agopian75624082009-05-19 19:08:10 -070040#include <binder/IPCThreadState.h>
41#include <binder/IServiceManager.h>
42#include <binder/MemoryHeapBase.h>
43#include <binder/MemoryBase.h>
Mathias Agopianb1e7cd12013-02-14 17:11:27 -080044#include <gui/Surface.h>
Nicolas Catania1d187f12009-05-12 23:25:55 -070045#include <utils/Errors.h> // for status_t
46#include <utils/String8.h>
Marco Nelissen10dbb8e2009-09-20 10:42:13 -070047#include <utils/SystemClock.h>
Lajos Molnar06ad1522014-08-28 07:27:44 -070048#include <utils/Timers.h>
Nicolas Catania1d187f12009-05-12 23:25:55 -070049#include <utils/Vector.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080050
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -070051#include <codec2/hidl/client.h>
Marco Nelissen42057ce2019-09-23 12:15:57 -070052#include <datasource/HTTPBase.h>
Philip P. Moltmannbda45752020-07-17 16:41:18 -070053#include <media/AidlConversion.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080054#include <media/IMediaHTTPService.h>
Jeff Brown2013a542012-09-04 21:38:42 -070055#include <media/IRemoteDisplay.h>
56#include <media/IRemoteDisplayClient.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080057#include <media/MediaPlayerInterface.h>
58#include <media/mediarecorder.h>
59#include <media/MediaMetadataRetrieverInterface.h>
nikoa64c8c72009-07-20 15:07:26 -070060#include <media/Metadata.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080061#include <media/AudioTrack.h>
Dongwon Kangd91dc5a2017-10-10 00:07:09 -070062#include <media/stagefright/InterfaceUtils.h>
Wonsik Kim6f675772019-08-20 17:06:53 -070063#include <media/stagefright/MediaCodecConstants.h>
Lajos Molnar1381d4b2014-08-07 15:18:35 -070064#include <media/stagefright/MediaCodecList.h>
Eric Laurent9cb839a2011-09-27 09:48:56 -070065#include <media/stagefright/MediaErrors.h>
Marco Nelissen83b0fd92015-09-16 13:48:07 -070066#include <media/stagefright/Utils.h>
Marco Nelissen42057ce2019-09-23 12:15:57 -070067#include <media/stagefright/FoundationUtils.h>
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +010068#include <media/stagefright/foundation/ADebug.h>
Marco Nelissenf09611f2015-02-13 14:12:42 -080069#include <media/stagefright/foundation/ALooperRoster.h>
Chong Zhang181fd9b2017-02-16 15:53:03 -080070#include <media/stagefright/SurfaceUtils.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070071#include <mediautils/BatteryNotifier.h>
Andy Hunge9eb03e2020-04-04 14:08:23 -070072#include <mediautils/MemoryLeakTrackUtil.h>
Andy Hung53541292016-04-13 16:48:51 -070073#include <memunreachable/memunreachable.h>
Dima Zavin64760242011-05-11 14:15:23 -070074#include <system/audio.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070075
Gloria Wang7cf180c2011-02-19 18:37:57 -080076#include <private/android_filesystem_config.h>
77
James Dong559bf282012-03-28 10:29:14 -070078#include "ActivityManager.h"
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080079#include "MediaRecorderClient.h"
80#include "MediaPlayerService.h"
81#include "MetadataRetrieverClient.h"
John Grossman44a7e422012-06-21 17:29:24 -070082#include "MediaPlayerFactory.h"
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080083
Nicolas Catania14d27472009-07-13 14:37:49 -070084#include "TestPlayerStub.h"
Ray Essickafca1562022-01-25 09:51:42 -080085#include <nuplayer/NuPlayerDriver.h>
Andreas Huber20111aa2009-07-14 16:56:47 -070086
Andreas Hubered3e3e02012-03-26 11:13:27 -070087
Wei Jia502c2f42017-07-13 17:47:56 -070088static const int kDumpLockRetries = 50;
89static const int kDumpLockSleepUs = 20000;
90
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070091namespace {
nikoa64c8c72009-07-20 15:07:26 -070092using android::media::Metadata;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070093using android::status_t;
94using android::OK;
95using android::BAD_VALUE;
96using android::NOT_ENOUGH_DATA;
97using android::Parcel;
Ivan Lozano8cf3a072017-08-09 09:01:33 -070098using android::media::VolumeShaper;
Svet Ganov33761132021-05-13 22:51:08 +000099using android::content::AttributionSourceState;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700100
101// Max number of entries in the filter.
102const int kMaxFilterSize = 64; // I pulled that out of thin air.
103
Andy Hungff874dc2016-04-11 16:49:09 -0700104const float kMaxRequiredSpeed = 8.0f; // for PCM tracks allow up to 8x speedup.
105
nikoa64c8c72009-07-20 15:07:26 -0700106// FIXME: Move all the metadata related function in the Metadata.cpp
nikod608a812009-07-16 16:39:53 -0700107
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700108
109// Unmarshall a filter from a Parcel.
110// Filter format in a parcel:
111//
112// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
113// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
114// | number of entries (n) |
115// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
116// | metadata type 1 |
117// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
118// | metadata type 2 |
119// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
120// ....
121// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
122// | metadata type n |
123// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
124//
125// @param p Parcel that should start with a filter.
126// @param[out] filter On exit contains the list of metadata type to be
127// filtered.
128// @param[out] status On exit contains the status code to be returned.
129// @return true if the parcel starts with a valid filter.
130bool unmarshallFilter(const Parcel& p,
nikoa64c8c72009-07-20 15:07:26 -0700131 Metadata::Filter *filter,
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700132 status_t *status)
133{
Nicolas Catania48290382009-07-10 13:53:06 -0700134 int32_t val;
135 if (p.readInt32(&val) != OK)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700136 {
Steve Block29357bc2012-01-06 19:20:56 +0000137 ALOGE("Failed to read filter's length");
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700138 *status = NOT_ENOUGH_DATA;
139 return false;
140 }
141
Nicolas Catania48290382009-07-10 13:53:06 -0700142 if( val > kMaxFilterSize || val < 0)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700143 {
Steve Block29357bc2012-01-06 19:20:56 +0000144 ALOGE("Invalid filter len %d", val);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700145 *status = BAD_VALUE;
146 return false;
147 }
148
Nicolas Catania48290382009-07-10 13:53:06 -0700149 const size_t num = val;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700150
151 filter->clear();
Nicolas Catania48290382009-07-10 13:53:06 -0700152 filter->setCapacity(num);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700153
nikoa64c8c72009-07-20 15:07:26 -0700154 size_t size = num * sizeof(Metadata::Type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700155
Nicolas Catania48290382009-07-10 13:53:06 -0700156
157 if (p.dataAvail() < size)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700158 {
Andy Hung833b4752016-04-04 17:15:48 -0700159 ALOGE("Filter too short expected %zu but got %zu", size, p.dataAvail());
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700160 *status = NOT_ENOUGH_DATA;
161 return false;
162 }
163
nikoa64c8c72009-07-20 15:07:26 -0700164 const Metadata::Type *data =
165 static_cast<const Metadata::Type*>(p.readInplace(size));
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700166
Nicolas Catania48290382009-07-10 13:53:06 -0700167 if (NULL == data)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700168 {
Steve Block29357bc2012-01-06 19:20:56 +0000169 ALOGE("Filter had no data");
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700170 *status = BAD_VALUE;
171 return false;
172 }
173
174 // TODO: The stl impl of vector would be more efficient here
175 // because it degenerates into a memcpy on pod types. Try to
176 // replace later or use stl::set.
Nicolas Catania48290382009-07-10 13:53:06 -0700177 for (size_t i = 0; i < num; ++i)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700178 {
Nicolas Catania48290382009-07-10 13:53:06 -0700179 filter->add(*data);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700180 ++data;
181 }
182 *status = OK;
183 return true;
184}
185
Nicolas Catania48290382009-07-10 13:53:06 -0700186// @param filter Of metadata type.
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700187// @param val To be searched.
188// @return true if a match was found.
nikoa64c8c72009-07-20 15:07:26 -0700189bool findMetadata(const Metadata::Filter& filter, const int32_t val)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700190{
191 // Deal with empty and ANY right away
192 if (filter.isEmpty()) return false;
nikoa64c8c72009-07-20 15:07:26 -0700193 if (filter[0] == Metadata::kAny) return true;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700194
Nicolas Catania48290382009-07-10 13:53:06 -0700195 return filter.indexOf(val) >= 0;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700196}
197
198} // anonymous namespace
199
200
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700201namespace {
202using android::Parcel;
203using android::String16;
204
205// marshalling tag indicating flattened utf16 tags
206// keep in sync with frameworks/base/media/java/android/media/AudioAttributes.java
207const int32_t kAudioAttributesMarshallTagFlattenTags = 1;
208
209// Audio attributes format in a parcel:
210//
211// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
212// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
213// | usage |
214// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
215// | content_type |
216// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Hyejin Kim4f418f92014-09-05 15:50:03 +0900217// | source |
218// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700219// | flags |
220// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
221// | kAudioAttributesMarshallTagFlattenTags | // ignore tags if not found
222// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
223// | flattened tags in UTF16 |
224// | ... |
225// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
226//
227// @param p Parcel that contains audio attributes.
228// @param[out] attributes On exit points to an initialized audio_attributes_t structure
229// @param[out] status On exit contains the status code to be returned.
230void unmarshallAudioAttributes(const Parcel& parcel, audio_attributes_t *attributes)
231{
232 attributes->usage = (audio_usage_t) parcel.readInt32();
233 attributes->content_type = (audio_content_type_t) parcel.readInt32();
Hyejin Kim4f418f92014-09-05 15:50:03 +0900234 attributes->source = (audio_source_t) parcel.readInt32();
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700235 attributes->flags = (audio_flags_mask_t) parcel.readInt32();
236 const bool hasFlattenedTag = (parcel.readInt32() == kAudioAttributesMarshallTagFlattenTags);
237 if (hasFlattenedTag) {
238 // the tags are UTF16, convert to UTF8
239 String16 tags = parcel.readString16();
240 ssize_t realTagSize = utf16_to_utf8_length(tags.string(), tags.size());
241 if (realTagSize <= 0) {
242 strcpy(attributes->tags, "");
243 } else {
244 // copy the flattened string into the attributes as the destination for the conversion:
245 // copying array size -1, array for tags was calloc'd, no need to NULL-terminate it
246 size_t tagSize = realTagSize > AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 ?
247 AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 : realTagSize;
Sergio Giro1d3f4272016-06-28 18:24:52 +0100248 utf16_to_utf8(tags.string(), tagSize, attributes->tags,
249 sizeof(attributes->tags) / sizeof(attributes->tags[0]));
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700250 }
251 } else {
252 ALOGE("unmarshallAudioAttributes() received unflattened tags, ignoring tag values");
253 strcpy(attributes->tags, "");
254 }
255}
256} // anonymous namespace
257
258
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800259namespace android {
260
Marco Nelissenf09611f2015-02-13 14:12:42 -0800261extern ALooperRoster gLooperRoster;
262
263
Dave Burked681bbb2011-08-30 14:39:17 +0100264static bool checkPermission(const char* permissionString) {
Dave Burked681bbb2011-08-30 14:39:17 +0100265 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
266 bool ok = checkCallingPermission(String16(permissionString));
Steve Block29357bc2012-01-06 19:20:56 +0000267 if (!ok) ALOGE("Request requires %s", permissionString);
Dave Burked681bbb2011-08-30 14:39:17 +0100268 return ok;
269}
270
Wonsik Kim6f675772019-08-20 17:06:53 -0700271static void dumpCodecDetails(int fd, const sp<IMediaCodecList> &codecList, bool queryDecoders) {
272 const size_t SIZE = 256;
273 char buffer[SIZE];
274 String8 result;
275
276 const char *codecType = queryDecoders? "Decoder" : "Encoder";
277 snprintf(buffer, SIZE - 1, "\n%s infos by media types:\n"
278 "=============================\n", codecType);
279 result.append(buffer);
280
281 size_t numCodecs = codecList->countCodecs();
282
283 // gather all media types supported by codec class, and link to codecs that support them
284 KeyedVector<AString, Vector<sp<MediaCodecInfo>>> allMediaTypes;
285 for (size_t codec_ix = 0; codec_ix < numCodecs; ++codec_ix) {
286 sp<MediaCodecInfo> info = codecList->getCodecInfo(codec_ix);
287 if (info->isEncoder() == !queryDecoders) {
288 Vector<AString> supportedMediaTypes;
289 info->getSupportedMediaTypes(&supportedMediaTypes);
290 if (!supportedMediaTypes.size()) {
291 snprintf(buffer, SIZE - 1, "warning: %s does not support any media types\n",
292 info->getCodecName());
293 result.append(buffer);
294 } else {
295 for (const AString &mediaType : supportedMediaTypes) {
296 if (allMediaTypes.indexOfKey(mediaType) < 0) {
297 allMediaTypes.add(mediaType, Vector<sp<MediaCodecInfo>>());
298 }
299 allMediaTypes.editValueFor(mediaType).add(info);
300 }
301 }
302 }
303 }
304
305 KeyedVector<AString, bool> visitedCodecs;
306 for (size_t type_ix = 0; type_ix < allMediaTypes.size(); ++type_ix) {
307 const AString &mediaType = allMediaTypes.keyAt(type_ix);
308 snprintf(buffer, SIZE - 1, "\nMedia type '%s':\n", mediaType.c_str());
309 result.append(buffer);
310
311 for (const sp<MediaCodecInfo> &info : allMediaTypes.valueAt(type_ix)) {
312 sp<MediaCodecInfo::Capabilities> caps = info->getCapabilitiesFor(mediaType.c_str());
313 if (caps == NULL) {
314 snprintf(buffer, SIZE - 1, "warning: %s does not have capabilities for type %s\n",
315 info->getCodecName(), mediaType.c_str());
316 result.append(buffer);
317 continue;
318 }
319 snprintf(buffer, SIZE - 1, " %s \"%s\" supports\n",
320 codecType, info->getCodecName());
321 result.append(buffer);
322
323 auto printList = [&](const char *type, const Vector<AString> &values){
324 snprintf(buffer, SIZE - 1, " %s: [", type);
325 result.append(buffer);
326 for (size_t j = 0; j < values.size(); ++j) {
327 snprintf(buffer, SIZE - 1, "\n %s%s", values[j].c_str(),
328 j == values.size() - 1 ? " " : ",");
329 result.append(buffer);
330 }
331 result.append("]\n");
332 };
333
334 if (visitedCodecs.indexOfKey(info->getCodecName()) < 0) {
335 visitedCodecs.add(info->getCodecName(), true);
336 {
337 Vector<AString> aliases;
338 info->getAliases(&aliases);
339 // quote alias
340 for (AString &alias : aliases) {
341 alias.insert("\"", 1, 0);
342 alias.append('"');
343 }
344 printList("aliases", aliases);
345 }
346 {
347 uint32_t attrs = info->getAttributes();
348 Vector<AString> list;
349 list.add(AStringPrintf("encoder: %d",
350 !!(attrs & MediaCodecInfo::kFlagIsEncoder)));
351 list.add(AStringPrintf("vendor: %d",
352 !!(attrs & MediaCodecInfo::kFlagIsVendor)));
353 list.add(AStringPrintf("software-only: %d",
354 !!(attrs & MediaCodecInfo::kFlagIsSoftwareOnly)));
355 list.add(AStringPrintf("hw-accelerated: %d",
356 !!(attrs & MediaCodecInfo::kFlagIsHardwareAccelerated)));
357 printList(AStringPrintf("attributes: %#x", attrs).c_str(), list);
358 }
359
360 snprintf(buffer, SIZE - 1, " owner: \"%s\"\n", info->getOwnerName());
361 result.append(buffer);
362 snprintf(buffer, SIZE - 1, " rank: %u\n", info->getRank());
363 result.append(buffer);
364 } else {
365 result.append(" aliases, attributes, owner, rank: see above\n");
366 }
367
368 {
369 Vector<AString> list;
370 Vector<MediaCodecInfo::ProfileLevel> profileLevels;
371 caps->getSupportedProfileLevels(&profileLevels);
372 for (const MediaCodecInfo::ProfileLevel &pl : profileLevels) {
373 const char *niceProfile =
374 mediaType.equalsIgnoreCase(MIMETYPE_AUDIO_AAC)
375 ? asString_AACObject(pl.mProfile) :
376 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_MPEG2)
377 ? asString_MPEG2Profile(pl.mProfile) :
378 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_H263)
379 ? asString_H263Profile(pl.mProfile) :
380 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_MPEG4)
381 ? asString_MPEG4Profile(pl.mProfile) :
382 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_AVC)
383 ? asString_AVCProfile(pl.mProfile) :
384 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_VP8)
385 ? asString_VP8Profile(pl.mProfile) :
386 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_HEVC)
387 ? asString_HEVCProfile(pl.mProfile) :
388 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_VP9)
389 ? asString_VP9Profile(pl.mProfile) :
390 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_AV1)
391 ? asString_AV1Profile(pl.mProfile) : "??";
392 const char *niceLevel =
393 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_MPEG2)
394 ? asString_MPEG2Level(pl.mLevel) :
395 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_H263)
396 ? asString_H263Level(pl.mLevel) :
397 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_MPEG4)
398 ? asString_MPEG4Level(pl.mLevel) :
399 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_AVC)
400 ? asString_AVCLevel(pl.mLevel) :
401 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_VP8)
402 ? asString_VP8Level(pl.mLevel) :
403 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_HEVC)
404 ? asString_HEVCTierLevel(pl.mLevel) :
405 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_VP9)
406 ? asString_VP9Level(pl.mLevel) :
407 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_AV1)
408 ? asString_AV1Level(pl.mLevel) : "??";
409
410 list.add(AStringPrintf("% 5u/% 5u (%s/%s)",
411 pl.mProfile, pl.mLevel, niceProfile, niceLevel));
412 }
413 printList("profile/levels", list);
414 }
415
416 {
417 Vector<AString> list;
418 Vector<uint32_t> colors;
419 caps->getSupportedColorFormats(&colors);
420 for (uint32_t color : colors) {
421 list.add(AStringPrintf("%#x (%s)", color,
422 asString_ColorFormat((int32_t)color)));
423 }
424 printList("colors", list);
425 }
426
Wonsik Kimd579f3e2019-10-07 14:14:09 -0700427 result.append(" details: ");
428 result.append(caps->getDetails()->debugString(6).c_str());
429 result.append("\n");
Wonsik Kim6f675772019-08-20 17:06:53 -0700430 }
431 }
432 result.append("\n");
433 ::write(fd, result.string(), result.size());
434}
435
436
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800437// 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 -0800438/* static */ int MediaPlayerService::AudioOutput::mMinBufferCount = 4;
439/* static */ bool MediaPlayerService::AudioOutput::mIsOnEmulator = false;
440
441void MediaPlayerService::instantiate() {
442 defaultServiceManager()->addService(
443 String16("media.player"), new MediaPlayerService());
444}
445
446MediaPlayerService::MediaPlayerService()
447{
Steve Block3856b092011-10-20 11:56:00 +0100448 ALOGV("MediaPlayerService created");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800449 mNextConnId = 1;
Gloria Wang9ee159b2011-02-24 14:51:45 -0800450
John Grossman44a7e422012-06-21 17:29:24 -0700451 MediaPlayerFactory::registerBuiltinFactories();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800452}
453
454MediaPlayerService::~MediaPlayerService()
455{
Steve Block3856b092011-10-20 11:56:00 +0100456 ALOGV("MediaPlayerService destroyed");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800457}
458
Svet Ganov33761132021-05-13 22:51:08 +0000459sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(
460 const AttributionSourceState& attributionSource)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800461{
Svet Ganov33761132021-05-13 22:51:08 +0000462 // TODO b/182392769: use attribution source util
463 AttributionSourceState verifiedAttributionSource = attributionSource;
464 verifiedAttributionSource.uid = VALUE_OR_FATAL(
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700465 legacy2aidl_uid_t_int32_t(IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +0000466 verifiedAttributionSource.pid = VALUE_OR_FATAL(
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700467 legacy2aidl_pid_t_int32_t(IPCThreadState::self()->getCallingPid()));
468 sp<MediaRecorderClient> recorder =
Svet Ganov33761132021-05-13 22:51:08 +0000469 new MediaRecorderClient(this, verifiedAttributionSource);
Gloria Wangdac6a312009-10-29 15:46:37 -0700470 wp<MediaRecorderClient> w = recorder;
471 Mutex::Autolock lock(mLock);
472 mMediaRecorderClients.add(w);
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700473 ALOGV("Create new media recorder client from pid %s",
Svet Ganov33761132021-05-13 22:51:08 +0000474 verifiedAttributionSource.toString().c_str());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800475 return recorder;
476}
477
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -0700478void MediaPlayerService::removeMediaRecorderClient(const wp<MediaRecorderClient>& client)
Gloria Wangdac6a312009-10-29 15:46:37 -0700479{
480 Mutex::Autolock lock(mLock);
481 mMediaRecorderClients.remove(client);
Steve Block3856b092011-10-20 11:56:00 +0100482 ALOGV("Delete media recorder client");
Gloria Wangdac6a312009-10-29 15:46:37 -0700483}
484
Glenn Kastenf37971f2012-02-03 11:06:53 -0800485sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800486{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800487 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800488 sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
Steve Block3856b092011-10-20 11:56:00 +0100489 ALOGV("Create new media retriever from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800490 return retriever;
491}
492
Glenn Kastenf37971f2012-02-03 11:06:53 -0800493sp<IMediaPlayer> MediaPlayerService::create(const sp<IMediaPlayerClient>& client,
Svet Ganov33761132021-05-13 22:51:08 +0000494 audio_session_t audioSessionId, const AttributionSourceState& attributionSource)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800495{
496 int32_t connId = android_atomic_inc(&mNextConnId);
Svet Ganov33761132021-05-13 22:51:08 +0000497 // TODO b/182392769: use attribution source util
498 AttributionSourceState verifiedAttributionSource = attributionSource;
499 verifiedAttributionSource.pid = VALUE_OR_FATAL(
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700500 legacy2aidl_pid_t_int32_t(IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +0000501 verifiedAttributionSource.uid = VALUE_OR_FATAL(
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700502 legacy2aidl_uid_t_int32_t(IPCThreadState::self()->getCallingUid()));
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700503
504 sp<Client> c = new Client(
Svet Ganov33761132021-05-13 22:51:08 +0000505 this, verifiedAttributionSource, connId, client, audioSessionId);
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700506
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700507 ALOGV("Create new client(%d) from %s, ", connId,
Svet Ganov33761132021-05-13 22:51:08 +0000508 verifiedAttributionSource.toString().c_str());
Dave Burked681bbb2011-08-30 14:39:17 +0100509
510 wp<Client> w = c;
511 {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800512 Mutex::Autolock lock(mLock);
513 mClients.add(w);
514 }
Andreas Hubere2b10282010-11-23 11:41:34 -0800515 return c;
516}
517
Lajos Molnar1381d4b2014-08-07 15:18:35 -0700518sp<IMediaCodecList> MediaPlayerService::getCodecList() const {
519 return MediaCodecList::getLocalInstance();
520}
521
Jeff Brown2013a542012-09-04 21:38:42 -0700522sp<IRemoteDisplay> MediaPlayerService::listenForRemoteDisplay(
Chong Zhangd0a98fa2017-09-14 17:43:10 -0700523 const String16 &/*opPackageName*/,
524 const sp<IRemoteDisplayClient>& /*client*/,
525 const String8& /*iface*/) {
526 ALOGE("listenForRemoteDisplay is no longer supported!");
Jeff Brownaba33d52012-09-07 17:38:58 -0700527
Chong Zhangd0a98fa2017-09-14 17:43:10 -0700528 return NULL;
Jeff Brown2013a542012-09-04 21:38:42 -0700529}
530
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800531status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
532{
533 const size_t SIZE = 256;
534 char buffer[SIZE];
535 String8 result;
536
537 result.append(" AudioOutput\n");
538 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n",
539 mStreamType, mLeftVolume, mRightVolume);
540 result.append(buffer);
541 snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n",
Eric Laurentdb354e52012-03-05 17:27:11 -0800542 mMsecsPerFrame, (mTrack != 0) ? mTrack->latency() : -1);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800543 result.append(buffer);
Eric Laurent2beeb502010-07-16 07:43:46 -0700544 snprintf(buffer, 255, " aux effect id(%d), send level (%f)\n",
545 mAuxEffectId, mSendLevel);
546 result.append(buffer);
547
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800548 ::write(fd, result.string(), result.size());
549 if (mTrack != 0) {
550 mTrack->dump(fd, args);
551 }
552 return NO_ERROR;
553}
554
Lajos Molnar6d339f12015-04-17 16:15:53 -0700555status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800556{
557 const size_t SIZE = 256;
558 char buffer[SIZE];
559 String8 result;
560 result.append(" Client\n");
Svet Ganov33761132021-05-13 22:51:08 +0000561 snprintf(buffer, 255, " AttributionSource(%s), connId(%d), status(%d), looping(%s)\n",
562 mAttributionSource.toString().c_str(), mConnId, mStatus, mLoop?"true": "false");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800563 result.append(buffer);
Wei Jia502c2f42017-07-13 17:47:56 -0700564
565 sp<MediaPlayerBase> p;
566 sp<AudioOutput> audioOutput;
567 bool locked = false;
568 for (int i = 0; i < kDumpLockRetries; ++i) {
569 if (mLock.tryLock() == NO_ERROR) {
570 locked = true;
571 break;
572 }
573 usleep(kDumpLockSleepUs);
Andreas Hubera0b1d4b2011-06-07 15:52:25 -0700574 }
Wei Jia502c2f42017-07-13 17:47:56 -0700575
576 if (locked) {
577 p = mPlayer;
578 audioOutput = mAudioOutput;
579 mLock.unlock();
580 } else {
581 result.append(" lock is taken, no dump from player and audio output\n");
582 }
583 write(fd, result.string(), result.size());
584
585 if (p != NULL) {
586 p->dump(fd, args);
587 }
588 if (audioOutput != 0) {
589 audioOutput->dump(fd, args);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800590 }
591 write(fd, "\n", 1);
592 return NO_ERROR;
593}
594
Marco Nelissenf09611f2015-02-13 14:12:42 -0800595/**
596 * The only arguments this understands right now are -c, -von and -voff,
597 * which are parsed by ALooperRoster::dump()
598 */
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800599status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
600{
601 const size_t SIZE = 256;
602 char buffer[SIZE];
603 String8 result;
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530604 SortedVector< sp<Client> > clients; //to serialise the mutex unlock & client destruction.
605 SortedVector< sp<MediaRecorderClient> > mediaRecorderClients;
606
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800607 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
Wonsik Kim6f675772019-08-20 17:06:53 -0700608 snprintf(buffer, SIZE - 1, "Permission Denial: "
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800609 "can't dump MediaPlayerService from pid=%d, uid=%d\n",
610 IPCThreadState::self()->getCallingPid(),
611 IPCThreadState::self()->getCallingUid());
612 result.append(buffer);
613 } else {
Lajos Molnara42e6cc2022-05-17 15:13:31 -0700614 {
615 // capture clients under lock
616 Mutex::Autolock lock(mLock);
617 for (int i = 0, n = mClients.size(); i < n; ++i) {
618 sp<Client> c = mClients[i].promote();
619 if (c != nullptr) {
620 clients.add(c);
621 }
622 }
623
James Dongb9141222010-07-08 11:16:11 -0700624 for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
625 sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
Lajos Molnara42e6cc2022-05-17 15:13:31 -0700626 if (c != nullptr) {
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530627 mediaRecorderClients.add(c);
James Donge579e282011-10-18 22:29:20 -0700628 }
James Dongb9141222010-07-08 11:16:11 -0700629 }
Gloria Wangdac6a312009-10-29 15:46:37 -0700630 }
631
Lajos Molnara42e6cc2022-05-17 15:13:31 -0700632 // dump clients outside of lock
633 for (const sp<Client> &c : clients) {
634 c->dump(fd, args);
635 }
636 if (mediaRecorderClients.size() == 0) {
637 result.append(" No media recorder client\n\n");
638 } else {
639 for (const sp<MediaRecorderClient> &c : mediaRecorderClients) {
640 snprintf(buffer, 255, " MediaRecorderClient pid(%d)\n",
641 c->mAttributionSource.pid);
642 result.append(buffer);
643 write(fd, result.string(), result.size());
644 result = "\n";
645 c->dump(fd, args);
646
647 }
648 }
649
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800650 result.append(" Files opened and/or mapped:\n");
Wonsik Kim6f675772019-08-20 17:06:53 -0700651 snprintf(buffer, SIZE - 1, "/proc/%d/maps", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800652 FILE *f = fopen(buffer, "r");
653 if (f) {
654 while (!feof(f)) {
Wonsik Kim6f675772019-08-20 17:06:53 -0700655 fgets(buffer, SIZE - 1, f);
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700656 if (strstr(buffer, " /storage/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800657 strstr(buffer, " /system/sounds/") ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700658 strstr(buffer, " /data/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800659 strstr(buffer, " /system/media/")) {
660 result.append(" ");
661 result.append(buffer);
662 }
663 }
664 fclose(f);
665 } else {
666 result.append("couldn't open ");
667 result.append(buffer);
668 result.append("\n");
669 }
670
Wonsik Kim6f675772019-08-20 17:06:53 -0700671 snprintf(buffer, SIZE - 1, "/proc/%d/fd", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800672 DIR *d = opendir(buffer);
673 if (d) {
674 struct dirent *ent;
675 while((ent = readdir(d)) != NULL) {
676 if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
Wonsik Kim6f675772019-08-20 17:06:53 -0700677 snprintf(buffer, SIZE - 1, "/proc/%d/fd/%s", getpid(), ent->d_name);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800678 struct stat s;
679 if (lstat(buffer, &s) == 0) {
680 if ((s.st_mode & S_IFMT) == S_IFLNK) {
681 char linkto[256];
682 int len = readlink(buffer, linkto, sizeof(linkto));
683 if(len > 0) {
684 if(len > 255) {
685 linkto[252] = '.';
686 linkto[253] = '.';
687 linkto[254] = '.';
688 linkto[255] = 0;
689 } else {
690 linkto[len] = 0;
691 }
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700692 if (strstr(linkto, "/storage/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800693 strstr(linkto, "/system/sounds/") == linkto ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700694 strstr(linkto, "/data/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800695 strstr(linkto, "/system/media/") == linkto) {
696 result.append(" ");
697 result.append(buffer);
698 result.append(" -> ");
699 result.append(linkto);
700 result.append("\n");
701 }
702 }
703 } else {
704 result.append(" unexpected type for ");
705 result.append(buffer);
706 result.append("\n");
707 }
708 }
709 }
710 }
711 closedir(d);
712 } else {
713 result.append("couldn't open ");
714 result.append(buffer);
715 result.append("\n");
716 }
717
Marco Nelissenf09611f2015-02-13 14:12:42 -0800718 gLooperRoster.dump(fd, args);
719
Wonsik Kimd579f3e2019-10-07 14:14:09 -0700720 sp<IMediaCodecList> codecList = getCodecList();
721 dumpCodecDetails(fd, codecList, true /* decoders */);
722 dumpCodecDetails(fd, codecList, false /* !decoders */);
723
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800724 bool dumpMem = false;
Andy Hung53541292016-04-13 16:48:51 -0700725 bool unreachableMemory = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800726 for (size_t i = 0; i < args.size(); i++) {
727 if (args[i] == String16("-m")) {
728 dumpMem = true;
Andy Hung53541292016-04-13 16:48:51 -0700729 } else if (args[i] == String16("--unreachable")) {
730 unreachableMemory = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800731 }
732 }
733 if (dumpMem) {
Andy Hung07b745e2016-05-23 16:21:07 -0700734 result.append("\nDumping memory:\n");
735 std::string s = dumpMemoryAddresses(100 /* limit */);
736 result.append(s.c_str(), s.size());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800737 }
Andy Hung53541292016-04-13 16:48:51 -0700738 if (unreachableMemory) {
739 result.append("\nDumping unreachable memory:\n");
740 // TODO - should limit be an argument parameter?
741 std::string s = GetUnreachableMemoryString(true /* contents */, 10000 /* limit */);
742 result.append(s.c_str(), s.size());
743 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800744 }
745 write(fd, result.string(), result.size());
Wonsik Kim6f675772019-08-20 17:06:53 -0700746
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800747 return NO_ERROR;
748}
749
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -0700750void MediaPlayerService::removeClient(const wp<Client>& client)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800751{
752 Mutex::Autolock lock(mLock);
753 mClients.remove(client);
754}
755
Robert Shihee0a0e32016-08-16 16:50:54 -0700756bool MediaPlayerService::hasClient(wp<Client> client)
757{
758 Mutex::Autolock lock(mLock);
759 return mClients.indexOf(client) != NAME_NOT_FOUND;
760}
761
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700762MediaPlayerService::Client::Client(
Svet Ganov33761132021-05-13 22:51:08 +0000763 const sp<MediaPlayerService>& service, const AttributionSourceState& attributionSource,
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700764 int32_t connId, const sp<IMediaPlayerClient>& client,
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700765 audio_session_t audioSessionId)
Svet Ganov33761132021-05-13 22:51:08 +0000766 : mAttributionSource(attributionSource)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800767{
Steve Block3856b092011-10-20 11:56:00 +0100768 ALOGV("Client(%d) constructor", connId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800769 mConnId = connId;
770 mService = service;
771 mClient = client;
772 mLoop = false;
773 mStatus = NO_INIT;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700774 mAudioSessionId = audioSessionId;
John Grossmanc795b642012-02-22 15:38:35 -0800775 mRetransmitEndpointValid = false;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700776 mAudioAttributes = NULL;
Pawin Vongmasa082e4f72017-12-17 02:31:18 -0800777 mListener = new Listener(this);
Eric Laurenta514bdb2010-06-21 09:27:30 -0700778
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800779#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000780 ALOGD("create Antagonizer");
Pawin Vongmasa082e4f72017-12-17 02:31:18 -0800781 mAntagonizer = new Antagonizer(mListener);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800782#endif
783}
784
785MediaPlayerService::Client::~Client()
786{
Svet Ganov33761132021-05-13 22:51:08 +0000787 ALOGV("Client(%d) destructor AttributionSource = %s", mConnId,
788 mAttributionSource.toString().c_str());
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700789 mAudioOutput.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800790 wp<Client> client(this);
791 disconnect();
792 mService->removeClient(client);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700793 if (mAudioAttributes != NULL) {
794 free(mAudioAttributes);
795 }
jiabin156c6872017-10-06 09:47:15 -0700796 mAudioDeviceUpdatedListener.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800797}
798
799void MediaPlayerService::Client::disconnect()
800{
Svet Ganov33761132021-05-13 22:51:08 +0000801 ALOGV("disconnect(%d) from AttributionSource %s", mConnId,
802 mAttributionSource.toString().c_str());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800803 // grab local reference and clear main reference to prevent future
804 // access to object
805 sp<MediaPlayerBase> p;
806 {
807 Mutex::Autolock l(mLock);
808 p = mPlayer;
beanzdcfefde2012-11-05 09:51:43 +0800809 mClient.clear();
Wei Jia502c2f42017-07-13 17:47:56 -0700810 mPlayer.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800811 }
Andreas Huber20111aa2009-07-14 16:56:47 -0700812
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800813 // clear the notification to prevent callbacks to dead client
814 // and reset the player. We assume the player will serialize
815 // access to itself if necessary.
816 if (p != 0) {
Pawin Vongmasa082e4f72017-12-17 02:31:18 -0800817 p->setNotifyCallback(0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800818#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000819 ALOGD("kill Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800820 mAntagonizer->kill();
821#endif
822 p->reset();
823 }
824
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700825 {
826 Mutex::Autolock l(mLock);
827 disconnectNativeWindow_l();
828 }
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700829
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800830 IPCThreadState::self()->flushCommands();
831}
832
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800833sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
834{
835 // determine if we have the right player type
Wei Jia502c2f42017-07-13 17:47:56 -0700836 sp<MediaPlayerBase> p = getPlayer();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800837 if ((p != NULL) && (p->playerType() != playerType)) {
Steve Block3856b092011-10-20 11:56:00 +0100838 ALOGV("delete player");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800839 p.clear();
840 }
841 if (p == NULL) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700842 p = MediaPlayerFactory::createPlayer(playerType, mListener,
Svet Ganov33761132021-05-13 22:51:08 +0000843 VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(mAttributionSource.pid)));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800844 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700845
Jason Simmonsdb29e522011-08-12 13:46:55 -0700846 if (p != NULL) {
Svet Ganov33761132021-05-13 22:51:08 +0000847 p->setUID(VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(mAttributionSource.uid)));
Jason Simmonsdb29e522011-08-12 13:46:55 -0700848 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700849
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800850 return p;
851}
852
jiabin156c6872017-10-06 09:47:15 -0700853void MediaPlayerService::Client::AudioDeviceUpdatedNotifier::onAudioDeviceUpdate(
854 audio_io_handle_t audioIo,
855 audio_port_handle_t deviceId) {
856 sp<MediaPlayerBase> listener = mListener.promote();
857 if (listener != NULL) {
858 listener->sendEvent(MEDIA_AUDIO_ROUTING_CHANGED, audioIo, deviceId);
859 } else {
860 ALOGW("listener for process %d death is gone", MEDIA_AUDIO_ROUTING_CHANGED);
861 }
862}
863
John Grossmanc795b642012-02-22 15:38:35 -0800864sp<MediaPlayerBase> MediaPlayerService::Client::setDataSource_pre(
865 player_type playerType)
866{
867 ALOGV("player type = %d", playerType);
868
869 // create the right type of player
870 sp<MediaPlayerBase> p = createPlayer(playerType);
871 if (p == NULL) {
872 return p;
873 }
874
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700875 std::vector<DeathNotifier> deathNotifiers;
876
877 // Listen to death of media.extractor service
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700878 sp<IServiceManager> sm = defaultServiceManager();
879 sp<IBinder> binder = sm->getService(String16("media.extractor"));
Marco Nelissen1b5a7ee2016-09-30 13:54:30 -0700880 if (binder == NULL) {
881 ALOGE("extractor service not available");
882 return NULL;
883 }
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700884 deathNotifiers.emplace_back(
885 binder, [l = wp<MediaPlayerBase>(p)]() {
886 sp<MediaPlayerBase> listener = l.promote();
887 if (listener) {
888 ALOGI("media.extractor died. Sending death notification.");
889 listener->sendEvent(MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED,
890 MEDIAEXTRACTOR_PROCESS_DEATH);
891 } else {
892 ALOGW("media.extractor died without a death handler.");
893 }
894 });
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700895
Marco Nelissena0c98412019-03-29 12:10:19 -0700896 {
897 using ::android::hidl::base::V1_0::IBase;
898
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700899 // Listen to death of OMX service
Marco Nelissena0c98412019-03-29 12:10:19 -0700900 {
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700901 sp<IBase> base = ::android::hardware::media::omx::V1_0::
902 IOmx::getService();
903 if (base == nullptr) {
Marco Nelissena0c98412019-03-29 12:10:19 -0700904 ALOGD("OMX service is not available");
905 } else {
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700906 deathNotifiers.emplace_back(
907 base, [l = wp<MediaPlayerBase>(p)]() {
908 sp<MediaPlayerBase> listener = l.promote();
909 if (listener) {
910 ALOGI("OMX service died. "
911 "Sending death notification.");
912 listener->sendEvent(
913 MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED,
914 MEDIACODEC_PROCESS_DEATH);
915 } else {
916 ALOGW("OMX service died without a death handler.");
917 }
918 });
Marco Nelissena0c98412019-03-29 12:10:19 -0700919 }
920 }
921
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700922 // Listen to death of Codec2 services
Marco Nelissena0c98412019-03-29 12:10:19 -0700923 {
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700924 for (std::shared_ptr<Codec2Client> const& client :
925 Codec2Client::CreateFromAllServices()) {
926 sp<IBase> base = client->getBase();
927 deathNotifiers.emplace_back(
928 base, [l = wp<MediaPlayerBase>(p),
929 name = std::string(client->getServiceName())]() {
930 sp<MediaPlayerBase> listener = l.promote();
931 if (listener) {
932 ALOGI("Codec2 service \"%s\" died. "
933 "Sending death notification.",
934 name.c_str());
935 listener->sendEvent(
936 MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED,
937 MEDIACODEC_PROCESS_DEATH);
938 } else {
939 ALOGW("Codec2 service \"%s\" died "
940 "without a death handler.",
941 name.c_str());
942 }
943 });
Marco Nelissene4da6c62019-04-01 15:01:41 -0700944 }
Marco Nelissena0c98412019-03-29 12:10:19 -0700945 }
Marco Nelissen1b5a7ee2016-09-30 13:54:30 -0700946 }
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700947
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700948 Mutex::Autolock lock(mLock);
949
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700950 mDeathNotifiers.clear();
951 mDeathNotifiers.swap(deathNotifiers);
jiabin156c6872017-10-06 09:47:15 -0700952 mAudioDeviceUpdatedListener = new AudioDeviceUpdatedNotifier(p);
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700953
John Grossmanc795b642012-02-22 15:38:35 -0800954 if (!p->hardwareOutput()) {
Svet Ganov33761132021-05-13 22:51:08 +0000955 mAudioOutput = new AudioOutput(mAudioSessionId, mAttributionSource,
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700956 mAudioAttributes, mAudioDeviceUpdatedListener);
John Grossmanc795b642012-02-22 15:38:35 -0800957 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
958 }
959
960 return p;
961}
962
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700963status_t MediaPlayerService::Client::setDataSource_post(
John Grossmanc795b642012-02-22 15:38:35 -0800964 const sp<MediaPlayerBase>& p,
965 status_t status)
966{
967 ALOGV(" setDataSource");
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700968 if (status != OK) {
969 ALOGE(" error: %d", status);
970 return status;
John Grossmanc795b642012-02-22 15:38:35 -0800971 }
972
973 // Set the re-transmission endpoint if one was chosen.
974 if (mRetransmitEndpointValid) {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700975 status = p->setRetransmitEndpoint(&mRetransmitEndpoint);
976 if (status != NO_ERROR) {
977 ALOGE("setRetransmitEndpoint error: %d", status);
John Grossmanc795b642012-02-22 15:38:35 -0800978 }
979 }
980
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700981 if (status == OK) {
982 Mutex::Autolock lock(mLock);
John Grossmanc795b642012-02-22 15:38:35 -0800983 mPlayer = p;
984 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700985 return status;
John Grossmanc795b642012-02-22 15:38:35 -0800986}
987
Andreas Huber2db84552010-01-28 11:19:57 -0800988status_t MediaPlayerService::Client::setDataSource(
Andreas Huber1b86fe02014-01-29 11:13:26 -0800989 const sp<IMediaHTTPService> &httpService,
990 const char *url,
991 const KeyedVector<String8, String8> *headers)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800992{
Steve Block3856b092011-10-20 11:56:00 +0100993 ALOGV("setDataSource(%s)", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800994 if (url == NULL)
995 return UNKNOWN_ERROR;
996
Dave Burked681bbb2011-08-30 14:39:17 +0100997 if ((strncmp(url, "http://", 7) == 0) ||
998 (strncmp(url, "https://", 8) == 0) ||
999 (strncmp(url, "rtsp://", 7) == 0)) {
1000 if (!checkPermission("android.permission.INTERNET")) {
1001 return PERMISSION_DENIED;
1002 }
1003 }
1004
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001005 if (strncmp(url, "content://", 10) == 0) {
1006 // get a filedescriptor for the content Uri and
1007 // pass it to the setDataSource(fd) method
1008
1009 String16 url16(url);
1010 int fd = android::openContentProviderFile(url16);
1011 if (fd < 0)
1012 {
Steve Block29357bc2012-01-06 19:20:56 +00001013 ALOGE("Couldn't open fd for %s", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001014 return UNKNOWN_ERROR;
1015 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001016 status_t status = setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001017 close(fd);
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001018 return mStatus = status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001019 } else {
John Grossman44a7e422012-06-21 17:29:24 -07001020 player_type playerType = MediaPlayerFactory::getPlayerType(this, url);
John Grossmanc795b642012-02-22 15:38:35 -08001021 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
1022 if (p == NULL) {
1023 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001024 }
1025
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001026 return mStatus =
1027 setDataSource_post(
1028 p, p->setDataSource(httpService, url, headers));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001029 }
1030}
1031
1032status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
1033{
Marco Nelissen83b0fd92015-09-16 13:48:07 -07001034 ALOGV("setDataSource fd=%d (%s), offset=%lld, length=%lld",
1035 fd, nameForFd(fd).c_str(), (long long) offset, (long long) length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001036 struct stat sb;
1037 int ret = fstat(fd, &sb);
1038 if (ret != 0) {
Steve Block29357bc2012-01-06 19:20:56 +00001039 ALOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001040 return UNKNOWN_ERROR;
1041 }
1042
Andy Hung833b4752016-04-04 17:15:48 -07001043 ALOGV("st_dev = %llu", static_cast<unsigned long long>(sb.st_dev));
Steve Block3856b092011-10-20 11:56:00 +01001044 ALOGV("st_mode = %u", sb.st_mode);
Mark Salyzyn77342f72014-06-18 16:31:32 -07001045 ALOGV("st_uid = %lu", static_cast<unsigned long>(sb.st_uid));
1046 ALOGV("st_gid = %lu", static_cast<unsigned long>(sb.st_gid));
Andy Hung833b4752016-04-04 17:15:48 -07001047 ALOGV("st_size = %llu", static_cast<unsigned long long>(sb.st_size));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001048
1049 if (offset >= sb.st_size) {
Steve Block29357bc2012-01-06 19:20:56 +00001050 ALOGE("offset error");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001051 return UNKNOWN_ERROR;
1052 }
1053 if (offset + length > sb.st_size) {
1054 length = sb.st_size - offset;
Andy Hung833b4752016-04-04 17:15:48 -07001055 ALOGV("calculated length = %lld", (long long)length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001056 }
1057
John Grossman44a7e422012-06-21 17:29:24 -07001058 player_type playerType = MediaPlayerFactory::getPlayerType(this,
1059 fd,
1060 offset,
1061 length);
John Grossmanc795b642012-02-22 15:38:35 -08001062 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
1063 if (p == NULL) {
1064 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001065 }
1066
1067 // now set data source
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001068 return mStatus = setDataSource_post(p, p->setDataSource(fd, offset, length));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001069}
1070
Andreas Hubere2b10282010-11-23 11:41:34 -08001071status_t MediaPlayerService::Client::setDataSource(
1072 const sp<IStreamSource> &source) {
1073 // create the right type of player
John Grossman44a7e422012-06-21 17:29:24 -07001074 player_type playerType = MediaPlayerFactory::getPlayerType(this, source);
John Grossmanc795b642012-02-22 15:38:35 -08001075 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
Andreas Hubere2b10282010-11-23 11:41:34 -08001076 if (p == NULL) {
1077 return NO_INIT;
1078 }
1079
Andreas Hubere2b10282010-11-23 11:41:34 -08001080 // now set data source
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001081 return mStatus = setDataSource_post(p, p->setDataSource(source));
Andreas Hubere2b10282010-11-23 11:41:34 -08001082}
1083
Chris Watkins99f31602015-03-20 13:06:33 -07001084status_t MediaPlayerService::Client::setDataSource(
1085 const sp<IDataSource> &source) {
Dongwon Kangd91dc5a2017-10-10 00:07:09 -07001086 sp<DataSource> dataSource = CreateDataSourceFromIDataSource(source);
Chris Watkins99f31602015-03-20 13:06:33 -07001087 player_type playerType = MediaPlayerFactory::getPlayerType(this, dataSource);
1088 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
1089 if (p == NULL) {
1090 return NO_INIT;
1091 }
1092 // now set data source
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001093 return mStatus = setDataSource_post(p, p->setDataSource(dataSource));
Chris Watkins99f31602015-03-20 13:06:33 -07001094}
1095
Byeongjo Park28225ab2019-01-24 20:31:19 +09001096status_t MediaPlayerService::Client::setDataSource(
1097 const String8& rtpParams) {
1098 player_type playerType = NU_PLAYER;
1099 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
1100 if (p == NULL) {
1101 return NO_INIT;
1102 }
1103 // now set data source
1104 return mStatus = setDataSource_post(p, p->setDataSource(rtpParams));
1105}
1106
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001107void MediaPlayerService::Client::disconnectNativeWindow_l() {
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001108 if (mConnectedWindow != NULL) {
Chong Zhang181fd9b2017-02-16 15:53:03 -08001109 status_t err = nativeWindowDisconnect(
1110 mConnectedWindow.get(), "disconnectNativeWindow");
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001111
1112 if (err != OK) {
Chong Zhang181fd9b2017-02-16 15:53:03 -08001113 ALOGW("nativeWindowDisconnect returned an error: %s (%d)",
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001114 strerror(-err), err);
1115 }
1116 }
1117 mConnectedWindow.clear();
1118}
1119
Glenn Kasten11731182011-02-08 17:26:17 -08001120status_t MediaPlayerService::Client::setVideoSurfaceTexture(
Andy McFadden484566c2012-12-18 09:46:54 -08001121 const sp<IGraphicBufferProducer>& bufferProducer)
Glenn Kasten11731182011-02-08 17:26:17 -08001122{
Andy McFadden484566c2012-12-18 09:46:54 -08001123 ALOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, bufferProducer.get());
Glenn Kasten11731182011-02-08 17:26:17 -08001124 sp<MediaPlayerBase> p = getPlayer();
1125 if (p == 0) return UNKNOWN_ERROR;
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001126
Marco Nelissenf8880202014-11-14 07:58:25 -08001127 sp<IBinder> binder(IInterface::asBinder(bufferProducer));
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001128 if (mConnectedWindowBinder == binder) {
1129 return OK;
1130 }
1131
1132 sp<ANativeWindow> anw;
Andy McFadden484566c2012-12-18 09:46:54 -08001133 if (bufferProducer != NULL) {
Marco Nelissenee08f7e2013-09-16 13:30:01 -07001134 anw = new Surface(bufferProducer, true /* controlledByApp */);
Chong Zhang181fd9b2017-02-16 15:53:03 -08001135 status_t err = nativeWindowConnect(anw.get(), "setVideoSurfaceTexture");
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001136
1137 if (err != OK) {
Steve Block29357bc2012-01-06 19:20:56 +00001138 ALOGE("setVideoSurfaceTexture failed: %d", err);
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001139 // Note that we must do the reset before disconnecting from the ANW.
1140 // Otherwise queue/dequeue calls could be made on the disconnected
1141 // ANW, which may result in errors.
1142 reset();
1143
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001144 Mutex::Autolock lock(mLock);
1145 disconnectNativeWindow_l();
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001146
1147 return err;
1148 }
1149 }
1150
Andy McFadden484566c2012-12-18 09:46:54 -08001151 // Note that we must set the player's new GraphicBufferProducer before
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001152 // disconnecting the old one. Otherwise queue/dequeue calls could be made
1153 // on the disconnected ANW, which may result in errors.
Andy McFadden484566c2012-12-18 09:46:54 -08001154 status_t err = p->setVideoSurfaceTexture(bufferProducer);
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001155
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001156 mLock.lock();
1157 disconnectNativeWindow_l();
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001158
1159 if (err == OK) {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001160 mConnectedWindow = anw;
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001161 mConnectedWindowBinder = binder;
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001162 mLock.unlock();
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001163 } else {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001164 mLock.unlock();
1165 status_t err = nativeWindowDisconnect(
1166 anw.get(), "disconnectNativeWindow");
1167
1168 if (err != OK) {
1169 ALOGW("nativeWindowDisconnect returned an error: %s (%d)",
1170 strerror(-err), err);
1171 }
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001172 }
1173
1174 return err;
Glenn Kasten11731182011-02-08 17:26:17 -08001175}
1176
Nicolas Catania1d187f12009-05-12 23:25:55 -07001177status_t MediaPlayerService::Client::invoke(const Parcel& request,
1178 Parcel *reply)
1179{
1180 sp<MediaPlayerBase> p = getPlayer();
1181 if (p == NULL) return UNKNOWN_ERROR;
1182 return p->invoke(request, reply);
1183}
1184
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001185// This call doesn't need to access the native player.
1186status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
1187{
1188 status_t status;
nikoa64c8c72009-07-20 15:07:26 -07001189 media::Metadata::Filter allow, drop;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001190
Nicolas Catania48290382009-07-10 13:53:06 -07001191 if (unmarshallFilter(filter, &allow, &status) &&
1192 unmarshallFilter(filter, &drop, &status)) {
1193 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001194
1195 mMetadataAllow = allow;
1196 mMetadataDrop = drop;
1197 }
1198 return status;
1199}
1200
Nicolas Catania48290382009-07-10 13:53:06 -07001201status_t MediaPlayerService::Client::getMetadata(
Mark Salyzyn77342f72014-06-18 16:31:32 -07001202 bool update_only, bool /*apply_filter*/, Parcel *reply)
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001203{
nikoa64c8c72009-07-20 15:07:26 -07001204 sp<MediaPlayerBase> player = getPlayer();
1205 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania48290382009-07-10 13:53:06 -07001206
nikod608a812009-07-16 16:39:53 -07001207 status_t status;
1208 // Placeholder for the return code, updated by the caller.
1209 reply->writeInt32(-1);
1210
nikoa64c8c72009-07-20 15:07:26 -07001211 media::Metadata::Filter ids;
Nicolas Catania48290382009-07-10 13:53:06 -07001212
1213 // We don't block notifications while we fetch the data. We clear
1214 // mMetadataUpdated first so we don't lose notifications happening
1215 // during the rest of this call.
1216 {
1217 Mutex::Autolock lock(mLock);
1218 if (update_only) {
nikod608a812009-07-16 16:39:53 -07001219 ids = mMetadataUpdated;
Nicolas Catania48290382009-07-10 13:53:06 -07001220 }
1221 mMetadataUpdated.clear();
1222 }
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001223
nikoa64c8c72009-07-20 15:07:26 -07001224 media::Metadata metadata(reply);
Nicolas Catania48290382009-07-10 13:53:06 -07001225
nikoa64c8c72009-07-20 15:07:26 -07001226 metadata.appendHeader();
1227 status = player->getMetadata(ids, reply);
nikod608a812009-07-16 16:39:53 -07001228
1229 if (status != OK) {
nikoa64c8c72009-07-20 15:07:26 -07001230 metadata.resetParcel();
Steve Block29357bc2012-01-06 19:20:56 +00001231 ALOGE("getMetadata failed %d", status);
nikod608a812009-07-16 16:39:53 -07001232 return status;
1233 }
1234
1235 // FIXME: Implement filtering on the result. Not critical since
1236 // filtering takes place on the update notifications already. This
1237 // would be when all the metadata are fetch and a filter is set.
1238
nikod608a812009-07-16 16:39:53 -07001239 // Everything is fine, update the metadata length.
nikoa64c8c72009-07-20 15:07:26 -07001240 metadata.updateLength();
nikod608a812009-07-16 16:39:53 -07001241 return OK;
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001242}
1243
Wei Jiad399e7e2016-10-26 15:49:11 -07001244status_t MediaPlayerService::Client::setBufferingSettings(
1245 const BufferingSettings& buffering)
1246{
Wei Jiadc6f3402017-01-09 15:04:18 -08001247 ALOGV("[%d] setBufferingSettings{%s}",
1248 mConnId, buffering.toString().string());
Wei Jiad399e7e2016-10-26 15:49:11 -07001249 sp<MediaPlayerBase> p = getPlayer();
1250 if (p == 0) return UNKNOWN_ERROR;
1251 return p->setBufferingSettings(buffering);
1252}
1253
Wei Jia9bb38032017-03-23 18:00:38 -07001254status_t MediaPlayerService::Client::getBufferingSettings(
Wei Jiad399e7e2016-10-26 15:49:11 -07001255 BufferingSettings* buffering /* nonnull */)
1256{
1257 sp<MediaPlayerBase> p = getPlayer();
1258 // TODO: create mPlayer on demand.
1259 if (p == 0) return UNKNOWN_ERROR;
Wei Jia9bb38032017-03-23 18:00:38 -07001260 status_t ret = p->getBufferingSettings(buffering);
Wei Jiad399e7e2016-10-26 15:49:11 -07001261 if (ret == NO_ERROR) {
Wei Jia9bb38032017-03-23 18:00:38 -07001262 ALOGV("[%d] getBufferingSettings{%s}",
Wei Jiadc6f3402017-01-09 15:04:18 -08001263 mConnId, buffering->toString().string());
Wei Jiad399e7e2016-10-26 15:49:11 -07001264 } else {
Wei Jia9bb38032017-03-23 18:00:38 -07001265 ALOGE("[%d] getBufferingSettings returned %d", mConnId, ret);
Wei Jiad399e7e2016-10-26 15:49:11 -07001266 }
1267 return ret;
1268}
1269
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001270status_t MediaPlayerService::Client::prepareAsync()
1271{
Steve Block3856b092011-10-20 11:56:00 +01001272 ALOGV("[%d] prepareAsync", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001273 sp<MediaPlayerBase> p = getPlayer();
1274 if (p == 0) return UNKNOWN_ERROR;
1275 status_t ret = p->prepareAsync();
1276#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +00001277 ALOGD("start Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001278 if (ret == NO_ERROR) mAntagonizer->start();
1279#endif
1280 return ret;
1281}
1282
1283status_t MediaPlayerService::Client::start()
1284{
Steve Block3856b092011-10-20 11:56:00 +01001285 ALOGV("[%d] start", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001286 sp<MediaPlayerBase> p = getPlayer();
1287 if (p == 0) return UNKNOWN_ERROR;
1288 p->setLooping(mLoop);
1289 return p->start();
1290}
1291
1292status_t MediaPlayerService::Client::stop()
1293{
Steve Block3856b092011-10-20 11:56:00 +01001294 ALOGV("[%d] stop", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001295 sp<MediaPlayerBase> p = getPlayer();
1296 if (p == 0) return UNKNOWN_ERROR;
1297 return p->stop();
1298}
1299
1300status_t MediaPlayerService::Client::pause()
1301{
Steve Block3856b092011-10-20 11:56:00 +01001302 ALOGV("[%d] pause", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001303 sp<MediaPlayerBase> p = getPlayer();
1304 if (p == 0) return UNKNOWN_ERROR;
1305 return p->pause();
1306}
1307
1308status_t MediaPlayerService::Client::isPlaying(bool* state)
1309{
1310 *state = false;
1311 sp<MediaPlayerBase> p = getPlayer();
1312 if (p == 0) return UNKNOWN_ERROR;
1313 *state = p->isPlaying();
Steve Block3856b092011-10-20 11:56:00 +01001314 ALOGV("[%d] isPlaying: %d", mConnId, *state);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001315 return NO_ERROR;
1316}
1317
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001318status_t MediaPlayerService::Client::setPlaybackSettings(const AudioPlaybackRate& rate)
Wei Jia98160162015-02-04 17:01:11 -08001319{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001320 ALOGV("[%d] setPlaybackSettings(%f, %f, %d, %d)",
1321 mConnId, rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Wei Jia98160162015-02-04 17:01:11 -08001322 sp<MediaPlayerBase> p = getPlayer();
1323 if (p == 0) return UNKNOWN_ERROR;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001324 return p->setPlaybackSettings(rate);
1325}
1326
1327status_t MediaPlayerService::Client::getPlaybackSettings(AudioPlaybackRate* rate /* nonnull */)
1328{
1329 sp<MediaPlayerBase> p = getPlayer();
1330 if (p == 0) return UNKNOWN_ERROR;
1331 status_t ret = p->getPlaybackSettings(rate);
1332 if (ret == NO_ERROR) {
1333 ALOGV("[%d] getPlaybackSettings(%f, %f, %d, %d)",
1334 mConnId, rate->mSpeed, rate->mPitch, rate->mFallbackMode, rate->mStretchMode);
1335 } else {
1336 ALOGV("[%d] getPlaybackSettings returned %d", mConnId, ret);
1337 }
1338 return ret;
1339}
1340
1341status_t MediaPlayerService::Client::setSyncSettings(
1342 const AVSyncSettings& sync, float videoFpsHint)
1343{
1344 ALOGV("[%d] setSyncSettings(%u, %u, %f, %f)",
1345 mConnId, sync.mSource, sync.mAudioAdjustMode, sync.mTolerance, videoFpsHint);
1346 sp<MediaPlayerBase> p = getPlayer();
1347 if (p == 0) return UNKNOWN_ERROR;
1348 return p->setSyncSettings(sync, videoFpsHint);
1349}
1350
1351status_t MediaPlayerService::Client::getSyncSettings(
1352 AVSyncSettings* sync /* nonnull */, float* videoFps /* nonnull */)
1353{
1354 sp<MediaPlayerBase> p = getPlayer();
1355 if (p == 0) return UNKNOWN_ERROR;
1356 status_t ret = p->getSyncSettings(sync, videoFps);
1357 if (ret == NO_ERROR) {
1358 ALOGV("[%d] getSyncSettings(%u, %u, %f, %f)",
1359 mConnId, sync->mSource, sync->mAudioAdjustMode, sync->mTolerance, *videoFps);
1360 } else {
1361 ALOGV("[%d] getSyncSettings returned %d", mConnId, ret);
1362 }
1363 return ret;
Wei Jia98160162015-02-04 17:01:11 -08001364}
1365
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001366status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
1367{
Steve Block3856b092011-10-20 11:56:00 +01001368 ALOGV("getCurrentPosition");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001369 sp<MediaPlayerBase> p = getPlayer();
1370 if (p == 0) return UNKNOWN_ERROR;
1371 status_t ret = p->getCurrentPosition(msec);
1372 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001373 ALOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001374 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001375 ALOGE("getCurrentPosition returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001376 }
1377 return ret;
1378}
1379
1380status_t MediaPlayerService::Client::getDuration(int *msec)
1381{
Steve Block3856b092011-10-20 11:56:00 +01001382 ALOGV("getDuration");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001383 sp<MediaPlayerBase> p = getPlayer();
1384 if (p == 0) return UNKNOWN_ERROR;
1385 status_t ret = p->getDuration(msec);
1386 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001387 ALOGV("[%d] getDuration = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001388 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001389 ALOGE("getDuration returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001390 }
1391 return ret;
1392}
1393
Marco Nelissen6b74d672012-02-28 16:07:44 -08001394status_t MediaPlayerService::Client::setNextPlayer(const sp<IMediaPlayer>& player) {
1395 ALOGV("setNextPlayer");
1396 Mutex::Autolock l(mLock);
1397 sp<Client> c = static_cast<Client*>(player.get());
Wei Jia28284122016-08-30 13:49:06 -07001398 if (c != NULL && !mService->hasClient(c)) {
Robert Shihee0a0e32016-08-16 16:50:54 -07001399 return BAD_VALUE;
1400 }
1401
Marco Nelissen6b74d672012-02-28 16:07:44 -08001402 mNextClient = c;
John Grossman5f7e55e2012-08-24 14:47:25 -07001403
1404 if (c != NULL) {
1405 if (mAudioOutput != NULL) {
1406 mAudioOutput->setNextOutput(c->mAudioOutput);
1407 } else if ((mPlayer != NULL) && !mPlayer->hardwareOutput()) {
1408 ALOGE("no current audio output");
1409 }
1410
1411 if ((mPlayer != NULL) && (mNextClient->getPlayer() != NULL)) {
1412 mPlayer->setNextPlayer(mNextClient->getPlayer());
1413 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001414 }
John Grossman5f7e55e2012-08-24 14:47:25 -07001415
Marco Nelissen6b74d672012-02-28 16:07:44 -08001416 return OK;
1417}
1418
Andy Hung9fc8b5c2017-01-24 13:36:48 -08001419VolumeShaper::Status MediaPlayerService::Client::applyVolumeShaper(
1420 const sp<VolumeShaper::Configuration>& configuration,
1421 const sp<VolumeShaper::Operation>& operation) {
1422 // for hardware output, call player instead
1423 ALOGV("Client::applyVolumeShaper(%p)", this);
1424 sp<MediaPlayerBase> p = getPlayer();
1425 {
1426 Mutex::Autolock l(mLock);
1427 if (p != 0 && p->hardwareOutput()) {
1428 // TODO: investigate internal implementation
1429 return VolumeShaper::Status(INVALID_OPERATION);
1430 }
1431 if (mAudioOutput.get() != nullptr) {
1432 return mAudioOutput->applyVolumeShaper(configuration, operation);
1433 }
1434 }
1435 return VolumeShaper::Status(INVALID_OPERATION);
1436}
1437
1438sp<VolumeShaper::State> MediaPlayerService::Client::getVolumeShaperState(int id) {
1439 // for hardware output, call player instead
1440 ALOGV("Client::getVolumeShaperState(%p)", this);
1441 sp<MediaPlayerBase> p = getPlayer();
1442 {
1443 Mutex::Autolock l(mLock);
1444 if (p != 0 && p->hardwareOutput()) {
1445 // TODO: investigate internal implementation.
1446 return nullptr;
1447 }
1448 if (mAudioOutput.get() != nullptr) {
1449 return mAudioOutput->getVolumeShaperState(id);
1450 }
1451 }
1452 return nullptr;
1453}
1454
Wei Jiac5de0912016-11-18 10:22:14 -08001455status_t MediaPlayerService::Client::seekTo(int msec, MediaPlayerSeekMode mode)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001456{
Wei Jiac5de0912016-11-18 10:22:14 -08001457 ALOGV("[%d] seekTo(%d, %d)", mConnId, msec, mode);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001458 sp<MediaPlayerBase> p = getPlayer();
1459 if (p == 0) return UNKNOWN_ERROR;
Wei Jiac5de0912016-11-18 10:22:14 -08001460 return p->seekTo(msec, mode);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001461}
1462
1463status_t MediaPlayerService::Client::reset()
1464{
Steve Block3856b092011-10-20 11:56:00 +01001465 ALOGV("[%d] reset", mConnId);
John Grossmanc795b642012-02-22 15:38:35 -08001466 mRetransmitEndpointValid = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001467 sp<MediaPlayerBase> p = getPlayer();
1468 if (p == 0) return UNKNOWN_ERROR;
1469 return p->reset();
1470}
1471
Wei Jia52c28512017-09-13 18:17:51 -07001472status_t MediaPlayerService::Client::notifyAt(int64_t mediaTimeUs)
1473{
1474 ALOGV("[%d] notifyAt(%lld)", mConnId, (long long)mediaTimeUs);
1475 sp<MediaPlayerBase> p = getPlayer();
1476 if (p == 0) return UNKNOWN_ERROR;
1477 return p->notifyAt(mediaTimeUs);
1478}
1479
Glenn Kastenfff6d712012-01-12 16:38:12 -08001480status_t MediaPlayerService::Client::setAudioStreamType(audio_stream_type_t type)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001481{
Steve Block3856b092011-10-20 11:56:00 +01001482 ALOGV("[%d] setAudioStreamType(%d)", mConnId, type);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001483 // TODO: for hardware output, call player instead
1484 Mutex::Autolock l(mLock);
1485 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1486 return NO_ERROR;
1487}
1488
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001489status_t MediaPlayerService::Client::setAudioAttributes_l(const Parcel &parcel)
1490{
1491 if (mAudioAttributes != NULL) { free(mAudioAttributes); }
1492 mAudioAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001493 if (mAudioAttributes == NULL) {
1494 return NO_MEMORY;
1495 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001496 unmarshallAudioAttributes(parcel, mAudioAttributes);
1497
1498 ALOGV("setAudioAttributes_l() usage=%d content=%d flags=0x%x tags=%s",
1499 mAudioAttributes->usage, mAudioAttributes->content_type, mAudioAttributes->flags,
1500 mAudioAttributes->tags);
1501
1502 if (mAudioOutput != 0) {
1503 mAudioOutput->setAudioAttributes(mAudioAttributes);
1504 }
1505 return NO_ERROR;
1506}
1507
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001508status_t MediaPlayerService::Client::setLooping(int loop)
1509{
Steve Block3856b092011-10-20 11:56:00 +01001510 ALOGV("[%d] setLooping(%d)", mConnId, loop);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001511 mLoop = loop;
1512 sp<MediaPlayerBase> p = getPlayer();
1513 if (p != 0) return p->setLooping(loop);
1514 return NO_ERROR;
1515}
1516
1517status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1518{
Steve Block3856b092011-10-20 11:56:00 +01001519 ALOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
John Grossman761defc2012-02-09 15:09:05 -08001520
1521 // for hardware output, call player instead
1522 sp<MediaPlayerBase> p = getPlayer();
1523 {
1524 Mutex::Autolock l(mLock);
1525 if (p != 0 && p->hardwareOutput()) {
1526 MediaPlayerHWInterface* hwp =
1527 reinterpret_cast<MediaPlayerHWInterface*>(p.get());
1528 return hwp->setVolume(leftVolume, rightVolume);
1529 } else {
1530 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1531 return NO_ERROR;
1532 }
1533 }
1534
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001535 return NO_ERROR;
1536}
1537
Eric Laurent2beeb502010-07-16 07:43:46 -07001538status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1539{
Steve Block3856b092011-10-20 11:56:00 +01001540 ALOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
Eric Laurent2beeb502010-07-16 07:43:46 -07001541 Mutex::Autolock l(mLock);
1542 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1543 return NO_ERROR;
1544}
1545
1546status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1547{
Steve Block3856b092011-10-20 11:56:00 +01001548 ALOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
Eric Laurent2beeb502010-07-16 07:43:46 -07001549 Mutex::Autolock l(mLock);
1550 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1551 return NO_ERROR;
1552}
Nicolas Catania48290382009-07-10 13:53:06 -07001553
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001554status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
Steve Block3856b092011-10-20 11:56:00 +01001555 ALOGV("[%d] setParameter(%d)", mConnId, key);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001556 switch (key) {
1557 case KEY_PARAMETER_AUDIO_ATTRIBUTES:
1558 {
1559 Mutex::Autolock l(mLock);
1560 return setAudioAttributes_l(request);
1561 }
1562 default:
1563 sp<MediaPlayerBase> p = getPlayer();
1564 if (p == 0) { return UNKNOWN_ERROR; }
1565 return p->setParameter(key, request);
1566 }
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001567}
1568
1569status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
Steve Block3856b092011-10-20 11:56:00 +01001570 ALOGV("[%d] getParameter(%d)", mConnId, key);
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001571 sp<MediaPlayerBase> p = getPlayer();
1572 if (p == 0) return UNKNOWN_ERROR;
1573 return p->getParameter(key, reply);
1574}
1575
John Grossmanc795b642012-02-22 15:38:35 -08001576status_t MediaPlayerService::Client::setRetransmitEndpoint(
1577 const struct sockaddr_in* endpoint) {
1578
1579 if (NULL != endpoint) {
1580 uint32_t a = ntohl(endpoint->sin_addr.s_addr);
1581 uint16_t p = ntohs(endpoint->sin_port);
1582 ALOGV("[%d] setRetransmitEndpoint(%u.%u.%u.%u:%hu)", mConnId,
1583 (a >> 24), (a >> 16) & 0xFF, (a >> 8) & 0xFF, (a & 0xFF), p);
1584 } else {
1585 ALOGV("[%d] setRetransmitEndpoint = <none>", mConnId);
1586 }
1587
1588 sp<MediaPlayerBase> p = getPlayer();
1589
1590 // Right now, the only valid time to set a retransmit endpoint is before
1591 // player selection has been made (since the presence or absence of a
1592 // retransmit endpoint is going to determine which player is selected during
1593 // setDataSource).
1594 if (p != 0) return INVALID_OPERATION;
1595
1596 if (NULL != endpoint) {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001597 Mutex::Autolock lock(mLock);
John Grossmanc795b642012-02-22 15:38:35 -08001598 mRetransmitEndpoint = *endpoint;
1599 mRetransmitEndpointValid = true;
1600 } else {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001601 Mutex::Autolock lock(mLock);
John Grossmanc795b642012-02-22 15:38:35 -08001602 mRetransmitEndpointValid = false;
1603 }
1604
1605 return NO_ERROR;
1606}
1607
John Grossman44a7e422012-06-21 17:29:24 -07001608status_t MediaPlayerService::Client::getRetransmitEndpoint(
1609 struct sockaddr_in* endpoint)
1610{
1611 if (NULL == endpoint)
1612 return BAD_VALUE;
1613
1614 sp<MediaPlayerBase> p = getPlayer();
1615
1616 if (p != NULL)
1617 return p->getRetransmitEndpoint(endpoint);
1618
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001619 Mutex::Autolock lock(mLock);
John Grossman44a7e422012-06-21 17:29:24 -07001620 if (!mRetransmitEndpointValid)
1621 return NO_INIT;
1622
1623 *endpoint = mRetransmitEndpoint;
1624
1625 return NO_ERROR;
1626}
1627
Gloria Wangb483c472011-04-11 17:23:27 -07001628void MediaPlayerService::Client::notify(
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001629 int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001630{
James Dongb8a98252012-08-26 16:13:03 -07001631 sp<IMediaPlayerClient> c;
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001632 sp<Client> nextClient;
1633 status_t errStartNext = NO_ERROR;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001634 {
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001635 Mutex::Autolock l(mLock);
1636 c = mClient;
1637 if (msg == MEDIA_PLAYBACK_COMPLETE && mNextClient != NULL) {
1638 nextClient = mNextClient;
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001639
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001640 if (mAudioOutput != NULL)
1641 mAudioOutput->switchToNextOutput();
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001642
1643 errStartNext = nextClient->start();
1644 }
1645 }
1646
1647 if (nextClient != NULL) {
1648 sp<IMediaPlayerClient> nc;
1649 {
1650 Mutex::Autolock l(nextClient->mLock);
1651 nc = nextClient->mClient;
1652 }
1653 if (nc != NULL) {
1654 if (errStartNext == NO_ERROR) {
1655 nc->notify(MEDIA_INFO, MEDIA_INFO_STARTED_AS_NEXT, 0, obj);
1656 } else {
1657 nc->notify(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN , 0, obj);
1658 ALOGE("gapless:start playback for next track failed, err(%d)", errStartNext);
Wei Jia2afac0c2016-01-07 12:13:07 -08001659 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001660 }
1661 }
1662
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001663 if (MEDIA_INFO == msg &&
Nicolas Catania48290382009-07-10 13:53:06 -07001664 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikoa64c8c72009-07-20 15:07:26 -07001665 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania48290382009-07-10 13:53:06 -07001666
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001667 if(shouldDropMetadata(metadata_type)) {
Nicolas Catania48290382009-07-10 13:53:06 -07001668 return;
1669 }
1670
1671 // Update the list of metadata that have changed. getMetadata
1672 // also access mMetadataUpdated and clears it.
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001673 addNewMetadataUpdate(metadata_type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001674 }
James Dongb8a98252012-08-26 16:13:03 -07001675
1676 if (c != NULL) {
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001677 ALOGV("[%d] notify (%d, %d, %d)", mConnId, msg, ext1, ext2);
James Dongb8a98252012-08-26 16:13:03 -07001678 c->notify(msg, ext1, ext2, obj);
1679 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001680}
1681
Nicolas Catania48290382009-07-10 13:53:06 -07001682
nikoa64c8c72009-07-20 15:07:26 -07001683bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001684{
Nicolas Catania48290382009-07-10 13:53:06 -07001685 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001686
Nicolas Catania48290382009-07-10 13:53:06 -07001687 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001688 return true;
1689 }
1690
Nicolas Catania48290382009-07-10 13:53:06 -07001691 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001692 return false;
Nicolas Catania48290382009-07-10 13:53:06 -07001693 } else {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001694 return true;
1695 }
1696}
1697
Nicolas Catania48290382009-07-10 13:53:06 -07001698
nikoa64c8c72009-07-20 15:07:26 -07001699void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania48290382009-07-10 13:53:06 -07001700 Mutex::Autolock lock(mLock);
1701 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1702 mMetadataUpdated.add(metadata_type);
1703 }
1704}
1705
Hassan Shojaniacefac142017-02-06 21:02:02 -08001706// Modular DRM
1707status_t MediaPlayerService::Client::prepareDrm(const uint8_t uuid[16],
1708 const Vector<uint8_t>& drmSessionId)
1709{
1710 ALOGV("[%d] prepareDrm", mConnId);
1711 sp<MediaPlayerBase> p = getPlayer();
1712 if (p == 0) return UNKNOWN_ERROR;
1713
1714 status_t ret = p->prepareDrm(uuid, drmSessionId);
1715 ALOGV("prepareDrm ret: %d", ret);
1716
1717 return ret;
1718}
1719
1720status_t MediaPlayerService::Client::releaseDrm()
1721{
1722 ALOGV("[%d] releaseDrm", mConnId);
1723 sp<MediaPlayerBase> p = getPlayer();
1724 if (p == 0) return UNKNOWN_ERROR;
1725
1726 status_t ret = p->releaseDrm();
1727 ALOGV("releaseDrm ret: %d", ret);
1728
1729 return ret;
1730}
1731
jiabin156c6872017-10-06 09:47:15 -07001732status_t MediaPlayerService::Client::setOutputDevice(audio_port_handle_t deviceId)
1733{
1734 ALOGV("[%d] setOutputDevice", mConnId);
1735 {
1736 Mutex::Autolock l(mLock);
1737 if (mAudioOutput.get() != nullptr) {
1738 return mAudioOutput->setOutputDevice(deviceId);
1739 }
1740 }
1741 return NO_INIT;
1742}
1743
1744status_t MediaPlayerService::Client::getRoutedDeviceId(audio_port_handle_t* deviceId)
1745{
1746 ALOGV("[%d] getRoutedDeviceId", mConnId);
1747 {
1748 Mutex::Autolock l(mLock);
1749 if (mAudioOutput.get() != nullptr) {
1750 return mAudioOutput->getRoutedDeviceId(deviceId);
1751 }
1752 }
1753 return NO_INIT;
1754}
1755
1756status_t MediaPlayerService::Client::enableAudioDeviceCallback(bool enabled)
1757{
1758 ALOGV("[%d] enableAudioDeviceCallback, %d", mConnId, enabled);
1759 {
1760 Mutex::Autolock l(mLock);
1761 if (mAudioOutput.get() != nullptr) {
1762 return mAudioOutput->enableAudioDeviceCallback(enabled);
1763 }
1764 }
1765 return NO_INIT;
1766}
1767
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001768#if CALLBACK_ANTAGONIZER
1769const int Antagonizer::interval = 10000; // 10 msecs
1770
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001771Antagonizer::Antagonizer(const sp<MediaPlayerBase::Listener> &listener) :
1772 mExit(false), mActive(false), mListener(listener)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001773{
1774 createThread(callbackThread, this);
1775}
1776
1777void Antagonizer::kill()
1778{
1779 Mutex::Autolock _l(mLock);
1780 mActive = false;
1781 mExit = true;
1782 mCondition.wait(mLock);
1783}
1784
1785int Antagonizer::callbackThread(void* user)
1786{
Steve Blockb8a80522011-12-20 16:23:08 +00001787 ALOGD("Antagonizer started");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001788 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1789 while (!p->mExit) {
1790 if (p->mActive) {
Steve Block3856b092011-10-20 11:56:00 +01001791 ALOGV("send event");
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001792 p->mListener->notify(0, 0, 0, 0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001793 }
1794 usleep(interval);
1795 }
1796 Mutex::Autolock _l(p->mLock);
1797 p->mCondition.signal();
Steve Blockb8a80522011-12-20 16:23:08 +00001798 ALOGD("Antagonizer stopped");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001799 return 0;
1800}
1801#endif
1802
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001803#undef LOG_TAG
1804#define LOG_TAG "AudioSink"
Svet Ganov33761132021-05-13 22:51:08 +00001805MediaPlayerService::AudioOutput::AudioOutput(audio_session_t sessionId,
1806 const AttributionSourceState& attributionSource, const audio_attributes_t* attr,
1807 const sp<AudioSystem::AudioDeviceCallback>& deviceCallback)
Andreas Huber20111aa2009-07-14 16:56:47 -07001808 : mCallback(NULL),
Eric Laurenta514bdb2010-06-21 09:27:30 -07001809 mCallbackCookie(NULL),
Marco Nelissen6b74d672012-02-28 16:07:44 -08001810 mCallbackData(NULL),
Andy Hungd1c74342015-07-07 16:54:23 -07001811 mStreamType(AUDIO_STREAM_MUSIC),
Andy Hungd1c74342015-07-07 16:54:23 -07001812 mLeftVolume(1.0),
1813 mRightVolume(1.0),
1814 mPlaybackRate(AUDIO_PLAYBACK_RATE_DEFAULT),
1815 mSampleRateHz(0),
1816 mMsecsPerFrame(0),
1817 mFrameSize(0),
Eric Laurent1948eb32012-04-13 16:50:19 -07001818 mSessionId(sessionId),
Svet Ganov33761132021-05-13 22:51:08 +00001819 mAttributionSource(attributionSource),
Andy Hungd1c74342015-07-07 16:54:23 -07001820 mSendLevel(0.0),
1821 mAuxEffectId(0),
Andy Hung4ef88d72017-02-21 19:47:53 -08001822 mFlags(AUDIO_OUTPUT_FLAG_NONE),
jiabin156c6872017-10-06 09:47:15 -07001823 mVolumeHandler(new media::VolumeHandler()),
1824 mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE),
jiabin161b64f2017-11-17 09:31:48 -08001825 mRoutedDeviceId(AUDIO_PORT_HANDLE_NONE),
jiabin156c6872017-10-06 09:47:15 -07001826 mDeviceCallbackEnabled(false),
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001827 mDeviceCallback(deviceCallback)
Andy Hungd1c74342015-07-07 16:54:23 -07001828{
Steve Block3856b092011-10-20 11:56:00 +01001829 ALOGV("AudioOutput(%d)", sessionId);
Eric Laurent43562692015-07-15 16:49:07 -07001830 if (attr != NULL) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001831 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1832 if (mAttributes != NULL) {
1833 memcpy(mAttributes, attr, sizeof(audio_attributes_t));
François Gaffie58d4be52018-11-06 15:30:12 +01001834 mStreamType = AudioSystem::attributesToStreamType(*attr);
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001835 }
1836 } else {
1837 mAttributes = NULL;
Eric Laurent43562692015-07-15 16:49:07 -07001838 }
1839
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001840 setMinBufferCount();
1841}
1842
1843MediaPlayerService::AudioOutput::~AudioOutput()
1844{
1845 close();
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001846 free(mAttributes);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001847}
1848
Andy Hungd1c74342015-07-07 16:54:23 -07001849//static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001850void MediaPlayerService::AudioOutput::setMinBufferCount()
1851{
Roman Kiryanova3f34462021-03-10 16:17:24 -08001852 if (property_get_bool("ro.boot.qemu", false)) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001853 mIsOnEmulator = true;
1854 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1855 }
1856}
1857
Andy Hungd1c74342015-07-07 16:54:23 -07001858// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001859bool MediaPlayerService::AudioOutput::isOnEmulator()
1860{
Andy Hungd1c74342015-07-07 16:54:23 -07001861 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001862 return mIsOnEmulator;
1863}
1864
Andy Hungd1c74342015-07-07 16:54:23 -07001865// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001866int MediaPlayerService::AudioOutput::getMinBufferCount()
1867{
Andy Hungd1c74342015-07-07 16:54:23 -07001868 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001869 return mMinBufferCount;
1870}
1871
1872ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1873{
Andy Hungd1c74342015-07-07 16:54:23 -07001874 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001875 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001876 return mTrack->frameCount() * mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001877}
1878
1879ssize_t MediaPlayerService::AudioOutput::frameCount() const
1880{
Andy Hungd1c74342015-07-07 16:54:23 -07001881 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001882 if (mTrack == 0) return NO_INIT;
1883 return mTrack->frameCount();
1884}
1885
1886ssize_t MediaPlayerService::AudioOutput::channelCount() const
1887{
Andy Hungd1c74342015-07-07 16:54:23 -07001888 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001889 if (mTrack == 0) return NO_INIT;
1890 return mTrack->channelCount();
1891}
1892
1893ssize_t MediaPlayerService::AudioOutput::frameSize() const
1894{
Andy Hungd1c74342015-07-07 16:54:23 -07001895 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001896 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001897 return mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001898}
1899
1900uint32_t MediaPlayerService::AudioOutput::latency () const
1901{
Andy Hungd1c74342015-07-07 16:54:23 -07001902 Mutex::Autolock lock(mLock);
Eric Laurentdb354e52012-03-05 17:27:11 -08001903 if (mTrack == 0) return 0;
1904 return mTrack->latency();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001905}
1906
1907float MediaPlayerService::AudioOutput::msecsPerFrame() const
1908{
Andy Hungd1c74342015-07-07 16:54:23 -07001909 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001910 return mMsecsPerFrame;
1911}
1912
Marco Nelissen4110c102012-03-29 09:31:28 -07001913status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position) const
Eric Laurent342e9cf2010-01-19 17:37:09 -08001914{
Andy Hungd1c74342015-07-07 16:54:23 -07001915 Mutex::Autolock lock(mLock);
Eric Laurent342e9cf2010-01-19 17:37:09 -08001916 if (mTrack == 0) return NO_INIT;
1917 return mTrack->getPosition(position);
1918}
1919
Lajos Molnar06ad1522014-08-28 07:27:44 -07001920status_t MediaPlayerService::AudioOutput::getTimestamp(AudioTimestamp &ts) const
1921{
Andy Hungd1c74342015-07-07 16:54:23 -07001922 Mutex::Autolock lock(mLock);
Lajos Molnar06ad1522014-08-28 07:27:44 -07001923 if (mTrack == 0) return NO_INIT;
1924 return mTrack->getTimestamp(ts);
1925}
1926
Wei Jiac4ac8172015-10-21 10:35:48 -07001927// TODO: Remove unnecessary calls to getPlayedOutDurationUs()
1928// as it acquires locks and may query the audio driver.
1929//
1930// Some calls could conceivably retrieve extrapolated data instead of
1931// accessing getTimestamp() or getPosition() every time a data buffer with
1932// a media time is received.
1933//
1934// Calculate duration of played samples if played at normal rate (i.e., 1.0).
1935int64_t MediaPlayerService::AudioOutput::getPlayedOutDurationUs(int64_t nowUs) const
1936{
1937 Mutex::Autolock lock(mLock);
1938 if (mTrack == 0 || mSampleRateHz == 0) {
Wei Jia213f4902015-10-22 08:55:25 -07001939 return 0;
Wei Jiac4ac8172015-10-21 10:35:48 -07001940 }
1941
1942 uint32_t numFramesPlayed;
Andy Hung5d313802016-10-10 15:09:39 -07001943 int64_t numFramesPlayedAtUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001944 AudioTimestamp ts;
Wei Jiac4ac8172015-10-21 10:35:48 -07001945
1946 status_t res = mTrack->getTimestamp(ts);
1947 if (res == OK) { // case 1: mixing audio tracks and offloaded tracks.
1948 numFramesPlayed = ts.mPosition;
Andy Hung5d313802016-10-10 15:09:39 -07001949 numFramesPlayedAtUs = ts.mTime.tv_sec * 1000000LL + ts.mTime.tv_nsec / 1000;
1950 //ALOGD("getTimestamp: OK %d %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001951 } else if (res == WOULD_BLOCK) { // case 2: transitory state on start of a new track
1952 numFramesPlayed = 0;
Andy Hung5d313802016-10-10 15:09:39 -07001953 numFramesPlayedAtUs = nowUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001954 //ALOGD("getTimestamp: WOULD_BLOCK %d %lld",
Andy Hung5d313802016-10-10 15:09:39 -07001955 // numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001956 } else { // case 3: transitory at new track or audio fast tracks.
1957 res = mTrack->getPosition(&numFramesPlayed);
1958 CHECK_EQ(res, (status_t)OK);
Andy Hung5d313802016-10-10 15:09:39 -07001959 numFramesPlayedAtUs = nowUs;
1960 numFramesPlayedAtUs += 1000LL * mTrack->latency() / 2; /* XXX */
1961 //ALOGD("getPosition: %u %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001962 }
1963
1964 // CHECK_EQ(numFramesPlayed & (1 << 31), 0); // can't be negative until 12.4 hrs, test
1965 // TODO: remove the (int32_t) casting below as it may overflow at 12.4 hours.
1966 int64_t durationUs = (int64_t)((int32_t)numFramesPlayed * 1000000LL / mSampleRateHz)
Andy Hung5d313802016-10-10 15:09:39 -07001967 + nowUs - numFramesPlayedAtUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001968 if (durationUs < 0) {
1969 // Occurs when numFramesPlayed position is very small and the following:
1970 // (1) In case 1, the time nowUs is computed before getTimestamp() is called and
Andy Hung5d313802016-10-10 15:09:39 -07001971 // numFramesPlayedAtUs is greater than nowUs by time more than numFramesPlayed.
Wei Jiac4ac8172015-10-21 10:35:48 -07001972 // (2) In case 3, using getPosition and adding mAudioSink->latency() to
Andy Hung5d313802016-10-10 15:09:39 -07001973 // numFramesPlayedAtUs, by a time amount greater than numFramesPlayed.
Wei Jiac4ac8172015-10-21 10:35:48 -07001974 //
1975 // Both of these are transitory conditions.
1976 ALOGV("getPlayedOutDurationUs: negative duration %lld set to zero", (long long)durationUs);
1977 durationUs = 0;
1978 }
1979 ALOGV("getPlayedOutDurationUs(%lld) nowUs(%lld) frames(%u) framesAt(%lld)",
Andy Hung5d313802016-10-10 15:09:39 -07001980 (long long)durationUs, (long long)nowUs,
1981 numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001982 return durationUs;
1983}
1984
Marco Nelissen4110c102012-03-29 09:31:28 -07001985status_t MediaPlayerService::AudioOutput::getFramesWritten(uint32_t *frameswritten) const
1986{
Andy Hungd1c74342015-07-07 16:54:23 -07001987 Mutex::Autolock lock(mLock);
Marco Nelissen4110c102012-03-29 09:31:28 -07001988 if (mTrack == 0) return NO_INIT;
Andy Hung2f6e73d2016-04-08 12:12:58 -07001989 ExtendedTimestamp ets;
1990 status_t status = mTrack->getTimestamp(&ets);
1991 if (status == OK || status == WOULD_BLOCK) {
1992 *frameswritten = (uint32_t)ets.mPosition[ExtendedTimestamp::LOCATION_CLIENT];
1993 }
1994 return status;
Marco Nelissen4110c102012-03-29 09:31:28 -07001995}
1996
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001997status_t MediaPlayerService::AudioOutput::setParameters(const String8& keyValuePairs)
1998{
Andy Hungd1c74342015-07-07 16:54:23 -07001999 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002000 if (mTrack == 0) return NO_INIT;
2001 return mTrack->setParameters(keyValuePairs);
2002}
2003
2004String8 MediaPlayerService::AudioOutput::getParameters(const String8& keys)
2005{
Andy Hungd1c74342015-07-07 16:54:23 -07002006 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002007 if (mTrack == 0) return String8::empty();
2008 return mTrack->getParameters(keys);
2009}
2010
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07002011void MediaPlayerService::AudioOutput::setAudioAttributes(const audio_attributes_t * attributes) {
Andy Hungd1c74342015-07-07 16:54:23 -07002012 Mutex::Autolock lock(mLock);
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07002013 if (attributes == NULL) {
2014 free(mAttributes);
2015 mAttributes = NULL;
2016 } else {
2017 if (mAttributes == NULL) {
2018 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
2019 }
2020 memcpy(mAttributes, attributes, sizeof(audio_attributes_t));
François Gaffie58d4be52018-11-06 15:30:12 +01002021 mStreamType = AudioSystem::attributesToStreamType(*attributes);
Eric Laurent43562692015-07-15 16:49:07 -07002022 }
2023}
2024
2025void MediaPlayerService::AudioOutput::setAudioStreamType(audio_stream_type_t streamType)
2026{
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07002027 Mutex::Autolock lock(mLock);
Eric Laurent43562692015-07-15 16:49:07 -07002028 // do not allow direct stream type modification if attributes have been set
2029 if (mAttributes == NULL) {
2030 mStreamType = streamType;
2031 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07002032}
2033
Andy Hungd1c74342015-07-07 16:54:23 -07002034void MediaPlayerService::AudioOutput::deleteRecycledTrack_l()
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002035{
Andy Hungd1c74342015-07-07 16:54:23 -07002036 ALOGV("deleteRecycledTrack_l");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002037 if (mRecycledTrack != 0) {
2038
2039 if (mCallbackData != NULL) {
2040 mCallbackData->setOutput(NULL);
2041 mCallbackData->endTrackSwitch();
2042 }
2043
2044 if ((mRecycledTrack->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) {
Andy Hunge13f8a62016-03-30 14:20:42 -07002045 int32_t msec = 0;
2046 if (!mRecycledTrack->stopped()) { // check if active
2047 (void)mRecycledTrack->pendingDuration(&msec);
2048 }
2049 mRecycledTrack->stop(); // ensure full data drain
2050 ALOGD("deleting recycled track, waiting for data drain (%d msec)", msec);
2051 if (msec > 0) {
2052 static const int32_t WAIT_LIMIT_MS = 3000;
2053 if (msec > WAIT_LIMIT_MS) {
2054 msec = WAIT_LIMIT_MS;
2055 }
2056 usleep(msec * 1000LL);
2057 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002058 }
2059 // An offloaded track isn't flushed because the STREAM_END is reported
2060 // slightly prematurely to allow time for the gapless track switch
2061 // but this means that if we decide not to recycle the track there
2062 // could be a small amount of residual data still playing. We leave
2063 // AudioFlinger to drain the track.
2064
2065 mRecycledTrack.clear();
Andy Hungd1c74342015-07-07 16:54:23 -07002066 close_l();
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002067 mCallbackData.clear();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002068 }
2069}
2070
Andy Hungd1c74342015-07-07 16:54:23 -07002071void MediaPlayerService::AudioOutput::close_l()
2072{
2073 mTrack.clear();
2074}
2075
Andreas Huber20111aa2009-07-14 16:56:47 -07002076status_t MediaPlayerService::AudioOutput::open(
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08002077 uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
2078 audio_format_t format, int bufferCount,
Eric Laurent1948eb32012-04-13 16:50:19 -07002079 AudioCallback cb, void *cookie,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002080 audio_output_flags_t flags,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07002081 const audio_offload_info_t *offloadInfo,
Andy Hung179652e2015-05-31 22:49:46 -07002082 bool doNotReconnect,
2083 uint32_t suggestedFrameCount)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002084{
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002085 ALOGV("open(%u, %d, 0x%x, 0x%x, %d, %d 0x%x)", sampleRate, channelCount, channelMask,
2086 format, bufferCount, mSessionId, flags);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002087
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002088 // offloading is only supported in callback mode for now.
2089 // offloadInfo must be present if offload flag is set
2090 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) &&
2091 ((cb == NULL) || (offloadInfo == NULL))) {
2092 return BAD_VALUE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002093 }
2094
Andy Hung179652e2015-05-31 22:49:46 -07002095 // compute frame count for the AudioTrack internal buffer
2096 size_t frameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002097 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
2098 frameCount = 0; // AudioTrack will get frame count from AudioFlinger
2099 } else {
Andy Hung179652e2015-05-31 22:49:46 -07002100 // try to estimate the buffer processing fetch size from AudioFlinger.
2101 // framesPerBuffer is approximate and generally correct, except when it's not :-).
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002102 uint32_t afSampleRate;
2103 size_t afFrameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002104 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
2105 return NO_INIT;
2106 }
2107 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
2108 return NO_INIT;
2109 }
Ben Romberger259fb462018-08-07 17:58:53 -07002110 if (afSampleRate == 0) {
2111 return NO_INIT;
2112 }
Andy Hung179652e2015-05-31 22:49:46 -07002113 const size_t framesPerBuffer =
2114 (unsigned long long)sampleRate * afFrameCount / afSampleRate;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002115
Andy Hung179652e2015-05-31 22:49:46 -07002116 if (bufferCount == 0) {
Ben Romberger259fb462018-08-07 17:58:53 -07002117 if (framesPerBuffer == 0) {
2118 return NO_INIT;
2119 }
Andy Hung179652e2015-05-31 22:49:46 -07002120 // use suggestedFrameCount
2121 bufferCount = (suggestedFrameCount + framesPerBuffer - 1) / framesPerBuffer;
2122 }
2123 // Check argument bufferCount against the mininum buffer count
2124 if (bufferCount != 0 && bufferCount < mMinBufferCount) {
2125 ALOGV("bufferCount (%d) increased to %d", bufferCount, mMinBufferCount);
2126 bufferCount = mMinBufferCount;
2127 }
2128 // if frameCount is 0, then AudioTrack will get frame count from AudioFlinger
2129 // which will be the minimum size permitted.
2130 frameCount = bufferCount * framesPerBuffer;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002131 }
Andreas Huber20111aa2009-07-14 16:56:47 -07002132
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08002133 if (channelMask == CHANNEL_MASK_USE_CHANNEL_ORDER) {
Glenn Kastenab334fd2012-03-14 12:56:06 -07002134 channelMask = audio_channel_out_mask_from_count(channelCount);
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08002135 if (0 == channelMask) {
2136 ALOGE("open() error, can\'t derive mask for %d audio channels", channelCount);
2137 return NO_INIT;
2138 }
2139 }
Eric Laurent1948eb32012-04-13 16:50:19 -07002140
Andy Hungd1c74342015-07-07 16:54:23 -07002141 Mutex::Autolock lock(mLock);
Andy Hung179652e2015-05-31 22:49:46 -07002142 mCallback = cb;
2143 mCallbackCookie = cookie;
2144
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002145 // Check whether we can recycle the track
2146 bool reuse = false;
2147 bool bothOffloaded = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07002148
Glenn Kasten2799d742013-05-30 14:33:29 -07002149 if (mRecycledTrack != 0) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002150 // check whether we are switching between two offloaded tracks
2151 bothOffloaded = (flags & mRecycledTrack->getFlags()
2152 & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0;
Marco Nelissen67295b52012-06-11 14:52:53 -07002153
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002154 // check if the existing track can be reused as-is, or if a new track needs to be created.
2155 reuse = true;
2156
Marco Nelissen67295b52012-06-11 14:52:53 -07002157 if ((mCallbackData == NULL && mCallback != NULL) ||
2158 (mCallbackData != NULL && mCallback == NULL)) {
2159 // recycled track uses callbacks but the caller wants to use writes, or vice versa
2160 ALOGV("can't chain callback and write");
2161 reuse = false;
2162 } else if ((mRecycledTrack->getSampleRate() != sampleRate) ||
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002163 (mRecycledTrack->channelCount() != (uint32_t)channelCount) ) {
2164 ALOGV("samplerate, channelcount differ: %u/%u Hz, %u/%d ch",
Marco Nelissen67295b52012-06-11 14:52:53 -07002165 mRecycledTrack->getSampleRate(), sampleRate,
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002166 mRecycledTrack->channelCount(), channelCount);
Marco Nelissen67295b52012-06-11 14:52:53 -07002167 reuse = false;
2168 } else if (flags != mFlags) {
2169 ALOGV("output flags differ %08x/%08x", flags, mFlags);
2170 reuse = false;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002171 } else if (mRecycledTrack->format() != format) {
2172 reuse = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07002173 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002174 } else {
2175 ALOGV("no track available to recycle");
2176 }
2177
2178 ALOGV_IF(bothOffloaded, "both tracks offloaded");
2179
2180 // If we can't recycle and both tracks are offloaded
2181 // we must close the previous output before opening a new one
2182 if (bothOffloaded && !reuse) {
2183 ALOGV("both offloaded and not recycling");
Andy Hungd1c74342015-07-07 16:54:23 -07002184 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002185 }
2186
2187 sp<AudioTrack> t;
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002188 sp<CallbackData> newcbd;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002189
2190 // We don't attempt to create a new track if we are recycling an
2191 // offloaded track. But, if we are recycling a non-offloaded or we
2192 // are switching where one is offloaded and one isn't then we create
2193 // the new track in advance so that we can read additional stream info
2194
2195 if (!(reuse && bothOffloaded)) {
2196 ALOGV("creating new AudioTrack");
2197
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002198 if (mCallback != nullptr) {
2199 newcbd = sp<CallbackData>::make(wp<AudioOutput>::fromExisting(this));
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002200 t = new AudioTrack(
2201 mStreamType,
2202 sampleRate,
2203 format,
2204 channelMask,
2205 frameCount,
2206 flags,
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002207 newcbd,
2208 0, // notification frames
2209 mSessionId,
2210 AudioTrack::TRANSFER_CALLBACK,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002211 offloadInfo,
Svet Ganov33761132021-05-13 22:51:08 +00002212 mAttributionSource,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07002213 mAttributes,
jiabin156c6872017-10-06 09:47:15 -07002214 doNotReconnect,
2215 1.0f, // default value for maxRequiredSpeed
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002216 mSelectedDeviceId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002217 } else {
Andy Hungff874dc2016-04-11 16:49:09 -07002218 // TODO: Due to buffer memory concerns, we use a max target playback speed
2219 // based on mPlaybackRate at the time of open (instead of kMaxRequiredSpeed),
2220 // also clamping the target speed to 1.0 <= targetSpeed <= kMaxRequiredSpeed.
2221 const float targetSpeed =
2222 std::min(std::max(mPlaybackRate.mSpeed, 1.0f), kMaxRequiredSpeed);
2223 ALOGW_IF(targetSpeed != mPlaybackRate.mSpeed,
2224 "track target speed:%f clamped from playback speed:%f",
2225 targetSpeed, mPlaybackRate.mSpeed);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002226 t = new AudioTrack(
2227 mStreamType,
2228 sampleRate,
2229 format,
2230 channelMask,
2231 frameCount,
2232 flags,
Atneya Nairc1bf42b2021-11-29 19:00:54 -05002233 nullptr, // callback
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002234 0, // notification frames
2235 mSessionId,
2236 AudioTrack::TRANSFER_DEFAULT,
2237 NULL, // offload info
Svet Ganov33761132021-05-13 22:51:08 +00002238 mAttributionSource,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07002239 mAttributes,
Andy Hungff874dc2016-04-11 16:49:09 -07002240 doNotReconnect,
jiabin156c6872017-10-06 09:47:15 -07002241 targetSpeed,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002242 mSelectedDeviceId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002243 }
Andy Hunga6b27032020-04-27 10:34:24 -07002244 // Set caller name so it can be logged in destructor.
2245 // MediaMetricsConstants.h: AMEDIAMETRICS_PROP_CALLERNAME_VALUE_MEDIA
2246 t->setCallerName("media");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002247 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
2248 ALOGE("Unable to create audio track");
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002249 // t, newcbd goes out of scope, so reference count drops to zero
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002250 return NO_INIT;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07002251 } else {
2252 // successful AudioTrack initialization implies a legacy stream type was generated
2253 // from the audio attributes
2254 mStreamType = t->streamType();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002255 }
2256 }
2257
2258 if (reuse) {
2259 CHECK(mRecycledTrack != NULL);
2260
2261 if (!bothOffloaded) {
2262 if (mRecycledTrack->frameCount() != t->frameCount()) {
Andy Hung833b4752016-04-04 17:15:48 -07002263 ALOGV("framecount differs: %zu/%zu frames",
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002264 mRecycledTrack->frameCount(), t->frameCount());
2265 reuse = false;
2266 }
Jaideep Sharmab3ce4482020-11-16 11:52:35 +05302267 // If recycled and new tracks are not on the same output,
2268 // don't reuse the recycled one.
2269 if (mRecycledTrack->getOutput() != t->getOutput()) {
2270 ALOGV("output has changed, don't reuse track");
2271 reuse = false;
2272 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002273 }
2274
Marco Nelissen67295b52012-06-11 14:52:53 -07002275 if (reuse) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002276 ALOGV("chaining to next output and recycling track");
Andy Hungd1c74342015-07-07 16:54:23 -07002277 close_l();
Marco Nelissen67295b52012-06-11 14:52:53 -07002278 mTrack = mRecycledTrack;
Glenn Kasten2799d742013-05-30 14:33:29 -07002279 mRecycledTrack.clear();
Marco Nelissen67295b52012-06-11 14:52:53 -07002280 if (mCallbackData != NULL) {
2281 mCallbackData->setOutput(this);
2282 }
Wei Jiae0bbac92016-07-18 16:04:53 -07002283 return updateTrack();
Marco Nelissen67295b52012-06-11 14:52:53 -07002284 }
Marco Nelissen67295b52012-06-11 14:52:53 -07002285 }
2286
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002287 // we're not going to reuse the track, unblock and flush it
2288 // this was done earlier if both tracks are offloaded
2289 if (!bothOffloaded) {
Andy Hungd1c74342015-07-07 16:54:23 -07002290 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002291 }
2292
2293 CHECK((t != NULL) && ((mCallback == NULL) || (newcbd != NULL)));
2294
Marco Nelissen67295b52012-06-11 14:52:53 -07002295 mCallbackData = newcbd;
Steve Block3856b092011-10-20 11:56:00 +01002296 ALOGV("setVolume");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002297 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07002298
Andy Hung39399b62017-04-21 15:07:45 -07002299 // Restore VolumeShapers for the MediaPlayer in case the track was recreated
2300 // due to an output sink error (e.g. offload to non-offload switch).
2301 mVolumeHandler->forall([&t](const VolumeShaper &shaper) -> VolumeShaper::Status {
2302 sp<VolumeShaper::Operation> operationToEnd =
2303 new VolumeShaper::Operation(shaper.mOperation);
2304 // TODO: Ideally we would restore to the exact xOffset position
2305 // as returned by getVolumeShaperState(), but we don't have that
2306 // information when restoring at the client unless we periodically poll
2307 // the server or create shared memory state.
2308 //
2309 // For now, we simply advance to the end of the VolumeShaper effect
2310 // if it has been started.
2311 if (shaper.isStarted()) {
Andy Hungf3702642017-05-05 17:33:32 -07002312 operationToEnd->setNormalizedTime(1.f);
Andy Hung39399b62017-04-21 15:07:45 -07002313 }
2314 return t->applyVolumeShaper(shaper.mConfiguration, operationToEnd);
Andy Hung4ef88d72017-02-21 19:47:53 -08002315 });
Andy Hung4ef88d72017-02-21 19:47:53 -08002316
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002317 mSampleRateHz = sampleRate;
Preetam Singh Ranawat2e17eef2015-08-12 12:11:46 -07002318 mFlags = flags;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002319 mMsecsPerFrame = 1E3f / (mPlaybackRate.mSpeed * sampleRate);
Andy Hungd1c74342015-07-07 16:54:23 -07002320 mFrameSize = t->frameSize();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002321 mTrack = t;
Eric Laurent2beeb502010-07-16 07:43:46 -07002322
Wei Jiae0bbac92016-07-18 16:04:53 -07002323 return updateTrack();
2324}
2325
2326status_t MediaPlayerService::AudioOutput::updateTrack() {
2327 if (mTrack == NULL) {
2328 return NO_ERROR;
2329 }
2330
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002331 status_t res = NO_ERROR;
Wei Jia0162d002015-06-09 11:59:33 -07002332 // Note some output devices may give us a direct track even though we don't specify it.
2333 // Example: Line application b/17459982.
Wei Jiae0bbac92016-07-18 16:04:53 -07002334 if ((mTrack->getFlags()
2335 & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) {
2336 res = mTrack->setPlaybackRate(mPlaybackRate);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002337 if (res == NO_ERROR) {
Wei Jiae0bbac92016-07-18 16:04:53 -07002338 mTrack->setAuxEffectSendLevel(mSendLevel);
2339 res = mTrack->attachAuxEffect(mAuxEffectId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002340 }
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002341 }
jiabin156c6872017-10-06 09:47:15 -07002342 mTrack->setOutputDevice(mSelectedDeviceId);
2343 if (mDeviceCallbackEnabled) {
2344 mTrack->addAudioDeviceCallback(mDeviceCallback.promote());
2345 }
Wei Jiae0bbac92016-07-18 16:04:53 -07002346 ALOGV("updateTrack() DONE status %d", res);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002347 return res;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002348}
2349
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002350status_t MediaPlayerService::AudioOutput::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002351{
Steve Block3856b092011-10-20 11:56:00 +01002352 ALOGV("start");
Andy Hungd1c74342015-07-07 16:54:23 -07002353 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08002354 if (mCallbackData != NULL) {
2355 mCallbackData->endTrackSwitch();
2356 }
Glenn Kasten2799d742013-05-30 14:33:29 -07002357 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002358 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07002359 mTrack->setAuxEffectSendLevel(mSendLevel);
Andy Hung39399b62017-04-21 15:07:45 -07002360 status_t status = mTrack->start();
2361 if (status == NO_ERROR) {
2362 mVolumeHandler->setStarted();
2363 }
2364 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002365 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002366 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002367}
2368
Marco Nelissen6b74d672012-02-28 16:07:44 -08002369void MediaPlayerService::AudioOutput::setNextOutput(const sp<AudioOutput>& nextOutput) {
Andy Hungd1c74342015-07-07 16:54:23 -07002370 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08002371 mNextOutput = nextOutput;
2372}
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08002373
Marco Nelissen6b74d672012-02-28 16:07:44 -08002374void MediaPlayerService::AudioOutput::switchToNextOutput() {
2375 ALOGV("switchToNextOutput");
Andy Hungd1c74342015-07-07 16:54:23 -07002376
2377 // Try to acquire the callback lock before moving track (without incurring deadlock).
2378 const unsigned kMaxSwitchTries = 100;
2379 Mutex::Autolock lock(mLock);
2380 for (unsigned tries = 0;;) {
2381 if (mTrack == 0) {
2382 return;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002383 }
Andy Hungd1c74342015-07-07 16:54:23 -07002384 if (mNextOutput != NULL && mNextOutput != this) {
2385 if (mCallbackData != NULL) {
2386 // two alternative approaches
2387#if 1
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002388 sp<CallbackData> callbackData = mCallbackData;
Andy Hungd1c74342015-07-07 16:54:23 -07002389 mLock.unlock();
2390 // proper acquisition sequence
2391 callbackData->lock();
2392 mLock.lock();
2393 // Caution: it is unlikely that someone deleted our callback or changed our target
2394 if (callbackData != mCallbackData || mNextOutput == NULL || mNextOutput == this) {
2395 // fatal if we are starved out.
2396 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2397 "switchToNextOutput() cannot obtain correct lock sequence");
2398 callbackData->unlock();
2399 continue;
2400 }
2401 callbackData->mSwitching = true; // begin track switch
Wei Jiaadee56a2016-08-05 15:40:34 -07002402 callbackData->setOutput(NULL);
Andy Hungd1c74342015-07-07 16:54:23 -07002403#else
2404 // tryBeginTrackSwitch() returns false if the callback has the lock.
2405 if (!mCallbackData->tryBeginTrackSwitch()) {
2406 // fatal if we are starved out.
2407 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2408 "switchToNextOutput() cannot obtain callback lock");
2409 mLock.unlock();
2410 usleep(5 * 1000 /* usec */); // allow callback to use AudioOutput
2411 mLock.lock();
2412 continue;
2413 }
2414#endif
2415 }
2416
2417 Mutex::Autolock nextLock(mNextOutput->mLock);
2418
2419 // If the next output track is not NULL, then it has been
2420 // opened already for playback.
2421 // This is possible even without the next player being started,
2422 // for example, the next player could be prepared and seeked.
2423 //
2424 // Presuming it isn't advisable to force the track over.
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002425 if (mNextOutput->mTrack == nullptr) {
Andy Hungd1c74342015-07-07 16:54:23 -07002426 ALOGD("Recycling track for gapless playback");
Andy Hungd1c74342015-07-07 16:54:23 -07002427 mNextOutput->mCallbackData = mCallbackData;
2428 mNextOutput->mRecycledTrack = mTrack;
2429 mNextOutput->mSampleRateHz = mSampleRateHz;
2430 mNextOutput->mMsecsPerFrame = mMsecsPerFrame;
Andy Hungd1c74342015-07-07 16:54:23 -07002431 mNextOutput->mFlags = mFlags;
2432 mNextOutput->mFrameSize = mFrameSize;
2433 close_l();
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002434 mCallbackData.clear();
Andy Hungd1c74342015-07-07 16:54:23 -07002435 } else {
2436 ALOGW("Ignoring gapless playback because next player has already started");
2437 // remove track in case resource needed for future players.
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002438 if (mCallbackData != nullptr) {
Andy Hungd1c74342015-07-07 16:54:23 -07002439 mCallbackData->endTrackSwitch(); // release lock for callbacks before close.
2440 }
2441 close_l();
2442 }
2443 }
2444 break;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002445 }
2446}
2447
Wei Jia7d3f4df2015-03-03 15:28:00 -08002448ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002449{
Andy Hungd1c74342015-07-07 16:54:23 -07002450 Mutex::Autolock lock(mLock);
Glenn Kastenadad3d72014-02-21 14:51:43 -08002451 LOG_ALWAYS_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
Andreas Huber20111aa2009-07-14 16:56:47 -07002452
Steve Block3856b092011-10-20 11:56:00 +01002453 //ALOGV("write(%p, %u)", buffer, size);
Glenn Kasten2799d742013-05-30 14:33:29 -07002454 if (mTrack != 0) {
Andy Hung2f6e73d2016-04-08 12:12:58 -07002455 return mTrack->write(buffer, size, blocking);
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07002456 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002457 return NO_INIT;
2458}
2459
2460void MediaPlayerService::AudioOutput::stop()
2461{
Steve Block3856b092011-10-20 11:56:00 +01002462 ALOGV("stop");
Andy Hungd1c74342015-07-07 16:54:23 -07002463 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002464 if (mTrack != 0) mTrack->stop();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002465}
2466
2467void MediaPlayerService::AudioOutput::flush()
2468{
Steve Block3856b092011-10-20 11:56:00 +01002469 ALOGV("flush");
Andy Hungd1c74342015-07-07 16:54:23 -07002470 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002471 if (mTrack != 0) mTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002472}
2473
2474void MediaPlayerService::AudioOutput::pause()
2475{
Steve Block3856b092011-10-20 11:56:00 +01002476 ALOGV("pause");
Andy Hung959b5b82021-09-24 10:46:20 -07002477 // We use pauseAndWait() instead of pause() to ensure tracks ramp to silence before
2478 // any flush. We choose 40 ms timeout to allow 1 deep buffer mixer period
2479 // to occur. Often waiting is 0 - 20 ms.
2480 using namespace std::chrono_literals;
2481 constexpr auto TIMEOUT_MS = 40ms;
Andy Hungd1c74342015-07-07 16:54:23 -07002482 Mutex::Autolock lock(mLock);
Andy Hung959b5b82021-09-24 10:46:20 -07002483 if (mTrack != 0) mTrack->pauseAndWait(TIMEOUT_MS);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002484}
2485
2486void MediaPlayerService::AudioOutput::close()
2487{
Steve Block3856b092011-10-20 11:56:00 +01002488 ALOGV("close");
Erik Wolsheimer7845a1f2015-10-30 12:07:52 -07002489 sp<AudioTrack> track;
2490 {
2491 Mutex::Autolock lock(mLock);
2492 track = mTrack;
2493 close_l(); // clears mTrack
2494 }
2495 // destruction of the track occurs outside of mutex.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002496}
2497
2498void MediaPlayerService::AudioOutput::setVolume(float left, float right)
2499{
Steve Block3856b092011-10-20 11:56:00 +01002500 ALOGV("setVolume(%f, %f)", left, right);
Andy Hungd1c74342015-07-07 16:54:23 -07002501 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002502 mLeftVolume = left;
2503 mRightVolume = right;
Glenn Kasten2799d742013-05-30 14:33:29 -07002504 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002505 mTrack->setVolume(left, right);
2506 }
2507}
2508
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002509status_t MediaPlayerService::AudioOutput::setPlaybackRate(const AudioPlaybackRate &rate)
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002510{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002511 ALOGV("setPlaybackRate(%f %f %d %d)",
2512 rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Andy Hungd1c74342015-07-07 16:54:23 -07002513 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002514 if (mTrack == 0) {
2515 // remember rate so that we can set it when the track is opened
2516 mPlaybackRate = rate;
2517 return OK;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002518 }
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002519 status_t res = mTrack->setPlaybackRate(rate);
2520 if (res != NO_ERROR) {
2521 return res;
2522 }
2523 // rate.mSpeed is always greater than 0 if setPlaybackRate succeeded
2524 CHECK_GT(rate.mSpeed, 0.f);
2525 mPlaybackRate = rate;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002526 if (mSampleRateHz != 0) {
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002527 mMsecsPerFrame = 1E3f / (rate.mSpeed * mSampleRateHz);
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002528 }
2529 return res;
2530}
2531
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002532status_t MediaPlayerService::AudioOutput::getPlaybackRate(AudioPlaybackRate *rate)
2533{
2534 ALOGV("setPlaybackRate");
Andy Hungd1c74342015-07-07 16:54:23 -07002535 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002536 if (mTrack == 0) {
2537 return NO_INIT;
2538 }
2539 *rate = mTrack->getPlaybackRate();
2540 return NO_ERROR;
2541}
2542
Eric Laurent2beeb502010-07-16 07:43:46 -07002543status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
2544{
Steve Block3856b092011-10-20 11:56:00 +01002545 ALOGV("setAuxEffectSendLevel(%f)", level);
Andy Hungd1c74342015-07-07 16:54:23 -07002546 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002547 mSendLevel = level;
Glenn Kasten2799d742013-05-30 14:33:29 -07002548 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002549 return mTrack->setAuxEffectSendLevel(level);
2550 }
2551 return NO_ERROR;
2552}
2553
2554status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
2555{
Steve Block3856b092011-10-20 11:56:00 +01002556 ALOGV("attachAuxEffect(%d)", effectId);
Andy Hungd1c74342015-07-07 16:54:23 -07002557 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002558 mAuxEffectId = effectId;
Glenn Kasten2799d742013-05-30 14:33:29 -07002559 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002560 return mTrack->attachAuxEffect(effectId);
2561 }
2562 return NO_ERROR;
2563}
2564
jiabin156c6872017-10-06 09:47:15 -07002565status_t MediaPlayerService::AudioOutput::setOutputDevice(audio_port_handle_t deviceId)
2566{
2567 ALOGV("setOutputDevice(%d)", deviceId);
2568 Mutex::Autolock lock(mLock);
2569 mSelectedDeviceId = deviceId;
2570 if (mTrack != 0) {
2571 return mTrack->setOutputDevice(deviceId);
2572 }
2573 return NO_ERROR;
2574}
2575
2576status_t MediaPlayerService::AudioOutput::getRoutedDeviceId(audio_port_handle_t* deviceId)
2577{
2578 ALOGV("getRoutedDeviceId");
2579 Mutex::Autolock lock(mLock);
2580 if (mTrack != 0) {
jiabin161b64f2017-11-17 09:31:48 -08002581 mRoutedDeviceId = mTrack->getRoutedDeviceId();
jiabin156c6872017-10-06 09:47:15 -07002582 }
jiabin161b64f2017-11-17 09:31:48 -08002583 *deviceId = mRoutedDeviceId;
2584 return NO_ERROR;
jiabin156c6872017-10-06 09:47:15 -07002585}
2586
2587status_t MediaPlayerService::AudioOutput::enableAudioDeviceCallback(bool enabled)
2588{
2589 ALOGV("enableAudioDeviceCallback, %d", enabled);
2590 Mutex::Autolock lock(mLock);
2591 mDeviceCallbackEnabled = enabled;
2592 if (mTrack != 0) {
2593 status_t status;
2594 if (enabled) {
2595 status = mTrack->addAudioDeviceCallback(mDeviceCallback.promote());
2596 } else {
2597 status = mTrack->removeAudioDeviceCallback(mDeviceCallback.promote());
2598 }
2599 return status;
2600 }
2601 return NO_ERROR;
2602}
2603
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002604VolumeShaper::Status MediaPlayerService::AudioOutput::applyVolumeShaper(
2605 const sp<VolumeShaper::Configuration>& configuration,
2606 const sp<VolumeShaper::Operation>& operation)
2607{
2608 Mutex::Autolock lock(mLock);
2609 ALOGV("AudioOutput::applyVolumeShaper");
Andy Hung4ef88d72017-02-21 19:47:53 -08002610
Andy Hung4ef88d72017-02-21 19:47:53 -08002611 mVolumeHandler->setIdIfNecessary(configuration);
Andy Hung39399b62017-04-21 15:07:45 -07002612
2613 VolumeShaper::Status status;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002614 if (mTrack != 0) {
Andy Hung39399b62017-04-21 15:07:45 -07002615 status = mTrack->applyVolumeShaper(configuration, operation);
2616 if (status >= 0) {
2617 (void)mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hungf3702642017-05-05 17:33:32 -07002618 if (mTrack->isPlaying()) { // match local AudioTrack to properly restore.
2619 mVolumeHandler->setStarted();
2620 }
Andy Hung39399b62017-04-21 15:07:45 -07002621 }
Andy Hung4ef88d72017-02-21 19:47:53 -08002622 } else {
Andy Hungc01eddb2017-07-21 16:42:41 -07002623 // VolumeShapers are not affected when a track moves between players for
2624 // gapless playback (setNextMediaPlayer).
2625 // We forward VolumeShaper operations that do not change configuration
2626 // to the new player so that unducking may occur as expected.
2627 // Unducking is an idempotent operation, same if applied back-to-back.
2628 if (configuration->getType() == VolumeShaper::Configuration::TYPE_ID
2629 && mNextOutput != nullptr) {
2630 ALOGV("applyVolumeShaper: Attempting to forward missed operation: %s %s",
2631 configuration->toString().c_str(), operation->toString().c_str());
2632 Mutex::Autolock nextLock(mNextOutput->mLock);
2633
2634 // recycled track should be forwarded from this AudioSink by switchToNextOutput
2635 sp<AudioTrack> track = mNextOutput->mRecycledTrack;
2636 if (track != nullptr) {
2637 ALOGD("Forward VolumeShaper operation to recycled track %p", track.get());
2638 (void)track->applyVolumeShaper(configuration, operation);
2639 } else {
2640 // There is a small chance that the unduck occurs after the next
2641 // player has already started, but before it is registered to receive
2642 // the unduck command.
2643 track = mNextOutput->mTrack;
2644 if (track != nullptr) {
2645 ALOGD("Forward VolumeShaper operation to track %p", track.get());
2646 (void)track->applyVolumeShaper(configuration, operation);
2647 }
2648 }
2649 }
Andy Hung39399b62017-04-21 15:07:45 -07002650 status = mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002651 }
Andy Hung39399b62017-04-21 15:07:45 -07002652 return status;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002653}
2654
2655sp<VolumeShaper::State> MediaPlayerService::AudioOutput::getVolumeShaperState(int id)
2656{
2657 Mutex::Autolock lock(mLock);
2658 if (mTrack != 0) {
2659 return mTrack->getVolumeShaperState(id);
Andy Hung4ef88d72017-02-21 19:47:53 -08002660 } else {
2661 return mVolumeHandler->getVolumeShaperState(id);
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002662 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002663}
2664
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002665size_t MediaPlayerService::AudioOutput::CallbackData::onMoreData(const AudioTrack::Buffer& buffer) {
2666 ALOGD("data callback");
2667 lock();
2668 sp<AudioOutput> me = getOutput();
2669 if (me == nullptr) {
2670 unlock();
2671 return 0;
2672 }
2673 size_t actualSize = (*me->mCallback)(
Atneya Nair03079272022-01-18 17:03:14 -05002674 me.get(), buffer.data(), buffer.size(), me->mCallbackCookie,
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002675 CB_EVENT_FILL_BUFFER);
2676
2677 // Log when no data is returned from the callback.
2678 // (1) We may have no data (especially with network streaming sources).
2679 // (2) We may have reached the EOS and the audio track is not stopped yet.
2680 // Note that AwesomePlayer/AudioPlayer will only return zero size when it reaches the EOS.
2681 // NuPlayerRenderer will return zero when it doesn't have data (it doesn't block to fill).
2682 //
2683 // This is a benign busy-wait, with the next data request generated 10 ms or more later;
2684 // nevertheless for power reasons, we don't want to see too many of these.
2685
Santiago Seifert578aeb52022-10-24 07:59:12 +00002686 ALOGV_IF(actualSize == 0 && buffer.size() > 0, "callbackwrapper: empty buffer returned");
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002687 unlock();
2688 return actualSize;
2689}
2690
2691void MediaPlayerService::AudioOutput::CallbackData::onStreamEnd() {
2692 lock();
2693 sp<AudioOutput> me = getOutput();
2694 if (me == nullptr) {
2695 unlock();
Marco Nelissen6b74d672012-02-28 16:07:44 -08002696 return;
2697 }
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002698 ALOGV("callbackwrapper: deliver EVENT_STREAM_END");
2699 (*me->mCallback)(me.get(), NULL /* buffer */, 0 /* size */,
2700 me->mCallbackCookie, CB_EVENT_STREAM_END);
2701 unlock();
2702}
Andreas Huber20111aa2009-07-14 16:56:47 -07002703
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002704
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002705void MediaPlayerService::AudioOutput::CallbackData::onNewIAudioTrack() {
2706 lock();
2707 sp<AudioOutput> me = getOutput();
2708 if (me == nullptr) {
2709 unlock();
2710 return;
Andreas Huber51c1e0e2011-04-04 11:43:40 -07002711 }
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002712 ALOGV("callbackwrapper: deliver EVENT_TEAR_DOWN");
2713 (*me->mCallback)(me.get(), NULL /* buffer */, 0 /* size */,
2714 me->mCallbackCookie, CB_EVENT_TEAR_DOWN);
2715 unlock();
2716}
Andreas Huber51c1e0e2011-04-04 11:43:40 -07002717
Atneya Nair4dc66dc2021-11-02 12:59:19 -04002718void MediaPlayerService::AudioOutput::CallbackData::onUnderrun() {
2719 // This occurs when there is no data available, typically
2720 // when there is a failure to supply data to the AudioTrack. It can also
2721 // occur in non-offloaded mode when the audio device comes out of standby.
2722 //
2723 // If an AudioTrack underruns it outputs silence. Since this happens suddenly
2724 // it may sound like an audible pop or glitch.
2725 //
2726 // The underrun event is sent once per track underrun; the condition is reset
2727 // when more data is sent to the AudioTrack.
2728 ALOGD("callbackwrapper: EVENT_UNDERRUN (discarded)");
2729
Andreas Huber20111aa2009-07-14 16:56:47 -07002730}
2731
Glenn Kastend848eb42016-03-08 13:42:11 -08002732audio_session_t MediaPlayerService::AudioOutput::getSessionId() const
Eric Laurent8c563ed2010-10-07 18:23:03 -07002733{
Andy Hungd1c74342015-07-07 16:54:23 -07002734 Mutex::Autolock lock(mLock);
Eric Laurent8c563ed2010-10-07 18:23:03 -07002735 return mSessionId;
2736}
2737
Eric Laurent6f59db12013-07-26 17:16:50 -07002738uint32_t MediaPlayerService::AudioOutput::getSampleRate() const
2739{
Andy Hungd1c74342015-07-07 16:54:23 -07002740 Mutex::Autolock lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -07002741 if (mTrack == 0) return 0;
2742 return mTrack->getSampleRate();
2743}
2744
Andy Hungf2c87b32016-04-07 19:49:29 -07002745int64_t MediaPlayerService::AudioOutput::getBufferDurationInUs() const
2746{
2747 Mutex::Autolock lock(mLock);
2748 if (mTrack == 0) {
2749 return 0;
2750 }
2751 int64_t duration;
2752 if (mTrack->getBufferDurationInUs(&duration) != OK) {
2753 return 0;
2754 }
2755 return duration;
2756}
2757
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002758////////////////////////////////////////////////////////////////////////////////
2759
2760struct CallbackThread : public Thread {
2761 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
2762 MediaPlayerBase::AudioSink::AudioCallback cb,
2763 void *cookie);
2764
2765protected:
2766 virtual ~CallbackThread();
2767
2768 virtual bool threadLoop();
2769
2770private:
2771 wp<MediaPlayerBase::AudioSink> mSink;
2772 MediaPlayerBase::AudioSink::AudioCallback mCallback;
2773 void *mCookie;
2774 void *mBuffer;
2775 size_t mBufferSize;
2776
2777 CallbackThread(const CallbackThread &);
2778 CallbackThread &operator=(const CallbackThread &);
2779};
2780
2781CallbackThread::CallbackThread(
2782 const wp<MediaPlayerBase::AudioSink> &sink,
2783 MediaPlayerBase::AudioSink::AudioCallback cb,
2784 void *cookie)
2785 : mSink(sink),
2786 mCallback(cb),
2787 mCookie(cookie),
2788 mBuffer(NULL),
2789 mBufferSize(0) {
2790}
2791
2792CallbackThread::~CallbackThread() {
2793 if (mBuffer) {
2794 free(mBuffer);
2795 mBuffer = NULL;
2796 }
2797}
2798
2799bool CallbackThread::threadLoop() {
2800 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
2801 if (sink == NULL) {
2802 return false;
2803 }
2804
2805 if (mBuffer == NULL) {
2806 mBufferSize = sink->bufferSize();
2807 mBuffer = malloc(mBufferSize);
2808 }
2809
2810 size_t actualSize =
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002811 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie,
2812 MediaPlayerBase::AudioSink::CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002813
2814 if (actualSize > 0) {
2815 sink->write(mBuffer, actualSize);
Andy Hunga31335a2014-08-20 17:37:59 -07002816 // Could return false on sink->write() error or short count.
2817 // Not necessarily appropriate but would work for AudioCache behavior.
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002818 }
2819
2820 return true;
2821}
2822
2823////////////////////////////////////////////////////////////////////////////////
2824
Chong Zhange5b9b692017-05-11 11:44:56 -07002825void MediaPlayerService::addBatteryData(uint32_t params) {
2826 mBatteryTracker.addBatteryData(params);
2827}
2828
2829status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
2830 return mBatteryTracker.pullBatteryData(reply);
2831}
2832
2833MediaPlayerService::BatteryTracker::BatteryTracker() {
2834 mBatteryAudio.refCount = 0;
2835 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2836 mBatteryAudio.deviceOn[i] = 0;
2837 mBatteryAudio.lastTime[i] = 0;
2838 mBatteryAudio.totalTime[i] = 0;
2839 }
2840 // speaker is on by default
2841 mBatteryAudio.deviceOn[SPEAKER] = 1;
2842
2843 // reset battery stats
2844 // if the mediaserver has crashed, battery stats could be left
2845 // in bad state, reset the state upon service start.
2846 BatteryNotifier::getInstance().noteResetVideo();
2847}
2848
2849void MediaPlayerService::BatteryTracker::addBatteryData(uint32_t params)
Gloria Wang7cf180c2011-02-19 18:37:57 -08002850{
2851 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002852
2853 int32_t time = systemTime() / 1000000L;
2854
2855 // change audio output devices. This notification comes from AudioFlinger
2856 if ((params & kBatteryDataSpeakerOn)
2857 || (params & kBatteryDataOtherAudioDeviceOn)) {
2858
2859 int deviceOn[NUM_AUDIO_DEVICES];
2860 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2861 deviceOn[i] = 0;
2862 }
2863
2864 if ((params & kBatteryDataSpeakerOn)
2865 && (params & kBatteryDataOtherAudioDeviceOn)) {
2866 deviceOn[SPEAKER_AND_OTHER] = 1;
2867 } else if (params & kBatteryDataSpeakerOn) {
2868 deviceOn[SPEAKER] = 1;
2869 } else {
2870 deviceOn[OTHER_AUDIO_DEVICE] = 1;
2871 }
2872
2873 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2874 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
2875
2876 if (mBatteryAudio.refCount > 0) { // if playing audio
2877 if (!deviceOn[i]) {
2878 mBatteryAudio.lastTime[i] += time;
2879 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2880 mBatteryAudio.lastTime[i] = 0;
2881 } else {
2882 mBatteryAudio.lastTime[i] = 0 - time;
2883 }
2884 }
2885
2886 mBatteryAudio.deviceOn[i] = deviceOn[i];
2887 }
2888 }
2889 return;
2890 }
2891
Marco Nelissenb7848f12014-12-04 08:57:56 -08002892 // an audio stream is started
Gloria Wang9ee159b2011-02-24 14:51:45 -08002893 if (params & kBatteryDataAudioFlingerStart) {
2894 // record the start time only if currently no other audio
2895 // is being played
2896 if (mBatteryAudio.refCount == 0) {
2897 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2898 if (mBatteryAudio.deviceOn[i]) {
2899 mBatteryAudio.lastTime[i] -= time;
2900 }
2901 }
2902 }
2903
2904 mBatteryAudio.refCount ++;
2905 return;
2906
2907 } else if (params & kBatteryDataAudioFlingerStop) {
2908 if (mBatteryAudio.refCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002909 ALOGW("Battery track warning: refCount is <= 0");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002910 return;
2911 }
2912
2913 // record the stop time only if currently this is the only
2914 // audio being played
2915 if (mBatteryAudio.refCount == 1) {
2916 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2917 if (mBatteryAudio.deviceOn[i]) {
2918 mBatteryAudio.lastTime[i] += time;
2919 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2920 mBatteryAudio.lastTime[i] = 0;
2921 }
2922 }
2923 }
2924
2925 mBatteryAudio.refCount --;
2926 return;
2927 }
2928
Andy Hung1afd0982016-11-08 16:13:44 -08002929 uid_t uid = IPCThreadState::self()->getCallingUid();
Gloria Wang7cf180c2011-02-19 18:37:57 -08002930 if (uid == AID_MEDIA) {
2931 return;
2932 }
2933 int index = mBatteryData.indexOfKey(uid);
Gloria Wang7cf180c2011-02-19 18:37:57 -08002934
2935 if (index < 0) { // create a new entry for this UID
2936 BatteryUsageInfo info;
2937 info.audioTotalTime = 0;
2938 info.videoTotalTime = 0;
2939 info.audioLastTime = 0;
2940 info.videoLastTime = 0;
2941 info.refCount = 0;
2942
Gloria Wang9ee159b2011-02-24 14:51:45 -08002943 if (mBatteryData.add(uid, info) == NO_MEMORY) {
Steve Block29357bc2012-01-06 19:20:56 +00002944 ALOGE("Battery track error: no memory for new app");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002945 return;
2946 }
Gloria Wang7cf180c2011-02-19 18:37:57 -08002947 }
2948
2949 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
2950
2951 if (params & kBatteryDataCodecStarted) {
2952 if (params & kBatteryDataTrackAudio) {
2953 info.audioLastTime -= time;
2954 info.refCount ++;
2955 }
2956 if (params & kBatteryDataTrackVideo) {
2957 info.videoLastTime -= time;
2958 info.refCount ++;
2959 }
2960 } else {
2961 if (info.refCount == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002962 ALOGW("Battery track warning: refCount is already 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002963 return;
2964 } else if (info.refCount < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00002965 ALOGE("Battery track error: refCount < 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002966 mBatteryData.removeItem(uid);
2967 return;
2968 }
2969
2970 if (params & kBatteryDataTrackAudio) {
2971 info.audioLastTime += time;
2972 info.refCount --;
2973 }
2974 if (params & kBatteryDataTrackVideo) {
2975 info.videoLastTime += time;
2976 info.refCount --;
2977 }
2978
2979 // no stream is being played by this UID
2980 if (info.refCount == 0) {
2981 info.audioTotalTime += info.audioLastTime;
2982 info.audioLastTime = 0;
2983 info.videoTotalTime += info.videoLastTime;
2984 info.videoLastTime = 0;
2985 }
2986 }
2987}
2988
Chong Zhange5b9b692017-05-11 11:44:56 -07002989status_t MediaPlayerService::BatteryTracker::pullBatteryData(Parcel* reply) {
Gloria Wang7cf180c2011-02-19 18:37:57 -08002990 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002991
2992 // audio output devices usage
2993 int32_t time = systemTime() / 1000000L; //in ms
2994 int32_t totalTime;
2995
2996 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2997 totalTime = mBatteryAudio.totalTime[i];
2998
2999 if (mBatteryAudio.deviceOn[i]
3000 && (mBatteryAudio.lastTime[i] != 0)) {
3001 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
3002 totalTime += tmpTime;
3003 }
3004
3005 reply->writeInt32(totalTime);
3006 // reset the total time
3007 mBatteryAudio.totalTime[i] = 0;
3008 }
3009
3010 // codec usage
Gloria Wang7cf180c2011-02-19 18:37:57 -08003011 BatteryUsageInfo info;
3012 int size = mBatteryData.size();
3013
3014 reply->writeInt32(size);
3015 int i = 0;
3016
3017 while (i < size) {
3018 info = mBatteryData.valueAt(i);
3019
3020 reply->writeInt32(mBatteryData.keyAt(i)); //UID
3021 reply->writeInt32(info.audioTotalTime);
3022 reply->writeInt32(info.videoTotalTime);
3023
3024 info.audioTotalTime = 0;
3025 info.videoTotalTime = 0;
3026
3027 // remove the UID entry where no stream is being played
3028 if (info.refCount <= 0) {
3029 mBatteryData.removeItemsAt(i);
3030 size --;
3031 i --;
3032 }
3033 i++;
3034 }
3035 return NO_ERROR;
3036}
nikoa64c8c72009-07-20 15:07:26 -07003037} // namespace android