blob: 5061024f8f0d4cfe7a3c54ca789e68cd56d47c39 [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
Marco Nelissena0c98412019-03-29 12:10:19 -070037#include <android/hardware/media/omx/1.0/IOmxStore.h>
38#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
Andreas Huber1b86fe02014-01-29 11:13:26 -080050#include <media/IMediaHTTPService.h>
Jeff Brown2013a542012-09-04 21:38:42 -070051#include <media/IRemoteDisplay.h>
52#include <media/IRemoteDisplayClient.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080053#include <media/MediaPlayerInterface.h>
54#include <media/mediarecorder.h>
55#include <media/MediaMetadataRetrieverInterface.h>
nikoa64c8c72009-07-20 15:07:26 -070056#include <media/Metadata.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080057#include <media/AudioTrack.h>
James Dong8635b7b2011-03-14 17:01:38 -070058#include <media/MemoryLeakTrackUtil.h>
Dongwon Kangd91dc5a2017-10-10 00:07:09 -070059#include <media/stagefright/InterfaceUtils.h>
Lajos Molnar1381d4b2014-08-07 15:18:35 -070060#include <media/stagefright/MediaCodecList.h>
Eric Laurent9cb839a2011-09-27 09:48:56 -070061#include <media/stagefright/MediaErrors.h>
Marco Nelissen83b0fd92015-09-16 13:48:07 -070062#include <media/stagefright/Utils.h>
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +010063#include <media/stagefright/foundation/ADebug.h>
Marco Nelissenf09611f2015-02-13 14:12:42 -080064#include <media/stagefright/foundation/ALooperRoster.h>
Chong Zhang181fd9b2017-02-16 15:53:03 -080065#include <media/stagefright/SurfaceUtils.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070066#include <mediautils/BatteryNotifier.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080067
Andy Hung53541292016-04-13 16:48:51 -070068#include <memunreachable/memunreachable.h>
Dima Zavin64760242011-05-11 14:15:23 -070069#include <system/audio.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070070
Gloria Wang7cf180c2011-02-19 18:37:57 -080071#include <private/android_filesystem_config.h>
72
James Dong559bf282012-03-28 10:29:14 -070073#include "ActivityManager.h"
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080074#include "MediaRecorderClient.h"
75#include "MediaPlayerService.h"
76#include "MetadataRetrieverClient.h"
John Grossman44a7e422012-06-21 17:29:24 -070077#include "MediaPlayerFactory.h"
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080078
Nicolas Catania14d27472009-07-13 14:37:49 -070079#include "TestPlayerStub.h"
Andreas Huberf9334412010-12-15 15:17:42 -080080#include "nuplayer/NuPlayerDriver.h"
Andreas Huber20111aa2009-07-14 16:56:47 -070081
Andreas Huberb7319a72013-05-29 14:20:52 -070082#include "HTTPBase.h"
Andreas Hubered3e3e02012-03-26 11:13:27 -070083
Wei Jia502c2f42017-07-13 17:47:56 -070084static const int kDumpLockRetries = 50;
85static const int kDumpLockSleepUs = 20000;
86
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070087namespace {
nikoa64c8c72009-07-20 15:07:26 -070088using android::media::Metadata;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070089using android::status_t;
90using android::OK;
91using android::BAD_VALUE;
92using android::NOT_ENOUGH_DATA;
93using android::Parcel;
Ivan Lozano8cf3a072017-08-09 09:01:33 -070094using android::media::VolumeShaper;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070095
96// Max number of entries in the filter.
97const int kMaxFilterSize = 64; // I pulled that out of thin air.
98
Andy Hungff874dc2016-04-11 16:49:09 -070099const float kMaxRequiredSpeed = 8.0f; // for PCM tracks allow up to 8x speedup.
100
nikoa64c8c72009-07-20 15:07:26 -0700101// FIXME: Move all the metadata related function in the Metadata.cpp
nikod608a812009-07-16 16:39:53 -0700102
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700103
104// Unmarshall a filter from a Parcel.
105// Filter format in a parcel:
106//
107// 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
108// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
109// | number of entries (n) |
110// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
111// | metadata type 1 |
112// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
113// | metadata type 2 |
114// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
115// ....
116// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
117// | metadata type n |
118// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
119//
120// @param p Parcel that should start with a filter.
121// @param[out] filter On exit contains the list of metadata type to be
122// filtered.
123// @param[out] status On exit contains the status code to be returned.
124// @return true if the parcel starts with a valid filter.
125bool unmarshallFilter(const Parcel& p,
nikoa64c8c72009-07-20 15:07:26 -0700126 Metadata::Filter *filter,
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700127 status_t *status)
128{
Nicolas Catania48290382009-07-10 13:53:06 -0700129 int32_t val;
130 if (p.readInt32(&val) != OK)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700131 {
Steve Block29357bc2012-01-06 19:20:56 +0000132 ALOGE("Failed to read filter's length");
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700133 *status = NOT_ENOUGH_DATA;
134 return false;
135 }
136
Nicolas Catania48290382009-07-10 13:53:06 -0700137 if( val > kMaxFilterSize || val < 0)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700138 {
Steve Block29357bc2012-01-06 19:20:56 +0000139 ALOGE("Invalid filter len %d", val);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700140 *status = BAD_VALUE;
141 return false;
142 }
143
Nicolas Catania48290382009-07-10 13:53:06 -0700144 const size_t num = val;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700145
146 filter->clear();
Nicolas Catania48290382009-07-10 13:53:06 -0700147 filter->setCapacity(num);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700148
nikoa64c8c72009-07-20 15:07:26 -0700149 size_t size = num * sizeof(Metadata::Type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700150
Nicolas Catania48290382009-07-10 13:53:06 -0700151
152 if (p.dataAvail() < size)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700153 {
Andy Hung833b4752016-04-04 17:15:48 -0700154 ALOGE("Filter too short expected %zu but got %zu", size, p.dataAvail());
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700155 *status = NOT_ENOUGH_DATA;
156 return false;
157 }
158
nikoa64c8c72009-07-20 15:07:26 -0700159 const Metadata::Type *data =
160 static_cast<const Metadata::Type*>(p.readInplace(size));
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700161
Nicolas Catania48290382009-07-10 13:53:06 -0700162 if (NULL == data)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700163 {
Steve Block29357bc2012-01-06 19:20:56 +0000164 ALOGE("Filter had no data");
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700165 *status = BAD_VALUE;
166 return false;
167 }
168
169 // TODO: The stl impl of vector would be more efficient here
170 // because it degenerates into a memcpy on pod types. Try to
171 // replace later or use stl::set.
Nicolas Catania48290382009-07-10 13:53:06 -0700172 for (size_t i = 0; i < num; ++i)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700173 {
Nicolas Catania48290382009-07-10 13:53:06 -0700174 filter->add(*data);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700175 ++data;
176 }
177 *status = OK;
178 return true;
179}
180
Nicolas Catania48290382009-07-10 13:53:06 -0700181// @param filter Of metadata type.
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700182// @param val To be searched.
183// @return true if a match was found.
nikoa64c8c72009-07-20 15:07:26 -0700184bool findMetadata(const Metadata::Filter& filter, const int32_t val)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700185{
186 // Deal with empty and ANY right away
187 if (filter.isEmpty()) return false;
nikoa64c8c72009-07-20 15:07:26 -0700188 if (filter[0] == Metadata::kAny) return true;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700189
Nicolas Catania48290382009-07-10 13:53:06 -0700190 return filter.indexOf(val) >= 0;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700191}
192
193} // anonymous namespace
194
195
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700196namespace {
197using android::Parcel;
198using android::String16;
199
200// marshalling tag indicating flattened utf16 tags
201// keep in sync with frameworks/base/media/java/android/media/AudioAttributes.java
202const int32_t kAudioAttributesMarshallTagFlattenTags = 1;
203
204// Audio attributes format in a parcel:
205//
206// 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
207// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
208// | usage |
209// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
210// | content_type |
211// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Hyejin Kim4f418f92014-09-05 15:50:03 +0900212// | source |
213// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700214// | flags |
215// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
216// | kAudioAttributesMarshallTagFlattenTags | // ignore tags if not found
217// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
218// | flattened tags in UTF16 |
219// | ... |
220// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
221//
222// @param p Parcel that contains audio attributes.
223// @param[out] attributes On exit points to an initialized audio_attributes_t structure
224// @param[out] status On exit contains the status code to be returned.
225void unmarshallAudioAttributes(const Parcel& parcel, audio_attributes_t *attributes)
226{
227 attributes->usage = (audio_usage_t) parcel.readInt32();
228 attributes->content_type = (audio_content_type_t) parcel.readInt32();
Hyejin Kim4f418f92014-09-05 15:50:03 +0900229 attributes->source = (audio_source_t) parcel.readInt32();
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700230 attributes->flags = (audio_flags_mask_t) parcel.readInt32();
231 const bool hasFlattenedTag = (parcel.readInt32() == kAudioAttributesMarshallTagFlattenTags);
232 if (hasFlattenedTag) {
233 // the tags are UTF16, convert to UTF8
234 String16 tags = parcel.readString16();
235 ssize_t realTagSize = utf16_to_utf8_length(tags.string(), tags.size());
236 if (realTagSize <= 0) {
237 strcpy(attributes->tags, "");
238 } else {
239 // copy the flattened string into the attributes as the destination for the conversion:
240 // copying array size -1, array for tags was calloc'd, no need to NULL-terminate it
241 size_t tagSize = realTagSize > AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 ?
242 AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 : realTagSize;
Sergio Giro1d3f4272016-06-28 18:24:52 +0100243 utf16_to_utf8(tags.string(), tagSize, attributes->tags,
244 sizeof(attributes->tags) / sizeof(attributes->tags[0]));
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700245 }
246 } else {
247 ALOGE("unmarshallAudioAttributes() received unflattened tags, ignoring tag values");
248 strcpy(attributes->tags, "");
249 }
250}
251} // anonymous namespace
252
253
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800254namespace android {
255
Marco Nelissenf09611f2015-02-13 14:12:42 -0800256extern ALooperRoster gLooperRoster;
257
258
Dave Burked681bbb2011-08-30 14:39:17 +0100259static bool checkPermission(const char* permissionString) {
Dave Burked681bbb2011-08-30 14:39:17 +0100260 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
261 bool ok = checkCallingPermission(String16(permissionString));
Steve Block29357bc2012-01-06 19:20:56 +0000262 if (!ok) ALOGE("Request requires %s", permissionString);
Dave Burked681bbb2011-08-30 14:39:17 +0100263 return ok;
264}
265
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800266// 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 -0800267/* static */ int MediaPlayerService::AudioOutput::mMinBufferCount = 4;
268/* static */ bool MediaPlayerService::AudioOutput::mIsOnEmulator = false;
269
270void MediaPlayerService::instantiate() {
271 defaultServiceManager()->addService(
272 String16("media.player"), new MediaPlayerService());
273}
274
275MediaPlayerService::MediaPlayerService()
276{
Steve Block3856b092011-10-20 11:56:00 +0100277 ALOGV("MediaPlayerService created");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800278 mNextConnId = 1;
Gloria Wang9ee159b2011-02-24 14:51:45 -0800279
John Grossman44a7e422012-06-21 17:29:24 -0700280 MediaPlayerFactory::registerBuiltinFactories();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800281}
282
283MediaPlayerService::~MediaPlayerService()
284{
Steve Block3856b092011-10-20 11:56:00 +0100285 ALOGV("MediaPlayerService destroyed");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800286}
287
Svet Ganovbe71aa22015-04-28 12:06:02 -0700288sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(const String16 &opPackageName)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800289{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800290 pid_t pid = IPCThreadState::self()->getCallingPid();
Svet Ganovbe71aa22015-04-28 12:06:02 -0700291 sp<MediaRecorderClient> recorder = new MediaRecorderClient(this, pid, opPackageName);
Gloria Wangdac6a312009-10-29 15:46:37 -0700292 wp<MediaRecorderClient> w = recorder;
293 Mutex::Autolock lock(mLock);
294 mMediaRecorderClients.add(w);
Steve Block3856b092011-10-20 11:56:00 +0100295 ALOGV("Create new media recorder client from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800296 return recorder;
297}
298
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -0700299void MediaPlayerService::removeMediaRecorderClient(const wp<MediaRecorderClient>& client)
Gloria Wangdac6a312009-10-29 15:46:37 -0700300{
301 Mutex::Autolock lock(mLock);
302 mMediaRecorderClients.remove(client);
Steve Block3856b092011-10-20 11:56:00 +0100303 ALOGV("Delete media recorder client");
Gloria Wangdac6a312009-10-29 15:46:37 -0700304}
305
Glenn Kastenf37971f2012-02-03 11:06:53 -0800306sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800307{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800308 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800309 sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
Steve Block3856b092011-10-20 11:56:00 +0100310 ALOGV("Create new media retriever from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800311 return retriever;
312}
313
Glenn Kastenf37971f2012-02-03 11:06:53 -0800314sp<IMediaPlayer> MediaPlayerService::create(const sp<IMediaPlayerClient>& client,
Glenn Kastend848eb42016-03-08 13:42:11 -0800315 audio_session_t audioSessionId)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800316{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800317 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800318 int32_t connId = android_atomic_inc(&mNextConnId);
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700319
320 sp<Client> c = new Client(
321 this, pid, connId, client, audioSessionId,
322 IPCThreadState::self()->getCallingUid());
323
Steve Block3856b092011-10-20 11:56:00 +0100324 ALOGV("Create new client(%d) from pid %d, uid %d, ", connId, pid,
Dave Burked681bbb2011-08-30 14:39:17 +0100325 IPCThreadState::self()->getCallingUid());
326
327 wp<Client> w = c;
328 {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800329 Mutex::Autolock lock(mLock);
330 mClients.add(w);
331 }
Andreas Hubere2b10282010-11-23 11:41:34 -0800332 return c;
333}
334
Lajos Molnar1381d4b2014-08-07 15:18:35 -0700335sp<IMediaCodecList> MediaPlayerService::getCodecList() const {
336 return MediaCodecList::getLocalInstance();
337}
338
Jeff Brown2013a542012-09-04 21:38:42 -0700339sp<IRemoteDisplay> MediaPlayerService::listenForRemoteDisplay(
Chong Zhangd0a98fa2017-09-14 17:43:10 -0700340 const String16 &/*opPackageName*/,
341 const sp<IRemoteDisplayClient>& /*client*/,
342 const String8& /*iface*/) {
343 ALOGE("listenForRemoteDisplay is no longer supported!");
Jeff Brownaba33d52012-09-07 17:38:58 -0700344
Chong Zhangd0a98fa2017-09-14 17:43:10 -0700345 return NULL;
Jeff Brown2013a542012-09-04 21:38:42 -0700346}
347
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800348status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
349{
350 const size_t SIZE = 256;
351 char buffer[SIZE];
352 String8 result;
353
354 result.append(" AudioOutput\n");
355 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n",
356 mStreamType, mLeftVolume, mRightVolume);
357 result.append(buffer);
358 snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n",
Eric Laurentdb354e52012-03-05 17:27:11 -0800359 mMsecsPerFrame, (mTrack != 0) ? mTrack->latency() : -1);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800360 result.append(buffer);
Eric Laurent2beeb502010-07-16 07:43:46 -0700361 snprintf(buffer, 255, " aux effect id(%d), send level (%f)\n",
362 mAuxEffectId, mSendLevel);
363 result.append(buffer);
364
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800365 ::write(fd, result.string(), result.size());
366 if (mTrack != 0) {
367 mTrack->dump(fd, args);
368 }
369 return NO_ERROR;
370}
371
Lajos Molnar6d339f12015-04-17 16:15:53 -0700372status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800373{
374 const size_t SIZE = 256;
375 char buffer[SIZE];
376 String8 result;
377 result.append(" Client\n");
378 snprintf(buffer, 255, " pid(%d), connId(%d), status(%d), looping(%s)\n",
379 mPid, mConnId, mStatus, mLoop?"true": "false");
380 result.append(buffer);
Wei Jia502c2f42017-07-13 17:47:56 -0700381
382 sp<MediaPlayerBase> p;
383 sp<AudioOutput> audioOutput;
384 bool locked = false;
385 for (int i = 0; i < kDumpLockRetries; ++i) {
386 if (mLock.tryLock() == NO_ERROR) {
387 locked = true;
388 break;
389 }
390 usleep(kDumpLockSleepUs);
Andreas Hubera0b1d4b2011-06-07 15:52:25 -0700391 }
Wei Jia502c2f42017-07-13 17:47:56 -0700392
393 if (locked) {
394 p = mPlayer;
395 audioOutput = mAudioOutput;
396 mLock.unlock();
397 } else {
398 result.append(" lock is taken, no dump from player and audio output\n");
399 }
400 write(fd, result.string(), result.size());
401
402 if (p != NULL) {
403 p->dump(fd, args);
404 }
405 if (audioOutput != 0) {
406 audioOutput->dump(fd, args);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800407 }
408 write(fd, "\n", 1);
409 return NO_ERROR;
410}
411
Marco Nelissenf09611f2015-02-13 14:12:42 -0800412/**
413 * The only arguments this understands right now are -c, -von and -voff,
414 * which are parsed by ALooperRoster::dump()
415 */
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800416status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
417{
418 const size_t SIZE = 256;
419 char buffer[SIZE];
420 String8 result;
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530421 SortedVector< sp<Client> > clients; //to serialise the mutex unlock & client destruction.
422 SortedVector< sp<MediaRecorderClient> > mediaRecorderClients;
423
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800424 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
425 snprintf(buffer, SIZE, "Permission Denial: "
426 "can't dump MediaPlayerService from pid=%d, uid=%d\n",
427 IPCThreadState::self()->getCallingPid(),
428 IPCThreadState::self()->getCallingUid());
429 result.append(buffer);
430 } else {
431 Mutex::Autolock lock(mLock);
432 for (int i = 0, n = mClients.size(); i < n; ++i) {
433 sp<Client> c = mClients[i].promote();
434 if (c != 0) c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530435 clients.add(c);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800436 }
James Dongb9141222010-07-08 11:16:11 -0700437 if (mMediaRecorderClients.size() == 0) {
438 result.append(" No media recorder client\n\n");
439 } else {
440 for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
441 sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
James Donge579e282011-10-18 22:29:20 -0700442 if (c != 0) {
443 snprintf(buffer, 255, " MediaRecorderClient pid(%d)\n", c->mPid);
444 result.append(buffer);
445 write(fd, result.string(), result.size());
446 result = "\n";
447 c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530448 mediaRecorderClients.add(c);
James Donge579e282011-10-18 22:29:20 -0700449 }
James Dongb9141222010-07-08 11:16:11 -0700450 }
Gloria Wangdac6a312009-10-29 15:46:37 -0700451 }
452
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800453 result.append(" Files opened and/or mapped:\n");
Marco Nelissenf09611f2015-02-13 14:12:42 -0800454 snprintf(buffer, SIZE, "/proc/%d/maps", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800455 FILE *f = fopen(buffer, "r");
456 if (f) {
457 while (!feof(f)) {
458 fgets(buffer, SIZE, f);
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700459 if (strstr(buffer, " /storage/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800460 strstr(buffer, " /system/sounds/") ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700461 strstr(buffer, " /data/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800462 strstr(buffer, " /system/media/")) {
463 result.append(" ");
464 result.append(buffer);
465 }
466 }
467 fclose(f);
468 } else {
469 result.append("couldn't open ");
470 result.append(buffer);
471 result.append("\n");
472 }
473
Marco Nelissenf09611f2015-02-13 14:12:42 -0800474 snprintf(buffer, SIZE, "/proc/%d/fd", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800475 DIR *d = opendir(buffer);
476 if (d) {
477 struct dirent *ent;
478 while((ent = readdir(d)) != NULL) {
479 if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
Marco Nelissenf09611f2015-02-13 14:12:42 -0800480 snprintf(buffer, SIZE, "/proc/%d/fd/%s", getpid(), ent->d_name);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800481 struct stat s;
482 if (lstat(buffer, &s) == 0) {
483 if ((s.st_mode & S_IFMT) == S_IFLNK) {
484 char linkto[256];
485 int len = readlink(buffer, linkto, sizeof(linkto));
486 if(len > 0) {
487 if(len > 255) {
488 linkto[252] = '.';
489 linkto[253] = '.';
490 linkto[254] = '.';
491 linkto[255] = 0;
492 } else {
493 linkto[len] = 0;
494 }
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700495 if (strstr(linkto, "/storage/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800496 strstr(linkto, "/system/sounds/") == linkto ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700497 strstr(linkto, "/data/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800498 strstr(linkto, "/system/media/") == linkto) {
499 result.append(" ");
500 result.append(buffer);
501 result.append(" -> ");
502 result.append(linkto);
503 result.append("\n");
504 }
505 }
506 } else {
507 result.append(" unexpected type for ");
508 result.append(buffer);
509 result.append("\n");
510 }
511 }
512 }
513 }
514 closedir(d);
515 } else {
516 result.append("couldn't open ");
517 result.append(buffer);
518 result.append("\n");
519 }
520
Marco Nelissenf09611f2015-02-13 14:12:42 -0800521 gLooperRoster.dump(fd, args);
522
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800523 bool dumpMem = false;
Andy Hung53541292016-04-13 16:48:51 -0700524 bool unreachableMemory = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800525 for (size_t i = 0; i < args.size(); i++) {
526 if (args[i] == String16("-m")) {
527 dumpMem = true;
Andy Hung53541292016-04-13 16:48:51 -0700528 } else if (args[i] == String16("--unreachable")) {
529 unreachableMemory = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800530 }
531 }
532 if (dumpMem) {
Andy Hung07b745e2016-05-23 16:21:07 -0700533 result.append("\nDumping memory:\n");
534 std::string s = dumpMemoryAddresses(100 /* limit */);
535 result.append(s.c_str(), s.size());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800536 }
Andy Hung53541292016-04-13 16:48:51 -0700537 if (unreachableMemory) {
538 result.append("\nDumping unreachable memory:\n");
539 // TODO - should limit be an argument parameter?
540 std::string s = GetUnreachableMemoryString(true /* contents */, 10000 /* limit */);
541 result.append(s.c_str(), s.size());
542 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800543 }
544 write(fd, result.string(), result.size());
545 return NO_ERROR;
546}
547
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -0700548void MediaPlayerService::removeClient(const wp<Client>& client)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800549{
550 Mutex::Autolock lock(mLock);
551 mClients.remove(client);
552}
553
Robert Shihee0a0e32016-08-16 16:50:54 -0700554bool MediaPlayerService::hasClient(wp<Client> client)
555{
556 Mutex::Autolock lock(mLock);
557 return mClients.indexOf(client) != NAME_NOT_FOUND;
558}
559
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700560MediaPlayerService::Client::Client(
561 const sp<MediaPlayerService>& service, pid_t pid,
562 int32_t connId, const sp<IMediaPlayerClient>& client,
Glenn Kastend848eb42016-03-08 13:42:11 -0800563 audio_session_t audioSessionId, uid_t uid)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800564{
Steve Block3856b092011-10-20 11:56:00 +0100565 ALOGV("Client(%d) constructor", connId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800566 mPid = pid;
567 mConnId = connId;
568 mService = service;
569 mClient = client;
570 mLoop = false;
571 mStatus = NO_INIT;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700572 mAudioSessionId = audioSessionId;
Andy Hung1afd0982016-11-08 16:13:44 -0800573 mUid = uid;
John Grossmanc795b642012-02-22 15:38:35 -0800574 mRetransmitEndpointValid = false;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700575 mAudioAttributes = NULL;
Pawin Vongmasa082e4f72017-12-17 02:31:18 -0800576 mListener = new Listener(this);
Eric Laurenta514bdb2010-06-21 09:27:30 -0700577
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800578#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000579 ALOGD("create Antagonizer");
Pawin Vongmasa082e4f72017-12-17 02:31:18 -0800580 mAntagonizer = new Antagonizer(mListener);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800581#endif
582}
583
584MediaPlayerService::Client::~Client()
585{
Steve Block3856b092011-10-20 11:56:00 +0100586 ALOGV("Client(%d) destructor pid = %d", mConnId, mPid);
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700587 mAudioOutput.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800588 wp<Client> client(this);
589 disconnect();
590 mService->removeClient(client);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700591 if (mAudioAttributes != NULL) {
592 free(mAudioAttributes);
593 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700594 clearDeathNotifiers_l();
jiabin156c6872017-10-06 09:47:15 -0700595 mAudioDeviceUpdatedListener.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800596}
597
598void MediaPlayerService::Client::disconnect()
599{
Steve Block3856b092011-10-20 11:56:00 +0100600 ALOGV("disconnect(%d) from pid %d", mConnId, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800601 // grab local reference and clear main reference to prevent future
602 // access to object
603 sp<MediaPlayerBase> p;
604 {
605 Mutex::Autolock l(mLock);
606 p = mPlayer;
beanzdcfefde2012-11-05 09:51:43 +0800607 mClient.clear();
Wei Jia502c2f42017-07-13 17:47:56 -0700608 mPlayer.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800609 }
Andreas Huber20111aa2009-07-14 16:56:47 -0700610
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800611 // clear the notification to prevent callbacks to dead client
612 // and reset the player. We assume the player will serialize
613 // access to itself if necessary.
614 if (p != 0) {
Pawin Vongmasa082e4f72017-12-17 02:31:18 -0800615 p->setNotifyCallback(0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800616#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000617 ALOGD("kill Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800618 mAntagonizer->kill();
619#endif
620 p->reset();
621 }
622
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700623 {
624 Mutex::Autolock l(mLock);
625 disconnectNativeWindow_l();
626 }
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700627
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800628 IPCThreadState::self()->flushCommands();
629}
630
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800631sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
632{
633 // determine if we have the right player type
Wei Jia502c2f42017-07-13 17:47:56 -0700634 sp<MediaPlayerBase> p = getPlayer();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800635 if ((p != NULL) && (p->playerType() != playerType)) {
Steve Block3856b092011-10-20 11:56:00 +0100636 ALOGV("delete player");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800637 p.clear();
638 }
639 if (p == NULL) {
Pawin Vongmasa082e4f72017-12-17 02:31:18 -0800640 p = MediaPlayerFactory::createPlayer(playerType, mListener, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800641 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700642
Jason Simmonsdb29e522011-08-12 13:46:55 -0700643 if (p != NULL) {
Andy Hung1afd0982016-11-08 16:13:44 -0800644 p->setUID(mUid);
Jason Simmonsdb29e522011-08-12 13:46:55 -0700645 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700646
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800647 return p;
648}
649
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700650MediaPlayerService::Client::ServiceDeathNotifier::ServiceDeathNotifier(
651 const sp<IBinder>& service,
652 const sp<MediaPlayerBase>& listener,
653 int which) {
654 mService = service;
Marco Nelissena0c98412019-03-29 12:10:19 -0700655 mHService = nullptr;
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800656 mListener = listener;
657 mWhich = which;
658}
659
660MediaPlayerService::Client::ServiceDeathNotifier::ServiceDeathNotifier(
Marco Nelissena0c98412019-03-29 12:10:19 -0700661 const sp<android::hidl::base::V1_0::IBase>& hService,
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800662 const sp<MediaPlayerBase>& listener,
663 int which) {
664 mService = nullptr;
Marco Nelissena0c98412019-03-29 12:10:19 -0700665 mHService = hService;
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700666 mListener = listener;
667 mWhich = which;
668}
669
670MediaPlayerService::Client::ServiceDeathNotifier::~ServiceDeathNotifier() {
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700671}
672
673void MediaPlayerService::Client::ServiceDeathNotifier::binderDied(const wp<IBinder>& /*who*/) {
674 sp<MediaPlayerBase> listener = mListener.promote();
675 if (listener != NULL) {
676 listener->sendEvent(MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED, mWhich);
677 } else {
678 ALOGW("listener for process %d death is gone", mWhich);
679 }
680}
681
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800682void MediaPlayerService::Client::ServiceDeathNotifier::serviceDied(
683 uint64_t /* cookie */,
684 const wp<::android::hidl::base::V1_0::IBase>& /* who */) {
685 sp<MediaPlayerBase> listener = mListener.promote();
686 if (listener != NULL) {
687 listener->sendEvent(MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED, mWhich);
688 } else {
689 ALOGW("listener for process %d death is gone", mWhich);
690 }
691}
692
693void MediaPlayerService::Client::ServiceDeathNotifier::unlinkToDeath() {
694 if (mService != nullptr) {
695 mService->unlinkToDeath(this);
696 mService = nullptr;
Marco Nelissena0c98412019-03-29 12:10:19 -0700697 } else if (mHService != nullptr) {
698 mHService->unlinkToDeath(this);
699 mHService = nullptr;
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800700 }
701}
702
jiabin156c6872017-10-06 09:47:15 -0700703void MediaPlayerService::Client::AudioDeviceUpdatedNotifier::onAudioDeviceUpdate(
704 audio_io_handle_t audioIo,
705 audio_port_handle_t deviceId) {
706 sp<MediaPlayerBase> listener = mListener.promote();
707 if (listener != NULL) {
708 listener->sendEvent(MEDIA_AUDIO_ROUTING_CHANGED, audioIo, deviceId);
709 } else {
710 ALOGW("listener for process %d death is gone", MEDIA_AUDIO_ROUTING_CHANGED);
711 }
712}
713
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700714void MediaPlayerService::Client::clearDeathNotifiers_l() {
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800715 if (mExtractorDeathListener != nullptr) {
716 mExtractorDeathListener->unlinkToDeath();
717 mExtractorDeathListener = nullptr;
718 }
Marco Nelissena0c98412019-03-29 12:10:19 -0700719 for (const sp<ServiceDeathNotifier>& codecDeathListener : mCodecDeathListeners) {
720 if (codecDeathListener != nullptr) {
721 codecDeathListener->unlinkToDeath();
722 }
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800723 }
Marco Nelissena0c98412019-03-29 12:10:19 -0700724 mCodecDeathListeners.clear();
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800725}
726
John Grossmanc795b642012-02-22 15:38:35 -0800727sp<MediaPlayerBase> MediaPlayerService::Client::setDataSource_pre(
728 player_type playerType)
729{
730 ALOGV("player type = %d", playerType);
731
732 // create the right type of player
733 sp<MediaPlayerBase> p = createPlayer(playerType);
734 if (p == NULL) {
735 return p;
736 }
737
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700738 sp<IServiceManager> sm = defaultServiceManager();
739 sp<IBinder> binder = sm->getService(String16("media.extractor"));
Marco Nelissen1b5a7ee2016-09-30 13:54:30 -0700740 if (binder == NULL) {
741 ALOGE("extractor service not available");
742 return NULL;
743 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700744 sp<ServiceDeathNotifier> extractorDeathListener =
745 new ServiceDeathNotifier(binder, p, MEDIAEXTRACTOR_PROCESS_DEATH);
746 binder->linkToDeath(extractorDeathListener);
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700747
Marco Nelissena0c98412019-03-29 12:10:19 -0700748 std::vector<sp<ServiceDeathNotifier>> codecDeathListeners;
749 {
750 using ::android::hidl::base::V1_0::IBase;
751
752 // Listen to OMX's IOmxStore/default
753 {
754 sp<IBase> store = ::android::hardware::media::omx::V1_0::
755 IOmxStore::getService();
756 if (store == nullptr) {
757 ALOGD("OMX service is not available");
758 } else {
759 sp<ServiceDeathNotifier> codecDeathListener =
760 new ServiceDeathNotifier(store, p, MEDIACODEC_PROCESS_DEATH);
761 store->linkToDeath(codecDeathListener, 0);
762 codecDeathListeners.emplace_back(codecDeathListener);
763 }
764 }
765
766 // Listen to Codec2's IComponentStore/software
767 // TODO: Listen to all Codec2 services.
768 {
769 sp<IBase> store = ::android::hardware::media::c2::V1_0::
770 IComponentStore::getService();
771 if (store == nullptr) {
772 ALOGD("Codec2 system service is not available");
773 } else {
774 sp<ServiceDeathNotifier> codecDeathListener =
775 new ServiceDeathNotifier(store, p, MEDIACODEC_PROCESS_DEATH);
776 store->linkToDeath(codecDeathListener, 0);
777 codecDeathListeners.emplace_back(codecDeathListener);
778 }
Marco Nelissene4da6c62019-04-01 15:01:41 -0700779
780 store = ::android::hardware::media::c2::V1_0::
781 IComponentStore::getService("software");
782 if (store == nullptr) {
783 ALOGD("Codec2 swcodec service is not available");
784 } else {
785 sp<ServiceDeathNotifier> codecDeathListener =
786 new ServiceDeathNotifier(store, p, MEDIACODEC_PROCESS_DEATH);
787 store->linkToDeath(codecDeathListener, 0);
788 codecDeathListeners.emplace_back(codecDeathListener);
789 }
Marco Nelissena0c98412019-03-29 12:10:19 -0700790 }
Marco Nelissen1b5a7ee2016-09-30 13:54:30 -0700791 }
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700792
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700793 Mutex::Autolock lock(mLock);
794
795 clearDeathNotifiers_l();
796 mExtractorDeathListener = extractorDeathListener;
Marco Nelissena0c98412019-03-29 12:10:19 -0700797 mCodecDeathListeners.swap(codecDeathListeners);
jiabin156c6872017-10-06 09:47:15 -0700798 mAudioDeviceUpdatedListener = new AudioDeviceUpdatedNotifier(p);
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700799
John Grossmanc795b642012-02-22 15:38:35 -0800800 if (!p->hardwareOutput()) {
Marco Nelissend457c972014-02-11 08:47:07 -0800801 mAudioOutput = new AudioOutput(mAudioSessionId, IPCThreadState::self()->getCallingUid(),
jiabin156c6872017-10-06 09:47:15 -0700802 mPid, mAudioAttributes, mAudioDeviceUpdatedListener);
John Grossmanc795b642012-02-22 15:38:35 -0800803 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
804 }
805
806 return p;
807}
808
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700809status_t MediaPlayerService::Client::setDataSource_post(
John Grossmanc795b642012-02-22 15:38:35 -0800810 const sp<MediaPlayerBase>& p,
811 status_t status)
812{
813 ALOGV(" setDataSource");
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700814 if (status != OK) {
815 ALOGE(" error: %d", status);
816 return status;
John Grossmanc795b642012-02-22 15:38:35 -0800817 }
818
819 // Set the re-transmission endpoint if one was chosen.
820 if (mRetransmitEndpointValid) {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700821 status = p->setRetransmitEndpoint(&mRetransmitEndpoint);
822 if (status != NO_ERROR) {
823 ALOGE("setRetransmitEndpoint error: %d", status);
John Grossmanc795b642012-02-22 15:38:35 -0800824 }
825 }
826
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700827 if (status == OK) {
828 Mutex::Autolock lock(mLock);
John Grossmanc795b642012-02-22 15:38:35 -0800829 mPlayer = p;
830 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700831 return status;
John Grossmanc795b642012-02-22 15:38:35 -0800832}
833
Andreas Huber2db84552010-01-28 11:19:57 -0800834status_t MediaPlayerService::Client::setDataSource(
Andreas Huber1b86fe02014-01-29 11:13:26 -0800835 const sp<IMediaHTTPService> &httpService,
836 const char *url,
837 const KeyedVector<String8, String8> *headers)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800838{
Steve Block3856b092011-10-20 11:56:00 +0100839 ALOGV("setDataSource(%s)", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800840 if (url == NULL)
841 return UNKNOWN_ERROR;
842
Dave Burked681bbb2011-08-30 14:39:17 +0100843 if ((strncmp(url, "http://", 7) == 0) ||
844 (strncmp(url, "https://", 8) == 0) ||
845 (strncmp(url, "rtsp://", 7) == 0)) {
846 if (!checkPermission("android.permission.INTERNET")) {
847 return PERMISSION_DENIED;
848 }
849 }
850
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800851 if (strncmp(url, "content://", 10) == 0) {
852 // get a filedescriptor for the content Uri and
853 // pass it to the setDataSource(fd) method
854
855 String16 url16(url);
856 int fd = android::openContentProviderFile(url16);
857 if (fd < 0)
858 {
Steve Block29357bc2012-01-06 19:20:56 +0000859 ALOGE("Couldn't open fd for %s", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800860 return UNKNOWN_ERROR;
861 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700862 status_t status = setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800863 close(fd);
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700864 return mStatus = status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800865 } else {
John Grossman44a7e422012-06-21 17:29:24 -0700866 player_type playerType = MediaPlayerFactory::getPlayerType(this, url);
John Grossmanc795b642012-02-22 15:38:35 -0800867 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
868 if (p == NULL) {
869 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800870 }
871
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700872 return mStatus =
873 setDataSource_post(
874 p, p->setDataSource(httpService, url, headers));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800875 }
876}
877
878status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
879{
Marco Nelissen83b0fd92015-09-16 13:48:07 -0700880 ALOGV("setDataSource fd=%d (%s), offset=%lld, length=%lld",
881 fd, nameForFd(fd).c_str(), (long long) offset, (long long) length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800882 struct stat sb;
883 int ret = fstat(fd, &sb);
884 if (ret != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000885 ALOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800886 return UNKNOWN_ERROR;
887 }
888
Andy Hung833b4752016-04-04 17:15:48 -0700889 ALOGV("st_dev = %llu", static_cast<unsigned long long>(sb.st_dev));
Steve Block3856b092011-10-20 11:56:00 +0100890 ALOGV("st_mode = %u", sb.st_mode);
Mark Salyzyn77342f72014-06-18 16:31:32 -0700891 ALOGV("st_uid = %lu", static_cast<unsigned long>(sb.st_uid));
892 ALOGV("st_gid = %lu", static_cast<unsigned long>(sb.st_gid));
Andy Hung833b4752016-04-04 17:15:48 -0700893 ALOGV("st_size = %llu", static_cast<unsigned long long>(sb.st_size));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800894
895 if (offset >= sb.st_size) {
Steve Block29357bc2012-01-06 19:20:56 +0000896 ALOGE("offset error");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800897 return UNKNOWN_ERROR;
898 }
899 if (offset + length > sb.st_size) {
900 length = sb.st_size - offset;
Andy Hung833b4752016-04-04 17:15:48 -0700901 ALOGV("calculated length = %lld", (long long)length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800902 }
903
John Grossman44a7e422012-06-21 17:29:24 -0700904 player_type playerType = MediaPlayerFactory::getPlayerType(this,
905 fd,
906 offset,
907 length);
John Grossmanc795b642012-02-22 15:38:35 -0800908 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
909 if (p == NULL) {
910 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800911 }
912
913 // now set data source
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700914 return mStatus = setDataSource_post(p, p->setDataSource(fd, offset, length));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800915}
916
Andreas Hubere2b10282010-11-23 11:41:34 -0800917status_t MediaPlayerService::Client::setDataSource(
918 const sp<IStreamSource> &source) {
919 // create the right type of player
John Grossman44a7e422012-06-21 17:29:24 -0700920 player_type playerType = MediaPlayerFactory::getPlayerType(this, source);
John Grossmanc795b642012-02-22 15:38:35 -0800921 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
Andreas Hubere2b10282010-11-23 11:41:34 -0800922 if (p == NULL) {
923 return NO_INIT;
924 }
925
Andreas Hubere2b10282010-11-23 11:41:34 -0800926 // now set data source
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700927 return mStatus = setDataSource_post(p, p->setDataSource(source));
Andreas Hubere2b10282010-11-23 11:41:34 -0800928}
929
Chris Watkins99f31602015-03-20 13:06:33 -0700930status_t MediaPlayerService::Client::setDataSource(
931 const sp<IDataSource> &source) {
Dongwon Kangd91dc5a2017-10-10 00:07:09 -0700932 sp<DataSource> dataSource = CreateDataSourceFromIDataSource(source);
Chris Watkins99f31602015-03-20 13:06:33 -0700933 player_type playerType = MediaPlayerFactory::getPlayerType(this, dataSource);
934 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
935 if (p == NULL) {
936 return NO_INIT;
937 }
938 // now set data source
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700939 return mStatus = setDataSource_post(p, p->setDataSource(dataSource));
Chris Watkins99f31602015-03-20 13:06:33 -0700940}
941
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700942void MediaPlayerService::Client::disconnectNativeWindow_l() {
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700943 if (mConnectedWindow != NULL) {
Chong Zhang181fd9b2017-02-16 15:53:03 -0800944 status_t err = nativeWindowDisconnect(
945 mConnectedWindow.get(), "disconnectNativeWindow");
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700946
947 if (err != OK) {
Chong Zhang181fd9b2017-02-16 15:53:03 -0800948 ALOGW("nativeWindowDisconnect returned an error: %s (%d)",
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700949 strerror(-err), err);
950 }
951 }
952 mConnectedWindow.clear();
953}
954
Glenn Kasten11731182011-02-08 17:26:17 -0800955status_t MediaPlayerService::Client::setVideoSurfaceTexture(
Andy McFadden484566c2012-12-18 09:46:54 -0800956 const sp<IGraphicBufferProducer>& bufferProducer)
Glenn Kasten11731182011-02-08 17:26:17 -0800957{
Andy McFadden484566c2012-12-18 09:46:54 -0800958 ALOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, bufferProducer.get());
Glenn Kasten11731182011-02-08 17:26:17 -0800959 sp<MediaPlayerBase> p = getPlayer();
960 if (p == 0) return UNKNOWN_ERROR;
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700961
Marco Nelissenf8880202014-11-14 07:58:25 -0800962 sp<IBinder> binder(IInterface::asBinder(bufferProducer));
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700963 if (mConnectedWindowBinder == binder) {
964 return OK;
965 }
966
967 sp<ANativeWindow> anw;
Andy McFadden484566c2012-12-18 09:46:54 -0800968 if (bufferProducer != NULL) {
Marco Nelissenee08f7e2013-09-16 13:30:01 -0700969 anw = new Surface(bufferProducer, true /* controlledByApp */);
Chong Zhang181fd9b2017-02-16 15:53:03 -0800970 status_t err = nativeWindowConnect(anw.get(), "setVideoSurfaceTexture");
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700971
972 if (err != OK) {
Steve Block29357bc2012-01-06 19:20:56 +0000973 ALOGE("setVideoSurfaceTexture failed: %d", err);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700974 // Note that we must do the reset before disconnecting from the ANW.
975 // Otherwise queue/dequeue calls could be made on the disconnected
976 // ANW, which may result in errors.
977 reset();
978
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700979 Mutex::Autolock lock(mLock);
980 disconnectNativeWindow_l();
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700981
982 return err;
983 }
984 }
985
Andy McFadden484566c2012-12-18 09:46:54 -0800986 // Note that we must set the player's new GraphicBufferProducer before
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700987 // disconnecting the old one. Otherwise queue/dequeue calls could be made
988 // on the disconnected ANW, which may result in errors.
Andy McFadden484566c2012-12-18 09:46:54 -0800989 status_t err = p->setVideoSurfaceTexture(bufferProducer);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700990
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700991 mLock.lock();
992 disconnectNativeWindow_l();
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700993
994 if (err == OK) {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700995 mConnectedWindow = anw;
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700996 mConnectedWindowBinder = binder;
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700997 mLock.unlock();
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700998 } else {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700999 mLock.unlock();
1000 status_t err = nativeWindowDisconnect(
1001 anw.get(), "disconnectNativeWindow");
1002
1003 if (err != OK) {
1004 ALOGW("nativeWindowDisconnect returned an error: %s (%d)",
1005 strerror(-err), err);
1006 }
Jamie Gennis7dae00b2011-10-26 18:36:31 -07001007 }
1008
1009 return err;
Glenn Kasten11731182011-02-08 17:26:17 -08001010}
1011
Nicolas Catania1d187f12009-05-12 23:25:55 -07001012status_t MediaPlayerService::Client::invoke(const Parcel& request,
1013 Parcel *reply)
1014{
1015 sp<MediaPlayerBase> p = getPlayer();
1016 if (p == NULL) return UNKNOWN_ERROR;
1017 return p->invoke(request, reply);
1018}
1019
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001020// This call doesn't need to access the native player.
1021status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
1022{
1023 status_t status;
nikoa64c8c72009-07-20 15:07:26 -07001024 media::Metadata::Filter allow, drop;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001025
Nicolas Catania48290382009-07-10 13:53:06 -07001026 if (unmarshallFilter(filter, &allow, &status) &&
1027 unmarshallFilter(filter, &drop, &status)) {
1028 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001029
1030 mMetadataAllow = allow;
1031 mMetadataDrop = drop;
1032 }
1033 return status;
1034}
1035
Nicolas Catania48290382009-07-10 13:53:06 -07001036status_t MediaPlayerService::Client::getMetadata(
Mark Salyzyn77342f72014-06-18 16:31:32 -07001037 bool update_only, bool /*apply_filter*/, Parcel *reply)
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001038{
nikoa64c8c72009-07-20 15:07:26 -07001039 sp<MediaPlayerBase> player = getPlayer();
1040 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania48290382009-07-10 13:53:06 -07001041
nikod608a812009-07-16 16:39:53 -07001042 status_t status;
1043 // Placeholder for the return code, updated by the caller.
1044 reply->writeInt32(-1);
1045
nikoa64c8c72009-07-20 15:07:26 -07001046 media::Metadata::Filter ids;
Nicolas Catania48290382009-07-10 13:53:06 -07001047
1048 // We don't block notifications while we fetch the data. We clear
1049 // mMetadataUpdated first so we don't lose notifications happening
1050 // during the rest of this call.
1051 {
1052 Mutex::Autolock lock(mLock);
1053 if (update_only) {
nikod608a812009-07-16 16:39:53 -07001054 ids = mMetadataUpdated;
Nicolas Catania48290382009-07-10 13:53:06 -07001055 }
1056 mMetadataUpdated.clear();
1057 }
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001058
nikoa64c8c72009-07-20 15:07:26 -07001059 media::Metadata metadata(reply);
Nicolas Catania48290382009-07-10 13:53:06 -07001060
nikoa64c8c72009-07-20 15:07:26 -07001061 metadata.appendHeader();
1062 status = player->getMetadata(ids, reply);
nikod608a812009-07-16 16:39:53 -07001063
1064 if (status != OK) {
nikoa64c8c72009-07-20 15:07:26 -07001065 metadata.resetParcel();
Steve Block29357bc2012-01-06 19:20:56 +00001066 ALOGE("getMetadata failed %d", status);
nikod608a812009-07-16 16:39:53 -07001067 return status;
1068 }
1069
1070 // FIXME: Implement filtering on the result. Not critical since
1071 // filtering takes place on the update notifications already. This
1072 // would be when all the metadata are fetch and a filter is set.
1073
nikod608a812009-07-16 16:39:53 -07001074 // Everything is fine, update the metadata length.
nikoa64c8c72009-07-20 15:07:26 -07001075 metadata.updateLength();
nikod608a812009-07-16 16:39:53 -07001076 return OK;
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001077}
1078
Wei Jiad399e7e2016-10-26 15:49:11 -07001079status_t MediaPlayerService::Client::setBufferingSettings(
1080 const BufferingSettings& buffering)
1081{
Wei Jiadc6f3402017-01-09 15:04:18 -08001082 ALOGV("[%d] setBufferingSettings{%s}",
1083 mConnId, buffering.toString().string());
Wei Jiad399e7e2016-10-26 15:49:11 -07001084 sp<MediaPlayerBase> p = getPlayer();
1085 if (p == 0) return UNKNOWN_ERROR;
1086 return p->setBufferingSettings(buffering);
1087}
1088
Wei Jia9bb38032017-03-23 18:00:38 -07001089status_t MediaPlayerService::Client::getBufferingSettings(
Wei Jiad399e7e2016-10-26 15:49:11 -07001090 BufferingSettings* buffering /* nonnull */)
1091{
1092 sp<MediaPlayerBase> p = getPlayer();
1093 // TODO: create mPlayer on demand.
1094 if (p == 0) return UNKNOWN_ERROR;
Wei Jia9bb38032017-03-23 18:00:38 -07001095 status_t ret = p->getBufferingSettings(buffering);
Wei Jiad399e7e2016-10-26 15:49:11 -07001096 if (ret == NO_ERROR) {
Wei Jia9bb38032017-03-23 18:00:38 -07001097 ALOGV("[%d] getBufferingSettings{%s}",
Wei Jiadc6f3402017-01-09 15:04:18 -08001098 mConnId, buffering->toString().string());
Wei Jiad399e7e2016-10-26 15:49:11 -07001099 } else {
Wei Jia9bb38032017-03-23 18:00:38 -07001100 ALOGE("[%d] getBufferingSettings returned %d", mConnId, ret);
Wei Jiad399e7e2016-10-26 15:49:11 -07001101 }
1102 return ret;
1103}
1104
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001105status_t MediaPlayerService::Client::prepareAsync()
1106{
Steve Block3856b092011-10-20 11:56:00 +01001107 ALOGV("[%d] prepareAsync", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001108 sp<MediaPlayerBase> p = getPlayer();
1109 if (p == 0) return UNKNOWN_ERROR;
1110 status_t ret = p->prepareAsync();
1111#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +00001112 ALOGD("start Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001113 if (ret == NO_ERROR) mAntagonizer->start();
1114#endif
1115 return ret;
1116}
1117
1118status_t MediaPlayerService::Client::start()
1119{
Steve Block3856b092011-10-20 11:56:00 +01001120 ALOGV("[%d] start", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001121 sp<MediaPlayerBase> p = getPlayer();
1122 if (p == 0) return UNKNOWN_ERROR;
1123 p->setLooping(mLoop);
1124 return p->start();
1125}
1126
1127status_t MediaPlayerService::Client::stop()
1128{
Steve Block3856b092011-10-20 11:56:00 +01001129 ALOGV("[%d] stop", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001130 sp<MediaPlayerBase> p = getPlayer();
1131 if (p == 0) return UNKNOWN_ERROR;
1132 return p->stop();
1133}
1134
1135status_t MediaPlayerService::Client::pause()
1136{
Steve Block3856b092011-10-20 11:56:00 +01001137 ALOGV("[%d] pause", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001138 sp<MediaPlayerBase> p = getPlayer();
1139 if (p == 0) return UNKNOWN_ERROR;
1140 return p->pause();
1141}
1142
1143status_t MediaPlayerService::Client::isPlaying(bool* state)
1144{
1145 *state = false;
1146 sp<MediaPlayerBase> p = getPlayer();
1147 if (p == 0) return UNKNOWN_ERROR;
1148 *state = p->isPlaying();
Steve Block3856b092011-10-20 11:56:00 +01001149 ALOGV("[%d] isPlaying: %d", mConnId, *state);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001150 return NO_ERROR;
1151}
1152
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001153status_t MediaPlayerService::Client::setPlaybackSettings(const AudioPlaybackRate& rate)
Wei Jia98160162015-02-04 17:01:11 -08001154{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001155 ALOGV("[%d] setPlaybackSettings(%f, %f, %d, %d)",
1156 mConnId, rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Wei Jia98160162015-02-04 17:01:11 -08001157 sp<MediaPlayerBase> p = getPlayer();
1158 if (p == 0) return UNKNOWN_ERROR;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001159 return p->setPlaybackSettings(rate);
1160}
1161
1162status_t MediaPlayerService::Client::getPlaybackSettings(AudioPlaybackRate* rate /* nonnull */)
1163{
1164 sp<MediaPlayerBase> p = getPlayer();
1165 if (p == 0) return UNKNOWN_ERROR;
1166 status_t ret = p->getPlaybackSettings(rate);
1167 if (ret == NO_ERROR) {
1168 ALOGV("[%d] getPlaybackSettings(%f, %f, %d, %d)",
1169 mConnId, rate->mSpeed, rate->mPitch, rate->mFallbackMode, rate->mStretchMode);
1170 } else {
1171 ALOGV("[%d] getPlaybackSettings returned %d", mConnId, ret);
1172 }
1173 return ret;
1174}
1175
1176status_t MediaPlayerService::Client::setSyncSettings(
1177 const AVSyncSettings& sync, float videoFpsHint)
1178{
1179 ALOGV("[%d] setSyncSettings(%u, %u, %f, %f)",
1180 mConnId, sync.mSource, sync.mAudioAdjustMode, sync.mTolerance, videoFpsHint);
1181 sp<MediaPlayerBase> p = getPlayer();
1182 if (p == 0) return UNKNOWN_ERROR;
1183 return p->setSyncSettings(sync, videoFpsHint);
1184}
1185
1186status_t MediaPlayerService::Client::getSyncSettings(
1187 AVSyncSettings* sync /* nonnull */, float* videoFps /* nonnull */)
1188{
1189 sp<MediaPlayerBase> p = getPlayer();
1190 if (p == 0) return UNKNOWN_ERROR;
1191 status_t ret = p->getSyncSettings(sync, videoFps);
1192 if (ret == NO_ERROR) {
1193 ALOGV("[%d] getSyncSettings(%u, %u, %f, %f)",
1194 mConnId, sync->mSource, sync->mAudioAdjustMode, sync->mTolerance, *videoFps);
1195 } else {
1196 ALOGV("[%d] getSyncSettings returned %d", mConnId, ret);
1197 }
1198 return ret;
Wei Jia98160162015-02-04 17:01:11 -08001199}
1200
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001201status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
1202{
Steve Block3856b092011-10-20 11:56:00 +01001203 ALOGV("getCurrentPosition");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001204 sp<MediaPlayerBase> p = getPlayer();
1205 if (p == 0) return UNKNOWN_ERROR;
1206 status_t ret = p->getCurrentPosition(msec);
1207 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001208 ALOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001209 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001210 ALOGE("getCurrentPosition returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001211 }
1212 return ret;
1213}
1214
1215status_t MediaPlayerService::Client::getDuration(int *msec)
1216{
Steve Block3856b092011-10-20 11:56:00 +01001217 ALOGV("getDuration");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001218 sp<MediaPlayerBase> p = getPlayer();
1219 if (p == 0) return UNKNOWN_ERROR;
1220 status_t ret = p->getDuration(msec);
1221 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001222 ALOGV("[%d] getDuration = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001223 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001224 ALOGE("getDuration returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001225 }
1226 return ret;
1227}
1228
Marco Nelissen6b74d672012-02-28 16:07:44 -08001229status_t MediaPlayerService::Client::setNextPlayer(const sp<IMediaPlayer>& player) {
1230 ALOGV("setNextPlayer");
1231 Mutex::Autolock l(mLock);
1232 sp<Client> c = static_cast<Client*>(player.get());
Wei Jia28284122016-08-30 13:49:06 -07001233 if (c != NULL && !mService->hasClient(c)) {
Robert Shihee0a0e32016-08-16 16:50:54 -07001234 return BAD_VALUE;
1235 }
1236
Marco Nelissen6b74d672012-02-28 16:07:44 -08001237 mNextClient = c;
John Grossman5f7e55e2012-08-24 14:47:25 -07001238
1239 if (c != NULL) {
1240 if (mAudioOutput != NULL) {
1241 mAudioOutput->setNextOutput(c->mAudioOutput);
1242 } else if ((mPlayer != NULL) && !mPlayer->hardwareOutput()) {
1243 ALOGE("no current audio output");
1244 }
1245
1246 if ((mPlayer != NULL) && (mNextClient->getPlayer() != NULL)) {
1247 mPlayer->setNextPlayer(mNextClient->getPlayer());
1248 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001249 }
John Grossman5f7e55e2012-08-24 14:47:25 -07001250
Marco Nelissen6b74d672012-02-28 16:07:44 -08001251 return OK;
1252}
1253
Andy Hung9fc8b5c2017-01-24 13:36:48 -08001254VolumeShaper::Status MediaPlayerService::Client::applyVolumeShaper(
1255 const sp<VolumeShaper::Configuration>& configuration,
1256 const sp<VolumeShaper::Operation>& operation) {
1257 // for hardware output, call player instead
1258 ALOGV("Client::applyVolumeShaper(%p)", this);
1259 sp<MediaPlayerBase> p = getPlayer();
1260 {
1261 Mutex::Autolock l(mLock);
1262 if (p != 0 && p->hardwareOutput()) {
1263 // TODO: investigate internal implementation
1264 return VolumeShaper::Status(INVALID_OPERATION);
1265 }
1266 if (mAudioOutput.get() != nullptr) {
1267 return mAudioOutput->applyVolumeShaper(configuration, operation);
1268 }
1269 }
1270 return VolumeShaper::Status(INVALID_OPERATION);
1271}
1272
1273sp<VolumeShaper::State> MediaPlayerService::Client::getVolumeShaperState(int id) {
1274 // for hardware output, call player instead
1275 ALOGV("Client::getVolumeShaperState(%p)", this);
1276 sp<MediaPlayerBase> p = getPlayer();
1277 {
1278 Mutex::Autolock l(mLock);
1279 if (p != 0 && p->hardwareOutput()) {
1280 // TODO: investigate internal implementation.
1281 return nullptr;
1282 }
1283 if (mAudioOutput.get() != nullptr) {
1284 return mAudioOutput->getVolumeShaperState(id);
1285 }
1286 }
1287 return nullptr;
1288}
1289
Wei Jiac5de0912016-11-18 10:22:14 -08001290status_t MediaPlayerService::Client::seekTo(int msec, MediaPlayerSeekMode mode)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001291{
Wei Jiac5de0912016-11-18 10:22:14 -08001292 ALOGV("[%d] seekTo(%d, %d)", mConnId, msec, mode);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001293 sp<MediaPlayerBase> p = getPlayer();
1294 if (p == 0) return UNKNOWN_ERROR;
Wei Jiac5de0912016-11-18 10:22:14 -08001295 return p->seekTo(msec, mode);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001296}
1297
1298status_t MediaPlayerService::Client::reset()
1299{
Steve Block3856b092011-10-20 11:56:00 +01001300 ALOGV("[%d] reset", mConnId);
John Grossmanc795b642012-02-22 15:38:35 -08001301 mRetransmitEndpointValid = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001302 sp<MediaPlayerBase> p = getPlayer();
1303 if (p == 0) return UNKNOWN_ERROR;
1304 return p->reset();
1305}
1306
Wei Jia52c28512017-09-13 18:17:51 -07001307status_t MediaPlayerService::Client::notifyAt(int64_t mediaTimeUs)
1308{
1309 ALOGV("[%d] notifyAt(%lld)", mConnId, (long long)mediaTimeUs);
1310 sp<MediaPlayerBase> p = getPlayer();
1311 if (p == 0) return UNKNOWN_ERROR;
1312 return p->notifyAt(mediaTimeUs);
1313}
1314
Glenn Kastenfff6d712012-01-12 16:38:12 -08001315status_t MediaPlayerService::Client::setAudioStreamType(audio_stream_type_t type)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001316{
Steve Block3856b092011-10-20 11:56:00 +01001317 ALOGV("[%d] setAudioStreamType(%d)", mConnId, type);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001318 // TODO: for hardware output, call player instead
1319 Mutex::Autolock l(mLock);
1320 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1321 return NO_ERROR;
1322}
1323
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001324status_t MediaPlayerService::Client::setAudioAttributes_l(const Parcel &parcel)
1325{
1326 if (mAudioAttributes != NULL) { free(mAudioAttributes); }
1327 mAudioAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001328 if (mAudioAttributes == NULL) {
1329 return NO_MEMORY;
1330 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001331 unmarshallAudioAttributes(parcel, mAudioAttributes);
1332
1333 ALOGV("setAudioAttributes_l() usage=%d content=%d flags=0x%x tags=%s",
1334 mAudioAttributes->usage, mAudioAttributes->content_type, mAudioAttributes->flags,
1335 mAudioAttributes->tags);
1336
1337 if (mAudioOutput != 0) {
1338 mAudioOutput->setAudioAttributes(mAudioAttributes);
1339 }
1340 return NO_ERROR;
1341}
1342
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001343status_t MediaPlayerService::Client::setLooping(int loop)
1344{
Steve Block3856b092011-10-20 11:56:00 +01001345 ALOGV("[%d] setLooping(%d)", mConnId, loop);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001346 mLoop = loop;
1347 sp<MediaPlayerBase> p = getPlayer();
1348 if (p != 0) return p->setLooping(loop);
1349 return NO_ERROR;
1350}
1351
1352status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1353{
Steve Block3856b092011-10-20 11:56:00 +01001354 ALOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
John Grossman761defc2012-02-09 15:09:05 -08001355
1356 // for hardware output, call player instead
1357 sp<MediaPlayerBase> p = getPlayer();
1358 {
1359 Mutex::Autolock l(mLock);
1360 if (p != 0 && p->hardwareOutput()) {
1361 MediaPlayerHWInterface* hwp =
1362 reinterpret_cast<MediaPlayerHWInterface*>(p.get());
1363 return hwp->setVolume(leftVolume, rightVolume);
1364 } else {
1365 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1366 return NO_ERROR;
1367 }
1368 }
1369
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001370 return NO_ERROR;
1371}
1372
Eric Laurent2beeb502010-07-16 07:43:46 -07001373status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1374{
Steve Block3856b092011-10-20 11:56:00 +01001375 ALOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
Eric Laurent2beeb502010-07-16 07:43:46 -07001376 Mutex::Autolock l(mLock);
1377 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1378 return NO_ERROR;
1379}
1380
1381status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1382{
Steve Block3856b092011-10-20 11:56:00 +01001383 ALOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
Eric Laurent2beeb502010-07-16 07:43:46 -07001384 Mutex::Autolock l(mLock);
1385 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1386 return NO_ERROR;
1387}
Nicolas Catania48290382009-07-10 13:53:06 -07001388
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001389status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
Steve Block3856b092011-10-20 11:56:00 +01001390 ALOGV("[%d] setParameter(%d)", mConnId, key);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001391 switch (key) {
1392 case KEY_PARAMETER_AUDIO_ATTRIBUTES:
1393 {
1394 Mutex::Autolock l(mLock);
1395 return setAudioAttributes_l(request);
1396 }
1397 default:
1398 sp<MediaPlayerBase> p = getPlayer();
1399 if (p == 0) { return UNKNOWN_ERROR; }
1400 return p->setParameter(key, request);
1401 }
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001402}
1403
1404status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
Steve Block3856b092011-10-20 11:56:00 +01001405 ALOGV("[%d] getParameter(%d)", mConnId, key);
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001406 sp<MediaPlayerBase> p = getPlayer();
1407 if (p == 0) return UNKNOWN_ERROR;
1408 return p->getParameter(key, reply);
1409}
1410
John Grossmanc795b642012-02-22 15:38:35 -08001411status_t MediaPlayerService::Client::setRetransmitEndpoint(
1412 const struct sockaddr_in* endpoint) {
1413
1414 if (NULL != endpoint) {
1415 uint32_t a = ntohl(endpoint->sin_addr.s_addr);
1416 uint16_t p = ntohs(endpoint->sin_port);
1417 ALOGV("[%d] setRetransmitEndpoint(%u.%u.%u.%u:%hu)", mConnId,
1418 (a >> 24), (a >> 16) & 0xFF, (a >> 8) & 0xFF, (a & 0xFF), p);
1419 } else {
1420 ALOGV("[%d] setRetransmitEndpoint = <none>", mConnId);
1421 }
1422
1423 sp<MediaPlayerBase> p = getPlayer();
1424
1425 // Right now, the only valid time to set a retransmit endpoint is before
1426 // player selection has been made (since the presence or absence of a
1427 // retransmit endpoint is going to determine which player is selected during
1428 // setDataSource).
1429 if (p != 0) return INVALID_OPERATION;
1430
1431 if (NULL != endpoint) {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001432 Mutex::Autolock lock(mLock);
John Grossmanc795b642012-02-22 15:38:35 -08001433 mRetransmitEndpoint = *endpoint;
1434 mRetransmitEndpointValid = true;
1435 } else {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001436 Mutex::Autolock lock(mLock);
John Grossmanc795b642012-02-22 15:38:35 -08001437 mRetransmitEndpointValid = false;
1438 }
1439
1440 return NO_ERROR;
1441}
1442
John Grossman44a7e422012-06-21 17:29:24 -07001443status_t MediaPlayerService::Client::getRetransmitEndpoint(
1444 struct sockaddr_in* endpoint)
1445{
1446 if (NULL == endpoint)
1447 return BAD_VALUE;
1448
1449 sp<MediaPlayerBase> p = getPlayer();
1450
1451 if (p != NULL)
1452 return p->getRetransmitEndpoint(endpoint);
1453
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001454 Mutex::Autolock lock(mLock);
John Grossman44a7e422012-06-21 17:29:24 -07001455 if (!mRetransmitEndpointValid)
1456 return NO_INIT;
1457
1458 *endpoint = mRetransmitEndpoint;
1459
1460 return NO_ERROR;
1461}
1462
Gloria Wangb483c472011-04-11 17:23:27 -07001463void MediaPlayerService::Client::notify(
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001464 int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001465{
James Dongb8a98252012-08-26 16:13:03 -07001466 sp<IMediaPlayerClient> c;
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001467 sp<Client> nextClient;
1468 status_t errStartNext = NO_ERROR;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001469 {
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001470 Mutex::Autolock l(mLock);
1471 c = mClient;
1472 if (msg == MEDIA_PLAYBACK_COMPLETE && mNextClient != NULL) {
1473 nextClient = mNextClient;
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001474
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001475 if (mAudioOutput != NULL)
1476 mAudioOutput->switchToNextOutput();
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001477
1478 errStartNext = nextClient->start();
1479 }
1480 }
1481
1482 if (nextClient != NULL) {
1483 sp<IMediaPlayerClient> nc;
1484 {
1485 Mutex::Autolock l(nextClient->mLock);
1486 nc = nextClient->mClient;
1487 }
1488 if (nc != NULL) {
1489 if (errStartNext == NO_ERROR) {
1490 nc->notify(MEDIA_INFO, MEDIA_INFO_STARTED_AS_NEXT, 0, obj);
1491 } else {
1492 nc->notify(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN , 0, obj);
1493 ALOGE("gapless:start playback for next track failed, err(%d)", errStartNext);
Wei Jia2afac0c2016-01-07 12:13:07 -08001494 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001495 }
1496 }
1497
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001498 if (MEDIA_INFO == msg &&
Nicolas Catania48290382009-07-10 13:53:06 -07001499 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikoa64c8c72009-07-20 15:07:26 -07001500 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania48290382009-07-10 13:53:06 -07001501
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001502 if(shouldDropMetadata(metadata_type)) {
Nicolas Catania48290382009-07-10 13:53:06 -07001503 return;
1504 }
1505
1506 // Update the list of metadata that have changed. getMetadata
1507 // also access mMetadataUpdated and clears it.
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001508 addNewMetadataUpdate(metadata_type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001509 }
James Dongb8a98252012-08-26 16:13:03 -07001510
1511 if (c != NULL) {
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001512 ALOGV("[%d] notify (%d, %d, %d)", mConnId, msg, ext1, ext2);
James Dongb8a98252012-08-26 16:13:03 -07001513 c->notify(msg, ext1, ext2, obj);
1514 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001515}
1516
Nicolas Catania48290382009-07-10 13:53:06 -07001517
nikoa64c8c72009-07-20 15:07:26 -07001518bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001519{
Nicolas Catania48290382009-07-10 13:53:06 -07001520 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001521
Nicolas Catania48290382009-07-10 13:53:06 -07001522 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001523 return true;
1524 }
1525
Nicolas Catania48290382009-07-10 13:53:06 -07001526 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001527 return false;
Nicolas Catania48290382009-07-10 13:53:06 -07001528 } else {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001529 return true;
1530 }
1531}
1532
Nicolas Catania48290382009-07-10 13:53:06 -07001533
nikoa64c8c72009-07-20 15:07:26 -07001534void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania48290382009-07-10 13:53:06 -07001535 Mutex::Autolock lock(mLock);
1536 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1537 mMetadataUpdated.add(metadata_type);
1538 }
1539}
1540
Hassan Shojaniacefac142017-02-06 21:02:02 -08001541// Modular DRM
1542status_t MediaPlayerService::Client::prepareDrm(const uint8_t uuid[16],
1543 const Vector<uint8_t>& drmSessionId)
1544{
1545 ALOGV("[%d] prepareDrm", mConnId);
1546 sp<MediaPlayerBase> p = getPlayer();
1547 if (p == 0) return UNKNOWN_ERROR;
1548
1549 status_t ret = p->prepareDrm(uuid, drmSessionId);
1550 ALOGV("prepareDrm ret: %d", ret);
1551
1552 return ret;
1553}
1554
1555status_t MediaPlayerService::Client::releaseDrm()
1556{
1557 ALOGV("[%d] releaseDrm", mConnId);
1558 sp<MediaPlayerBase> p = getPlayer();
1559 if (p == 0) return UNKNOWN_ERROR;
1560
1561 status_t ret = p->releaseDrm();
1562 ALOGV("releaseDrm ret: %d", ret);
1563
1564 return ret;
1565}
1566
jiabin156c6872017-10-06 09:47:15 -07001567status_t MediaPlayerService::Client::setOutputDevice(audio_port_handle_t deviceId)
1568{
1569 ALOGV("[%d] setOutputDevice", mConnId);
1570 {
1571 Mutex::Autolock l(mLock);
1572 if (mAudioOutput.get() != nullptr) {
1573 return mAudioOutput->setOutputDevice(deviceId);
1574 }
1575 }
1576 return NO_INIT;
1577}
1578
1579status_t MediaPlayerService::Client::getRoutedDeviceId(audio_port_handle_t* deviceId)
1580{
1581 ALOGV("[%d] getRoutedDeviceId", mConnId);
1582 {
1583 Mutex::Autolock l(mLock);
1584 if (mAudioOutput.get() != nullptr) {
1585 return mAudioOutput->getRoutedDeviceId(deviceId);
1586 }
1587 }
1588 return NO_INIT;
1589}
1590
1591status_t MediaPlayerService::Client::enableAudioDeviceCallback(bool enabled)
1592{
1593 ALOGV("[%d] enableAudioDeviceCallback, %d", mConnId, enabled);
1594 {
1595 Mutex::Autolock l(mLock);
1596 if (mAudioOutput.get() != nullptr) {
1597 return mAudioOutput->enableAudioDeviceCallback(enabled);
1598 }
1599 }
1600 return NO_INIT;
1601}
1602
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001603#if CALLBACK_ANTAGONIZER
1604const int Antagonizer::interval = 10000; // 10 msecs
1605
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001606Antagonizer::Antagonizer(const sp<MediaPlayerBase::Listener> &listener) :
1607 mExit(false), mActive(false), mListener(listener)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001608{
1609 createThread(callbackThread, this);
1610}
1611
1612void Antagonizer::kill()
1613{
1614 Mutex::Autolock _l(mLock);
1615 mActive = false;
1616 mExit = true;
1617 mCondition.wait(mLock);
1618}
1619
1620int Antagonizer::callbackThread(void* user)
1621{
Steve Blockb8a80522011-12-20 16:23:08 +00001622 ALOGD("Antagonizer started");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001623 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1624 while (!p->mExit) {
1625 if (p->mActive) {
Steve Block3856b092011-10-20 11:56:00 +01001626 ALOGV("send event");
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001627 p->mListener->notify(0, 0, 0, 0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001628 }
1629 usleep(interval);
1630 }
1631 Mutex::Autolock _l(p->mLock);
1632 p->mCondition.signal();
Steve Blockb8a80522011-12-20 16:23:08 +00001633 ALOGD("Antagonizer stopped");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001634 return 0;
1635}
1636#endif
1637
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001638#undef LOG_TAG
1639#define LOG_TAG "AudioSink"
Andy Hung1afd0982016-11-08 16:13:44 -08001640MediaPlayerService::AudioOutput::AudioOutput(audio_session_t sessionId, uid_t uid, int pid,
jiabin156c6872017-10-06 09:47:15 -07001641 const audio_attributes_t* attr, const sp<AudioSystem::AudioDeviceCallback>& deviceCallback)
Andreas Huber20111aa2009-07-14 16:56:47 -07001642 : mCallback(NULL),
Eric Laurenta514bdb2010-06-21 09:27:30 -07001643 mCallbackCookie(NULL),
Marco Nelissen6b74d672012-02-28 16:07:44 -08001644 mCallbackData(NULL),
Andy Hungd1c74342015-07-07 16:54:23 -07001645 mStreamType(AUDIO_STREAM_MUSIC),
Andy Hungd1c74342015-07-07 16:54:23 -07001646 mLeftVolume(1.0),
1647 mRightVolume(1.0),
1648 mPlaybackRate(AUDIO_PLAYBACK_RATE_DEFAULT),
1649 mSampleRateHz(0),
1650 mMsecsPerFrame(0),
1651 mFrameSize(0),
Eric Laurent1948eb32012-04-13 16:50:19 -07001652 mSessionId(sessionId),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001653 mUid(uid),
Marco Nelissend457c972014-02-11 08:47:07 -08001654 mPid(pid),
Andy Hungd1c74342015-07-07 16:54:23 -07001655 mSendLevel(0.0),
1656 mAuxEffectId(0),
Andy Hung4ef88d72017-02-21 19:47:53 -08001657 mFlags(AUDIO_OUTPUT_FLAG_NONE),
jiabin156c6872017-10-06 09:47:15 -07001658 mVolumeHandler(new media::VolumeHandler()),
1659 mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE),
jiabin161b64f2017-11-17 09:31:48 -08001660 mRoutedDeviceId(AUDIO_PORT_HANDLE_NONE),
jiabin156c6872017-10-06 09:47:15 -07001661 mDeviceCallbackEnabled(false),
1662 mDeviceCallback(deviceCallback)
Andy Hungd1c74342015-07-07 16:54:23 -07001663{
Steve Block3856b092011-10-20 11:56:00 +01001664 ALOGV("AudioOutput(%d)", sessionId);
Eric Laurent43562692015-07-15 16:49:07 -07001665 if (attr != NULL) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001666 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1667 if (mAttributes != NULL) {
1668 memcpy(mAttributes, attr, sizeof(audio_attributes_t));
François Gaffie58d4be52018-11-06 15:30:12 +01001669 mStreamType = AudioSystem::attributesToStreamType(*attr);
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001670 }
1671 } else {
1672 mAttributes = NULL;
Eric Laurent43562692015-07-15 16:49:07 -07001673 }
1674
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001675 setMinBufferCount();
1676}
1677
1678MediaPlayerService::AudioOutput::~AudioOutput()
1679{
1680 close();
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001681 free(mAttributes);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001682 delete mCallbackData;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001683}
1684
Andy Hungd1c74342015-07-07 16:54:23 -07001685//static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001686void MediaPlayerService::AudioOutput::setMinBufferCount()
1687{
1688 char value[PROPERTY_VALUE_MAX];
1689 if (property_get("ro.kernel.qemu", value, 0)) {
1690 mIsOnEmulator = true;
1691 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1692 }
1693}
1694
Andy Hungd1c74342015-07-07 16:54:23 -07001695// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001696bool MediaPlayerService::AudioOutput::isOnEmulator()
1697{
Andy Hungd1c74342015-07-07 16:54:23 -07001698 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001699 return mIsOnEmulator;
1700}
1701
Andy Hungd1c74342015-07-07 16:54:23 -07001702// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001703int MediaPlayerService::AudioOutput::getMinBufferCount()
1704{
Andy Hungd1c74342015-07-07 16:54:23 -07001705 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001706 return mMinBufferCount;
1707}
1708
1709ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1710{
Andy Hungd1c74342015-07-07 16:54:23 -07001711 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001712 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001713 return mTrack->frameCount() * mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001714}
1715
1716ssize_t MediaPlayerService::AudioOutput::frameCount() const
1717{
Andy Hungd1c74342015-07-07 16:54:23 -07001718 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001719 if (mTrack == 0) return NO_INIT;
1720 return mTrack->frameCount();
1721}
1722
1723ssize_t MediaPlayerService::AudioOutput::channelCount() const
1724{
Andy Hungd1c74342015-07-07 16:54:23 -07001725 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001726 if (mTrack == 0) return NO_INIT;
1727 return mTrack->channelCount();
1728}
1729
1730ssize_t MediaPlayerService::AudioOutput::frameSize() const
1731{
Andy Hungd1c74342015-07-07 16:54:23 -07001732 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001733 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001734 return mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001735}
1736
1737uint32_t MediaPlayerService::AudioOutput::latency () const
1738{
Andy Hungd1c74342015-07-07 16:54:23 -07001739 Mutex::Autolock lock(mLock);
Eric Laurentdb354e52012-03-05 17:27:11 -08001740 if (mTrack == 0) return 0;
1741 return mTrack->latency();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001742}
1743
1744float MediaPlayerService::AudioOutput::msecsPerFrame() const
1745{
Andy Hungd1c74342015-07-07 16:54:23 -07001746 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001747 return mMsecsPerFrame;
1748}
1749
Marco Nelissen4110c102012-03-29 09:31:28 -07001750status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position) const
Eric Laurent342e9cf2010-01-19 17:37:09 -08001751{
Andy Hungd1c74342015-07-07 16:54:23 -07001752 Mutex::Autolock lock(mLock);
Eric Laurent342e9cf2010-01-19 17:37:09 -08001753 if (mTrack == 0) return NO_INIT;
1754 return mTrack->getPosition(position);
1755}
1756
Lajos Molnar06ad1522014-08-28 07:27:44 -07001757status_t MediaPlayerService::AudioOutput::getTimestamp(AudioTimestamp &ts) const
1758{
Andy Hungd1c74342015-07-07 16:54:23 -07001759 Mutex::Autolock lock(mLock);
Lajos Molnar06ad1522014-08-28 07:27:44 -07001760 if (mTrack == 0) return NO_INIT;
1761 return mTrack->getTimestamp(ts);
1762}
1763
Wei Jiac4ac8172015-10-21 10:35:48 -07001764// TODO: Remove unnecessary calls to getPlayedOutDurationUs()
1765// as it acquires locks and may query the audio driver.
1766//
1767// Some calls could conceivably retrieve extrapolated data instead of
1768// accessing getTimestamp() or getPosition() every time a data buffer with
1769// a media time is received.
1770//
1771// Calculate duration of played samples if played at normal rate (i.e., 1.0).
1772int64_t MediaPlayerService::AudioOutput::getPlayedOutDurationUs(int64_t nowUs) const
1773{
1774 Mutex::Autolock lock(mLock);
1775 if (mTrack == 0 || mSampleRateHz == 0) {
Wei Jia213f4902015-10-22 08:55:25 -07001776 return 0;
Wei Jiac4ac8172015-10-21 10:35:48 -07001777 }
1778
1779 uint32_t numFramesPlayed;
Andy Hung5d313802016-10-10 15:09:39 -07001780 int64_t numFramesPlayedAtUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001781 AudioTimestamp ts;
Wei Jiac4ac8172015-10-21 10:35:48 -07001782
1783 status_t res = mTrack->getTimestamp(ts);
1784 if (res == OK) { // case 1: mixing audio tracks and offloaded tracks.
1785 numFramesPlayed = ts.mPosition;
Andy Hung5d313802016-10-10 15:09:39 -07001786 numFramesPlayedAtUs = ts.mTime.tv_sec * 1000000LL + ts.mTime.tv_nsec / 1000;
1787 //ALOGD("getTimestamp: OK %d %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001788 } else if (res == WOULD_BLOCK) { // case 2: transitory state on start of a new track
1789 numFramesPlayed = 0;
Andy Hung5d313802016-10-10 15:09:39 -07001790 numFramesPlayedAtUs = nowUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001791 //ALOGD("getTimestamp: WOULD_BLOCK %d %lld",
Andy Hung5d313802016-10-10 15:09:39 -07001792 // numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001793 } else { // case 3: transitory at new track or audio fast tracks.
1794 res = mTrack->getPosition(&numFramesPlayed);
1795 CHECK_EQ(res, (status_t)OK);
Andy Hung5d313802016-10-10 15:09:39 -07001796 numFramesPlayedAtUs = nowUs;
1797 numFramesPlayedAtUs += 1000LL * mTrack->latency() / 2; /* XXX */
1798 //ALOGD("getPosition: %u %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001799 }
1800
1801 // CHECK_EQ(numFramesPlayed & (1 << 31), 0); // can't be negative until 12.4 hrs, test
1802 // TODO: remove the (int32_t) casting below as it may overflow at 12.4 hours.
1803 int64_t durationUs = (int64_t)((int32_t)numFramesPlayed * 1000000LL / mSampleRateHz)
Andy Hung5d313802016-10-10 15:09:39 -07001804 + nowUs - numFramesPlayedAtUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001805 if (durationUs < 0) {
1806 // Occurs when numFramesPlayed position is very small and the following:
1807 // (1) In case 1, the time nowUs is computed before getTimestamp() is called and
Andy Hung5d313802016-10-10 15:09:39 -07001808 // numFramesPlayedAtUs is greater than nowUs by time more than numFramesPlayed.
Wei Jiac4ac8172015-10-21 10:35:48 -07001809 // (2) In case 3, using getPosition and adding mAudioSink->latency() to
Andy Hung5d313802016-10-10 15:09:39 -07001810 // numFramesPlayedAtUs, by a time amount greater than numFramesPlayed.
Wei Jiac4ac8172015-10-21 10:35:48 -07001811 //
1812 // Both of these are transitory conditions.
1813 ALOGV("getPlayedOutDurationUs: negative duration %lld set to zero", (long long)durationUs);
1814 durationUs = 0;
1815 }
1816 ALOGV("getPlayedOutDurationUs(%lld) nowUs(%lld) frames(%u) framesAt(%lld)",
Andy Hung5d313802016-10-10 15:09:39 -07001817 (long long)durationUs, (long long)nowUs,
1818 numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001819 return durationUs;
1820}
1821
Marco Nelissen4110c102012-03-29 09:31:28 -07001822status_t MediaPlayerService::AudioOutput::getFramesWritten(uint32_t *frameswritten) const
1823{
Andy Hungd1c74342015-07-07 16:54:23 -07001824 Mutex::Autolock lock(mLock);
Marco Nelissen4110c102012-03-29 09:31:28 -07001825 if (mTrack == 0) return NO_INIT;
Andy Hung2f6e73d2016-04-08 12:12:58 -07001826 ExtendedTimestamp ets;
1827 status_t status = mTrack->getTimestamp(&ets);
1828 if (status == OK || status == WOULD_BLOCK) {
1829 *frameswritten = (uint32_t)ets.mPosition[ExtendedTimestamp::LOCATION_CLIENT];
1830 }
1831 return status;
Marco Nelissen4110c102012-03-29 09:31:28 -07001832}
1833
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001834status_t MediaPlayerService::AudioOutput::setParameters(const String8& keyValuePairs)
1835{
Andy Hungd1c74342015-07-07 16:54:23 -07001836 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001837 if (mTrack == 0) return NO_INIT;
1838 return mTrack->setParameters(keyValuePairs);
1839}
1840
1841String8 MediaPlayerService::AudioOutput::getParameters(const String8& keys)
1842{
Andy Hungd1c74342015-07-07 16:54:23 -07001843 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001844 if (mTrack == 0) return String8::empty();
1845 return mTrack->getParameters(keys);
1846}
1847
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001848void MediaPlayerService::AudioOutput::setAudioAttributes(const audio_attributes_t * attributes) {
Andy Hungd1c74342015-07-07 16:54:23 -07001849 Mutex::Autolock lock(mLock);
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001850 if (attributes == NULL) {
1851 free(mAttributes);
1852 mAttributes = NULL;
1853 } else {
1854 if (mAttributes == NULL) {
1855 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1856 }
1857 memcpy(mAttributes, attributes, sizeof(audio_attributes_t));
François Gaffie58d4be52018-11-06 15:30:12 +01001858 mStreamType = AudioSystem::attributesToStreamType(*attributes);
Eric Laurent43562692015-07-15 16:49:07 -07001859 }
1860}
1861
1862void MediaPlayerService::AudioOutput::setAudioStreamType(audio_stream_type_t streamType)
1863{
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001864 Mutex::Autolock lock(mLock);
Eric Laurent43562692015-07-15 16:49:07 -07001865 // do not allow direct stream type modification if attributes have been set
1866 if (mAttributes == NULL) {
1867 mStreamType = streamType;
1868 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001869}
1870
Andy Hungd1c74342015-07-07 16:54:23 -07001871void MediaPlayerService::AudioOutput::deleteRecycledTrack_l()
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001872{
Andy Hungd1c74342015-07-07 16:54:23 -07001873 ALOGV("deleteRecycledTrack_l");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001874 if (mRecycledTrack != 0) {
1875
1876 if (mCallbackData != NULL) {
1877 mCallbackData->setOutput(NULL);
1878 mCallbackData->endTrackSwitch();
1879 }
1880
1881 if ((mRecycledTrack->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) {
Andy Hunge13f8a62016-03-30 14:20:42 -07001882 int32_t msec = 0;
1883 if (!mRecycledTrack->stopped()) { // check if active
1884 (void)mRecycledTrack->pendingDuration(&msec);
1885 }
1886 mRecycledTrack->stop(); // ensure full data drain
1887 ALOGD("deleting recycled track, waiting for data drain (%d msec)", msec);
1888 if (msec > 0) {
1889 static const int32_t WAIT_LIMIT_MS = 3000;
1890 if (msec > WAIT_LIMIT_MS) {
1891 msec = WAIT_LIMIT_MS;
1892 }
1893 usleep(msec * 1000LL);
1894 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001895 }
1896 // An offloaded track isn't flushed because the STREAM_END is reported
1897 // slightly prematurely to allow time for the gapless track switch
1898 // but this means that if we decide not to recycle the track there
1899 // could be a small amount of residual data still playing. We leave
1900 // AudioFlinger to drain the track.
1901
1902 mRecycledTrack.clear();
Andy Hungd1c74342015-07-07 16:54:23 -07001903 close_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001904 delete mCallbackData;
1905 mCallbackData = NULL;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001906 }
1907}
1908
Andy Hungd1c74342015-07-07 16:54:23 -07001909void MediaPlayerService::AudioOutput::close_l()
1910{
1911 mTrack.clear();
1912}
1913
Andreas Huber20111aa2009-07-14 16:56:47 -07001914status_t MediaPlayerService::AudioOutput::open(
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001915 uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
1916 audio_format_t format, int bufferCount,
Eric Laurent1948eb32012-04-13 16:50:19 -07001917 AudioCallback cb, void *cookie,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001918 audio_output_flags_t flags,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001919 const audio_offload_info_t *offloadInfo,
Andy Hung179652e2015-05-31 22:49:46 -07001920 bool doNotReconnect,
1921 uint32_t suggestedFrameCount)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001922{
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001923 ALOGV("open(%u, %d, 0x%x, 0x%x, %d, %d 0x%x)", sampleRate, channelCount, channelMask,
1924 format, bufferCount, mSessionId, flags);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001925
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001926 // offloading is only supported in callback mode for now.
1927 // offloadInfo must be present if offload flag is set
1928 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) &&
1929 ((cb == NULL) || (offloadInfo == NULL))) {
1930 return BAD_VALUE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001931 }
1932
Andy Hung179652e2015-05-31 22:49:46 -07001933 // compute frame count for the AudioTrack internal buffer
1934 size_t frameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001935 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1936 frameCount = 0; // AudioTrack will get frame count from AudioFlinger
1937 } else {
Andy Hung179652e2015-05-31 22:49:46 -07001938 // try to estimate the buffer processing fetch size from AudioFlinger.
1939 // framesPerBuffer is approximate and generally correct, except when it's not :-).
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001940 uint32_t afSampleRate;
1941 size_t afFrameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001942 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1943 return NO_INIT;
1944 }
1945 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1946 return NO_INIT;
1947 }
Ben Romberger259fb462018-08-07 17:58:53 -07001948 if (afSampleRate == 0) {
1949 return NO_INIT;
1950 }
Andy Hung179652e2015-05-31 22:49:46 -07001951 const size_t framesPerBuffer =
1952 (unsigned long long)sampleRate * afFrameCount / afSampleRate;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001953
Andy Hung179652e2015-05-31 22:49:46 -07001954 if (bufferCount == 0) {
Ben Romberger259fb462018-08-07 17:58:53 -07001955 if (framesPerBuffer == 0) {
1956 return NO_INIT;
1957 }
Andy Hung179652e2015-05-31 22:49:46 -07001958 // use suggestedFrameCount
1959 bufferCount = (suggestedFrameCount + framesPerBuffer - 1) / framesPerBuffer;
1960 }
1961 // Check argument bufferCount against the mininum buffer count
1962 if (bufferCount != 0 && bufferCount < mMinBufferCount) {
1963 ALOGV("bufferCount (%d) increased to %d", bufferCount, mMinBufferCount);
1964 bufferCount = mMinBufferCount;
1965 }
1966 // if frameCount is 0, then AudioTrack will get frame count from AudioFlinger
1967 // which will be the minimum size permitted.
1968 frameCount = bufferCount * framesPerBuffer;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001969 }
Andreas Huber20111aa2009-07-14 16:56:47 -07001970
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001971 if (channelMask == CHANNEL_MASK_USE_CHANNEL_ORDER) {
Glenn Kastenab334fd2012-03-14 12:56:06 -07001972 channelMask = audio_channel_out_mask_from_count(channelCount);
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001973 if (0 == channelMask) {
1974 ALOGE("open() error, can\'t derive mask for %d audio channels", channelCount);
1975 return NO_INIT;
1976 }
1977 }
Eric Laurent1948eb32012-04-13 16:50:19 -07001978
Andy Hungd1c74342015-07-07 16:54:23 -07001979 Mutex::Autolock lock(mLock);
Andy Hung179652e2015-05-31 22:49:46 -07001980 mCallback = cb;
1981 mCallbackCookie = cookie;
1982
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001983 // Check whether we can recycle the track
1984 bool reuse = false;
1985 bool bothOffloaded = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001986
Glenn Kasten2799d742013-05-30 14:33:29 -07001987 if (mRecycledTrack != 0) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001988 // check whether we are switching between two offloaded tracks
1989 bothOffloaded = (flags & mRecycledTrack->getFlags()
1990 & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0;
Marco Nelissen67295b52012-06-11 14:52:53 -07001991
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001992 // check if the existing track can be reused as-is, or if a new track needs to be created.
1993 reuse = true;
1994
Marco Nelissen67295b52012-06-11 14:52:53 -07001995 if ((mCallbackData == NULL && mCallback != NULL) ||
1996 (mCallbackData != NULL && mCallback == NULL)) {
1997 // recycled track uses callbacks but the caller wants to use writes, or vice versa
1998 ALOGV("can't chain callback and write");
1999 reuse = false;
2000 } else if ((mRecycledTrack->getSampleRate() != sampleRate) ||
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002001 (mRecycledTrack->channelCount() != (uint32_t)channelCount) ) {
2002 ALOGV("samplerate, channelcount differ: %u/%u Hz, %u/%d ch",
Marco Nelissen67295b52012-06-11 14:52:53 -07002003 mRecycledTrack->getSampleRate(), sampleRate,
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002004 mRecycledTrack->channelCount(), channelCount);
Marco Nelissen67295b52012-06-11 14:52:53 -07002005 reuse = false;
2006 } else if (flags != mFlags) {
2007 ALOGV("output flags differ %08x/%08x", flags, mFlags);
2008 reuse = false;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002009 } else if (mRecycledTrack->format() != format) {
2010 reuse = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07002011 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002012 } else {
2013 ALOGV("no track available to recycle");
2014 }
2015
2016 ALOGV_IF(bothOffloaded, "both tracks offloaded");
2017
2018 // If we can't recycle and both tracks are offloaded
2019 // we must close the previous output before opening a new one
2020 if (bothOffloaded && !reuse) {
2021 ALOGV("both offloaded and not recycling");
Andy Hungd1c74342015-07-07 16:54:23 -07002022 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002023 }
2024
2025 sp<AudioTrack> t;
2026 CallbackData *newcbd = NULL;
2027
2028 // We don't attempt to create a new track if we are recycling an
2029 // offloaded track. But, if we are recycling a non-offloaded or we
2030 // are switching where one is offloaded and one isn't then we create
2031 // the new track in advance so that we can read additional stream info
2032
2033 if (!(reuse && bothOffloaded)) {
2034 ALOGV("creating new AudioTrack");
2035
2036 if (mCallback != NULL) {
2037 newcbd = new CallbackData(this);
2038 t = new AudioTrack(
2039 mStreamType,
2040 sampleRate,
2041 format,
2042 channelMask,
2043 frameCount,
2044 flags,
2045 CallbackWrapper,
2046 newcbd,
2047 0, // notification frames
2048 mSessionId,
2049 AudioTrack::TRANSFER_CALLBACK,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002050 offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -08002051 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07002052 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07002053 mAttributes,
jiabin156c6872017-10-06 09:47:15 -07002054 doNotReconnect,
2055 1.0f, // default value for maxRequiredSpeed
2056 mSelectedDeviceId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002057 } else {
Andy Hungff874dc2016-04-11 16:49:09 -07002058 // TODO: Due to buffer memory concerns, we use a max target playback speed
2059 // based on mPlaybackRate at the time of open (instead of kMaxRequiredSpeed),
2060 // also clamping the target speed to 1.0 <= targetSpeed <= kMaxRequiredSpeed.
2061 const float targetSpeed =
2062 std::min(std::max(mPlaybackRate.mSpeed, 1.0f), kMaxRequiredSpeed);
2063 ALOGW_IF(targetSpeed != mPlaybackRate.mSpeed,
2064 "track target speed:%f clamped from playback speed:%f",
2065 targetSpeed, mPlaybackRate.mSpeed);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002066 t = new AudioTrack(
2067 mStreamType,
2068 sampleRate,
2069 format,
2070 channelMask,
2071 frameCount,
2072 flags,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002073 NULL, // callback
2074 NULL, // user data
2075 0, // notification frames
2076 mSessionId,
2077 AudioTrack::TRANSFER_DEFAULT,
2078 NULL, // offload info
Marco Nelissend457c972014-02-11 08:47:07 -08002079 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07002080 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07002081 mAttributes,
Andy Hungff874dc2016-04-11 16:49:09 -07002082 doNotReconnect,
jiabin156c6872017-10-06 09:47:15 -07002083 targetSpeed,
2084 mSelectedDeviceId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002085 }
2086
2087 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
2088 ALOGE("Unable to create audio track");
2089 delete newcbd;
Glenn Kasten3e98ecd2015-05-18 13:13:24 -07002090 // t goes out of scope, so reference count drops to zero
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002091 return NO_INIT;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07002092 } else {
2093 // successful AudioTrack initialization implies a legacy stream type was generated
2094 // from the audio attributes
2095 mStreamType = t->streamType();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002096 }
2097 }
2098
2099 if (reuse) {
2100 CHECK(mRecycledTrack != NULL);
2101
2102 if (!bothOffloaded) {
2103 if (mRecycledTrack->frameCount() != t->frameCount()) {
Andy Hung833b4752016-04-04 17:15:48 -07002104 ALOGV("framecount differs: %zu/%zu frames",
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002105 mRecycledTrack->frameCount(), t->frameCount());
2106 reuse = false;
2107 }
2108 }
2109
Marco Nelissen67295b52012-06-11 14:52:53 -07002110 if (reuse) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002111 ALOGV("chaining to next output and recycling track");
Andy Hungd1c74342015-07-07 16:54:23 -07002112 close_l();
Marco Nelissen67295b52012-06-11 14:52:53 -07002113 mTrack = mRecycledTrack;
Glenn Kasten2799d742013-05-30 14:33:29 -07002114 mRecycledTrack.clear();
Marco Nelissen67295b52012-06-11 14:52:53 -07002115 if (mCallbackData != NULL) {
2116 mCallbackData->setOutput(this);
2117 }
Marco Nelissen67295b52012-06-11 14:52:53 -07002118 delete newcbd;
Wei Jiae0bbac92016-07-18 16:04:53 -07002119 return updateTrack();
Marco Nelissen67295b52012-06-11 14:52:53 -07002120 }
Marco Nelissen67295b52012-06-11 14:52:53 -07002121 }
2122
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002123 // we're not going to reuse the track, unblock and flush it
2124 // this was done earlier if both tracks are offloaded
2125 if (!bothOffloaded) {
Andy Hungd1c74342015-07-07 16:54:23 -07002126 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002127 }
2128
2129 CHECK((t != NULL) && ((mCallback == NULL) || (newcbd != NULL)));
2130
Marco Nelissen67295b52012-06-11 14:52:53 -07002131 mCallbackData = newcbd;
Steve Block3856b092011-10-20 11:56:00 +01002132 ALOGV("setVolume");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002133 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07002134
Andy Hung39399b62017-04-21 15:07:45 -07002135 // Restore VolumeShapers for the MediaPlayer in case the track was recreated
2136 // due to an output sink error (e.g. offload to non-offload switch).
2137 mVolumeHandler->forall([&t](const VolumeShaper &shaper) -> VolumeShaper::Status {
2138 sp<VolumeShaper::Operation> operationToEnd =
2139 new VolumeShaper::Operation(shaper.mOperation);
2140 // TODO: Ideally we would restore to the exact xOffset position
2141 // as returned by getVolumeShaperState(), but we don't have that
2142 // information when restoring at the client unless we periodically poll
2143 // the server or create shared memory state.
2144 //
2145 // For now, we simply advance to the end of the VolumeShaper effect
2146 // if it has been started.
2147 if (shaper.isStarted()) {
Andy Hungf3702642017-05-05 17:33:32 -07002148 operationToEnd->setNormalizedTime(1.f);
Andy Hung39399b62017-04-21 15:07:45 -07002149 }
2150 return t->applyVolumeShaper(shaper.mConfiguration, operationToEnd);
Andy Hung4ef88d72017-02-21 19:47:53 -08002151 });
Andy Hung4ef88d72017-02-21 19:47:53 -08002152
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002153 mSampleRateHz = sampleRate;
Preetam Singh Ranawat2e17eef2015-08-12 12:11:46 -07002154 mFlags = flags;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002155 mMsecsPerFrame = 1E3f / (mPlaybackRate.mSpeed * sampleRate);
Andy Hungd1c74342015-07-07 16:54:23 -07002156 mFrameSize = t->frameSize();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002157 mTrack = t;
Eric Laurent2beeb502010-07-16 07:43:46 -07002158
Wei Jiae0bbac92016-07-18 16:04:53 -07002159 return updateTrack();
2160}
2161
2162status_t MediaPlayerService::AudioOutput::updateTrack() {
2163 if (mTrack == NULL) {
2164 return NO_ERROR;
2165 }
2166
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002167 status_t res = NO_ERROR;
Wei Jia0162d002015-06-09 11:59:33 -07002168 // Note some output devices may give us a direct track even though we don't specify it.
2169 // Example: Line application b/17459982.
Wei Jiae0bbac92016-07-18 16:04:53 -07002170 if ((mTrack->getFlags()
2171 & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) {
2172 res = mTrack->setPlaybackRate(mPlaybackRate);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002173 if (res == NO_ERROR) {
Wei Jiae0bbac92016-07-18 16:04:53 -07002174 mTrack->setAuxEffectSendLevel(mSendLevel);
2175 res = mTrack->attachAuxEffect(mAuxEffectId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002176 }
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002177 }
jiabin156c6872017-10-06 09:47:15 -07002178 mTrack->setOutputDevice(mSelectedDeviceId);
2179 if (mDeviceCallbackEnabled) {
2180 mTrack->addAudioDeviceCallback(mDeviceCallback.promote());
2181 }
Wei Jiae0bbac92016-07-18 16:04:53 -07002182 ALOGV("updateTrack() DONE status %d", res);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002183 return res;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002184}
2185
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002186status_t MediaPlayerService::AudioOutput::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002187{
Steve Block3856b092011-10-20 11:56:00 +01002188 ALOGV("start");
Andy Hungd1c74342015-07-07 16:54:23 -07002189 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08002190 if (mCallbackData != NULL) {
2191 mCallbackData->endTrackSwitch();
2192 }
Glenn Kasten2799d742013-05-30 14:33:29 -07002193 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002194 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07002195 mTrack->setAuxEffectSendLevel(mSendLevel);
Andy Hung39399b62017-04-21 15:07:45 -07002196 status_t status = mTrack->start();
2197 if (status == NO_ERROR) {
2198 mVolumeHandler->setStarted();
2199 }
2200 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002201 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002202 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002203}
2204
Marco Nelissen6b74d672012-02-28 16:07:44 -08002205void MediaPlayerService::AudioOutput::setNextOutput(const sp<AudioOutput>& nextOutput) {
Andy Hungd1c74342015-07-07 16:54:23 -07002206 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08002207 mNextOutput = nextOutput;
2208}
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08002209
Marco Nelissen6b74d672012-02-28 16:07:44 -08002210void MediaPlayerService::AudioOutput::switchToNextOutput() {
2211 ALOGV("switchToNextOutput");
Andy Hungd1c74342015-07-07 16:54:23 -07002212
2213 // Try to acquire the callback lock before moving track (without incurring deadlock).
2214 const unsigned kMaxSwitchTries = 100;
2215 Mutex::Autolock lock(mLock);
2216 for (unsigned tries = 0;;) {
2217 if (mTrack == 0) {
2218 return;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002219 }
Andy Hungd1c74342015-07-07 16:54:23 -07002220 if (mNextOutput != NULL && mNextOutput != this) {
2221 if (mCallbackData != NULL) {
2222 // two alternative approaches
2223#if 1
2224 CallbackData *callbackData = mCallbackData;
2225 mLock.unlock();
2226 // proper acquisition sequence
2227 callbackData->lock();
2228 mLock.lock();
2229 // Caution: it is unlikely that someone deleted our callback or changed our target
2230 if (callbackData != mCallbackData || mNextOutput == NULL || mNextOutput == this) {
2231 // fatal if we are starved out.
2232 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2233 "switchToNextOutput() cannot obtain correct lock sequence");
2234 callbackData->unlock();
2235 continue;
2236 }
2237 callbackData->mSwitching = true; // begin track switch
Wei Jiaadee56a2016-08-05 15:40:34 -07002238 callbackData->setOutput(NULL);
Andy Hungd1c74342015-07-07 16:54:23 -07002239#else
2240 // tryBeginTrackSwitch() returns false if the callback has the lock.
2241 if (!mCallbackData->tryBeginTrackSwitch()) {
2242 // fatal if we are starved out.
2243 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2244 "switchToNextOutput() cannot obtain callback lock");
2245 mLock.unlock();
2246 usleep(5 * 1000 /* usec */); // allow callback to use AudioOutput
2247 mLock.lock();
2248 continue;
2249 }
2250#endif
2251 }
2252
2253 Mutex::Autolock nextLock(mNextOutput->mLock);
2254
2255 // If the next output track is not NULL, then it has been
2256 // opened already for playback.
2257 // This is possible even without the next player being started,
2258 // for example, the next player could be prepared and seeked.
2259 //
2260 // Presuming it isn't advisable to force the track over.
2261 if (mNextOutput->mTrack == NULL) {
2262 ALOGD("Recycling track for gapless playback");
2263 delete mNextOutput->mCallbackData;
2264 mNextOutput->mCallbackData = mCallbackData;
2265 mNextOutput->mRecycledTrack = mTrack;
2266 mNextOutput->mSampleRateHz = mSampleRateHz;
2267 mNextOutput->mMsecsPerFrame = mMsecsPerFrame;
Andy Hungd1c74342015-07-07 16:54:23 -07002268 mNextOutput->mFlags = mFlags;
2269 mNextOutput->mFrameSize = mFrameSize;
2270 close_l();
2271 mCallbackData = NULL; // destruction handled by mNextOutput
2272 } else {
2273 ALOGW("Ignoring gapless playback because next player has already started");
2274 // remove track in case resource needed for future players.
2275 if (mCallbackData != NULL) {
2276 mCallbackData->endTrackSwitch(); // release lock for callbacks before close.
2277 }
2278 close_l();
2279 }
2280 }
2281 break;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002282 }
2283}
2284
Wei Jia7d3f4df2015-03-03 15:28:00 -08002285ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002286{
Andy Hungd1c74342015-07-07 16:54:23 -07002287 Mutex::Autolock lock(mLock);
Glenn Kastenadad3d72014-02-21 14:51:43 -08002288 LOG_ALWAYS_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
Andreas Huber20111aa2009-07-14 16:56:47 -07002289
Steve Block3856b092011-10-20 11:56:00 +01002290 //ALOGV("write(%p, %u)", buffer, size);
Glenn Kasten2799d742013-05-30 14:33:29 -07002291 if (mTrack != 0) {
Andy Hung2f6e73d2016-04-08 12:12:58 -07002292 return mTrack->write(buffer, size, blocking);
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07002293 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002294 return NO_INIT;
2295}
2296
2297void MediaPlayerService::AudioOutput::stop()
2298{
Steve Block3856b092011-10-20 11:56:00 +01002299 ALOGV("stop");
Andy Hungd1c74342015-07-07 16:54:23 -07002300 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002301 if (mTrack != 0) mTrack->stop();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002302}
2303
2304void MediaPlayerService::AudioOutput::flush()
2305{
Steve Block3856b092011-10-20 11:56:00 +01002306 ALOGV("flush");
Andy Hungd1c74342015-07-07 16:54:23 -07002307 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002308 if (mTrack != 0) mTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002309}
2310
2311void MediaPlayerService::AudioOutput::pause()
2312{
Steve Block3856b092011-10-20 11:56:00 +01002313 ALOGV("pause");
Andy Hungd1c74342015-07-07 16:54:23 -07002314 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002315 if (mTrack != 0) mTrack->pause();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002316}
2317
2318void MediaPlayerService::AudioOutput::close()
2319{
Steve Block3856b092011-10-20 11:56:00 +01002320 ALOGV("close");
Erik Wolsheimer7845a1f2015-10-30 12:07:52 -07002321 sp<AudioTrack> track;
2322 {
2323 Mutex::Autolock lock(mLock);
2324 track = mTrack;
2325 close_l(); // clears mTrack
2326 }
2327 // destruction of the track occurs outside of mutex.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002328}
2329
2330void MediaPlayerService::AudioOutput::setVolume(float left, float right)
2331{
Steve Block3856b092011-10-20 11:56:00 +01002332 ALOGV("setVolume(%f, %f)", left, right);
Andy Hungd1c74342015-07-07 16:54:23 -07002333 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002334 mLeftVolume = left;
2335 mRightVolume = right;
Glenn Kasten2799d742013-05-30 14:33:29 -07002336 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002337 mTrack->setVolume(left, right);
2338 }
2339}
2340
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002341status_t MediaPlayerService::AudioOutput::setPlaybackRate(const AudioPlaybackRate &rate)
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002342{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002343 ALOGV("setPlaybackRate(%f %f %d %d)",
2344 rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Andy Hungd1c74342015-07-07 16:54:23 -07002345 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002346 if (mTrack == 0) {
2347 // remember rate so that we can set it when the track is opened
2348 mPlaybackRate = rate;
2349 return OK;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002350 }
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002351 status_t res = mTrack->setPlaybackRate(rate);
2352 if (res != NO_ERROR) {
2353 return res;
2354 }
2355 // rate.mSpeed is always greater than 0 if setPlaybackRate succeeded
2356 CHECK_GT(rate.mSpeed, 0.f);
2357 mPlaybackRate = rate;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002358 if (mSampleRateHz != 0) {
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002359 mMsecsPerFrame = 1E3f / (rate.mSpeed * mSampleRateHz);
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002360 }
2361 return res;
2362}
2363
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002364status_t MediaPlayerService::AudioOutput::getPlaybackRate(AudioPlaybackRate *rate)
2365{
2366 ALOGV("setPlaybackRate");
Andy Hungd1c74342015-07-07 16:54:23 -07002367 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002368 if (mTrack == 0) {
2369 return NO_INIT;
2370 }
2371 *rate = mTrack->getPlaybackRate();
2372 return NO_ERROR;
2373}
2374
Eric Laurent2beeb502010-07-16 07:43:46 -07002375status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
2376{
Steve Block3856b092011-10-20 11:56:00 +01002377 ALOGV("setAuxEffectSendLevel(%f)", level);
Andy Hungd1c74342015-07-07 16:54:23 -07002378 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002379 mSendLevel = level;
Glenn Kasten2799d742013-05-30 14:33:29 -07002380 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002381 return mTrack->setAuxEffectSendLevel(level);
2382 }
2383 return NO_ERROR;
2384}
2385
2386status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
2387{
Steve Block3856b092011-10-20 11:56:00 +01002388 ALOGV("attachAuxEffect(%d)", effectId);
Andy Hungd1c74342015-07-07 16:54:23 -07002389 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002390 mAuxEffectId = effectId;
Glenn Kasten2799d742013-05-30 14:33:29 -07002391 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002392 return mTrack->attachAuxEffect(effectId);
2393 }
2394 return NO_ERROR;
2395}
2396
jiabin156c6872017-10-06 09:47:15 -07002397status_t MediaPlayerService::AudioOutput::setOutputDevice(audio_port_handle_t deviceId)
2398{
2399 ALOGV("setOutputDevice(%d)", deviceId);
2400 Mutex::Autolock lock(mLock);
2401 mSelectedDeviceId = deviceId;
2402 if (mTrack != 0) {
2403 return mTrack->setOutputDevice(deviceId);
2404 }
2405 return NO_ERROR;
2406}
2407
2408status_t MediaPlayerService::AudioOutput::getRoutedDeviceId(audio_port_handle_t* deviceId)
2409{
2410 ALOGV("getRoutedDeviceId");
2411 Mutex::Autolock lock(mLock);
2412 if (mTrack != 0) {
jiabin161b64f2017-11-17 09:31:48 -08002413 mRoutedDeviceId = mTrack->getRoutedDeviceId();
jiabin156c6872017-10-06 09:47:15 -07002414 }
jiabin161b64f2017-11-17 09:31:48 -08002415 *deviceId = mRoutedDeviceId;
2416 return NO_ERROR;
jiabin156c6872017-10-06 09:47:15 -07002417}
2418
2419status_t MediaPlayerService::AudioOutput::enableAudioDeviceCallback(bool enabled)
2420{
2421 ALOGV("enableAudioDeviceCallback, %d", enabled);
2422 Mutex::Autolock lock(mLock);
2423 mDeviceCallbackEnabled = enabled;
2424 if (mTrack != 0) {
2425 status_t status;
2426 if (enabled) {
2427 status = mTrack->addAudioDeviceCallback(mDeviceCallback.promote());
2428 } else {
2429 status = mTrack->removeAudioDeviceCallback(mDeviceCallback.promote());
2430 }
2431 return status;
2432 }
2433 return NO_ERROR;
2434}
2435
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002436VolumeShaper::Status MediaPlayerService::AudioOutput::applyVolumeShaper(
2437 const sp<VolumeShaper::Configuration>& configuration,
2438 const sp<VolumeShaper::Operation>& operation)
2439{
2440 Mutex::Autolock lock(mLock);
2441 ALOGV("AudioOutput::applyVolumeShaper");
Andy Hung4ef88d72017-02-21 19:47:53 -08002442
Andy Hung4ef88d72017-02-21 19:47:53 -08002443 mVolumeHandler->setIdIfNecessary(configuration);
Andy Hung39399b62017-04-21 15:07:45 -07002444
2445 VolumeShaper::Status status;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002446 if (mTrack != 0) {
Andy Hung39399b62017-04-21 15:07:45 -07002447 status = mTrack->applyVolumeShaper(configuration, operation);
2448 if (status >= 0) {
2449 (void)mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hungf3702642017-05-05 17:33:32 -07002450 if (mTrack->isPlaying()) { // match local AudioTrack to properly restore.
2451 mVolumeHandler->setStarted();
2452 }
Andy Hung39399b62017-04-21 15:07:45 -07002453 }
Andy Hung4ef88d72017-02-21 19:47:53 -08002454 } else {
Andy Hungc01eddb2017-07-21 16:42:41 -07002455 // VolumeShapers are not affected when a track moves between players for
2456 // gapless playback (setNextMediaPlayer).
2457 // We forward VolumeShaper operations that do not change configuration
2458 // to the new player so that unducking may occur as expected.
2459 // Unducking is an idempotent operation, same if applied back-to-back.
2460 if (configuration->getType() == VolumeShaper::Configuration::TYPE_ID
2461 && mNextOutput != nullptr) {
2462 ALOGV("applyVolumeShaper: Attempting to forward missed operation: %s %s",
2463 configuration->toString().c_str(), operation->toString().c_str());
2464 Mutex::Autolock nextLock(mNextOutput->mLock);
2465
2466 // recycled track should be forwarded from this AudioSink by switchToNextOutput
2467 sp<AudioTrack> track = mNextOutput->mRecycledTrack;
2468 if (track != nullptr) {
2469 ALOGD("Forward VolumeShaper operation to recycled track %p", track.get());
2470 (void)track->applyVolumeShaper(configuration, operation);
2471 } else {
2472 // There is a small chance that the unduck occurs after the next
2473 // player has already started, but before it is registered to receive
2474 // the unduck command.
2475 track = mNextOutput->mTrack;
2476 if (track != nullptr) {
2477 ALOGD("Forward VolumeShaper operation to track %p", track.get());
2478 (void)track->applyVolumeShaper(configuration, operation);
2479 }
2480 }
2481 }
Andy Hung39399b62017-04-21 15:07:45 -07002482 status = mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002483 }
Andy Hung39399b62017-04-21 15:07:45 -07002484 return status;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002485}
2486
2487sp<VolumeShaper::State> MediaPlayerService::AudioOutput::getVolumeShaperState(int id)
2488{
2489 Mutex::Autolock lock(mLock);
2490 if (mTrack != 0) {
2491 return mTrack->getVolumeShaperState(id);
Andy Hung4ef88d72017-02-21 19:47:53 -08002492 } else {
2493 return mVolumeHandler->getVolumeShaperState(id);
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002494 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002495}
2496
Andreas Huber20111aa2009-07-14 16:56:47 -07002497// static
2498void MediaPlayerService::AudioOutput::CallbackWrapper(
Glenn Kastend217a8c2011-06-01 15:20:35 -07002499 int event, void *cookie, void *info) {
Steve Block3856b092011-10-20 11:56:00 +01002500 //ALOGV("callbackwrapper");
Marco Nelissen6b74d672012-02-28 16:07:44 -08002501 CallbackData *data = (CallbackData*)cookie;
Andy Hungd1c74342015-07-07 16:54:23 -07002502 // lock to ensure we aren't caught in the middle of a track switch.
Marco Nelissen6b74d672012-02-28 16:07:44 -08002503 data->lock();
2504 AudioOutput *me = data->getOutput();
Andreas Huber20111aa2009-07-14 16:56:47 -07002505 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002506 if (me == NULL) {
2507 // no output set, likely because the track was scheduled to be reused
2508 // by another player, but the format turned out to be incompatible.
2509 data->unlock();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002510 if (buffer != NULL) {
2511 buffer->size = 0;
2512 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08002513 return;
2514 }
Andreas Huber20111aa2009-07-14 16:56:47 -07002515
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002516 switch(event) {
2517 case AudioTrack::EVENT_MORE_DATA: {
2518 size_t actualSize = (*me->mCallback)(
2519 me, buffer->raw, buffer->size, me->mCallbackCookie,
2520 CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002521
Andy Hung719b46b2015-05-31 22:18:25 -07002522 // Log when no data is returned from the callback.
2523 // (1) We may have no data (especially with network streaming sources).
2524 // (2) We may have reached the EOS and the audio track is not stopped yet.
2525 // Note that AwesomePlayer/AudioPlayer will only return zero size when it reaches the EOS.
2526 // NuPlayerRenderer will return zero when it doesn't have data (it doesn't block to fill).
2527 //
2528 // This is a benign busy-wait, with the next data request generated 10 ms or more later;
2529 // nevertheless for power reasons, we don't want to see too many of these.
Andreas Huber2e8ffaf2010-02-18 16:45:13 -08002530
Andy Hung719b46b2015-05-31 22:18:25 -07002531 ALOGV_IF(actualSize == 0 && buffer->size > 0, "callbackwrapper: empty buffer returned");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002532
2533 buffer->size = actualSize;
2534 } break;
2535
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002536 case AudioTrack::EVENT_STREAM_END:
Andy Hung719b46b2015-05-31 22:18:25 -07002537 // currently only occurs for offloaded callbacks
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002538 ALOGV("callbackwrapper: deliver EVENT_STREAM_END");
2539 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2540 me->mCallbackCookie, CB_EVENT_STREAM_END);
2541 break;
2542
2543 case AudioTrack::EVENT_NEW_IAUDIOTRACK :
2544 ALOGV("callbackwrapper: deliver EVENT_TEAR_DOWN");
2545 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2546 me->mCallbackCookie, CB_EVENT_TEAR_DOWN);
2547 break;
2548
Glenn Kasten421743b2015-06-01 08:18:08 -07002549 case AudioTrack::EVENT_UNDERRUN:
Andy Hung719b46b2015-05-31 22:18:25 -07002550 // This occurs when there is no data available, typically
Glenn Kasten421743b2015-06-01 08:18:08 -07002551 // when there is a failure to supply data to the AudioTrack. It can also
2552 // occur in non-offloaded mode when the audio device comes out of standby.
2553 //
Andy Hung719b46b2015-05-31 22:18:25 -07002554 // If an AudioTrack underruns it outputs silence. Since this happens suddenly
2555 // it may sound like an audible pop or glitch.
2556 //
2557 // The underrun event is sent once per track underrun; the condition is reset
2558 // when more data is sent to the AudioTrack.
Eric Laurente93cc032016-05-05 10:15:10 -07002559 ALOGD("callbackwrapper: EVENT_UNDERRUN (discarded)");
Glenn Kasten421743b2015-06-01 08:18:08 -07002560 break;
2561
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002562 default:
2563 ALOGE("received unknown event type: %d inside CallbackWrapper !", event);
Andreas Huber51c1e0e2011-04-04 11:43:40 -07002564 }
2565
Marco Nelissen6b74d672012-02-28 16:07:44 -08002566 data->unlock();
Andreas Huber20111aa2009-07-14 16:56:47 -07002567}
2568
Glenn Kastend848eb42016-03-08 13:42:11 -08002569audio_session_t MediaPlayerService::AudioOutput::getSessionId() const
Eric Laurent8c563ed2010-10-07 18:23:03 -07002570{
Andy Hungd1c74342015-07-07 16:54:23 -07002571 Mutex::Autolock lock(mLock);
Eric Laurent8c563ed2010-10-07 18:23:03 -07002572 return mSessionId;
2573}
2574
Eric Laurent6f59db12013-07-26 17:16:50 -07002575uint32_t MediaPlayerService::AudioOutput::getSampleRate() const
2576{
Andy Hungd1c74342015-07-07 16:54:23 -07002577 Mutex::Autolock lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -07002578 if (mTrack == 0) return 0;
2579 return mTrack->getSampleRate();
2580}
2581
Andy Hungf2c87b32016-04-07 19:49:29 -07002582int64_t MediaPlayerService::AudioOutput::getBufferDurationInUs() const
2583{
2584 Mutex::Autolock lock(mLock);
2585 if (mTrack == 0) {
2586 return 0;
2587 }
2588 int64_t duration;
2589 if (mTrack->getBufferDurationInUs(&duration) != OK) {
2590 return 0;
2591 }
2592 return duration;
2593}
2594
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002595////////////////////////////////////////////////////////////////////////////////
2596
2597struct CallbackThread : public Thread {
2598 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
2599 MediaPlayerBase::AudioSink::AudioCallback cb,
2600 void *cookie);
2601
2602protected:
2603 virtual ~CallbackThread();
2604
2605 virtual bool threadLoop();
2606
2607private:
2608 wp<MediaPlayerBase::AudioSink> mSink;
2609 MediaPlayerBase::AudioSink::AudioCallback mCallback;
2610 void *mCookie;
2611 void *mBuffer;
2612 size_t mBufferSize;
2613
2614 CallbackThread(const CallbackThread &);
2615 CallbackThread &operator=(const CallbackThread &);
2616};
2617
2618CallbackThread::CallbackThread(
2619 const wp<MediaPlayerBase::AudioSink> &sink,
2620 MediaPlayerBase::AudioSink::AudioCallback cb,
2621 void *cookie)
2622 : mSink(sink),
2623 mCallback(cb),
2624 mCookie(cookie),
2625 mBuffer(NULL),
2626 mBufferSize(0) {
2627}
2628
2629CallbackThread::~CallbackThread() {
2630 if (mBuffer) {
2631 free(mBuffer);
2632 mBuffer = NULL;
2633 }
2634}
2635
2636bool CallbackThread::threadLoop() {
2637 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
2638 if (sink == NULL) {
2639 return false;
2640 }
2641
2642 if (mBuffer == NULL) {
2643 mBufferSize = sink->bufferSize();
2644 mBuffer = malloc(mBufferSize);
2645 }
2646
2647 size_t actualSize =
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002648 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie,
2649 MediaPlayerBase::AudioSink::CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002650
2651 if (actualSize > 0) {
2652 sink->write(mBuffer, actualSize);
Andy Hunga31335a2014-08-20 17:37:59 -07002653 // Could return false on sink->write() error or short count.
2654 // Not necessarily appropriate but would work for AudioCache behavior.
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002655 }
2656
2657 return true;
2658}
2659
2660////////////////////////////////////////////////////////////////////////////////
2661
Chong Zhange5b9b692017-05-11 11:44:56 -07002662void MediaPlayerService::addBatteryData(uint32_t params) {
2663 mBatteryTracker.addBatteryData(params);
2664}
2665
2666status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
2667 return mBatteryTracker.pullBatteryData(reply);
2668}
2669
2670MediaPlayerService::BatteryTracker::BatteryTracker() {
2671 mBatteryAudio.refCount = 0;
2672 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2673 mBatteryAudio.deviceOn[i] = 0;
2674 mBatteryAudio.lastTime[i] = 0;
2675 mBatteryAudio.totalTime[i] = 0;
2676 }
2677 // speaker is on by default
2678 mBatteryAudio.deviceOn[SPEAKER] = 1;
2679
2680 // reset battery stats
2681 // if the mediaserver has crashed, battery stats could be left
2682 // in bad state, reset the state upon service start.
2683 BatteryNotifier::getInstance().noteResetVideo();
2684}
2685
2686void MediaPlayerService::BatteryTracker::addBatteryData(uint32_t params)
Gloria Wang7cf180c2011-02-19 18:37:57 -08002687{
2688 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002689
2690 int32_t time = systemTime() / 1000000L;
2691
2692 // change audio output devices. This notification comes from AudioFlinger
2693 if ((params & kBatteryDataSpeakerOn)
2694 || (params & kBatteryDataOtherAudioDeviceOn)) {
2695
2696 int deviceOn[NUM_AUDIO_DEVICES];
2697 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2698 deviceOn[i] = 0;
2699 }
2700
2701 if ((params & kBatteryDataSpeakerOn)
2702 && (params & kBatteryDataOtherAudioDeviceOn)) {
2703 deviceOn[SPEAKER_AND_OTHER] = 1;
2704 } else if (params & kBatteryDataSpeakerOn) {
2705 deviceOn[SPEAKER] = 1;
2706 } else {
2707 deviceOn[OTHER_AUDIO_DEVICE] = 1;
2708 }
2709
2710 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2711 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
2712
2713 if (mBatteryAudio.refCount > 0) { // if playing audio
2714 if (!deviceOn[i]) {
2715 mBatteryAudio.lastTime[i] += time;
2716 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2717 mBatteryAudio.lastTime[i] = 0;
2718 } else {
2719 mBatteryAudio.lastTime[i] = 0 - time;
2720 }
2721 }
2722
2723 mBatteryAudio.deviceOn[i] = deviceOn[i];
2724 }
2725 }
2726 return;
2727 }
2728
Marco Nelissenb7848f12014-12-04 08:57:56 -08002729 // an audio stream is started
Gloria Wang9ee159b2011-02-24 14:51:45 -08002730 if (params & kBatteryDataAudioFlingerStart) {
2731 // record the start time only if currently no other audio
2732 // is being played
2733 if (mBatteryAudio.refCount == 0) {
2734 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2735 if (mBatteryAudio.deviceOn[i]) {
2736 mBatteryAudio.lastTime[i] -= time;
2737 }
2738 }
2739 }
2740
2741 mBatteryAudio.refCount ++;
2742 return;
2743
2744 } else if (params & kBatteryDataAudioFlingerStop) {
2745 if (mBatteryAudio.refCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002746 ALOGW("Battery track warning: refCount is <= 0");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002747 return;
2748 }
2749
2750 // record the stop time only if currently this is the only
2751 // audio being played
2752 if (mBatteryAudio.refCount == 1) {
2753 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2754 if (mBatteryAudio.deviceOn[i]) {
2755 mBatteryAudio.lastTime[i] += time;
2756 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2757 mBatteryAudio.lastTime[i] = 0;
2758 }
2759 }
2760 }
2761
2762 mBatteryAudio.refCount --;
2763 return;
2764 }
2765
Andy Hung1afd0982016-11-08 16:13:44 -08002766 uid_t uid = IPCThreadState::self()->getCallingUid();
Gloria Wang7cf180c2011-02-19 18:37:57 -08002767 if (uid == AID_MEDIA) {
2768 return;
2769 }
2770 int index = mBatteryData.indexOfKey(uid);
Gloria Wang7cf180c2011-02-19 18:37:57 -08002771
2772 if (index < 0) { // create a new entry for this UID
2773 BatteryUsageInfo info;
2774 info.audioTotalTime = 0;
2775 info.videoTotalTime = 0;
2776 info.audioLastTime = 0;
2777 info.videoLastTime = 0;
2778 info.refCount = 0;
2779
Gloria Wang9ee159b2011-02-24 14:51:45 -08002780 if (mBatteryData.add(uid, info) == NO_MEMORY) {
Steve Block29357bc2012-01-06 19:20:56 +00002781 ALOGE("Battery track error: no memory for new app");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002782 return;
2783 }
Gloria Wang7cf180c2011-02-19 18:37:57 -08002784 }
2785
2786 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
2787
2788 if (params & kBatteryDataCodecStarted) {
2789 if (params & kBatteryDataTrackAudio) {
2790 info.audioLastTime -= time;
2791 info.refCount ++;
2792 }
2793 if (params & kBatteryDataTrackVideo) {
2794 info.videoLastTime -= time;
2795 info.refCount ++;
2796 }
2797 } else {
2798 if (info.refCount == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002799 ALOGW("Battery track warning: refCount is already 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002800 return;
2801 } else if (info.refCount < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00002802 ALOGE("Battery track error: refCount < 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002803 mBatteryData.removeItem(uid);
2804 return;
2805 }
2806
2807 if (params & kBatteryDataTrackAudio) {
2808 info.audioLastTime += time;
2809 info.refCount --;
2810 }
2811 if (params & kBatteryDataTrackVideo) {
2812 info.videoLastTime += time;
2813 info.refCount --;
2814 }
2815
2816 // no stream is being played by this UID
2817 if (info.refCount == 0) {
2818 info.audioTotalTime += info.audioLastTime;
2819 info.audioLastTime = 0;
2820 info.videoTotalTime += info.videoLastTime;
2821 info.videoLastTime = 0;
2822 }
2823 }
2824}
2825
Chong Zhange5b9b692017-05-11 11:44:56 -07002826status_t MediaPlayerService::BatteryTracker::pullBatteryData(Parcel* reply) {
Gloria Wang7cf180c2011-02-19 18:37:57 -08002827 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002828
2829 // audio output devices usage
2830 int32_t time = systemTime() / 1000000L; //in ms
2831 int32_t totalTime;
2832
2833 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2834 totalTime = mBatteryAudio.totalTime[i];
2835
2836 if (mBatteryAudio.deviceOn[i]
2837 && (mBatteryAudio.lastTime[i] != 0)) {
2838 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
2839 totalTime += tmpTime;
2840 }
2841
2842 reply->writeInt32(totalTime);
2843 // reset the total time
2844 mBatteryAudio.totalTime[i] = 0;
2845 }
2846
2847 // codec usage
Gloria Wang7cf180c2011-02-19 18:37:57 -08002848 BatteryUsageInfo info;
2849 int size = mBatteryData.size();
2850
2851 reply->writeInt32(size);
2852 int i = 0;
2853
2854 while (i < size) {
2855 info = mBatteryData.valueAt(i);
2856
2857 reply->writeInt32(mBatteryData.keyAt(i)); //UID
2858 reply->writeInt32(info.audioTotalTime);
2859 reply->writeInt32(info.videoTotalTime);
2860
2861 info.audioTotalTime = 0;
2862 info.videoTotalTime = 0;
2863
2864 // remove the UID entry where no stream is being played
2865 if (info.refCount <= 0) {
2866 mBatteryData.removeItemsAt(i);
2867 size --;
2868 i --;
2869 }
2870 i++;
2871 }
2872 return NO_ERROR;
2873}
nikoa64c8c72009-07-20 15:07:26 -07002874} // namespace android