blob: 77a56d10db7ee9ef1131d75e03ef8f37960ba56e [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
Byeongjo Park28225ab2019-01-24 20:31:19 +09001066status_t MediaPlayerService::Client::setDataSource(
1067 const String8& rtpParams) {
1068 player_type playerType = NU_PLAYER;
1069 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
1070 if (p == NULL) {
1071 return NO_INIT;
1072 }
1073 // now set data source
1074 return mStatus = setDataSource_post(p, p->setDataSource(rtpParams));
1075}
1076
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001077void MediaPlayerService::Client::disconnectNativeWindow_l() {
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001078 if (mConnectedWindow != NULL) {
Chong Zhang181fd9b2017-02-16 15:53:03 -08001079 status_t err = nativeWindowDisconnect(
1080 mConnectedWindow.get(), "disconnectNativeWindow");
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001081
1082 if (err != OK) {
Chong Zhang181fd9b2017-02-16 15:53:03 -08001083 ALOGW("nativeWindowDisconnect returned an error: %s (%d)",
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001084 strerror(-err), err);
1085 }
1086 }
1087 mConnectedWindow.clear();
1088}
1089
Glenn Kasten11731182011-02-08 17:26:17 -08001090status_t MediaPlayerService::Client::setVideoSurfaceTexture(
Andy McFadden484566c2012-12-18 09:46:54 -08001091 const sp<IGraphicBufferProducer>& bufferProducer)
Glenn Kasten11731182011-02-08 17:26:17 -08001092{
Andy McFadden484566c2012-12-18 09:46:54 -08001093 ALOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, bufferProducer.get());
Glenn Kasten11731182011-02-08 17:26:17 -08001094 sp<MediaPlayerBase> p = getPlayer();
1095 if (p == 0) return UNKNOWN_ERROR;
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001096
Marco Nelissenf8880202014-11-14 07:58:25 -08001097 sp<IBinder> binder(IInterface::asBinder(bufferProducer));
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001098 if (mConnectedWindowBinder == binder) {
1099 return OK;
1100 }
1101
1102 sp<ANativeWindow> anw;
Andy McFadden484566c2012-12-18 09:46:54 -08001103 if (bufferProducer != NULL) {
Marco Nelissenee08f7e2013-09-16 13:30:01 -07001104 anw = new Surface(bufferProducer, true /* controlledByApp */);
Chong Zhang181fd9b2017-02-16 15:53:03 -08001105 status_t err = nativeWindowConnect(anw.get(), "setVideoSurfaceTexture");
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001106
1107 if (err != OK) {
Steve Block29357bc2012-01-06 19:20:56 +00001108 ALOGE("setVideoSurfaceTexture failed: %d", err);
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001109 // Note that we must do the reset before disconnecting from the ANW.
1110 // Otherwise queue/dequeue calls could be made on the disconnected
1111 // ANW, which may result in errors.
1112 reset();
1113
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001114 Mutex::Autolock lock(mLock);
1115 disconnectNativeWindow_l();
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001116
1117 return err;
1118 }
1119 }
1120
Andy McFadden484566c2012-12-18 09:46:54 -08001121 // Note that we must set the player's new GraphicBufferProducer before
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001122 // disconnecting the old one. Otherwise queue/dequeue calls could be made
1123 // on the disconnected ANW, which may result in errors.
Andy McFadden484566c2012-12-18 09:46:54 -08001124 status_t err = p->setVideoSurfaceTexture(bufferProducer);
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001125
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001126 mLock.lock();
1127 disconnectNativeWindow_l();
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001128
1129 if (err == OK) {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001130 mConnectedWindow = anw;
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001131 mConnectedWindowBinder = binder;
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001132 mLock.unlock();
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001133 } else {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001134 mLock.unlock();
1135 status_t err = nativeWindowDisconnect(
1136 anw.get(), "disconnectNativeWindow");
1137
1138 if (err != OK) {
1139 ALOGW("nativeWindowDisconnect returned an error: %s (%d)",
1140 strerror(-err), err);
1141 }
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001142 }
1143
1144 return err;
Glenn Kasten11731182011-02-08 17:26:17 -08001145}
1146
Nicolas Catania1d187f12009-05-12 23:25:55 -07001147status_t MediaPlayerService::Client::invoke(const Parcel& request,
1148 Parcel *reply)
1149{
1150 sp<MediaPlayerBase> p = getPlayer();
1151 if (p == NULL) return UNKNOWN_ERROR;
1152 return p->invoke(request, reply);
1153}
1154
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001155// This call doesn't need to access the native player.
1156status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
1157{
1158 status_t status;
nikoa64c8c72009-07-20 15:07:26 -07001159 media::Metadata::Filter allow, drop;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001160
Nicolas Catania48290382009-07-10 13:53:06 -07001161 if (unmarshallFilter(filter, &allow, &status) &&
1162 unmarshallFilter(filter, &drop, &status)) {
1163 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001164
1165 mMetadataAllow = allow;
1166 mMetadataDrop = drop;
1167 }
1168 return status;
1169}
1170
Nicolas Catania48290382009-07-10 13:53:06 -07001171status_t MediaPlayerService::Client::getMetadata(
Mark Salyzyn77342f72014-06-18 16:31:32 -07001172 bool update_only, bool /*apply_filter*/, Parcel *reply)
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001173{
nikoa64c8c72009-07-20 15:07:26 -07001174 sp<MediaPlayerBase> player = getPlayer();
1175 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania48290382009-07-10 13:53:06 -07001176
nikod608a812009-07-16 16:39:53 -07001177 status_t status;
1178 // Placeholder for the return code, updated by the caller.
1179 reply->writeInt32(-1);
1180
nikoa64c8c72009-07-20 15:07:26 -07001181 media::Metadata::Filter ids;
Nicolas Catania48290382009-07-10 13:53:06 -07001182
1183 // We don't block notifications while we fetch the data. We clear
1184 // mMetadataUpdated first so we don't lose notifications happening
1185 // during the rest of this call.
1186 {
1187 Mutex::Autolock lock(mLock);
1188 if (update_only) {
nikod608a812009-07-16 16:39:53 -07001189 ids = mMetadataUpdated;
Nicolas Catania48290382009-07-10 13:53:06 -07001190 }
1191 mMetadataUpdated.clear();
1192 }
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001193
nikoa64c8c72009-07-20 15:07:26 -07001194 media::Metadata metadata(reply);
Nicolas Catania48290382009-07-10 13:53:06 -07001195
nikoa64c8c72009-07-20 15:07:26 -07001196 metadata.appendHeader();
1197 status = player->getMetadata(ids, reply);
nikod608a812009-07-16 16:39:53 -07001198
1199 if (status != OK) {
nikoa64c8c72009-07-20 15:07:26 -07001200 metadata.resetParcel();
Steve Block29357bc2012-01-06 19:20:56 +00001201 ALOGE("getMetadata failed %d", status);
nikod608a812009-07-16 16:39:53 -07001202 return status;
1203 }
1204
1205 // FIXME: Implement filtering on the result. Not critical since
1206 // filtering takes place on the update notifications already. This
1207 // would be when all the metadata are fetch and a filter is set.
1208
nikod608a812009-07-16 16:39:53 -07001209 // Everything is fine, update the metadata length.
nikoa64c8c72009-07-20 15:07:26 -07001210 metadata.updateLength();
nikod608a812009-07-16 16:39:53 -07001211 return OK;
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001212}
1213
Wei Jiad399e7e2016-10-26 15:49:11 -07001214status_t MediaPlayerService::Client::setBufferingSettings(
1215 const BufferingSettings& buffering)
1216{
Wei Jiadc6f3402017-01-09 15:04:18 -08001217 ALOGV("[%d] setBufferingSettings{%s}",
1218 mConnId, buffering.toString().string());
Wei Jiad399e7e2016-10-26 15:49:11 -07001219 sp<MediaPlayerBase> p = getPlayer();
1220 if (p == 0) return UNKNOWN_ERROR;
1221 return p->setBufferingSettings(buffering);
1222}
1223
Wei Jia9bb38032017-03-23 18:00:38 -07001224status_t MediaPlayerService::Client::getBufferingSettings(
Wei Jiad399e7e2016-10-26 15:49:11 -07001225 BufferingSettings* buffering /* nonnull */)
1226{
1227 sp<MediaPlayerBase> p = getPlayer();
1228 // TODO: create mPlayer on demand.
1229 if (p == 0) return UNKNOWN_ERROR;
Wei Jia9bb38032017-03-23 18:00:38 -07001230 status_t ret = p->getBufferingSettings(buffering);
Wei Jiad399e7e2016-10-26 15:49:11 -07001231 if (ret == NO_ERROR) {
Wei Jia9bb38032017-03-23 18:00:38 -07001232 ALOGV("[%d] getBufferingSettings{%s}",
Wei Jiadc6f3402017-01-09 15:04:18 -08001233 mConnId, buffering->toString().string());
Wei Jiad399e7e2016-10-26 15:49:11 -07001234 } else {
Wei Jia9bb38032017-03-23 18:00:38 -07001235 ALOGE("[%d] getBufferingSettings returned %d", mConnId, ret);
Wei Jiad399e7e2016-10-26 15:49:11 -07001236 }
1237 return ret;
1238}
1239
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001240status_t MediaPlayerService::Client::prepareAsync()
1241{
Steve Block3856b092011-10-20 11:56:00 +01001242 ALOGV("[%d] prepareAsync", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001243 sp<MediaPlayerBase> p = getPlayer();
1244 if (p == 0) return UNKNOWN_ERROR;
1245 status_t ret = p->prepareAsync();
1246#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +00001247 ALOGD("start Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001248 if (ret == NO_ERROR) mAntagonizer->start();
1249#endif
1250 return ret;
1251}
1252
1253status_t MediaPlayerService::Client::start()
1254{
Steve Block3856b092011-10-20 11:56:00 +01001255 ALOGV("[%d] start", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001256 sp<MediaPlayerBase> p = getPlayer();
1257 if (p == 0) return UNKNOWN_ERROR;
1258 p->setLooping(mLoop);
1259 return p->start();
1260}
1261
1262status_t MediaPlayerService::Client::stop()
1263{
Steve Block3856b092011-10-20 11:56:00 +01001264 ALOGV("[%d] stop", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001265 sp<MediaPlayerBase> p = getPlayer();
1266 if (p == 0) return UNKNOWN_ERROR;
1267 return p->stop();
1268}
1269
1270status_t MediaPlayerService::Client::pause()
1271{
Steve Block3856b092011-10-20 11:56:00 +01001272 ALOGV("[%d] pause", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001273 sp<MediaPlayerBase> p = getPlayer();
1274 if (p == 0) return UNKNOWN_ERROR;
1275 return p->pause();
1276}
1277
1278status_t MediaPlayerService::Client::isPlaying(bool* state)
1279{
1280 *state = false;
1281 sp<MediaPlayerBase> p = getPlayer();
1282 if (p == 0) return UNKNOWN_ERROR;
1283 *state = p->isPlaying();
Steve Block3856b092011-10-20 11:56:00 +01001284 ALOGV("[%d] isPlaying: %d", mConnId, *state);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001285 return NO_ERROR;
1286}
1287
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001288status_t MediaPlayerService::Client::setPlaybackSettings(const AudioPlaybackRate& rate)
Wei Jia98160162015-02-04 17:01:11 -08001289{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001290 ALOGV("[%d] setPlaybackSettings(%f, %f, %d, %d)",
1291 mConnId, rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Wei Jia98160162015-02-04 17:01:11 -08001292 sp<MediaPlayerBase> p = getPlayer();
1293 if (p == 0) return UNKNOWN_ERROR;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001294 return p->setPlaybackSettings(rate);
1295}
1296
1297status_t MediaPlayerService::Client::getPlaybackSettings(AudioPlaybackRate* rate /* nonnull */)
1298{
1299 sp<MediaPlayerBase> p = getPlayer();
1300 if (p == 0) return UNKNOWN_ERROR;
1301 status_t ret = p->getPlaybackSettings(rate);
1302 if (ret == NO_ERROR) {
1303 ALOGV("[%d] getPlaybackSettings(%f, %f, %d, %d)",
1304 mConnId, rate->mSpeed, rate->mPitch, rate->mFallbackMode, rate->mStretchMode);
1305 } else {
1306 ALOGV("[%d] getPlaybackSettings returned %d", mConnId, ret);
1307 }
1308 return ret;
1309}
1310
1311status_t MediaPlayerService::Client::setSyncSettings(
1312 const AVSyncSettings& sync, float videoFpsHint)
1313{
1314 ALOGV("[%d] setSyncSettings(%u, %u, %f, %f)",
1315 mConnId, sync.mSource, sync.mAudioAdjustMode, sync.mTolerance, videoFpsHint);
1316 sp<MediaPlayerBase> p = getPlayer();
1317 if (p == 0) return UNKNOWN_ERROR;
1318 return p->setSyncSettings(sync, videoFpsHint);
1319}
1320
1321status_t MediaPlayerService::Client::getSyncSettings(
1322 AVSyncSettings* sync /* nonnull */, float* videoFps /* nonnull */)
1323{
1324 sp<MediaPlayerBase> p = getPlayer();
1325 if (p == 0) return UNKNOWN_ERROR;
1326 status_t ret = p->getSyncSettings(sync, videoFps);
1327 if (ret == NO_ERROR) {
1328 ALOGV("[%d] getSyncSettings(%u, %u, %f, %f)",
1329 mConnId, sync->mSource, sync->mAudioAdjustMode, sync->mTolerance, *videoFps);
1330 } else {
1331 ALOGV("[%d] getSyncSettings returned %d", mConnId, ret);
1332 }
1333 return ret;
Wei Jia98160162015-02-04 17:01:11 -08001334}
1335
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001336status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
1337{
Steve Block3856b092011-10-20 11:56:00 +01001338 ALOGV("getCurrentPosition");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001339 sp<MediaPlayerBase> p = getPlayer();
1340 if (p == 0) return UNKNOWN_ERROR;
1341 status_t ret = p->getCurrentPosition(msec);
1342 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001343 ALOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001344 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001345 ALOGE("getCurrentPosition returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001346 }
1347 return ret;
1348}
1349
1350status_t MediaPlayerService::Client::getDuration(int *msec)
1351{
Steve Block3856b092011-10-20 11:56:00 +01001352 ALOGV("getDuration");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001353 sp<MediaPlayerBase> p = getPlayer();
1354 if (p == 0) return UNKNOWN_ERROR;
1355 status_t ret = p->getDuration(msec);
1356 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001357 ALOGV("[%d] getDuration = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001358 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001359 ALOGE("getDuration returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001360 }
1361 return ret;
1362}
1363
Marco Nelissen6b74d672012-02-28 16:07:44 -08001364status_t MediaPlayerService::Client::setNextPlayer(const sp<IMediaPlayer>& player) {
1365 ALOGV("setNextPlayer");
1366 Mutex::Autolock l(mLock);
1367 sp<Client> c = static_cast<Client*>(player.get());
Wei Jia28284122016-08-30 13:49:06 -07001368 if (c != NULL && !mService->hasClient(c)) {
Robert Shihee0a0e32016-08-16 16:50:54 -07001369 return BAD_VALUE;
1370 }
1371
Marco Nelissen6b74d672012-02-28 16:07:44 -08001372 mNextClient = c;
John Grossman5f7e55e2012-08-24 14:47:25 -07001373
1374 if (c != NULL) {
1375 if (mAudioOutput != NULL) {
1376 mAudioOutput->setNextOutput(c->mAudioOutput);
1377 } else if ((mPlayer != NULL) && !mPlayer->hardwareOutput()) {
1378 ALOGE("no current audio output");
1379 }
1380
1381 if ((mPlayer != NULL) && (mNextClient->getPlayer() != NULL)) {
1382 mPlayer->setNextPlayer(mNextClient->getPlayer());
1383 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001384 }
John Grossman5f7e55e2012-08-24 14:47:25 -07001385
Marco Nelissen6b74d672012-02-28 16:07:44 -08001386 return OK;
1387}
1388
Andy Hung9fc8b5c2017-01-24 13:36:48 -08001389VolumeShaper::Status MediaPlayerService::Client::applyVolumeShaper(
1390 const sp<VolumeShaper::Configuration>& configuration,
1391 const sp<VolumeShaper::Operation>& operation) {
1392 // for hardware output, call player instead
1393 ALOGV("Client::applyVolumeShaper(%p)", this);
1394 sp<MediaPlayerBase> p = getPlayer();
1395 {
1396 Mutex::Autolock l(mLock);
1397 if (p != 0 && p->hardwareOutput()) {
1398 // TODO: investigate internal implementation
1399 return VolumeShaper::Status(INVALID_OPERATION);
1400 }
1401 if (mAudioOutput.get() != nullptr) {
1402 return mAudioOutput->applyVolumeShaper(configuration, operation);
1403 }
1404 }
1405 return VolumeShaper::Status(INVALID_OPERATION);
1406}
1407
1408sp<VolumeShaper::State> MediaPlayerService::Client::getVolumeShaperState(int id) {
1409 // for hardware output, call player instead
1410 ALOGV("Client::getVolumeShaperState(%p)", this);
1411 sp<MediaPlayerBase> p = getPlayer();
1412 {
1413 Mutex::Autolock l(mLock);
1414 if (p != 0 && p->hardwareOutput()) {
1415 // TODO: investigate internal implementation.
1416 return nullptr;
1417 }
1418 if (mAudioOutput.get() != nullptr) {
1419 return mAudioOutput->getVolumeShaperState(id);
1420 }
1421 }
1422 return nullptr;
1423}
1424
Wei Jiac5de0912016-11-18 10:22:14 -08001425status_t MediaPlayerService::Client::seekTo(int msec, MediaPlayerSeekMode mode)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001426{
Wei Jiac5de0912016-11-18 10:22:14 -08001427 ALOGV("[%d] seekTo(%d, %d)", mConnId, msec, mode);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001428 sp<MediaPlayerBase> p = getPlayer();
1429 if (p == 0) return UNKNOWN_ERROR;
Wei Jiac5de0912016-11-18 10:22:14 -08001430 return p->seekTo(msec, mode);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001431}
1432
1433status_t MediaPlayerService::Client::reset()
1434{
Steve Block3856b092011-10-20 11:56:00 +01001435 ALOGV("[%d] reset", mConnId);
John Grossmanc795b642012-02-22 15:38:35 -08001436 mRetransmitEndpointValid = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001437 sp<MediaPlayerBase> p = getPlayer();
1438 if (p == 0) return UNKNOWN_ERROR;
1439 return p->reset();
1440}
1441
Wei Jia52c28512017-09-13 18:17:51 -07001442status_t MediaPlayerService::Client::notifyAt(int64_t mediaTimeUs)
1443{
1444 ALOGV("[%d] notifyAt(%lld)", mConnId, (long long)mediaTimeUs);
1445 sp<MediaPlayerBase> p = getPlayer();
1446 if (p == 0) return UNKNOWN_ERROR;
1447 return p->notifyAt(mediaTimeUs);
1448}
1449
Glenn Kastenfff6d712012-01-12 16:38:12 -08001450status_t MediaPlayerService::Client::setAudioStreamType(audio_stream_type_t type)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001451{
Steve Block3856b092011-10-20 11:56:00 +01001452 ALOGV("[%d] setAudioStreamType(%d)", mConnId, type);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001453 // TODO: for hardware output, call player instead
1454 Mutex::Autolock l(mLock);
1455 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1456 return NO_ERROR;
1457}
1458
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001459status_t MediaPlayerService::Client::setAudioAttributes_l(const Parcel &parcel)
1460{
1461 if (mAudioAttributes != NULL) { free(mAudioAttributes); }
1462 mAudioAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001463 if (mAudioAttributes == NULL) {
1464 return NO_MEMORY;
1465 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001466 unmarshallAudioAttributes(parcel, mAudioAttributes);
1467
1468 ALOGV("setAudioAttributes_l() usage=%d content=%d flags=0x%x tags=%s",
1469 mAudioAttributes->usage, mAudioAttributes->content_type, mAudioAttributes->flags,
1470 mAudioAttributes->tags);
1471
1472 if (mAudioOutput != 0) {
1473 mAudioOutput->setAudioAttributes(mAudioAttributes);
1474 }
1475 return NO_ERROR;
1476}
1477
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001478status_t MediaPlayerService::Client::setLooping(int loop)
1479{
Steve Block3856b092011-10-20 11:56:00 +01001480 ALOGV("[%d] setLooping(%d)", mConnId, loop);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001481 mLoop = loop;
1482 sp<MediaPlayerBase> p = getPlayer();
1483 if (p != 0) return p->setLooping(loop);
1484 return NO_ERROR;
1485}
1486
1487status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1488{
Steve Block3856b092011-10-20 11:56:00 +01001489 ALOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
John Grossman761defc2012-02-09 15:09:05 -08001490
1491 // for hardware output, call player instead
1492 sp<MediaPlayerBase> p = getPlayer();
1493 {
1494 Mutex::Autolock l(mLock);
1495 if (p != 0 && p->hardwareOutput()) {
1496 MediaPlayerHWInterface* hwp =
1497 reinterpret_cast<MediaPlayerHWInterface*>(p.get());
1498 return hwp->setVolume(leftVolume, rightVolume);
1499 } else {
1500 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1501 return NO_ERROR;
1502 }
1503 }
1504
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001505 return NO_ERROR;
1506}
1507
Eric Laurent2beeb502010-07-16 07:43:46 -07001508status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1509{
Steve Block3856b092011-10-20 11:56:00 +01001510 ALOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
Eric Laurent2beeb502010-07-16 07:43:46 -07001511 Mutex::Autolock l(mLock);
1512 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1513 return NO_ERROR;
1514}
1515
1516status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1517{
Steve Block3856b092011-10-20 11:56:00 +01001518 ALOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
Eric Laurent2beeb502010-07-16 07:43:46 -07001519 Mutex::Autolock l(mLock);
1520 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1521 return NO_ERROR;
1522}
Nicolas Catania48290382009-07-10 13:53:06 -07001523
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001524status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
Steve Block3856b092011-10-20 11:56:00 +01001525 ALOGV("[%d] setParameter(%d)", mConnId, key);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001526 switch (key) {
1527 case KEY_PARAMETER_AUDIO_ATTRIBUTES:
1528 {
1529 Mutex::Autolock l(mLock);
1530 return setAudioAttributes_l(request);
1531 }
1532 default:
1533 sp<MediaPlayerBase> p = getPlayer();
1534 if (p == 0) { return UNKNOWN_ERROR; }
1535 return p->setParameter(key, request);
1536 }
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001537}
1538
1539status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
Steve Block3856b092011-10-20 11:56:00 +01001540 ALOGV("[%d] getParameter(%d)", mConnId, key);
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001541 sp<MediaPlayerBase> p = getPlayer();
1542 if (p == 0) return UNKNOWN_ERROR;
1543 return p->getParameter(key, reply);
1544}
1545
John Grossmanc795b642012-02-22 15:38:35 -08001546status_t MediaPlayerService::Client::setRetransmitEndpoint(
1547 const struct sockaddr_in* endpoint) {
1548
1549 if (NULL != endpoint) {
1550 uint32_t a = ntohl(endpoint->sin_addr.s_addr);
1551 uint16_t p = ntohs(endpoint->sin_port);
1552 ALOGV("[%d] setRetransmitEndpoint(%u.%u.%u.%u:%hu)", mConnId,
1553 (a >> 24), (a >> 16) & 0xFF, (a >> 8) & 0xFF, (a & 0xFF), p);
1554 } else {
1555 ALOGV("[%d] setRetransmitEndpoint = <none>", mConnId);
1556 }
1557
1558 sp<MediaPlayerBase> p = getPlayer();
1559
1560 // Right now, the only valid time to set a retransmit endpoint is before
1561 // player selection has been made (since the presence or absence of a
1562 // retransmit endpoint is going to determine which player is selected during
1563 // setDataSource).
1564 if (p != 0) return INVALID_OPERATION;
1565
1566 if (NULL != endpoint) {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001567 Mutex::Autolock lock(mLock);
John Grossmanc795b642012-02-22 15:38:35 -08001568 mRetransmitEndpoint = *endpoint;
1569 mRetransmitEndpointValid = true;
1570 } else {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001571 Mutex::Autolock lock(mLock);
John Grossmanc795b642012-02-22 15:38:35 -08001572 mRetransmitEndpointValid = false;
1573 }
1574
1575 return NO_ERROR;
1576}
1577
John Grossman44a7e422012-06-21 17:29:24 -07001578status_t MediaPlayerService::Client::getRetransmitEndpoint(
1579 struct sockaddr_in* endpoint)
1580{
1581 if (NULL == endpoint)
1582 return BAD_VALUE;
1583
1584 sp<MediaPlayerBase> p = getPlayer();
1585
1586 if (p != NULL)
1587 return p->getRetransmitEndpoint(endpoint);
1588
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001589 Mutex::Autolock lock(mLock);
John Grossman44a7e422012-06-21 17:29:24 -07001590 if (!mRetransmitEndpointValid)
1591 return NO_INIT;
1592
1593 *endpoint = mRetransmitEndpoint;
1594
1595 return NO_ERROR;
1596}
1597
Gloria Wangb483c472011-04-11 17:23:27 -07001598void MediaPlayerService::Client::notify(
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001599 int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001600{
James Dongb8a98252012-08-26 16:13:03 -07001601 sp<IMediaPlayerClient> c;
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001602 sp<Client> nextClient;
1603 status_t errStartNext = NO_ERROR;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001604 {
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001605 Mutex::Autolock l(mLock);
1606 c = mClient;
1607 if (msg == MEDIA_PLAYBACK_COMPLETE && mNextClient != NULL) {
1608 nextClient = mNextClient;
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001609
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001610 if (mAudioOutput != NULL)
1611 mAudioOutput->switchToNextOutput();
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001612
1613 errStartNext = nextClient->start();
1614 }
1615 }
1616
1617 if (nextClient != NULL) {
1618 sp<IMediaPlayerClient> nc;
1619 {
1620 Mutex::Autolock l(nextClient->mLock);
1621 nc = nextClient->mClient;
1622 }
1623 if (nc != NULL) {
1624 if (errStartNext == NO_ERROR) {
1625 nc->notify(MEDIA_INFO, MEDIA_INFO_STARTED_AS_NEXT, 0, obj);
1626 } else {
1627 nc->notify(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN , 0, obj);
1628 ALOGE("gapless:start playback for next track failed, err(%d)", errStartNext);
Wei Jia2afac0c2016-01-07 12:13:07 -08001629 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001630 }
1631 }
1632
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001633 if (MEDIA_INFO == msg &&
Nicolas Catania48290382009-07-10 13:53:06 -07001634 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikoa64c8c72009-07-20 15:07:26 -07001635 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania48290382009-07-10 13:53:06 -07001636
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001637 if(shouldDropMetadata(metadata_type)) {
Nicolas Catania48290382009-07-10 13:53:06 -07001638 return;
1639 }
1640
1641 // Update the list of metadata that have changed. getMetadata
1642 // also access mMetadataUpdated and clears it.
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001643 addNewMetadataUpdate(metadata_type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001644 }
James Dongb8a98252012-08-26 16:13:03 -07001645
1646 if (c != NULL) {
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001647 ALOGV("[%d] notify (%d, %d, %d)", mConnId, msg, ext1, ext2);
James Dongb8a98252012-08-26 16:13:03 -07001648 c->notify(msg, ext1, ext2, obj);
1649 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001650}
1651
Nicolas Catania48290382009-07-10 13:53:06 -07001652
nikoa64c8c72009-07-20 15:07:26 -07001653bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001654{
Nicolas Catania48290382009-07-10 13:53:06 -07001655 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001656
Nicolas Catania48290382009-07-10 13:53:06 -07001657 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001658 return true;
1659 }
1660
Nicolas Catania48290382009-07-10 13:53:06 -07001661 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001662 return false;
Nicolas Catania48290382009-07-10 13:53:06 -07001663 } else {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001664 return true;
1665 }
1666}
1667
Nicolas Catania48290382009-07-10 13:53:06 -07001668
nikoa64c8c72009-07-20 15:07:26 -07001669void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania48290382009-07-10 13:53:06 -07001670 Mutex::Autolock lock(mLock);
1671 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1672 mMetadataUpdated.add(metadata_type);
1673 }
1674}
1675
Hassan Shojaniacefac142017-02-06 21:02:02 -08001676// Modular DRM
1677status_t MediaPlayerService::Client::prepareDrm(const uint8_t uuid[16],
1678 const Vector<uint8_t>& drmSessionId)
1679{
1680 ALOGV("[%d] prepareDrm", mConnId);
1681 sp<MediaPlayerBase> p = getPlayer();
1682 if (p == 0) return UNKNOWN_ERROR;
1683
1684 status_t ret = p->prepareDrm(uuid, drmSessionId);
1685 ALOGV("prepareDrm ret: %d", ret);
1686
1687 return ret;
1688}
1689
1690status_t MediaPlayerService::Client::releaseDrm()
1691{
1692 ALOGV("[%d] releaseDrm", mConnId);
1693 sp<MediaPlayerBase> p = getPlayer();
1694 if (p == 0) return UNKNOWN_ERROR;
1695
1696 status_t ret = p->releaseDrm();
1697 ALOGV("releaseDrm ret: %d", ret);
1698
1699 return ret;
1700}
1701
jiabin156c6872017-10-06 09:47:15 -07001702status_t MediaPlayerService::Client::setOutputDevice(audio_port_handle_t deviceId)
1703{
1704 ALOGV("[%d] setOutputDevice", mConnId);
1705 {
1706 Mutex::Autolock l(mLock);
1707 if (mAudioOutput.get() != nullptr) {
1708 return mAudioOutput->setOutputDevice(deviceId);
1709 }
1710 }
1711 return NO_INIT;
1712}
1713
1714status_t MediaPlayerService::Client::getRoutedDeviceId(audio_port_handle_t* deviceId)
1715{
1716 ALOGV("[%d] getRoutedDeviceId", mConnId);
1717 {
1718 Mutex::Autolock l(mLock);
1719 if (mAudioOutput.get() != nullptr) {
1720 return mAudioOutput->getRoutedDeviceId(deviceId);
1721 }
1722 }
1723 return NO_INIT;
1724}
1725
1726status_t MediaPlayerService::Client::enableAudioDeviceCallback(bool enabled)
1727{
1728 ALOGV("[%d] enableAudioDeviceCallback, %d", mConnId, enabled);
1729 {
1730 Mutex::Autolock l(mLock);
1731 if (mAudioOutput.get() != nullptr) {
1732 return mAudioOutput->enableAudioDeviceCallback(enabled);
1733 }
1734 }
1735 return NO_INIT;
1736}
1737
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001738#if CALLBACK_ANTAGONIZER
1739const int Antagonizer::interval = 10000; // 10 msecs
1740
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001741Antagonizer::Antagonizer(const sp<MediaPlayerBase::Listener> &listener) :
1742 mExit(false), mActive(false), mListener(listener)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001743{
1744 createThread(callbackThread, this);
1745}
1746
1747void Antagonizer::kill()
1748{
1749 Mutex::Autolock _l(mLock);
1750 mActive = false;
1751 mExit = true;
1752 mCondition.wait(mLock);
1753}
1754
1755int Antagonizer::callbackThread(void* user)
1756{
Steve Blockb8a80522011-12-20 16:23:08 +00001757 ALOGD("Antagonizer started");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001758 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1759 while (!p->mExit) {
1760 if (p->mActive) {
Steve Block3856b092011-10-20 11:56:00 +01001761 ALOGV("send event");
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001762 p->mListener->notify(0, 0, 0, 0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001763 }
1764 usleep(interval);
1765 }
1766 Mutex::Autolock _l(p->mLock);
1767 p->mCondition.signal();
Steve Blockb8a80522011-12-20 16:23:08 +00001768 ALOGD("Antagonizer stopped");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001769 return 0;
1770}
1771#endif
1772
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001773#undef LOG_TAG
1774#define LOG_TAG "AudioSink"
Andy Hung1afd0982016-11-08 16:13:44 -08001775MediaPlayerService::AudioOutput::AudioOutput(audio_session_t sessionId, uid_t uid, int pid,
jiabin156c6872017-10-06 09:47:15 -07001776 const audio_attributes_t* attr, const sp<AudioSystem::AudioDeviceCallback>& deviceCallback)
Andreas Huber20111aa2009-07-14 16:56:47 -07001777 : mCallback(NULL),
Eric Laurenta514bdb2010-06-21 09:27:30 -07001778 mCallbackCookie(NULL),
Marco Nelissen6b74d672012-02-28 16:07:44 -08001779 mCallbackData(NULL),
Andy Hungd1c74342015-07-07 16:54:23 -07001780 mStreamType(AUDIO_STREAM_MUSIC),
Andy Hungd1c74342015-07-07 16:54:23 -07001781 mLeftVolume(1.0),
1782 mRightVolume(1.0),
1783 mPlaybackRate(AUDIO_PLAYBACK_RATE_DEFAULT),
1784 mSampleRateHz(0),
1785 mMsecsPerFrame(0),
1786 mFrameSize(0),
Eric Laurent1948eb32012-04-13 16:50:19 -07001787 mSessionId(sessionId),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001788 mUid(uid),
Marco Nelissend457c972014-02-11 08:47:07 -08001789 mPid(pid),
Andy Hungd1c74342015-07-07 16:54:23 -07001790 mSendLevel(0.0),
1791 mAuxEffectId(0),
Andy Hung4ef88d72017-02-21 19:47:53 -08001792 mFlags(AUDIO_OUTPUT_FLAG_NONE),
jiabin156c6872017-10-06 09:47:15 -07001793 mVolumeHandler(new media::VolumeHandler()),
1794 mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE),
jiabin161b64f2017-11-17 09:31:48 -08001795 mRoutedDeviceId(AUDIO_PORT_HANDLE_NONE),
jiabin156c6872017-10-06 09:47:15 -07001796 mDeviceCallbackEnabled(false),
1797 mDeviceCallback(deviceCallback)
Andy Hungd1c74342015-07-07 16:54:23 -07001798{
Steve Block3856b092011-10-20 11:56:00 +01001799 ALOGV("AudioOutput(%d)", sessionId);
Eric Laurent43562692015-07-15 16:49:07 -07001800 if (attr != NULL) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001801 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1802 if (mAttributes != NULL) {
1803 memcpy(mAttributes, attr, sizeof(audio_attributes_t));
François Gaffie58d4be52018-11-06 15:30:12 +01001804 mStreamType = AudioSystem::attributesToStreamType(*attr);
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001805 }
1806 } else {
1807 mAttributes = NULL;
Eric Laurent43562692015-07-15 16:49:07 -07001808 }
1809
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001810 setMinBufferCount();
1811}
1812
1813MediaPlayerService::AudioOutput::~AudioOutput()
1814{
1815 close();
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001816 free(mAttributes);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001817 delete mCallbackData;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001818}
1819
Andy Hungd1c74342015-07-07 16:54:23 -07001820//static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001821void MediaPlayerService::AudioOutput::setMinBufferCount()
1822{
1823 char value[PROPERTY_VALUE_MAX];
1824 if (property_get("ro.kernel.qemu", value, 0)) {
1825 mIsOnEmulator = true;
1826 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1827 }
1828}
1829
Andy Hungd1c74342015-07-07 16:54:23 -07001830// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001831bool MediaPlayerService::AudioOutput::isOnEmulator()
1832{
Andy Hungd1c74342015-07-07 16:54:23 -07001833 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001834 return mIsOnEmulator;
1835}
1836
Andy Hungd1c74342015-07-07 16:54:23 -07001837// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001838int MediaPlayerService::AudioOutput::getMinBufferCount()
1839{
Andy Hungd1c74342015-07-07 16:54:23 -07001840 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001841 return mMinBufferCount;
1842}
1843
1844ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1845{
Andy Hungd1c74342015-07-07 16:54:23 -07001846 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001847 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001848 return mTrack->frameCount() * mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001849}
1850
1851ssize_t MediaPlayerService::AudioOutput::frameCount() const
1852{
Andy Hungd1c74342015-07-07 16:54:23 -07001853 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001854 if (mTrack == 0) return NO_INIT;
1855 return mTrack->frameCount();
1856}
1857
1858ssize_t MediaPlayerService::AudioOutput::channelCount() const
1859{
Andy Hungd1c74342015-07-07 16:54:23 -07001860 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001861 if (mTrack == 0) return NO_INIT;
1862 return mTrack->channelCount();
1863}
1864
1865ssize_t MediaPlayerService::AudioOutput::frameSize() const
1866{
Andy Hungd1c74342015-07-07 16:54:23 -07001867 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001868 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001869 return mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001870}
1871
1872uint32_t MediaPlayerService::AudioOutput::latency () const
1873{
Andy Hungd1c74342015-07-07 16:54:23 -07001874 Mutex::Autolock lock(mLock);
Eric Laurentdb354e52012-03-05 17:27:11 -08001875 if (mTrack == 0) return 0;
1876 return mTrack->latency();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001877}
1878
1879float MediaPlayerService::AudioOutput::msecsPerFrame() const
1880{
Andy Hungd1c74342015-07-07 16:54:23 -07001881 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001882 return mMsecsPerFrame;
1883}
1884
Marco Nelissen4110c102012-03-29 09:31:28 -07001885status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position) const
Eric Laurent342e9cf2010-01-19 17:37:09 -08001886{
Andy Hungd1c74342015-07-07 16:54:23 -07001887 Mutex::Autolock lock(mLock);
Eric Laurent342e9cf2010-01-19 17:37:09 -08001888 if (mTrack == 0) return NO_INIT;
1889 return mTrack->getPosition(position);
1890}
1891
Lajos Molnar06ad1522014-08-28 07:27:44 -07001892status_t MediaPlayerService::AudioOutput::getTimestamp(AudioTimestamp &ts) const
1893{
Andy Hungd1c74342015-07-07 16:54:23 -07001894 Mutex::Autolock lock(mLock);
Lajos Molnar06ad1522014-08-28 07:27:44 -07001895 if (mTrack == 0) return NO_INIT;
1896 return mTrack->getTimestamp(ts);
1897}
1898
Wei Jiac4ac8172015-10-21 10:35:48 -07001899// TODO: Remove unnecessary calls to getPlayedOutDurationUs()
1900// as it acquires locks and may query the audio driver.
1901//
1902// Some calls could conceivably retrieve extrapolated data instead of
1903// accessing getTimestamp() or getPosition() every time a data buffer with
1904// a media time is received.
1905//
1906// Calculate duration of played samples if played at normal rate (i.e., 1.0).
1907int64_t MediaPlayerService::AudioOutput::getPlayedOutDurationUs(int64_t nowUs) const
1908{
1909 Mutex::Autolock lock(mLock);
1910 if (mTrack == 0 || mSampleRateHz == 0) {
Wei Jia213f4902015-10-22 08:55:25 -07001911 return 0;
Wei Jiac4ac8172015-10-21 10:35:48 -07001912 }
1913
1914 uint32_t numFramesPlayed;
Andy Hung5d313802016-10-10 15:09:39 -07001915 int64_t numFramesPlayedAtUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001916 AudioTimestamp ts;
Wei Jiac4ac8172015-10-21 10:35:48 -07001917
1918 status_t res = mTrack->getTimestamp(ts);
1919 if (res == OK) { // case 1: mixing audio tracks and offloaded tracks.
1920 numFramesPlayed = ts.mPosition;
Andy Hung5d313802016-10-10 15:09:39 -07001921 numFramesPlayedAtUs = ts.mTime.tv_sec * 1000000LL + ts.mTime.tv_nsec / 1000;
1922 //ALOGD("getTimestamp: OK %d %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001923 } else if (res == WOULD_BLOCK) { // case 2: transitory state on start of a new track
1924 numFramesPlayed = 0;
Andy Hung5d313802016-10-10 15:09:39 -07001925 numFramesPlayedAtUs = nowUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001926 //ALOGD("getTimestamp: WOULD_BLOCK %d %lld",
Andy Hung5d313802016-10-10 15:09:39 -07001927 // numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001928 } else { // case 3: transitory at new track or audio fast tracks.
1929 res = mTrack->getPosition(&numFramesPlayed);
1930 CHECK_EQ(res, (status_t)OK);
Andy Hung5d313802016-10-10 15:09:39 -07001931 numFramesPlayedAtUs = nowUs;
1932 numFramesPlayedAtUs += 1000LL * mTrack->latency() / 2; /* XXX */
1933 //ALOGD("getPosition: %u %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001934 }
1935
1936 // CHECK_EQ(numFramesPlayed & (1 << 31), 0); // can't be negative until 12.4 hrs, test
1937 // TODO: remove the (int32_t) casting below as it may overflow at 12.4 hours.
1938 int64_t durationUs = (int64_t)((int32_t)numFramesPlayed * 1000000LL / mSampleRateHz)
Andy Hung5d313802016-10-10 15:09:39 -07001939 + nowUs - numFramesPlayedAtUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001940 if (durationUs < 0) {
1941 // Occurs when numFramesPlayed position is very small and the following:
1942 // (1) In case 1, the time nowUs is computed before getTimestamp() is called and
Andy Hung5d313802016-10-10 15:09:39 -07001943 // numFramesPlayedAtUs is greater than nowUs by time more than numFramesPlayed.
Wei Jiac4ac8172015-10-21 10:35:48 -07001944 // (2) In case 3, using getPosition and adding mAudioSink->latency() to
Andy Hung5d313802016-10-10 15:09:39 -07001945 // numFramesPlayedAtUs, by a time amount greater than numFramesPlayed.
Wei Jiac4ac8172015-10-21 10:35:48 -07001946 //
1947 // Both of these are transitory conditions.
1948 ALOGV("getPlayedOutDurationUs: negative duration %lld set to zero", (long long)durationUs);
1949 durationUs = 0;
1950 }
1951 ALOGV("getPlayedOutDurationUs(%lld) nowUs(%lld) frames(%u) framesAt(%lld)",
Andy Hung5d313802016-10-10 15:09:39 -07001952 (long long)durationUs, (long long)nowUs,
1953 numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001954 return durationUs;
1955}
1956
Marco Nelissen4110c102012-03-29 09:31:28 -07001957status_t MediaPlayerService::AudioOutput::getFramesWritten(uint32_t *frameswritten) const
1958{
Andy Hungd1c74342015-07-07 16:54:23 -07001959 Mutex::Autolock lock(mLock);
Marco Nelissen4110c102012-03-29 09:31:28 -07001960 if (mTrack == 0) return NO_INIT;
Andy Hung2f6e73d2016-04-08 12:12:58 -07001961 ExtendedTimestamp ets;
1962 status_t status = mTrack->getTimestamp(&ets);
1963 if (status == OK || status == WOULD_BLOCK) {
1964 *frameswritten = (uint32_t)ets.mPosition[ExtendedTimestamp::LOCATION_CLIENT];
1965 }
1966 return status;
Marco Nelissen4110c102012-03-29 09:31:28 -07001967}
1968
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001969status_t MediaPlayerService::AudioOutput::setParameters(const String8& keyValuePairs)
1970{
Andy Hungd1c74342015-07-07 16:54:23 -07001971 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001972 if (mTrack == 0) return NO_INIT;
1973 return mTrack->setParameters(keyValuePairs);
1974}
1975
1976String8 MediaPlayerService::AudioOutput::getParameters(const String8& keys)
1977{
Andy Hungd1c74342015-07-07 16:54:23 -07001978 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001979 if (mTrack == 0) return String8::empty();
1980 return mTrack->getParameters(keys);
1981}
1982
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001983void MediaPlayerService::AudioOutput::setAudioAttributes(const audio_attributes_t * attributes) {
Andy Hungd1c74342015-07-07 16:54:23 -07001984 Mutex::Autolock lock(mLock);
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001985 if (attributes == NULL) {
1986 free(mAttributes);
1987 mAttributes = NULL;
1988 } else {
1989 if (mAttributes == NULL) {
1990 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1991 }
1992 memcpy(mAttributes, attributes, sizeof(audio_attributes_t));
François Gaffie58d4be52018-11-06 15:30:12 +01001993 mStreamType = AudioSystem::attributesToStreamType(*attributes);
Eric Laurent43562692015-07-15 16:49:07 -07001994 }
1995}
1996
1997void MediaPlayerService::AudioOutput::setAudioStreamType(audio_stream_type_t streamType)
1998{
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001999 Mutex::Autolock lock(mLock);
Eric Laurent43562692015-07-15 16:49:07 -07002000 // do not allow direct stream type modification if attributes have been set
2001 if (mAttributes == NULL) {
2002 mStreamType = streamType;
2003 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07002004}
2005
Andy Hungd1c74342015-07-07 16:54:23 -07002006void MediaPlayerService::AudioOutput::deleteRecycledTrack_l()
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002007{
Andy Hungd1c74342015-07-07 16:54:23 -07002008 ALOGV("deleteRecycledTrack_l");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002009 if (mRecycledTrack != 0) {
2010
2011 if (mCallbackData != NULL) {
2012 mCallbackData->setOutput(NULL);
2013 mCallbackData->endTrackSwitch();
2014 }
2015
2016 if ((mRecycledTrack->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) {
Andy Hunge13f8a62016-03-30 14:20:42 -07002017 int32_t msec = 0;
2018 if (!mRecycledTrack->stopped()) { // check if active
2019 (void)mRecycledTrack->pendingDuration(&msec);
2020 }
2021 mRecycledTrack->stop(); // ensure full data drain
2022 ALOGD("deleting recycled track, waiting for data drain (%d msec)", msec);
2023 if (msec > 0) {
2024 static const int32_t WAIT_LIMIT_MS = 3000;
2025 if (msec > WAIT_LIMIT_MS) {
2026 msec = WAIT_LIMIT_MS;
2027 }
2028 usleep(msec * 1000LL);
2029 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002030 }
2031 // An offloaded track isn't flushed because the STREAM_END is reported
2032 // slightly prematurely to allow time for the gapless track switch
2033 // but this means that if we decide not to recycle the track there
2034 // could be a small amount of residual data still playing. We leave
2035 // AudioFlinger to drain the track.
2036
2037 mRecycledTrack.clear();
Andy Hungd1c74342015-07-07 16:54:23 -07002038 close_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002039 delete mCallbackData;
2040 mCallbackData = NULL;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002041 }
2042}
2043
Andy Hungd1c74342015-07-07 16:54:23 -07002044void MediaPlayerService::AudioOutput::close_l()
2045{
2046 mTrack.clear();
2047}
2048
Andreas Huber20111aa2009-07-14 16:56:47 -07002049status_t MediaPlayerService::AudioOutput::open(
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08002050 uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
2051 audio_format_t format, int bufferCount,
Eric Laurent1948eb32012-04-13 16:50:19 -07002052 AudioCallback cb, void *cookie,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002053 audio_output_flags_t flags,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07002054 const audio_offload_info_t *offloadInfo,
Andy Hung179652e2015-05-31 22:49:46 -07002055 bool doNotReconnect,
2056 uint32_t suggestedFrameCount)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002057{
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002058 ALOGV("open(%u, %d, 0x%x, 0x%x, %d, %d 0x%x)", sampleRate, channelCount, channelMask,
2059 format, bufferCount, mSessionId, flags);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002060
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002061 // offloading is only supported in callback mode for now.
2062 // offloadInfo must be present if offload flag is set
2063 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) &&
2064 ((cb == NULL) || (offloadInfo == NULL))) {
2065 return BAD_VALUE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002066 }
2067
Andy Hung179652e2015-05-31 22:49:46 -07002068 // compute frame count for the AudioTrack internal buffer
2069 size_t frameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002070 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
2071 frameCount = 0; // AudioTrack will get frame count from AudioFlinger
2072 } else {
Andy Hung179652e2015-05-31 22:49:46 -07002073 // try to estimate the buffer processing fetch size from AudioFlinger.
2074 // framesPerBuffer is approximate and generally correct, except when it's not :-).
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002075 uint32_t afSampleRate;
2076 size_t afFrameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002077 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
2078 return NO_INIT;
2079 }
2080 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
2081 return NO_INIT;
2082 }
Ben Romberger259fb462018-08-07 17:58:53 -07002083 if (afSampleRate == 0) {
2084 return NO_INIT;
2085 }
Andy Hung179652e2015-05-31 22:49:46 -07002086 const size_t framesPerBuffer =
2087 (unsigned long long)sampleRate * afFrameCount / afSampleRate;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002088
Andy Hung179652e2015-05-31 22:49:46 -07002089 if (bufferCount == 0) {
Ben Romberger259fb462018-08-07 17:58:53 -07002090 if (framesPerBuffer == 0) {
2091 return NO_INIT;
2092 }
Andy Hung179652e2015-05-31 22:49:46 -07002093 // use suggestedFrameCount
2094 bufferCount = (suggestedFrameCount + framesPerBuffer - 1) / framesPerBuffer;
2095 }
2096 // Check argument bufferCount against the mininum buffer count
2097 if (bufferCount != 0 && bufferCount < mMinBufferCount) {
2098 ALOGV("bufferCount (%d) increased to %d", bufferCount, mMinBufferCount);
2099 bufferCount = mMinBufferCount;
2100 }
2101 // if frameCount is 0, then AudioTrack will get frame count from AudioFlinger
2102 // which will be the minimum size permitted.
2103 frameCount = bufferCount * framesPerBuffer;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002104 }
Andreas Huber20111aa2009-07-14 16:56:47 -07002105
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08002106 if (channelMask == CHANNEL_MASK_USE_CHANNEL_ORDER) {
Glenn Kastenab334fd2012-03-14 12:56:06 -07002107 channelMask = audio_channel_out_mask_from_count(channelCount);
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08002108 if (0 == channelMask) {
2109 ALOGE("open() error, can\'t derive mask for %d audio channels", channelCount);
2110 return NO_INIT;
2111 }
2112 }
Eric Laurent1948eb32012-04-13 16:50:19 -07002113
Andy Hungd1c74342015-07-07 16:54:23 -07002114 Mutex::Autolock lock(mLock);
Andy Hung179652e2015-05-31 22:49:46 -07002115 mCallback = cb;
2116 mCallbackCookie = cookie;
2117
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002118 // Check whether we can recycle the track
2119 bool reuse = false;
2120 bool bothOffloaded = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07002121
Glenn Kasten2799d742013-05-30 14:33:29 -07002122 if (mRecycledTrack != 0) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002123 // check whether we are switching between two offloaded tracks
2124 bothOffloaded = (flags & mRecycledTrack->getFlags()
2125 & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0;
Marco Nelissen67295b52012-06-11 14:52:53 -07002126
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002127 // check if the existing track can be reused as-is, or if a new track needs to be created.
2128 reuse = true;
2129
Marco Nelissen67295b52012-06-11 14:52:53 -07002130 if ((mCallbackData == NULL && mCallback != NULL) ||
2131 (mCallbackData != NULL && mCallback == NULL)) {
2132 // recycled track uses callbacks but the caller wants to use writes, or vice versa
2133 ALOGV("can't chain callback and write");
2134 reuse = false;
2135 } else if ((mRecycledTrack->getSampleRate() != sampleRate) ||
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002136 (mRecycledTrack->channelCount() != (uint32_t)channelCount) ) {
2137 ALOGV("samplerate, channelcount differ: %u/%u Hz, %u/%d ch",
Marco Nelissen67295b52012-06-11 14:52:53 -07002138 mRecycledTrack->getSampleRate(), sampleRate,
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002139 mRecycledTrack->channelCount(), channelCount);
Marco Nelissen67295b52012-06-11 14:52:53 -07002140 reuse = false;
2141 } else if (flags != mFlags) {
2142 ALOGV("output flags differ %08x/%08x", flags, mFlags);
2143 reuse = false;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002144 } else if (mRecycledTrack->format() != format) {
2145 reuse = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07002146 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002147 } else {
2148 ALOGV("no track available to recycle");
2149 }
2150
2151 ALOGV_IF(bothOffloaded, "both tracks offloaded");
2152
2153 // If we can't recycle and both tracks are offloaded
2154 // we must close the previous output before opening a new one
2155 if (bothOffloaded && !reuse) {
2156 ALOGV("both offloaded and not recycling");
Andy Hungd1c74342015-07-07 16:54:23 -07002157 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002158 }
2159
2160 sp<AudioTrack> t;
2161 CallbackData *newcbd = NULL;
2162
2163 // We don't attempt to create a new track if we are recycling an
2164 // offloaded track. But, if we are recycling a non-offloaded or we
2165 // are switching where one is offloaded and one isn't then we create
2166 // the new track in advance so that we can read additional stream info
2167
2168 if (!(reuse && bothOffloaded)) {
2169 ALOGV("creating new AudioTrack");
2170
2171 if (mCallback != NULL) {
2172 newcbd = new CallbackData(this);
2173 t = new AudioTrack(
2174 mStreamType,
2175 sampleRate,
2176 format,
2177 channelMask,
2178 frameCount,
2179 flags,
2180 CallbackWrapper,
2181 newcbd,
2182 0, // notification frames
2183 mSessionId,
2184 AudioTrack::TRANSFER_CALLBACK,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002185 offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -08002186 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07002187 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07002188 mAttributes,
jiabin156c6872017-10-06 09:47:15 -07002189 doNotReconnect,
2190 1.0f, // default value for maxRequiredSpeed
2191 mSelectedDeviceId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002192 } else {
Andy Hungff874dc2016-04-11 16:49:09 -07002193 // TODO: Due to buffer memory concerns, we use a max target playback speed
2194 // based on mPlaybackRate at the time of open (instead of kMaxRequiredSpeed),
2195 // also clamping the target speed to 1.0 <= targetSpeed <= kMaxRequiredSpeed.
2196 const float targetSpeed =
2197 std::min(std::max(mPlaybackRate.mSpeed, 1.0f), kMaxRequiredSpeed);
2198 ALOGW_IF(targetSpeed != mPlaybackRate.mSpeed,
2199 "track target speed:%f clamped from playback speed:%f",
2200 targetSpeed, mPlaybackRate.mSpeed);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002201 t = new AudioTrack(
2202 mStreamType,
2203 sampleRate,
2204 format,
2205 channelMask,
2206 frameCount,
2207 flags,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002208 NULL, // callback
2209 NULL, // user data
2210 0, // notification frames
2211 mSessionId,
2212 AudioTrack::TRANSFER_DEFAULT,
2213 NULL, // offload info
Marco Nelissend457c972014-02-11 08:47:07 -08002214 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07002215 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07002216 mAttributes,
Andy Hungff874dc2016-04-11 16:49:09 -07002217 doNotReconnect,
jiabin156c6872017-10-06 09:47:15 -07002218 targetSpeed,
2219 mSelectedDeviceId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002220 }
2221
2222 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
2223 ALOGE("Unable to create audio track");
2224 delete newcbd;
Glenn Kasten3e98ecd2015-05-18 13:13:24 -07002225 // t goes out of scope, so reference count drops to zero
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002226 return NO_INIT;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07002227 } else {
2228 // successful AudioTrack initialization implies a legacy stream type was generated
2229 // from the audio attributes
2230 mStreamType = t->streamType();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002231 }
2232 }
2233
2234 if (reuse) {
2235 CHECK(mRecycledTrack != NULL);
2236
2237 if (!bothOffloaded) {
2238 if (mRecycledTrack->frameCount() != t->frameCount()) {
Andy Hung833b4752016-04-04 17:15:48 -07002239 ALOGV("framecount differs: %zu/%zu frames",
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002240 mRecycledTrack->frameCount(), t->frameCount());
2241 reuse = false;
2242 }
2243 }
2244
Marco Nelissen67295b52012-06-11 14:52:53 -07002245 if (reuse) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002246 ALOGV("chaining to next output and recycling track");
Andy Hungd1c74342015-07-07 16:54:23 -07002247 close_l();
Marco Nelissen67295b52012-06-11 14:52:53 -07002248 mTrack = mRecycledTrack;
Glenn Kasten2799d742013-05-30 14:33:29 -07002249 mRecycledTrack.clear();
Marco Nelissen67295b52012-06-11 14:52:53 -07002250 if (mCallbackData != NULL) {
2251 mCallbackData->setOutput(this);
2252 }
Marco Nelissen67295b52012-06-11 14:52:53 -07002253 delete newcbd;
Wei Jiae0bbac92016-07-18 16:04:53 -07002254 return updateTrack();
Marco Nelissen67295b52012-06-11 14:52:53 -07002255 }
Marco Nelissen67295b52012-06-11 14:52:53 -07002256 }
2257
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002258 // we're not going to reuse the track, unblock and flush it
2259 // this was done earlier if both tracks are offloaded
2260 if (!bothOffloaded) {
Andy Hungd1c74342015-07-07 16:54:23 -07002261 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002262 }
2263
2264 CHECK((t != NULL) && ((mCallback == NULL) || (newcbd != NULL)));
2265
Marco Nelissen67295b52012-06-11 14:52:53 -07002266 mCallbackData = newcbd;
Steve Block3856b092011-10-20 11:56:00 +01002267 ALOGV("setVolume");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002268 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07002269
Andy Hung39399b62017-04-21 15:07:45 -07002270 // Restore VolumeShapers for the MediaPlayer in case the track was recreated
2271 // due to an output sink error (e.g. offload to non-offload switch).
2272 mVolumeHandler->forall([&t](const VolumeShaper &shaper) -> VolumeShaper::Status {
2273 sp<VolumeShaper::Operation> operationToEnd =
2274 new VolumeShaper::Operation(shaper.mOperation);
2275 // TODO: Ideally we would restore to the exact xOffset position
2276 // as returned by getVolumeShaperState(), but we don't have that
2277 // information when restoring at the client unless we periodically poll
2278 // the server or create shared memory state.
2279 //
2280 // For now, we simply advance to the end of the VolumeShaper effect
2281 // if it has been started.
2282 if (shaper.isStarted()) {
Andy Hungf3702642017-05-05 17:33:32 -07002283 operationToEnd->setNormalizedTime(1.f);
Andy Hung39399b62017-04-21 15:07:45 -07002284 }
2285 return t->applyVolumeShaper(shaper.mConfiguration, operationToEnd);
Andy Hung4ef88d72017-02-21 19:47:53 -08002286 });
Andy Hung4ef88d72017-02-21 19:47:53 -08002287
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002288 mSampleRateHz = sampleRate;
Preetam Singh Ranawat2e17eef2015-08-12 12:11:46 -07002289 mFlags = flags;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002290 mMsecsPerFrame = 1E3f / (mPlaybackRate.mSpeed * sampleRate);
Andy Hungd1c74342015-07-07 16:54:23 -07002291 mFrameSize = t->frameSize();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002292 mTrack = t;
Eric Laurent2beeb502010-07-16 07:43:46 -07002293
Wei Jiae0bbac92016-07-18 16:04:53 -07002294 return updateTrack();
2295}
2296
2297status_t MediaPlayerService::AudioOutput::updateTrack() {
2298 if (mTrack == NULL) {
2299 return NO_ERROR;
2300 }
2301
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002302 status_t res = NO_ERROR;
Wei Jia0162d002015-06-09 11:59:33 -07002303 // Note some output devices may give us a direct track even though we don't specify it.
2304 // Example: Line application b/17459982.
Wei Jiae0bbac92016-07-18 16:04:53 -07002305 if ((mTrack->getFlags()
2306 & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) {
2307 res = mTrack->setPlaybackRate(mPlaybackRate);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002308 if (res == NO_ERROR) {
Wei Jiae0bbac92016-07-18 16:04:53 -07002309 mTrack->setAuxEffectSendLevel(mSendLevel);
2310 res = mTrack->attachAuxEffect(mAuxEffectId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002311 }
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002312 }
jiabin156c6872017-10-06 09:47:15 -07002313 mTrack->setOutputDevice(mSelectedDeviceId);
2314 if (mDeviceCallbackEnabled) {
2315 mTrack->addAudioDeviceCallback(mDeviceCallback.promote());
2316 }
Wei Jiae0bbac92016-07-18 16:04:53 -07002317 ALOGV("updateTrack() DONE status %d", res);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002318 return res;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002319}
2320
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002321status_t MediaPlayerService::AudioOutput::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002322{
Steve Block3856b092011-10-20 11:56:00 +01002323 ALOGV("start");
Andy Hungd1c74342015-07-07 16:54:23 -07002324 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08002325 if (mCallbackData != NULL) {
2326 mCallbackData->endTrackSwitch();
2327 }
Glenn Kasten2799d742013-05-30 14:33:29 -07002328 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002329 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07002330 mTrack->setAuxEffectSendLevel(mSendLevel);
Andy Hung39399b62017-04-21 15:07:45 -07002331 status_t status = mTrack->start();
2332 if (status == NO_ERROR) {
2333 mVolumeHandler->setStarted();
2334 }
2335 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002336 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002337 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002338}
2339
Marco Nelissen6b74d672012-02-28 16:07:44 -08002340void MediaPlayerService::AudioOutput::setNextOutput(const sp<AudioOutput>& nextOutput) {
Andy Hungd1c74342015-07-07 16:54:23 -07002341 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08002342 mNextOutput = nextOutput;
2343}
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08002344
Marco Nelissen6b74d672012-02-28 16:07:44 -08002345void MediaPlayerService::AudioOutput::switchToNextOutput() {
2346 ALOGV("switchToNextOutput");
Andy Hungd1c74342015-07-07 16:54:23 -07002347
2348 // Try to acquire the callback lock before moving track (without incurring deadlock).
2349 const unsigned kMaxSwitchTries = 100;
2350 Mutex::Autolock lock(mLock);
2351 for (unsigned tries = 0;;) {
2352 if (mTrack == 0) {
2353 return;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002354 }
Andy Hungd1c74342015-07-07 16:54:23 -07002355 if (mNextOutput != NULL && mNextOutput != this) {
2356 if (mCallbackData != NULL) {
2357 // two alternative approaches
2358#if 1
2359 CallbackData *callbackData = mCallbackData;
2360 mLock.unlock();
2361 // proper acquisition sequence
2362 callbackData->lock();
2363 mLock.lock();
2364 // Caution: it is unlikely that someone deleted our callback or changed our target
2365 if (callbackData != mCallbackData || mNextOutput == NULL || mNextOutput == this) {
2366 // fatal if we are starved out.
2367 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2368 "switchToNextOutput() cannot obtain correct lock sequence");
2369 callbackData->unlock();
2370 continue;
2371 }
2372 callbackData->mSwitching = true; // begin track switch
Wei Jiaadee56a2016-08-05 15:40:34 -07002373 callbackData->setOutput(NULL);
Andy Hungd1c74342015-07-07 16:54:23 -07002374#else
2375 // tryBeginTrackSwitch() returns false if the callback has the lock.
2376 if (!mCallbackData->tryBeginTrackSwitch()) {
2377 // fatal if we are starved out.
2378 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2379 "switchToNextOutput() cannot obtain callback lock");
2380 mLock.unlock();
2381 usleep(5 * 1000 /* usec */); // allow callback to use AudioOutput
2382 mLock.lock();
2383 continue;
2384 }
2385#endif
2386 }
2387
2388 Mutex::Autolock nextLock(mNextOutput->mLock);
2389
2390 // If the next output track is not NULL, then it has been
2391 // opened already for playback.
2392 // This is possible even without the next player being started,
2393 // for example, the next player could be prepared and seeked.
2394 //
2395 // Presuming it isn't advisable to force the track over.
2396 if (mNextOutput->mTrack == NULL) {
2397 ALOGD("Recycling track for gapless playback");
2398 delete mNextOutput->mCallbackData;
2399 mNextOutput->mCallbackData = mCallbackData;
2400 mNextOutput->mRecycledTrack = mTrack;
2401 mNextOutput->mSampleRateHz = mSampleRateHz;
2402 mNextOutput->mMsecsPerFrame = mMsecsPerFrame;
Andy Hungd1c74342015-07-07 16:54:23 -07002403 mNextOutput->mFlags = mFlags;
2404 mNextOutput->mFrameSize = mFrameSize;
2405 close_l();
2406 mCallbackData = NULL; // destruction handled by mNextOutput
2407 } else {
2408 ALOGW("Ignoring gapless playback because next player has already started");
2409 // remove track in case resource needed for future players.
2410 if (mCallbackData != NULL) {
2411 mCallbackData->endTrackSwitch(); // release lock for callbacks before close.
2412 }
2413 close_l();
2414 }
2415 }
2416 break;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002417 }
2418}
2419
Wei Jia7d3f4df2015-03-03 15:28:00 -08002420ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002421{
Andy Hungd1c74342015-07-07 16:54:23 -07002422 Mutex::Autolock lock(mLock);
Glenn Kastenadad3d72014-02-21 14:51:43 -08002423 LOG_ALWAYS_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
Andreas Huber20111aa2009-07-14 16:56:47 -07002424
Steve Block3856b092011-10-20 11:56:00 +01002425 //ALOGV("write(%p, %u)", buffer, size);
Glenn Kasten2799d742013-05-30 14:33:29 -07002426 if (mTrack != 0) {
Andy Hung2f6e73d2016-04-08 12:12:58 -07002427 return mTrack->write(buffer, size, blocking);
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07002428 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002429 return NO_INIT;
2430}
2431
2432void MediaPlayerService::AudioOutput::stop()
2433{
Steve Block3856b092011-10-20 11:56:00 +01002434 ALOGV("stop");
Andy Hungd1c74342015-07-07 16:54:23 -07002435 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002436 if (mTrack != 0) mTrack->stop();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002437}
2438
2439void MediaPlayerService::AudioOutput::flush()
2440{
Steve Block3856b092011-10-20 11:56:00 +01002441 ALOGV("flush");
Andy Hungd1c74342015-07-07 16:54:23 -07002442 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002443 if (mTrack != 0) mTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002444}
2445
2446void MediaPlayerService::AudioOutput::pause()
2447{
Steve Block3856b092011-10-20 11:56:00 +01002448 ALOGV("pause");
Andy Hungd1c74342015-07-07 16:54:23 -07002449 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002450 if (mTrack != 0) mTrack->pause();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002451}
2452
2453void MediaPlayerService::AudioOutput::close()
2454{
Steve Block3856b092011-10-20 11:56:00 +01002455 ALOGV("close");
Erik Wolsheimer7845a1f2015-10-30 12:07:52 -07002456 sp<AudioTrack> track;
2457 {
2458 Mutex::Autolock lock(mLock);
2459 track = mTrack;
2460 close_l(); // clears mTrack
2461 }
2462 // destruction of the track occurs outside of mutex.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002463}
2464
2465void MediaPlayerService::AudioOutput::setVolume(float left, float right)
2466{
Steve Block3856b092011-10-20 11:56:00 +01002467 ALOGV("setVolume(%f, %f)", left, right);
Andy Hungd1c74342015-07-07 16:54:23 -07002468 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002469 mLeftVolume = left;
2470 mRightVolume = right;
Glenn Kasten2799d742013-05-30 14:33:29 -07002471 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002472 mTrack->setVolume(left, right);
2473 }
2474}
2475
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002476status_t MediaPlayerService::AudioOutput::setPlaybackRate(const AudioPlaybackRate &rate)
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002477{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002478 ALOGV("setPlaybackRate(%f %f %d %d)",
2479 rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Andy Hungd1c74342015-07-07 16:54:23 -07002480 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002481 if (mTrack == 0) {
2482 // remember rate so that we can set it when the track is opened
2483 mPlaybackRate = rate;
2484 return OK;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002485 }
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002486 status_t res = mTrack->setPlaybackRate(rate);
2487 if (res != NO_ERROR) {
2488 return res;
2489 }
2490 // rate.mSpeed is always greater than 0 if setPlaybackRate succeeded
2491 CHECK_GT(rate.mSpeed, 0.f);
2492 mPlaybackRate = rate;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002493 if (mSampleRateHz != 0) {
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002494 mMsecsPerFrame = 1E3f / (rate.mSpeed * mSampleRateHz);
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002495 }
2496 return res;
2497}
2498
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002499status_t MediaPlayerService::AudioOutput::getPlaybackRate(AudioPlaybackRate *rate)
2500{
2501 ALOGV("setPlaybackRate");
Andy Hungd1c74342015-07-07 16:54:23 -07002502 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002503 if (mTrack == 0) {
2504 return NO_INIT;
2505 }
2506 *rate = mTrack->getPlaybackRate();
2507 return NO_ERROR;
2508}
2509
Eric Laurent2beeb502010-07-16 07:43:46 -07002510status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
2511{
Steve Block3856b092011-10-20 11:56:00 +01002512 ALOGV("setAuxEffectSendLevel(%f)", level);
Andy Hungd1c74342015-07-07 16:54:23 -07002513 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002514 mSendLevel = level;
Glenn Kasten2799d742013-05-30 14:33:29 -07002515 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002516 return mTrack->setAuxEffectSendLevel(level);
2517 }
2518 return NO_ERROR;
2519}
2520
2521status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
2522{
Steve Block3856b092011-10-20 11:56:00 +01002523 ALOGV("attachAuxEffect(%d)", effectId);
Andy Hungd1c74342015-07-07 16:54:23 -07002524 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002525 mAuxEffectId = effectId;
Glenn Kasten2799d742013-05-30 14:33:29 -07002526 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002527 return mTrack->attachAuxEffect(effectId);
2528 }
2529 return NO_ERROR;
2530}
2531
jiabin156c6872017-10-06 09:47:15 -07002532status_t MediaPlayerService::AudioOutput::setOutputDevice(audio_port_handle_t deviceId)
2533{
2534 ALOGV("setOutputDevice(%d)", deviceId);
2535 Mutex::Autolock lock(mLock);
2536 mSelectedDeviceId = deviceId;
2537 if (mTrack != 0) {
2538 return mTrack->setOutputDevice(deviceId);
2539 }
2540 return NO_ERROR;
2541}
2542
2543status_t MediaPlayerService::AudioOutput::getRoutedDeviceId(audio_port_handle_t* deviceId)
2544{
2545 ALOGV("getRoutedDeviceId");
2546 Mutex::Autolock lock(mLock);
2547 if (mTrack != 0) {
jiabin161b64f2017-11-17 09:31:48 -08002548 mRoutedDeviceId = mTrack->getRoutedDeviceId();
jiabin156c6872017-10-06 09:47:15 -07002549 }
jiabin161b64f2017-11-17 09:31:48 -08002550 *deviceId = mRoutedDeviceId;
2551 return NO_ERROR;
jiabin156c6872017-10-06 09:47:15 -07002552}
2553
2554status_t MediaPlayerService::AudioOutput::enableAudioDeviceCallback(bool enabled)
2555{
2556 ALOGV("enableAudioDeviceCallback, %d", enabled);
2557 Mutex::Autolock lock(mLock);
2558 mDeviceCallbackEnabled = enabled;
2559 if (mTrack != 0) {
2560 status_t status;
2561 if (enabled) {
2562 status = mTrack->addAudioDeviceCallback(mDeviceCallback.promote());
2563 } else {
2564 status = mTrack->removeAudioDeviceCallback(mDeviceCallback.promote());
2565 }
2566 return status;
2567 }
2568 return NO_ERROR;
2569}
2570
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002571VolumeShaper::Status MediaPlayerService::AudioOutput::applyVolumeShaper(
2572 const sp<VolumeShaper::Configuration>& configuration,
2573 const sp<VolumeShaper::Operation>& operation)
2574{
2575 Mutex::Autolock lock(mLock);
2576 ALOGV("AudioOutput::applyVolumeShaper");
Andy Hung4ef88d72017-02-21 19:47:53 -08002577
Andy Hung4ef88d72017-02-21 19:47:53 -08002578 mVolumeHandler->setIdIfNecessary(configuration);
Andy Hung39399b62017-04-21 15:07:45 -07002579
2580 VolumeShaper::Status status;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002581 if (mTrack != 0) {
Andy Hung39399b62017-04-21 15:07:45 -07002582 status = mTrack->applyVolumeShaper(configuration, operation);
2583 if (status >= 0) {
2584 (void)mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hungf3702642017-05-05 17:33:32 -07002585 if (mTrack->isPlaying()) { // match local AudioTrack to properly restore.
2586 mVolumeHandler->setStarted();
2587 }
Andy Hung39399b62017-04-21 15:07:45 -07002588 }
Andy Hung4ef88d72017-02-21 19:47:53 -08002589 } else {
Andy Hungc01eddb2017-07-21 16:42:41 -07002590 // VolumeShapers are not affected when a track moves between players for
2591 // gapless playback (setNextMediaPlayer).
2592 // We forward VolumeShaper operations that do not change configuration
2593 // to the new player so that unducking may occur as expected.
2594 // Unducking is an idempotent operation, same if applied back-to-back.
2595 if (configuration->getType() == VolumeShaper::Configuration::TYPE_ID
2596 && mNextOutput != nullptr) {
2597 ALOGV("applyVolumeShaper: Attempting to forward missed operation: %s %s",
2598 configuration->toString().c_str(), operation->toString().c_str());
2599 Mutex::Autolock nextLock(mNextOutput->mLock);
2600
2601 // recycled track should be forwarded from this AudioSink by switchToNextOutput
2602 sp<AudioTrack> track = mNextOutput->mRecycledTrack;
2603 if (track != nullptr) {
2604 ALOGD("Forward VolumeShaper operation to recycled track %p", track.get());
2605 (void)track->applyVolumeShaper(configuration, operation);
2606 } else {
2607 // There is a small chance that the unduck occurs after the next
2608 // player has already started, but before it is registered to receive
2609 // the unduck command.
2610 track = mNextOutput->mTrack;
2611 if (track != nullptr) {
2612 ALOGD("Forward VolumeShaper operation to track %p", track.get());
2613 (void)track->applyVolumeShaper(configuration, operation);
2614 }
2615 }
2616 }
Andy Hung39399b62017-04-21 15:07:45 -07002617 status = mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002618 }
Andy Hung39399b62017-04-21 15:07:45 -07002619 return status;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002620}
2621
2622sp<VolumeShaper::State> MediaPlayerService::AudioOutput::getVolumeShaperState(int id)
2623{
2624 Mutex::Autolock lock(mLock);
2625 if (mTrack != 0) {
2626 return mTrack->getVolumeShaperState(id);
Andy Hung4ef88d72017-02-21 19:47:53 -08002627 } else {
2628 return mVolumeHandler->getVolumeShaperState(id);
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002629 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002630}
2631
Andreas Huber20111aa2009-07-14 16:56:47 -07002632// static
2633void MediaPlayerService::AudioOutput::CallbackWrapper(
Glenn Kastend217a8c2011-06-01 15:20:35 -07002634 int event, void *cookie, void *info) {
Steve Block3856b092011-10-20 11:56:00 +01002635 //ALOGV("callbackwrapper");
Marco Nelissen6b74d672012-02-28 16:07:44 -08002636 CallbackData *data = (CallbackData*)cookie;
Andy Hungd1c74342015-07-07 16:54:23 -07002637 // lock to ensure we aren't caught in the middle of a track switch.
Marco Nelissen6b74d672012-02-28 16:07:44 -08002638 data->lock();
2639 AudioOutput *me = data->getOutput();
Andreas Huber20111aa2009-07-14 16:56:47 -07002640 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002641 if (me == NULL) {
2642 // no output set, likely because the track was scheduled to be reused
2643 // by another player, but the format turned out to be incompatible.
2644 data->unlock();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002645 if (buffer != NULL) {
2646 buffer->size = 0;
2647 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08002648 return;
2649 }
Andreas Huber20111aa2009-07-14 16:56:47 -07002650
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002651 switch(event) {
2652 case AudioTrack::EVENT_MORE_DATA: {
2653 size_t actualSize = (*me->mCallback)(
2654 me, buffer->raw, buffer->size, me->mCallbackCookie,
2655 CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002656
Andy Hung719b46b2015-05-31 22:18:25 -07002657 // Log when no data is returned from the callback.
2658 // (1) We may have no data (especially with network streaming sources).
2659 // (2) We may have reached the EOS and the audio track is not stopped yet.
2660 // Note that AwesomePlayer/AudioPlayer will only return zero size when it reaches the EOS.
2661 // NuPlayerRenderer will return zero when it doesn't have data (it doesn't block to fill).
2662 //
2663 // This is a benign busy-wait, with the next data request generated 10 ms or more later;
2664 // nevertheless for power reasons, we don't want to see too many of these.
Andreas Huber2e8ffaf2010-02-18 16:45:13 -08002665
Andy Hung719b46b2015-05-31 22:18:25 -07002666 ALOGV_IF(actualSize == 0 && buffer->size > 0, "callbackwrapper: empty buffer returned");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002667
2668 buffer->size = actualSize;
2669 } break;
2670
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002671 case AudioTrack::EVENT_STREAM_END:
Andy Hung719b46b2015-05-31 22:18:25 -07002672 // currently only occurs for offloaded callbacks
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002673 ALOGV("callbackwrapper: deliver EVENT_STREAM_END");
2674 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2675 me->mCallbackCookie, CB_EVENT_STREAM_END);
2676 break;
2677
2678 case AudioTrack::EVENT_NEW_IAUDIOTRACK :
2679 ALOGV("callbackwrapper: deliver EVENT_TEAR_DOWN");
2680 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2681 me->mCallbackCookie, CB_EVENT_TEAR_DOWN);
2682 break;
2683
Glenn Kasten421743b2015-06-01 08:18:08 -07002684 case AudioTrack::EVENT_UNDERRUN:
Andy Hung719b46b2015-05-31 22:18:25 -07002685 // This occurs when there is no data available, typically
Glenn Kasten421743b2015-06-01 08:18:08 -07002686 // when there is a failure to supply data to the AudioTrack. It can also
2687 // occur in non-offloaded mode when the audio device comes out of standby.
2688 //
Andy Hung719b46b2015-05-31 22:18:25 -07002689 // If an AudioTrack underruns it outputs silence. Since this happens suddenly
2690 // it may sound like an audible pop or glitch.
2691 //
2692 // The underrun event is sent once per track underrun; the condition is reset
2693 // when more data is sent to the AudioTrack.
Eric Laurente93cc032016-05-05 10:15:10 -07002694 ALOGD("callbackwrapper: EVENT_UNDERRUN (discarded)");
Glenn Kasten421743b2015-06-01 08:18:08 -07002695 break;
2696
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002697 default:
2698 ALOGE("received unknown event type: %d inside CallbackWrapper !", event);
Andreas Huber51c1e0e2011-04-04 11:43:40 -07002699 }
2700
Marco Nelissen6b74d672012-02-28 16:07:44 -08002701 data->unlock();
Andreas Huber20111aa2009-07-14 16:56:47 -07002702}
2703
Glenn Kastend848eb42016-03-08 13:42:11 -08002704audio_session_t MediaPlayerService::AudioOutput::getSessionId() const
Eric Laurent8c563ed2010-10-07 18:23:03 -07002705{
Andy Hungd1c74342015-07-07 16:54:23 -07002706 Mutex::Autolock lock(mLock);
Eric Laurent8c563ed2010-10-07 18:23:03 -07002707 return mSessionId;
2708}
2709
Eric Laurent6f59db12013-07-26 17:16:50 -07002710uint32_t MediaPlayerService::AudioOutput::getSampleRate() const
2711{
Andy Hungd1c74342015-07-07 16:54:23 -07002712 Mutex::Autolock lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -07002713 if (mTrack == 0) return 0;
2714 return mTrack->getSampleRate();
2715}
2716
Andy Hungf2c87b32016-04-07 19:49:29 -07002717int64_t MediaPlayerService::AudioOutput::getBufferDurationInUs() const
2718{
2719 Mutex::Autolock lock(mLock);
2720 if (mTrack == 0) {
2721 return 0;
2722 }
2723 int64_t duration;
2724 if (mTrack->getBufferDurationInUs(&duration) != OK) {
2725 return 0;
2726 }
2727 return duration;
2728}
2729
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002730////////////////////////////////////////////////////////////////////////////////
2731
2732struct CallbackThread : public Thread {
2733 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
2734 MediaPlayerBase::AudioSink::AudioCallback cb,
2735 void *cookie);
2736
2737protected:
2738 virtual ~CallbackThread();
2739
2740 virtual bool threadLoop();
2741
2742private:
2743 wp<MediaPlayerBase::AudioSink> mSink;
2744 MediaPlayerBase::AudioSink::AudioCallback mCallback;
2745 void *mCookie;
2746 void *mBuffer;
2747 size_t mBufferSize;
2748
2749 CallbackThread(const CallbackThread &);
2750 CallbackThread &operator=(const CallbackThread &);
2751};
2752
2753CallbackThread::CallbackThread(
2754 const wp<MediaPlayerBase::AudioSink> &sink,
2755 MediaPlayerBase::AudioSink::AudioCallback cb,
2756 void *cookie)
2757 : mSink(sink),
2758 mCallback(cb),
2759 mCookie(cookie),
2760 mBuffer(NULL),
2761 mBufferSize(0) {
2762}
2763
2764CallbackThread::~CallbackThread() {
2765 if (mBuffer) {
2766 free(mBuffer);
2767 mBuffer = NULL;
2768 }
2769}
2770
2771bool CallbackThread::threadLoop() {
2772 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
2773 if (sink == NULL) {
2774 return false;
2775 }
2776
2777 if (mBuffer == NULL) {
2778 mBufferSize = sink->bufferSize();
2779 mBuffer = malloc(mBufferSize);
2780 }
2781
2782 size_t actualSize =
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002783 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie,
2784 MediaPlayerBase::AudioSink::CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002785
2786 if (actualSize > 0) {
2787 sink->write(mBuffer, actualSize);
Andy Hunga31335a2014-08-20 17:37:59 -07002788 // Could return false on sink->write() error or short count.
2789 // Not necessarily appropriate but would work for AudioCache behavior.
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002790 }
2791
2792 return true;
2793}
2794
2795////////////////////////////////////////////////////////////////////////////////
2796
Chong Zhange5b9b692017-05-11 11:44:56 -07002797void MediaPlayerService::addBatteryData(uint32_t params) {
2798 mBatteryTracker.addBatteryData(params);
2799}
2800
2801status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
2802 return mBatteryTracker.pullBatteryData(reply);
2803}
2804
2805MediaPlayerService::BatteryTracker::BatteryTracker() {
2806 mBatteryAudio.refCount = 0;
2807 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2808 mBatteryAudio.deviceOn[i] = 0;
2809 mBatteryAudio.lastTime[i] = 0;
2810 mBatteryAudio.totalTime[i] = 0;
2811 }
2812 // speaker is on by default
2813 mBatteryAudio.deviceOn[SPEAKER] = 1;
2814
2815 // reset battery stats
2816 // if the mediaserver has crashed, battery stats could be left
2817 // in bad state, reset the state upon service start.
2818 BatteryNotifier::getInstance().noteResetVideo();
2819}
2820
2821void MediaPlayerService::BatteryTracker::addBatteryData(uint32_t params)
Gloria Wang7cf180c2011-02-19 18:37:57 -08002822{
2823 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002824
2825 int32_t time = systemTime() / 1000000L;
2826
2827 // change audio output devices. This notification comes from AudioFlinger
2828 if ((params & kBatteryDataSpeakerOn)
2829 || (params & kBatteryDataOtherAudioDeviceOn)) {
2830
2831 int deviceOn[NUM_AUDIO_DEVICES];
2832 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2833 deviceOn[i] = 0;
2834 }
2835
2836 if ((params & kBatteryDataSpeakerOn)
2837 && (params & kBatteryDataOtherAudioDeviceOn)) {
2838 deviceOn[SPEAKER_AND_OTHER] = 1;
2839 } else if (params & kBatteryDataSpeakerOn) {
2840 deviceOn[SPEAKER] = 1;
2841 } else {
2842 deviceOn[OTHER_AUDIO_DEVICE] = 1;
2843 }
2844
2845 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2846 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
2847
2848 if (mBatteryAudio.refCount > 0) { // if playing audio
2849 if (!deviceOn[i]) {
2850 mBatteryAudio.lastTime[i] += time;
2851 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2852 mBatteryAudio.lastTime[i] = 0;
2853 } else {
2854 mBatteryAudio.lastTime[i] = 0 - time;
2855 }
2856 }
2857
2858 mBatteryAudio.deviceOn[i] = deviceOn[i];
2859 }
2860 }
2861 return;
2862 }
2863
Marco Nelissenb7848f12014-12-04 08:57:56 -08002864 // an audio stream is started
Gloria Wang9ee159b2011-02-24 14:51:45 -08002865 if (params & kBatteryDataAudioFlingerStart) {
2866 // record the start time only if currently no other audio
2867 // is being played
2868 if (mBatteryAudio.refCount == 0) {
2869 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2870 if (mBatteryAudio.deviceOn[i]) {
2871 mBatteryAudio.lastTime[i] -= time;
2872 }
2873 }
2874 }
2875
2876 mBatteryAudio.refCount ++;
2877 return;
2878
2879 } else if (params & kBatteryDataAudioFlingerStop) {
2880 if (mBatteryAudio.refCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002881 ALOGW("Battery track warning: refCount is <= 0");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002882 return;
2883 }
2884
2885 // record the stop time only if currently this is the only
2886 // audio being played
2887 if (mBatteryAudio.refCount == 1) {
2888 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2889 if (mBatteryAudio.deviceOn[i]) {
2890 mBatteryAudio.lastTime[i] += time;
2891 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2892 mBatteryAudio.lastTime[i] = 0;
2893 }
2894 }
2895 }
2896
2897 mBatteryAudio.refCount --;
2898 return;
2899 }
2900
Andy Hung1afd0982016-11-08 16:13:44 -08002901 uid_t uid = IPCThreadState::self()->getCallingUid();
Gloria Wang7cf180c2011-02-19 18:37:57 -08002902 if (uid == AID_MEDIA) {
2903 return;
2904 }
2905 int index = mBatteryData.indexOfKey(uid);
Gloria Wang7cf180c2011-02-19 18:37:57 -08002906
2907 if (index < 0) { // create a new entry for this UID
2908 BatteryUsageInfo info;
2909 info.audioTotalTime = 0;
2910 info.videoTotalTime = 0;
2911 info.audioLastTime = 0;
2912 info.videoLastTime = 0;
2913 info.refCount = 0;
2914
Gloria Wang9ee159b2011-02-24 14:51:45 -08002915 if (mBatteryData.add(uid, info) == NO_MEMORY) {
Steve Block29357bc2012-01-06 19:20:56 +00002916 ALOGE("Battery track error: no memory for new app");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002917 return;
2918 }
Gloria Wang7cf180c2011-02-19 18:37:57 -08002919 }
2920
2921 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
2922
2923 if (params & kBatteryDataCodecStarted) {
2924 if (params & kBatteryDataTrackAudio) {
2925 info.audioLastTime -= time;
2926 info.refCount ++;
2927 }
2928 if (params & kBatteryDataTrackVideo) {
2929 info.videoLastTime -= time;
2930 info.refCount ++;
2931 }
2932 } else {
2933 if (info.refCount == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002934 ALOGW("Battery track warning: refCount is already 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002935 return;
2936 } else if (info.refCount < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00002937 ALOGE("Battery track error: refCount < 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002938 mBatteryData.removeItem(uid);
2939 return;
2940 }
2941
2942 if (params & kBatteryDataTrackAudio) {
2943 info.audioLastTime += time;
2944 info.refCount --;
2945 }
2946 if (params & kBatteryDataTrackVideo) {
2947 info.videoLastTime += time;
2948 info.refCount --;
2949 }
2950
2951 // no stream is being played by this UID
2952 if (info.refCount == 0) {
2953 info.audioTotalTime += info.audioLastTime;
2954 info.audioLastTime = 0;
2955 info.videoTotalTime += info.videoLastTime;
2956 info.videoLastTime = 0;
2957 }
2958 }
2959}
2960
Chong Zhange5b9b692017-05-11 11:44:56 -07002961status_t MediaPlayerService::BatteryTracker::pullBatteryData(Parcel* reply) {
Gloria Wang7cf180c2011-02-19 18:37:57 -08002962 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002963
2964 // audio output devices usage
2965 int32_t time = systemTime() / 1000000L; //in ms
2966 int32_t totalTime;
2967
2968 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2969 totalTime = mBatteryAudio.totalTime[i];
2970
2971 if (mBatteryAudio.deviceOn[i]
2972 && (mBatteryAudio.lastTime[i] != 0)) {
2973 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
2974 totalTime += tmpTime;
2975 }
2976
2977 reply->writeInt32(totalTime);
2978 // reset the total time
2979 mBatteryAudio.totalTime[i] = 0;
2980 }
2981
2982 // codec usage
Gloria Wang7cf180c2011-02-19 18:37:57 -08002983 BatteryUsageInfo info;
2984 int size = mBatteryData.size();
2985
2986 reply->writeInt32(size);
2987 int i = 0;
2988
2989 while (i < size) {
2990 info = mBatteryData.valueAt(i);
2991
2992 reply->writeInt32(mBatteryData.keyAt(i)); //UID
2993 reply->writeInt32(info.audioTotalTime);
2994 reply->writeInt32(info.videoTotalTime);
2995
2996 info.audioTotalTime = 0;
2997 info.videoTotalTime = 0;
2998
2999 // remove the UID entry where no stream is being played
3000 if (info.refCount <= 0) {
3001 mBatteryData.removeItemsAt(i);
3002 size --;
3003 i --;
3004 }
3005 i++;
3006 }
3007 return NO_ERROR;
3008}
nikoa64c8c72009-07-20 15:07:26 -07003009} // namespace android