blob: 71a73709f0fe62b25ed34d5ac2ae7787a2cf1ecf [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 }
779 }
Marco Nelissen1b5a7ee2016-09-30 13:54:30 -0700780 }
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700781
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700782 Mutex::Autolock lock(mLock);
783
784 clearDeathNotifiers_l();
785 mExtractorDeathListener = extractorDeathListener;
Marco Nelissena0c98412019-03-29 12:10:19 -0700786 mCodecDeathListeners.swap(codecDeathListeners);
jiabin156c6872017-10-06 09:47:15 -0700787 mAudioDeviceUpdatedListener = new AudioDeviceUpdatedNotifier(p);
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700788
John Grossmanc795b642012-02-22 15:38:35 -0800789 if (!p->hardwareOutput()) {
Marco Nelissend457c972014-02-11 08:47:07 -0800790 mAudioOutput = new AudioOutput(mAudioSessionId, IPCThreadState::self()->getCallingUid(),
jiabin156c6872017-10-06 09:47:15 -0700791 mPid, mAudioAttributes, mAudioDeviceUpdatedListener);
John Grossmanc795b642012-02-22 15:38:35 -0800792 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
793 }
794
795 return p;
796}
797
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700798status_t MediaPlayerService::Client::setDataSource_post(
John Grossmanc795b642012-02-22 15:38:35 -0800799 const sp<MediaPlayerBase>& p,
800 status_t status)
801{
802 ALOGV(" setDataSource");
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700803 if (status != OK) {
804 ALOGE(" error: %d", status);
805 return status;
John Grossmanc795b642012-02-22 15:38:35 -0800806 }
807
808 // Set the re-transmission endpoint if one was chosen.
809 if (mRetransmitEndpointValid) {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700810 status = p->setRetransmitEndpoint(&mRetransmitEndpoint);
811 if (status != NO_ERROR) {
812 ALOGE("setRetransmitEndpoint error: %d", status);
John Grossmanc795b642012-02-22 15:38:35 -0800813 }
814 }
815
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700816 if (status == OK) {
817 Mutex::Autolock lock(mLock);
John Grossmanc795b642012-02-22 15:38:35 -0800818 mPlayer = p;
819 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700820 return status;
John Grossmanc795b642012-02-22 15:38:35 -0800821}
822
Andreas Huber2db84552010-01-28 11:19:57 -0800823status_t MediaPlayerService::Client::setDataSource(
Andreas Huber1b86fe02014-01-29 11:13:26 -0800824 const sp<IMediaHTTPService> &httpService,
825 const char *url,
826 const KeyedVector<String8, String8> *headers)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800827{
Steve Block3856b092011-10-20 11:56:00 +0100828 ALOGV("setDataSource(%s)", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800829 if (url == NULL)
830 return UNKNOWN_ERROR;
831
Dave Burked681bbb2011-08-30 14:39:17 +0100832 if ((strncmp(url, "http://", 7) == 0) ||
833 (strncmp(url, "https://", 8) == 0) ||
834 (strncmp(url, "rtsp://", 7) == 0)) {
835 if (!checkPermission("android.permission.INTERNET")) {
836 return PERMISSION_DENIED;
837 }
838 }
839
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800840 if (strncmp(url, "content://", 10) == 0) {
841 // get a filedescriptor for the content Uri and
842 // pass it to the setDataSource(fd) method
843
844 String16 url16(url);
845 int fd = android::openContentProviderFile(url16);
846 if (fd < 0)
847 {
Steve Block29357bc2012-01-06 19:20:56 +0000848 ALOGE("Couldn't open fd for %s", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800849 return UNKNOWN_ERROR;
850 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700851 status_t status = setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800852 close(fd);
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700853 return mStatus = status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800854 } else {
John Grossman44a7e422012-06-21 17:29:24 -0700855 player_type playerType = MediaPlayerFactory::getPlayerType(this, url);
John Grossmanc795b642012-02-22 15:38:35 -0800856 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
857 if (p == NULL) {
858 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800859 }
860
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700861 return mStatus =
862 setDataSource_post(
863 p, p->setDataSource(httpService, url, headers));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800864 }
865}
866
867status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
868{
Marco Nelissen83b0fd92015-09-16 13:48:07 -0700869 ALOGV("setDataSource fd=%d (%s), offset=%lld, length=%lld",
870 fd, nameForFd(fd).c_str(), (long long) offset, (long long) length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800871 struct stat sb;
872 int ret = fstat(fd, &sb);
873 if (ret != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000874 ALOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800875 return UNKNOWN_ERROR;
876 }
877
Andy Hung833b4752016-04-04 17:15:48 -0700878 ALOGV("st_dev = %llu", static_cast<unsigned long long>(sb.st_dev));
Steve Block3856b092011-10-20 11:56:00 +0100879 ALOGV("st_mode = %u", sb.st_mode);
Mark Salyzyn77342f72014-06-18 16:31:32 -0700880 ALOGV("st_uid = %lu", static_cast<unsigned long>(sb.st_uid));
881 ALOGV("st_gid = %lu", static_cast<unsigned long>(sb.st_gid));
Andy Hung833b4752016-04-04 17:15:48 -0700882 ALOGV("st_size = %llu", static_cast<unsigned long long>(sb.st_size));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800883
884 if (offset >= sb.st_size) {
Steve Block29357bc2012-01-06 19:20:56 +0000885 ALOGE("offset error");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800886 return UNKNOWN_ERROR;
887 }
888 if (offset + length > sb.st_size) {
889 length = sb.st_size - offset;
Andy Hung833b4752016-04-04 17:15:48 -0700890 ALOGV("calculated length = %lld", (long long)length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800891 }
892
John Grossman44a7e422012-06-21 17:29:24 -0700893 player_type playerType = MediaPlayerFactory::getPlayerType(this,
894 fd,
895 offset,
896 length);
John Grossmanc795b642012-02-22 15:38:35 -0800897 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
898 if (p == NULL) {
899 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800900 }
901
902 // now set data source
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700903 return mStatus = setDataSource_post(p, p->setDataSource(fd, offset, length));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800904}
905
Andreas Hubere2b10282010-11-23 11:41:34 -0800906status_t MediaPlayerService::Client::setDataSource(
907 const sp<IStreamSource> &source) {
908 // create the right type of player
John Grossman44a7e422012-06-21 17:29:24 -0700909 player_type playerType = MediaPlayerFactory::getPlayerType(this, source);
John Grossmanc795b642012-02-22 15:38:35 -0800910 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
Andreas Hubere2b10282010-11-23 11:41:34 -0800911 if (p == NULL) {
912 return NO_INIT;
913 }
914
Andreas Hubere2b10282010-11-23 11:41:34 -0800915 // now set data source
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700916 return mStatus = setDataSource_post(p, p->setDataSource(source));
Andreas Hubere2b10282010-11-23 11:41:34 -0800917}
918
Chris Watkins99f31602015-03-20 13:06:33 -0700919status_t MediaPlayerService::Client::setDataSource(
920 const sp<IDataSource> &source) {
Dongwon Kangd91dc5a2017-10-10 00:07:09 -0700921 sp<DataSource> dataSource = CreateDataSourceFromIDataSource(source);
Chris Watkins99f31602015-03-20 13:06:33 -0700922 player_type playerType = MediaPlayerFactory::getPlayerType(this, dataSource);
923 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
924 if (p == NULL) {
925 return NO_INIT;
926 }
927 // now set data source
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700928 return mStatus = setDataSource_post(p, p->setDataSource(dataSource));
Chris Watkins99f31602015-03-20 13:06:33 -0700929}
930
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700931void MediaPlayerService::Client::disconnectNativeWindow_l() {
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700932 if (mConnectedWindow != NULL) {
Chong Zhang181fd9b2017-02-16 15:53:03 -0800933 status_t err = nativeWindowDisconnect(
934 mConnectedWindow.get(), "disconnectNativeWindow");
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700935
936 if (err != OK) {
Chong Zhang181fd9b2017-02-16 15:53:03 -0800937 ALOGW("nativeWindowDisconnect returned an error: %s (%d)",
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700938 strerror(-err), err);
939 }
940 }
941 mConnectedWindow.clear();
942}
943
Glenn Kasten11731182011-02-08 17:26:17 -0800944status_t MediaPlayerService::Client::setVideoSurfaceTexture(
Andy McFadden484566c2012-12-18 09:46:54 -0800945 const sp<IGraphicBufferProducer>& bufferProducer)
Glenn Kasten11731182011-02-08 17:26:17 -0800946{
Andy McFadden484566c2012-12-18 09:46:54 -0800947 ALOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, bufferProducer.get());
Glenn Kasten11731182011-02-08 17:26:17 -0800948 sp<MediaPlayerBase> p = getPlayer();
949 if (p == 0) return UNKNOWN_ERROR;
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700950
Marco Nelissenf8880202014-11-14 07:58:25 -0800951 sp<IBinder> binder(IInterface::asBinder(bufferProducer));
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700952 if (mConnectedWindowBinder == binder) {
953 return OK;
954 }
955
956 sp<ANativeWindow> anw;
Andy McFadden484566c2012-12-18 09:46:54 -0800957 if (bufferProducer != NULL) {
Marco Nelissenee08f7e2013-09-16 13:30:01 -0700958 anw = new Surface(bufferProducer, true /* controlledByApp */);
Chong Zhang181fd9b2017-02-16 15:53:03 -0800959 status_t err = nativeWindowConnect(anw.get(), "setVideoSurfaceTexture");
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700960
961 if (err != OK) {
Steve Block29357bc2012-01-06 19:20:56 +0000962 ALOGE("setVideoSurfaceTexture failed: %d", err);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700963 // Note that we must do the reset before disconnecting from the ANW.
964 // Otherwise queue/dequeue calls could be made on the disconnected
965 // ANW, which may result in errors.
966 reset();
967
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700968 Mutex::Autolock lock(mLock);
969 disconnectNativeWindow_l();
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700970
971 return err;
972 }
973 }
974
Andy McFadden484566c2012-12-18 09:46:54 -0800975 // Note that we must set the player's new GraphicBufferProducer before
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700976 // disconnecting the old one. Otherwise queue/dequeue calls could be made
977 // on the disconnected ANW, which may result in errors.
Andy McFadden484566c2012-12-18 09:46:54 -0800978 status_t err = p->setVideoSurfaceTexture(bufferProducer);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700979
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700980 mLock.lock();
981 disconnectNativeWindow_l();
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700982
983 if (err == OK) {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700984 mConnectedWindow = anw;
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700985 mConnectedWindowBinder = binder;
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700986 mLock.unlock();
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700987 } else {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700988 mLock.unlock();
989 status_t err = nativeWindowDisconnect(
990 anw.get(), "disconnectNativeWindow");
991
992 if (err != OK) {
993 ALOGW("nativeWindowDisconnect returned an error: %s (%d)",
994 strerror(-err), err);
995 }
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700996 }
997
998 return err;
Glenn Kasten11731182011-02-08 17:26:17 -0800999}
1000
Nicolas Catania1d187f12009-05-12 23:25:55 -07001001status_t MediaPlayerService::Client::invoke(const Parcel& request,
1002 Parcel *reply)
1003{
1004 sp<MediaPlayerBase> p = getPlayer();
1005 if (p == NULL) return UNKNOWN_ERROR;
1006 return p->invoke(request, reply);
1007}
1008
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001009// This call doesn't need to access the native player.
1010status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
1011{
1012 status_t status;
nikoa64c8c72009-07-20 15:07:26 -07001013 media::Metadata::Filter allow, drop;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001014
Nicolas Catania48290382009-07-10 13:53:06 -07001015 if (unmarshallFilter(filter, &allow, &status) &&
1016 unmarshallFilter(filter, &drop, &status)) {
1017 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001018
1019 mMetadataAllow = allow;
1020 mMetadataDrop = drop;
1021 }
1022 return status;
1023}
1024
Nicolas Catania48290382009-07-10 13:53:06 -07001025status_t MediaPlayerService::Client::getMetadata(
Mark Salyzyn77342f72014-06-18 16:31:32 -07001026 bool update_only, bool /*apply_filter*/, Parcel *reply)
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001027{
nikoa64c8c72009-07-20 15:07:26 -07001028 sp<MediaPlayerBase> player = getPlayer();
1029 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania48290382009-07-10 13:53:06 -07001030
nikod608a812009-07-16 16:39:53 -07001031 status_t status;
1032 // Placeholder for the return code, updated by the caller.
1033 reply->writeInt32(-1);
1034
nikoa64c8c72009-07-20 15:07:26 -07001035 media::Metadata::Filter ids;
Nicolas Catania48290382009-07-10 13:53:06 -07001036
1037 // We don't block notifications while we fetch the data. We clear
1038 // mMetadataUpdated first so we don't lose notifications happening
1039 // during the rest of this call.
1040 {
1041 Mutex::Autolock lock(mLock);
1042 if (update_only) {
nikod608a812009-07-16 16:39:53 -07001043 ids = mMetadataUpdated;
Nicolas Catania48290382009-07-10 13:53:06 -07001044 }
1045 mMetadataUpdated.clear();
1046 }
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001047
nikoa64c8c72009-07-20 15:07:26 -07001048 media::Metadata metadata(reply);
Nicolas Catania48290382009-07-10 13:53:06 -07001049
nikoa64c8c72009-07-20 15:07:26 -07001050 metadata.appendHeader();
1051 status = player->getMetadata(ids, reply);
nikod608a812009-07-16 16:39:53 -07001052
1053 if (status != OK) {
nikoa64c8c72009-07-20 15:07:26 -07001054 metadata.resetParcel();
Steve Block29357bc2012-01-06 19:20:56 +00001055 ALOGE("getMetadata failed %d", status);
nikod608a812009-07-16 16:39:53 -07001056 return status;
1057 }
1058
1059 // FIXME: Implement filtering on the result. Not critical since
1060 // filtering takes place on the update notifications already. This
1061 // would be when all the metadata are fetch and a filter is set.
1062
nikod608a812009-07-16 16:39:53 -07001063 // Everything is fine, update the metadata length.
nikoa64c8c72009-07-20 15:07:26 -07001064 metadata.updateLength();
nikod608a812009-07-16 16:39:53 -07001065 return OK;
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001066}
1067
Wei Jiad399e7e2016-10-26 15:49:11 -07001068status_t MediaPlayerService::Client::setBufferingSettings(
1069 const BufferingSettings& buffering)
1070{
Wei Jiadc6f3402017-01-09 15:04:18 -08001071 ALOGV("[%d] setBufferingSettings{%s}",
1072 mConnId, buffering.toString().string());
Wei Jiad399e7e2016-10-26 15:49:11 -07001073 sp<MediaPlayerBase> p = getPlayer();
1074 if (p == 0) return UNKNOWN_ERROR;
1075 return p->setBufferingSettings(buffering);
1076}
1077
Wei Jia9bb38032017-03-23 18:00:38 -07001078status_t MediaPlayerService::Client::getBufferingSettings(
Wei Jiad399e7e2016-10-26 15:49:11 -07001079 BufferingSettings* buffering /* nonnull */)
1080{
1081 sp<MediaPlayerBase> p = getPlayer();
1082 // TODO: create mPlayer on demand.
1083 if (p == 0) return UNKNOWN_ERROR;
Wei Jia9bb38032017-03-23 18:00:38 -07001084 status_t ret = p->getBufferingSettings(buffering);
Wei Jiad399e7e2016-10-26 15:49:11 -07001085 if (ret == NO_ERROR) {
Wei Jia9bb38032017-03-23 18:00:38 -07001086 ALOGV("[%d] getBufferingSettings{%s}",
Wei Jiadc6f3402017-01-09 15:04:18 -08001087 mConnId, buffering->toString().string());
Wei Jiad399e7e2016-10-26 15:49:11 -07001088 } else {
Wei Jia9bb38032017-03-23 18:00:38 -07001089 ALOGE("[%d] getBufferingSettings returned %d", mConnId, ret);
Wei Jiad399e7e2016-10-26 15:49:11 -07001090 }
1091 return ret;
1092}
1093
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001094status_t MediaPlayerService::Client::prepareAsync()
1095{
Steve Block3856b092011-10-20 11:56:00 +01001096 ALOGV("[%d] prepareAsync", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001097 sp<MediaPlayerBase> p = getPlayer();
1098 if (p == 0) return UNKNOWN_ERROR;
1099 status_t ret = p->prepareAsync();
1100#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +00001101 ALOGD("start Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001102 if (ret == NO_ERROR) mAntagonizer->start();
1103#endif
1104 return ret;
1105}
1106
1107status_t MediaPlayerService::Client::start()
1108{
Steve Block3856b092011-10-20 11:56:00 +01001109 ALOGV("[%d] start", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001110 sp<MediaPlayerBase> p = getPlayer();
1111 if (p == 0) return UNKNOWN_ERROR;
1112 p->setLooping(mLoop);
1113 return p->start();
1114}
1115
1116status_t MediaPlayerService::Client::stop()
1117{
Steve Block3856b092011-10-20 11:56:00 +01001118 ALOGV("[%d] stop", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001119 sp<MediaPlayerBase> p = getPlayer();
1120 if (p == 0) return UNKNOWN_ERROR;
1121 return p->stop();
1122}
1123
1124status_t MediaPlayerService::Client::pause()
1125{
Steve Block3856b092011-10-20 11:56:00 +01001126 ALOGV("[%d] pause", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001127 sp<MediaPlayerBase> p = getPlayer();
1128 if (p == 0) return UNKNOWN_ERROR;
1129 return p->pause();
1130}
1131
1132status_t MediaPlayerService::Client::isPlaying(bool* state)
1133{
1134 *state = false;
1135 sp<MediaPlayerBase> p = getPlayer();
1136 if (p == 0) return UNKNOWN_ERROR;
1137 *state = p->isPlaying();
Steve Block3856b092011-10-20 11:56:00 +01001138 ALOGV("[%d] isPlaying: %d", mConnId, *state);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001139 return NO_ERROR;
1140}
1141
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001142status_t MediaPlayerService::Client::setPlaybackSettings(const AudioPlaybackRate& rate)
Wei Jia98160162015-02-04 17:01:11 -08001143{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001144 ALOGV("[%d] setPlaybackSettings(%f, %f, %d, %d)",
1145 mConnId, rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Wei Jia98160162015-02-04 17:01:11 -08001146 sp<MediaPlayerBase> p = getPlayer();
1147 if (p == 0) return UNKNOWN_ERROR;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001148 return p->setPlaybackSettings(rate);
1149}
1150
1151status_t MediaPlayerService::Client::getPlaybackSettings(AudioPlaybackRate* rate /* nonnull */)
1152{
1153 sp<MediaPlayerBase> p = getPlayer();
1154 if (p == 0) return UNKNOWN_ERROR;
1155 status_t ret = p->getPlaybackSettings(rate);
1156 if (ret == NO_ERROR) {
1157 ALOGV("[%d] getPlaybackSettings(%f, %f, %d, %d)",
1158 mConnId, rate->mSpeed, rate->mPitch, rate->mFallbackMode, rate->mStretchMode);
1159 } else {
1160 ALOGV("[%d] getPlaybackSettings returned %d", mConnId, ret);
1161 }
1162 return ret;
1163}
1164
1165status_t MediaPlayerService::Client::setSyncSettings(
1166 const AVSyncSettings& sync, float videoFpsHint)
1167{
1168 ALOGV("[%d] setSyncSettings(%u, %u, %f, %f)",
1169 mConnId, sync.mSource, sync.mAudioAdjustMode, sync.mTolerance, videoFpsHint);
1170 sp<MediaPlayerBase> p = getPlayer();
1171 if (p == 0) return UNKNOWN_ERROR;
1172 return p->setSyncSettings(sync, videoFpsHint);
1173}
1174
1175status_t MediaPlayerService::Client::getSyncSettings(
1176 AVSyncSettings* sync /* nonnull */, float* videoFps /* nonnull */)
1177{
1178 sp<MediaPlayerBase> p = getPlayer();
1179 if (p == 0) return UNKNOWN_ERROR;
1180 status_t ret = p->getSyncSettings(sync, videoFps);
1181 if (ret == NO_ERROR) {
1182 ALOGV("[%d] getSyncSettings(%u, %u, %f, %f)",
1183 mConnId, sync->mSource, sync->mAudioAdjustMode, sync->mTolerance, *videoFps);
1184 } else {
1185 ALOGV("[%d] getSyncSettings returned %d", mConnId, ret);
1186 }
1187 return ret;
Wei Jia98160162015-02-04 17:01:11 -08001188}
1189
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001190status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
1191{
Steve Block3856b092011-10-20 11:56:00 +01001192 ALOGV("getCurrentPosition");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001193 sp<MediaPlayerBase> p = getPlayer();
1194 if (p == 0) return UNKNOWN_ERROR;
1195 status_t ret = p->getCurrentPosition(msec);
1196 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001197 ALOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001198 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001199 ALOGE("getCurrentPosition returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001200 }
1201 return ret;
1202}
1203
1204status_t MediaPlayerService::Client::getDuration(int *msec)
1205{
Steve Block3856b092011-10-20 11:56:00 +01001206 ALOGV("getDuration");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001207 sp<MediaPlayerBase> p = getPlayer();
1208 if (p == 0) return UNKNOWN_ERROR;
1209 status_t ret = p->getDuration(msec);
1210 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001211 ALOGV("[%d] getDuration = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001212 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001213 ALOGE("getDuration returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001214 }
1215 return ret;
1216}
1217
Marco Nelissen6b74d672012-02-28 16:07:44 -08001218status_t MediaPlayerService::Client::setNextPlayer(const sp<IMediaPlayer>& player) {
1219 ALOGV("setNextPlayer");
1220 Mutex::Autolock l(mLock);
1221 sp<Client> c = static_cast<Client*>(player.get());
Wei Jia28284122016-08-30 13:49:06 -07001222 if (c != NULL && !mService->hasClient(c)) {
Robert Shihee0a0e32016-08-16 16:50:54 -07001223 return BAD_VALUE;
1224 }
1225
Marco Nelissen6b74d672012-02-28 16:07:44 -08001226 mNextClient = c;
John Grossman5f7e55e2012-08-24 14:47:25 -07001227
1228 if (c != NULL) {
1229 if (mAudioOutput != NULL) {
1230 mAudioOutput->setNextOutput(c->mAudioOutput);
1231 } else if ((mPlayer != NULL) && !mPlayer->hardwareOutput()) {
1232 ALOGE("no current audio output");
1233 }
1234
1235 if ((mPlayer != NULL) && (mNextClient->getPlayer() != NULL)) {
1236 mPlayer->setNextPlayer(mNextClient->getPlayer());
1237 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001238 }
John Grossman5f7e55e2012-08-24 14:47:25 -07001239
Marco Nelissen6b74d672012-02-28 16:07:44 -08001240 return OK;
1241}
1242
Andy Hung9fc8b5c2017-01-24 13:36:48 -08001243VolumeShaper::Status MediaPlayerService::Client::applyVolumeShaper(
1244 const sp<VolumeShaper::Configuration>& configuration,
1245 const sp<VolumeShaper::Operation>& operation) {
1246 // for hardware output, call player instead
1247 ALOGV("Client::applyVolumeShaper(%p)", this);
1248 sp<MediaPlayerBase> p = getPlayer();
1249 {
1250 Mutex::Autolock l(mLock);
1251 if (p != 0 && p->hardwareOutput()) {
1252 // TODO: investigate internal implementation
1253 return VolumeShaper::Status(INVALID_OPERATION);
1254 }
1255 if (mAudioOutput.get() != nullptr) {
1256 return mAudioOutput->applyVolumeShaper(configuration, operation);
1257 }
1258 }
1259 return VolumeShaper::Status(INVALID_OPERATION);
1260}
1261
1262sp<VolumeShaper::State> MediaPlayerService::Client::getVolumeShaperState(int id) {
1263 // for hardware output, call player instead
1264 ALOGV("Client::getVolumeShaperState(%p)", this);
1265 sp<MediaPlayerBase> p = getPlayer();
1266 {
1267 Mutex::Autolock l(mLock);
1268 if (p != 0 && p->hardwareOutput()) {
1269 // TODO: investigate internal implementation.
1270 return nullptr;
1271 }
1272 if (mAudioOutput.get() != nullptr) {
1273 return mAudioOutput->getVolumeShaperState(id);
1274 }
1275 }
1276 return nullptr;
1277}
1278
Wei Jiac5de0912016-11-18 10:22:14 -08001279status_t MediaPlayerService::Client::seekTo(int msec, MediaPlayerSeekMode mode)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001280{
Wei Jiac5de0912016-11-18 10:22:14 -08001281 ALOGV("[%d] seekTo(%d, %d)", mConnId, msec, mode);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001282 sp<MediaPlayerBase> p = getPlayer();
1283 if (p == 0) return UNKNOWN_ERROR;
Wei Jiac5de0912016-11-18 10:22:14 -08001284 return p->seekTo(msec, mode);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001285}
1286
1287status_t MediaPlayerService::Client::reset()
1288{
Steve Block3856b092011-10-20 11:56:00 +01001289 ALOGV("[%d] reset", mConnId);
John Grossmanc795b642012-02-22 15:38:35 -08001290 mRetransmitEndpointValid = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001291 sp<MediaPlayerBase> p = getPlayer();
1292 if (p == 0) return UNKNOWN_ERROR;
1293 return p->reset();
1294}
1295
Wei Jia52c28512017-09-13 18:17:51 -07001296status_t MediaPlayerService::Client::notifyAt(int64_t mediaTimeUs)
1297{
1298 ALOGV("[%d] notifyAt(%lld)", mConnId, (long long)mediaTimeUs);
1299 sp<MediaPlayerBase> p = getPlayer();
1300 if (p == 0) return UNKNOWN_ERROR;
1301 return p->notifyAt(mediaTimeUs);
1302}
1303
Glenn Kastenfff6d712012-01-12 16:38:12 -08001304status_t MediaPlayerService::Client::setAudioStreamType(audio_stream_type_t type)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001305{
Steve Block3856b092011-10-20 11:56:00 +01001306 ALOGV("[%d] setAudioStreamType(%d)", mConnId, type);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001307 // TODO: for hardware output, call player instead
1308 Mutex::Autolock l(mLock);
1309 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1310 return NO_ERROR;
1311}
1312
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001313status_t MediaPlayerService::Client::setAudioAttributes_l(const Parcel &parcel)
1314{
1315 if (mAudioAttributes != NULL) { free(mAudioAttributes); }
1316 mAudioAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001317 if (mAudioAttributes == NULL) {
1318 return NO_MEMORY;
1319 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001320 unmarshallAudioAttributes(parcel, mAudioAttributes);
1321
1322 ALOGV("setAudioAttributes_l() usage=%d content=%d flags=0x%x tags=%s",
1323 mAudioAttributes->usage, mAudioAttributes->content_type, mAudioAttributes->flags,
1324 mAudioAttributes->tags);
1325
1326 if (mAudioOutput != 0) {
1327 mAudioOutput->setAudioAttributes(mAudioAttributes);
1328 }
1329 return NO_ERROR;
1330}
1331
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001332status_t MediaPlayerService::Client::setLooping(int loop)
1333{
Steve Block3856b092011-10-20 11:56:00 +01001334 ALOGV("[%d] setLooping(%d)", mConnId, loop);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001335 mLoop = loop;
1336 sp<MediaPlayerBase> p = getPlayer();
1337 if (p != 0) return p->setLooping(loop);
1338 return NO_ERROR;
1339}
1340
1341status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1342{
Steve Block3856b092011-10-20 11:56:00 +01001343 ALOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
John Grossman761defc2012-02-09 15:09:05 -08001344
1345 // for hardware output, call player instead
1346 sp<MediaPlayerBase> p = getPlayer();
1347 {
1348 Mutex::Autolock l(mLock);
1349 if (p != 0 && p->hardwareOutput()) {
1350 MediaPlayerHWInterface* hwp =
1351 reinterpret_cast<MediaPlayerHWInterface*>(p.get());
1352 return hwp->setVolume(leftVolume, rightVolume);
1353 } else {
1354 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1355 return NO_ERROR;
1356 }
1357 }
1358
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001359 return NO_ERROR;
1360}
1361
Eric Laurent2beeb502010-07-16 07:43:46 -07001362status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1363{
Steve Block3856b092011-10-20 11:56:00 +01001364 ALOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
Eric Laurent2beeb502010-07-16 07:43:46 -07001365 Mutex::Autolock l(mLock);
1366 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1367 return NO_ERROR;
1368}
1369
1370status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1371{
Steve Block3856b092011-10-20 11:56:00 +01001372 ALOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
Eric Laurent2beeb502010-07-16 07:43:46 -07001373 Mutex::Autolock l(mLock);
1374 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1375 return NO_ERROR;
1376}
Nicolas Catania48290382009-07-10 13:53:06 -07001377
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001378status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
Steve Block3856b092011-10-20 11:56:00 +01001379 ALOGV("[%d] setParameter(%d)", mConnId, key);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001380 switch (key) {
1381 case KEY_PARAMETER_AUDIO_ATTRIBUTES:
1382 {
1383 Mutex::Autolock l(mLock);
1384 return setAudioAttributes_l(request);
1385 }
1386 default:
1387 sp<MediaPlayerBase> p = getPlayer();
1388 if (p == 0) { return UNKNOWN_ERROR; }
1389 return p->setParameter(key, request);
1390 }
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001391}
1392
1393status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
Steve Block3856b092011-10-20 11:56:00 +01001394 ALOGV("[%d] getParameter(%d)", mConnId, key);
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001395 sp<MediaPlayerBase> p = getPlayer();
1396 if (p == 0) return UNKNOWN_ERROR;
1397 return p->getParameter(key, reply);
1398}
1399
John Grossmanc795b642012-02-22 15:38:35 -08001400status_t MediaPlayerService::Client::setRetransmitEndpoint(
1401 const struct sockaddr_in* endpoint) {
1402
1403 if (NULL != endpoint) {
1404 uint32_t a = ntohl(endpoint->sin_addr.s_addr);
1405 uint16_t p = ntohs(endpoint->sin_port);
1406 ALOGV("[%d] setRetransmitEndpoint(%u.%u.%u.%u:%hu)", mConnId,
1407 (a >> 24), (a >> 16) & 0xFF, (a >> 8) & 0xFF, (a & 0xFF), p);
1408 } else {
1409 ALOGV("[%d] setRetransmitEndpoint = <none>", mConnId);
1410 }
1411
1412 sp<MediaPlayerBase> p = getPlayer();
1413
1414 // Right now, the only valid time to set a retransmit endpoint is before
1415 // player selection has been made (since the presence or absence of a
1416 // retransmit endpoint is going to determine which player is selected during
1417 // setDataSource).
1418 if (p != 0) return INVALID_OPERATION;
1419
1420 if (NULL != endpoint) {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001421 Mutex::Autolock lock(mLock);
John Grossmanc795b642012-02-22 15:38:35 -08001422 mRetransmitEndpoint = *endpoint;
1423 mRetransmitEndpointValid = true;
1424 } else {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001425 Mutex::Autolock lock(mLock);
John Grossmanc795b642012-02-22 15:38:35 -08001426 mRetransmitEndpointValid = false;
1427 }
1428
1429 return NO_ERROR;
1430}
1431
John Grossman44a7e422012-06-21 17:29:24 -07001432status_t MediaPlayerService::Client::getRetransmitEndpoint(
1433 struct sockaddr_in* endpoint)
1434{
1435 if (NULL == endpoint)
1436 return BAD_VALUE;
1437
1438 sp<MediaPlayerBase> p = getPlayer();
1439
1440 if (p != NULL)
1441 return p->getRetransmitEndpoint(endpoint);
1442
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001443 Mutex::Autolock lock(mLock);
John Grossman44a7e422012-06-21 17:29:24 -07001444 if (!mRetransmitEndpointValid)
1445 return NO_INIT;
1446
1447 *endpoint = mRetransmitEndpoint;
1448
1449 return NO_ERROR;
1450}
1451
Gloria Wangb483c472011-04-11 17:23:27 -07001452void MediaPlayerService::Client::notify(
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001453 int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001454{
James Dongb8a98252012-08-26 16:13:03 -07001455 sp<IMediaPlayerClient> c;
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001456 sp<Client> nextClient;
1457 status_t errStartNext = NO_ERROR;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001458 {
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001459 Mutex::Autolock l(mLock);
1460 c = mClient;
1461 if (msg == MEDIA_PLAYBACK_COMPLETE && mNextClient != NULL) {
1462 nextClient = mNextClient;
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001463
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001464 if (mAudioOutput != NULL)
1465 mAudioOutput->switchToNextOutput();
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001466
1467 errStartNext = nextClient->start();
1468 }
1469 }
1470
1471 if (nextClient != NULL) {
1472 sp<IMediaPlayerClient> nc;
1473 {
1474 Mutex::Autolock l(nextClient->mLock);
1475 nc = nextClient->mClient;
1476 }
1477 if (nc != NULL) {
1478 if (errStartNext == NO_ERROR) {
1479 nc->notify(MEDIA_INFO, MEDIA_INFO_STARTED_AS_NEXT, 0, obj);
1480 } else {
1481 nc->notify(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN , 0, obj);
1482 ALOGE("gapless:start playback for next track failed, err(%d)", errStartNext);
Wei Jia2afac0c2016-01-07 12:13:07 -08001483 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001484 }
1485 }
1486
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001487 if (MEDIA_INFO == msg &&
Nicolas Catania48290382009-07-10 13:53:06 -07001488 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikoa64c8c72009-07-20 15:07:26 -07001489 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania48290382009-07-10 13:53:06 -07001490
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001491 if(shouldDropMetadata(metadata_type)) {
Nicolas Catania48290382009-07-10 13:53:06 -07001492 return;
1493 }
1494
1495 // Update the list of metadata that have changed. getMetadata
1496 // also access mMetadataUpdated and clears it.
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001497 addNewMetadataUpdate(metadata_type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001498 }
James Dongb8a98252012-08-26 16:13:03 -07001499
1500 if (c != NULL) {
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001501 ALOGV("[%d] notify (%d, %d, %d)", mConnId, msg, ext1, ext2);
James Dongb8a98252012-08-26 16:13:03 -07001502 c->notify(msg, ext1, ext2, obj);
1503 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001504}
1505
Nicolas Catania48290382009-07-10 13:53:06 -07001506
nikoa64c8c72009-07-20 15:07:26 -07001507bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001508{
Nicolas Catania48290382009-07-10 13:53:06 -07001509 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001510
Nicolas Catania48290382009-07-10 13:53:06 -07001511 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001512 return true;
1513 }
1514
Nicolas Catania48290382009-07-10 13:53:06 -07001515 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001516 return false;
Nicolas Catania48290382009-07-10 13:53:06 -07001517 } else {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001518 return true;
1519 }
1520}
1521
Nicolas Catania48290382009-07-10 13:53:06 -07001522
nikoa64c8c72009-07-20 15:07:26 -07001523void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania48290382009-07-10 13:53:06 -07001524 Mutex::Autolock lock(mLock);
1525 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1526 mMetadataUpdated.add(metadata_type);
1527 }
1528}
1529
Hassan Shojaniacefac142017-02-06 21:02:02 -08001530// Modular DRM
1531status_t MediaPlayerService::Client::prepareDrm(const uint8_t uuid[16],
1532 const Vector<uint8_t>& drmSessionId)
1533{
1534 ALOGV("[%d] prepareDrm", mConnId);
1535 sp<MediaPlayerBase> p = getPlayer();
1536 if (p == 0) return UNKNOWN_ERROR;
1537
1538 status_t ret = p->prepareDrm(uuid, drmSessionId);
1539 ALOGV("prepareDrm ret: %d", ret);
1540
1541 return ret;
1542}
1543
1544status_t MediaPlayerService::Client::releaseDrm()
1545{
1546 ALOGV("[%d] releaseDrm", mConnId);
1547 sp<MediaPlayerBase> p = getPlayer();
1548 if (p == 0) return UNKNOWN_ERROR;
1549
1550 status_t ret = p->releaseDrm();
1551 ALOGV("releaseDrm ret: %d", ret);
1552
1553 return ret;
1554}
1555
jiabin156c6872017-10-06 09:47:15 -07001556status_t MediaPlayerService::Client::setOutputDevice(audio_port_handle_t deviceId)
1557{
1558 ALOGV("[%d] setOutputDevice", mConnId);
1559 {
1560 Mutex::Autolock l(mLock);
1561 if (mAudioOutput.get() != nullptr) {
1562 return mAudioOutput->setOutputDevice(deviceId);
1563 }
1564 }
1565 return NO_INIT;
1566}
1567
1568status_t MediaPlayerService::Client::getRoutedDeviceId(audio_port_handle_t* deviceId)
1569{
1570 ALOGV("[%d] getRoutedDeviceId", mConnId);
1571 {
1572 Mutex::Autolock l(mLock);
1573 if (mAudioOutput.get() != nullptr) {
1574 return mAudioOutput->getRoutedDeviceId(deviceId);
1575 }
1576 }
1577 return NO_INIT;
1578}
1579
1580status_t MediaPlayerService::Client::enableAudioDeviceCallback(bool enabled)
1581{
1582 ALOGV("[%d] enableAudioDeviceCallback, %d", mConnId, enabled);
1583 {
1584 Mutex::Autolock l(mLock);
1585 if (mAudioOutput.get() != nullptr) {
1586 return mAudioOutput->enableAudioDeviceCallback(enabled);
1587 }
1588 }
1589 return NO_INIT;
1590}
1591
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001592#if CALLBACK_ANTAGONIZER
1593const int Antagonizer::interval = 10000; // 10 msecs
1594
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001595Antagonizer::Antagonizer(const sp<MediaPlayerBase::Listener> &listener) :
1596 mExit(false), mActive(false), mListener(listener)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001597{
1598 createThread(callbackThread, this);
1599}
1600
1601void Antagonizer::kill()
1602{
1603 Mutex::Autolock _l(mLock);
1604 mActive = false;
1605 mExit = true;
1606 mCondition.wait(mLock);
1607}
1608
1609int Antagonizer::callbackThread(void* user)
1610{
Steve Blockb8a80522011-12-20 16:23:08 +00001611 ALOGD("Antagonizer started");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001612 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1613 while (!p->mExit) {
1614 if (p->mActive) {
Steve Block3856b092011-10-20 11:56:00 +01001615 ALOGV("send event");
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001616 p->mListener->notify(0, 0, 0, 0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001617 }
1618 usleep(interval);
1619 }
1620 Mutex::Autolock _l(p->mLock);
1621 p->mCondition.signal();
Steve Blockb8a80522011-12-20 16:23:08 +00001622 ALOGD("Antagonizer stopped");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001623 return 0;
1624}
1625#endif
1626
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001627#undef LOG_TAG
1628#define LOG_TAG "AudioSink"
Andy Hung1afd0982016-11-08 16:13:44 -08001629MediaPlayerService::AudioOutput::AudioOutput(audio_session_t sessionId, uid_t uid, int pid,
jiabin156c6872017-10-06 09:47:15 -07001630 const audio_attributes_t* attr, const sp<AudioSystem::AudioDeviceCallback>& deviceCallback)
Andreas Huber20111aa2009-07-14 16:56:47 -07001631 : mCallback(NULL),
Eric Laurenta514bdb2010-06-21 09:27:30 -07001632 mCallbackCookie(NULL),
Marco Nelissen6b74d672012-02-28 16:07:44 -08001633 mCallbackData(NULL),
Andy Hungd1c74342015-07-07 16:54:23 -07001634 mStreamType(AUDIO_STREAM_MUSIC),
Andy Hungd1c74342015-07-07 16:54:23 -07001635 mLeftVolume(1.0),
1636 mRightVolume(1.0),
1637 mPlaybackRate(AUDIO_PLAYBACK_RATE_DEFAULT),
1638 mSampleRateHz(0),
1639 mMsecsPerFrame(0),
1640 mFrameSize(0),
Eric Laurent1948eb32012-04-13 16:50:19 -07001641 mSessionId(sessionId),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001642 mUid(uid),
Marco Nelissend457c972014-02-11 08:47:07 -08001643 mPid(pid),
Andy Hungd1c74342015-07-07 16:54:23 -07001644 mSendLevel(0.0),
1645 mAuxEffectId(0),
Andy Hung4ef88d72017-02-21 19:47:53 -08001646 mFlags(AUDIO_OUTPUT_FLAG_NONE),
jiabin156c6872017-10-06 09:47:15 -07001647 mVolumeHandler(new media::VolumeHandler()),
1648 mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE),
jiabin161b64f2017-11-17 09:31:48 -08001649 mRoutedDeviceId(AUDIO_PORT_HANDLE_NONE),
jiabin156c6872017-10-06 09:47:15 -07001650 mDeviceCallbackEnabled(false),
1651 mDeviceCallback(deviceCallback)
Andy Hungd1c74342015-07-07 16:54:23 -07001652{
Steve Block3856b092011-10-20 11:56:00 +01001653 ALOGV("AudioOutput(%d)", sessionId);
Eric Laurent43562692015-07-15 16:49:07 -07001654 if (attr != NULL) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001655 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1656 if (mAttributes != NULL) {
1657 memcpy(mAttributes, attr, sizeof(audio_attributes_t));
François Gaffie58d4be52018-11-06 15:30:12 +01001658 mStreamType = AudioSystem::attributesToStreamType(*attr);
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001659 }
1660 } else {
1661 mAttributes = NULL;
Eric Laurent43562692015-07-15 16:49:07 -07001662 }
1663
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001664 setMinBufferCount();
1665}
1666
1667MediaPlayerService::AudioOutput::~AudioOutput()
1668{
1669 close();
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001670 free(mAttributes);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001671 delete mCallbackData;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001672}
1673
Andy Hungd1c74342015-07-07 16:54:23 -07001674//static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001675void MediaPlayerService::AudioOutput::setMinBufferCount()
1676{
1677 char value[PROPERTY_VALUE_MAX];
1678 if (property_get("ro.kernel.qemu", value, 0)) {
1679 mIsOnEmulator = true;
1680 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1681 }
1682}
1683
Andy Hungd1c74342015-07-07 16:54:23 -07001684// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001685bool MediaPlayerService::AudioOutput::isOnEmulator()
1686{
Andy Hungd1c74342015-07-07 16:54:23 -07001687 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001688 return mIsOnEmulator;
1689}
1690
Andy Hungd1c74342015-07-07 16:54:23 -07001691// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001692int MediaPlayerService::AudioOutput::getMinBufferCount()
1693{
Andy Hungd1c74342015-07-07 16:54:23 -07001694 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001695 return mMinBufferCount;
1696}
1697
1698ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1699{
Andy Hungd1c74342015-07-07 16:54:23 -07001700 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001701 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001702 return mTrack->frameCount() * mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001703}
1704
1705ssize_t MediaPlayerService::AudioOutput::frameCount() const
1706{
Andy Hungd1c74342015-07-07 16:54:23 -07001707 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001708 if (mTrack == 0) return NO_INIT;
1709 return mTrack->frameCount();
1710}
1711
1712ssize_t MediaPlayerService::AudioOutput::channelCount() const
1713{
Andy Hungd1c74342015-07-07 16:54:23 -07001714 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001715 if (mTrack == 0) return NO_INIT;
1716 return mTrack->channelCount();
1717}
1718
1719ssize_t MediaPlayerService::AudioOutput::frameSize() const
1720{
Andy Hungd1c74342015-07-07 16:54:23 -07001721 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001722 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001723 return mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001724}
1725
1726uint32_t MediaPlayerService::AudioOutput::latency () const
1727{
Andy Hungd1c74342015-07-07 16:54:23 -07001728 Mutex::Autolock lock(mLock);
Eric Laurentdb354e52012-03-05 17:27:11 -08001729 if (mTrack == 0) return 0;
1730 return mTrack->latency();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001731}
1732
1733float MediaPlayerService::AudioOutput::msecsPerFrame() const
1734{
Andy Hungd1c74342015-07-07 16:54:23 -07001735 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001736 return mMsecsPerFrame;
1737}
1738
Marco Nelissen4110c102012-03-29 09:31:28 -07001739status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position) const
Eric Laurent342e9cf2010-01-19 17:37:09 -08001740{
Andy Hungd1c74342015-07-07 16:54:23 -07001741 Mutex::Autolock lock(mLock);
Eric Laurent342e9cf2010-01-19 17:37:09 -08001742 if (mTrack == 0) return NO_INIT;
1743 return mTrack->getPosition(position);
1744}
1745
Lajos Molnar06ad1522014-08-28 07:27:44 -07001746status_t MediaPlayerService::AudioOutput::getTimestamp(AudioTimestamp &ts) const
1747{
Andy Hungd1c74342015-07-07 16:54:23 -07001748 Mutex::Autolock lock(mLock);
Lajos Molnar06ad1522014-08-28 07:27:44 -07001749 if (mTrack == 0) return NO_INIT;
1750 return mTrack->getTimestamp(ts);
1751}
1752
Wei Jiac4ac8172015-10-21 10:35:48 -07001753// TODO: Remove unnecessary calls to getPlayedOutDurationUs()
1754// as it acquires locks and may query the audio driver.
1755//
1756// Some calls could conceivably retrieve extrapolated data instead of
1757// accessing getTimestamp() or getPosition() every time a data buffer with
1758// a media time is received.
1759//
1760// Calculate duration of played samples if played at normal rate (i.e., 1.0).
1761int64_t MediaPlayerService::AudioOutput::getPlayedOutDurationUs(int64_t nowUs) const
1762{
1763 Mutex::Autolock lock(mLock);
1764 if (mTrack == 0 || mSampleRateHz == 0) {
Wei Jia213f4902015-10-22 08:55:25 -07001765 return 0;
Wei Jiac4ac8172015-10-21 10:35:48 -07001766 }
1767
1768 uint32_t numFramesPlayed;
Andy Hung5d313802016-10-10 15:09:39 -07001769 int64_t numFramesPlayedAtUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001770 AudioTimestamp ts;
Wei Jiac4ac8172015-10-21 10:35:48 -07001771
1772 status_t res = mTrack->getTimestamp(ts);
1773 if (res == OK) { // case 1: mixing audio tracks and offloaded tracks.
1774 numFramesPlayed = ts.mPosition;
Andy Hung5d313802016-10-10 15:09:39 -07001775 numFramesPlayedAtUs = ts.mTime.tv_sec * 1000000LL + ts.mTime.tv_nsec / 1000;
1776 //ALOGD("getTimestamp: OK %d %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001777 } else if (res == WOULD_BLOCK) { // case 2: transitory state on start of a new track
1778 numFramesPlayed = 0;
Andy Hung5d313802016-10-10 15:09:39 -07001779 numFramesPlayedAtUs = nowUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001780 //ALOGD("getTimestamp: WOULD_BLOCK %d %lld",
Andy Hung5d313802016-10-10 15:09:39 -07001781 // numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001782 } else { // case 3: transitory at new track or audio fast tracks.
1783 res = mTrack->getPosition(&numFramesPlayed);
1784 CHECK_EQ(res, (status_t)OK);
Andy Hung5d313802016-10-10 15:09:39 -07001785 numFramesPlayedAtUs = nowUs;
1786 numFramesPlayedAtUs += 1000LL * mTrack->latency() / 2; /* XXX */
1787 //ALOGD("getPosition: %u %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001788 }
1789
1790 // CHECK_EQ(numFramesPlayed & (1 << 31), 0); // can't be negative until 12.4 hrs, test
1791 // TODO: remove the (int32_t) casting below as it may overflow at 12.4 hours.
1792 int64_t durationUs = (int64_t)((int32_t)numFramesPlayed * 1000000LL / mSampleRateHz)
Andy Hung5d313802016-10-10 15:09:39 -07001793 + nowUs - numFramesPlayedAtUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001794 if (durationUs < 0) {
1795 // Occurs when numFramesPlayed position is very small and the following:
1796 // (1) In case 1, the time nowUs is computed before getTimestamp() is called and
Andy Hung5d313802016-10-10 15:09:39 -07001797 // numFramesPlayedAtUs is greater than nowUs by time more than numFramesPlayed.
Wei Jiac4ac8172015-10-21 10:35:48 -07001798 // (2) In case 3, using getPosition and adding mAudioSink->latency() to
Andy Hung5d313802016-10-10 15:09:39 -07001799 // numFramesPlayedAtUs, by a time amount greater than numFramesPlayed.
Wei Jiac4ac8172015-10-21 10:35:48 -07001800 //
1801 // Both of these are transitory conditions.
1802 ALOGV("getPlayedOutDurationUs: negative duration %lld set to zero", (long long)durationUs);
1803 durationUs = 0;
1804 }
1805 ALOGV("getPlayedOutDurationUs(%lld) nowUs(%lld) frames(%u) framesAt(%lld)",
Andy Hung5d313802016-10-10 15:09:39 -07001806 (long long)durationUs, (long long)nowUs,
1807 numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001808 return durationUs;
1809}
1810
Marco Nelissen4110c102012-03-29 09:31:28 -07001811status_t MediaPlayerService::AudioOutput::getFramesWritten(uint32_t *frameswritten) const
1812{
Andy Hungd1c74342015-07-07 16:54:23 -07001813 Mutex::Autolock lock(mLock);
Marco Nelissen4110c102012-03-29 09:31:28 -07001814 if (mTrack == 0) return NO_INIT;
Andy Hung2f6e73d2016-04-08 12:12:58 -07001815 ExtendedTimestamp ets;
1816 status_t status = mTrack->getTimestamp(&ets);
1817 if (status == OK || status == WOULD_BLOCK) {
1818 *frameswritten = (uint32_t)ets.mPosition[ExtendedTimestamp::LOCATION_CLIENT];
1819 }
1820 return status;
Marco Nelissen4110c102012-03-29 09:31:28 -07001821}
1822
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001823status_t MediaPlayerService::AudioOutput::setParameters(const String8& keyValuePairs)
1824{
Andy Hungd1c74342015-07-07 16:54:23 -07001825 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001826 if (mTrack == 0) return NO_INIT;
1827 return mTrack->setParameters(keyValuePairs);
1828}
1829
1830String8 MediaPlayerService::AudioOutput::getParameters(const String8& keys)
1831{
Andy Hungd1c74342015-07-07 16:54:23 -07001832 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001833 if (mTrack == 0) return String8::empty();
1834 return mTrack->getParameters(keys);
1835}
1836
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001837void MediaPlayerService::AudioOutput::setAudioAttributes(const audio_attributes_t * attributes) {
Andy Hungd1c74342015-07-07 16:54:23 -07001838 Mutex::Autolock lock(mLock);
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001839 if (attributes == NULL) {
1840 free(mAttributes);
1841 mAttributes = NULL;
1842 } else {
1843 if (mAttributes == NULL) {
1844 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1845 }
1846 memcpy(mAttributes, attributes, sizeof(audio_attributes_t));
François Gaffie58d4be52018-11-06 15:30:12 +01001847 mStreamType = AudioSystem::attributesToStreamType(*attributes);
Eric Laurent43562692015-07-15 16:49:07 -07001848 }
1849}
1850
1851void MediaPlayerService::AudioOutput::setAudioStreamType(audio_stream_type_t streamType)
1852{
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001853 Mutex::Autolock lock(mLock);
Eric Laurent43562692015-07-15 16:49:07 -07001854 // do not allow direct stream type modification if attributes have been set
1855 if (mAttributes == NULL) {
1856 mStreamType = streamType;
1857 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001858}
1859
Andy Hungd1c74342015-07-07 16:54:23 -07001860void MediaPlayerService::AudioOutput::deleteRecycledTrack_l()
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001861{
Andy Hungd1c74342015-07-07 16:54:23 -07001862 ALOGV("deleteRecycledTrack_l");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001863 if (mRecycledTrack != 0) {
1864
1865 if (mCallbackData != NULL) {
1866 mCallbackData->setOutput(NULL);
1867 mCallbackData->endTrackSwitch();
1868 }
1869
1870 if ((mRecycledTrack->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) {
Andy Hunge13f8a62016-03-30 14:20:42 -07001871 int32_t msec = 0;
1872 if (!mRecycledTrack->stopped()) { // check if active
1873 (void)mRecycledTrack->pendingDuration(&msec);
1874 }
1875 mRecycledTrack->stop(); // ensure full data drain
1876 ALOGD("deleting recycled track, waiting for data drain (%d msec)", msec);
1877 if (msec > 0) {
1878 static const int32_t WAIT_LIMIT_MS = 3000;
1879 if (msec > WAIT_LIMIT_MS) {
1880 msec = WAIT_LIMIT_MS;
1881 }
1882 usleep(msec * 1000LL);
1883 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001884 }
1885 // An offloaded track isn't flushed because the STREAM_END is reported
1886 // slightly prematurely to allow time for the gapless track switch
1887 // but this means that if we decide not to recycle the track there
1888 // could be a small amount of residual data still playing. We leave
1889 // AudioFlinger to drain the track.
1890
1891 mRecycledTrack.clear();
Andy Hungd1c74342015-07-07 16:54:23 -07001892 close_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001893 delete mCallbackData;
1894 mCallbackData = NULL;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001895 }
1896}
1897
Andy Hungd1c74342015-07-07 16:54:23 -07001898void MediaPlayerService::AudioOutput::close_l()
1899{
1900 mTrack.clear();
1901}
1902
Andreas Huber20111aa2009-07-14 16:56:47 -07001903status_t MediaPlayerService::AudioOutput::open(
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001904 uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
1905 audio_format_t format, int bufferCount,
Eric Laurent1948eb32012-04-13 16:50:19 -07001906 AudioCallback cb, void *cookie,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001907 audio_output_flags_t flags,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001908 const audio_offload_info_t *offloadInfo,
Andy Hung179652e2015-05-31 22:49:46 -07001909 bool doNotReconnect,
1910 uint32_t suggestedFrameCount)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001911{
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001912 ALOGV("open(%u, %d, 0x%x, 0x%x, %d, %d 0x%x)", sampleRate, channelCount, channelMask,
1913 format, bufferCount, mSessionId, flags);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001914
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001915 // offloading is only supported in callback mode for now.
1916 // offloadInfo must be present if offload flag is set
1917 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) &&
1918 ((cb == NULL) || (offloadInfo == NULL))) {
1919 return BAD_VALUE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001920 }
1921
Andy Hung179652e2015-05-31 22:49:46 -07001922 // compute frame count for the AudioTrack internal buffer
1923 size_t frameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001924 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1925 frameCount = 0; // AudioTrack will get frame count from AudioFlinger
1926 } else {
Andy Hung179652e2015-05-31 22:49:46 -07001927 // try to estimate the buffer processing fetch size from AudioFlinger.
1928 // framesPerBuffer is approximate and generally correct, except when it's not :-).
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001929 uint32_t afSampleRate;
1930 size_t afFrameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001931 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1932 return NO_INIT;
1933 }
1934 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1935 return NO_INIT;
1936 }
Ben Romberger259fb462018-08-07 17:58:53 -07001937 if (afSampleRate == 0) {
1938 return NO_INIT;
1939 }
Andy Hung179652e2015-05-31 22:49:46 -07001940 const size_t framesPerBuffer =
1941 (unsigned long long)sampleRate * afFrameCount / afSampleRate;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001942
Andy Hung179652e2015-05-31 22:49:46 -07001943 if (bufferCount == 0) {
Ben Romberger259fb462018-08-07 17:58:53 -07001944 if (framesPerBuffer == 0) {
1945 return NO_INIT;
1946 }
Andy Hung179652e2015-05-31 22:49:46 -07001947 // use suggestedFrameCount
1948 bufferCount = (suggestedFrameCount + framesPerBuffer - 1) / framesPerBuffer;
1949 }
1950 // Check argument bufferCount against the mininum buffer count
1951 if (bufferCount != 0 && bufferCount < mMinBufferCount) {
1952 ALOGV("bufferCount (%d) increased to %d", bufferCount, mMinBufferCount);
1953 bufferCount = mMinBufferCount;
1954 }
1955 // if frameCount is 0, then AudioTrack will get frame count from AudioFlinger
1956 // which will be the minimum size permitted.
1957 frameCount = bufferCount * framesPerBuffer;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001958 }
Andreas Huber20111aa2009-07-14 16:56:47 -07001959
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001960 if (channelMask == CHANNEL_MASK_USE_CHANNEL_ORDER) {
Glenn Kastenab334fd2012-03-14 12:56:06 -07001961 channelMask = audio_channel_out_mask_from_count(channelCount);
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001962 if (0 == channelMask) {
1963 ALOGE("open() error, can\'t derive mask for %d audio channels", channelCount);
1964 return NO_INIT;
1965 }
1966 }
Eric Laurent1948eb32012-04-13 16:50:19 -07001967
Andy Hungd1c74342015-07-07 16:54:23 -07001968 Mutex::Autolock lock(mLock);
Andy Hung179652e2015-05-31 22:49:46 -07001969 mCallback = cb;
1970 mCallbackCookie = cookie;
1971
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001972 // Check whether we can recycle the track
1973 bool reuse = false;
1974 bool bothOffloaded = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001975
Glenn Kasten2799d742013-05-30 14:33:29 -07001976 if (mRecycledTrack != 0) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001977 // check whether we are switching between two offloaded tracks
1978 bothOffloaded = (flags & mRecycledTrack->getFlags()
1979 & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0;
Marco Nelissen67295b52012-06-11 14:52:53 -07001980
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001981 // check if the existing track can be reused as-is, or if a new track needs to be created.
1982 reuse = true;
1983
Marco Nelissen67295b52012-06-11 14:52:53 -07001984 if ((mCallbackData == NULL && mCallback != NULL) ||
1985 (mCallbackData != NULL && mCallback == NULL)) {
1986 // recycled track uses callbacks but the caller wants to use writes, or vice versa
1987 ALOGV("can't chain callback and write");
1988 reuse = false;
1989 } else if ((mRecycledTrack->getSampleRate() != sampleRate) ||
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001990 (mRecycledTrack->channelCount() != (uint32_t)channelCount) ) {
1991 ALOGV("samplerate, channelcount differ: %u/%u Hz, %u/%d ch",
Marco Nelissen67295b52012-06-11 14:52:53 -07001992 mRecycledTrack->getSampleRate(), sampleRate,
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001993 mRecycledTrack->channelCount(), channelCount);
Marco Nelissen67295b52012-06-11 14:52:53 -07001994 reuse = false;
1995 } else if (flags != mFlags) {
1996 ALOGV("output flags differ %08x/%08x", flags, mFlags);
1997 reuse = false;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001998 } else if (mRecycledTrack->format() != format) {
1999 reuse = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07002000 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002001 } else {
2002 ALOGV("no track available to recycle");
2003 }
2004
2005 ALOGV_IF(bothOffloaded, "both tracks offloaded");
2006
2007 // If we can't recycle and both tracks are offloaded
2008 // we must close the previous output before opening a new one
2009 if (bothOffloaded && !reuse) {
2010 ALOGV("both offloaded and not recycling");
Andy Hungd1c74342015-07-07 16:54:23 -07002011 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002012 }
2013
2014 sp<AudioTrack> t;
2015 CallbackData *newcbd = NULL;
2016
2017 // We don't attempt to create a new track if we are recycling an
2018 // offloaded track. But, if we are recycling a non-offloaded or we
2019 // are switching where one is offloaded and one isn't then we create
2020 // the new track in advance so that we can read additional stream info
2021
2022 if (!(reuse && bothOffloaded)) {
2023 ALOGV("creating new AudioTrack");
2024
2025 if (mCallback != NULL) {
2026 newcbd = new CallbackData(this);
2027 t = new AudioTrack(
2028 mStreamType,
2029 sampleRate,
2030 format,
2031 channelMask,
2032 frameCount,
2033 flags,
2034 CallbackWrapper,
2035 newcbd,
2036 0, // notification frames
2037 mSessionId,
2038 AudioTrack::TRANSFER_CALLBACK,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002039 offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -08002040 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07002041 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07002042 mAttributes,
jiabin156c6872017-10-06 09:47:15 -07002043 doNotReconnect,
2044 1.0f, // default value for maxRequiredSpeed
2045 mSelectedDeviceId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002046 } else {
Andy Hungff874dc2016-04-11 16:49:09 -07002047 // TODO: Due to buffer memory concerns, we use a max target playback speed
2048 // based on mPlaybackRate at the time of open (instead of kMaxRequiredSpeed),
2049 // also clamping the target speed to 1.0 <= targetSpeed <= kMaxRequiredSpeed.
2050 const float targetSpeed =
2051 std::min(std::max(mPlaybackRate.mSpeed, 1.0f), kMaxRequiredSpeed);
2052 ALOGW_IF(targetSpeed != mPlaybackRate.mSpeed,
2053 "track target speed:%f clamped from playback speed:%f",
2054 targetSpeed, mPlaybackRate.mSpeed);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002055 t = new AudioTrack(
2056 mStreamType,
2057 sampleRate,
2058 format,
2059 channelMask,
2060 frameCount,
2061 flags,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002062 NULL, // callback
2063 NULL, // user data
2064 0, // notification frames
2065 mSessionId,
2066 AudioTrack::TRANSFER_DEFAULT,
2067 NULL, // offload info
Marco Nelissend457c972014-02-11 08:47:07 -08002068 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07002069 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07002070 mAttributes,
Andy Hungff874dc2016-04-11 16:49:09 -07002071 doNotReconnect,
jiabin156c6872017-10-06 09:47:15 -07002072 targetSpeed,
2073 mSelectedDeviceId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002074 }
2075
2076 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
2077 ALOGE("Unable to create audio track");
2078 delete newcbd;
Glenn Kasten3e98ecd2015-05-18 13:13:24 -07002079 // t goes out of scope, so reference count drops to zero
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002080 return NO_INIT;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07002081 } else {
2082 // successful AudioTrack initialization implies a legacy stream type was generated
2083 // from the audio attributes
2084 mStreamType = t->streamType();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002085 }
2086 }
2087
2088 if (reuse) {
2089 CHECK(mRecycledTrack != NULL);
2090
2091 if (!bothOffloaded) {
2092 if (mRecycledTrack->frameCount() != t->frameCount()) {
Andy Hung833b4752016-04-04 17:15:48 -07002093 ALOGV("framecount differs: %zu/%zu frames",
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002094 mRecycledTrack->frameCount(), t->frameCount());
2095 reuse = false;
2096 }
2097 }
2098
Marco Nelissen67295b52012-06-11 14:52:53 -07002099 if (reuse) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002100 ALOGV("chaining to next output and recycling track");
Andy Hungd1c74342015-07-07 16:54:23 -07002101 close_l();
Marco Nelissen67295b52012-06-11 14:52:53 -07002102 mTrack = mRecycledTrack;
Glenn Kasten2799d742013-05-30 14:33:29 -07002103 mRecycledTrack.clear();
Marco Nelissen67295b52012-06-11 14:52:53 -07002104 if (mCallbackData != NULL) {
2105 mCallbackData->setOutput(this);
2106 }
Marco Nelissen67295b52012-06-11 14:52:53 -07002107 delete newcbd;
Wei Jiae0bbac92016-07-18 16:04:53 -07002108 return updateTrack();
Marco Nelissen67295b52012-06-11 14:52:53 -07002109 }
Marco Nelissen67295b52012-06-11 14:52:53 -07002110 }
2111
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002112 // we're not going to reuse the track, unblock and flush it
2113 // this was done earlier if both tracks are offloaded
2114 if (!bothOffloaded) {
Andy Hungd1c74342015-07-07 16:54:23 -07002115 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002116 }
2117
2118 CHECK((t != NULL) && ((mCallback == NULL) || (newcbd != NULL)));
2119
Marco Nelissen67295b52012-06-11 14:52:53 -07002120 mCallbackData = newcbd;
Steve Block3856b092011-10-20 11:56:00 +01002121 ALOGV("setVolume");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002122 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07002123
Andy Hung39399b62017-04-21 15:07:45 -07002124 // Restore VolumeShapers for the MediaPlayer in case the track was recreated
2125 // due to an output sink error (e.g. offload to non-offload switch).
2126 mVolumeHandler->forall([&t](const VolumeShaper &shaper) -> VolumeShaper::Status {
2127 sp<VolumeShaper::Operation> operationToEnd =
2128 new VolumeShaper::Operation(shaper.mOperation);
2129 // TODO: Ideally we would restore to the exact xOffset position
2130 // as returned by getVolumeShaperState(), but we don't have that
2131 // information when restoring at the client unless we periodically poll
2132 // the server or create shared memory state.
2133 //
2134 // For now, we simply advance to the end of the VolumeShaper effect
2135 // if it has been started.
2136 if (shaper.isStarted()) {
Andy Hungf3702642017-05-05 17:33:32 -07002137 operationToEnd->setNormalizedTime(1.f);
Andy Hung39399b62017-04-21 15:07:45 -07002138 }
2139 return t->applyVolumeShaper(shaper.mConfiguration, operationToEnd);
Andy Hung4ef88d72017-02-21 19:47:53 -08002140 });
Andy Hung4ef88d72017-02-21 19:47:53 -08002141
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002142 mSampleRateHz = sampleRate;
Preetam Singh Ranawat2e17eef2015-08-12 12:11:46 -07002143 mFlags = flags;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002144 mMsecsPerFrame = 1E3f / (mPlaybackRate.mSpeed * sampleRate);
Andy Hungd1c74342015-07-07 16:54:23 -07002145 mFrameSize = t->frameSize();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002146 mTrack = t;
Eric Laurent2beeb502010-07-16 07:43:46 -07002147
Wei Jiae0bbac92016-07-18 16:04:53 -07002148 return updateTrack();
2149}
2150
2151status_t MediaPlayerService::AudioOutput::updateTrack() {
2152 if (mTrack == NULL) {
2153 return NO_ERROR;
2154 }
2155
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002156 status_t res = NO_ERROR;
Wei Jia0162d002015-06-09 11:59:33 -07002157 // Note some output devices may give us a direct track even though we don't specify it.
2158 // Example: Line application b/17459982.
Wei Jiae0bbac92016-07-18 16:04:53 -07002159 if ((mTrack->getFlags()
2160 & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) {
2161 res = mTrack->setPlaybackRate(mPlaybackRate);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002162 if (res == NO_ERROR) {
Wei Jiae0bbac92016-07-18 16:04:53 -07002163 mTrack->setAuxEffectSendLevel(mSendLevel);
2164 res = mTrack->attachAuxEffect(mAuxEffectId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002165 }
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002166 }
jiabin156c6872017-10-06 09:47:15 -07002167 mTrack->setOutputDevice(mSelectedDeviceId);
2168 if (mDeviceCallbackEnabled) {
2169 mTrack->addAudioDeviceCallback(mDeviceCallback.promote());
2170 }
Wei Jiae0bbac92016-07-18 16:04:53 -07002171 ALOGV("updateTrack() DONE status %d", res);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002172 return res;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002173}
2174
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002175status_t MediaPlayerService::AudioOutput::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002176{
Steve Block3856b092011-10-20 11:56:00 +01002177 ALOGV("start");
Andy Hungd1c74342015-07-07 16:54:23 -07002178 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08002179 if (mCallbackData != NULL) {
2180 mCallbackData->endTrackSwitch();
2181 }
Glenn Kasten2799d742013-05-30 14:33:29 -07002182 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002183 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07002184 mTrack->setAuxEffectSendLevel(mSendLevel);
Andy Hung39399b62017-04-21 15:07:45 -07002185 status_t status = mTrack->start();
2186 if (status == NO_ERROR) {
2187 mVolumeHandler->setStarted();
2188 }
2189 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002190 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002191 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002192}
2193
Marco Nelissen6b74d672012-02-28 16:07:44 -08002194void MediaPlayerService::AudioOutput::setNextOutput(const sp<AudioOutput>& nextOutput) {
Andy Hungd1c74342015-07-07 16:54:23 -07002195 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08002196 mNextOutput = nextOutput;
2197}
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08002198
Marco Nelissen6b74d672012-02-28 16:07:44 -08002199void MediaPlayerService::AudioOutput::switchToNextOutput() {
2200 ALOGV("switchToNextOutput");
Andy Hungd1c74342015-07-07 16:54:23 -07002201
2202 // Try to acquire the callback lock before moving track (without incurring deadlock).
2203 const unsigned kMaxSwitchTries = 100;
2204 Mutex::Autolock lock(mLock);
2205 for (unsigned tries = 0;;) {
2206 if (mTrack == 0) {
2207 return;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002208 }
Andy Hungd1c74342015-07-07 16:54:23 -07002209 if (mNextOutput != NULL && mNextOutput != this) {
2210 if (mCallbackData != NULL) {
2211 // two alternative approaches
2212#if 1
2213 CallbackData *callbackData = mCallbackData;
2214 mLock.unlock();
2215 // proper acquisition sequence
2216 callbackData->lock();
2217 mLock.lock();
2218 // Caution: it is unlikely that someone deleted our callback or changed our target
2219 if (callbackData != mCallbackData || mNextOutput == NULL || mNextOutput == this) {
2220 // fatal if we are starved out.
2221 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2222 "switchToNextOutput() cannot obtain correct lock sequence");
2223 callbackData->unlock();
2224 continue;
2225 }
2226 callbackData->mSwitching = true; // begin track switch
Wei Jiaadee56a2016-08-05 15:40:34 -07002227 callbackData->setOutput(NULL);
Andy Hungd1c74342015-07-07 16:54:23 -07002228#else
2229 // tryBeginTrackSwitch() returns false if the callback has the lock.
2230 if (!mCallbackData->tryBeginTrackSwitch()) {
2231 // fatal if we are starved out.
2232 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2233 "switchToNextOutput() cannot obtain callback lock");
2234 mLock.unlock();
2235 usleep(5 * 1000 /* usec */); // allow callback to use AudioOutput
2236 mLock.lock();
2237 continue;
2238 }
2239#endif
2240 }
2241
2242 Mutex::Autolock nextLock(mNextOutput->mLock);
2243
2244 // If the next output track is not NULL, then it has been
2245 // opened already for playback.
2246 // This is possible even without the next player being started,
2247 // for example, the next player could be prepared and seeked.
2248 //
2249 // Presuming it isn't advisable to force the track over.
2250 if (mNextOutput->mTrack == NULL) {
2251 ALOGD("Recycling track for gapless playback");
2252 delete mNextOutput->mCallbackData;
2253 mNextOutput->mCallbackData = mCallbackData;
2254 mNextOutput->mRecycledTrack = mTrack;
2255 mNextOutput->mSampleRateHz = mSampleRateHz;
2256 mNextOutput->mMsecsPerFrame = mMsecsPerFrame;
Andy Hungd1c74342015-07-07 16:54:23 -07002257 mNextOutput->mFlags = mFlags;
2258 mNextOutput->mFrameSize = mFrameSize;
2259 close_l();
2260 mCallbackData = NULL; // destruction handled by mNextOutput
2261 } else {
2262 ALOGW("Ignoring gapless playback because next player has already started");
2263 // remove track in case resource needed for future players.
2264 if (mCallbackData != NULL) {
2265 mCallbackData->endTrackSwitch(); // release lock for callbacks before close.
2266 }
2267 close_l();
2268 }
2269 }
2270 break;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002271 }
2272}
2273
Wei Jia7d3f4df2015-03-03 15:28:00 -08002274ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002275{
Andy Hungd1c74342015-07-07 16:54:23 -07002276 Mutex::Autolock lock(mLock);
Glenn Kastenadad3d72014-02-21 14:51:43 -08002277 LOG_ALWAYS_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
Andreas Huber20111aa2009-07-14 16:56:47 -07002278
Steve Block3856b092011-10-20 11:56:00 +01002279 //ALOGV("write(%p, %u)", buffer, size);
Glenn Kasten2799d742013-05-30 14:33:29 -07002280 if (mTrack != 0) {
Andy Hung2f6e73d2016-04-08 12:12:58 -07002281 return mTrack->write(buffer, size, blocking);
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07002282 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002283 return NO_INIT;
2284}
2285
2286void MediaPlayerService::AudioOutput::stop()
2287{
Steve Block3856b092011-10-20 11:56:00 +01002288 ALOGV("stop");
Andy Hungd1c74342015-07-07 16:54:23 -07002289 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002290 if (mTrack != 0) mTrack->stop();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002291}
2292
2293void MediaPlayerService::AudioOutput::flush()
2294{
Steve Block3856b092011-10-20 11:56:00 +01002295 ALOGV("flush");
Andy Hungd1c74342015-07-07 16:54:23 -07002296 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002297 if (mTrack != 0) mTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002298}
2299
2300void MediaPlayerService::AudioOutput::pause()
2301{
Steve Block3856b092011-10-20 11:56:00 +01002302 ALOGV("pause");
Andy Hungd1c74342015-07-07 16:54:23 -07002303 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002304 if (mTrack != 0) mTrack->pause();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002305}
2306
2307void MediaPlayerService::AudioOutput::close()
2308{
Steve Block3856b092011-10-20 11:56:00 +01002309 ALOGV("close");
Erik Wolsheimer7845a1f2015-10-30 12:07:52 -07002310 sp<AudioTrack> track;
2311 {
2312 Mutex::Autolock lock(mLock);
2313 track = mTrack;
2314 close_l(); // clears mTrack
2315 }
2316 // destruction of the track occurs outside of mutex.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002317}
2318
2319void MediaPlayerService::AudioOutput::setVolume(float left, float right)
2320{
Steve Block3856b092011-10-20 11:56:00 +01002321 ALOGV("setVolume(%f, %f)", left, right);
Andy Hungd1c74342015-07-07 16:54:23 -07002322 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002323 mLeftVolume = left;
2324 mRightVolume = right;
Glenn Kasten2799d742013-05-30 14:33:29 -07002325 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002326 mTrack->setVolume(left, right);
2327 }
2328}
2329
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002330status_t MediaPlayerService::AudioOutput::setPlaybackRate(const AudioPlaybackRate &rate)
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002331{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002332 ALOGV("setPlaybackRate(%f %f %d %d)",
2333 rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Andy Hungd1c74342015-07-07 16:54:23 -07002334 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002335 if (mTrack == 0) {
2336 // remember rate so that we can set it when the track is opened
2337 mPlaybackRate = rate;
2338 return OK;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002339 }
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002340 status_t res = mTrack->setPlaybackRate(rate);
2341 if (res != NO_ERROR) {
2342 return res;
2343 }
2344 // rate.mSpeed is always greater than 0 if setPlaybackRate succeeded
2345 CHECK_GT(rate.mSpeed, 0.f);
2346 mPlaybackRate = rate;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002347 if (mSampleRateHz != 0) {
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002348 mMsecsPerFrame = 1E3f / (rate.mSpeed * mSampleRateHz);
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002349 }
2350 return res;
2351}
2352
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002353status_t MediaPlayerService::AudioOutput::getPlaybackRate(AudioPlaybackRate *rate)
2354{
2355 ALOGV("setPlaybackRate");
Andy Hungd1c74342015-07-07 16:54:23 -07002356 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002357 if (mTrack == 0) {
2358 return NO_INIT;
2359 }
2360 *rate = mTrack->getPlaybackRate();
2361 return NO_ERROR;
2362}
2363
Eric Laurent2beeb502010-07-16 07:43:46 -07002364status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
2365{
Steve Block3856b092011-10-20 11:56:00 +01002366 ALOGV("setAuxEffectSendLevel(%f)", level);
Andy Hungd1c74342015-07-07 16:54:23 -07002367 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002368 mSendLevel = level;
Glenn Kasten2799d742013-05-30 14:33:29 -07002369 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002370 return mTrack->setAuxEffectSendLevel(level);
2371 }
2372 return NO_ERROR;
2373}
2374
2375status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
2376{
Steve Block3856b092011-10-20 11:56:00 +01002377 ALOGV("attachAuxEffect(%d)", effectId);
Andy Hungd1c74342015-07-07 16:54:23 -07002378 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002379 mAuxEffectId = effectId;
Glenn Kasten2799d742013-05-30 14:33:29 -07002380 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002381 return mTrack->attachAuxEffect(effectId);
2382 }
2383 return NO_ERROR;
2384}
2385
jiabin156c6872017-10-06 09:47:15 -07002386status_t MediaPlayerService::AudioOutput::setOutputDevice(audio_port_handle_t deviceId)
2387{
2388 ALOGV("setOutputDevice(%d)", deviceId);
2389 Mutex::Autolock lock(mLock);
2390 mSelectedDeviceId = deviceId;
2391 if (mTrack != 0) {
2392 return mTrack->setOutputDevice(deviceId);
2393 }
2394 return NO_ERROR;
2395}
2396
2397status_t MediaPlayerService::AudioOutput::getRoutedDeviceId(audio_port_handle_t* deviceId)
2398{
2399 ALOGV("getRoutedDeviceId");
2400 Mutex::Autolock lock(mLock);
2401 if (mTrack != 0) {
jiabin161b64f2017-11-17 09:31:48 -08002402 mRoutedDeviceId = mTrack->getRoutedDeviceId();
jiabin156c6872017-10-06 09:47:15 -07002403 }
jiabin161b64f2017-11-17 09:31:48 -08002404 *deviceId = mRoutedDeviceId;
2405 return NO_ERROR;
jiabin156c6872017-10-06 09:47:15 -07002406}
2407
2408status_t MediaPlayerService::AudioOutput::enableAudioDeviceCallback(bool enabled)
2409{
2410 ALOGV("enableAudioDeviceCallback, %d", enabled);
2411 Mutex::Autolock lock(mLock);
2412 mDeviceCallbackEnabled = enabled;
2413 if (mTrack != 0) {
2414 status_t status;
2415 if (enabled) {
2416 status = mTrack->addAudioDeviceCallback(mDeviceCallback.promote());
2417 } else {
2418 status = mTrack->removeAudioDeviceCallback(mDeviceCallback.promote());
2419 }
2420 return status;
2421 }
2422 return NO_ERROR;
2423}
2424
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002425VolumeShaper::Status MediaPlayerService::AudioOutput::applyVolumeShaper(
2426 const sp<VolumeShaper::Configuration>& configuration,
2427 const sp<VolumeShaper::Operation>& operation)
2428{
2429 Mutex::Autolock lock(mLock);
2430 ALOGV("AudioOutput::applyVolumeShaper");
Andy Hung4ef88d72017-02-21 19:47:53 -08002431
Andy Hung4ef88d72017-02-21 19:47:53 -08002432 mVolumeHandler->setIdIfNecessary(configuration);
Andy Hung39399b62017-04-21 15:07:45 -07002433
2434 VolumeShaper::Status status;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002435 if (mTrack != 0) {
Andy Hung39399b62017-04-21 15:07:45 -07002436 status = mTrack->applyVolumeShaper(configuration, operation);
2437 if (status >= 0) {
2438 (void)mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hungf3702642017-05-05 17:33:32 -07002439 if (mTrack->isPlaying()) { // match local AudioTrack to properly restore.
2440 mVolumeHandler->setStarted();
2441 }
Andy Hung39399b62017-04-21 15:07:45 -07002442 }
Andy Hung4ef88d72017-02-21 19:47:53 -08002443 } else {
Andy Hungc01eddb2017-07-21 16:42:41 -07002444 // VolumeShapers are not affected when a track moves between players for
2445 // gapless playback (setNextMediaPlayer).
2446 // We forward VolumeShaper operations that do not change configuration
2447 // to the new player so that unducking may occur as expected.
2448 // Unducking is an idempotent operation, same if applied back-to-back.
2449 if (configuration->getType() == VolumeShaper::Configuration::TYPE_ID
2450 && mNextOutput != nullptr) {
2451 ALOGV("applyVolumeShaper: Attempting to forward missed operation: %s %s",
2452 configuration->toString().c_str(), operation->toString().c_str());
2453 Mutex::Autolock nextLock(mNextOutput->mLock);
2454
2455 // recycled track should be forwarded from this AudioSink by switchToNextOutput
2456 sp<AudioTrack> track = mNextOutput->mRecycledTrack;
2457 if (track != nullptr) {
2458 ALOGD("Forward VolumeShaper operation to recycled track %p", track.get());
2459 (void)track->applyVolumeShaper(configuration, operation);
2460 } else {
2461 // There is a small chance that the unduck occurs after the next
2462 // player has already started, but before it is registered to receive
2463 // the unduck command.
2464 track = mNextOutput->mTrack;
2465 if (track != nullptr) {
2466 ALOGD("Forward VolumeShaper operation to track %p", track.get());
2467 (void)track->applyVolumeShaper(configuration, operation);
2468 }
2469 }
2470 }
Andy Hung39399b62017-04-21 15:07:45 -07002471 status = mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002472 }
Andy Hung39399b62017-04-21 15:07:45 -07002473 return status;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002474}
2475
2476sp<VolumeShaper::State> MediaPlayerService::AudioOutput::getVolumeShaperState(int id)
2477{
2478 Mutex::Autolock lock(mLock);
2479 if (mTrack != 0) {
2480 return mTrack->getVolumeShaperState(id);
Andy Hung4ef88d72017-02-21 19:47:53 -08002481 } else {
2482 return mVolumeHandler->getVolumeShaperState(id);
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002483 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002484}
2485
Andreas Huber20111aa2009-07-14 16:56:47 -07002486// static
2487void MediaPlayerService::AudioOutput::CallbackWrapper(
Glenn Kastend217a8c2011-06-01 15:20:35 -07002488 int event, void *cookie, void *info) {
Steve Block3856b092011-10-20 11:56:00 +01002489 //ALOGV("callbackwrapper");
Marco Nelissen6b74d672012-02-28 16:07:44 -08002490 CallbackData *data = (CallbackData*)cookie;
Andy Hungd1c74342015-07-07 16:54:23 -07002491 // lock to ensure we aren't caught in the middle of a track switch.
Marco Nelissen6b74d672012-02-28 16:07:44 -08002492 data->lock();
2493 AudioOutput *me = data->getOutput();
Andreas Huber20111aa2009-07-14 16:56:47 -07002494 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002495 if (me == NULL) {
2496 // no output set, likely because the track was scheduled to be reused
2497 // by another player, but the format turned out to be incompatible.
2498 data->unlock();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002499 if (buffer != NULL) {
2500 buffer->size = 0;
2501 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08002502 return;
2503 }
Andreas Huber20111aa2009-07-14 16:56:47 -07002504
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002505 switch(event) {
2506 case AudioTrack::EVENT_MORE_DATA: {
2507 size_t actualSize = (*me->mCallback)(
2508 me, buffer->raw, buffer->size, me->mCallbackCookie,
2509 CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002510
Andy Hung719b46b2015-05-31 22:18:25 -07002511 // Log when no data is returned from the callback.
2512 // (1) We may have no data (especially with network streaming sources).
2513 // (2) We may have reached the EOS and the audio track is not stopped yet.
2514 // Note that AwesomePlayer/AudioPlayer will only return zero size when it reaches the EOS.
2515 // NuPlayerRenderer will return zero when it doesn't have data (it doesn't block to fill).
2516 //
2517 // This is a benign busy-wait, with the next data request generated 10 ms or more later;
2518 // nevertheless for power reasons, we don't want to see too many of these.
Andreas Huber2e8ffaf2010-02-18 16:45:13 -08002519
Andy Hung719b46b2015-05-31 22:18:25 -07002520 ALOGV_IF(actualSize == 0 && buffer->size > 0, "callbackwrapper: empty buffer returned");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002521
2522 buffer->size = actualSize;
2523 } break;
2524
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002525 case AudioTrack::EVENT_STREAM_END:
Andy Hung719b46b2015-05-31 22:18:25 -07002526 // currently only occurs for offloaded callbacks
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002527 ALOGV("callbackwrapper: deliver EVENT_STREAM_END");
2528 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2529 me->mCallbackCookie, CB_EVENT_STREAM_END);
2530 break;
2531
2532 case AudioTrack::EVENT_NEW_IAUDIOTRACK :
2533 ALOGV("callbackwrapper: deliver EVENT_TEAR_DOWN");
2534 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2535 me->mCallbackCookie, CB_EVENT_TEAR_DOWN);
2536 break;
2537
Glenn Kasten421743b2015-06-01 08:18:08 -07002538 case AudioTrack::EVENT_UNDERRUN:
Andy Hung719b46b2015-05-31 22:18:25 -07002539 // This occurs when there is no data available, typically
Glenn Kasten421743b2015-06-01 08:18:08 -07002540 // when there is a failure to supply data to the AudioTrack. It can also
2541 // occur in non-offloaded mode when the audio device comes out of standby.
2542 //
Andy Hung719b46b2015-05-31 22:18:25 -07002543 // If an AudioTrack underruns it outputs silence. Since this happens suddenly
2544 // it may sound like an audible pop or glitch.
2545 //
2546 // The underrun event is sent once per track underrun; the condition is reset
2547 // when more data is sent to the AudioTrack.
Eric Laurente93cc032016-05-05 10:15:10 -07002548 ALOGD("callbackwrapper: EVENT_UNDERRUN (discarded)");
Glenn Kasten421743b2015-06-01 08:18:08 -07002549 break;
2550
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002551 default:
2552 ALOGE("received unknown event type: %d inside CallbackWrapper !", event);
Andreas Huber51c1e0e2011-04-04 11:43:40 -07002553 }
2554
Marco Nelissen6b74d672012-02-28 16:07:44 -08002555 data->unlock();
Andreas Huber20111aa2009-07-14 16:56:47 -07002556}
2557
Glenn Kastend848eb42016-03-08 13:42:11 -08002558audio_session_t MediaPlayerService::AudioOutput::getSessionId() const
Eric Laurent8c563ed2010-10-07 18:23:03 -07002559{
Andy Hungd1c74342015-07-07 16:54:23 -07002560 Mutex::Autolock lock(mLock);
Eric Laurent8c563ed2010-10-07 18:23:03 -07002561 return mSessionId;
2562}
2563
Eric Laurent6f59db12013-07-26 17:16:50 -07002564uint32_t MediaPlayerService::AudioOutput::getSampleRate() const
2565{
Andy Hungd1c74342015-07-07 16:54:23 -07002566 Mutex::Autolock lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -07002567 if (mTrack == 0) return 0;
2568 return mTrack->getSampleRate();
2569}
2570
Andy Hungf2c87b32016-04-07 19:49:29 -07002571int64_t MediaPlayerService::AudioOutput::getBufferDurationInUs() const
2572{
2573 Mutex::Autolock lock(mLock);
2574 if (mTrack == 0) {
2575 return 0;
2576 }
2577 int64_t duration;
2578 if (mTrack->getBufferDurationInUs(&duration) != OK) {
2579 return 0;
2580 }
2581 return duration;
2582}
2583
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002584////////////////////////////////////////////////////////////////////////////////
2585
2586struct CallbackThread : public Thread {
2587 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
2588 MediaPlayerBase::AudioSink::AudioCallback cb,
2589 void *cookie);
2590
2591protected:
2592 virtual ~CallbackThread();
2593
2594 virtual bool threadLoop();
2595
2596private:
2597 wp<MediaPlayerBase::AudioSink> mSink;
2598 MediaPlayerBase::AudioSink::AudioCallback mCallback;
2599 void *mCookie;
2600 void *mBuffer;
2601 size_t mBufferSize;
2602
2603 CallbackThread(const CallbackThread &);
2604 CallbackThread &operator=(const CallbackThread &);
2605};
2606
2607CallbackThread::CallbackThread(
2608 const wp<MediaPlayerBase::AudioSink> &sink,
2609 MediaPlayerBase::AudioSink::AudioCallback cb,
2610 void *cookie)
2611 : mSink(sink),
2612 mCallback(cb),
2613 mCookie(cookie),
2614 mBuffer(NULL),
2615 mBufferSize(0) {
2616}
2617
2618CallbackThread::~CallbackThread() {
2619 if (mBuffer) {
2620 free(mBuffer);
2621 mBuffer = NULL;
2622 }
2623}
2624
2625bool CallbackThread::threadLoop() {
2626 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
2627 if (sink == NULL) {
2628 return false;
2629 }
2630
2631 if (mBuffer == NULL) {
2632 mBufferSize = sink->bufferSize();
2633 mBuffer = malloc(mBufferSize);
2634 }
2635
2636 size_t actualSize =
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002637 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie,
2638 MediaPlayerBase::AudioSink::CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002639
2640 if (actualSize > 0) {
2641 sink->write(mBuffer, actualSize);
Andy Hunga31335a2014-08-20 17:37:59 -07002642 // Could return false on sink->write() error or short count.
2643 // Not necessarily appropriate but would work for AudioCache behavior.
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002644 }
2645
2646 return true;
2647}
2648
2649////////////////////////////////////////////////////////////////////////////////
2650
Chong Zhange5b9b692017-05-11 11:44:56 -07002651void MediaPlayerService::addBatteryData(uint32_t params) {
2652 mBatteryTracker.addBatteryData(params);
2653}
2654
2655status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
2656 return mBatteryTracker.pullBatteryData(reply);
2657}
2658
2659MediaPlayerService::BatteryTracker::BatteryTracker() {
2660 mBatteryAudio.refCount = 0;
2661 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2662 mBatteryAudio.deviceOn[i] = 0;
2663 mBatteryAudio.lastTime[i] = 0;
2664 mBatteryAudio.totalTime[i] = 0;
2665 }
2666 // speaker is on by default
2667 mBatteryAudio.deviceOn[SPEAKER] = 1;
2668
2669 // reset battery stats
2670 // if the mediaserver has crashed, battery stats could be left
2671 // in bad state, reset the state upon service start.
2672 BatteryNotifier::getInstance().noteResetVideo();
2673}
2674
2675void MediaPlayerService::BatteryTracker::addBatteryData(uint32_t params)
Gloria Wang7cf180c2011-02-19 18:37:57 -08002676{
2677 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002678
2679 int32_t time = systemTime() / 1000000L;
2680
2681 // change audio output devices. This notification comes from AudioFlinger
2682 if ((params & kBatteryDataSpeakerOn)
2683 || (params & kBatteryDataOtherAudioDeviceOn)) {
2684
2685 int deviceOn[NUM_AUDIO_DEVICES];
2686 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2687 deviceOn[i] = 0;
2688 }
2689
2690 if ((params & kBatteryDataSpeakerOn)
2691 && (params & kBatteryDataOtherAudioDeviceOn)) {
2692 deviceOn[SPEAKER_AND_OTHER] = 1;
2693 } else if (params & kBatteryDataSpeakerOn) {
2694 deviceOn[SPEAKER] = 1;
2695 } else {
2696 deviceOn[OTHER_AUDIO_DEVICE] = 1;
2697 }
2698
2699 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2700 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
2701
2702 if (mBatteryAudio.refCount > 0) { // if playing audio
2703 if (!deviceOn[i]) {
2704 mBatteryAudio.lastTime[i] += time;
2705 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2706 mBatteryAudio.lastTime[i] = 0;
2707 } else {
2708 mBatteryAudio.lastTime[i] = 0 - time;
2709 }
2710 }
2711
2712 mBatteryAudio.deviceOn[i] = deviceOn[i];
2713 }
2714 }
2715 return;
2716 }
2717
Marco Nelissenb7848f12014-12-04 08:57:56 -08002718 // an audio stream is started
Gloria Wang9ee159b2011-02-24 14:51:45 -08002719 if (params & kBatteryDataAudioFlingerStart) {
2720 // record the start time only if currently no other audio
2721 // is being played
2722 if (mBatteryAudio.refCount == 0) {
2723 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2724 if (mBatteryAudio.deviceOn[i]) {
2725 mBatteryAudio.lastTime[i] -= time;
2726 }
2727 }
2728 }
2729
2730 mBatteryAudio.refCount ++;
2731 return;
2732
2733 } else if (params & kBatteryDataAudioFlingerStop) {
2734 if (mBatteryAudio.refCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002735 ALOGW("Battery track warning: refCount is <= 0");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002736 return;
2737 }
2738
2739 // record the stop time only if currently this is the only
2740 // audio being played
2741 if (mBatteryAudio.refCount == 1) {
2742 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2743 if (mBatteryAudio.deviceOn[i]) {
2744 mBatteryAudio.lastTime[i] += time;
2745 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2746 mBatteryAudio.lastTime[i] = 0;
2747 }
2748 }
2749 }
2750
2751 mBatteryAudio.refCount --;
2752 return;
2753 }
2754
Andy Hung1afd0982016-11-08 16:13:44 -08002755 uid_t uid = IPCThreadState::self()->getCallingUid();
Gloria Wang7cf180c2011-02-19 18:37:57 -08002756 if (uid == AID_MEDIA) {
2757 return;
2758 }
2759 int index = mBatteryData.indexOfKey(uid);
Gloria Wang7cf180c2011-02-19 18:37:57 -08002760
2761 if (index < 0) { // create a new entry for this UID
2762 BatteryUsageInfo info;
2763 info.audioTotalTime = 0;
2764 info.videoTotalTime = 0;
2765 info.audioLastTime = 0;
2766 info.videoLastTime = 0;
2767 info.refCount = 0;
2768
Gloria Wang9ee159b2011-02-24 14:51:45 -08002769 if (mBatteryData.add(uid, info) == NO_MEMORY) {
Steve Block29357bc2012-01-06 19:20:56 +00002770 ALOGE("Battery track error: no memory for new app");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002771 return;
2772 }
Gloria Wang7cf180c2011-02-19 18:37:57 -08002773 }
2774
2775 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
2776
2777 if (params & kBatteryDataCodecStarted) {
2778 if (params & kBatteryDataTrackAudio) {
2779 info.audioLastTime -= time;
2780 info.refCount ++;
2781 }
2782 if (params & kBatteryDataTrackVideo) {
2783 info.videoLastTime -= time;
2784 info.refCount ++;
2785 }
2786 } else {
2787 if (info.refCount == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002788 ALOGW("Battery track warning: refCount is already 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002789 return;
2790 } else if (info.refCount < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00002791 ALOGE("Battery track error: refCount < 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002792 mBatteryData.removeItem(uid);
2793 return;
2794 }
2795
2796 if (params & kBatteryDataTrackAudio) {
2797 info.audioLastTime += time;
2798 info.refCount --;
2799 }
2800 if (params & kBatteryDataTrackVideo) {
2801 info.videoLastTime += time;
2802 info.refCount --;
2803 }
2804
2805 // no stream is being played by this UID
2806 if (info.refCount == 0) {
2807 info.audioTotalTime += info.audioLastTime;
2808 info.audioLastTime = 0;
2809 info.videoTotalTime += info.videoLastTime;
2810 info.videoLastTime = 0;
2811 }
2812 }
2813}
2814
Chong Zhange5b9b692017-05-11 11:44:56 -07002815status_t MediaPlayerService::BatteryTracker::pullBatteryData(Parcel* reply) {
Gloria Wang7cf180c2011-02-19 18:37:57 -08002816 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002817
2818 // audio output devices usage
2819 int32_t time = systemTime() / 1000000L; //in ms
2820 int32_t totalTime;
2821
2822 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2823 totalTime = mBatteryAudio.totalTime[i];
2824
2825 if (mBatteryAudio.deviceOn[i]
2826 && (mBatteryAudio.lastTime[i] != 0)) {
2827 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
2828 totalTime += tmpTime;
2829 }
2830
2831 reply->writeInt32(totalTime);
2832 // reset the total time
2833 mBatteryAudio.totalTime[i] = 0;
2834 }
2835
2836 // codec usage
Gloria Wang7cf180c2011-02-19 18:37:57 -08002837 BatteryUsageInfo info;
2838 int size = mBatteryData.size();
2839
2840 reply->writeInt32(size);
2841 int i = 0;
2842
2843 while (i < size) {
2844 info = mBatteryData.valueAt(i);
2845
2846 reply->writeInt32(mBatteryData.keyAt(i)); //UID
2847 reply->writeInt32(info.audioTotalTime);
2848 reply->writeInt32(info.videoTotalTime);
2849
2850 info.audioTotalTime = 0;
2851 info.videoTotalTime = 0;
2852
2853 // remove the UID entry where no stream is being played
2854 if (info.refCount <= 0) {
2855 mBatteryData.removeItemsAt(i);
2856 size --;
2857 i --;
2858 }
2859 i++;
2860 }
2861 return NO_ERROR;
2862}
nikoa64c8c72009-07-20 15:07:26 -07002863} // namespace android