blob: 81ffcbc1de3145d5d2dbc2a6a2919dbbe07023f7 [file] [log] [blame]
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001/*
2**
3** Copyright 2008, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18// Proxy for media player implementations
19
20//#define LOG_NDEBUG 0
21#define LOG_TAG "MediaPlayerService"
22#include <utils/Log.h>
23
24#include <sys/types.h>
25#include <sys/stat.h>
Gloria Wang7cf180c2011-02-19 18:37:57 -080026#include <sys/time.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080027#include <dirent.h>
28#include <unistd.h>
29
30#include <string.h>
Mathias Agopian6f74b0c2009-06-03 17:32:49 -070031
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080032#include <cutils/atomic.h>
Nicolas Catania14d27472009-07-13 14:37:49 -070033#include <cutils/properties.h> // for property_get
Mathias Agopian6f74b0c2009-06-03 17:32:49 -070034
35#include <utils/misc.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080036
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -070037#include <android/hardware/media/omx/1.0/IOmx.h>
Marco Nelissena0c98412019-03-29 12:10:19 -070038#include <android/hardware/media/c2/1.0/IComponentStore.h>
Mathias Agopian75624082009-05-19 19:08:10 -070039#include <binder/IPCThreadState.h>
40#include <binder/IServiceManager.h>
41#include <binder/MemoryHeapBase.h>
42#include <binder/MemoryBase.h>
Mathias Agopianb1e7cd12013-02-14 17:11:27 -080043#include <gui/Surface.h>
Nicolas Catania1d187f12009-05-12 23:25:55 -070044#include <utils/Errors.h> // for status_t
45#include <utils/String8.h>
Marco Nelissen10dbb8e2009-09-20 10:42:13 -070046#include <utils/SystemClock.h>
Lajos Molnar06ad1522014-08-28 07:27:44 -070047#include <utils/Timers.h>
Nicolas Catania1d187f12009-05-12 23:25:55 -070048#include <utils/Vector.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080049
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -070050#include <codec2/hidl/client.h>
Marco Nelissen42057ce2019-09-23 12:15:57 -070051#include <datasource/HTTPBase.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080052#include <media/IMediaHTTPService.h>
Jeff Brown2013a542012-09-04 21:38:42 -070053#include <media/IRemoteDisplay.h>
54#include <media/IRemoteDisplayClient.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080055#include <media/MediaPlayerInterface.h>
56#include <media/mediarecorder.h>
57#include <media/MediaMetadataRetrieverInterface.h>
nikoa64c8c72009-07-20 15:07:26 -070058#include <media/Metadata.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080059#include <media/AudioTrack.h>
James Dong8635b7b2011-03-14 17:01:38 -070060#include <media/MemoryLeakTrackUtil.h>
Dongwon Kangd91dc5a2017-10-10 00:07:09 -070061#include <media/stagefright/InterfaceUtils.h>
Wonsik Kim6f675772019-08-20 17:06:53 -070062#include <media/stagefright/MediaCodecConstants.h>
Lajos Molnar1381d4b2014-08-07 15:18:35 -070063#include <media/stagefright/MediaCodecList.h>
Eric Laurent9cb839a2011-09-27 09:48:56 -070064#include <media/stagefright/MediaErrors.h>
Marco Nelissen83b0fd92015-09-16 13:48:07 -070065#include <media/stagefright/Utils.h>
Marco Nelissen42057ce2019-09-23 12:15:57 -070066#include <media/stagefright/FoundationUtils.h>
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +010067#include <media/stagefright/foundation/ADebug.h>
Marco Nelissenf09611f2015-02-13 14:12:42 -080068#include <media/stagefright/foundation/ALooperRoster.h>
Chong Zhang181fd9b2017-02-16 15:53:03 -080069#include <media/stagefright/SurfaceUtils.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070070#include <mediautils/BatteryNotifier.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080071
Andy Hung53541292016-04-13 16:48:51 -070072#include <memunreachable/memunreachable.h>
Dima Zavin64760242011-05-11 14:15:23 -070073#include <system/audio.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070074
Gloria Wang7cf180c2011-02-19 18:37:57 -080075#include <private/android_filesystem_config.h>
76
James Dong559bf282012-03-28 10:29:14 -070077#include "ActivityManager.h"
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080078#include "MediaRecorderClient.h"
79#include "MediaPlayerService.h"
80#include "MetadataRetrieverClient.h"
John Grossman44a7e422012-06-21 17:29:24 -070081#include "MediaPlayerFactory.h"
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080082
Nicolas Catania14d27472009-07-13 14:37:49 -070083#include "TestPlayerStub.h"
Andreas Huberf9334412010-12-15 15:17:42 -080084#include "nuplayer/NuPlayerDriver.h"
Andreas Huber20111aa2009-07-14 16:56:47 -070085
Andreas Hubered3e3e02012-03-26 11:13:27 -070086
Wei Jia502c2f42017-07-13 17:47:56 -070087static const int kDumpLockRetries = 50;
88static const int kDumpLockSleepUs = 20000;
89
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070090namespace {
nikoa64c8c72009-07-20 15:07:26 -070091using android::media::Metadata;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070092using android::status_t;
93using android::OK;
94using android::BAD_VALUE;
95using android::NOT_ENOUGH_DATA;
96using android::Parcel;
Ivan Lozano8cf3a072017-08-09 09:01:33 -070097using android::media::VolumeShaper;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070098
99// Max number of entries in the filter.
100const int kMaxFilterSize = 64; // I pulled that out of thin air.
101
Andy Hungff874dc2016-04-11 16:49:09 -0700102const float kMaxRequiredSpeed = 8.0f; // for PCM tracks allow up to 8x speedup.
103
nikoa64c8c72009-07-20 15:07:26 -0700104// FIXME: Move all the metadata related function in the Metadata.cpp
nikod608a812009-07-16 16:39:53 -0700105
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700106
107// Unmarshall a filter from a Parcel.
108// Filter format in a parcel:
109//
110// 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
111// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
112// | number of entries (n) |
113// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
114// | metadata type 1 |
115// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
116// | metadata type 2 |
117// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
118// ....
119// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
120// | metadata type n |
121// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
122//
123// @param p Parcel that should start with a filter.
124// @param[out] filter On exit contains the list of metadata type to be
125// filtered.
126// @param[out] status On exit contains the status code to be returned.
127// @return true if the parcel starts with a valid filter.
128bool unmarshallFilter(const Parcel& p,
nikoa64c8c72009-07-20 15:07:26 -0700129 Metadata::Filter *filter,
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700130 status_t *status)
131{
Nicolas Catania48290382009-07-10 13:53:06 -0700132 int32_t val;
133 if (p.readInt32(&val) != OK)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700134 {
Steve Block29357bc2012-01-06 19:20:56 +0000135 ALOGE("Failed to read filter's length");
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700136 *status = NOT_ENOUGH_DATA;
137 return false;
138 }
139
Nicolas Catania48290382009-07-10 13:53:06 -0700140 if( val > kMaxFilterSize || val < 0)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700141 {
Steve Block29357bc2012-01-06 19:20:56 +0000142 ALOGE("Invalid filter len %d", val);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700143 *status = BAD_VALUE;
144 return false;
145 }
146
Nicolas Catania48290382009-07-10 13:53:06 -0700147 const size_t num = val;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700148
149 filter->clear();
Nicolas Catania48290382009-07-10 13:53:06 -0700150 filter->setCapacity(num);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700151
nikoa64c8c72009-07-20 15:07:26 -0700152 size_t size = num * sizeof(Metadata::Type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700153
Nicolas Catania48290382009-07-10 13:53:06 -0700154
155 if (p.dataAvail() < size)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700156 {
Andy Hung833b4752016-04-04 17:15:48 -0700157 ALOGE("Filter too short expected %zu but got %zu", size, p.dataAvail());
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700158 *status = NOT_ENOUGH_DATA;
159 return false;
160 }
161
nikoa64c8c72009-07-20 15:07:26 -0700162 const Metadata::Type *data =
163 static_cast<const Metadata::Type*>(p.readInplace(size));
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700164
Nicolas Catania48290382009-07-10 13:53:06 -0700165 if (NULL == data)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700166 {
Steve Block29357bc2012-01-06 19:20:56 +0000167 ALOGE("Filter had no data");
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700168 *status = BAD_VALUE;
169 return false;
170 }
171
172 // TODO: The stl impl of vector would be more efficient here
173 // because it degenerates into a memcpy on pod types. Try to
174 // replace later or use stl::set.
Nicolas Catania48290382009-07-10 13:53:06 -0700175 for (size_t i = 0; i < num; ++i)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700176 {
Nicolas Catania48290382009-07-10 13:53:06 -0700177 filter->add(*data);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700178 ++data;
179 }
180 *status = OK;
181 return true;
182}
183
Nicolas Catania48290382009-07-10 13:53:06 -0700184// @param filter Of metadata type.
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700185// @param val To be searched.
186// @return true if a match was found.
nikoa64c8c72009-07-20 15:07:26 -0700187bool findMetadata(const Metadata::Filter& filter, const int32_t val)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700188{
189 // Deal with empty and ANY right away
190 if (filter.isEmpty()) return false;
nikoa64c8c72009-07-20 15:07:26 -0700191 if (filter[0] == Metadata::kAny) return true;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700192
Nicolas Catania48290382009-07-10 13:53:06 -0700193 return filter.indexOf(val) >= 0;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700194}
195
196} // anonymous namespace
197
198
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700199namespace {
200using android::Parcel;
201using android::String16;
202
203// marshalling tag indicating flattened utf16 tags
204// keep in sync with frameworks/base/media/java/android/media/AudioAttributes.java
205const int32_t kAudioAttributesMarshallTagFlattenTags = 1;
206
207// Audio attributes format in a parcel:
208//
209// 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
210// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
211// | usage |
212// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
213// | content_type |
214// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Hyejin Kim4f418f92014-09-05 15:50:03 +0900215// | source |
216// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700217// | flags |
218// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
219// | kAudioAttributesMarshallTagFlattenTags | // ignore tags if not found
220// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
221// | flattened tags in UTF16 |
222// | ... |
223// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
224//
225// @param p Parcel that contains audio attributes.
226// @param[out] attributes On exit points to an initialized audio_attributes_t structure
227// @param[out] status On exit contains the status code to be returned.
228void unmarshallAudioAttributes(const Parcel& parcel, audio_attributes_t *attributes)
229{
230 attributes->usage = (audio_usage_t) parcel.readInt32();
231 attributes->content_type = (audio_content_type_t) parcel.readInt32();
Hyejin Kim4f418f92014-09-05 15:50:03 +0900232 attributes->source = (audio_source_t) parcel.readInt32();
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700233 attributes->flags = (audio_flags_mask_t) parcel.readInt32();
234 const bool hasFlattenedTag = (parcel.readInt32() == kAudioAttributesMarshallTagFlattenTags);
235 if (hasFlattenedTag) {
236 // the tags are UTF16, convert to UTF8
237 String16 tags = parcel.readString16();
238 ssize_t realTagSize = utf16_to_utf8_length(tags.string(), tags.size());
239 if (realTagSize <= 0) {
240 strcpy(attributes->tags, "");
241 } else {
242 // copy the flattened string into the attributes as the destination for the conversion:
243 // copying array size -1, array for tags was calloc'd, no need to NULL-terminate it
244 size_t tagSize = realTagSize > AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 ?
245 AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 : realTagSize;
Sergio Giro1d3f4272016-06-28 18:24:52 +0100246 utf16_to_utf8(tags.string(), tagSize, attributes->tags,
247 sizeof(attributes->tags) / sizeof(attributes->tags[0]));
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700248 }
249 } else {
250 ALOGE("unmarshallAudioAttributes() received unflattened tags, ignoring tag values");
251 strcpy(attributes->tags, "");
252 }
253}
254} // anonymous namespace
255
256
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800257namespace android {
258
Marco Nelissenf09611f2015-02-13 14:12:42 -0800259extern ALooperRoster gLooperRoster;
260
261
Dave Burked681bbb2011-08-30 14:39:17 +0100262static bool checkPermission(const char* permissionString) {
Dave Burked681bbb2011-08-30 14:39:17 +0100263 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
264 bool ok = checkCallingPermission(String16(permissionString));
Steve Block29357bc2012-01-06 19:20:56 +0000265 if (!ok) ALOGE("Request requires %s", permissionString);
Dave Burked681bbb2011-08-30 14:39:17 +0100266 return ok;
267}
268
Wonsik Kim6f675772019-08-20 17:06:53 -0700269static void dumpCodecDetails(int fd, const sp<IMediaCodecList> &codecList, bool queryDecoders) {
270 const size_t SIZE = 256;
271 char buffer[SIZE];
272 String8 result;
273
274 const char *codecType = queryDecoders? "Decoder" : "Encoder";
275 snprintf(buffer, SIZE - 1, "\n%s infos by media types:\n"
276 "=============================\n", codecType);
277 result.append(buffer);
278
279 size_t numCodecs = codecList->countCodecs();
280
281 // gather all media types supported by codec class, and link to codecs that support them
282 KeyedVector<AString, Vector<sp<MediaCodecInfo>>> allMediaTypes;
283 for (size_t codec_ix = 0; codec_ix < numCodecs; ++codec_ix) {
284 sp<MediaCodecInfo> info = codecList->getCodecInfo(codec_ix);
285 if (info->isEncoder() == !queryDecoders) {
286 Vector<AString> supportedMediaTypes;
287 info->getSupportedMediaTypes(&supportedMediaTypes);
288 if (!supportedMediaTypes.size()) {
289 snprintf(buffer, SIZE - 1, "warning: %s does not support any media types\n",
290 info->getCodecName());
291 result.append(buffer);
292 } else {
293 for (const AString &mediaType : supportedMediaTypes) {
294 if (allMediaTypes.indexOfKey(mediaType) < 0) {
295 allMediaTypes.add(mediaType, Vector<sp<MediaCodecInfo>>());
296 }
297 allMediaTypes.editValueFor(mediaType).add(info);
298 }
299 }
300 }
301 }
302
303 KeyedVector<AString, bool> visitedCodecs;
304 for (size_t type_ix = 0; type_ix < allMediaTypes.size(); ++type_ix) {
305 const AString &mediaType = allMediaTypes.keyAt(type_ix);
306 snprintf(buffer, SIZE - 1, "\nMedia type '%s':\n", mediaType.c_str());
307 result.append(buffer);
308
309 for (const sp<MediaCodecInfo> &info : allMediaTypes.valueAt(type_ix)) {
310 sp<MediaCodecInfo::Capabilities> caps = info->getCapabilitiesFor(mediaType.c_str());
311 if (caps == NULL) {
312 snprintf(buffer, SIZE - 1, "warning: %s does not have capabilities for type %s\n",
313 info->getCodecName(), mediaType.c_str());
314 result.append(buffer);
315 continue;
316 }
317 snprintf(buffer, SIZE - 1, " %s \"%s\" supports\n",
318 codecType, info->getCodecName());
319 result.append(buffer);
320
321 auto printList = [&](const char *type, const Vector<AString> &values){
322 snprintf(buffer, SIZE - 1, " %s: [", type);
323 result.append(buffer);
324 for (size_t j = 0; j < values.size(); ++j) {
325 snprintf(buffer, SIZE - 1, "\n %s%s", values[j].c_str(),
326 j == values.size() - 1 ? " " : ",");
327 result.append(buffer);
328 }
329 result.append("]\n");
330 };
331
332 if (visitedCodecs.indexOfKey(info->getCodecName()) < 0) {
333 visitedCodecs.add(info->getCodecName(), true);
334 {
335 Vector<AString> aliases;
336 info->getAliases(&aliases);
337 // quote alias
338 for (AString &alias : aliases) {
339 alias.insert("\"", 1, 0);
340 alias.append('"');
341 }
342 printList("aliases", aliases);
343 }
344 {
345 uint32_t attrs = info->getAttributes();
346 Vector<AString> list;
347 list.add(AStringPrintf("encoder: %d",
348 !!(attrs & MediaCodecInfo::kFlagIsEncoder)));
349 list.add(AStringPrintf("vendor: %d",
350 !!(attrs & MediaCodecInfo::kFlagIsVendor)));
351 list.add(AStringPrintf("software-only: %d",
352 !!(attrs & MediaCodecInfo::kFlagIsSoftwareOnly)));
353 list.add(AStringPrintf("hw-accelerated: %d",
354 !!(attrs & MediaCodecInfo::kFlagIsHardwareAccelerated)));
355 printList(AStringPrintf("attributes: %#x", attrs).c_str(), list);
356 }
357
358 snprintf(buffer, SIZE - 1, " owner: \"%s\"\n", info->getOwnerName());
359 result.append(buffer);
360 snprintf(buffer, SIZE - 1, " rank: %u\n", info->getRank());
361 result.append(buffer);
362 } else {
363 result.append(" aliases, attributes, owner, rank: see above\n");
364 }
365
366 {
367 Vector<AString> list;
368 Vector<MediaCodecInfo::ProfileLevel> profileLevels;
369 caps->getSupportedProfileLevels(&profileLevels);
370 for (const MediaCodecInfo::ProfileLevel &pl : profileLevels) {
371 const char *niceProfile =
372 mediaType.equalsIgnoreCase(MIMETYPE_AUDIO_AAC)
373 ? asString_AACObject(pl.mProfile) :
374 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_MPEG2)
375 ? asString_MPEG2Profile(pl.mProfile) :
376 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_H263)
377 ? asString_H263Profile(pl.mProfile) :
378 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_MPEG4)
379 ? asString_MPEG4Profile(pl.mProfile) :
380 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_AVC)
381 ? asString_AVCProfile(pl.mProfile) :
382 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_VP8)
383 ? asString_VP8Profile(pl.mProfile) :
384 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_HEVC)
385 ? asString_HEVCProfile(pl.mProfile) :
386 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_VP9)
387 ? asString_VP9Profile(pl.mProfile) :
388 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_AV1)
389 ? asString_AV1Profile(pl.mProfile) : "??";
390 const char *niceLevel =
391 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_MPEG2)
392 ? asString_MPEG2Level(pl.mLevel) :
393 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_H263)
394 ? asString_H263Level(pl.mLevel) :
395 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_MPEG4)
396 ? asString_MPEG4Level(pl.mLevel) :
397 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_AVC)
398 ? asString_AVCLevel(pl.mLevel) :
399 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_VP8)
400 ? asString_VP8Level(pl.mLevel) :
401 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_HEVC)
402 ? asString_HEVCTierLevel(pl.mLevel) :
403 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_VP9)
404 ? asString_VP9Level(pl.mLevel) :
405 mediaType.equalsIgnoreCase(MIMETYPE_VIDEO_AV1)
406 ? asString_AV1Level(pl.mLevel) : "??";
407
408 list.add(AStringPrintf("% 5u/% 5u (%s/%s)",
409 pl.mProfile, pl.mLevel, niceProfile, niceLevel));
410 }
411 printList("profile/levels", list);
412 }
413
414 {
415 Vector<AString> list;
416 Vector<uint32_t> colors;
417 caps->getSupportedColorFormats(&colors);
418 for (uint32_t color : colors) {
419 list.add(AStringPrintf("%#x (%s)", color,
420 asString_ColorFormat((int32_t)color)));
421 }
422 printList("colors", list);
423 }
424
Wonsik Kimd579f3e2019-10-07 14:14:09 -0700425 result.append(" details: ");
426 result.append(caps->getDetails()->debugString(6).c_str());
427 result.append("\n");
Wonsik Kim6f675772019-08-20 17:06:53 -0700428 }
429 }
430 result.append("\n");
431 ::write(fd, result.string(), result.size());
432}
433
434
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800435// 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 -0800436/* static */ int MediaPlayerService::AudioOutput::mMinBufferCount = 4;
437/* static */ bool MediaPlayerService::AudioOutput::mIsOnEmulator = false;
438
439void MediaPlayerService::instantiate() {
440 defaultServiceManager()->addService(
441 String16("media.player"), new MediaPlayerService());
442}
443
444MediaPlayerService::MediaPlayerService()
445{
Steve Block3856b092011-10-20 11:56:00 +0100446 ALOGV("MediaPlayerService created");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800447 mNextConnId = 1;
Gloria Wang9ee159b2011-02-24 14:51:45 -0800448
John Grossman44a7e422012-06-21 17:29:24 -0700449 MediaPlayerFactory::registerBuiltinFactories();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800450}
451
452MediaPlayerService::~MediaPlayerService()
453{
Steve Block3856b092011-10-20 11:56:00 +0100454 ALOGV("MediaPlayerService destroyed");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800455}
456
Svet Ganovbe71aa22015-04-28 12:06:02 -0700457sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(const String16 &opPackageName)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800458{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800459 pid_t pid = IPCThreadState::self()->getCallingPid();
Svet Ganovbe71aa22015-04-28 12:06:02 -0700460 sp<MediaRecorderClient> recorder = new MediaRecorderClient(this, pid, opPackageName);
Gloria Wangdac6a312009-10-29 15:46:37 -0700461 wp<MediaRecorderClient> w = recorder;
462 Mutex::Autolock lock(mLock);
463 mMediaRecorderClients.add(w);
Steve Block3856b092011-10-20 11:56:00 +0100464 ALOGV("Create new media recorder client from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800465 return recorder;
466}
467
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -0700468void MediaPlayerService::removeMediaRecorderClient(const wp<MediaRecorderClient>& client)
Gloria Wangdac6a312009-10-29 15:46:37 -0700469{
470 Mutex::Autolock lock(mLock);
471 mMediaRecorderClients.remove(client);
Steve Block3856b092011-10-20 11:56:00 +0100472 ALOGV("Delete media recorder client");
Gloria Wangdac6a312009-10-29 15:46:37 -0700473}
474
Glenn Kastenf37971f2012-02-03 11:06:53 -0800475sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800476{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800477 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800478 sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
Steve Block3856b092011-10-20 11:56:00 +0100479 ALOGV("Create new media retriever from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800480 return retriever;
481}
482
Glenn Kastenf37971f2012-02-03 11:06:53 -0800483sp<IMediaPlayer> MediaPlayerService::create(const sp<IMediaPlayerClient>& client,
Glenn Kastend848eb42016-03-08 13:42:11 -0800484 audio_session_t audioSessionId)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800485{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800486 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800487 int32_t connId = android_atomic_inc(&mNextConnId);
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700488
489 sp<Client> c = new Client(
490 this, pid, connId, client, audioSessionId,
491 IPCThreadState::self()->getCallingUid());
492
Steve Block3856b092011-10-20 11:56:00 +0100493 ALOGV("Create new client(%d) from pid %d, uid %d, ", connId, pid,
Dave Burked681bbb2011-08-30 14:39:17 +0100494 IPCThreadState::self()->getCallingUid());
495
496 wp<Client> w = c;
497 {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800498 Mutex::Autolock lock(mLock);
499 mClients.add(w);
500 }
Andreas Hubere2b10282010-11-23 11:41:34 -0800501 return c;
502}
503
Lajos Molnar1381d4b2014-08-07 15:18:35 -0700504sp<IMediaCodecList> MediaPlayerService::getCodecList() const {
505 return MediaCodecList::getLocalInstance();
506}
507
Jeff Brown2013a542012-09-04 21:38:42 -0700508sp<IRemoteDisplay> MediaPlayerService::listenForRemoteDisplay(
Chong Zhangd0a98fa2017-09-14 17:43:10 -0700509 const String16 &/*opPackageName*/,
510 const sp<IRemoteDisplayClient>& /*client*/,
511 const String8& /*iface*/) {
512 ALOGE("listenForRemoteDisplay is no longer supported!");
Jeff Brownaba33d52012-09-07 17:38:58 -0700513
Chong Zhangd0a98fa2017-09-14 17:43:10 -0700514 return NULL;
Jeff Brown2013a542012-09-04 21:38:42 -0700515}
516
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800517status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
518{
519 const size_t SIZE = 256;
520 char buffer[SIZE];
521 String8 result;
522
523 result.append(" AudioOutput\n");
524 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n",
525 mStreamType, mLeftVolume, mRightVolume);
526 result.append(buffer);
527 snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n",
Eric Laurentdb354e52012-03-05 17:27:11 -0800528 mMsecsPerFrame, (mTrack != 0) ? mTrack->latency() : -1);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800529 result.append(buffer);
Eric Laurent2beeb502010-07-16 07:43:46 -0700530 snprintf(buffer, 255, " aux effect id(%d), send level (%f)\n",
531 mAuxEffectId, mSendLevel);
532 result.append(buffer);
533
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800534 ::write(fd, result.string(), result.size());
535 if (mTrack != 0) {
536 mTrack->dump(fd, args);
537 }
538 return NO_ERROR;
539}
540
Lajos Molnar6d339f12015-04-17 16:15:53 -0700541status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800542{
543 const size_t SIZE = 256;
544 char buffer[SIZE];
545 String8 result;
546 result.append(" Client\n");
547 snprintf(buffer, 255, " pid(%d), connId(%d), status(%d), looping(%s)\n",
548 mPid, mConnId, mStatus, mLoop?"true": "false");
549 result.append(buffer);
Wei Jia502c2f42017-07-13 17:47:56 -0700550
551 sp<MediaPlayerBase> p;
552 sp<AudioOutput> audioOutput;
553 bool locked = false;
554 for (int i = 0; i < kDumpLockRetries; ++i) {
555 if (mLock.tryLock() == NO_ERROR) {
556 locked = true;
557 break;
558 }
559 usleep(kDumpLockSleepUs);
Andreas Hubera0b1d4b2011-06-07 15:52:25 -0700560 }
Wei Jia502c2f42017-07-13 17:47:56 -0700561
562 if (locked) {
563 p = mPlayer;
564 audioOutput = mAudioOutput;
565 mLock.unlock();
566 } else {
567 result.append(" lock is taken, no dump from player and audio output\n");
568 }
569 write(fd, result.string(), result.size());
570
571 if (p != NULL) {
572 p->dump(fd, args);
573 }
574 if (audioOutput != 0) {
575 audioOutput->dump(fd, args);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800576 }
577 write(fd, "\n", 1);
578 return NO_ERROR;
579}
580
Marco Nelissenf09611f2015-02-13 14:12:42 -0800581/**
582 * The only arguments this understands right now are -c, -von and -voff,
583 * which are parsed by ALooperRoster::dump()
584 */
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800585status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
586{
587 const size_t SIZE = 256;
588 char buffer[SIZE];
589 String8 result;
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530590 SortedVector< sp<Client> > clients; //to serialise the mutex unlock & client destruction.
591 SortedVector< sp<MediaRecorderClient> > mediaRecorderClients;
592
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800593 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
Wonsik Kim6f675772019-08-20 17:06:53 -0700594 snprintf(buffer, SIZE - 1, "Permission Denial: "
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800595 "can't dump MediaPlayerService from pid=%d, uid=%d\n",
596 IPCThreadState::self()->getCallingPid(),
597 IPCThreadState::self()->getCallingUid());
598 result.append(buffer);
599 } else {
600 Mutex::Autolock lock(mLock);
601 for (int i = 0, n = mClients.size(); i < n; ++i) {
602 sp<Client> c = mClients[i].promote();
603 if (c != 0) c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530604 clients.add(c);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800605 }
James Dongb9141222010-07-08 11:16:11 -0700606 if (mMediaRecorderClients.size() == 0) {
607 result.append(" No media recorder client\n\n");
608 } else {
609 for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
610 sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
James Donge579e282011-10-18 22:29:20 -0700611 if (c != 0) {
612 snprintf(buffer, 255, " MediaRecorderClient pid(%d)\n", c->mPid);
613 result.append(buffer);
614 write(fd, result.string(), result.size());
615 result = "\n";
616 c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530617 mediaRecorderClients.add(c);
James Donge579e282011-10-18 22:29:20 -0700618 }
James Dongb9141222010-07-08 11:16:11 -0700619 }
Gloria Wangdac6a312009-10-29 15:46:37 -0700620 }
621
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800622 result.append(" Files opened and/or mapped:\n");
Wonsik Kim6f675772019-08-20 17:06:53 -0700623 snprintf(buffer, SIZE - 1, "/proc/%d/maps", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800624 FILE *f = fopen(buffer, "r");
625 if (f) {
626 while (!feof(f)) {
Wonsik Kim6f675772019-08-20 17:06:53 -0700627 fgets(buffer, SIZE - 1, f);
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700628 if (strstr(buffer, " /storage/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800629 strstr(buffer, " /system/sounds/") ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700630 strstr(buffer, " /data/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800631 strstr(buffer, " /system/media/")) {
632 result.append(" ");
633 result.append(buffer);
634 }
635 }
636 fclose(f);
637 } else {
638 result.append("couldn't open ");
639 result.append(buffer);
640 result.append("\n");
641 }
642
Wonsik Kim6f675772019-08-20 17:06:53 -0700643 snprintf(buffer, SIZE - 1, "/proc/%d/fd", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800644 DIR *d = opendir(buffer);
645 if (d) {
646 struct dirent *ent;
647 while((ent = readdir(d)) != NULL) {
648 if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
Wonsik Kim6f675772019-08-20 17:06:53 -0700649 snprintf(buffer, SIZE - 1, "/proc/%d/fd/%s", getpid(), ent->d_name);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800650 struct stat s;
651 if (lstat(buffer, &s) == 0) {
652 if ((s.st_mode & S_IFMT) == S_IFLNK) {
653 char linkto[256];
654 int len = readlink(buffer, linkto, sizeof(linkto));
655 if(len > 0) {
656 if(len > 255) {
657 linkto[252] = '.';
658 linkto[253] = '.';
659 linkto[254] = '.';
660 linkto[255] = 0;
661 } else {
662 linkto[len] = 0;
663 }
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700664 if (strstr(linkto, "/storage/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800665 strstr(linkto, "/system/sounds/") == linkto ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700666 strstr(linkto, "/data/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800667 strstr(linkto, "/system/media/") == linkto) {
668 result.append(" ");
669 result.append(buffer);
670 result.append(" -> ");
671 result.append(linkto);
672 result.append("\n");
673 }
674 }
675 } else {
676 result.append(" unexpected type for ");
677 result.append(buffer);
678 result.append("\n");
679 }
680 }
681 }
682 }
683 closedir(d);
684 } else {
685 result.append("couldn't open ");
686 result.append(buffer);
687 result.append("\n");
688 }
689
Marco Nelissenf09611f2015-02-13 14:12:42 -0800690 gLooperRoster.dump(fd, args);
691
Wonsik Kimd579f3e2019-10-07 14:14:09 -0700692 sp<IMediaCodecList> codecList = getCodecList();
693 dumpCodecDetails(fd, codecList, true /* decoders */);
694 dumpCodecDetails(fd, codecList, false /* !decoders */);
695
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800696 bool dumpMem = false;
Andy Hung53541292016-04-13 16:48:51 -0700697 bool unreachableMemory = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800698 for (size_t i = 0; i < args.size(); i++) {
699 if (args[i] == String16("-m")) {
700 dumpMem = true;
Andy Hung53541292016-04-13 16:48:51 -0700701 } else if (args[i] == String16("--unreachable")) {
702 unreachableMemory = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800703 }
704 }
705 if (dumpMem) {
Andy Hung07b745e2016-05-23 16:21:07 -0700706 result.append("\nDumping memory:\n");
707 std::string s = dumpMemoryAddresses(100 /* limit */);
708 result.append(s.c_str(), s.size());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800709 }
Andy Hung53541292016-04-13 16:48:51 -0700710 if (unreachableMemory) {
711 result.append("\nDumping unreachable memory:\n");
712 // TODO - should limit be an argument parameter?
713 std::string s = GetUnreachableMemoryString(true /* contents */, 10000 /* limit */);
714 result.append(s.c_str(), s.size());
715 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800716 }
717 write(fd, result.string(), result.size());
Wonsik Kim6f675772019-08-20 17:06:53 -0700718
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800719 return NO_ERROR;
720}
721
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -0700722void MediaPlayerService::removeClient(const wp<Client>& client)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800723{
724 Mutex::Autolock lock(mLock);
725 mClients.remove(client);
726}
727
Robert Shihee0a0e32016-08-16 16:50:54 -0700728bool MediaPlayerService::hasClient(wp<Client> client)
729{
730 Mutex::Autolock lock(mLock);
731 return mClients.indexOf(client) != NAME_NOT_FOUND;
732}
733
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700734MediaPlayerService::Client::Client(
735 const sp<MediaPlayerService>& service, pid_t pid,
736 int32_t connId, const sp<IMediaPlayerClient>& client,
Glenn Kastend848eb42016-03-08 13:42:11 -0800737 audio_session_t audioSessionId, uid_t uid)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800738{
Steve Block3856b092011-10-20 11:56:00 +0100739 ALOGV("Client(%d) constructor", connId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800740 mPid = pid;
741 mConnId = connId;
742 mService = service;
743 mClient = client;
744 mLoop = false;
745 mStatus = NO_INIT;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700746 mAudioSessionId = audioSessionId;
Andy Hung1afd0982016-11-08 16:13:44 -0800747 mUid = uid;
John Grossmanc795b642012-02-22 15:38:35 -0800748 mRetransmitEndpointValid = false;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700749 mAudioAttributes = NULL;
Pawin Vongmasa082e4f72017-12-17 02:31:18 -0800750 mListener = new Listener(this);
Eric Laurenta514bdb2010-06-21 09:27:30 -0700751
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800752#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000753 ALOGD("create Antagonizer");
Pawin Vongmasa082e4f72017-12-17 02:31:18 -0800754 mAntagonizer = new Antagonizer(mListener);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800755#endif
756}
757
758MediaPlayerService::Client::~Client()
759{
Steve Block3856b092011-10-20 11:56:00 +0100760 ALOGV("Client(%d) destructor pid = %d", mConnId, mPid);
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700761 mAudioOutput.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800762 wp<Client> client(this);
763 disconnect();
764 mService->removeClient(client);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700765 if (mAudioAttributes != NULL) {
766 free(mAudioAttributes);
767 }
jiabin156c6872017-10-06 09:47:15 -0700768 mAudioDeviceUpdatedListener.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800769}
770
771void MediaPlayerService::Client::disconnect()
772{
Steve Block3856b092011-10-20 11:56:00 +0100773 ALOGV("disconnect(%d) from pid %d", mConnId, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800774 // grab local reference and clear main reference to prevent future
775 // access to object
776 sp<MediaPlayerBase> p;
777 {
778 Mutex::Autolock l(mLock);
779 p = mPlayer;
beanzdcfefde2012-11-05 09:51:43 +0800780 mClient.clear();
Wei Jia502c2f42017-07-13 17:47:56 -0700781 mPlayer.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800782 }
Andreas Huber20111aa2009-07-14 16:56:47 -0700783
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800784 // clear the notification to prevent callbacks to dead client
785 // and reset the player. We assume the player will serialize
786 // access to itself if necessary.
787 if (p != 0) {
Pawin Vongmasa082e4f72017-12-17 02:31:18 -0800788 p->setNotifyCallback(0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800789#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000790 ALOGD("kill Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800791 mAntagonizer->kill();
792#endif
793 p->reset();
794 }
795
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700796 {
797 Mutex::Autolock l(mLock);
798 disconnectNativeWindow_l();
799 }
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700800
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800801 IPCThreadState::self()->flushCommands();
802}
803
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800804sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
805{
806 // determine if we have the right player type
Wei Jia502c2f42017-07-13 17:47:56 -0700807 sp<MediaPlayerBase> p = getPlayer();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800808 if ((p != NULL) && (p->playerType() != playerType)) {
Steve Block3856b092011-10-20 11:56:00 +0100809 ALOGV("delete player");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800810 p.clear();
811 }
812 if (p == NULL) {
Pawin Vongmasa082e4f72017-12-17 02:31:18 -0800813 p = MediaPlayerFactory::createPlayer(playerType, mListener, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800814 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700815
Jason Simmonsdb29e522011-08-12 13:46:55 -0700816 if (p != NULL) {
Andy Hung1afd0982016-11-08 16:13:44 -0800817 p->setUID(mUid);
Jason Simmonsdb29e522011-08-12 13:46:55 -0700818 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700819
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800820 return p;
821}
822
jiabin156c6872017-10-06 09:47:15 -0700823void MediaPlayerService::Client::AudioDeviceUpdatedNotifier::onAudioDeviceUpdate(
824 audio_io_handle_t audioIo,
825 audio_port_handle_t deviceId) {
826 sp<MediaPlayerBase> listener = mListener.promote();
827 if (listener != NULL) {
828 listener->sendEvent(MEDIA_AUDIO_ROUTING_CHANGED, audioIo, deviceId);
829 } else {
830 ALOGW("listener for process %d death is gone", MEDIA_AUDIO_ROUTING_CHANGED);
831 }
832}
833
John Grossmanc795b642012-02-22 15:38:35 -0800834sp<MediaPlayerBase> MediaPlayerService::Client::setDataSource_pre(
835 player_type playerType)
836{
837 ALOGV("player type = %d", playerType);
838
839 // create the right type of player
840 sp<MediaPlayerBase> p = createPlayer(playerType);
841 if (p == NULL) {
842 return p;
843 }
844
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700845 std::vector<DeathNotifier> deathNotifiers;
846
847 // Listen to death of media.extractor service
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700848 sp<IServiceManager> sm = defaultServiceManager();
849 sp<IBinder> binder = sm->getService(String16("media.extractor"));
Marco Nelissen1b5a7ee2016-09-30 13:54:30 -0700850 if (binder == NULL) {
851 ALOGE("extractor service not available");
852 return NULL;
853 }
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700854 deathNotifiers.emplace_back(
855 binder, [l = wp<MediaPlayerBase>(p)]() {
856 sp<MediaPlayerBase> listener = l.promote();
857 if (listener) {
858 ALOGI("media.extractor died. Sending death notification.");
859 listener->sendEvent(MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED,
860 MEDIAEXTRACTOR_PROCESS_DEATH);
861 } else {
862 ALOGW("media.extractor died without a death handler.");
863 }
864 });
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700865
Marco Nelissena0c98412019-03-29 12:10:19 -0700866 {
867 using ::android::hidl::base::V1_0::IBase;
868
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700869 // Listen to death of OMX service
Marco Nelissena0c98412019-03-29 12:10:19 -0700870 {
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700871 sp<IBase> base = ::android::hardware::media::omx::V1_0::
872 IOmx::getService();
873 if (base == nullptr) {
Marco Nelissena0c98412019-03-29 12:10:19 -0700874 ALOGD("OMX service is not available");
875 } else {
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700876 deathNotifiers.emplace_back(
877 base, [l = wp<MediaPlayerBase>(p)]() {
878 sp<MediaPlayerBase> listener = l.promote();
879 if (listener) {
880 ALOGI("OMX service died. "
881 "Sending death notification.");
882 listener->sendEvent(
883 MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED,
884 MEDIACODEC_PROCESS_DEATH);
885 } else {
886 ALOGW("OMX service died without a death handler.");
887 }
888 });
Marco Nelissena0c98412019-03-29 12:10:19 -0700889 }
890 }
891
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700892 // Listen to death of Codec2 services
Marco Nelissena0c98412019-03-29 12:10:19 -0700893 {
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700894 for (std::shared_ptr<Codec2Client> const& client :
895 Codec2Client::CreateFromAllServices()) {
896 sp<IBase> base = client->getBase();
897 deathNotifiers.emplace_back(
898 base, [l = wp<MediaPlayerBase>(p),
899 name = std::string(client->getServiceName())]() {
900 sp<MediaPlayerBase> listener = l.promote();
901 if (listener) {
902 ALOGI("Codec2 service \"%s\" died. "
903 "Sending death notification.",
904 name.c_str());
905 listener->sendEvent(
906 MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED,
907 MEDIACODEC_PROCESS_DEATH);
908 } else {
909 ALOGW("Codec2 service \"%s\" died "
910 "without a death handler.",
911 name.c_str());
912 }
913 });
Marco Nelissene4da6c62019-04-01 15:01:41 -0700914 }
Marco Nelissena0c98412019-03-29 12:10:19 -0700915 }
Marco Nelissen1b5a7ee2016-09-30 13:54:30 -0700916 }
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700917
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700918 Mutex::Autolock lock(mLock);
919
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700920 mDeathNotifiers.clear();
921 mDeathNotifiers.swap(deathNotifiers);
jiabin156c6872017-10-06 09:47:15 -0700922 mAudioDeviceUpdatedListener = new AudioDeviceUpdatedNotifier(p);
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700923
John Grossmanc795b642012-02-22 15:38:35 -0800924 if (!p->hardwareOutput()) {
Marco Nelissend457c972014-02-11 08:47:07 -0800925 mAudioOutput = new AudioOutput(mAudioSessionId, IPCThreadState::self()->getCallingUid(),
jiabin156c6872017-10-06 09:47:15 -0700926 mPid, mAudioAttributes, mAudioDeviceUpdatedListener);
John Grossmanc795b642012-02-22 15:38:35 -0800927 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
928 }
929
930 return p;
931}
932
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700933status_t MediaPlayerService::Client::setDataSource_post(
John Grossmanc795b642012-02-22 15:38:35 -0800934 const sp<MediaPlayerBase>& p,
935 status_t status)
936{
937 ALOGV(" setDataSource");
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700938 if (status != OK) {
939 ALOGE(" error: %d", status);
940 return status;
John Grossmanc795b642012-02-22 15:38:35 -0800941 }
942
943 // Set the re-transmission endpoint if one was chosen.
944 if (mRetransmitEndpointValid) {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700945 status = p->setRetransmitEndpoint(&mRetransmitEndpoint);
946 if (status != NO_ERROR) {
947 ALOGE("setRetransmitEndpoint error: %d", status);
John Grossmanc795b642012-02-22 15:38:35 -0800948 }
949 }
950
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700951 if (status == OK) {
952 Mutex::Autolock lock(mLock);
John Grossmanc795b642012-02-22 15:38:35 -0800953 mPlayer = p;
954 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700955 return status;
John Grossmanc795b642012-02-22 15:38:35 -0800956}
957
Andreas Huber2db84552010-01-28 11:19:57 -0800958status_t MediaPlayerService::Client::setDataSource(
Andreas Huber1b86fe02014-01-29 11:13:26 -0800959 const sp<IMediaHTTPService> &httpService,
960 const char *url,
961 const KeyedVector<String8, String8> *headers)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800962{
Steve Block3856b092011-10-20 11:56:00 +0100963 ALOGV("setDataSource(%s)", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800964 if (url == NULL)
965 return UNKNOWN_ERROR;
966
Dave Burked681bbb2011-08-30 14:39:17 +0100967 if ((strncmp(url, "http://", 7) == 0) ||
968 (strncmp(url, "https://", 8) == 0) ||
969 (strncmp(url, "rtsp://", 7) == 0)) {
970 if (!checkPermission("android.permission.INTERNET")) {
971 return PERMISSION_DENIED;
972 }
973 }
974
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800975 if (strncmp(url, "content://", 10) == 0) {
976 // get a filedescriptor for the content Uri and
977 // pass it to the setDataSource(fd) method
978
979 String16 url16(url);
980 int fd = android::openContentProviderFile(url16);
981 if (fd < 0)
982 {
Steve Block29357bc2012-01-06 19:20:56 +0000983 ALOGE("Couldn't open fd for %s", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800984 return UNKNOWN_ERROR;
985 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700986 status_t status = setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800987 close(fd);
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700988 return mStatus = status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800989 } else {
John Grossman44a7e422012-06-21 17:29:24 -0700990 player_type playerType = MediaPlayerFactory::getPlayerType(this, url);
John Grossmanc795b642012-02-22 15:38:35 -0800991 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
992 if (p == NULL) {
993 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800994 }
995
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700996 return mStatus =
997 setDataSource_post(
998 p, p->setDataSource(httpService, url, headers));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800999 }
1000}
1001
1002status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
1003{
Marco Nelissen83b0fd92015-09-16 13:48:07 -07001004 ALOGV("setDataSource fd=%d (%s), offset=%lld, length=%lld",
1005 fd, nameForFd(fd).c_str(), (long long) offset, (long long) length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001006 struct stat sb;
1007 int ret = fstat(fd, &sb);
1008 if (ret != 0) {
Steve Block29357bc2012-01-06 19:20:56 +00001009 ALOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001010 return UNKNOWN_ERROR;
1011 }
1012
Andy Hung833b4752016-04-04 17:15:48 -07001013 ALOGV("st_dev = %llu", static_cast<unsigned long long>(sb.st_dev));
Steve Block3856b092011-10-20 11:56:00 +01001014 ALOGV("st_mode = %u", sb.st_mode);
Mark Salyzyn77342f72014-06-18 16:31:32 -07001015 ALOGV("st_uid = %lu", static_cast<unsigned long>(sb.st_uid));
1016 ALOGV("st_gid = %lu", static_cast<unsigned long>(sb.st_gid));
Andy Hung833b4752016-04-04 17:15:48 -07001017 ALOGV("st_size = %llu", static_cast<unsigned long long>(sb.st_size));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001018
1019 if (offset >= sb.st_size) {
Steve Block29357bc2012-01-06 19:20:56 +00001020 ALOGE("offset error");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001021 return UNKNOWN_ERROR;
1022 }
1023 if (offset + length > sb.st_size) {
1024 length = sb.st_size - offset;
Andy Hung833b4752016-04-04 17:15:48 -07001025 ALOGV("calculated length = %lld", (long long)length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001026 }
1027
John Grossman44a7e422012-06-21 17:29:24 -07001028 player_type playerType = MediaPlayerFactory::getPlayerType(this,
1029 fd,
1030 offset,
1031 length);
John Grossmanc795b642012-02-22 15:38:35 -08001032 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
1033 if (p == NULL) {
1034 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001035 }
1036
1037 // now set data source
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001038 return mStatus = setDataSource_post(p, p->setDataSource(fd, offset, length));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001039}
1040
Andreas Hubere2b10282010-11-23 11:41:34 -08001041status_t MediaPlayerService::Client::setDataSource(
1042 const sp<IStreamSource> &source) {
1043 // create the right type of player
John Grossman44a7e422012-06-21 17:29:24 -07001044 player_type playerType = MediaPlayerFactory::getPlayerType(this, source);
John Grossmanc795b642012-02-22 15:38:35 -08001045 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
Andreas Hubere2b10282010-11-23 11:41:34 -08001046 if (p == NULL) {
1047 return NO_INIT;
1048 }
1049
Andreas Hubere2b10282010-11-23 11:41:34 -08001050 // now set data source
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001051 return mStatus = setDataSource_post(p, p->setDataSource(source));
Andreas Hubere2b10282010-11-23 11:41:34 -08001052}
1053
Chris Watkins99f31602015-03-20 13:06:33 -07001054status_t MediaPlayerService::Client::setDataSource(
1055 const sp<IDataSource> &source) {
Dongwon Kangd91dc5a2017-10-10 00:07:09 -07001056 sp<DataSource> dataSource = CreateDataSourceFromIDataSource(source);
Chris Watkins99f31602015-03-20 13:06:33 -07001057 player_type playerType = MediaPlayerFactory::getPlayerType(this, dataSource);
1058 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
1059 if (p == NULL) {
1060 return NO_INIT;
1061 }
1062 // now set data source
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001063 return mStatus = setDataSource_post(p, p->setDataSource(dataSource));
Chris Watkins99f31602015-03-20 13:06:33 -07001064}
1065
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001066void MediaPlayerService::Client::disconnectNativeWindow_l() {
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001067 if (mConnectedWindow != NULL) {
Chong Zhang181fd9b2017-02-16 15:53:03 -08001068 status_t err = nativeWindowDisconnect(
1069 mConnectedWindow.get(), "disconnectNativeWindow");
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001070
1071 if (err != OK) {
Chong Zhang181fd9b2017-02-16 15:53:03 -08001072 ALOGW("nativeWindowDisconnect returned an error: %s (%d)",
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001073 strerror(-err), err);
1074 }
1075 }
1076 mConnectedWindow.clear();
1077}
1078
Glenn Kasten11731182011-02-08 17:26:17 -08001079status_t MediaPlayerService::Client::setVideoSurfaceTexture(
Andy McFadden484566c2012-12-18 09:46:54 -08001080 const sp<IGraphicBufferProducer>& bufferProducer)
Glenn Kasten11731182011-02-08 17:26:17 -08001081{
Andy McFadden484566c2012-12-18 09:46:54 -08001082 ALOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, bufferProducer.get());
Glenn Kasten11731182011-02-08 17:26:17 -08001083 sp<MediaPlayerBase> p = getPlayer();
1084 if (p == 0) return UNKNOWN_ERROR;
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001085
Marco Nelissenf8880202014-11-14 07:58:25 -08001086 sp<IBinder> binder(IInterface::asBinder(bufferProducer));
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001087 if (mConnectedWindowBinder == binder) {
1088 return OK;
1089 }
1090
1091 sp<ANativeWindow> anw;
Andy McFadden484566c2012-12-18 09:46:54 -08001092 if (bufferProducer != NULL) {
Marco Nelissenee08f7e2013-09-16 13:30:01 -07001093 anw = new Surface(bufferProducer, true /* controlledByApp */);
Chong Zhang181fd9b2017-02-16 15:53:03 -08001094 status_t err = nativeWindowConnect(anw.get(), "setVideoSurfaceTexture");
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001095
1096 if (err != OK) {
Steve Block29357bc2012-01-06 19:20:56 +00001097 ALOGE("setVideoSurfaceTexture failed: %d", err);
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001098 // Note that we must do the reset before disconnecting from the ANW.
1099 // Otherwise queue/dequeue calls could be made on the disconnected
1100 // ANW, which may result in errors.
1101 reset();
1102
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001103 Mutex::Autolock lock(mLock);
1104 disconnectNativeWindow_l();
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001105
1106 return err;
1107 }
1108 }
1109
Andy McFadden484566c2012-12-18 09:46:54 -08001110 // Note that we must set the player's new GraphicBufferProducer before
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001111 // disconnecting the old one. Otherwise queue/dequeue calls could be made
1112 // on the disconnected ANW, which may result in errors.
Andy McFadden484566c2012-12-18 09:46:54 -08001113 status_t err = p->setVideoSurfaceTexture(bufferProducer);
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001114
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001115 mLock.lock();
1116 disconnectNativeWindow_l();
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001117
1118 if (err == OK) {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001119 mConnectedWindow = anw;
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001120 mConnectedWindowBinder = binder;
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001121 mLock.unlock();
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001122 } else {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001123 mLock.unlock();
1124 status_t err = nativeWindowDisconnect(
1125 anw.get(), "disconnectNativeWindow");
1126
1127 if (err != OK) {
1128 ALOGW("nativeWindowDisconnect returned an error: %s (%d)",
1129 strerror(-err), err);
1130 }
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001131 }
1132
1133 return err;
Glenn Kasten11731182011-02-08 17:26:17 -08001134}
1135
Nicolas Catania1d187f12009-05-12 23:25:55 -07001136status_t MediaPlayerService::Client::invoke(const Parcel& request,
1137 Parcel *reply)
1138{
1139 sp<MediaPlayerBase> p = getPlayer();
1140 if (p == NULL) return UNKNOWN_ERROR;
1141 return p->invoke(request, reply);
1142}
1143
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001144// This call doesn't need to access the native player.
1145status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
1146{
1147 status_t status;
nikoa64c8c72009-07-20 15:07:26 -07001148 media::Metadata::Filter allow, drop;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001149
Nicolas Catania48290382009-07-10 13:53:06 -07001150 if (unmarshallFilter(filter, &allow, &status) &&
1151 unmarshallFilter(filter, &drop, &status)) {
1152 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001153
1154 mMetadataAllow = allow;
1155 mMetadataDrop = drop;
1156 }
1157 return status;
1158}
1159
Nicolas Catania48290382009-07-10 13:53:06 -07001160status_t MediaPlayerService::Client::getMetadata(
Mark Salyzyn77342f72014-06-18 16:31:32 -07001161 bool update_only, bool /*apply_filter*/, Parcel *reply)
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001162{
nikoa64c8c72009-07-20 15:07:26 -07001163 sp<MediaPlayerBase> player = getPlayer();
1164 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania48290382009-07-10 13:53:06 -07001165
nikod608a812009-07-16 16:39:53 -07001166 status_t status;
1167 // Placeholder for the return code, updated by the caller.
1168 reply->writeInt32(-1);
1169
nikoa64c8c72009-07-20 15:07:26 -07001170 media::Metadata::Filter ids;
Nicolas Catania48290382009-07-10 13:53:06 -07001171
1172 // We don't block notifications while we fetch the data. We clear
1173 // mMetadataUpdated first so we don't lose notifications happening
1174 // during the rest of this call.
1175 {
1176 Mutex::Autolock lock(mLock);
1177 if (update_only) {
nikod608a812009-07-16 16:39:53 -07001178 ids = mMetadataUpdated;
Nicolas Catania48290382009-07-10 13:53:06 -07001179 }
1180 mMetadataUpdated.clear();
1181 }
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001182
nikoa64c8c72009-07-20 15:07:26 -07001183 media::Metadata metadata(reply);
Nicolas Catania48290382009-07-10 13:53:06 -07001184
nikoa64c8c72009-07-20 15:07:26 -07001185 metadata.appendHeader();
1186 status = player->getMetadata(ids, reply);
nikod608a812009-07-16 16:39:53 -07001187
1188 if (status != OK) {
nikoa64c8c72009-07-20 15:07:26 -07001189 metadata.resetParcel();
Steve Block29357bc2012-01-06 19:20:56 +00001190 ALOGE("getMetadata failed %d", status);
nikod608a812009-07-16 16:39:53 -07001191 return status;
1192 }
1193
1194 // FIXME: Implement filtering on the result. Not critical since
1195 // filtering takes place on the update notifications already. This
1196 // would be when all the metadata are fetch and a filter is set.
1197
nikod608a812009-07-16 16:39:53 -07001198 // Everything is fine, update the metadata length.
nikoa64c8c72009-07-20 15:07:26 -07001199 metadata.updateLength();
nikod608a812009-07-16 16:39:53 -07001200 return OK;
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001201}
1202
Wei Jiad399e7e2016-10-26 15:49:11 -07001203status_t MediaPlayerService::Client::setBufferingSettings(
1204 const BufferingSettings& buffering)
1205{
Wei Jiadc6f3402017-01-09 15:04:18 -08001206 ALOGV("[%d] setBufferingSettings{%s}",
1207 mConnId, buffering.toString().string());
Wei Jiad399e7e2016-10-26 15:49:11 -07001208 sp<MediaPlayerBase> p = getPlayer();
1209 if (p == 0) return UNKNOWN_ERROR;
1210 return p->setBufferingSettings(buffering);
1211}
1212
Wei Jia9bb38032017-03-23 18:00:38 -07001213status_t MediaPlayerService::Client::getBufferingSettings(
Wei Jiad399e7e2016-10-26 15:49:11 -07001214 BufferingSettings* buffering /* nonnull */)
1215{
1216 sp<MediaPlayerBase> p = getPlayer();
1217 // TODO: create mPlayer on demand.
1218 if (p == 0) return UNKNOWN_ERROR;
Wei Jia9bb38032017-03-23 18:00:38 -07001219 status_t ret = p->getBufferingSettings(buffering);
Wei Jiad399e7e2016-10-26 15:49:11 -07001220 if (ret == NO_ERROR) {
Wei Jia9bb38032017-03-23 18:00:38 -07001221 ALOGV("[%d] getBufferingSettings{%s}",
Wei Jiadc6f3402017-01-09 15:04:18 -08001222 mConnId, buffering->toString().string());
Wei Jiad399e7e2016-10-26 15:49:11 -07001223 } else {
Wei Jia9bb38032017-03-23 18:00:38 -07001224 ALOGE("[%d] getBufferingSettings returned %d", mConnId, ret);
Wei Jiad399e7e2016-10-26 15:49:11 -07001225 }
1226 return ret;
1227}
1228
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001229status_t MediaPlayerService::Client::prepareAsync()
1230{
Steve Block3856b092011-10-20 11:56:00 +01001231 ALOGV("[%d] prepareAsync", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001232 sp<MediaPlayerBase> p = getPlayer();
1233 if (p == 0) return UNKNOWN_ERROR;
1234 status_t ret = p->prepareAsync();
1235#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +00001236 ALOGD("start Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001237 if (ret == NO_ERROR) mAntagonizer->start();
1238#endif
1239 return ret;
1240}
1241
1242status_t MediaPlayerService::Client::start()
1243{
Steve Block3856b092011-10-20 11:56:00 +01001244 ALOGV("[%d] start", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001245 sp<MediaPlayerBase> p = getPlayer();
1246 if (p == 0) return UNKNOWN_ERROR;
1247 p->setLooping(mLoop);
1248 return p->start();
1249}
1250
1251status_t MediaPlayerService::Client::stop()
1252{
Steve Block3856b092011-10-20 11:56:00 +01001253 ALOGV("[%d] stop", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001254 sp<MediaPlayerBase> p = getPlayer();
1255 if (p == 0) return UNKNOWN_ERROR;
1256 return p->stop();
1257}
1258
1259status_t MediaPlayerService::Client::pause()
1260{
Steve Block3856b092011-10-20 11:56:00 +01001261 ALOGV("[%d] pause", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001262 sp<MediaPlayerBase> p = getPlayer();
1263 if (p == 0) return UNKNOWN_ERROR;
1264 return p->pause();
1265}
1266
1267status_t MediaPlayerService::Client::isPlaying(bool* state)
1268{
1269 *state = false;
1270 sp<MediaPlayerBase> p = getPlayer();
1271 if (p == 0) return UNKNOWN_ERROR;
1272 *state = p->isPlaying();
Steve Block3856b092011-10-20 11:56:00 +01001273 ALOGV("[%d] isPlaying: %d", mConnId, *state);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001274 return NO_ERROR;
1275}
1276
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001277status_t MediaPlayerService::Client::setPlaybackSettings(const AudioPlaybackRate& rate)
Wei Jia98160162015-02-04 17:01:11 -08001278{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001279 ALOGV("[%d] setPlaybackSettings(%f, %f, %d, %d)",
1280 mConnId, rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Wei Jia98160162015-02-04 17:01:11 -08001281 sp<MediaPlayerBase> p = getPlayer();
1282 if (p == 0) return UNKNOWN_ERROR;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001283 return p->setPlaybackSettings(rate);
1284}
1285
1286status_t MediaPlayerService::Client::getPlaybackSettings(AudioPlaybackRate* rate /* nonnull */)
1287{
1288 sp<MediaPlayerBase> p = getPlayer();
1289 if (p == 0) return UNKNOWN_ERROR;
1290 status_t ret = p->getPlaybackSettings(rate);
1291 if (ret == NO_ERROR) {
1292 ALOGV("[%d] getPlaybackSettings(%f, %f, %d, %d)",
1293 mConnId, rate->mSpeed, rate->mPitch, rate->mFallbackMode, rate->mStretchMode);
1294 } else {
1295 ALOGV("[%d] getPlaybackSettings returned %d", mConnId, ret);
1296 }
1297 return ret;
1298}
1299
1300status_t MediaPlayerService::Client::setSyncSettings(
1301 const AVSyncSettings& sync, float videoFpsHint)
1302{
1303 ALOGV("[%d] setSyncSettings(%u, %u, %f, %f)",
1304 mConnId, sync.mSource, sync.mAudioAdjustMode, sync.mTolerance, videoFpsHint);
1305 sp<MediaPlayerBase> p = getPlayer();
1306 if (p == 0) return UNKNOWN_ERROR;
1307 return p->setSyncSettings(sync, videoFpsHint);
1308}
1309
1310status_t MediaPlayerService::Client::getSyncSettings(
1311 AVSyncSettings* sync /* nonnull */, float* videoFps /* nonnull */)
1312{
1313 sp<MediaPlayerBase> p = getPlayer();
1314 if (p == 0) return UNKNOWN_ERROR;
1315 status_t ret = p->getSyncSettings(sync, videoFps);
1316 if (ret == NO_ERROR) {
1317 ALOGV("[%d] getSyncSettings(%u, %u, %f, %f)",
1318 mConnId, sync->mSource, sync->mAudioAdjustMode, sync->mTolerance, *videoFps);
1319 } else {
1320 ALOGV("[%d] getSyncSettings returned %d", mConnId, ret);
1321 }
1322 return ret;
Wei Jia98160162015-02-04 17:01:11 -08001323}
1324
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001325status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
1326{
Steve Block3856b092011-10-20 11:56:00 +01001327 ALOGV("getCurrentPosition");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001328 sp<MediaPlayerBase> p = getPlayer();
1329 if (p == 0) return UNKNOWN_ERROR;
1330 status_t ret = p->getCurrentPosition(msec);
1331 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001332 ALOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001333 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001334 ALOGE("getCurrentPosition returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001335 }
1336 return ret;
1337}
1338
1339status_t MediaPlayerService::Client::getDuration(int *msec)
1340{
Steve Block3856b092011-10-20 11:56:00 +01001341 ALOGV("getDuration");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001342 sp<MediaPlayerBase> p = getPlayer();
1343 if (p == 0) return UNKNOWN_ERROR;
1344 status_t ret = p->getDuration(msec);
1345 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001346 ALOGV("[%d] getDuration = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001347 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001348 ALOGE("getDuration returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001349 }
1350 return ret;
1351}
1352
Marco Nelissen6b74d672012-02-28 16:07:44 -08001353status_t MediaPlayerService::Client::setNextPlayer(const sp<IMediaPlayer>& player) {
1354 ALOGV("setNextPlayer");
1355 Mutex::Autolock l(mLock);
1356 sp<Client> c = static_cast<Client*>(player.get());
Wei Jia28284122016-08-30 13:49:06 -07001357 if (c != NULL && !mService->hasClient(c)) {
Robert Shihee0a0e32016-08-16 16:50:54 -07001358 return BAD_VALUE;
1359 }
1360
Marco Nelissen6b74d672012-02-28 16:07:44 -08001361 mNextClient = c;
John Grossman5f7e55e2012-08-24 14:47:25 -07001362
1363 if (c != NULL) {
1364 if (mAudioOutput != NULL) {
1365 mAudioOutput->setNextOutput(c->mAudioOutput);
1366 } else if ((mPlayer != NULL) && !mPlayer->hardwareOutput()) {
1367 ALOGE("no current audio output");
1368 }
1369
1370 if ((mPlayer != NULL) && (mNextClient->getPlayer() != NULL)) {
1371 mPlayer->setNextPlayer(mNextClient->getPlayer());
1372 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001373 }
John Grossman5f7e55e2012-08-24 14:47:25 -07001374
Marco Nelissen6b74d672012-02-28 16:07:44 -08001375 return OK;
1376}
1377
Andy Hung9fc8b5c2017-01-24 13:36:48 -08001378VolumeShaper::Status MediaPlayerService::Client::applyVolumeShaper(
1379 const sp<VolumeShaper::Configuration>& configuration,
1380 const sp<VolumeShaper::Operation>& operation) {
1381 // for hardware output, call player instead
1382 ALOGV("Client::applyVolumeShaper(%p)", this);
1383 sp<MediaPlayerBase> p = getPlayer();
1384 {
1385 Mutex::Autolock l(mLock);
1386 if (p != 0 && p->hardwareOutput()) {
1387 // TODO: investigate internal implementation
1388 return VolumeShaper::Status(INVALID_OPERATION);
1389 }
1390 if (mAudioOutput.get() != nullptr) {
1391 return mAudioOutput->applyVolumeShaper(configuration, operation);
1392 }
1393 }
1394 return VolumeShaper::Status(INVALID_OPERATION);
1395}
1396
1397sp<VolumeShaper::State> MediaPlayerService::Client::getVolumeShaperState(int id) {
1398 // for hardware output, call player instead
1399 ALOGV("Client::getVolumeShaperState(%p)", this);
1400 sp<MediaPlayerBase> p = getPlayer();
1401 {
1402 Mutex::Autolock l(mLock);
1403 if (p != 0 && p->hardwareOutput()) {
1404 // TODO: investigate internal implementation.
1405 return nullptr;
1406 }
1407 if (mAudioOutput.get() != nullptr) {
1408 return mAudioOutput->getVolumeShaperState(id);
1409 }
1410 }
1411 return nullptr;
1412}
1413
Wei Jiac5de0912016-11-18 10:22:14 -08001414status_t MediaPlayerService::Client::seekTo(int msec, MediaPlayerSeekMode mode)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001415{
Wei Jiac5de0912016-11-18 10:22:14 -08001416 ALOGV("[%d] seekTo(%d, %d)", mConnId, msec, mode);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001417 sp<MediaPlayerBase> p = getPlayer();
1418 if (p == 0) return UNKNOWN_ERROR;
Wei Jiac5de0912016-11-18 10:22:14 -08001419 return p->seekTo(msec, mode);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001420}
1421
1422status_t MediaPlayerService::Client::reset()
1423{
Steve Block3856b092011-10-20 11:56:00 +01001424 ALOGV("[%d] reset", mConnId);
John Grossmanc795b642012-02-22 15:38:35 -08001425 mRetransmitEndpointValid = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001426 sp<MediaPlayerBase> p = getPlayer();
1427 if (p == 0) return UNKNOWN_ERROR;
1428 return p->reset();
1429}
1430
Wei Jia52c28512017-09-13 18:17:51 -07001431status_t MediaPlayerService::Client::notifyAt(int64_t mediaTimeUs)
1432{
1433 ALOGV("[%d] notifyAt(%lld)", mConnId, (long long)mediaTimeUs);
1434 sp<MediaPlayerBase> p = getPlayer();
1435 if (p == 0) return UNKNOWN_ERROR;
1436 return p->notifyAt(mediaTimeUs);
1437}
1438
Glenn Kastenfff6d712012-01-12 16:38:12 -08001439status_t MediaPlayerService::Client::setAudioStreamType(audio_stream_type_t type)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001440{
Steve Block3856b092011-10-20 11:56:00 +01001441 ALOGV("[%d] setAudioStreamType(%d)", mConnId, type);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001442 // TODO: for hardware output, call player instead
1443 Mutex::Autolock l(mLock);
1444 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1445 return NO_ERROR;
1446}
1447
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001448status_t MediaPlayerService::Client::setAudioAttributes_l(const Parcel &parcel)
1449{
1450 if (mAudioAttributes != NULL) { free(mAudioAttributes); }
1451 mAudioAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001452 if (mAudioAttributes == NULL) {
1453 return NO_MEMORY;
1454 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001455 unmarshallAudioAttributes(parcel, mAudioAttributes);
1456
1457 ALOGV("setAudioAttributes_l() usage=%d content=%d flags=0x%x tags=%s",
1458 mAudioAttributes->usage, mAudioAttributes->content_type, mAudioAttributes->flags,
1459 mAudioAttributes->tags);
1460
1461 if (mAudioOutput != 0) {
1462 mAudioOutput->setAudioAttributes(mAudioAttributes);
1463 }
1464 return NO_ERROR;
1465}
1466
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001467status_t MediaPlayerService::Client::setLooping(int loop)
1468{
Steve Block3856b092011-10-20 11:56:00 +01001469 ALOGV("[%d] setLooping(%d)", mConnId, loop);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001470 mLoop = loop;
1471 sp<MediaPlayerBase> p = getPlayer();
1472 if (p != 0) return p->setLooping(loop);
1473 return NO_ERROR;
1474}
1475
1476status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1477{
Steve Block3856b092011-10-20 11:56:00 +01001478 ALOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
John Grossman761defc2012-02-09 15:09:05 -08001479
1480 // for hardware output, call player instead
1481 sp<MediaPlayerBase> p = getPlayer();
1482 {
1483 Mutex::Autolock l(mLock);
1484 if (p != 0 && p->hardwareOutput()) {
1485 MediaPlayerHWInterface* hwp =
1486 reinterpret_cast<MediaPlayerHWInterface*>(p.get());
1487 return hwp->setVolume(leftVolume, rightVolume);
1488 } else {
1489 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1490 return NO_ERROR;
1491 }
1492 }
1493
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001494 return NO_ERROR;
1495}
1496
Eric Laurent2beeb502010-07-16 07:43:46 -07001497status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1498{
Steve Block3856b092011-10-20 11:56:00 +01001499 ALOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
Eric Laurent2beeb502010-07-16 07:43:46 -07001500 Mutex::Autolock l(mLock);
1501 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1502 return NO_ERROR;
1503}
1504
1505status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1506{
Steve Block3856b092011-10-20 11:56:00 +01001507 ALOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
Eric Laurent2beeb502010-07-16 07:43:46 -07001508 Mutex::Autolock l(mLock);
1509 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1510 return NO_ERROR;
1511}
Nicolas Catania48290382009-07-10 13:53:06 -07001512
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001513status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
Steve Block3856b092011-10-20 11:56:00 +01001514 ALOGV("[%d] setParameter(%d)", mConnId, key);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001515 switch (key) {
1516 case KEY_PARAMETER_AUDIO_ATTRIBUTES:
1517 {
1518 Mutex::Autolock l(mLock);
1519 return setAudioAttributes_l(request);
1520 }
1521 default:
1522 sp<MediaPlayerBase> p = getPlayer();
1523 if (p == 0) { return UNKNOWN_ERROR; }
1524 return p->setParameter(key, request);
1525 }
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001526}
1527
1528status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
Steve Block3856b092011-10-20 11:56:00 +01001529 ALOGV("[%d] getParameter(%d)", mConnId, key);
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001530 sp<MediaPlayerBase> p = getPlayer();
1531 if (p == 0) return UNKNOWN_ERROR;
1532 return p->getParameter(key, reply);
1533}
1534
John Grossmanc795b642012-02-22 15:38:35 -08001535status_t MediaPlayerService::Client::setRetransmitEndpoint(
1536 const struct sockaddr_in* endpoint) {
1537
1538 if (NULL != endpoint) {
1539 uint32_t a = ntohl(endpoint->sin_addr.s_addr);
1540 uint16_t p = ntohs(endpoint->sin_port);
1541 ALOGV("[%d] setRetransmitEndpoint(%u.%u.%u.%u:%hu)", mConnId,
1542 (a >> 24), (a >> 16) & 0xFF, (a >> 8) & 0xFF, (a & 0xFF), p);
1543 } else {
1544 ALOGV("[%d] setRetransmitEndpoint = <none>", mConnId);
1545 }
1546
1547 sp<MediaPlayerBase> p = getPlayer();
1548
1549 // Right now, the only valid time to set a retransmit endpoint is before
1550 // player selection has been made (since the presence or absence of a
1551 // retransmit endpoint is going to determine which player is selected during
1552 // setDataSource).
1553 if (p != 0) return INVALID_OPERATION;
1554
1555 if (NULL != endpoint) {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001556 Mutex::Autolock lock(mLock);
John Grossmanc795b642012-02-22 15:38:35 -08001557 mRetransmitEndpoint = *endpoint;
1558 mRetransmitEndpointValid = true;
1559 } else {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001560 Mutex::Autolock lock(mLock);
John Grossmanc795b642012-02-22 15:38:35 -08001561 mRetransmitEndpointValid = false;
1562 }
1563
1564 return NO_ERROR;
1565}
1566
John Grossman44a7e422012-06-21 17:29:24 -07001567status_t MediaPlayerService::Client::getRetransmitEndpoint(
1568 struct sockaddr_in* endpoint)
1569{
1570 if (NULL == endpoint)
1571 return BAD_VALUE;
1572
1573 sp<MediaPlayerBase> p = getPlayer();
1574
1575 if (p != NULL)
1576 return p->getRetransmitEndpoint(endpoint);
1577
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001578 Mutex::Autolock lock(mLock);
John Grossman44a7e422012-06-21 17:29:24 -07001579 if (!mRetransmitEndpointValid)
1580 return NO_INIT;
1581
1582 *endpoint = mRetransmitEndpoint;
1583
1584 return NO_ERROR;
1585}
1586
Gloria Wangb483c472011-04-11 17:23:27 -07001587void MediaPlayerService::Client::notify(
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001588 int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001589{
James Dongb8a98252012-08-26 16:13:03 -07001590 sp<IMediaPlayerClient> c;
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001591 sp<Client> nextClient;
1592 status_t errStartNext = NO_ERROR;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001593 {
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001594 Mutex::Autolock l(mLock);
1595 c = mClient;
1596 if (msg == MEDIA_PLAYBACK_COMPLETE && mNextClient != NULL) {
1597 nextClient = mNextClient;
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001598
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001599 if (mAudioOutput != NULL)
1600 mAudioOutput->switchToNextOutput();
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001601
1602 errStartNext = nextClient->start();
1603 }
1604 }
1605
1606 if (nextClient != NULL) {
1607 sp<IMediaPlayerClient> nc;
1608 {
1609 Mutex::Autolock l(nextClient->mLock);
1610 nc = nextClient->mClient;
1611 }
1612 if (nc != NULL) {
1613 if (errStartNext == NO_ERROR) {
1614 nc->notify(MEDIA_INFO, MEDIA_INFO_STARTED_AS_NEXT, 0, obj);
1615 } else {
1616 nc->notify(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN , 0, obj);
1617 ALOGE("gapless:start playback for next track failed, err(%d)", errStartNext);
Wei Jia2afac0c2016-01-07 12:13:07 -08001618 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001619 }
1620 }
1621
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001622 if (MEDIA_INFO == msg &&
Nicolas Catania48290382009-07-10 13:53:06 -07001623 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikoa64c8c72009-07-20 15:07:26 -07001624 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania48290382009-07-10 13:53:06 -07001625
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001626 if(shouldDropMetadata(metadata_type)) {
Nicolas Catania48290382009-07-10 13:53:06 -07001627 return;
1628 }
1629
1630 // Update the list of metadata that have changed. getMetadata
1631 // also access mMetadataUpdated and clears it.
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001632 addNewMetadataUpdate(metadata_type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001633 }
James Dongb8a98252012-08-26 16:13:03 -07001634
1635 if (c != NULL) {
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001636 ALOGV("[%d] notify (%d, %d, %d)", mConnId, msg, ext1, ext2);
James Dongb8a98252012-08-26 16:13:03 -07001637 c->notify(msg, ext1, ext2, obj);
1638 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001639}
1640
Nicolas Catania48290382009-07-10 13:53:06 -07001641
nikoa64c8c72009-07-20 15:07:26 -07001642bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001643{
Nicolas Catania48290382009-07-10 13:53:06 -07001644 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001645
Nicolas Catania48290382009-07-10 13:53:06 -07001646 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001647 return true;
1648 }
1649
Nicolas Catania48290382009-07-10 13:53:06 -07001650 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001651 return false;
Nicolas Catania48290382009-07-10 13:53:06 -07001652 } else {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001653 return true;
1654 }
1655}
1656
Nicolas Catania48290382009-07-10 13:53:06 -07001657
nikoa64c8c72009-07-20 15:07:26 -07001658void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania48290382009-07-10 13:53:06 -07001659 Mutex::Autolock lock(mLock);
1660 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1661 mMetadataUpdated.add(metadata_type);
1662 }
1663}
1664
Hassan Shojaniacefac142017-02-06 21:02:02 -08001665// Modular DRM
1666status_t MediaPlayerService::Client::prepareDrm(const uint8_t uuid[16],
1667 const Vector<uint8_t>& drmSessionId)
1668{
1669 ALOGV("[%d] prepareDrm", mConnId);
1670 sp<MediaPlayerBase> p = getPlayer();
1671 if (p == 0) return UNKNOWN_ERROR;
1672
1673 status_t ret = p->prepareDrm(uuid, drmSessionId);
1674 ALOGV("prepareDrm ret: %d", ret);
1675
1676 return ret;
1677}
1678
1679status_t MediaPlayerService::Client::releaseDrm()
1680{
1681 ALOGV("[%d] releaseDrm", mConnId);
1682 sp<MediaPlayerBase> p = getPlayer();
1683 if (p == 0) return UNKNOWN_ERROR;
1684
1685 status_t ret = p->releaseDrm();
1686 ALOGV("releaseDrm ret: %d", ret);
1687
1688 return ret;
1689}
1690
jiabin156c6872017-10-06 09:47:15 -07001691status_t MediaPlayerService::Client::setOutputDevice(audio_port_handle_t deviceId)
1692{
1693 ALOGV("[%d] setOutputDevice", mConnId);
1694 {
1695 Mutex::Autolock l(mLock);
1696 if (mAudioOutput.get() != nullptr) {
1697 return mAudioOutput->setOutputDevice(deviceId);
1698 }
1699 }
1700 return NO_INIT;
1701}
1702
1703status_t MediaPlayerService::Client::getRoutedDeviceId(audio_port_handle_t* deviceId)
1704{
1705 ALOGV("[%d] getRoutedDeviceId", mConnId);
1706 {
1707 Mutex::Autolock l(mLock);
1708 if (mAudioOutput.get() != nullptr) {
1709 return mAudioOutput->getRoutedDeviceId(deviceId);
1710 }
1711 }
1712 return NO_INIT;
1713}
1714
1715status_t MediaPlayerService::Client::enableAudioDeviceCallback(bool enabled)
1716{
1717 ALOGV("[%d] enableAudioDeviceCallback, %d", mConnId, enabled);
1718 {
1719 Mutex::Autolock l(mLock);
1720 if (mAudioOutput.get() != nullptr) {
1721 return mAudioOutput->enableAudioDeviceCallback(enabled);
1722 }
1723 }
1724 return NO_INIT;
1725}
1726
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001727#if CALLBACK_ANTAGONIZER
1728const int Antagonizer::interval = 10000; // 10 msecs
1729
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001730Antagonizer::Antagonizer(const sp<MediaPlayerBase::Listener> &listener) :
1731 mExit(false), mActive(false), mListener(listener)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001732{
1733 createThread(callbackThread, this);
1734}
1735
1736void Antagonizer::kill()
1737{
1738 Mutex::Autolock _l(mLock);
1739 mActive = false;
1740 mExit = true;
1741 mCondition.wait(mLock);
1742}
1743
1744int Antagonizer::callbackThread(void* user)
1745{
Steve Blockb8a80522011-12-20 16:23:08 +00001746 ALOGD("Antagonizer started");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001747 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1748 while (!p->mExit) {
1749 if (p->mActive) {
Steve Block3856b092011-10-20 11:56:00 +01001750 ALOGV("send event");
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001751 p->mListener->notify(0, 0, 0, 0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001752 }
1753 usleep(interval);
1754 }
1755 Mutex::Autolock _l(p->mLock);
1756 p->mCondition.signal();
Steve Blockb8a80522011-12-20 16:23:08 +00001757 ALOGD("Antagonizer stopped");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001758 return 0;
1759}
1760#endif
1761
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001762#undef LOG_TAG
1763#define LOG_TAG "AudioSink"
Andy Hung1afd0982016-11-08 16:13:44 -08001764MediaPlayerService::AudioOutput::AudioOutput(audio_session_t sessionId, uid_t uid, int pid,
jiabin156c6872017-10-06 09:47:15 -07001765 const audio_attributes_t* attr, const sp<AudioSystem::AudioDeviceCallback>& deviceCallback)
Andreas Huber20111aa2009-07-14 16:56:47 -07001766 : mCallback(NULL),
Eric Laurenta514bdb2010-06-21 09:27:30 -07001767 mCallbackCookie(NULL),
Marco Nelissen6b74d672012-02-28 16:07:44 -08001768 mCallbackData(NULL),
Andy Hungd1c74342015-07-07 16:54:23 -07001769 mStreamType(AUDIO_STREAM_MUSIC),
Andy Hungd1c74342015-07-07 16:54:23 -07001770 mLeftVolume(1.0),
1771 mRightVolume(1.0),
1772 mPlaybackRate(AUDIO_PLAYBACK_RATE_DEFAULT),
1773 mSampleRateHz(0),
1774 mMsecsPerFrame(0),
1775 mFrameSize(0),
Eric Laurent1948eb32012-04-13 16:50:19 -07001776 mSessionId(sessionId),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001777 mUid(uid),
Marco Nelissend457c972014-02-11 08:47:07 -08001778 mPid(pid),
Andy Hungd1c74342015-07-07 16:54:23 -07001779 mSendLevel(0.0),
1780 mAuxEffectId(0),
Andy Hung4ef88d72017-02-21 19:47:53 -08001781 mFlags(AUDIO_OUTPUT_FLAG_NONE),
jiabin156c6872017-10-06 09:47:15 -07001782 mVolumeHandler(new media::VolumeHandler()),
1783 mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE),
jiabin161b64fc2017-11-17 09:31:48 -08001784 mRoutedDeviceId(AUDIO_PORT_HANDLE_NONE),
jiabin156c6872017-10-06 09:47:15 -07001785 mDeviceCallbackEnabled(false),
1786 mDeviceCallback(deviceCallback)
Andy Hungd1c74342015-07-07 16:54:23 -07001787{
Steve Block3856b092011-10-20 11:56:00 +01001788 ALOGV("AudioOutput(%d)", sessionId);
Eric Laurent43562692015-07-15 16:49:07 -07001789 if (attr != NULL) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001790 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1791 if (mAttributes != NULL) {
1792 memcpy(mAttributes, attr, sizeof(audio_attributes_t));
François Gaffie58d4be52018-11-06 15:30:12 +01001793 mStreamType = AudioSystem::attributesToStreamType(*attr);
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001794 }
1795 } else {
1796 mAttributes = NULL;
Eric Laurent43562692015-07-15 16:49:07 -07001797 }
1798
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001799 setMinBufferCount();
1800}
1801
1802MediaPlayerService::AudioOutput::~AudioOutput()
1803{
1804 close();
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001805 free(mAttributes);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001806 delete mCallbackData;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001807}
1808
Andy Hungd1c74342015-07-07 16:54:23 -07001809//static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001810void MediaPlayerService::AudioOutput::setMinBufferCount()
1811{
1812 char value[PROPERTY_VALUE_MAX];
1813 if (property_get("ro.kernel.qemu", value, 0)) {
1814 mIsOnEmulator = true;
1815 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1816 }
1817}
1818
Andy Hungd1c74342015-07-07 16:54:23 -07001819// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001820bool MediaPlayerService::AudioOutput::isOnEmulator()
1821{
Andy Hungd1c74342015-07-07 16:54:23 -07001822 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001823 return mIsOnEmulator;
1824}
1825
Andy Hungd1c74342015-07-07 16:54:23 -07001826// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001827int MediaPlayerService::AudioOutput::getMinBufferCount()
1828{
Andy Hungd1c74342015-07-07 16:54:23 -07001829 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001830 return mMinBufferCount;
1831}
1832
1833ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1834{
Andy Hungd1c74342015-07-07 16:54:23 -07001835 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001836 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001837 return mTrack->frameCount() * mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001838}
1839
1840ssize_t MediaPlayerService::AudioOutput::frameCount() const
1841{
Andy Hungd1c74342015-07-07 16:54:23 -07001842 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001843 if (mTrack == 0) return NO_INIT;
1844 return mTrack->frameCount();
1845}
1846
1847ssize_t MediaPlayerService::AudioOutput::channelCount() const
1848{
Andy Hungd1c74342015-07-07 16:54:23 -07001849 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001850 if (mTrack == 0) return NO_INIT;
1851 return mTrack->channelCount();
1852}
1853
1854ssize_t MediaPlayerService::AudioOutput::frameSize() const
1855{
Andy Hungd1c74342015-07-07 16:54:23 -07001856 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001857 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001858 return mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001859}
1860
1861uint32_t MediaPlayerService::AudioOutput::latency () const
1862{
Andy Hungd1c74342015-07-07 16:54:23 -07001863 Mutex::Autolock lock(mLock);
Eric Laurentdb354e52012-03-05 17:27:11 -08001864 if (mTrack == 0) return 0;
1865 return mTrack->latency();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001866}
1867
1868float MediaPlayerService::AudioOutput::msecsPerFrame() const
1869{
Andy Hungd1c74342015-07-07 16:54:23 -07001870 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001871 return mMsecsPerFrame;
1872}
1873
Marco Nelissen4110c102012-03-29 09:31:28 -07001874status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position) const
Eric Laurent342e9cf2010-01-19 17:37:09 -08001875{
Andy Hungd1c74342015-07-07 16:54:23 -07001876 Mutex::Autolock lock(mLock);
Eric Laurent342e9cf2010-01-19 17:37:09 -08001877 if (mTrack == 0) return NO_INIT;
1878 return mTrack->getPosition(position);
1879}
1880
Lajos Molnar06ad1522014-08-28 07:27:44 -07001881status_t MediaPlayerService::AudioOutput::getTimestamp(AudioTimestamp &ts) const
1882{
Andy Hungd1c74342015-07-07 16:54:23 -07001883 Mutex::Autolock lock(mLock);
Lajos Molnar06ad1522014-08-28 07:27:44 -07001884 if (mTrack == 0) return NO_INIT;
1885 return mTrack->getTimestamp(ts);
1886}
1887
Wei Jiac4ac8172015-10-21 10:35:48 -07001888// TODO: Remove unnecessary calls to getPlayedOutDurationUs()
1889// as it acquires locks and may query the audio driver.
1890//
1891// Some calls could conceivably retrieve extrapolated data instead of
1892// accessing getTimestamp() or getPosition() every time a data buffer with
1893// a media time is received.
1894//
1895// Calculate duration of played samples if played at normal rate (i.e., 1.0).
1896int64_t MediaPlayerService::AudioOutput::getPlayedOutDurationUs(int64_t nowUs) const
1897{
1898 Mutex::Autolock lock(mLock);
1899 if (mTrack == 0 || mSampleRateHz == 0) {
Wei Jia213f4902015-10-22 08:55:25 -07001900 return 0;
Wei Jiac4ac8172015-10-21 10:35:48 -07001901 }
1902
1903 uint32_t numFramesPlayed;
Andy Hung5d313802016-10-10 15:09:39 -07001904 int64_t numFramesPlayedAtUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001905 AudioTimestamp ts;
Wei Jiac4ac8172015-10-21 10:35:48 -07001906
1907 status_t res = mTrack->getTimestamp(ts);
1908 if (res == OK) { // case 1: mixing audio tracks and offloaded tracks.
1909 numFramesPlayed = ts.mPosition;
Andy Hung5d313802016-10-10 15:09:39 -07001910 numFramesPlayedAtUs = ts.mTime.tv_sec * 1000000LL + ts.mTime.tv_nsec / 1000;
1911 //ALOGD("getTimestamp: OK %d %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001912 } else if (res == WOULD_BLOCK) { // case 2: transitory state on start of a new track
1913 numFramesPlayed = 0;
Andy Hung5d313802016-10-10 15:09:39 -07001914 numFramesPlayedAtUs = nowUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001915 //ALOGD("getTimestamp: WOULD_BLOCK %d %lld",
Andy Hung5d313802016-10-10 15:09:39 -07001916 // numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001917 } else { // case 3: transitory at new track or audio fast tracks.
1918 res = mTrack->getPosition(&numFramesPlayed);
1919 CHECK_EQ(res, (status_t)OK);
Andy Hung5d313802016-10-10 15:09:39 -07001920 numFramesPlayedAtUs = nowUs;
1921 numFramesPlayedAtUs += 1000LL * mTrack->latency() / 2; /* XXX */
1922 //ALOGD("getPosition: %u %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001923 }
1924
1925 // CHECK_EQ(numFramesPlayed & (1 << 31), 0); // can't be negative until 12.4 hrs, test
1926 // TODO: remove the (int32_t) casting below as it may overflow at 12.4 hours.
1927 int64_t durationUs = (int64_t)((int32_t)numFramesPlayed * 1000000LL / mSampleRateHz)
Andy Hung5d313802016-10-10 15:09:39 -07001928 + nowUs - numFramesPlayedAtUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001929 if (durationUs < 0) {
1930 // Occurs when numFramesPlayed position is very small and the following:
1931 // (1) In case 1, the time nowUs is computed before getTimestamp() is called and
Andy Hung5d313802016-10-10 15:09:39 -07001932 // numFramesPlayedAtUs is greater than nowUs by time more than numFramesPlayed.
Wei Jiac4ac8172015-10-21 10:35:48 -07001933 // (2) In case 3, using getPosition and adding mAudioSink->latency() to
Andy Hung5d313802016-10-10 15:09:39 -07001934 // numFramesPlayedAtUs, by a time amount greater than numFramesPlayed.
Wei Jiac4ac8172015-10-21 10:35:48 -07001935 //
1936 // Both of these are transitory conditions.
1937 ALOGV("getPlayedOutDurationUs: negative duration %lld set to zero", (long long)durationUs);
1938 durationUs = 0;
1939 }
1940 ALOGV("getPlayedOutDurationUs(%lld) nowUs(%lld) frames(%u) framesAt(%lld)",
Andy Hung5d313802016-10-10 15:09:39 -07001941 (long long)durationUs, (long long)nowUs,
1942 numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001943 return durationUs;
1944}
1945
Marco Nelissen4110c102012-03-29 09:31:28 -07001946status_t MediaPlayerService::AudioOutput::getFramesWritten(uint32_t *frameswritten) const
1947{
Andy Hungd1c74342015-07-07 16:54:23 -07001948 Mutex::Autolock lock(mLock);
Marco Nelissen4110c102012-03-29 09:31:28 -07001949 if (mTrack == 0) return NO_INIT;
Andy Hung2f6e73d2016-04-08 12:12:58 -07001950 ExtendedTimestamp ets;
1951 status_t status = mTrack->getTimestamp(&ets);
1952 if (status == OK || status == WOULD_BLOCK) {
1953 *frameswritten = (uint32_t)ets.mPosition[ExtendedTimestamp::LOCATION_CLIENT];
1954 }
1955 return status;
Marco Nelissen4110c102012-03-29 09:31:28 -07001956}
1957
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001958status_t MediaPlayerService::AudioOutput::setParameters(const String8& keyValuePairs)
1959{
Andy Hungd1c74342015-07-07 16:54:23 -07001960 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001961 if (mTrack == 0) return NO_INIT;
1962 return mTrack->setParameters(keyValuePairs);
1963}
1964
1965String8 MediaPlayerService::AudioOutput::getParameters(const String8& keys)
1966{
Andy Hungd1c74342015-07-07 16:54:23 -07001967 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001968 if (mTrack == 0) return String8::empty();
1969 return mTrack->getParameters(keys);
1970}
1971
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001972void MediaPlayerService::AudioOutput::setAudioAttributes(const audio_attributes_t * attributes) {
Andy Hungd1c74342015-07-07 16:54:23 -07001973 Mutex::Autolock lock(mLock);
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001974 if (attributes == NULL) {
1975 free(mAttributes);
1976 mAttributes = NULL;
1977 } else {
1978 if (mAttributes == NULL) {
1979 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1980 }
1981 memcpy(mAttributes, attributes, sizeof(audio_attributes_t));
François Gaffie58d4be52018-11-06 15:30:12 +01001982 mStreamType = AudioSystem::attributesToStreamType(*attributes);
Eric Laurent43562692015-07-15 16:49:07 -07001983 }
1984}
1985
1986void MediaPlayerService::AudioOutput::setAudioStreamType(audio_stream_type_t streamType)
1987{
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001988 Mutex::Autolock lock(mLock);
Eric Laurent43562692015-07-15 16:49:07 -07001989 // do not allow direct stream type modification if attributes have been set
1990 if (mAttributes == NULL) {
1991 mStreamType = streamType;
1992 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001993}
1994
Andy Hungd1c74342015-07-07 16:54:23 -07001995void MediaPlayerService::AudioOutput::deleteRecycledTrack_l()
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001996{
Andy Hungd1c74342015-07-07 16:54:23 -07001997 ALOGV("deleteRecycledTrack_l");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001998 if (mRecycledTrack != 0) {
1999
2000 if (mCallbackData != NULL) {
2001 mCallbackData->setOutput(NULL);
2002 mCallbackData->endTrackSwitch();
2003 }
2004
2005 if ((mRecycledTrack->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) {
Andy Hunge13f8a62016-03-30 14:20:42 -07002006 int32_t msec = 0;
2007 if (!mRecycledTrack->stopped()) { // check if active
2008 (void)mRecycledTrack->pendingDuration(&msec);
2009 }
2010 mRecycledTrack->stop(); // ensure full data drain
2011 ALOGD("deleting recycled track, waiting for data drain (%d msec)", msec);
2012 if (msec > 0) {
2013 static const int32_t WAIT_LIMIT_MS = 3000;
2014 if (msec > WAIT_LIMIT_MS) {
2015 msec = WAIT_LIMIT_MS;
2016 }
2017 usleep(msec * 1000LL);
2018 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002019 }
2020 // An offloaded track isn't flushed because the STREAM_END is reported
2021 // slightly prematurely to allow time for the gapless track switch
2022 // but this means that if we decide not to recycle the track there
2023 // could be a small amount of residual data still playing. We leave
2024 // AudioFlinger to drain the track.
2025
2026 mRecycledTrack.clear();
Andy Hungd1c74342015-07-07 16:54:23 -07002027 close_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002028 delete mCallbackData;
2029 mCallbackData = NULL;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002030 }
2031}
2032
Andy Hungd1c74342015-07-07 16:54:23 -07002033void MediaPlayerService::AudioOutput::close_l()
2034{
2035 mTrack.clear();
2036}
2037
Andreas Huber20111aa2009-07-14 16:56:47 -07002038status_t MediaPlayerService::AudioOutput::open(
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08002039 uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
2040 audio_format_t format, int bufferCount,
Eric Laurent1948eb32012-04-13 16:50:19 -07002041 AudioCallback cb, void *cookie,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002042 audio_output_flags_t flags,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07002043 const audio_offload_info_t *offloadInfo,
Andy Hung179652e2015-05-31 22:49:46 -07002044 bool doNotReconnect,
2045 uint32_t suggestedFrameCount)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002046{
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002047 ALOGV("open(%u, %d, 0x%x, 0x%x, %d, %d 0x%x)", sampleRate, channelCount, channelMask,
2048 format, bufferCount, mSessionId, flags);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002049
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002050 // offloading is only supported in callback mode for now.
2051 // offloadInfo must be present if offload flag is set
2052 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) &&
2053 ((cb == NULL) || (offloadInfo == NULL))) {
2054 return BAD_VALUE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002055 }
2056
Andy Hung179652e2015-05-31 22:49:46 -07002057 // compute frame count for the AudioTrack internal buffer
2058 size_t frameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002059 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
2060 frameCount = 0; // AudioTrack will get frame count from AudioFlinger
2061 } else {
Andy Hung179652e2015-05-31 22:49:46 -07002062 // try to estimate the buffer processing fetch size from AudioFlinger.
2063 // framesPerBuffer is approximate and generally correct, except when it's not :-).
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002064 uint32_t afSampleRate;
2065 size_t afFrameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002066 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
2067 return NO_INIT;
2068 }
2069 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
2070 return NO_INIT;
2071 }
Ben Romberger259fb462018-08-07 17:58:53 -07002072 if (afSampleRate == 0) {
2073 return NO_INIT;
2074 }
Andy Hung179652e2015-05-31 22:49:46 -07002075 const size_t framesPerBuffer =
2076 (unsigned long long)sampleRate * afFrameCount / afSampleRate;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002077
Andy Hung179652e2015-05-31 22:49:46 -07002078 if (bufferCount == 0) {
Ben Romberger259fb462018-08-07 17:58:53 -07002079 if (framesPerBuffer == 0) {
2080 return NO_INIT;
2081 }
Andy Hung179652e2015-05-31 22:49:46 -07002082 // use suggestedFrameCount
2083 bufferCount = (suggestedFrameCount + framesPerBuffer - 1) / framesPerBuffer;
2084 }
2085 // Check argument bufferCount against the mininum buffer count
2086 if (bufferCount != 0 && bufferCount < mMinBufferCount) {
2087 ALOGV("bufferCount (%d) increased to %d", bufferCount, mMinBufferCount);
2088 bufferCount = mMinBufferCount;
2089 }
2090 // if frameCount is 0, then AudioTrack will get frame count from AudioFlinger
2091 // which will be the minimum size permitted.
2092 frameCount = bufferCount * framesPerBuffer;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002093 }
Andreas Huber20111aa2009-07-14 16:56:47 -07002094
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08002095 if (channelMask == CHANNEL_MASK_USE_CHANNEL_ORDER) {
Glenn Kastenab334fd2012-03-14 12:56:06 -07002096 channelMask = audio_channel_out_mask_from_count(channelCount);
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08002097 if (0 == channelMask) {
2098 ALOGE("open() error, can\'t derive mask for %d audio channels", channelCount);
2099 return NO_INIT;
2100 }
2101 }
Eric Laurent1948eb32012-04-13 16:50:19 -07002102
Andy Hungd1c74342015-07-07 16:54:23 -07002103 Mutex::Autolock lock(mLock);
Andy Hung179652e2015-05-31 22:49:46 -07002104 mCallback = cb;
2105 mCallbackCookie = cookie;
2106
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002107 // Check whether we can recycle the track
2108 bool reuse = false;
2109 bool bothOffloaded = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07002110
Glenn Kasten2799d742013-05-30 14:33:29 -07002111 if (mRecycledTrack != 0) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002112 // check whether we are switching between two offloaded tracks
2113 bothOffloaded = (flags & mRecycledTrack->getFlags()
2114 & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0;
Marco Nelissen67295b52012-06-11 14:52:53 -07002115
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002116 // check if the existing track can be reused as-is, or if a new track needs to be created.
2117 reuse = true;
2118
Marco Nelissen67295b52012-06-11 14:52:53 -07002119 if ((mCallbackData == NULL && mCallback != NULL) ||
2120 (mCallbackData != NULL && mCallback == NULL)) {
2121 // recycled track uses callbacks but the caller wants to use writes, or vice versa
2122 ALOGV("can't chain callback and write");
2123 reuse = false;
2124 } else if ((mRecycledTrack->getSampleRate() != sampleRate) ||
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002125 (mRecycledTrack->channelCount() != (uint32_t)channelCount) ) {
2126 ALOGV("samplerate, channelcount differ: %u/%u Hz, %u/%d ch",
Marco Nelissen67295b52012-06-11 14:52:53 -07002127 mRecycledTrack->getSampleRate(), sampleRate,
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002128 mRecycledTrack->channelCount(), channelCount);
Marco Nelissen67295b52012-06-11 14:52:53 -07002129 reuse = false;
2130 } else if (flags != mFlags) {
2131 ALOGV("output flags differ %08x/%08x", flags, mFlags);
2132 reuse = false;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002133 } else if (mRecycledTrack->format() != format) {
2134 reuse = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07002135 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002136 } else {
2137 ALOGV("no track available to recycle");
2138 }
2139
2140 ALOGV_IF(bothOffloaded, "both tracks offloaded");
2141
2142 // If we can't recycle and both tracks are offloaded
2143 // we must close the previous output before opening a new one
2144 if (bothOffloaded && !reuse) {
2145 ALOGV("both offloaded and not recycling");
Andy Hungd1c74342015-07-07 16:54:23 -07002146 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002147 }
2148
2149 sp<AudioTrack> t;
2150 CallbackData *newcbd = NULL;
2151
2152 // We don't attempt to create a new track if we are recycling an
2153 // offloaded track. But, if we are recycling a non-offloaded or we
2154 // are switching where one is offloaded and one isn't then we create
2155 // the new track in advance so that we can read additional stream info
2156
2157 if (!(reuse && bothOffloaded)) {
2158 ALOGV("creating new AudioTrack");
2159
2160 if (mCallback != NULL) {
2161 newcbd = new CallbackData(this);
2162 t = new AudioTrack(
2163 mStreamType,
2164 sampleRate,
2165 format,
2166 channelMask,
2167 frameCount,
2168 flags,
2169 CallbackWrapper,
2170 newcbd,
2171 0, // notification frames
2172 mSessionId,
2173 AudioTrack::TRANSFER_CALLBACK,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002174 offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -08002175 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07002176 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07002177 mAttributes,
jiabin156c6872017-10-06 09:47:15 -07002178 doNotReconnect,
2179 1.0f, // default value for maxRequiredSpeed
2180 mSelectedDeviceId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002181 } else {
Andy Hungff874dc2016-04-11 16:49:09 -07002182 // TODO: Due to buffer memory concerns, we use a max target playback speed
2183 // based on mPlaybackRate at the time of open (instead of kMaxRequiredSpeed),
2184 // also clamping the target speed to 1.0 <= targetSpeed <= kMaxRequiredSpeed.
2185 const float targetSpeed =
2186 std::min(std::max(mPlaybackRate.mSpeed, 1.0f), kMaxRequiredSpeed);
2187 ALOGW_IF(targetSpeed != mPlaybackRate.mSpeed,
2188 "track target speed:%f clamped from playback speed:%f",
2189 targetSpeed, mPlaybackRate.mSpeed);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002190 t = new AudioTrack(
2191 mStreamType,
2192 sampleRate,
2193 format,
2194 channelMask,
2195 frameCount,
2196 flags,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002197 NULL, // callback
2198 NULL, // user data
2199 0, // notification frames
2200 mSessionId,
2201 AudioTrack::TRANSFER_DEFAULT,
2202 NULL, // offload info
Marco Nelissend457c972014-02-11 08:47:07 -08002203 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07002204 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07002205 mAttributes,
Andy Hungff874dc2016-04-11 16:49:09 -07002206 doNotReconnect,
jiabin156c6872017-10-06 09:47:15 -07002207 targetSpeed,
2208 mSelectedDeviceId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002209 }
2210
2211 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
2212 ALOGE("Unable to create audio track");
2213 delete newcbd;
Glenn Kasten3e98ecd2015-05-18 13:13:24 -07002214 // t goes out of scope, so reference count drops to zero
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002215 return NO_INIT;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07002216 } else {
2217 // successful AudioTrack initialization implies a legacy stream type was generated
2218 // from the audio attributes
2219 mStreamType = t->streamType();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002220 }
2221 }
2222
2223 if (reuse) {
2224 CHECK(mRecycledTrack != NULL);
2225
2226 if (!bothOffloaded) {
2227 if (mRecycledTrack->frameCount() != t->frameCount()) {
Andy Hung833b4752016-04-04 17:15:48 -07002228 ALOGV("framecount differs: %zu/%zu frames",
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002229 mRecycledTrack->frameCount(), t->frameCount());
2230 reuse = false;
2231 }
2232 }
2233
Marco Nelissen67295b52012-06-11 14:52:53 -07002234 if (reuse) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002235 ALOGV("chaining to next output and recycling track");
Andy Hungd1c74342015-07-07 16:54:23 -07002236 close_l();
Marco Nelissen67295b52012-06-11 14:52:53 -07002237 mTrack = mRecycledTrack;
Glenn Kasten2799d742013-05-30 14:33:29 -07002238 mRecycledTrack.clear();
Marco Nelissen67295b52012-06-11 14:52:53 -07002239 if (mCallbackData != NULL) {
2240 mCallbackData->setOutput(this);
2241 }
Marco Nelissen67295b52012-06-11 14:52:53 -07002242 delete newcbd;
Wei Jiae0bbac92016-07-18 16:04:53 -07002243 return updateTrack();
Marco Nelissen67295b52012-06-11 14:52:53 -07002244 }
Marco Nelissen67295b52012-06-11 14:52:53 -07002245 }
2246
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002247 // we're not going to reuse the track, unblock and flush it
2248 // this was done earlier if both tracks are offloaded
2249 if (!bothOffloaded) {
Andy Hungd1c74342015-07-07 16:54:23 -07002250 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002251 }
2252
2253 CHECK((t != NULL) && ((mCallback == NULL) || (newcbd != NULL)));
2254
Marco Nelissen67295b52012-06-11 14:52:53 -07002255 mCallbackData = newcbd;
Steve Block3856b092011-10-20 11:56:00 +01002256 ALOGV("setVolume");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002257 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07002258
Andy Hung39399b62017-04-21 15:07:45 -07002259 // Restore VolumeShapers for the MediaPlayer in case the track was recreated
2260 // due to an output sink error (e.g. offload to non-offload switch).
2261 mVolumeHandler->forall([&t](const VolumeShaper &shaper) -> VolumeShaper::Status {
2262 sp<VolumeShaper::Operation> operationToEnd =
2263 new VolumeShaper::Operation(shaper.mOperation);
2264 // TODO: Ideally we would restore to the exact xOffset position
2265 // as returned by getVolumeShaperState(), but we don't have that
2266 // information when restoring at the client unless we periodically poll
2267 // the server or create shared memory state.
2268 //
2269 // For now, we simply advance to the end of the VolumeShaper effect
2270 // if it has been started.
2271 if (shaper.isStarted()) {
Andy Hungf3702642017-05-05 17:33:32 -07002272 operationToEnd->setNormalizedTime(1.f);
Andy Hung39399b62017-04-21 15:07:45 -07002273 }
2274 return t->applyVolumeShaper(shaper.mConfiguration, operationToEnd);
Andy Hung4ef88d72017-02-21 19:47:53 -08002275 });
Andy Hung4ef88d72017-02-21 19:47:53 -08002276
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002277 mSampleRateHz = sampleRate;
Preetam Singh Ranawat2e17eef2015-08-12 12:11:46 -07002278 mFlags = flags;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002279 mMsecsPerFrame = 1E3f / (mPlaybackRate.mSpeed * sampleRate);
Andy Hungd1c74342015-07-07 16:54:23 -07002280 mFrameSize = t->frameSize();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002281 mTrack = t;
Eric Laurent2beeb502010-07-16 07:43:46 -07002282
Wei Jiae0bbac92016-07-18 16:04:53 -07002283 return updateTrack();
2284}
2285
2286status_t MediaPlayerService::AudioOutput::updateTrack() {
2287 if (mTrack == NULL) {
2288 return NO_ERROR;
2289 }
2290
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002291 status_t res = NO_ERROR;
Wei Jia0162d002015-06-09 11:59:33 -07002292 // Note some output devices may give us a direct track even though we don't specify it.
2293 // Example: Line application b/17459982.
Wei Jiae0bbac92016-07-18 16:04:53 -07002294 if ((mTrack->getFlags()
2295 & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) {
2296 res = mTrack->setPlaybackRate(mPlaybackRate);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002297 if (res == NO_ERROR) {
Wei Jiae0bbac92016-07-18 16:04:53 -07002298 mTrack->setAuxEffectSendLevel(mSendLevel);
2299 res = mTrack->attachAuxEffect(mAuxEffectId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002300 }
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002301 }
jiabin156c6872017-10-06 09:47:15 -07002302 mTrack->setOutputDevice(mSelectedDeviceId);
2303 if (mDeviceCallbackEnabled) {
2304 mTrack->addAudioDeviceCallback(mDeviceCallback.promote());
2305 }
Wei Jiae0bbac92016-07-18 16:04:53 -07002306 ALOGV("updateTrack() DONE status %d", res);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002307 return res;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002308}
2309
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002310status_t MediaPlayerService::AudioOutput::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002311{
Steve Block3856b092011-10-20 11:56:00 +01002312 ALOGV("start");
Andy Hungd1c74342015-07-07 16:54:23 -07002313 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08002314 if (mCallbackData != NULL) {
2315 mCallbackData->endTrackSwitch();
2316 }
Glenn Kasten2799d742013-05-30 14:33:29 -07002317 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002318 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07002319 mTrack->setAuxEffectSendLevel(mSendLevel);
Andy Hung39399b62017-04-21 15:07:45 -07002320 status_t status = mTrack->start();
2321 if (status == NO_ERROR) {
2322 mVolumeHandler->setStarted();
2323 }
2324 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002325 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002326 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002327}
2328
Marco Nelissen6b74d672012-02-28 16:07:44 -08002329void MediaPlayerService::AudioOutput::setNextOutput(const sp<AudioOutput>& nextOutput) {
Andy Hungd1c74342015-07-07 16:54:23 -07002330 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08002331 mNextOutput = nextOutput;
2332}
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08002333
Marco Nelissen6b74d672012-02-28 16:07:44 -08002334void MediaPlayerService::AudioOutput::switchToNextOutput() {
2335 ALOGV("switchToNextOutput");
Andy Hungd1c74342015-07-07 16:54:23 -07002336
2337 // Try to acquire the callback lock before moving track (without incurring deadlock).
2338 const unsigned kMaxSwitchTries = 100;
2339 Mutex::Autolock lock(mLock);
2340 for (unsigned tries = 0;;) {
2341 if (mTrack == 0) {
2342 return;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002343 }
Andy Hungd1c74342015-07-07 16:54:23 -07002344 if (mNextOutput != NULL && mNextOutput != this) {
2345 if (mCallbackData != NULL) {
2346 // two alternative approaches
2347#if 1
2348 CallbackData *callbackData = mCallbackData;
2349 mLock.unlock();
2350 // proper acquisition sequence
2351 callbackData->lock();
2352 mLock.lock();
2353 // Caution: it is unlikely that someone deleted our callback or changed our target
2354 if (callbackData != mCallbackData || mNextOutput == NULL || mNextOutput == this) {
2355 // fatal if we are starved out.
2356 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2357 "switchToNextOutput() cannot obtain correct lock sequence");
2358 callbackData->unlock();
2359 continue;
2360 }
2361 callbackData->mSwitching = true; // begin track switch
Wei Jiaadee56a2016-08-05 15:40:34 -07002362 callbackData->setOutput(NULL);
Andy Hungd1c74342015-07-07 16:54:23 -07002363#else
2364 // tryBeginTrackSwitch() returns false if the callback has the lock.
2365 if (!mCallbackData->tryBeginTrackSwitch()) {
2366 // fatal if we are starved out.
2367 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2368 "switchToNextOutput() cannot obtain callback lock");
2369 mLock.unlock();
2370 usleep(5 * 1000 /* usec */); // allow callback to use AudioOutput
2371 mLock.lock();
2372 continue;
2373 }
2374#endif
2375 }
2376
2377 Mutex::Autolock nextLock(mNextOutput->mLock);
2378
2379 // If the next output track is not NULL, then it has been
2380 // opened already for playback.
2381 // This is possible even without the next player being started,
2382 // for example, the next player could be prepared and seeked.
2383 //
2384 // Presuming it isn't advisable to force the track over.
2385 if (mNextOutput->mTrack == NULL) {
2386 ALOGD("Recycling track for gapless playback");
2387 delete mNextOutput->mCallbackData;
2388 mNextOutput->mCallbackData = mCallbackData;
2389 mNextOutput->mRecycledTrack = mTrack;
2390 mNextOutput->mSampleRateHz = mSampleRateHz;
2391 mNextOutput->mMsecsPerFrame = mMsecsPerFrame;
Andy Hungd1c74342015-07-07 16:54:23 -07002392 mNextOutput->mFlags = mFlags;
2393 mNextOutput->mFrameSize = mFrameSize;
2394 close_l();
2395 mCallbackData = NULL; // destruction handled by mNextOutput
2396 } else {
2397 ALOGW("Ignoring gapless playback because next player has already started");
2398 // remove track in case resource needed for future players.
2399 if (mCallbackData != NULL) {
2400 mCallbackData->endTrackSwitch(); // release lock for callbacks before close.
2401 }
2402 close_l();
2403 }
2404 }
2405 break;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002406 }
2407}
2408
Wei Jia7d3f4df2015-03-03 15:28:00 -08002409ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002410{
Andy Hungd1c74342015-07-07 16:54:23 -07002411 Mutex::Autolock lock(mLock);
Glenn Kastenadad3d72014-02-21 14:51:43 -08002412 LOG_ALWAYS_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
Andreas Huber20111aa2009-07-14 16:56:47 -07002413
Steve Block3856b092011-10-20 11:56:00 +01002414 //ALOGV("write(%p, %u)", buffer, size);
Glenn Kasten2799d742013-05-30 14:33:29 -07002415 if (mTrack != 0) {
Andy Hung2f6e73d2016-04-08 12:12:58 -07002416 return mTrack->write(buffer, size, blocking);
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07002417 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002418 return NO_INIT;
2419}
2420
2421void MediaPlayerService::AudioOutput::stop()
2422{
Steve Block3856b092011-10-20 11:56:00 +01002423 ALOGV("stop");
Andy Hungd1c74342015-07-07 16:54:23 -07002424 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002425 if (mTrack != 0) mTrack->stop();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002426}
2427
2428void MediaPlayerService::AudioOutput::flush()
2429{
Steve Block3856b092011-10-20 11:56:00 +01002430 ALOGV("flush");
Andy Hungd1c74342015-07-07 16:54:23 -07002431 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002432 if (mTrack != 0) mTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002433}
2434
2435void MediaPlayerService::AudioOutput::pause()
2436{
Steve Block3856b092011-10-20 11:56:00 +01002437 ALOGV("pause");
Andy Hungd1c74342015-07-07 16:54:23 -07002438 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002439 if (mTrack != 0) mTrack->pause();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002440}
2441
2442void MediaPlayerService::AudioOutput::close()
2443{
Steve Block3856b092011-10-20 11:56:00 +01002444 ALOGV("close");
Erik Wolsheimer7845a1f2015-10-30 12:07:52 -07002445 sp<AudioTrack> track;
2446 {
2447 Mutex::Autolock lock(mLock);
2448 track = mTrack;
2449 close_l(); // clears mTrack
2450 }
2451 // destruction of the track occurs outside of mutex.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002452}
2453
2454void MediaPlayerService::AudioOutput::setVolume(float left, float right)
2455{
Steve Block3856b092011-10-20 11:56:00 +01002456 ALOGV("setVolume(%f, %f)", left, right);
Andy Hungd1c74342015-07-07 16:54:23 -07002457 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002458 mLeftVolume = left;
2459 mRightVolume = right;
Glenn Kasten2799d742013-05-30 14:33:29 -07002460 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002461 mTrack->setVolume(left, right);
2462 }
2463}
2464
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002465status_t MediaPlayerService::AudioOutput::setPlaybackRate(const AudioPlaybackRate &rate)
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002466{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002467 ALOGV("setPlaybackRate(%f %f %d %d)",
2468 rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Andy Hungd1c74342015-07-07 16:54:23 -07002469 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002470 if (mTrack == 0) {
2471 // remember rate so that we can set it when the track is opened
2472 mPlaybackRate = rate;
2473 return OK;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002474 }
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002475 status_t res = mTrack->setPlaybackRate(rate);
2476 if (res != NO_ERROR) {
2477 return res;
2478 }
2479 // rate.mSpeed is always greater than 0 if setPlaybackRate succeeded
2480 CHECK_GT(rate.mSpeed, 0.f);
2481 mPlaybackRate = rate;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002482 if (mSampleRateHz != 0) {
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002483 mMsecsPerFrame = 1E3f / (rate.mSpeed * mSampleRateHz);
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002484 }
2485 return res;
2486}
2487
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002488status_t MediaPlayerService::AudioOutput::getPlaybackRate(AudioPlaybackRate *rate)
2489{
2490 ALOGV("setPlaybackRate");
Andy Hungd1c74342015-07-07 16:54:23 -07002491 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002492 if (mTrack == 0) {
2493 return NO_INIT;
2494 }
2495 *rate = mTrack->getPlaybackRate();
2496 return NO_ERROR;
2497}
2498
Eric Laurent2beeb502010-07-16 07:43:46 -07002499status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
2500{
Steve Block3856b092011-10-20 11:56:00 +01002501 ALOGV("setAuxEffectSendLevel(%f)", level);
Andy Hungd1c74342015-07-07 16:54:23 -07002502 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002503 mSendLevel = level;
Glenn Kasten2799d742013-05-30 14:33:29 -07002504 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002505 return mTrack->setAuxEffectSendLevel(level);
2506 }
2507 return NO_ERROR;
2508}
2509
2510status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
2511{
Steve Block3856b092011-10-20 11:56:00 +01002512 ALOGV("attachAuxEffect(%d)", effectId);
Andy Hungd1c74342015-07-07 16:54:23 -07002513 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002514 mAuxEffectId = effectId;
Glenn Kasten2799d742013-05-30 14:33:29 -07002515 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002516 return mTrack->attachAuxEffect(effectId);
2517 }
2518 return NO_ERROR;
2519}
2520
jiabin156c6872017-10-06 09:47:15 -07002521status_t MediaPlayerService::AudioOutput::setOutputDevice(audio_port_handle_t deviceId)
2522{
2523 ALOGV("setOutputDevice(%d)", deviceId);
2524 Mutex::Autolock lock(mLock);
2525 mSelectedDeviceId = deviceId;
2526 if (mTrack != 0) {
2527 return mTrack->setOutputDevice(deviceId);
2528 }
2529 return NO_ERROR;
2530}
2531
2532status_t MediaPlayerService::AudioOutput::getRoutedDeviceId(audio_port_handle_t* deviceId)
2533{
2534 ALOGV("getRoutedDeviceId");
2535 Mutex::Autolock lock(mLock);
2536 if (mTrack != 0) {
jiabin161b64fc2017-11-17 09:31:48 -08002537 mRoutedDeviceId = mTrack->getRoutedDeviceId();
jiabin156c6872017-10-06 09:47:15 -07002538 }
jiabin161b64fc2017-11-17 09:31:48 -08002539 *deviceId = mRoutedDeviceId;
2540 return NO_ERROR;
jiabin156c6872017-10-06 09:47:15 -07002541}
2542
2543status_t MediaPlayerService::AudioOutput::enableAudioDeviceCallback(bool enabled)
2544{
2545 ALOGV("enableAudioDeviceCallback, %d", enabled);
2546 Mutex::Autolock lock(mLock);
2547 mDeviceCallbackEnabled = enabled;
2548 if (mTrack != 0) {
2549 status_t status;
2550 if (enabled) {
2551 status = mTrack->addAudioDeviceCallback(mDeviceCallback.promote());
2552 } else {
2553 status = mTrack->removeAudioDeviceCallback(mDeviceCallback.promote());
2554 }
2555 return status;
2556 }
2557 return NO_ERROR;
2558}
2559
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002560VolumeShaper::Status MediaPlayerService::AudioOutput::applyVolumeShaper(
2561 const sp<VolumeShaper::Configuration>& configuration,
2562 const sp<VolumeShaper::Operation>& operation)
2563{
2564 Mutex::Autolock lock(mLock);
2565 ALOGV("AudioOutput::applyVolumeShaper");
Andy Hung4ef88d72017-02-21 19:47:53 -08002566
Andy Hung4ef88d72017-02-21 19:47:53 -08002567 mVolumeHandler->setIdIfNecessary(configuration);
Andy Hung39399b62017-04-21 15:07:45 -07002568
2569 VolumeShaper::Status status;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002570 if (mTrack != 0) {
Andy Hung39399b62017-04-21 15:07:45 -07002571 status = mTrack->applyVolumeShaper(configuration, operation);
2572 if (status >= 0) {
2573 (void)mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hungf3702642017-05-05 17:33:32 -07002574 if (mTrack->isPlaying()) { // match local AudioTrack to properly restore.
2575 mVolumeHandler->setStarted();
2576 }
Andy Hung39399b62017-04-21 15:07:45 -07002577 }
Andy Hung4ef88d72017-02-21 19:47:53 -08002578 } else {
Andy Hungc01eddb2017-07-21 16:42:41 -07002579 // VolumeShapers are not affected when a track moves between players for
2580 // gapless playback (setNextMediaPlayer).
2581 // We forward VolumeShaper operations that do not change configuration
2582 // to the new player so that unducking may occur as expected.
2583 // Unducking is an idempotent operation, same if applied back-to-back.
2584 if (configuration->getType() == VolumeShaper::Configuration::TYPE_ID
2585 && mNextOutput != nullptr) {
2586 ALOGV("applyVolumeShaper: Attempting to forward missed operation: %s %s",
2587 configuration->toString().c_str(), operation->toString().c_str());
2588 Mutex::Autolock nextLock(mNextOutput->mLock);
2589
2590 // recycled track should be forwarded from this AudioSink by switchToNextOutput
2591 sp<AudioTrack> track = mNextOutput->mRecycledTrack;
2592 if (track != nullptr) {
2593 ALOGD("Forward VolumeShaper operation to recycled track %p", track.get());
2594 (void)track->applyVolumeShaper(configuration, operation);
2595 } else {
2596 // There is a small chance that the unduck occurs after the next
2597 // player has already started, but before it is registered to receive
2598 // the unduck command.
2599 track = mNextOutput->mTrack;
2600 if (track != nullptr) {
2601 ALOGD("Forward VolumeShaper operation to track %p", track.get());
2602 (void)track->applyVolumeShaper(configuration, operation);
2603 }
2604 }
2605 }
Andy Hung39399b62017-04-21 15:07:45 -07002606 status = mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002607 }
Andy Hung39399b62017-04-21 15:07:45 -07002608 return status;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002609}
2610
2611sp<VolumeShaper::State> MediaPlayerService::AudioOutput::getVolumeShaperState(int id)
2612{
2613 Mutex::Autolock lock(mLock);
2614 if (mTrack != 0) {
2615 return mTrack->getVolumeShaperState(id);
Andy Hung4ef88d72017-02-21 19:47:53 -08002616 } else {
2617 return mVolumeHandler->getVolumeShaperState(id);
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002618 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002619}
2620
Andreas Huber20111aa2009-07-14 16:56:47 -07002621// static
2622void MediaPlayerService::AudioOutput::CallbackWrapper(
Glenn Kastend217a8c2011-06-01 15:20:35 -07002623 int event, void *cookie, void *info) {
Steve Block3856b092011-10-20 11:56:00 +01002624 //ALOGV("callbackwrapper");
Marco Nelissen6b74d672012-02-28 16:07:44 -08002625 CallbackData *data = (CallbackData*)cookie;
Andy Hungd1c74342015-07-07 16:54:23 -07002626 // lock to ensure we aren't caught in the middle of a track switch.
Marco Nelissen6b74d672012-02-28 16:07:44 -08002627 data->lock();
2628 AudioOutput *me = data->getOutput();
Andreas Huber20111aa2009-07-14 16:56:47 -07002629 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002630 if (me == NULL) {
2631 // no output set, likely because the track was scheduled to be reused
2632 // by another player, but the format turned out to be incompatible.
2633 data->unlock();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002634 if (buffer != NULL) {
2635 buffer->size = 0;
2636 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08002637 return;
2638 }
Andreas Huber20111aa2009-07-14 16:56:47 -07002639
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002640 switch(event) {
2641 case AudioTrack::EVENT_MORE_DATA: {
2642 size_t actualSize = (*me->mCallback)(
2643 me, buffer->raw, buffer->size, me->mCallbackCookie,
2644 CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002645
Andy Hung719b46b2015-05-31 22:18:25 -07002646 // Log when no data is returned from the callback.
2647 // (1) We may have no data (especially with network streaming sources).
2648 // (2) We may have reached the EOS and the audio track is not stopped yet.
2649 // Note that AwesomePlayer/AudioPlayer will only return zero size when it reaches the EOS.
2650 // NuPlayerRenderer will return zero when it doesn't have data (it doesn't block to fill).
2651 //
2652 // This is a benign busy-wait, with the next data request generated 10 ms or more later;
2653 // nevertheless for power reasons, we don't want to see too many of these.
Andreas Huber2e8ffaf2010-02-18 16:45:13 -08002654
Andy Hung719b46b2015-05-31 22:18:25 -07002655 ALOGV_IF(actualSize == 0 && buffer->size > 0, "callbackwrapper: empty buffer returned");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002656
2657 buffer->size = actualSize;
2658 } break;
2659
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002660 case AudioTrack::EVENT_STREAM_END:
Andy Hung719b46b2015-05-31 22:18:25 -07002661 // currently only occurs for offloaded callbacks
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002662 ALOGV("callbackwrapper: deliver EVENT_STREAM_END");
2663 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2664 me->mCallbackCookie, CB_EVENT_STREAM_END);
2665 break;
2666
2667 case AudioTrack::EVENT_NEW_IAUDIOTRACK :
2668 ALOGV("callbackwrapper: deliver EVENT_TEAR_DOWN");
2669 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2670 me->mCallbackCookie, CB_EVENT_TEAR_DOWN);
2671 break;
2672
Glenn Kasten421743b2015-06-01 08:18:08 -07002673 case AudioTrack::EVENT_UNDERRUN:
Andy Hung719b46b2015-05-31 22:18:25 -07002674 // This occurs when there is no data available, typically
Glenn Kasten421743b2015-06-01 08:18:08 -07002675 // when there is a failure to supply data to the AudioTrack. It can also
2676 // occur in non-offloaded mode when the audio device comes out of standby.
2677 //
Andy Hung719b46b2015-05-31 22:18:25 -07002678 // If an AudioTrack underruns it outputs silence. Since this happens suddenly
2679 // it may sound like an audible pop or glitch.
2680 //
2681 // The underrun event is sent once per track underrun; the condition is reset
2682 // when more data is sent to the AudioTrack.
Eric Laurente93cc032016-05-05 10:15:10 -07002683 ALOGD("callbackwrapper: EVENT_UNDERRUN (discarded)");
Glenn Kasten421743b2015-06-01 08:18:08 -07002684 break;
2685
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002686 default:
2687 ALOGE("received unknown event type: %d inside CallbackWrapper !", event);
Andreas Huber51c1e0e2011-04-04 11:43:40 -07002688 }
2689
Marco Nelissen6b74d672012-02-28 16:07:44 -08002690 data->unlock();
Andreas Huber20111aa2009-07-14 16:56:47 -07002691}
2692
Glenn Kastend848eb42016-03-08 13:42:11 -08002693audio_session_t MediaPlayerService::AudioOutput::getSessionId() const
Eric Laurent8c563ed2010-10-07 18:23:03 -07002694{
Andy Hungd1c74342015-07-07 16:54:23 -07002695 Mutex::Autolock lock(mLock);
Eric Laurent8c563ed2010-10-07 18:23:03 -07002696 return mSessionId;
2697}
2698
Eric Laurent6f59db12013-07-26 17:16:50 -07002699uint32_t MediaPlayerService::AudioOutput::getSampleRate() const
2700{
Andy Hungd1c74342015-07-07 16:54:23 -07002701 Mutex::Autolock lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -07002702 if (mTrack == 0) return 0;
2703 return mTrack->getSampleRate();
2704}
2705
Andy Hungf2c87b32016-04-07 19:49:29 -07002706int64_t MediaPlayerService::AudioOutput::getBufferDurationInUs() const
2707{
2708 Mutex::Autolock lock(mLock);
2709 if (mTrack == 0) {
2710 return 0;
2711 }
2712 int64_t duration;
2713 if (mTrack->getBufferDurationInUs(&duration) != OK) {
2714 return 0;
2715 }
2716 return duration;
2717}
2718
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002719////////////////////////////////////////////////////////////////////////////////
2720
2721struct CallbackThread : public Thread {
2722 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
2723 MediaPlayerBase::AudioSink::AudioCallback cb,
2724 void *cookie);
2725
2726protected:
2727 virtual ~CallbackThread();
2728
2729 virtual bool threadLoop();
2730
2731private:
2732 wp<MediaPlayerBase::AudioSink> mSink;
2733 MediaPlayerBase::AudioSink::AudioCallback mCallback;
2734 void *mCookie;
2735 void *mBuffer;
2736 size_t mBufferSize;
2737
2738 CallbackThread(const CallbackThread &);
2739 CallbackThread &operator=(const CallbackThread &);
2740};
2741
2742CallbackThread::CallbackThread(
2743 const wp<MediaPlayerBase::AudioSink> &sink,
2744 MediaPlayerBase::AudioSink::AudioCallback cb,
2745 void *cookie)
2746 : mSink(sink),
2747 mCallback(cb),
2748 mCookie(cookie),
2749 mBuffer(NULL),
2750 mBufferSize(0) {
2751}
2752
2753CallbackThread::~CallbackThread() {
2754 if (mBuffer) {
2755 free(mBuffer);
2756 mBuffer = NULL;
2757 }
2758}
2759
2760bool CallbackThread::threadLoop() {
2761 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
2762 if (sink == NULL) {
2763 return false;
2764 }
2765
2766 if (mBuffer == NULL) {
2767 mBufferSize = sink->bufferSize();
2768 mBuffer = malloc(mBufferSize);
2769 }
2770
2771 size_t actualSize =
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002772 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie,
2773 MediaPlayerBase::AudioSink::CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002774
2775 if (actualSize > 0) {
2776 sink->write(mBuffer, actualSize);
Andy Hunga31335a2014-08-20 17:37:59 -07002777 // Could return false on sink->write() error or short count.
2778 // Not necessarily appropriate but would work for AudioCache behavior.
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002779 }
2780
2781 return true;
2782}
2783
2784////////////////////////////////////////////////////////////////////////////////
2785
Chong Zhange5b9b692017-05-11 11:44:56 -07002786void MediaPlayerService::addBatteryData(uint32_t params) {
2787 mBatteryTracker.addBatteryData(params);
2788}
2789
2790status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
2791 return mBatteryTracker.pullBatteryData(reply);
2792}
2793
2794MediaPlayerService::BatteryTracker::BatteryTracker() {
2795 mBatteryAudio.refCount = 0;
2796 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2797 mBatteryAudio.deviceOn[i] = 0;
2798 mBatteryAudio.lastTime[i] = 0;
2799 mBatteryAudio.totalTime[i] = 0;
2800 }
2801 // speaker is on by default
2802 mBatteryAudio.deviceOn[SPEAKER] = 1;
2803
2804 // reset battery stats
2805 // if the mediaserver has crashed, battery stats could be left
2806 // in bad state, reset the state upon service start.
2807 BatteryNotifier::getInstance().noteResetVideo();
2808}
2809
2810void MediaPlayerService::BatteryTracker::addBatteryData(uint32_t params)
Gloria Wang7cf180c2011-02-19 18:37:57 -08002811{
2812 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002813
2814 int32_t time = systemTime() / 1000000L;
2815
2816 // change audio output devices. This notification comes from AudioFlinger
2817 if ((params & kBatteryDataSpeakerOn)
2818 || (params & kBatteryDataOtherAudioDeviceOn)) {
2819
2820 int deviceOn[NUM_AUDIO_DEVICES];
2821 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2822 deviceOn[i] = 0;
2823 }
2824
2825 if ((params & kBatteryDataSpeakerOn)
2826 && (params & kBatteryDataOtherAudioDeviceOn)) {
2827 deviceOn[SPEAKER_AND_OTHER] = 1;
2828 } else if (params & kBatteryDataSpeakerOn) {
2829 deviceOn[SPEAKER] = 1;
2830 } else {
2831 deviceOn[OTHER_AUDIO_DEVICE] = 1;
2832 }
2833
2834 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2835 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
2836
2837 if (mBatteryAudio.refCount > 0) { // if playing audio
2838 if (!deviceOn[i]) {
2839 mBatteryAudio.lastTime[i] += time;
2840 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2841 mBatteryAudio.lastTime[i] = 0;
2842 } else {
2843 mBatteryAudio.lastTime[i] = 0 - time;
2844 }
2845 }
2846
2847 mBatteryAudio.deviceOn[i] = deviceOn[i];
2848 }
2849 }
2850 return;
2851 }
2852
Marco Nelissenb7848f12014-12-04 08:57:56 -08002853 // an audio stream is started
Gloria Wang9ee159b2011-02-24 14:51:45 -08002854 if (params & kBatteryDataAudioFlingerStart) {
2855 // record the start time only if currently no other audio
2856 // is being played
2857 if (mBatteryAudio.refCount == 0) {
2858 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2859 if (mBatteryAudio.deviceOn[i]) {
2860 mBatteryAudio.lastTime[i] -= time;
2861 }
2862 }
2863 }
2864
2865 mBatteryAudio.refCount ++;
2866 return;
2867
2868 } else if (params & kBatteryDataAudioFlingerStop) {
2869 if (mBatteryAudio.refCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002870 ALOGW("Battery track warning: refCount is <= 0");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002871 return;
2872 }
2873
2874 // record the stop time only if currently this is the only
2875 // audio being played
2876 if (mBatteryAudio.refCount == 1) {
2877 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2878 if (mBatteryAudio.deviceOn[i]) {
2879 mBatteryAudio.lastTime[i] += time;
2880 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2881 mBatteryAudio.lastTime[i] = 0;
2882 }
2883 }
2884 }
2885
2886 mBatteryAudio.refCount --;
2887 return;
2888 }
2889
Andy Hung1afd0982016-11-08 16:13:44 -08002890 uid_t uid = IPCThreadState::self()->getCallingUid();
Gloria Wang7cf180c2011-02-19 18:37:57 -08002891 if (uid == AID_MEDIA) {
2892 return;
2893 }
2894 int index = mBatteryData.indexOfKey(uid);
Gloria Wang7cf180c2011-02-19 18:37:57 -08002895
2896 if (index < 0) { // create a new entry for this UID
2897 BatteryUsageInfo info;
2898 info.audioTotalTime = 0;
2899 info.videoTotalTime = 0;
2900 info.audioLastTime = 0;
2901 info.videoLastTime = 0;
2902 info.refCount = 0;
2903
Gloria Wang9ee159b2011-02-24 14:51:45 -08002904 if (mBatteryData.add(uid, info) == NO_MEMORY) {
Steve Block29357bc2012-01-06 19:20:56 +00002905 ALOGE("Battery track error: no memory for new app");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002906 return;
2907 }
Gloria Wang7cf180c2011-02-19 18:37:57 -08002908 }
2909
2910 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
2911
2912 if (params & kBatteryDataCodecStarted) {
2913 if (params & kBatteryDataTrackAudio) {
2914 info.audioLastTime -= time;
2915 info.refCount ++;
2916 }
2917 if (params & kBatteryDataTrackVideo) {
2918 info.videoLastTime -= time;
2919 info.refCount ++;
2920 }
2921 } else {
2922 if (info.refCount == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002923 ALOGW("Battery track warning: refCount is already 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002924 return;
2925 } else if (info.refCount < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00002926 ALOGE("Battery track error: refCount < 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002927 mBatteryData.removeItem(uid);
2928 return;
2929 }
2930
2931 if (params & kBatteryDataTrackAudio) {
2932 info.audioLastTime += time;
2933 info.refCount --;
2934 }
2935 if (params & kBatteryDataTrackVideo) {
2936 info.videoLastTime += time;
2937 info.refCount --;
2938 }
2939
2940 // no stream is being played by this UID
2941 if (info.refCount == 0) {
2942 info.audioTotalTime += info.audioLastTime;
2943 info.audioLastTime = 0;
2944 info.videoTotalTime += info.videoLastTime;
2945 info.videoLastTime = 0;
2946 }
2947 }
2948}
2949
Chong Zhange5b9b692017-05-11 11:44:56 -07002950status_t MediaPlayerService::BatteryTracker::pullBatteryData(Parcel* reply) {
Gloria Wang7cf180c2011-02-19 18:37:57 -08002951 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002952
2953 // audio output devices usage
2954 int32_t time = systemTime() / 1000000L; //in ms
2955 int32_t totalTime;
2956
2957 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2958 totalTime = mBatteryAudio.totalTime[i];
2959
2960 if (mBatteryAudio.deviceOn[i]
2961 && (mBatteryAudio.lastTime[i] != 0)) {
2962 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
2963 totalTime += tmpTime;
2964 }
2965
2966 reply->writeInt32(totalTime);
2967 // reset the total time
2968 mBatteryAudio.totalTime[i] = 0;
2969 }
2970
2971 // codec usage
Gloria Wang7cf180c2011-02-19 18:37:57 -08002972 BatteryUsageInfo info;
2973 int size = mBatteryData.size();
2974
2975 reply->writeInt32(size);
2976 int i = 0;
2977
2978 while (i < size) {
2979 info = mBatteryData.valueAt(i);
2980
2981 reply->writeInt32(mBatteryData.keyAt(i)); //UID
2982 reply->writeInt32(info.audioTotalTime);
2983 reply->writeInt32(info.videoTotalTime);
2984
2985 info.audioTotalTime = 0;
2986 info.videoTotalTime = 0;
2987
2988 // remove the UID entry where no stream is being played
2989 if (info.refCount <= 0) {
2990 mBatteryData.removeItemsAt(i);
2991 size --;
2992 i --;
2993 }
2994 i++;
2995 }
2996 return NO_ERROR;
2997}
nikoa64c8c72009-07-20 15:07:26 -07002998} // namespace android