blob: 84abfee6208f964084a4be1c6db8285b524e867d [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
Mathias Agopian75624082009-05-19 19:08:10 -070037#include <binder/IPCThreadState.h>
38#include <binder/IServiceManager.h>
39#include <binder/MemoryHeapBase.h>
40#include <binder/MemoryBase.h>
Mathias Agopianb1e7cd12013-02-14 17:11:27 -080041#include <gui/Surface.h>
Nicolas Catania1d187f12009-05-12 23:25:55 -070042#include <utils/Errors.h> // for status_t
43#include <utils/String8.h>
Marco Nelissen10dbb8e2009-09-20 10:42:13 -070044#include <utils/SystemClock.h>
Lajos Molnar06ad1522014-08-28 07:27:44 -070045#include <utils/Timers.h>
Nicolas Catania1d187f12009-05-12 23:25:55 -070046#include <utils/Vector.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080047
Eric Laurent43562692015-07-15 16:49:07 -070048#include <media/AudioPolicyHelper.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080049#include <media/IMediaHTTPService.h>
Jeff Brown2013a542012-09-04 21:38:42 -070050#include <media/IRemoteDisplay.h>
51#include <media/IRemoteDisplayClient.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080052#include <media/MediaPlayerInterface.h>
53#include <media/mediarecorder.h>
54#include <media/MediaMetadataRetrieverInterface.h>
nikoa64c8c72009-07-20 15:07:26 -070055#include <media/Metadata.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080056#include <media/AudioTrack.h>
James Dong8635b7b2011-03-14 17:01:38 -070057#include <media/MemoryLeakTrackUtil.h>
Dongwon Kangd91dc5a2017-10-10 00:07:09 -070058#include <media/stagefright/InterfaceUtils.h>
Lajos Molnar1381d4b2014-08-07 15:18:35 -070059#include <media/stagefright/MediaCodecList.h>
Eric Laurent9cb839a2011-09-27 09:48:56 -070060#include <media/stagefright/MediaErrors.h>
Marco Nelissen83b0fd92015-09-16 13:48:07 -070061#include <media/stagefright/Utils.h>
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +010062#include <media/stagefright/foundation/ADebug.h>
Marco Nelissenf09611f2015-02-13 14:12:42 -080063#include <media/stagefright/foundation/ALooperRoster.h>
Chong Zhang181fd9b2017-02-16 15:53:03 -080064#include <media/stagefright/SurfaceUtils.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070065#include <mediautils/BatteryNotifier.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080066
Andy Hung53541292016-04-13 16:48:51 -070067#include <memunreachable/memunreachable.h>
Dima Zavin64760242011-05-11 14:15:23 -070068#include <system/audio.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070069
Gloria Wang7cf180c2011-02-19 18:37:57 -080070#include <private/android_filesystem_config.h>
71
James Dong559bf282012-03-28 10:29:14 -070072#include "ActivityManager.h"
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080073#include "MediaRecorderClient.h"
74#include "MediaPlayerService.h"
75#include "MetadataRetrieverClient.h"
John Grossman44a7e422012-06-21 17:29:24 -070076#include "MediaPlayerFactory.h"
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080077
Nicolas Catania14d27472009-07-13 14:37:49 -070078#include "TestPlayerStub.h"
Andreas Huberf9334412010-12-15 15:17:42 -080079#include "nuplayer/NuPlayerDriver.h"
Andreas Huber20111aa2009-07-14 16:56:47 -070080
Andreas Huberb7319a72013-05-29 14:20:52 -070081#include "HTTPBase.h"
Andreas Hubered3e3e02012-03-26 11:13:27 -070082
Wei Jia502c2f42017-07-13 17:47:56 -070083static const int kDumpLockRetries = 50;
84static const int kDumpLockSleepUs = 20000;
85
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070086namespace {
nikoa64c8c72009-07-20 15:07:26 -070087using android::media::Metadata;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070088using android::status_t;
89using android::OK;
90using android::BAD_VALUE;
91using android::NOT_ENOUGH_DATA;
92using android::Parcel;
Ivan Lozano8cf3a072017-08-09 09:01:33 -070093using android::media::VolumeShaper;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070094
95// Max number of entries in the filter.
96const int kMaxFilterSize = 64; // I pulled that out of thin air.
97
Andy Hungff874dc2016-04-11 16:49:09 -070098const float kMaxRequiredSpeed = 8.0f; // for PCM tracks allow up to 8x speedup.
99
nikoa64c8c72009-07-20 15:07:26 -0700100// FIXME: Move all the metadata related function in the Metadata.cpp
nikod608a812009-07-16 16:39:53 -0700101
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700102
103// Unmarshall a filter from a Parcel.
104// Filter format in a parcel:
105//
106// 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
107// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
108// | number of entries (n) |
109// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
110// | metadata type 1 |
111// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
112// | metadata type 2 |
113// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
114// ....
115// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
116// | metadata type n |
117// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
118//
119// @param p Parcel that should start with a filter.
120// @param[out] filter On exit contains the list of metadata type to be
121// filtered.
122// @param[out] status On exit contains the status code to be returned.
123// @return true if the parcel starts with a valid filter.
124bool unmarshallFilter(const Parcel& p,
nikoa64c8c72009-07-20 15:07:26 -0700125 Metadata::Filter *filter,
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700126 status_t *status)
127{
Nicolas Catania48290382009-07-10 13:53:06 -0700128 int32_t val;
129 if (p.readInt32(&val) != OK)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700130 {
Steve Block29357bc2012-01-06 19:20:56 +0000131 ALOGE("Failed to read filter's length");
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700132 *status = NOT_ENOUGH_DATA;
133 return false;
134 }
135
Nicolas Catania48290382009-07-10 13:53:06 -0700136 if( val > kMaxFilterSize || val < 0)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700137 {
Steve Block29357bc2012-01-06 19:20:56 +0000138 ALOGE("Invalid filter len %d", val);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700139 *status = BAD_VALUE;
140 return false;
141 }
142
Nicolas Catania48290382009-07-10 13:53:06 -0700143 const size_t num = val;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700144
145 filter->clear();
Nicolas Catania48290382009-07-10 13:53:06 -0700146 filter->setCapacity(num);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700147
nikoa64c8c72009-07-20 15:07:26 -0700148 size_t size = num * sizeof(Metadata::Type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700149
Nicolas Catania48290382009-07-10 13:53:06 -0700150
151 if (p.dataAvail() < size)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700152 {
Andy Hung833b4752016-04-04 17:15:48 -0700153 ALOGE("Filter too short expected %zu but got %zu", size, p.dataAvail());
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700154 *status = NOT_ENOUGH_DATA;
155 return false;
156 }
157
nikoa64c8c72009-07-20 15:07:26 -0700158 const Metadata::Type *data =
159 static_cast<const Metadata::Type*>(p.readInplace(size));
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700160
Nicolas Catania48290382009-07-10 13:53:06 -0700161 if (NULL == data)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700162 {
Steve Block29357bc2012-01-06 19:20:56 +0000163 ALOGE("Filter had no data");
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700164 *status = BAD_VALUE;
165 return false;
166 }
167
168 // TODO: The stl impl of vector would be more efficient here
169 // because it degenerates into a memcpy on pod types. Try to
170 // replace later or use stl::set.
Nicolas Catania48290382009-07-10 13:53:06 -0700171 for (size_t i = 0; i < num; ++i)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700172 {
Nicolas Catania48290382009-07-10 13:53:06 -0700173 filter->add(*data);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700174 ++data;
175 }
176 *status = OK;
177 return true;
178}
179
Nicolas Catania48290382009-07-10 13:53:06 -0700180// @param filter Of metadata type.
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700181// @param val To be searched.
182// @return true if a match was found.
nikoa64c8c72009-07-20 15:07:26 -0700183bool findMetadata(const Metadata::Filter& filter, const int32_t val)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700184{
185 // Deal with empty and ANY right away
186 if (filter.isEmpty()) return false;
nikoa64c8c72009-07-20 15:07:26 -0700187 if (filter[0] == Metadata::kAny) return true;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700188
Nicolas Catania48290382009-07-10 13:53:06 -0700189 return filter.indexOf(val) >= 0;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700190}
191
192} // anonymous namespace
193
194
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700195namespace {
196using android::Parcel;
197using android::String16;
198
199// marshalling tag indicating flattened utf16 tags
200// keep in sync with frameworks/base/media/java/android/media/AudioAttributes.java
201const int32_t kAudioAttributesMarshallTagFlattenTags = 1;
202
203// Audio attributes format in a parcel:
204//
205// 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
206// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
207// | usage |
208// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
209// | content_type |
210// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Hyejin Kim4f418f92014-09-05 15:50:03 +0900211// | source |
212// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700213// | flags |
214// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
215// | kAudioAttributesMarshallTagFlattenTags | // ignore tags if not found
216// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
217// | flattened tags in UTF16 |
218// | ... |
219// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
220//
221// @param p Parcel that contains audio attributes.
222// @param[out] attributes On exit points to an initialized audio_attributes_t structure
223// @param[out] status On exit contains the status code to be returned.
224void unmarshallAudioAttributes(const Parcel& parcel, audio_attributes_t *attributes)
225{
226 attributes->usage = (audio_usage_t) parcel.readInt32();
227 attributes->content_type = (audio_content_type_t) parcel.readInt32();
Hyejin Kim4f418f92014-09-05 15:50:03 +0900228 attributes->source = (audio_source_t) parcel.readInt32();
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700229 attributes->flags = (audio_flags_mask_t) parcel.readInt32();
230 const bool hasFlattenedTag = (parcel.readInt32() == kAudioAttributesMarshallTagFlattenTags);
231 if (hasFlattenedTag) {
232 // the tags are UTF16, convert to UTF8
233 String16 tags = parcel.readString16();
234 ssize_t realTagSize = utf16_to_utf8_length(tags.string(), tags.size());
235 if (realTagSize <= 0) {
236 strcpy(attributes->tags, "");
237 } else {
238 // copy the flattened string into the attributes as the destination for the conversion:
239 // copying array size -1, array for tags was calloc'd, no need to NULL-terminate it
240 size_t tagSize = realTagSize > AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 ?
241 AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 : realTagSize;
Sergio Giro1d3f4272016-06-28 18:24:52 +0100242 utf16_to_utf8(tags.string(), tagSize, attributes->tags,
243 sizeof(attributes->tags) / sizeof(attributes->tags[0]));
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700244 }
245 } else {
246 ALOGE("unmarshallAudioAttributes() received unflattened tags, ignoring tag values");
247 strcpy(attributes->tags, "");
248 }
249}
250} // anonymous namespace
251
252
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800253namespace android {
254
Marco Nelissenf09611f2015-02-13 14:12:42 -0800255extern ALooperRoster gLooperRoster;
256
257
Dave Burked681bbb2011-08-30 14:39:17 +0100258static bool checkPermission(const char* permissionString) {
Dave Burked681bbb2011-08-30 14:39:17 +0100259 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
260 bool ok = checkCallingPermission(String16(permissionString));
Steve Block29357bc2012-01-06 19:20:56 +0000261 if (!ok) ALOGE("Request requires %s", permissionString);
Dave Burked681bbb2011-08-30 14:39:17 +0100262 return ok;
263}
264
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800265// 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 -0800266/* static */ int MediaPlayerService::AudioOutput::mMinBufferCount = 4;
267/* static */ bool MediaPlayerService::AudioOutput::mIsOnEmulator = false;
268
269void MediaPlayerService::instantiate() {
270 defaultServiceManager()->addService(
271 String16("media.player"), new MediaPlayerService());
272}
273
274MediaPlayerService::MediaPlayerService()
275{
Steve Block3856b092011-10-20 11:56:00 +0100276 ALOGV("MediaPlayerService created");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800277 mNextConnId = 1;
Gloria Wang9ee159b2011-02-24 14:51:45 -0800278
John Grossman44a7e422012-06-21 17:29:24 -0700279 MediaPlayerFactory::registerBuiltinFactories();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800280}
281
282MediaPlayerService::~MediaPlayerService()
283{
Steve Block3856b092011-10-20 11:56:00 +0100284 ALOGV("MediaPlayerService destroyed");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800285}
286
Svet Ganovbe71aa22015-04-28 12:06:02 -0700287sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(const String16 &opPackageName)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800288{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800289 pid_t pid = IPCThreadState::self()->getCallingPid();
Svet Ganovbe71aa22015-04-28 12:06:02 -0700290 sp<MediaRecorderClient> recorder = new MediaRecorderClient(this, pid, opPackageName);
Gloria Wangdac6a312009-10-29 15:46:37 -0700291 wp<MediaRecorderClient> w = recorder;
292 Mutex::Autolock lock(mLock);
293 mMediaRecorderClients.add(w);
Steve Block3856b092011-10-20 11:56:00 +0100294 ALOGV("Create new media recorder client from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800295 return recorder;
296}
297
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -0700298void MediaPlayerService::removeMediaRecorderClient(const wp<MediaRecorderClient>& client)
Gloria Wangdac6a312009-10-29 15:46:37 -0700299{
300 Mutex::Autolock lock(mLock);
301 mMediaRecorderClients.remove(client);
Steve Block3856b092011-10-20 11:56:00 +0100302 ALOGV("Delete media recorder client");
Gloria Wangdac6a312009-10-29 15:46:37 -0700303}
304
Glenn Kastenf37971f2012-02-03 11:06:53 -0800305sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800306{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800307 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800308 sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
Steve Block3856b092011-10-20 11:56:00 +0100309 ALOGV("Create new media retriever from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800310 return retriever;
311}
312
Glenn Kastenf37971f2012-02-03 11:06:53 -0800313sp<IMediaPlayer> MediaPlayerService::create(const sp<IMediaPlayerClient>& client,
Glenn Kastend848eb42016-03-08 13:42:11 -0800314 audio_session_t audioSessionId)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800315{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800316 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800317 int32_t connId = android_atomic_inc(&mNextConnId);
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700318
319 sp<Client> c = new Client(
320 this, pid, connId, client, audioSessionId,
321 IPCThreadState::self()->getCallingUid());
322
Steve Block3856b092011-10-20 11:56:00 +0100323 ALOGV("Create new client(%d) from pid %d, uid %d, ", connId, pid,
Dave Burked681bbb2011-08-30 14:39:17 +0100324 IPCThreadState::self()->getCallingUid());
325
326 wp<Client> w = c;
327 {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800328 Mutex::Autolock lock(mLock);
329 mClients.add(w);
330 }
Andreas Hubere2b10282010-11-23 11:41:34 -0800331 return c;
332}
333
Lajos Molnar1381d4b2014-08-07 15:18:35 -0700334sp<IMediaCodecList> MediaPlayerService::getCodecList() const {
335 return MediaCodecList::getLocalInstance();
336}
337
Jeff Brown2013a542012-09-04 21:38:42 -0700338sp<IRemoteDisplay> MediaPlayerService::listenForRemoteDisplay(
Chong Zhangd0a98fa2017-09-14 17:43:10 -0700339 const String16 &/*opPackageName*/,
340 const sp<IRemoteDisplayClient>& /*client*/,
341 const String8& /*iface*/) {
342 ALOGE("listenForRemoteDisplay is no longer supported!");
Jeff Brownaba33d52012-09-07 17:38:58 -0700343
Chong Zhangd0a98fa2017-09-14 17:43:10 -0700344 return NULL;
Jeff Brown2013a542012-09-04 21:38:42 -0700345}
346
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800347status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
348{
349 const size_t SIZE = 256;
350 char buffer[SIZE];
351 String8 result;
352
353 result.append(" AudioOutput\n");
354 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n",
355 mStreamType, mLeftVolume, mRightVolume);
356 result.append(buffer);
357 snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n",
Eric Laurentdb354e52012-03-05 17:27:11 -0800358 mMsecsPerFrame, (mTrack != 0) ? mTrack->latency() : -1);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800359 result.append(buffer);
Eric Laurent2beeb502010-07-16 07:43:46 -0700360 snprintf(buffer, 255, " aux effect id(%d), send level (%f)\n",
361 mAuxEffectId, mSendLevel);
362 result.append(buffer);
363
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800364 ::write(fd, result.string(), result.size());
365 if (mTrack != 0) {
366 mTrack->dump(fd, args);
367 }
368 return NO_ERROR;
369}
370
Lajos Molnar6d339f12015-04-17 16:15:53 -0700371status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800372{
373 const size_t SIZE = 256;
374 char buffer[SIZE];
375 String8 result;
376 result.append(" Client\n");
377 snprintf(buffer, 255, " pid(%d), connId(%d), status(%d), looping(%s)\n",
378 mPid, mConnId, mStatus, mLoop?"true": "false");
379 result.append(buffer);
Wei Jia502c2f42017-07-13 17:47:56 -0700380
381 sp<MediaPlayerBase> p;
382 sp<AudioOutput> audioOutput;
383 bool locked = false;
384 for (int i = 0; i < kDumpLockRetries; ++i) {
385 if (mLock.tryLock() == NO_ERROR) {
386 locked = true;
387 break;
388 }
389 usleep(kDumpLockSleepUs);
Andreas Hubera0b1d4b2011-06-07 15:52:25 -0700390 }
Wei Jia502c2f42017-07-13 17:47:56 -0700391
392 if (locked) {
393 p = mPlayer;
394 audioOutput = mAudioOutput;
395 mLock.unlock();
396 } else {
397 result.append(" lock is taken, no dump from player and audio output\n");
398 }
399 write(fd, result.string(), result.size());
400
401 if (p != NULL) {
402 p->dump(fd, args);
403 }
404 if (audioOutput != 0) {
405 audioOutput->dump(fd, args);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800406 }
407 write(fd, "\n", 1);
408 return NO_ERROR;
409}
410
Marco Nelissenf09611f2015-02-13 14:12:42 -0800411/**
412 * The only arguments this understands right now are -c, -von and -voff,
413 * which are parsed by ALooperRoster::dump()
414 */
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800415status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
416{
417 const size_t SIZE = 256;
418 char buffer[SIZE];
419 String8 result;
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530420 SortedVector< sp<Client> > clients; //to serialise the mutex unlock & client destruction.
421 SortedVector< sp<MediaRecorderClient> > mediaRecorderClients;
422
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800423 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
424 snprintf(buffer, SIZE, "Permission Denial: "
425 "can't dump MediaPlayerService from pid=%d, uid=%d\n",
426 IPCThreadState::self()->getCallingPid(),
427 IPCThreadState::self()->getCallingUid());
428 result.append(buffer);
429 } else {
430 Mutex::Autolock lock(mLock);
431 for (int i = 0, n = mClients.size(); i < n; ++i) {
432 sp<Client> c = mClients[i].promote();
433 if (c != 0) c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530434 clients.add(c);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800435 }
James Dongb9141222010-07-08 11:16:11 -0700436 if (mMediaRecorderClients.size() == 0) {
437 result.append(" No media recorder client\n\n");
438 } else {
439 for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
440 sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
James Donge579e282011-10-18 22:29:20 -0700441 if (c != 0) {
442 snprintf(buffer, 255, " MediaRecorderClient pid(%d)\n", c->mPid);
443 result.append(buffer);
444 write(fd, result.string(), result.size());
445 result = "\n";
446 c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530447 mediaRecorderClients.add(c);
James Donge579e282011-10-18 22:29:20 -0700448 }
James Dongb9141222010-07-08 11:16:11 -0700449 }
Gloria Wangdac6a312009-10-29 15:46:37 -0700450 }
451
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800452 result.append(" Files opened and/or mapped:\n");
Marco Nelissenf09611f2015-02-13 14:12:42 -0800453 snprintf(buffer, SIZE, "/proc/%d/maps", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800454 FILE *f = fopen(buffer, "r");
455 if (f) {
456 while (!feof(f)) {
457 fgets(buffer, SIZE, f);
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700458 if (strstr(buffer, " /storage/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800459 strstr(buffer, " /system/sounds/") ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700460 strstr(buffer, " /data/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800461 strstr(buffer, " /system/media/")) {
462 result.append(" ");
463 result.append(buffer);
464 }
465 }
466 fclose(f);
467 } else {
468 result.append("couldn't open ");
469 result.append(buffer);
470 result.append("\n");
471 }
472
Marco Nelissenf09611f2015-02-13 14:12:42 -0800473 snprintf(buffer, SIZE, "/proc/%d/fd", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800474 DIR *d = opendir(buffer);
475 if (d) {
476 struct dirent *ent;
477 while((ent = readdir(d)) != NULL) {
478 if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
Marco Nelissenf09611f2015-02-13 14:12:42 -0800479 snprintf(buffer, SIZE, "/proc/%d/fd/%s", getpid(), ent->d_name);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800480 struct stat s;
481 if (lstat(buffer, &s) == 0) {
482 if ((s.st_mode & S_IFMT) == S_IFLNK) {
483 char linkto[256];
484 int len = readlink(buffer, linkto, sizeof(linkto));
485 if(len > 0) {
486 if(len > 255) {
487 linkto[252] = '.';
488 linkto[253] = '.';
489 linkto[254] = '.';
490 linkto[255] = 0;
491 } else {
492 linkto[len] = 0;
493 }
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700494 if (strstr(linkto, "/storage/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800495 strstr(linkto, "/system/sounds/") == linkto ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700496 strstr(linkto, "/data/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800497 strstr(linkto, "/system/media/") == linkto) {
498 result.append(" ");
499 result.append(buffer);
500 result.append(" -> ");
501 result.append(linkto);
502 result.append("\n");
503 }
504 }
505 } else {
506 result.append(" unexpected type for ");
507 result.append(buffer);
508 result.append("\n");
509 }
510 }
511 }
512 }
513 closedir(d);
514 } else {
515 result.append("couldn't open ");
516 result.append(buffer);
517 result.append("\n");
518 }
519
Marco Nelissenf09611f2015-02-13 14:12:42 -0800520 gLooperRoster.dump(fd, args);
521
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800522 bool dumpMem = false;
Andy Hung53541292016-04-13 16:48:51 -0700523 bool unreachableMemory = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800524 for (size_t i = 0; i < args.size(); i++) {
525 if (args[i] == String16("-m")) {
526 dumpMem = true;
Andy Hung53541292016-04-13 16:48:51 -0700527 } else if (args[i] == String16("--unreachable")) {
528 unreachableMemory = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800529 }
530 }
531 if (dumpMem) {
Andy Hung07b745e2016-05-23 16:21:07 -0700532 result.append("\nDumping memory:\n");
533 std::string s = dumpMemoryAddresses(100 /* limit */);
534 result.append(s.c_str(), s.size());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800535 }
Andy Hung53541292016-04-13 16:48:51 -0700536 if (unreachableMemory) {
537 result.append("\nDumping unreachable memory:\n");
538 // TODO - should limit be an argument parameter?
539 std::string s = GetUnreachableMemoryString(true /* contents */, 10000 /* limit */);
540 result.append(s.c_str(), s.size());
541 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800542 }
543 write(fd, result.string(), result.size());
544 return NO_ERROR;
545}
546
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -0700547void MediaPlayerService::removeClient(const wp<Client>& client)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800548{
549 Mutex::Autolock lock(mLock);
550 mClients.remove(client);
551}
552
Robert Shihee0a0e32016-08-16 16:50:54 -0700553bool MediaPlayerService::hasClient(wp<Client> client)
554{
555 Mutex::Autolock lock(mLock);
556 return mClients.indexOf(client) != NAME_NOT_FOUND;
557}
558
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700559MediaPlayerService::Client::Client(
560 const sp<MediaPlayerService>& service, pid_t pid,
561 int32_t connId, const sp<IMediaPlayerClient>& client,
Glenn Kastend848eb42016-03-08 13:42:11 -0800562 audio_session_t audioSessionId, uid_t uid)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800563{
Steve Block3856b092011-10-20 11:56:00 +0100564 ALOGV("Client(%d) constructor", connId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800565 mPid = pid;
566 mConnId = connId;
567 mService = service;
568 mClient = client;
569 mLoop = false;
570 mStatus = NO_INIT;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700571 mAudioSessionId = audioSessionId;
Andy Hung1afd0982016-11-08 16:13:44 -0800572 mUid = uid;
John Grossmanc795b642012-02-22 15:38:35 -0800573 mRetransmitEndpointValid = false;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700574 mAudioAttributes = NULL;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700575
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800576#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000577 ALOGD("create Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800578 mAntagonizer = new Antagonizer(notify, this);
579#endif
580}
581
582MediaPlayerService::Client::~Client()
583{
Steve Block3856b092011-10-20 11:56:00 +0100584 ALOGV("Client(%d) destructor pid = %d", mConnId, mPid);
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700585 mAudioOutput.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800586 wp<Client> client(this);
587 disconnect();
588 mService->removeClient(client);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700589 if (mAudioAttributes != NULL) {
590 free(mAudioAttributes);
591 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700592 clearDeathNotifiers_l();
jiabin156c6872017-10-06 09:47:15 -0700593 mAudioDeviceUpdatedListener.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800594}
595
596void MediaPlayerService::Client::disconnect()
597{
Steve Block3856b092011-10-20 11:56:00 +0100598 ALOGV("disconnect(%d) from pid %d", mConnId, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800599 // grab local reference and clear main reference to prevent future
600 // access to object
601 sp<MediaPlayerBase> p;
602 {
603 Mutex::Autolock l(mLock);
604 p = mPlayer;
beanzdcfefde2012-11-05 09:51:43 +0800605 mClient.clear();
Wei Jia502c2f42017-07-13 17:47:56 -0700606 mPlayer.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800607 }
Andreas Huber20111aa2009-07-14 16:56:47 -0700608
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800609 // clear the notification to prevent callbacks to dead client
610 // and reset the player. We assume the player will serialize
611 // access to itself if necessary.
612 if (p != 0) {
613 p->setNotifyCallback(0, 0);
614#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000615 ALOGD("kill Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800616 mAntagonizer->kill();
617#endif
618 p->reset();
619 }
620
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700621 {
622 Mutex::Autolock l(mLock);
623 disconnectNativeWindow_l();
624 }
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700625
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800626 IPCThreadState::self()->flushCommands();
627}
628
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800629sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
630{
631 // determine if we have the right player type
Wei Jia502c2f42017-07-13 17:47:56 -0700632 sp<MediaPlayerBase> p = getPlayer();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800633 if ((p != NULL) && (p->playerType() != playerType)) {
Steve Block3856b092011-10-20 11:56:00 +0100634 ALOGV("delete player");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800635 p.clear();
636 }
637 if (p == NULL) {
Ronghua Wu68845c12015-07-21 09:50:48 -0700638 p = MediaPlayerFactory::createPlayer(playerType, this, notify, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800639 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700640
Jason Simmonsdb29e522011-08-12 13:46:55 -0700641 if (p != NULL) {
Andy Hung1afd0982016-11-08 16:13:44 -0800642 p->setUID(mUid);
Jason Simmonsdb29e522011-08-12 13:46:55 -0700643 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700644
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800645 return p;
646}
647
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700648MediaPlayerService::Client::ServiceDeathNotifier::ServiceDeathNotifier(
649 const sp<IBinder>& service,
650 const sp<MediaPlayerBase>& listener,
651 int which) {
652 mService = service;
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800653 mOmx = nullptr;
654 mListener = listener;
655 mWhich = which;
656}
657
658MediaPlayerService::Client::ServiceDeathNotifier::ServiceDeathNotifier(
659 const sp<IOmx>& omx,
660 const sp<MediaPlayerBase>& listener,
661 int which) {
662 mService = nullptr;
663 mOmx = omx;
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700664 mListener = listener;
665 mWhich = which;
666}
667
668MediaPlayerService::Client::ServiceDeathNotifier::~ServiceDeathNotifier() {
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700669}
670
671void MediaPlayerService::Client::ServiceDeathNotifier::binderDied(const wp<IBinder>& /*who*/) {
672 sp<MediaPlayerBase> listener = mListener.promote();
673 if (listener != NULL) {
674 listener->sendEvent(MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED, mWhich);
675 } else {
676 ALOGW("listener for process %d death is gone", mWhich);
677 }
678}
679
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800680void MediaPlayerService::Client::ServiceDeathNotifier::serviceDied(
681 uint64_t /* cookie */,
682 const wp<::android::hidl::base::V1_0::IBase>& /* who */) {
683 sp<MediaPlayerBase> listener = mListener.promote();
684 if (listener != NULL) {
685 listener->sendEvent(MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED, mWhich);
686 } else {
687 ALOGW("listener for process %d death is gone", mWhich);
688 }
689}
690
691void MediaPlayerService::Client::ServiceDeathNotifier::unlinkToDeath() {
692 if (mService != nullptr) {
693 mService->unlinkToDeath(this);
694 mService = nullptr;
695 } else if (mOmx != nullptr) {
696 mOmx->unlinkToDeath(this);
697 mOmx = nullptr;
698 }
699}
700
jiabin156c6872017-10-06 09:47:15 -0700701void MediaPlayerService::Client::AudioDeviceUpdatedNotifier::onAudioDeviceUpdate(
702 audio_io_handle_t audioIo,
703 audio_port_handle_t deviceId) {
704 sp<MediaPlayerBase> listener = mListener.promote();
705 if (listener != NULL) {
706 listener->sendEvent(MEDIA_AUDIO_ROUTING_CHANGED, audioIo, deviceId);
707 } else {
708 ALOGW("listener for process %d death is gone", MEDIA_AUDIO_ROUTING_CHANGED);
709 }
710}
711
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700712void MediaPlayerService::Client::clearDeathNotifiers_l() {
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800713 if (mExtractorDeathListener != nullptr) {
714 mExtractorDeathListener->unlinkToDeath();
715 mExtractorDeathListener = nullptr;
716 }
717 if (mCodecDeathListener != nullptr) {
718 mCodecDeathListener->unlinkToDeath();
719 mCodecDeathListener = nullptr;
720 }
721}
722
John Grossmanc795b642012-02-22 15:38:35 -0800723sp<MediaPlayerBase> MediaPlayerService::Client::setDataSource_pre(
724 player_type playerType)
725{
726 ALOGV("player type = %d", playerType);
727
728 // create the right type of player
729 sp<MediaPlayerBase> p = createPlayer(playerType);
730 if (p == NULL) {
731 return p;
732 }
733
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700734 sp<IServiceManager> sm = defaultServiceManager();
735 sp<IBinder> binder = sm->getService(String16("media.extractor"));
Marco Nelissen1b5a7ee2016-09-30 13:54:30 -0700736 if (binder == NULL) {
737 ALOGE("extractor service not available");
738 return NULL;
739 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700740 sp<ServiceDeathNotifier> extractorDeathListener =
741 new ServiceDeathNotifier(binder, p, MEDIAEXTRACTOR_PROCESS_DEATH);
742 binder->linkToDeath(extractorDeathListener);
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700743
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700744 sp<ServiceDeathNotifier> codecDeathListener;
Colin Cross85e88d92017-10-26 16:16:55 -0700745 if (property_get_bool("persist.media.treble_omx", true)) {
746 // Treble IOmx
747 sp<IOmx> omx = IOmx::getService();
748 if (omx == nullptr) {
749 ALOGE("Treble IOmx not available");
750 return NULL;
751 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700752 codecDeathListener = new ServiceDeathNotifier(omx, p, MEDIACODEC_PROCESS_DEATH);
753 omx->linkToDeath(codecDeathListener, 0);
Colin Cross85e88d92017-10-26 16:16:55 -0700754 } else {
755 // Legacy IOMX
756 binder = sm->getService(String16("media.codec"));
757 if (binder == NULL) {
758 ALOGE("codec service not available");
759 return NULL;
760 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700761 codecDeathListener = new ServiceDeathNotifier(binder, p, MEDIACODEC_PROCESS_DEATH);
762 binder->linkToDeath(codecDeathListener);
Marco Nelissen1b5a7ee2016-09-30 13:54:30 -0700763 }
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700764
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700765 Mutex::Autolock lock(mLock);
766
767 clearDeathNotifiers_l();
768 mExtractorDeathListener = extractorDeathListener;
769 mCodecDeathListener = codecDeathListener;
jiabin156c6872017-10-06 09:47:15 -0700770 mAudioDeviceUpdatedListener = new AudioDeviceUpdatedNotifier(p);
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700771
John Grossmanc795b642012-02-22 15:38:35 -0800772 if (!p->hardwareOutput()) {
Marco Nelissend457c972014-02-11 08:47:07 -0800773 mAudioOutput = new AudioOutput(mAudioSessionId, IPCThreadState::self()->getCallingUid(),
jiabin156c6872017-10-06 09:47:15 -0700774 mPid, mAudioAttributes, mAudioDeviceUpdatedListener);
John Grossmanc795b642012-02-22 15:38:35 -0800775 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
776 }
777
778 return p;
779}
780
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700781status_t MediaPlayerService::Client::setDataSource_post(
John Grossmanc795b642012-02-22 15:38:35 -0800782 const sp<MediaPlayerBase>& p,
783 status_t status)
784{
785 ALOGV(" setDataSource");
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700786 if (status != OK) {
787 ALOGE(" error: %d", status);
788 return status;
John Grossmanc795b642012-02-22 15:38:35 -0800789 }
790
791 // Set the re-transmission endpoint if one was chosen.
792 if (mRetransmitEndpointValid) {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700793 status = p->setRetransmitEndpoint(&mRetransmitEndpoint);
794 if (status != NO_ERROR) {
795 ALOGE("setRetransmitEndpoint error: %d", status);
John Grossmanc795b642012-02-22 15:38:35 -0800796 }
797 }
798
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700799 if (status == OK) {
800 Mutex::Autolock lock(mLock);
John Grossmanc795b642012-02-22 15:38:35 -0800801 mPlayer = p;
802 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700803 return status;
John Grossmanc795b642012-02-22 15:38:35 -0800804}
805
Andreas Huber2db84552010-01-28 11:19:57 -0800806status_t MediaPlayerService::Client::setDataSource(
Andreas Huber1b86fe02014-01-29 11:13:26 -0800807 const sp<IMediaHTTPService> &httpService,
808 const char *url,
809 const KeyedVector<String8, String8> *headers)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800810{
Steve Block3856b092011-10-20 11:56:00 +0100811 ALOGV("setDataSource(%s)", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800812 if (url == NULL)
813 return UNKNOWN_ERROR;
814
Dave Burked681bbb2011-08-30 14:39:17 +0100815 if ((strncmp(url, "http://", 7) == 0) ||
816 (strncmp(url, "https://", 8) == 0) ||
817 (strncmp(url, "rtsp://", 7) == 0)) {
818 if (!checkPermission("android.permission.INTERNET")) {
819 return PERMISSION_DENIED;
820 }
821 }
822
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800823 if (strncmp(url, "content://", 10) == 0) {
824 // get a filedescriptor for the content Uri and
825 // pass it to the setDataSource(fd) method
826
827 String16 url16(url);
828 int fd = android::openContentProviderFile(url16);
829 if (fd < 0)
830 {
Steve Block29357bc2012-01-06 19:20:56 +0000831 ALOGE("Couldn't open fd for %s", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800832 return UNKNOWN_ERROR;
833 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700834 status_t status = setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800835 close(fd);
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700836 return mStatus = status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800837 } else {
John Grossman44a7e422012-06-21 17:29:24 -0700838 player_type playerType = MediaPlayerFactory::getPlayerType(this, url);
John Grossmanc795b642012-02-22 15:38:35 -0800839 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
840 if (p == NULL) {
841 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800842 }
843
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700844 return mStatus =
845 setDataSource_post(
846 p, p->setDataSource(httpService, url, headers));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800847 }
848}
849
850status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
851{
Marco Nelissen83b0fd92015-09-16 13:48:07 -0700852 ALOGV("setDataSource fd=%d (%s), offset=%lld, length=%lld",
853 fd, nameForFd(fd).c_str(), (long long) offset, (long long) length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800854 struct stat sb;
855 int ret = fstat(fd, &sb);
856 if (ret != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000857 ALOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800858 return UNKNOWN_ERROR;
859 }
860
Andy Hung833b4752016-04-04 17:15:48 -0700861 ALOGV("st_dev = %llu", static_cast<unsigned long long>(sb.st_dev));
Steve Block3856b092011-10-20 11:56:00 +0100862 ALOGV("st_mode = %u", sb.st_mode);
Mark Salyzyn77342f72014-06-18 16:31:32 -0700863 ALOGV("st_uid = %lu", static_cast<unsigned long>(sb.st_uid));
864 ALOGV("st_gid = %lu", static_cast<unsigned long>(sb.st_gid));
Andy Hung833b4752016-04-04 17:15:48 -0700865 ALOGV("st_size = %llu", static_cast<unsigned long long>(sb.st_size));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800866
867 if (offset >= sb.st_size) {
Steve Block29357bc2012-01-06 19:20:56 +0000868 ALOGE("offset error");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800869 return UNKNOWN_ERROR;
870 }
871 if (offset + length > sb.st_size) {
872 length = sb.st_size - offset;
Andy Hung833b4752016-04-04 17:15:48 -0700873 ALOGV("calculated length = %lld", (long long)length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800874 }
875
John Grossman44a7e422012-06-21 17:29:24 -0700876 player_type playerType = MediaPlayerFactory::getPlayerType(this,
877 fd,
878 offset,
879 length);
John Grossmanc795b642012-02-22 15:38:35 -0800880 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
881 if (p == NULL) {
882 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800883 }
884
885 // now set data source
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700886 return mStatus = setDataSource_post(p, p->setDataSource(fd, offset, length));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800887}
888
Andreas Hubere2b10282010-11-23 11:41:34 -0800889status_t MediaPlayerService::Client::setDataSource(
890 const sp<IStreamSource> &source) {
891 // create the right type of player
John Grossman44a7e422012-06-21 17:29:24 -0700892 player_type playerType = MediaPlayerFactory::getPlayerType(this, source);
John Grossmanc795b642012-02-22 15:38:35 -0800893 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
Andreas Hubere2b10282010-11-23 11:41:34 -0800894 if (p == NULL) {
895 return NO_INIT;
896 }
897
Andreas Hubere2b10282010-11-23 11:41:34 -0800898 // now set data source
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700899 return mStatus = setDataSource_post(p, p->setDataSource(source));
Andreas Hubere2b10282010-11-23 11:41:34 -0800900}
901
Chris Watkins99f31602015-03-20 13:06:33 -0700902status_t MediaPlayerService::Client::setDataSource(
903 const sp<IDataSource> &source) {
Dongwon Kangd91dc5a2017-10-10 00:07:09 -0700904 sp<DataSource> dataSource = CreateDataSourceFromIDataSource(source);
Chris Watkins99f31602015-03-20 13:06:33 -0700905 player_type playerType = MediaPlayerFactory::getPlayerType(this, dataSource);
906 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
907 if (p == NULL) {
908 return NO_INIT;
909 }
910 // now set data source
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700911 return mStatus = setDataSource_post(p, p->setDataSource(dataSource));
Chris Watkins99f31602015-03-20 13:06:33 -0700912}
913
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700914void MediaPlayerService::Client::disconnectNativeWindow_l() {
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700915 if (mConnectedWindow != NULL) {
Chong Zhang181fd9b2017-02-16 15:53:03 -0800916 status_t err = nativeWindowDisconnect(
917 mConnectedWindow.get(), "disconnectNativeWindow");
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700918
919 if (err != OK) {
Chong Zhang181fd9b2017-02-16 15:53:03 -0800920 ALOGW("nativeWindowDisconnect returned an error: %s (%d)",
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700921 strerror(-err), err);
922 }
923 }
924 mConnectedWindow.clear();
925}
926
Glenn Kasten11731182011-02-08 17:26:17 -0800927status_t MediaPlayerService::Client::setVideoSurfaceTexture(
Andy McFadden484566c2012-12-18 09:46:54 -0800928 const sp<IGraphicBufferProducer>& bufferProducer)
Glenn Kasten11731182011-02-08 17:26:17 -0800929{
Andy McFadden484566c2012-12-18 09:46:54 -0800930 ALOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, bufferProducer.get());
Glenn Kasten11731182011-02-08 17:26:17 -0800931 sp<MediaPlayerBase> p = getPlayer();
932 if (p == 0) return UNKNOWN_ERROR;
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700933
Marco Nelissenf8880202014-11-14 07:58:25 -0800934 sp<IBinder> binder(IInterface::asBinder(bufferProducer));
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700935 if (mConnectedWindowBinder == binder) {
936 return OK;
937 }
938
939 sp<ANativeWindow> anw;
Andy McFadden484566c2012-12-18 09:46:54 -0800940 if (bufferProducer != NULL) {
Marco Nelissenee08f7e2013-09-16 13:30:01 -0700941 anw = new Surface(bufferProducer, true /* controlledByApp */);
Chong Zhang181fd9b2017-02-16 15:53:03 -0800942 status_t err = nativeWindowConnect(anw.get(), "setVideoSurfaceTexture");
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700943
944 if (err != OK) {
Steve Block29357bc2012-01-06 19:20:56 +0000945 ALOGE("setVideoSurfaceTexture failed: %d", err);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700946 // Note that we must do the reset before disconnecting from the ANW.
947 // Otherwise queue/dequeue calls could be made on the disconnected
948 // ANW, which may result in errors.
949 reset();
950
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700951 Mutex::Autolock lock(mLock);
952 disconnectNativeWindow_l();
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700953
954 return err;
955 }
956 }
957
Andy McFadden484566c2012-12-18 09:46:54 -0800958 // Note that we must set the player's new GraphicBufferProducer before
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700959 // disconnecting the old one. Otherwise queue/dequeue calls could be made
960 // on the disconnected ANW, which may result in errors.
Andy McFadden484566c2012-12-18 09:46:54 -0800961 status_t err = p->setVideoSurfaceTexture(bufferProducer);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700962
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700963 mLock.lock();
964 disconnectNativeWindow_l();
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700965
966 if (err == OK) {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700967 mConnectedWindow = anw;
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700968 mConnectedWindowBinder = binder;
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700969 mLock.unlock();
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700970 } else {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700971 mLock.unlock();
972 status_t err = nativeWindowDisconnect(
973 anw.get(), "disconnectNativeWindow");
974
975 if (err != OK) {
976 ALOGW("nativeWindowDisconnect returned an error: %s (%d)",
977 strerror(-err), err);
978 }
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700979 }
980
981 return err;
Glenn Kasten11731182011-02-08 17:26:17 -0800982}
983
Nicolas Catania1d187f12009-05-12 23:25:55 -0700984status_t MediaPlayerService::Client::invoke(const Parcel& request,
985 Parcel *reply)
986{
987 sp<MediaPlayerBase> p = getPlayer();
988 if (p == NULL) return UNKNOWN_ERROR;
989 return p->invoke(request, reply);
990}
991
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700992// This call doesn't need to access the native player.
993status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
994{
995 status_t status;
nikoa64c8c72009-07-20 15:07:26 -0700996 media::Metadata::Filter allow, drop;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700997
Nicolas Catania48290382009-07-10 13:53:06 -0700998 if (unmarshallFilter(filter, &allow, &status) &&
999 unmarshallFilter(filter, &drop, &status)) {
1000 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001001
1002 mMetadataAllow = allow;
1003 mMetadataDrop = drop;
1004 }
1005 return status;
1006}
1007
Nicolas Catania48290382009-07-10 13:53:06 -07001008status_t MediaPlayerService::Client::getMetadata(
Mark Salyzyn77342f72014-06-18 16:31:32 -07001009 bool update_only, bool /*apply_filter*/, Parcel *reply)
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001010{
nikoa64c8c72009-07-20 15:07:26 -07001011 sp<MediaPlayerBase> player = getPlayer();
1012 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania48290382009-07-10 13:53:06 -07001013
nikod608a812009-07-16 16:39:53 -07001014 status_t status;
1015 // Placeholder for the return code, updated by the caller.
1016 reply->writeInt32(-1);
1017
nikoa64c8c72009-07-20 15:07:26 -07001018 media::Metadata::Filter ids;
Nicolas Catania48290382009-07-10 13:53:06 -07001019
1020 // We don't block notifications while we fetch the data. We clear
1021 // mMetadataUpdated first so we don't lose notifications happening
1022 // during the rest of this call.
1023 {
1024 Mutex::Autolock lock(mLock);
1025 if (update_only) {
nikod608a812009-07-16 16:39:53 -07001026 ids = mMetadataUpdated;
Nicolas Catania48290382009-07-10 13:53:06 -07001027 }
1028 mMetadataUpdated.clear();
1029 }
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001030
nikoa64c8c72009-07-20 15:07:26 -07001031 media::Metadata metadata(reply);
Nicolas Catania48290382009-07-10 13:53:06 -07001032
nikoa64c8c72009-07-20 15:07:26 -07001033 metadata.appendHeader();
1034 status = player->getMetadata(ids, reply);
nikod608a812009-07-16 16:39:53 -07001035
1036 if (status != OK) {
nikoa64c8c72009-07-20 15:07:26 -07001037 metadata.resetParcel();
Steve Block29357bc2012-01-06 19:20:56 +00001038 ALOGE("getMetadata failed %d", status);
nikod608a812009-07-16 16:39:53 -07001039 return status;
1040 }
1041
1042 // FIXME: Implement filtering on the result. Not critical since
1043 // filtering takes place on the update notifications already. This
1044 // would be when all the metadata are fetch and a filter is set.
1045
nikod608a812009-07-16 16:39:53 -07001046 // Everything is fine, update the metadata length.
nikoa64c8c72009-07-20 15:07:26 -07001047 metadata.updateLength();
nikod608a812009-07-16 16:39:53 -07001048 return OK;
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001049}
1050
Wei Jiad399e7e2016-10-26 15:49:11 -07001051status_t MediaPlayerService::Client::setBufferingSettings(
1052 const BufferingSettings& buffering)
1053{
Wei Jiadc6f3402017-01-09 15:04:18 -08001054 ALOGV("[%d] setBufferingSettings{%s}",
1055 mConnId, buffering.toString().string());
Wei Jiad399e7e2016-10-26 15:49:11 -07001056 sp<MediaPlayerBase> p = getPlayer();
1057 if (p == 0) return UNKNOWN_ERROR;
1058 return p->setBufferingSettings(buffering);
1059}
1060
1061status_t MediaPlayerService::Client::getDefaultBufferingSettings(
1062 BufferingSettings* buffering /* nonnull */)
1063{
1064 sp<MediaPlayerBase> p = getPlayer();
1065 // TODO: create mPlayer on demand.
1066 if (p == 0) return UNKNOWN_ERROR;
1067 status_t ret = p->getDefaultBufferingSettings(buffering);
1068 if (ret == NO_ERROR) {
Wei Jiadc6f3402017-01-09 15:04:18 -08001069 ALOGV("[%d] getDefaultBufferingSettings{%s}",
1070 mConnId, buffering->toString().string());
Wei Jiad399e7e2016-10-26 15:49:11 -07001071 } else {
1072 ALOGV("[%d] getDefaultBufferingSettings returned %d", mConnId, ret);
1073 }
1074 return ret;
1075}
1076
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001077status_t MediaPlayerService::Client::prepareAsync()
1078{
Steve Block3856b092011-10-20 11:56:00 +01001079 ALOGV("[%d] prepareAsync", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001080 sp<MediaPlayerBase> p = getPlayer();
1081 if (p == 0) return UNKNOWN_ERROR;
1082 status_t ret = p->prepareAsync();
1083#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +00001084 ALOGD("start Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001085 if (ret == NO_ERROR) mAntagonizer->start();
1086#endif
1087 return ret;
1088}
1089
1090status_t MediaPlayerService::Client::start()
1091{
Steve Block3856b092011-10-20 11:56:00 +01001092 ALOGV("[%d] start", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001093 sp<MediaPlayerBase> p = getPlayer();
1094 if (p == 0) return UNKNOWN_ERROR;
1095 p->setLooping(mLoop);
1096 return p->start();
1097}
1098
1099status_t MediaPlayerService::Client::stop()
1100{
Steve Block3856b092011-10-20 11:56:00 +01001101 ALOGV("[%d] stop", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001102 sp<MediaPlayerBase> p = getPlayer();
1103 if (p == 0) return UNKNOWN_ERROR;
1104 return p->stop();
1105}
1106
1107status_t MediaPlayerService::Client::pause()
1108{
Steve Block3856b092011-10-20 11:56:00 +01001109 ALOGV("[%d] pause", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001110 sp<MediaPlayerBase> p = getPlayer();
1111 if (p == 0) return UNKNOWN_ERROR;
1112 return p->pause();
1113}
1114
1115status_t MediaPlayerService::Client::isPlaying(bool* state)
1116{
1117 *state = false;
1118 sp<MediaPlayerBase> p = getPlayer();
1119 if (p == 0) return UNKNOWN_ERROR;
1120 *state = p->isPlaying();
Steve Block3856b092011-10-20 11:56:00 +01001121 ALOGV("[%d] isPlaying: %d", mConnId, *state);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001122 return NO_ERROR;
1123}
1124
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001125status_t MediaPlayerService::Client::setPlaybackSettings(const AudioPlaybackRate& rate)
Wei Jia98160162015-02-04 17:01:11 -08001126{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001127 ALOGV("[%d] setPlaybackSettings(%f, %f, %d, %d)",
1128 mConnId, rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Wei Jia98160162015-02-04 17:01:11 -08001129 sp<MediaPlayerBase> p = getPlayer();
1130 if (p == 0) return UNKNOWN_ERROR;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001131 return p->setPlaybackSettings(rate);
1132}
1133
1134status_t MediaPlayerService::Client::getPlaybackSettings(AudioPlaybackRate* rate /* nonnull */)
1135{
1136 sp<MediaPlayerBase> p = getPlayer();
1137 if (p == 0) return UNKNOWN_ERROR;
1138 status_t ret = p->getPlaybackSettings(rate);
1139 if (ret == NO_ERROR) {
1140 ALOGV("[%d] getPlaybackSettings(%f, %f, %d, %d)",
1141 mConnId, rate->mSpeed, rate->mPitch, rate->mFallbackMode, rate->mStretchMode);
1142 } else {
1143 ALOGV("[%d] getPlaybackSettings returned %d", mConnId, ret);
1144 }
1145 return ret;
1146}
1147
1148status_t MediaPlayerService::Client::setSyncSettings(
1149 const AVSyncSettings& sync, float videoFpsHint)
1150{
1151 ALOGV("[%d] setSyncSettings(%u, %u, %f, %f)",
1152 mConnId, sync.mSource, sync.mAudioAdjustMode, sync.mTolerance, videoFpsHint);
1153 sp<MediaPlayerBase> p = getPlayer();
1154 if (p == 0) return UNKNOWN_ERROR;
1155 return p->setSyncSettings(sync, videoFpsHint);
1156}
1157
1158status_t MediaPlayerService::Client::getSyncSettings(
1159 AVSyncSettings* sync /* nonnull */, float* videoFps /* nonnull */)
1160{
1161 sp<MediaPlayerBase> p = getPlayer();
1162 if (p == 0) return UNKNOWN_ERROR;
1163 status_t ret = p->getSyncSettings(sync, videoFps);
1164 if (ret == NO_ERROR) {
1165 ALOGV("[%d] getSyncSettings(%u, %u, %f, %f)",
1166 mConnId, sync->mSource, sync->mAudioAdjustMode, sync->mTolerance, *videoFps);
1167 } else {
1168 ALOGV("[%d] getSyncSettings returned %d", mConnId, ret);
1169 }
1170 return ret;
Wei Jia98160162015-02-04 17:01:11 -08001171}
1172
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001173status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
1174{
Steve Block3856b092011-10-20 11:56:00 +01001175 ALOGV("getCurrentPosition");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001176 sp<MediaPlayerBase> p = getPlayer();
1177 if (p == 0) return UNKNOWN_ERROR;
1178 status_t ret = p->getCurrentPosition(msec);
1179 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001180 ALOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001181 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001182 ALOGE("getCurrentPosition returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001183 }
1184 return ret;
1185}
1186
1187status_t MediaPlayerService::Client::getDuration(int *msec)
1188{
Steve Block3856b092011-10-20 11:56:00 +01001189 ALOGV("getDuration");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001190 sp<MediaPlayerBase> p = getPlayer();
1191 if (p == 0) return UNKNOWN_ERROR;
1192 status_t ret = p->getDuration(msec);
1193 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001194 ALOGV("[%d] getDuration = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001195 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001196 ALOGE("getDuration returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001197 }
1198 return ret;
1199}
1200
Marco Nelissen6b74d672012-02-28 16:07:44 -08001201status_t MediaPlayerService::Client::setNextPlayer(const sp<IMediaPlayer>& player) {
1202 ALOGV("setNextPlayer");
1203 Mutex::Autolock l(mLock);
1204 sp<Client> c = static_cast<Client*>(player.get());
Wei Jia28284122016-08-30 13:49:06 -07001205 if (c != NULL && !mService->hasClient(c)) {
Robert Shihee0a0e32016-08-16 16:50:54 -07001206 return BAD_VALUE;
1207 }
1208
Marco Nelissen6b74d672012-02-28 16:07:44 -08001209 mNextClient = c;
John Grossman5f7e55e2012-08-24 14:47:25 -07001210
1211 if (c != NULL) {
1212 if (mAudioOutput != NULL) {
1213 mAudioOutput->setNextOutput(c->mAudioOutput);
1214 } else if ((mPlayer != NULL) && !mPlayer->hardwareOutput()) {
1215 ALOGE("no current audio output");
1216 }
1217
1218 if ((mPlayer != NULL) && (mNextClient->getPlayer() != NULL)) {
1219 mPlayer->setNextPlayer(mNextClient->getPlayer());
1220 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001221 }
John Grossman5f7e55e2012-08-24 14:47:25 -07001222
Marco Nelissen6b74d672012-02-28 16:07:44 -08001223 return OK;
1224}
1225
Andy Hung9fc8b5c2017-01-24 13:36:48 -08001226VolumeShaper::Status MediaPlayerService::Client::applyVolumeShaper(
1227 const sp<VolumeShaper::Configuration>& configuration,
1228 const sp<VolumeShaper::Operation>& operation) {
1229 // for hardware output, call player instead
1230 ALOGV("Client::applyVolumeShaper(%p)", this);
1231 sp<MediaPlayerBase> p = getPlayer();
1232 {
1233 Mutex::Autolock l(mLock);
1234 if (p != 0 && p->hardwareOutput()) {
1235 // TODO: investigate internal implementation
1236 return VolumeShaper::Status(INVALID_OPERATION);
1237 }
1238 if (mAudioOutput.get() != nullptr) {
1239 return mAudioOutput->applyVolumeShaper(configuration, operation);
1240 }
1241 }
1242 return VolumeShaper::Status(INVALID_OPERATION);
1243}
1244
1245sp<VolumeShaper::State> MediaPlayerService::Client::getVolumeShaperState(int id) {
1246 // for hardware output, call player instead
1247 ALOGV("Client::getVolumeShaperState(%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 nullptr;
1254 }
1255 if (mAudioOutput.get() != nullptr) {
1256 return mAudioOutput->getVolumeShaperState(id);
1257 }
1258 }
1259 return nullptr;
1260}
1261
Wei Jiac5de0912016-11-18 10:22:14 -08001262status_t MediaPlayerService::Client::seekTo(int msec, MediaPlayerSeekMode mode)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001263{
Wei Jiac5de0912016-11-18 10:22:14 -08001264 ALOGV("[%d] seekTo(%d, %d)", mConnId, msec, mode);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001265 sp<MediaPlayerBase> p = getPlayer();
1266 if (p == 0) return UNKNOWN_ERROR;
Wei Jiac5de0912016-11-18 10:22:14 -08001267 return p->seekTo(msec, mode);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001268}
1269
1270status_t MediaPlayerService::Client::reset()
1271{
Steve Block3856b092011-10-20 11:56:00 +01001272 ALOGV("[%d] reset", mConnId);
John Grossmanc795b642012-02-22 15:38:35 -08001273 mRetransmitEndpointValid = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001274 sp<MediaPlayerBase> p = getPlayer();
1275 if (p == 0) return UNKNOWN_ERROR;
1276 return p->reset();
1277}
1278
Wei Jia52c28512017-09-13 18:17:51 -07001279status_t MediaPlayerService::Client::notifyAt(int64_t mediaTimeUs)
1280{
1281 ALOGV("[%d] notifyAt(%lld)", mConnId, (long long)mediaTimeUs);
1282 sp<MediaPlayerBase> p = getPlayer();
1283 if (p == 0) return UNKNOWN_ERROR;
1284 return p->notifyAt(mediaTimeUs);
1285}
1286
Glenn Kastenfff6d712012-01-12 16:38:12 -08001287status_t MediaPlayerService::Client::setAudioStreamType(audio_stream_type_t type)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001288{
Steve Block3856b092011-10-20 11:56:00 +01001289 ALOGV("[%d] setAudioStreamType(%d)", mConnId, type);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001290 // TODO: for hardware output, call player instead
1291 Mutex::Autolock l(mLock);
1292 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1293 return NO_ERROR;
1294}
1295
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001296status_t MediaPlayerService::Client::setAudioAttributes_l(const Parcel &parcel)
1297{
1298 if (mAudioAttributes != NULL) { free(mAudioAttributes); }
1299 mAudioAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001300 if (mAudioAttributes == NULL) {
1301 return NO_MEMORY;
1302 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001303 unmarshallAudioAttributes(parcel, mAudioAttributes);
1304
1305 ALOGV("setAudioAttributes_l() usage=%d content=%d flags=0x%x tags=%s",
1306 mAudioAttributes->usage, mAudioAttributes->content_type, mAudioAttributes->flags,
1307 mAudioAttributes->tags);
1308
1309 if (mAudioOutput != 0) {
1310 mAudioOutput->setAudioAttributes(mAudioAttributes);
1311 }
1312 return NO_ERROR;
1313}
1314
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001315status_t MediaPlayerService::Client::setLooping(int loop)
1316{
Steve Block3856b092011-10-20 11:56:00 +01001317 ALOGV("[%d] setLooping(%d)", mConnId, loop);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001318 mLoop = loop;
1319 sp<MediaPlayerBase> p = getPlayer();
1320 if (p != 0) return p->setLooping(loop);
1321 return NO_ERROR;
1322}
1323
1324status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1325{
Steve Block3856b092011-10-20 11:56:00 +01001326 ALOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
John Grossman761defc2012-02-09 15:09:05 -08001327
1328 // for hardware output, call player instead
1329 sp<MediaPlayerBase> p = getPlayer();
1330 {
1331 Mutex::Autolock l(mLock);
1332 if (p != 0 && p->hardwareOutput()) {
1333 MediaPlayerHWInterface* hwp =
1334 reinterpret_cast<MediaPlayerHWInterface*>(p.get());
1335 return hwp->setVolume(leftVolume, rightVolume);
1336 } else {
1337 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1338 return NO_ERROR;
1339 }
1340 }
1341
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001342 return NO_ERROR;
1343}
1344
Eric Laurent2beeb502010-07-16 07:43:46 -07001345status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1346{
Steve Block3856b092011-10-20 11:56:00 +01001347 ALOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
Eric Laurent2beeb502010-07-16 07:43:46 -07001348 Mutex::Autolock l(mLock);
1349 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1350 return NO_ERROR;
1351}
1352
1353status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1354{
Steve Block3856b092011-10-20 11:56:00 +01001355 ALOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
Eric Laurent2beeb502010-07-16 07:43:46 -07001356 Mutex::Autolock l(mLock);
1357 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1358 return NO_ERROR;
1359}
Nicolas Catania48290382009-07-10 13:53:06 -07001360
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001361status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
Steve Block3856b092011-10-20 11:56:00 +01001362 ALOGV("[%d] setParameter(%d)", mConnId, key);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001363 switch (key) {
1364 case KEY_PARAMETER_AUDIO_ATTRIBUTES:
1365 {
1366 Mutex::Autolock l(mLock);
1367 return setAudioAttributes_l(request);
1368 }
1369 default:
1370 sp<MediaPlayerBase> p = getPlayer();
1371 if (p == 0) { return UNKNOWN_ERROR; }
1372 return p->setParameter(key, request);
1373 }
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001374}
1375
1376status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
Steve Block3856b092011-10-20 11:56:00 +01001377 ALOGV("[%d] getParameter(%d)", mConnId, key);
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001378 sp<MediaPlayerBase> p = getPlayer();
1379 if (p == 0) return UNKNOWN_ERROR;
1380 return p->getParameter(key, reply);
1381}
1382
John Grossmanc795b642012-02-22 15:38:35 -08001383status_t MediaPlayerService::Client::setRetransmitEndpoint(
1384 const struct sockaddr_in* endpoint) {
1385
1386 if (NULL != endpoint) {
1387 uint32_t a = ntohl(endpoint->sin_addr.s_addr);
1388 uint16_t p = ntohs(endpoint->sin_port);
1389 ALOGV("[%d] setRetransmitEndpoint(%u.%u.%u.%u:%hu)", mConnId,
1390 (a >> 24), (a >> 16) & 0xFF, (a >> 8) & 0xFF, (a & 0xFF), p);
1391 } else {
1392 ALOGV("[%d] setRetransmitEndpoint = <none>", mConnId);
1393 }
1394
1395 sp<MediaPlayerBase> p = getPlayer();
1396
1397 // Right now, the only valid time to set a retransmit endpoint is before
1398 // player selection has been made (since the presence or absence of a
1399 // retransmit endpoint is going to determine which player is selected during
1400 // setDataSource).
1401 if (p != 0) return INVALID_OPERATION;
1402
1403 if (NULL != endpoint) {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001404 Mutex::Autolock lock(mLock);
John Grossmanc795b642012-02-22 15:38:35 -08001405 mRetransmitEndpoint = *endpoint;
1406 mRetransmitEndpointValid = true;
1407 } else {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001408 Mutex::Autolock lock(mLock);
John Grossmanc795b642012-02-22 15:38:35 -08001409 mRetransmitEndpointValid = false;
1410 }
1411
1412 return NO_ERROR;
1413}
1414
John Grossman44a7e422012-06-21 17:29:24 -07001415status_t MediaPlayerService::Client::getRetransmitEndpoint(
1416 struct sockaddr_in* endpoint)
1417{
1418 if (NULL == endpoint)
1419 return BAD_VALUE;
1420
1421 sp<MediaPlayerBase> p = getPlayer();
1422
1423 if (p != NULL)
1424 return p->getRetransmitEndpoint(endpoint);
1425
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001426 Mutex::Autolock lock(mLock);
John Grossman44a7e422012-06-21 17:29:24 -07001427 if (!mRetransmitEndpointValid)
1428 return NO_INIT;
1429
1430 *endpoint = mRetransmitEndpoint;
1431
1432 return NO_ERROR;
1433}
1434
Gloria Wangb483c472011-04-11 17:23:27 -07001435void MediaPlayerService::Client::notify(
1436 void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001437{
1438 Client* client = static_cast<Client*>(cookie);
James Dongb8a98252012-08-26 16:13:03 -07001439 if (client == NULL) {
1440 return;
1441 }
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001442
James Dongb8a98252012-08-26 16:13:03 -07001443 sp<IMediaPlayerClient> c;
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001444 sp<Client> nextClient;
1445 status_t errStartNext = NO_ERROR;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001446 {
1447 Mutex::Autolock l(client->mLock);
James Dongb8a98252012-08-26 16:13:03 -07001448 c = client->mClient;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001449 if (msg == MEDIA_PLAYBACK_COMPLETE && client->mNextClient != NULL) {
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001450 nextClient = client->mNextClient;
1451
John Grossmancb0b7552012-08-23 17:47:31 -07001452 if (client->mAudioOutput != NULL)
1453 client->mAudioOutput->switchToNextOutput();
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001454
1455 errStartNext = nextClient->start();
1456 }
1457 }
1458
1459 if (nextClient != NULL) {
1460 sp<IMediaPlayerClient> nc;
1461 {
1462 Mutex::Autolock l(nextClient->mLock);
1463 nc = nextClient->mClient;
1464 }
1465 if (nc != NULL) {
1466 if (errStartNext == NO_ERROR) {
1467 nc->notify(MEDIA_INFO, MEDIA_INFO_STARTED_AS_NEXT, 0, obj);
1468 } else {
1469 nc->notify(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN , 0, obj);
1470 ALOGE("gapless:start playback for next track failed, err(%d)", errStartNext);
Wei Jia2afac0c2016-01-07 12:13:07 -08001471 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001472 }
1473 }
1474
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001475 if (MEDIA_INFO == msg &&
Nicolas Catania48290382009-07-10 13:53:06 -07001476 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikoa64c8c72009-07-20 15:07:26 -07001477 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania48290382009-07-10 13:53:06 -07001478
1479 if(client->shouldDropMetadata(metadata_type)) {
1480 return;
1481 }
1482
1483 // Update the list of metadata that have changed. getMetadata
1484 // also access mMetadataUpdated and clears it.
1485 client->addNewMetadataUpdate(metadata_type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001486 }
James Dongb8a98252012-08-26 16:13:03 -07001487
1488 if (c != NULL) {
1489 ALOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
1490 c->notify(msg, ext1, ext2, obj);
1491 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001492}
1493
Nicolas Catania48290382009-07-10 13:53:06 -07001494
nikoa64c8c72009-07-20 15:07:26 -07001495bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001496{
Nicolas Catania48290382009-07-10 13:53:06 -07001497 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001498
Nicolas Catania48290382009-07-10 13:53:06 -07001499 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001500 return true;
1501 }
1502
Nicolas Catania48290382009-07-10 13:53:06 -07001503 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001504 return false;
Nicolas Catania48290382009-07-10 13:53:06 -07001505 } else {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001506 return true;
1507 }
1508}
1509
Nicolas Catania48290382009-07-10 13:53:06 -07001510
nikoa64c8c72009-07-20 15:07:26 -07001511void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania48290382009-07-10 13:53:06 -07001512 Mutex::Autolock lock(mLock);
1513 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1514 mMetadataUpdated.add(metadata_type);
1515 }
1516}
1517
Hassan Shojaniacefac142017-02-06 21:02:02 -08001518// Modular DRM
1519status_t MediaPlayerService::Client::prepareDrm(const uint8_t uuid[16],
1520 const Vector<uint8_t>& drmSessionId)
1521{
1522 ALOGV("[%d] prepareDrm", mConnId);
1523 sp<MediaPlayerBase> p = getPlayer();
1524 if (p == 0) return UNKNOWN_ERROR;
1525
1526 status_t ret = p->prepareDrm(uuid, drmSessionId);
1527 ALOGV("prepareDrm ret: %d", ret);
1528
1529 return ret;
1530}
1531
1532status_t MediaPlayerService::Client::releaseDrm()
1533{
1534 ALOGV("[%d] releaseDrm", mConnId);
1535 sp<MediaPlayerBase> p = getPlayer();
1536 if (p == 0) return UNKNOWN_ERROR;
1537
1538 status_t ret = p->releaseDrm();
1539 ALOGV("releaseDrm ret: %d", ret);
1540
1541 return ret;
1542}
1543
jiabin156c6872017-10-06 09:47:15 -07001544status_t MediaPlayerService::Client::setOutputDevice(audio_port_handle_t deviceId)
1545{
1546 ALOGV("[%d] setOutputDevice", mConnId);
1547 {
1548 Mutex::Autolock l(mLock);
1549 if (mAudioOutput.get() != nullptr) {
1550 return mAudioOutput->setOutputDevice(deviceId);
1551 }
1552 }
1553 return NO_INIT;
1554}
1555
1556status_t MediaPlayerService::Client::getRoutedDeviceId(audio_port_handle_t* deviceId)
1557{
1558 ALOGV("[%d] getRoutedDeviceId", mConnId);
1559 {
1560 Mutex::Autolock l(mLock);
1561 if (mAudioOutput.get() != nullptr) {
1562 return mAudioOutput->getRoutedDeviceId(deviceId);
1563 }
1564 }
1565 return NO_INIT;
1566}
1567
1568status_t MediaPlayerService::Client::enableAudioDeviceCallback(bool enabled)
1569{
1570 ALOGV("[%d] enableAudioDeviceCallback, %d", mConnId, enabled);
1571 {
1572 Mutex::Autolock l(mLock);
1573 if (mAudioOutput.get() != nullptr) {
1574 return mAudioOutput->enableAudioDeviceCallback(enabled);
1575 }
1576 }
1577 return NO_INIT;
1578}
1579
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001580#if CALLBACK_ANTAGONIZER
1581const int Antagonizer::interval = 10000; // 10 msecs
1582
1583Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1584 mExit(false), mActive(false), mClient(client), mCb(cb)
1585{
1586 createThread(callbackThread, this);
1587}
1588
1589void Antagonizer::kill()
1590{
1591 Mutex::Autolock _l(mLock);
1592 mActive = false;
1593 mExit = true;
1594 mCondition.wait(mLock);
1595}
1596
1597int Antagonizer::callbackThread(void* user)
1598{
Steve Blockb8a80522011-12-20 16:23:08 +00001599 ALOGD("Antagonizer started");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001600 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1601 while (!p->mExit) {
1602 if (p->mActive) {
Steve Block3856b092011-10-20 11:56:00 +01001603 ALOGV("send event");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001604 p->mCb(p->mClient, 0, 0, 0);
1605 }
1606 usleep(interval);
1607 }
1608 Mutex::Autolock _l(p->mLock);
1609 p->mCondition.signal();
Steve Blockb8a80522011-12-20 16:23:08 +00001610 ALOGD("Antagonizer stopped");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001611 return 0;
1612}
1613#endif
1614
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001615#undef LOG_TAG
1616#define LOG_TAG "AudioSink"
Andy Hung1afd0982016-11-08 16:13:44 -08001617MediaPlayerService::AudioOutput::AudioOutput(audio_session_t sessionId, uid_t uid, int pid,
jiabin156c6872017-10-06 09:47:15 -07001618 const audio_attributes_t* attr, const sp<AudioSystem::AudioDeviceCallback>& deviceCallback)
Andreas Huber20111aa2009-07-14 16:56:47 -07001619 : mCallback(NULL),
Eric Laurenta514bdb2010-06-21 09:27:30 -07001620 mCallbackCookie(NULL),
Marco Nelissen6b74d672012-02-28 16:07:44 -08001621 mCallbackData(NULL),
Andy Hungd1c74342015-07-07 16:54:23 -07001622 mStreamType(AUDIO_STREAM_MUSIC),
Andy Hungd1c74342015-07-07 16:54:23 -07001623 mLeftVolume(1.0),
1624 mRightVolume(1.0),
1625 mPlaybackRate(AUDIO_PLAYBACK_RATE_DEFAULT),
1626 mSampleRateHz(0),
1627 mMsecsPerFrame(0),
1628 mFrameSize(0),
Eric Laurent1948eb32012-04-13 16:50:19 -07001629 mSessionId(sessionId),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001630 mUid(uid),
Marco Nelissend457c972014-02-11 08:47:07 -08001631 mPid(pid),
Andy Hungd1c74342015-07-07 16:54:23 -07001632 mSendLevel(0.0),
1633 mAuxEffectId(0),
Andy Hung4ef88d72017-02-21 19:47:53 -08001634 mFlags(AUDIO_OUTPUT_FLAG_NONE),
jiabin156c6872017-10-06 09:47:15 -07001635 mVolumeHandler(new media::VolumeHandler()),
1636 mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE),
1637 mDeviceCallbackEnabled(false),
1638 mDeviceCallback(deviceCallback)
Andy Hungd1c74342015-07-07 16:54:23 -07001639{
Steve Block3856b092011-10-20 11:56:00 +01001640 ALOGV("AudioOutput(%d)", sessionId);
Eric Laurent43562692015-07-15 16:49:07 -07001641 if (attr != NULL) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001642 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1643 if (mAttributes != NULL) {
1644 memcpy(mAttributes, attr, sizeof(audio_attributes_t));
1645 mStreamType = audio_attributes_to_stream_type(attr);
1646 }
1647 } else {
1648 mAttributes = NULL;
Eric Laurent43562692015-07-15 16:49:07 -07001649 }
1650
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001651 setMinBufferCount();
1652}
1653
1654MediaPlayerService::AudioOutput::~AudioOutput()
1655{
1656 close();
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001657 free(mAttributes);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001658 delete mCallbackData;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001659}
1660
Andy Hungd1c74342015-07-07 16:54:23 -07001661//static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001662void MediaPlayerService::AudioOutput::setMinBufferCount()
1663{
1664 char value[PROPERTY_VALUE_MAX];
1665 if (property_get("ro.kernel.qemu", value, 0)) {
1666 mIsOnEmulator = true;
1667 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1668 }
1669}
1670
Andy Hungd1c74342015-07-07 16:54:23 -07001671// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001672bool MediaPlayerService::AudioOutput::isOnEmulator()
1673{
Andy Hungd1c74342015-07-07 16:54:23 -07001674 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001675 return mIsOnEmulator;
1676}
1677
Andy Hungd1c74342015-07-07 16:54:23 -07001678// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001679int MediaPlayerService::AudioOutput::getMinBufferCount()
1680{
Andy Hungd1c74342015-07-07 16:54:23 -07001681 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001682 return mMinBufferCount;
1683}
1684
1685ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1686{
Andy Hungd1c74342015-07-07 16:54:23 -07001687 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001688 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001689 return mTrack->frameCount() * mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001690}
1691
1692ssize_t MediaPlayerService::AudioOutput::frameCount() const
1693{
Andy Hungd1c74342015-07-07 16:54:23 -07001694 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001695 if (mTrack == 0) return NO_INIT;
1696 return mTrack->frameCount();
1697}
1698
1699ssize_t MediaPlayerService::AudioOutput::channelCount() const
1700{
Andy Hungd1c74342015-07-07 16:54:23 -07001701 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001702 if (mTrack == 0) return NO_INIT;
1703 return mTrack->channelCount();
1704}
1705
1706ssize_t MediaPlayerService::AudioOutput::frameSize() const
1707{
Andy Hungd1c74342015-07-07 16:54:23 -07001708 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001709 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001710 return mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001711}
1712
1713uint32_t MediaPlayerService::AudioOutput::latency () const
1714{
Andy Hungd1c74342015-07-07 16:54:23 -07001715 Mutex::Autolock lock(mLock);
Eric Laurentdb354e52012-03-05 17:27:11 -08001716 if (mTrack == 0) return 0;
1717 return mTrack->latency();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001718}
1719
1720float MediaPlayerService::AudioOutput::msecsPerFrame() const
1721{
Andy Hungd1c74342015-07-07 16:54:23 -07001722 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001723 return mMsecsPerFrame;
1724}
1725
Marco Nelissen4110c102012-03-29 09:31:28 -07001726status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position) const
Eric Laurent342e9cf2010-01-19 17:37:09 -08001727{
Andy Hungd1c74342015-07-07 16:54:23 -07001728 Mutex::Autolock lock(mLock);
Eric Laurent342e9cf2010-01-19 17:37:09 -08001729 if (mTrack == 0) return NO_INIT;
1730 return mTrack->getPosition(position);
1731}
1732
Lajos Molnar06ad1522014-08-28 07:27:44 -07001733status_t MediaPlayerService::AudioOutput::getTimestamp(AudioTimestamp &ts) const
1734{
Andy Hungd1c74342015-07-07 16:54:23 -07001735 Mutex::Autolock lock(mLock);
Lajos Molnar06ad1522014-08-28 07:27:44 -07001736 if (mTrack == 0) return NO_INIT;
1737 return mTrack->getTimestamp(ts);
1738}
1739
Wei Jiac4ac8172015-10-21 10:35:48 -07001740// TODO: Remove unnecessary calls to getPlayedOutDurationUs()
1741// as it acquires locks and may query the audio driver.
1742//
1743// Some calls could conceivably retrieve extrapolated data instead of
1744// accessing getTimestamp() or getPosition() every time a data buffer with
1745// a media time is received.
1746//
1747// Calculate duration of played samples if played at normal rate (i.e., 1.0).
1748int64_t MediaPlayerService::AudioOutput::getPlayedOutDurationUs(int64_t nowUs) const
1749{
1750 Mutex::Autolock lock(mLock);
1751 if (mTrack == 0 || mSampleRateHz == 0) {
Wei Jia213f4902015-10-22 08:55:25 -07001752 return 0;
Wei Jiac4ac8172015-10-21 10:35:48 -07001753 }
1754
1755 uint32_t numFramesPlayed;
Andy Hung5d313802016-10-10 15:09:39 -07001756 int64_t numFramesPlayedAtUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001757 AudioTimestamp ts;
Wei Jiac4ac8172015-10-21 10:35:48 -07001758
1759 status_t res = mTrack->getTimestamp(ts);
1760 if (res == OK) { // case 1: mixing audio tracks and offloaded tracks.
1761 numFramesPlayed = ts.mPosition;
Andy Hung5d313802016-10-10 15:09:39 -07001762 numFramesPlayedAtUs = ts.mTime.tv_sec * 1000000LL + ts.mTime.tv_nsec / 1000;
1763 //ALOGD("getTimestamp: OK %d %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001764 } else if (res == WOULD_BLOCK) { // case 2: transitory state on start of a new track
1765 numFramesPlayed = 0;
Andy Hung5d313802016-10-10 15:09:39 -07001766 numFramesPlayedAtUs = nowUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001767 //ALOGD("getTimestamp: WOULD_BLOCK %d %lld",
Andy Hung5d313802016-10-10 15:09:39 -07001768 // numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001769 } else { // case 3: transitory at new track or audio fast tracks.
1770 res = mTrack->getPosition(&numFramesPlayed);
1771 CHECK_EQ(res, (status_t)OK);
Andy Hung5d313802016-10-10 15:09:39 -07001772 numFramesPlayedAtUs = nowUs;
1773 numFramesPlayedAtUs += 1000LL * mTrack->latency() / 2; /* XXX */
1774 //ALOGD("getPosition: %u %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001775 }
1776
1777 // CHECK_EQ(numFramesPlayed & (1 << 31), 0); // can't be negative until 12.4 hrs, test
1778 // TODO: remove the (int32_t) casting below as it may overflow at 12.4 hours.
1779 int64_t durationUs = (int64_t)((int32_t)numFramesPlayed * 1000000LL / mSampleRateHz)
Andy Hung5d313802016-10-10 15:09:39 -07001780 + nowUs - numFramesPlayedAtUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001781 if (durationUs < 0) {
1782 // Occurs when numFramesPlayed position is very small and the following:
1783 // (1) In case 1, the time nowUs is computed before getTimestamp() is called and
Andy Hung5d313802016-10-10 15:09:39 -07001784 // numFramesPlayedAtUs is greater than nowUs by time more than numFramesPlayed.
Wei Jiac4ac8172015-10-21 10:35:48 -07001785 // (2) In case 3, using getPosition and adding mAudioSink->latency() to
Andy Hung5d313802016-10-10 15:09:39 -07001786 // numFramesPlayedAtUs, by a time amount greater than numFramesPlayed.
Wei Jiac4ac8172015-10-21 10:35:48 -07001787 //
1788 // Both of these are transitory conditions.
1789 ALOGV("getPlayedOutDurationUs: negative duration %lld set to zero", (long long)durationUs);
1790 durationUs = 0;
1791 }
1792 ALOGV("getPlayedOutDurationUs(%lld) nowUs(%lld) frames(%u) framesAt(%lld)",
Andy Hung5d313802016-10-10 15:09:39 -07001793 (long long)durationUs, (long long)nowUs,
1794 numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001795 return durationUs;
1796}
1797
Marco Nelissen4110c102012-03-29 09:31:28 -07001798status_t MediaPlayerService::AudioOutput::getFramesWritten(uint32_t *frameswritten) const
1799{
Andy Hungd1c74342015-07-07 16:54:23 -07001800 Mutex::Autolock lock(mLock);
Marco Nelissen4110c102012-03-29 09:31:28 -07001801 if (mTrack == 0) return NO_INIT;
Andy Hung2f6e73d2016-04-08 12:12:58 -07001802 ExtendedTimestamp ets;
1803 status_t status = mTrack->getTimestamp(&ets);
1804 if (status == OK || status == WOULD_BLOCK) {
1805 *frameswritten = (uint32_t)ets.mPosition[ExtendedTimestamp::LOCATION_CLIENT];
1806 }
1807 return status;
Marco Nelissen4110c102012-03-29 09:31:28 -07001808}
1809
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001810status_t MediaPlayerService::AudioOutput::setParameters(const String8& keyValuePairs)
1811{
Andy Hungd1c74342015-07-07 16:54:23 -07001812 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001813 if (mTrack == 0) return NO_INIT;
1814 return mTrack->setParameters(keyValuePairs);
1815}
1816
1817String8 MediaPlayerService::AudioOutput::getParameters(const String8& keys)
1818{
Andy Hungd1c74342015-07-07 16:54:23 -07001819 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001820 if (mTrack == 0) return String8::empty();
1821 return mTrack->getParameters(keys);
1822}
1823
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001824void MediaPlayerService::AudioOutput::setAudioAttributes(const audio_attributes_t * attributes) {
Andy Hungd1c74342015-07-07 16:54:23 -07001825 Mutex::Autolock lock(mLock);
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001826 if (attributes == NULL) {
1827 free(mAttributes);
1828 mAttributes = NULL;
1829 } else {
1830 if (mAttributes == NULL) {
1831 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1832 }
1833 memcpy(mAttributes, attributes, sizeof(audio_attributes_t));
Eric Laurent43562692015-07-15 16:49:07 -07001834 mStreamType = audio_attributes_to_stream_type(attributes);
1835 }
1836}
1837
1838void MediaPlayerService::AudioOutput::setAudioStreamType(audio_stream_type_t streamType)
1839{
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001840 Mutex::Autolock lock(mLock);
Eric Laurent43562692015-07-15 16:49:07 -07001841 // do not allow direct stream type modification if attributes have been set
1842 if (mAttributes == NULL) {
1843 mStreamType = streamType;
1844 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001845}
1846
Andy Hungd1c74342015-07-07 16:54:23 -07001847void MediaPlayerService::AudioOutput::deleteRecycledTrack_l()
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001848{
Andy Hungd1c74342015-07-07 16:54:23 -07001849 ALOGV("deleteRecycledTrack_l");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001850 if (mRecycledTrack != 0) {
1851
1852 if (mCallbackData != NULL) {
1853 mCallbackData->setOutput(NULL);
1854 mCallbackData->endTrackSwitch();
1855 }
1856
1857 if ((mRecycledTrack->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) {
Andy Hunge13f8a62016-03-30 14:20:42 -07001858 int32_t msec = 0;
1859 if (!mRecycledTrack->stopped()) { // check if active
1860 (void)mRecycledTrack->pendingDuration(&msec);
1861 }
1862 mRecycledTrack->stop(); // ensure full data drain
1863 ALOGD("deleting recycled track, waiting for data drain (%d msec)", msec);
1864 if (msec > 0) {
1865 static const int32_t WAIT_LIMIT_MS = 3000;
1866 if (msec > WAIT_LIMIT_MS) {
1867 msec = WAIT_LIMIT_MS;
1868 }
1869 usleep(msec * 1000LL);
1870 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001871 }
1872 // An offloaded track isn't flushed because the STREAM_END is reported
1873 // slightly prematurely to allow time for the gapless track switch
1874 // but this means that if we decide not to recycle the track there
1875 // could be a small amount of residual data still playing. We leave
1876 // AudioFlinger to drain the track.
1877
1878 mRecycledTrack.clear();
Andy Hungd1c74342015-07-07 16:54:23 -07001879 close_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001880 delete mCallbackData;
1881 mCallbackData = NULL;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001882 }
1883}
1884
Andy Hungd1c74342015-07-07 16:54:23 -07001885void MediaPlayerService::AudioOutput::close_l()
1886{
1887 mTrack.clear();
1888}
1889
Andreas Huber20111aa2009-07-14 16:56:47 -07001890status_t MediaPlayerService::AudioOutput::open(
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001891 uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
1892 audio_format_t format, int bufferCount,
Eric Laurent1948eb32012-04-13 16:50:19 -07001893 AudioCallback cb, void *cookie,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001894 audio_output_flags_t flags,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001895 const audio_offload_info_t *offloadInfo,
Andy Hung179652e2015-05-31 22:49:46 -07001896 bool doNotReconnect,
1897 uint32_t suggestedFrameCount)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001898{
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001899 ALOGV("open(%u, %d, 0x%x, 0x%x, %d, %d 0x%x)", sampleRate, channelCount, channelMask,
1900 format, bufferCount, mSessionId, flags);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001901
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001902 // offloading is only supported in callback mode for now.
1903 // offloadInfo must be present if offload flag is set
1904 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) &&
1905 ((cb == NULL) || (offloadInfo == NULL))) {
1906 return BAD_VALUE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001907 }
1908
Andy Hung179652e2015-05-31 22:49:46 -07001909 // compute frame count for the AudioTrack internal buffer
1910 size_t frameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001911 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1912 frameCount = 0; // AudioTrack will get frame count from AudioFlinger
1913 } else {
Andy Hung179652e2015-05-31 22:49:46 -07001914 // try to estimate the buffer processing fetch size from AudioFlinger.
1915 // framesPerBuffer is approximate and generally correct, except when it's not :-).
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001916 uint32_t afSampleRate;
1917 size_t afFrameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001918 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1919 return NO_INIT;
1920 }
1921 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1922 return NO_INIT;
1923 }
Andy Hung179652e2015-05-31 22:49:46 -07001924 const size_t framesPerBuffer =
1925 (unsigned long long)sampleRate * afFrameCount / afSampleRate;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001926
Andy Hung179652e2015-05-31 22:49:46 -07001927 if (bufferCount == 0) {
1928 // use suggestedFrameCount
1929 bufferCount = (suggestedFrameCount + framesPerBuffer - 1) / framesPerBuffer;
1930 }
1931 // Check argument bufferCount against the mininum buffer count
1932 if (bufferCount != 0 && bufferCount < mMinBufferCount) {
1933 ALOGV("bufferCount (%d) increased to %d", bufferCount, mMinBufferCount);
1934 bufferCount = mMinBufferCount;
1935 }
1936 // if frameCount is 0, then AudioTrack will get frame count from AudioFlinger
1937 // which will be the minimum size permitted.
1938 frameCount = bufferCount * framesPerBuffer;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001939 }
Andreas Huber20111aa2009-07-14 16:56:47 -07001940
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001941 if (channelMask == CHANNEL_MASK_USE_CHANNEL_ORDER) {
Glenn Kastenab334fd2012-03-14 12:56:06 -07001942 channelMask = audio_channel_out_mask_from_count(channelCount);
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001943 if (0 == channelMask) {
1944 ALOGE("open() error, can\'t derive mask for %d audio channels", channelCount);
1945 return NO_INIT;
1946 }
1947 }
Eric Laurent1948eb32012-04-13 16:50:19 -07001948
Andy Hungd1c74342015-07-07 16:54:23 -07001949 Mutex::Autolock lock(mLock);
Andy Hung179652e2015-05-31 22:49:46 -07001950 mCallback = cb;
1951 mCallbackCookie = cookie;
1952
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001953 // Check whether we can recycle the track
1954 bool reuse = false;
1955 bool bothOffloaded = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001956
Glenn Kasten2799d742013-05-30 14:33:29 -07001957 if (mRecycledTrack != 0) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001958 // check whether we are switching between two offloaded tracks
1959 bothOffloaded = (flags & mRecycledTrack->getFlags()
1960 & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0;
Marco Nelissen67295b52012-06-11 14:52:53 -07001961
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001962 // check if the existing track can be reused as-is, or if a new track needs to be created.
1963 reuse = true;
1964
Marco Nelissen67295b52012-06-11 14:52:53 -07001965 if ((mCallbackData == NULL && mCallback != NULL) ||
1966 (mCallbackData != NULL && mCallback == NULL)) {
1967 // recycled track uses callbacks but the caller wants to use writes, or vice versa
1968 ALOGV("can't chain callback and write");
1969 reuse = false;
1970 } else if ((mRecycledTrack->getSampleRate() != sampleRate) ||
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001971 (mRecycledTrack->channelCount() != (uint32_t)channelCount) ) {
1972 ALOGV("samplerate, channelcount differ: %u/%u Hz, %u/%d ch",
Marco Nelissen67295b52012-06-11 14:52:53 -07001973 mRecycledTrack->getSampleRate(), sampleRate,
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001974 mRecycledTrack->channelCount(), channelCount);
Marco Nelissen67295b52012-06-11 14:52:53 -07001975 reuse = false;
1976 } else if (flags != mFlags) {
1977 ALOGV("output flags differ %08x/%08x", flags, mFlags);
1978 reuse = false;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001979 } else if (mRecycledTrack->format() != format) {
1980 reuse = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001981 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001982 } else {
1983 ALOGV("no track available to recycle");
1984 }
1985
1986 ALOGV_IF(bothOffloaded, "both tracks offloaded");
1987
1988 // If we can't recycle and both tracks are offloaded
1989 // we must close the previous output before opening a new one
1990 if (bothOffloaded && !reuse) {
1991 ALOGV("both offloaded and not recycling");
Andy Hungd1c74342015-07-07 16:54:23 -07001992 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001993 }
1994
1995 sp<AudioTrack> t;
1996 CallbackData *newcbd = NULL;
1997
1998 // We don't attempt to create a new track if we are recycling an
1999 // offloaded track. But, if we are recycling a non-offloaded or we
2000 // are switching where one is offloaded and one isn't then we create
2001 // the new track in advance so that we can read additional stream info
2002
2003 if (!(reuse && bothOffloaded)) {
2004 ALOGV("creating new AudioTrack");
2005
2006 if (mCallback != NULL) {
2007 newcbd = new CallbackData(this);
2008 t = new AudioTrack(
2009 mStreamType,
2010 sampleRate,
2011 format,
2012 channelMask,
2013 frameCount,
2014 flags,
2015 CallbackWrapper,
2016 newcbd,
2017 0, // notification frames
2018 mSessionId,
2019 AudioTrack::TRANSFER_CALLBACK,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002020 offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -08002021 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07002022 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07002023 mAttributes,
jiabin156c6872017-10-06 09:47:15 -07002024 doNotReconnect,
2025 1.0f, // default value for maxRequiredSpeed
2026 mSelectedDeviceId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002027 } else {
Andy Hungff874dc2016-04-11 16:49:09 -07002028 // TODO: Due to buffer memory concerns, we use a max target playback speed
2029 // based on mPlaybackRate at the time of open (instead of kMaxRequiredSpeed),
2030 // also clamping the target speed to 1.0 <= targetSpeed <= kMaxRequiredSpeed.
2031 const float targetSpeed =
2032 std::min(std::max(mPlaybackRate.mSpeed, 1.0f), kMaxRequiredSpeed);
2033 ALOGW_IF(targetSpeed != mPlaybackRate.mSpeed,
2034 "track target speed:%f clamped from playback speed:%f",
2035 targetSpeed, mPlaybackRate.mSpeed);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002036 t = new AudioTrack(
2037 mStreamType,
2038 sampleRate,
2039 format,
2040 channelMask,
2041 frameCount,
2042 flags,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002043 NULL, // callback
2044 NULL, // user data
2045 0, // notification frames
2046 mSessionId,
2047 AudioTrack::TRANSFER_DEFAULT,
2048 NULL, // offload info
Marco Nelissend457c972014-02-11 08:47:07 -08002049 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07002050 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07002051 mAttributes,
Andy Hungff874dc2016-04-11 16:49:09 -07002052 doNotReconnect,
jiabin156c6872017-10-06 09:47:15 -07002053 targetSpeed,
2054 mSelectedDeviceId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002055 }
2056
2057 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
2058 ALOGE("Unable to create audio track");
2059 delete newcbd;
Glenn Kasten3e98ecd2015-05-18 13:13:24 -07002060 // t goes out of scope, so reference count drops to zero
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002061 return NO_INIT;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07002062 } else {
2063 // successful AudioTrack initialization implies a legacy stream type was generated
2064 // from the audio attributes
2065 mStreamType = t->streamType();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002066 }
2067 }
2068
2069 if (reuse) {
2070 CHECK(mRecycledTrack != NULL);
2071
2072 if (!bothOffloaded) {
2073 if (mRecycledTrack->frameCount() != t->frameCount()) {
Andy Hung833b4752016-04-04 17:15:48 -07002074 ALOGV("framecount differs: %zu/%zu frames",
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002075 mRecycledTrack->frameCount(), t->frameCount());
2076 reuse = false;
2077 }
2078 }
2079
Marco Nelissen67295b52012-06-11 14:52:53 -07002080 if (reuse) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002081 ALOGV("chaining to next output and recycling track");
Andy Hungd1c74342015-07-07 16:54:23 -07002082 close_l();
Marco Nelissen67295b52012-06-11 14:52:53 -07002083 mTrack = mRecycledTrack;
Glenn Kasten2799d742013-05-30 14:33:29 -07002084 mRecycledTrack.clear();
Marco Nelissen67295b52012-06-11 14:52:53 -07002085 if (mCallbackData != NULL) {
2086 mCallbackData->setOutput(this);
2087 }
Marco Nelissen67295b52012-06-11 14:52:53 -07002088 delete newcbd;
Wei Jiae0bbac92016-07-18 16:04:53 -07002089 return updateTrack();
Marco Nelissen67295b52012-06-11 14:52:53 -07002090 }
Marco Nelissen67295b52012-06-11 14:52:53 -07002091 }
2092
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002093 // we're not going to reuse the track, unblock and flush it
2094 // this was done earlier if both tracks are offloaded
2095 if (!bothOffloaded) {
Andy Hungd1c74342015-07-07 16:54:23 -07002096 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002097 }
2098
2099 CHECK((t != NULL) && ((mCallback == NULL) || (newcbd != NULL)));
2100
Marco Nelissen67295b52012-06-11 14:52:53 -07002101 mCallbackData = newcbd;
Steve Block3856b092011-10-20 11:56:00 +01002102 ALOGV("setVolume");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002103 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07002104
Andy Hung39399b62017-04-21 15:07:45 -07002105 // Restore VolumeShapers for the MediaPlayer in case the track was recreated
2106 // due to an output sink error (e.g. offload to non-offload switch).
2107 mVolumeHandler->forall([&t](const VolumeShaper &shaper) -> VolumeShaper::Status {
2108 sp<VolumeShaper::Operation> operationToEnd =
2109 new VolumeShaper::Operation(shaper.mOperation);
2110 // TODO: Ideally we would restore to the exact xOffset position
2111 // as returned by getVolumeShaperState(), but we don't have that
2112 // information when restoring at the client unless we periodically poll
2113 // the server or create shared memory state.
2114 //
2115 // For now, we simply advance to the end of the VolumeShaper effect
2116 // if it has been started.
2117 if (shaper.isStarted()) {
Andy Hungf3702642017-05-05 17:33:32 -07002118 operationToEnd->setNormalizedTime(1.f);
Andy Hung39399b62017-04-21 15:07:45 -07002119 }
2120 return t->applyVolumeShaper(shaper.mConfiguration, operationToEnd);
Andy Hung4ef88d72017-02-21 19:47:53 -08002121 });
Andy Hung4ef88d72017-02-21 19:47:53 -08002122
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002123 mSampleRateHz = sampleRate;
Preetam Singh Ranawat2e17eef2015-08-12 12:11:46 -07002124 mFlags = flags;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002125 mMsecsPerFrame = 1E3f / (mPlaybackRate.mSpeed * sampleRate);
Andy Hungd1c74342015-07-07 16:54:23 -07002126 mFrameSize = t->frameSize();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002127 mTrack = t;
Eric Laurent2beeb502010-07-16 07:43:46 -07002128
Wei Jiae0bbac92016-07-18 16:04:53 -07002129 return updateTrack();
2130}
2131
2132status_t MediaPlayerService::AudioOutput::updateTrack() {
2133 if (mTrack == NULL) {
2134 return NO_ERROR;
2135 }
2136
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002137 status_t res = NO_ERROR;
Wei Jia0162d002015-06-09 11:59:33 -07002138 // Note some output devices may give us a direct track even though we don't specify it.
2139 // Example: Line application b/17459982.
Wei Jiae0bbac92016-07-18 16:04:53 -07002140 if ((mTrack->getFlags()
2141 & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) {
2142 res = mTrack->setPlaybackRate(mPlaybackRate);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002143 if (res == NO_ERROR) {
Wei Jiae0bbac92016-07-18 16:04:53 -07002144 mTrack->setAuxEffectSendLevel(mSendLevel);
2145 res = mTrack->attachAuxEffect(mAuxEffectId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002146 }
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002147 }
jiabin156c6872017-10-06 09:47:15 -07002148 mTrack->setOutputDevice(mSelectedDeviceId);
2149 if (mDeviceCallbackEnabled) {
2150 mTrack->addAudioDeviceCallback(mDeviceCallback.promote());
2151 }
Wei Jiae0bbac92016-07-18 16:04:53 -07002152 ALOGV("updateTrack() DONE status %d", res);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002153 return res;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002154}
2155
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002156status_t MediaPlayerService::AudioOutput::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002157{
Steve Block3856b092011-10-20 11:56:00 +01002158 ALOGV("start");
Andy Hungd1c74342015-07-07 16:54:23 -07002159 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08002160 if (mCallbackData != NULL) {
2161 mCallbackData->endTrackSwitch();
2162 }
Glenn Kasten2799d742013-05-30 14:33:29 -07002163 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002164 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07002165 mTrack->setAuxEffectSendLevel(mSendLevel);
Andy Hung39399b62017-04-21 15:07:45 -07002166 status_t status = mTrack->start();
2167 if (status == NO_ERROR) {
2168 mVolumeHandler->setStarted();
2169 }
2170 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002171 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002172 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002173}
2174
Marco Nelissen6b74d672012-02-28 16:07:44 -08002175void MediaPlayerService::AudioOutput::setNextOutput(const sp<AudioOutput>& nextOutput) {
Andy Hungd1c74342015-07-07 16:54:23 -07002176 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08002177 mNextOutput = nextOutput;
2178}
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08002179
Marco Nelissen6b74d672012-02-28 16:07:44 -08002180void MediaPlayerService::AudioOutput::switchToNextOutput() {
2181 ALOGV("switchToNextOutput");
Andy Hungd1c74342015-07-07 16:54:23 -07002182
2183 // Try to acquire the callback lock before moving track (without incurring deadlock).
2184 const unsigned kMaxSwitchTries = 100;
2185 Mutex::Autolock lock(mLock);
2186 for (unsigned tries = 0;;) {
2187 if (mTrack == 0) {
2188 return;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002189 }
Andy Hungd1c74342015-07-07 16:54:23 -07002190 if (mNextOutput != NULL && mNextOutput != this) {
2191 if (mCallbackData != NULL) {
2192 // two alternative approaches
2193#if 1
2194 CallbackData *callbackData = mCallbackData;
2195 mLock.unlock();
2196 // proper acquisition sequence
2197 callbackData->lock();
2198 mLock.lock();
2199 // Caution: it is unlikely that someone deleted our callback or changed our target
2200 if (callbackData != mCallbackData || mNextOutput == NULL || mNextOutput == this) {
2201 // fatal if we are starved out.
2202 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2203 "switchToNextOutput() cannot obtain correct lock sequence");
2204 callbackData->unlock();
2205 continue;
2206 }
2207 callbackData->mSwitching = true; // begin track switch
Wei Jiaadee56a2016-08-05 15:40:34 -07002208 callbackData->setOutput(NULL);
Andy Hungd1c74342015-07-07 16:54:23 -07002209#else
2210 // tryBeginTrackSwitch() returns false if the callback has the lock.
2211 if (!mCallbackData->tryBeginTrackSwitch()) {
2212 // fatal if we are starved out.
2213 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2214 "switchToNextOutput() cannot obtain callback lock");
2215 mLock.unlock();
2216 usleep(5 * 1000 /* usec */); // allow callback to use AudioOutput
2217 mLock.lock();
2218 continue;
2219 }
2220#endif
2221 }
2222
2223 Mutex::Autolock nextLock(mNextOutput->mLock);
2224
2225 // If the next output track is not NULL, then it has been
2226 // opened already for playback.
2227 // This is possible even without the next player being started,
2228 // for example, the next player could be prepared and seeked.
2229 //
2230 // Presuming it isn't advisable to force the track over.
2231 if (mNextOutput->mTrack == NULL) {
2232 ALOGD("Recycling track for gapless playback");
2233 delete mNextOutput->mCallbackData;
2234 mNextOutput->mCallbackData = mCallbackData;
2235 mNextOutput->mRecycledTrack = mTrack;
2236 mNextOutput->mSampleRateHz = mSampleRateHz;
2237 mNextOutput->mMsecsPerFrame = mMsecsPerFrame;
Andy Hungd1c74342015-07-07 16:54:23 -07002238 mNextOutput->mFlags = mFlags;
2239 mNextOutput->mFrameSize = mFrameSize;
2240 close_l();
2241 mCallbackData = NULL; // destruction handled by mNextOutput
2242 } else {
2243 ALOGW("Ignoring gapless playback because next player has already started");
2244 // remove track in case resource needed for future players.
2245 if (mCallbackData != NULL) {
2246 mCallbackData->endTrackSwitch(); // release lock for callbacks before close.
2247 }
2248 close_l();
2249 }
2250 }
2251 break;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002252 }
2253}
2254
Wei Jia7d3f4df2015-03-03 15:28:00 -08002255ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002256{
Andy Hungd1c74342015-07-07 16:54:23 -07002257 Mutex::Autolock lock(mLock);
Glenn Kastenadad3d72014-02-21 14:51:43 -08002258 LOG_ALWAYS_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
Andreas Huber20111aa2009-07-14 16:56:47 -07002259
Steve Block3856b092011-10-20 11:56:00 +01002260 //ALOGV("write(%p, %u)", buffer, size);
Glenn Kasten2799d742013-05-30 14:33:29 -07002261 if (mTrack != 0) {
Andy Hung2f6e73d2016-04-08 12:12:58 -07002262 return mTrack->write(buffer, size, blocking);
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07002263 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002264 return NO_INIT;
2265}
2266
2267void MediaPlayerService::AudioOutput::stop()
2268{
Steve Block3856b092011-10-20 11:56:00 +01002269 ALOGV("stop");
Andy Hungd1c74342015-07-07 16:54:23 -07002270 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002271 if (mTrack != 0) mTrack->stop();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002272}
2273
2274void MediaPlayerService::AudioOutput::flush()
2275{
Steve Block3856b092011-10-20 11:56:00 +01002276 ALOGV("flush");
Andy Hungd1c74342015-07-07 16:54:23 -07002277 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002278 if (mTrack != 0) mTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002279}
2280
2281void MediaPlayerService::AudioOutput::pause()
2282{
Steve Block3856b092011-10-20 11:56:00 +01002283 ALOGV("pause");
Andy Hungd1c74342015-07-07 16:54:23 -07002284 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002285 if (mTrack != 0) mTrack->pause();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002286}
2287
2288void MediaPlayerService::AudioOutput::close()
2289{
Steve Block3856b092011-10-20 11:56:00 +01002290 ALOGV("close");
Erik Wolsheimer7845a1f2015-10-30 12:07:52 -07002291 sp<AudioTrack> track;
2292 {
2293 Mutex::Autolock lock(mLock);
2294 track = mTrack;
2295 close_l(); // clears mTrack
2296 }
2297 // destruction of the track occurs outside of mutex.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002298}
2299
2300void MediaPlayerService::AudioOutput::setVolume(float left, float right)
2301{
Steve Block3856b092011-10-20 11:56:00 +01002302 ALOGV("setVolume(%f, %f)", left, right);
Andy Hungd1c74342015-07-07 16:54:23 -07002303 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002304 mLeftVolume = left;
2305 mRightVolume = right;
Glenn Kasten2799d742013-05-30 14:33:29 -07002306 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002307 mTrack->setVolume(left, right);
2308 }
2309}
2310
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002311status_t MediaPlayerService::AudioOutput::setPlaybackRate(const AudioPlaybackRate &rate)
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002312{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002313 ALOGV("setPlaybackRate(%f %f %d %d)",
2314 rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Andy Hungd1c74342015-07-07 16:54:23 -07002315 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002316 if (mTrack == 0) {
2317 // remember rate so that we can set it when the track is opened
2318 mPlaybackRate = rate;
2319 return OK;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002320 }
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002321 status_t res = mTrack->setPlaybackRate(rate);
2322 if (res != NO_ERROR) {
2323 return res;
2324 }
2325 // rate.mSpeed is always greater than 0 if setPlaybackRate succeeded
2326 CHECK_GT(rate.mSpeed, 0.f);
2327 mPlaybackRate = rate;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002328 if (mSampleRateHz != 0) {
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002329 mMsecsPerFrame = 1E3f / (rate.mSpeed * mSampleRateHz);
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002330 }
2331 return res;
2332}
2333
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002334status_t MediaPlayerService::AudioOutput::getPlaybackRate(AudioPlaybackRate *rate)
2335{
2336 ALOGV("setPlaybackRate");
Andy Hungd1c74342015-07-07 16:54:23 -07002337 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002338 if (mTrack == 0) {
2339 return NO_INIT;
2340 }
2341 *rate = mTrack->getPlaybackRate();
2342 return NO_ERROR;
2343}
2344
Eric Laurent2beeb502010-07-16 07:43:46 -07002345status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
2346{
Steve Block3856b092011-10-20 11:56:00 +01002347 ALOGV("setAuxEffectSendLevel(%f)", level);
Andy Hungd1c74342015-07-07 16:54:23 -07002348 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002349 mSendLevel = level;
Glenn Kasten2799d742013-05-30 14:33:29 -07002350 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002351 return mTrack->setAuxEffectSendLevel(level);
2352 }
2353 return NO_ERROR;
2354}
2355
2356status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
2357{
Steve Block3856b092011-10-20 11:56:00 +01002358 ALOGV("attachAuxEffect(%d)", effectId);
Andy Hungd1c74342015-07-07 16:54:23 -07002359 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002360 mAuxEffectId = effectId;
Glenn Kasten2799d742013-05-30 14:33:29 -07002361 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002362 return mTrack->attachAuxEffect(effectId);
2363 }
2364 return NO_ERROR;
2365}
2366
jiabin156c6872017-10-06 09:47:15 -07002367status_t MediaPlayerService::AudioOutput::setOutputDevice(audio_port_handle_t deviceId)
2368{
2369 ALOGV("setOutputDevice(%d)", deviceId);
2370 Mutex::Autolock lock(mLock);
2371 mSelectedDeviceId = deviceId;
2372 if (mTrack != 0) {
2373 return mTrack->setOutputDevice(deviceId);
2374 }
2375 return NO_ERROR;
2376}
2377
2378status_t MediaPlayerService::AudioOutput::getRoutedDeviceId(audio_port_handle_t* deviceId)
2379{
2380 ALOGV("getRoutedDeviceId");
2381 Mutex::Autolock lock(mLock);
2382 if (mTrack != 0) {
2383 *deviceId = mTrack->getRoutedDeviceId();
2384 return NO_ERROR;
2385 }
2386 return NO_INIT;
2387}
2388
2389status_t MediaPlayerService::AudioOutput::enableAudioDeviceCallback(bool enabled)
2390{
2391 ALOGV("enableAudioDeviceCallback, %d", enabled);
2392 Mutex::Autolock lock(mLock);
2393 mDeviceCallbackEnabled = enabled;
2394 if (mTrack != 0) {
2395 status_t status;
2396 if (enabled) {
2397 status = mTrack->addAudioDeviceCallback(mDeviceCallback.promote());
2398 } else {
2399 status = mTrack->removeAudioDeviceCallback(mDeviceCallback.promote());
2400 }
2401 return status;
2402 }
2403 return NO_ERROR;
2404}
2405
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002406VolumeShaper::Status MediaPlayerService::AudioOutput::applyVolumeShaper(
2407 const sp<VolumeShaper::Configuration>& configuration,
2408 const sp<VolumeShaper::Operation>& operation)
2409{
2410 Mutex::Autolock lock(mLock);
2411 ALOGV("AudioOutput::applyVolumeShaper");
Andy Hung4ef88d72017-02-21 19:47:53 -08002412
Andy Hung4ef88d72017-02-21 19:47:53 -08002413 mVolumeHandler->setIdIfNecessary(configuration);
Andy Hung39399b62017-04-21 15:07:45 -07002414
2415 VolumeShaper::Status status;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002416 if (mTrack != 0) {
Andy Hung39399b62017-04-21 15:07:45 -07002417 status = mTrack->applyVolumeShaper(configuration, operation);
2418 if (status >= 0) {
2419 (void)mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hungf3702642017-05-05 17:33:32 -07002420 if (mTrack->isPlaying()) { // match local AudioTrack to properly restore.
2421 mVolumeHandler->setStarted();
2422 }
Andy Hung39399b62017-04-21 15:07:45 -07002423 }
Andy Hung4ef88d72017-02-21 19:47:53 -08002424 } else {
Andy Hungc01eddb2017-07-21 16:42:41 -07002425 // VolumeShapers are not affected when a track moves between players for
2426 // gapless playback (setNextMediaPlayer).
2427 // We forward VolumeShaper operations that do not change configuration
2428 // to the new player so that unducking may occur as expected.
2429 // Unducking is an idempotent operation, same if applied back-to-back.
2430 if (configuration->getType() == VolumeShaper::Configuration::TYPE_ID
2431 && mNextOutput != nullptr) {
2432 ALOGV("applyVolumeShaper: Attempting to forward missed operation: %s %s",
2433 configuration->toString().c_str(), operation->toString().c_str());
2434 Mutex::Autolock nextLock(mNextOutput->mLock);
2435
2436 // recycled track should be forwarded from this AudioSink by switchToNextOutput
2437 sp<AudioTrack> track = mNextOutput->mRecycledTrack;
2438 if (track != nullptr) {
2439 ALOGD("Forward VolumeShaper operation to recycled track %p", track.get());
2440 (void)track->applyVolumeShaper(configuration, operation);
2441 } else {
2442 // There is a small chance that the unduck occurs after the next
2443 // player has already started, but before it is registered to receive
2444 // the unduck command.
2445 track = mNextOutput->mTrack;
2446 if (track != nullptr) {
2447 ALOGD("Forward VolumeShaper operation to track %p", track.get());
2448 (void)track->applyVolumeShaper(configuration, operation);
2449 }
2450 }
2451 }
Andy Hung39399b62017-04-21 15:07:45 -07002452 status = mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002453 }
Andy Hung39399b62017-04-21 15:07:45 -07002454 return status;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002455}
2456
2457sp<VolumeShaper::State> MediaPlayerService::AudioOutput::getVolumeShaperState(int id)
2458{
2459 Mutex::Autolock lock(mLock);
2460 if (mTrack != 0) {
2461 return mTrack->getVolumeShaperState(id);
Andy Hung4ef88d72017-02-21 19:47:53 -08002462 } else {
2463 return mVolumeHandler->getVolumeShaperState(id);
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002464 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002465}
2466
Andreas Huber20111aa2009-07-14 16:56:47 -07002467// static
2468void MediaPlayerService::AudioOutput::CallbackWrapper(
Glenn Kastend217a8c2011-06-01 15:20:35 -07002469 int event, void *cookie, void *info) {
Steve Block3856b092011-10-20 11:56:00 +01002470 //ALOGV("callbackwrapper");
Marco Nelissen6b74d672012-02-28 16:07:44 -08002471 CallbackData *data = (CallbackData*)cookie;
Andy Hungd1c74342015-07-07 16:54:23 -07002472 // lock to ensure we aren't caught in the middle of a track switch.
Marco Nelissen6b74d672012-02-28 16:07:44 -08002473 data->lock();
2474 AudioOutput *me = data->getOutput();
Andreas Huber20111aa2009-07-14 16:56:47 -07002475 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002476 if (me == NULL) {
2477 // no output set, likely because the track was scheduled to be reused
2478 // by another player, but the format turned out to be incompatible.
2479 data->unlock();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002480 if (buffer != NULL) {
2481 buffer->size = 0;
2482 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08002483 return;
2484 }
Andreas Huber20111aa2009-07-14 16:56:47 -07002485
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002486 switch(event) {
2487 case AudioTrack::EVENT_MORE_DATA: {
2488 size_t actualSize = (*me->mCallback)(
2489 me, buffer->raw, buffer->size, me->mCallbackCookie,
2490 CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002491
Andy Hung719b46b2015-05-31 22:18:25 -07002492 // Log when no data is returned from the callback.
2493 // (1) We may have no data (especially with network streaming sources).
2494 // (2) We may have reached the EOS and the audio track is not stopped yet.
2495 // Note that AwesomePlayer/AudioPlayer will only return zero size when it reaches the EOS.
2496 // NuPlayerRenderer will return zero when it doesn't have data (it doesn't block to fill).
2497 //
2498 // This is a benign busy-wait, with the next data request generated 10 ms or more later;
2499 // nevertheless for power reasons, we don't want to see too many of these.
Andreas Huber2e8ffaf2010-02-18 16:45:13 -08002500
Andy Hung719b46b2015-05-31 22:18:25 -07002501 ALOGV_IF(actualSize == 0 && buffer->size > 0, "callbackwrapper: empty buffer returned");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002502
2503 buffer->size = actualSize;
2504 } break;
2505
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002506 case AudioTrack::EVENT_STREAM_END:
Andy Hung719b46b2015-05-31 22:18:25 -07002507 // currently only occurs for offloaded callbacks
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002508 ALOGV("callbackwrapper: deliver EVENT_STREAM_END");
2509 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2510 me->mCallbackCookie, CB_EVENT_STREAM_END);
2511 break;
2512
2513 case AudioTrack::EVENT_NEW_IAUDIOTRACK :
2514 ALOGV("callbackwrapper: deliver EVENT_TEAR_DOWN");
2515 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2516 me->mCallbackCookie, CB_EVENT_TEAR_DOWN);
2517 break;
2518
Glenn Kasten421743b2015-06-01 08:18:08 -07002519 case AudioTrack::EVENT_UNDERRUN:
Andy Hung719b46b2015-05-31 22:18:25 -07002520 // This occurs when there is no data available, typically
Glenn Kasten421743b2015-06-01 08:18:08 -07002521 // when there is a failure to supply data to the AudioTrack. It can also
2522 // occur in non-offloaded mode when the audio device comes out of standby.
2523 //
Andy Hung719b46b2015-05-31 22:18:25 -07002524 // If an AudioTrack underruns it outputs silence. Since this happens suddenly
2525 // it may sound like an audible pop or glitch.
2526 //
2527 // The underrun event is sent once per track underrun; the condition is reset
2528 // when more data is sent to the AudioTrack.
Eric Laurente93cc032016-05-05 10:15:10 -07002529 ALOGD("callbackwrapper: EVENT_UNDERRUN (discarded)");
Glenn Kasten421743b2015-06-01 08:18:08 -07002530 break;
2531
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002532 default:
2533 ALOGE("received unknown event type: %d inside CallbackWrapper !", event);
Andreas Huber51c1e0e2011-04-04 11:43:40 -07002534 }
2535
Marco Nelissen6b74d672012-02-28 16:07:44 -08002536 data->unlock();
Andreas Huber20111aa2009-07-14 16:56:47 -07002537}
2538
Glenn Kastend848eb42016-03-08 13:42:11 -08002539audio_session_t MediaPlayerService::AudioOutput::getSessionId() const
Eric Laurent8c563ed2010-10-07 18:23:03 -07002540{
Andy Hungd1c74342015-07-07 16:54:23 -07002541 Mutex::Autolock lock(mLock);
Eric Laurent8c563ed2010-10-07 18:23:03 -07002542 return mSessionId;
2543}
2544
Eric Laurent6f59db12013-07-26 17:16:50 -07002545uint32_t MediaPlayerService::AudioOutput::getSampleRate() const
2546{
Andy Hungd1c74342015-07-07 16:54:23 -07002547 Mutex::Autolock lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -07002548 if (mTrack == 0) return 0;
2549 return mTrack->getSampleRate();
2550}
2551
Andy Hungf2c87b32016-04-07 19:49:29 -07002552int64_t MediaPlayerService::AudioOutput::getBufferDurationInUs() const
2553{
2554 Mutex::Autolock lock(mLock);
2555 if (mTrack == 0) {
2556 return 0;
2557 }
2558 int64_t duration;
2559 if (mTrack->getBufferDurationInUs(&duration) != OK) {
2560 return 0;
2561 }
2562 return duration;
2563}
2564
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002565////////////////////////////////////////////////////////////////////////////////
2566
2567struct CallbackThread : public Thread {
2568 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
2569 MediaPlayerBase::AudioSink::AudioCallback cb,
2570 void *cookie);
2571
2572protected:
2573 virtual ~CallbackThread();
2574
2575 virtual bool threadLoop();
2576
2577private:
2578 wp<MediaPlayerBase::AudioSink> mSink;
2579 MediaPlayerBase::AudioSink::AudioCallback mCallback;
2580 void *mCookie;
2581 void *mBuffer;
2582 size_t mBufferSize;
2583
2584 CallbackThread(const CallbackThread &);
2585 CallbackThread &operator=(const CallbackThread &);
2586};
2587
2588CallbackThread::CallbackThread(
2589 const wp<MediaPlayerBase::AudioSink> &sink,
2590 MediaPlayerBase::AudioSink::AudioCallback cb,
2591 void *cookie)
2592 : mSink(sink),
2593 mCallback(cb),
2594 mCookie(cookie),
2595 mBuffer(NULL),
2596 mBufferSize(0) {
2597}
2598
2599CallbackThread::~CallbackThread() {
2600 if (mBuffer) {
2601 free(mBuffer);
2602 mBuffer = NULL;
2603 }
2604}
2605
2606bool CallbackThread::threadLoop() {
2607 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
2608 if (sink == NULL) {
2609 return false;
2610 }
2611
2612 if (mBuffer == NULL) {
2613 mBufferSize = sink->bufferSize();
2614 mBuffer = malloc(mBufferSize);
2615 }
2616
2617 size_t actualSize =
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002618 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie,
2619 MediaPlayerBase::AudioSink::CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002620
2621 if (actualSize > 0) {
2622 sink->write(mBuffer, actualSize);
Andy Hunga31335a2014-08-20 17:37:59 -07002623 // Could return false on sink->write() error or short count.
2624 // Not necessarily appropriate but would work for AudioCache behavior.
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002625 }
2626
2627 return true;
2628}
2629
2630////////////////////////////////////////////////////////////////////////////////
2631
Chong Zhange5b9b692017-05-11 11:44:56 -07002632void MediaPlayerService::addBatteryData(uint32_t params) {
2633 mBatteryTracker.addBatteryData(params);
2634}
2635
2636status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
2637 return mBatteryTracker.pullBatteryData(reply);
2638}
2639
2640MediaPlayerService::BatteryTracker::BatteryTracker() {
2641 mBatteryAudio.refCount = 0;
2642 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2643 mBatteryAudio.deviceOn[i] = 0;
2644 mBatteryAudio.lastTime[i] = 0;
2645 mBatteryAudio.totalTime[i] = 0;
2646 }
2647 // speaker is on by default
2648 mBatteryAudio.deviceOn[SPEAKER] = 1;
2649
2650 // reset battery stats
2651 // if the mediaserver has crashed, battery stats could be left
2652 // in bad state, reset the state upon service start.
2653 BatteryNotifier::getInstance().noteResetVideo();
2654}
2655
2656void MediaPlayerService::BatteryTracker::addBatteryData(uint32_t params)
Gloria Wang7cf180c2011-02-19 18:37:57 -08002657{
2658 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002659
2660 int32_t time = systemTime() / 1000000L;
2661
2662 // change audio output devices. This notification comes from AudioFlinger
2663 if ((params & kBatteryDataSpeakerOn)
2664 || (params & kBatteryDataOtherAudioDeviceOn)) {
2665
2666 int deviceOn[NUM_AUDIO_DEVICES];
2667 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2668 deviceOn[i] = 0;
2669 }
2670
2671 if ((params & kBatteryDataSpeakerOn)
2672 && (params & kBatteryDataOtherAudioDeviceOn)) {
2673 deviceOn[SPEAKER_AND_OTHER] = 1;
2674 } else if (params & kBatteryDataSpeakerOn) {
2675 deviceOn[SPEAKER] = 1;
2676 } else {
2677 deviceOn[OTHER_AUDIO_DEVICE] = 1;
2678 }
2679
2680 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2681 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
2682
2683 if (mBatteryAudio.refCount > 0) { // if playing audio
2684 if (!deviceOn[i]) {
2685 mBatteryAudio.lastTime[i] += time;
2686 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2687 mBatteryAudio.lastTime[i] = 0;
2688 } else {
2689 mBatteryAudio.lastTime[i] = 0 - time;
2690 }
2691 }
2692
2693 mBatteryAudio.deviceOn[i] = deviceOn[i];
2694 }
2695 }
2696 return;
2697 }
2698
Marco Nelissenb7848f12014-12-04 08:57:56 -08002699 // an audio stream is started
Gloria Wang9ee159b2011-02-24 14:51:45 -08002700 if (params & kBatteryDataAudioFlingerStart) {
2701 // record the start time only if currently no other audio
2702 // is being played
2703 if (mBatteryAudio.refCount == 0) {
2704 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2705 if (mBatteryAudio.deviceOn[i]) {
2706 mBatteryAudio.lastTime[i] -= time;
2707 }
2708 }
2709 }
2710
2711 mBatteryAudio.refCount ++;
2712 return;
2713
2714 } else if (params & kBatteryDataAudioFlingerStop) {
2715 if (mBatteryAudio.refCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002716 ALOGW("Battery track warning: refCount is <= 0");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002717 return;
2718 }
2719
2720 // record the stop time only if currently this is the only
2721 // audio being played
2722 if (mBatteryAudio.refCount == 1) {
2723 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2724 if (mBatteryAudio.deviceOn[i]) {
2725 mBatteryAudio.lastTime[i] += time;
2726 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2727 mBatteryAudio.lastTime[i] = 0;
2728 }
2729 }
2730 }
2731
2732 mBatteryAudio.refCount --;
2733 return;
2734 }
2735
Andy Hung1afd0982016-11-08 16:13:44 -08002736 uid_t uid = IPCThreadState::self()->getCallingUid();
Gloria Wang7cf180c2011-02-19 18:37:57 -08002737 if (uid == AID_MEDIA) {
2738 return;
2739 }
2740 int index = mBatteryData.indexOfKey(uid);
Gloria Wang7cf180c2011-02-19 18:37:57 -08002741
2742 if (index < 0) { // create a new entry for this UID
2743 BatteryUsageInfo info;
2744 info.audioTotalTime = 0;
2745 info.videoTotalTime = 0;
2746 info.audioLastTime = 0;
2747 info.videoLastTime = 0;
2748 info.refCount = 0;
2749
Gloria Wang9ee159b2011-02-24 14:51:45 -08002750 if (mBatteryData.add(uid, info) == NO_MEMORY) {
Steve Block29357bc2012-01-06 19:20:56 +00002751 ALOGE("Battery track error: no memory for new app");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002752 return;
2753 }
Gloria Wang7cf180c2011-02-19 18:37:57 -08002754 }
2755
2756 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
2757
2758 if (params & kBatteryDataCodecStarted) {
2759 if (params & kBatteryDataTrackAudio) {
2760 info.audioLastTime -= time;
2761 info.refCount ++;
2762 }
2763 if (params & kBatteryDataTrackVideo) {
2764 info.videoLastTime -= time;
2765 info.refCount ++;
2766 }
2767 } else {
2768 if (info.refCount == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002769 ALOGW("Battery track warning: refCount is already 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002770 return;
2771 } else if (info.refCount < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00002772 ALOGE("Battery track error: refCount < 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002773 mBatteryData.removeItem(uid);
2774 return;
2775 }
2776
2777 if (params & kBatteryDataTrackAudio) {
2778 info.audioLastTime += time;
2779 info.refCount --;
2780 }
2781 if (params & kBatteryDataTrackVideo) {
2782 info.videoLastTime += time;
2783 info.refCount --;
2784 }
2785
2786 // no stream is being played by this UID
2787 if (info.refCount == 0) {
2788 info.audioTotalTime += info.audioLastTime;
2789 info.audioLastTime = 0;
2790 info.videoTotalTime += info.videoLastTime;
2791 info.videoLastTime = 0;
2792 }
2793 }
2794}
2795
Chong Zhange5b9b692017-05-11 11:44:56 -07002796status_t MediaPlayerService::BatteryTracker::pullBatteryData(Parcel* reply) {
Gloria Wang7cf180c2011-02-19 18:37:57 -08002797 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002798
2799 // audio output devices usage
2800 int32_t time = systemTime() / 1000000L; //in ms
2801 int32_t totalTime;
2802
2803 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2804 totalTime = mBatteryAudio.totalTime[i];
2805
2806 if (mBatteryAudio.deviceOn[i]
2807 && (mBatteryAudio.lastTime[i] != 0)) {
2808 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
2809 totalTime += tmpTime;
2810 }
2811
2812 reply->writeInt32(totalTime);
2813 // reset the total time
2814 mBatteryAudio.totalTime[i] = 0;
2815 }
2816
2817 // codec usage
Gloria Wang7cf180c2011-02-19 18:37:57 -08002818 BatteryUsageInfo info;
2819 int size = mBatteryData.size();
2820
2821 reply->writeInt32(size);
2822 int i = 0;
2823
2824 while (i < size) {
2825 info = mBatteryData.valueAt(i);
2826
2827 reply->writeInt32(mBatteryData.keyAt(i)); //UID
2828 reply->writeInt32(info.audioTotalTime);
2829 reply->writeInt32(info.videoTotalTime);
2830
2831 info.audioTotalTime = 0;
2832 info.videoTotalTime = 0;
2833
2834 // remove the UID entry where no stream is being played
2835 if (info.refCount <= 0) {
2836 mBatteryData.removeItemsAt(i);
2837 size --;
2838 i --;
2839 }
2840 i++;
2841 }
2842 return NO_ERROR;
2843}
nikoa64c8c72009-07-20 15:07:26 -07002844} // namespace android