blob: 96f79e0654942e6e7294719042a64bc484b53545 [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;
Pawin Vongmasa082e4f72017-12-17 02:31:18 -0800575 mListener = new Listener(this);
Eric Laurenta514bdb2010-06-21 09:27:30 -0700576
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800577#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000578 ALOGD("create Antagonizer");
Pawin Vongmasa082e4f72017-12-17 02:31:18 -0800579 mAntagonizer = new Antagonizer(mListener);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800580#endif
581}
582
583MediaPlayerService::Client::~Client()
584{
Steve Block3856b092011-10-20 11:56:00 +0100585 ALOGV("Client(%d) destructor pid = %d", mConnId, mPid);
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700586 mAudioOutput.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800587 wp<Client> client(this);
588 disconnect();
589 mService->removeClient(client);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700590 if (mAudioAttributes != NULL) {
591 free(mAudioAttributes);
592 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700593 clearDeathNotifiers_l();
jiabin156c6872017-10-06 09:47:15 -0700594 mAudioDeviceUpdatedListener.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800595}
596
597void MediaPlayerService::Client::disconnect()
598{
Steve Block3856b092011-10-20 11:56:00 +0100599 ALOGV("disconnect(%d) from pid %d", mConnId, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800600 // grab local reference and clear main reference to prevent future
601 // access to object
602 sp<MediaPlayerBase> p;
603 {
604 Mutex::Autolock l(mLock);
605 p = mPlayer;
beanzdcfefde2012-11-05 09:51:43 +0800606 mClient.clear();
Wei Jia502c2f42017-07-13 17:47:56 -0700607 mPlayer.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800608 }
Andreas Huber20111aa2009-07-14 16:56:47 -0700609
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800610 // clear the notification to prevent callbacks to dead client
611 // and reset the player. We assume the player will serialize
612 // access to itself if necessary.
613 if (p != 0) {
Pawin Vongmasa082e4f72017-12-17 02:31:18 -0800614 p->setNotifyCallback(0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800615#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000616 ALOGD("kill Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800617 mAntagonizer->kill();
618#endif
619 p->reset();
620 }
621
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700622 {
623 Mutex::Autolock l(mLock);
624 disconnectNativeWindow_l();
625 }
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700626
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800627 IPCThreadState::self()->flushCommands();
628}
629
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800630sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
631{
632 // determine if we have the right player type
Wei Jia502c2f42017-07-13 17:47:56 -0700633 sp<MediaPlayerBase> p = getPlayer();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800634 if ((p != NULL) && (p->playerType() != playerType)) {
Steve Block3856b092011-10-20 11:56:00 +0100635 ALOGV("delete player");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800636 p.clear();
637 }
638 if (p == NULL) {
Pawin Vongmasa082e4f72017-12-17 02:31:18 -0800639 p = MediaPlayerFactory::createPlayer(playerType, mListener, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800640 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700641
Jason Simmonsdb29e522011-08-12 13:46:55 -0700642 if (p != NULL) {
Andy Hung1afd0982016-11-08 16:13:44 -0800643 p->setUID(mUid);
Jason Simmonsdb29e522011-08-12 13:46:55 -0700644 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700645
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800646 return p;
647}
648
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700649MediaPlayerService::Client::ServiceDeathNotifier::ServiceDeathNotifier(
650 const sp<IBinder>& service,
651 const sp<MediaPlayerBase>& listener,
652 int which) {
653 mService = service;
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800654 mOmx = nullptr;
655 mListener = listener;
656 mWhich = which;
657}
658
659MediaPlayerService::Client::ServiceDeathNotifier::ServiceDeathNotifier(
660 const sp<IOmx>& omx,
661 const sp<MediaPlayerBase>& listener,
662 int which) {
663 mService = nullptr;
664 mOmx = omx;
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700665 mListener = listener;
666 mWhich = which;
667}
668
669MediaPlayerService::Client::ServiceDeathNotifier::~ServiceDeathNotifier() {
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700670}
671
672void MediaPlayerService::Client::ServiceDeathNotifier::binderDied(const wp<IBinder>& /*who*/) {
673 sp<MediaPlayerBase> listener = mListener.promote();
674 if (listener != NULL) {
675 listener->sendEvent(MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED, mWhich);
676 } else {
677 ALOGW("listener for process %d death is gone", mWhich);
678 }
679}
680
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800681void MediaPlayerService::Client::ServiceDeathNotifier::serviceDied(
682 uint64_t /* cookie */,
683 const wp<::android::hidl::base::V1_0::IBase>& /* who */) {
684 sp<MediaPlayerBase> listener = mListener.promote();
685 if (listener != NULL) {
686 listener->sendEvent(MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED, mWhich);
687 } else {
688 ALOGW("listener for process %d death is gone", mWhich);
689 }
690}
691
692void MediaPlayerService::Client::ServiceDeathNotifier::unlinkToDeath() {
693 if (mService != nullptr) {
694 mService->unlinkToDeath(this);
695 mService = nullptr;
696 } else if (mOmx != nullptr) {
697 mOmx->unlinkToDeath(this);
698 mOmx = nullptr;
699 }
700}
701
jiabin156c6872017-10-06 09:47:15 -0700702void MediaPlayerService::Client::AudioDeviceUpdatedNotifier::onAudioDeviceUpdate(
703 audio_io_handle_t audioIo,
704 audio_port_handle_t deviceId) {
705 sp<MediaPlayerBase> listener = mListener.promote();
706 if (listener != NULL) {
707 listener->sendEvent(MEDIA_AUDIO_ROUTING_CHANGED, audioIo, deviceId);
708 } else {
709 ALOGW("listener for process %d death is gone", MEDIA_AUDIO_ROUTING_CHANGED);
710 }
711}
712
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700713void MediaPlayerService::Client::clearDeathNotifiers_l() {
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800714 if (mExtractorDeathListener != nullptr) {
715 mExtractorDeathListener->unlinkToDeath();
716 mExtractorDeathListener = nullptr;
717 }
718 if (mCodecDeathListener != nullptr) {
719 mCodecDeathListener->unlinkToDeath();
720 mCodecDeathListener = nullptr;
721 }
722}
723
John Grossmanc795b642012-02-22 15:38:35 -0800724sp<MediaPlayerBase> MediaPlayerService::Client::setDataSource_pre(
725 player_type playerType)
726{
727 ALOGV("player type = %d", playerType);
728
729 // create the right type of player
730 sp<MediaPlayerBase> p = createPlayer(playerType);
731 if (p == NULL) {
732 return p;
733 }
734
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700735 sp<IServiceManager> sm = defaultServiceManager();
736 sp<IBinder> binder = sm->getService(String16("media.extractor"));
Marco Nelissen1b5a7ee2016-09-30 13:54:30 -0700737 if (binder == NULL) {
738 ALOGE("extractor service not available");
739 return NULL;
740 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700741 sp<ServiceDeathNotifier> extractorDeathListener =
742 new ServiceDeathNotifier(binder, p, MEDIAEXTRACTOR_PROCESS_DEATH);
743 binder->linkToDeath(extractorDeathListener);
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700744
Pawin Vongmasa620e4662017-10-27 00:12:47 -0700745 sp<IOmx> omx = IOmx::getService();
746 if (omx == nullptr) {
747 ALOGE("IOmx service is not available");
748 return NULL;
Marco Nelissen1b5a7ee2016-09-30 13:54:30 -0700749 }
Pawin Vongmasa620e4662017-10-27 00:12:47 -0700750 sp<ServiceDeathNotifier> codecDeathListener =
751 new ServiceDeathNotifier(omx, p, MEDIACODEC_PROCESS_DEATH);
752 omx->linkToDeath(codecDeathListener, 0);
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700753
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700754 Mutex::Autolock lock(mLock);
755
756 clearDeathNotifiers_l();
757 mExtractorDeathListener = extractorDeathListener;
758 mCodecDeathListener = codecDeathListener;
jiabin156c6872017-10-06 09:47:15 -0700759 mAudioDeviceUpdatedListener = new AudioDeviceUpdatedNotifier(p);
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700760
John Grossmanc795b642012-02-22 15:38:35 -0800761 if (!p->hardwareOutput()) {
Marco Nelissend457c972014-02-11 08:47:07 -0800762 mAudioOutput = new AudioOutput(mAudioSessionId, IPCThreadState::self()->getCallingUid(),
jiabin156c6872017-10-06 09:47:15 -0700763 mPid, mAudioAttributes, mAudioDeviceUpdatedListener);
John Grossmanc795b642012-02-22 15:38:35 -0800764 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
765 }
766
767 return p;
768}
769
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700770status_t MediaPlayerService::Client::setDataSource_post(
John Grossmanc795b642012-02-22 15:38:35 -0800771 const sp<MediaPlayerBase>& p,
772 status_t status)
773{
774 ALOGV(" setDataSource");
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700775 if (status != OK) {
776 ALOGE(" error: %d", status);
777 return status;
John Grossmanc795b642012-02-22 15:38:35 -0800778 }
779
780 // Set the re-transmission endpoint if one was chosen.
781 if (mRetransmitEndpointValid) {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700782 status = p->setRetransmitEndpoint(&mRetransmitEndpoint);
783 if (status != NO_ERROR) {
784 ALOGE("setRetransmitEndpoint error: %d", status);
John Grossmanc795b642012-02-22 15:38:35 -0800785 }
786 }
787
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700788 if (status == OK) {
789 Mutex::Autolock lock(mLock);
John Grossmanc795b642012-02-22 15:38:35 -0800790 mPlayer = p;
791 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700792 return status;
John Grossmanc795b642012-02-22 15:38:35 -0800793}
794
Andreas Huber2db84552010-01-28 11:19:57 -0800795status_t MediaPlayerService::Client::setDataSource(
Andreas Huber1b86fe02014-01-29 11:13:26 -0800796 const sp<IMediaHTTPService> &httpService,
797 const char *url,
798 const KeyedVector<String8, String8> *headers)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800799{
Steve Block3856b092011-10-20 11:56:00 +0100800 ALOGV("setDataSource(%s)", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800801 if (url == NULL)
802 return UNKNOWN_ERROR;
803
Dave Burked681bbb2011-08-30 14:39:17 +0100804 if ((strncmp(url, "http://", 7) == 0) ||
805 (strncmp(url, "https://", 8) == 0) ||
806 (strncmp(url, "rtsp://", 7) == 0)) {
807 if (!checkPermission("android.permission.INTERNET")) {
808 return PERMISSION_DENIED;
809 }
810 }
811
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800812 if (strncmp(url, "content://", 10) == 0) {
813 // get a filedescriptor for the content Uri and
814 // pass it to the setDataSource(fd) method
815
816 String16 url16(url);
817 int fd = android::openContentProviderFile(url16);
818 if (fd < 0)
819 {
Steve Block29357bc2012-01-06 19:20:56 +0000820 ALOGE("Couldn't open fd for %s", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800821 return UNKNOWN_ERROR;
822 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700823 status_t status = setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800824 close(fd);
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700825 return mStatus = status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800826 } else {
John Grossman44a7e422012-06-21 17:29:24 -0700827 player_type playerType = MediaPlayerFactory::getPlayerType(this, url);
John Grossmanc795b642012-02-22 15:38:35 -0800828 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
829 if (p == NULL) {
830 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800831 }
832
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700833 return mStatus =
834 setDataSource_post(
835 p, p->setDataSource(httpService, url, headers));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800836 }
837}
838
839status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
840{
Marco Nelissen83b0fd92015-09-16 13:48:07 -0700841 ALOGV("setDataSource fd=%d (%s), offset=%lld, length=%lld",
842 fd, nameForFd(fd).c_str(), (long long) offset, (long long) length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800843 struct stat sb;
844 int ret = fstat(fd, &sb);
845 if (ret != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000846 ALOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800847 return UNKNOWN_ERROR;
848 }
849
Andy Hung833b4752016-04-04 17:15:48 -0700850 ALOGV("st_dev = %llu", static_cast<unsigned long long>(sb.st_dev));
Steve Block3856b092011-10-20 11:56:00 +0100851 ALOGV("st_mode = %u", sb.st_mode);
Mark Salyzyn77342f72014-06-18 16:31:32 -0700852 ALOGV("st_uid = %lu", static_cast<unsigned long>(sb.st_uid));
853 ALOGV("st_gid = %lu", static_cast<unsigned long>(sb.st_gid));
Andy Hung833b4752016-04-04 17:15:48 -0700854 ALOGV("st_size = %llu", static_cast<unsigned long long>(sb.st_size));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800855
856 if (offset >= sb.st_size) {
Steve Block29357bc2012-01-06 19:20:56 +0000857 ALOGE("offset error");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800858 return UNKNOWN_ERROR;
859 }
860 if (offset + length > sb.st_size) {
861 length = sb.st_size - offset;
Andy Hung833b4752016-04-04 17:15:48 -0700862 ALOGV("calculated length = %lld", (long long)length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800863 }
864
John Grossman44a7e422012-06-21 17:29:24 -0700865 player_type playerType = MediaPlayerFactory::getPlayerType(this,
866 fd,
867 offset,
868 length);
John Grossmanc795b642012-02-22 15:38:35 -0800869 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
870 if (p == NULL) {
871 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800872 }
873
874 // now set data source
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700875 return mStatus = setDataSource_post(p, p->setDataSource(fd, offset, length));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800876}
877
Andreas Hubere2b10282010-11-23 11:41:34 -0800878status_t MediaPlayerService::Client::setDataSource(
879 const sp<IStreamSource> &source) {
880 // create the right type of player
John Grossman44a7e422012-06-21 17:29:24 -0700881 player_type playerType = MediaPlayerFactory::getPlayerType(this, source);
John Grossmanc795b642012-02-22 15:38:35 -0800882 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
Andreas Hubere2b10282010-11-23 11:41:34 -0800883 if (p == NULL) {
884 return NO_INIT;
885 }
886
Andreas Hubere2b10282010-11-23 11:41:34 -0800887 // now set data source
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700888 return mStatus = setDataSource_post(p, p->setDataSource(source));
Andreas Hubere2b10282010-11-23 11:41:34 -0800889}
890
Chris Watkins99f31602015-03-20 13:06:33 -0700891status_t MediaPlayerService::Client::setDataSource(
892 const sp<IDataSource> &source) {
Dongwon Kangd91dc5a2017-10-10 00:07:09 -0700893 sp<DataSource> dataSource = CreateDataSourceFromIDataSource(source);
Chris Watkins99f31602015-03-20 13:06:33 -0700894 player_type playerType = MediaPlayerFactory::getPlayerType(this, dataSource);
895 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
896 if (p == NULL) {
897 return NO_INIT;
898 }
899 // now set data source
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700900 return mStatus = setDataSource_post(p, p->setDataSource(dataSource));
Chris Watkins99f31602015-03-20 13:06:33 -0700901}
902
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700903void MediaPlayerService::Client::disconnectNativeWindow_l() {
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700904 if (mConnectedWindow != NULL) {
Chong Zhang181fd9b2017-02-16 15:53:03 -0800905 status_t err = nativeWindowDisconnect(
906 mConnectedWindow.get(), "disconnectNativeWindow");
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700907
908 if (err != OK) {
Chong Zhang181fd9b2017-02-16 15:53:03 -0800909 ALOGW("nativeWindowDisconnect returned an error: %s (%d)",
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700910 strerror(-err), err);
911 }
912 }
913 mConnectedWindow.clear();
914}
915
Glenn Kasten11731182011-02-08 17:26:17 -0800916status_t MediaPlayerService::Client::setVideoSurfaceTexture(
Andy McFadden484566c2012-12-18 09:46:54 -0800917 const sp<IGraphicBufferProducer>& bufferProducer)
Glenn Kasten11731182011-02-08 17:26:17 -0800918{
Andy McFadden484566c2012-12-18 09:46:54 -0800919 ALOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, bufferProducer.get());
Glenn Kasten11731182011-02-08 17:26:17 -0800920 sp<MediaPlayerBase> p = getPlayer();
921 if (p == 0) return UNKNOWN_ERROR;
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700922
Marco Nelissenf8880202014-11-14 07:58:25 -0800923 sp<IBinder> binder(IInterface::asBinder(bufferProducer));
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700924 if (mConnectedWindowBinder == binder) {
925 return OK;
926 }
927
928 sp<ANativeWindow> anw;
Andy McFadden484566c2012-12-18 09:46:54 -0800929 if (bufferProducer != NULL) {
Marco Nelissenee08f7e2013-09-16 13:30:01 -0700930 anw = new Surface(bufferProducer, true /* controlledByApp */);
Chong Zhang181fd9b2017-02-16 15:53:03 -0800931 status_t err = nativeWindowConnect(anw.get(), "setVideoSurfaceTexture");
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700932
933 if (err != OK) {
Steve Block29357bc2012-01-06 19:20:56 +0000934 ALOGE("setVideoSurfaceTexture failed: %d", err);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700935 // Note that we must do the reset before disconnecting from the ANW.
936 // Otherwise queue/dequeue calls could be made on the disconnected
937 // ANW, which may result in errors.
938 reset();
939
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700940 Mutex::Autolock lock(mLock);
941 disconnectNativeWindow_l();
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700942
943 return err;
944 }
945 }
946
Andy McFadden484566c2012-12-18 09:46:54 -0800947 // Note that we must set the player's new GraphicBufferProducer before
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700948 // disconnecting the old one. Otherwise queue/dequeue calls could be made
949 // on the disconnected ANW, which may result in errors.
Andy McFadden484566c2012-12-18 09:46:54 -0800950 status_t err = p->setVideoSurfaceTexture(bufferProducer);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700951
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700952 mLock.lock();
953 disconnectNativeWindow_l();
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700954
955 if (err == OK) {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700956 mConnectedWindow = anw;
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700957 mConnectedWindowBinder = binder;
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700958 mLock.unlock();
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700959 } else {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700960 mLock.unlock();
961 status_t err = nativeWindowDisconnect(
962 anw.get(), "disconnectNativeWindow");
963
964 if (err != OK) {
965 ALOGW("nativeWindowDisconnect returned an error: %s (%d)",
966 strerror(-err), err);
967 }
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700968 }
969
970 return err;
Glenn Kasten11731182011-02-08 17:26:17 -0800971}
972
Nicolas Catania1d187f12009-05-12 23:25:55 -0700973status_t MediaPlayerService::Client::invoke(const Parcel& request,
974 Parcel *reply)
975{
976 sp<MediaPlayerBase> p = getPlayer();
977 if (p == NULL) return UNKNOWN_ERROR;
978 return p->invoke(request, reply);
979}
980
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700981// This call doesn't need to access the native player.
982status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
983{
984 status_t status;
nikoa64c8c72009-07-20 15:07:26 -0700985 media::Metadata::Filter allow, drop;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700986
Nicolas Catania48290382009-07-10 13:53:06 -0700987 if (unmarshallFilter(filter, &allow, &status) &&
988 unmarshallFilter(filter, &drop, &status)) {
989 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700990
991 mMetadataAllow = allow;
992 mMetadataDrop = drop;
993 }
994 return status;
995}
996
Nicolas Catania48290382009-07-10 13:53:06 -0700997status_t MediaPlayerService::Client::getMetadata(
Mark Salyzyn77342f72014-06-18 16:31:32 -0700998 bool update_only, bool /*apply_filter*/, Parcel *reply)
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700999{
nikoa64c8c72009-07-20 15:07:26 -07001000 sp<MediaPlayerBase> player = getPlayer();
1001 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania48290382009-07-10 13:53:06 -07001002
nikod608a812009-07-16 16:39:53 -07001003 status_t status;
1004 // Placeholder for the return code, updated by the caller.
1005 reply->writeInt32(-1);
1006
nikoa64c8c72009-07-20 15:07:26 -07001007 media::Metadata::Filter ids;
Nicolas Catania48290382009-07-10 13:53:06 -07001008
1009 // We don't block notifications while we fetch the data. We clear
1010 // mMetadataUpdated first so we don't lose notifications happening
1011 // during the rest of this call.
1012 {
1013 Mutex::Autolock lock(mLock);
1014 if (update_only) {
nikod608a812009-07-16 16:39:53 -07001015 ids = mMetadataUpdated;
Nicolas Catania48290382009-07-10 13:53:06 -07001016 }
1017 mMetadataUpdated.clear();
1018 }
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001019
nikoa64c8c72009-07-20 15:07:26 -07001020 media::Metadata metadata(reply);
Nicolas Catania48290382009-07-10 13:53:06 -07001021
nikoa64c8c72009-07-20 15:07:26 -07001022 metadata.appendHeader();
1023 status = player->getMetadata(ids, reply);
nikod608a812009-07-16 16:39:53 -07001024
1025 if (status != OK) {
nikoa64c8c72009-07-20 15:07:26 -07001026 metadata.resetParcel();
Steve Block29357bc2012-01-06 19:20:56 +00001027 ALOGE("getMetadata failed %d", status);
nikod608a812009-07-16 16:39:53 -07001028 return status;
1029 }
1030
1031 // FIXME: Implement filtering on the result. Not critical since
1032 // filtering takes place on the update notifications already. This
1033 // would be when all the metadata are fetch and a filter is set.
1034
nikod608a812009-07-16 16:39:53 -07001035 // Everything is fine, update the metadata length.
nikoa64c8c72009-07-20 15:07:26 -07001036 metadata.updateLength();
nikod608a812009-07-16 16:39:53 -07001037 return OK;
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001038}
1039
Wei Jiad399e7e2016-10-26 15:49:11 -07001040status_t MediaPlayerService::Client::setBufferingSettings(
1041 const BufferingSettings& buffering)
1042{
Wei Jiadc6f3402017-01-09 15:04:18 -08001043 ALOGV("[%d] setBufferingSettings{%s}",
1044 mConnId, buffering.toString().string());
Wei Jiad399e7e2016-10-26 15:49:11 -07001045 sp<MediaPlayerBase> p = getPlayer();
1046 if (p == 0) return UNKNOWN_ERROR;
1047 return p->setBufferingSettings(buffering);
1048}
1049
Wei Jia9bb38032017-03-23 18:00:38 -07001050status_t MediaPlayerService::Client::getBufferingSettings(
Wei Jiad399e7e2016-10-26 15:49:11 -07001051 BufferingSettings* buffering /* nonnull */)
1052{
1053 sp<MediaPlayerBase> p = getPlayer();
1054 // TODO: create mPlayer on demand.
1055 if (p == 0) return UNKNOWN_ERROR;
Wei Jia9bb38032017-03-23 18:00:38 -07001056 status_t ret = p->getBufferingSettings(buffering);
Wei Jiad399e7e2016-10-26 15:49:11 -07001057 if (ret == NO_ERROR) {
Wei Jia9bb38032017-03-23 18:00:38 -07001058 ALOGV("[%d] getBufferingSettings{%s}",
Wei Jiadc6f3402017-01-09 15:04:18 -08001059 mConnId, buffering->toString().string());
Wei Jiad399e7e2016-10-26 15:49:11 -07001060 } else {
Wei Jia9bb38032017-03-23 18:00:38 -07001061 ALOGE("[%d] getBufferingSettings returned %d", mConnId, ret);
Wei Jiad399e7e2016-10-26 15:49:11 -07001062 }
1063 return ret;
1064}
1065
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001066status_t MediaPlayerService::Client::prepareAsync()
1067{
Steve Block3856b092011-10-20 11:56:00 +01001068 ALOGV("[%d] prepareAsync", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001069 sp<MediaPlayerBase> p = getPlayer();
1070 if (p == 0) return UNKNOWN_ERROR;
1071 status_t ret = p->prepareAsync();
1072#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +00001073 ALOGD("start Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001074 if (ret == NO_ERROR) mAntagonizer->start();
1075#endif
1076 return ret;
1077}
1078
1079status_t MediaPlayerService::Client::start()
1080{
Steve Block3856b092011-10-20 11:56:00 +01001081 ALOGV("[%d] start", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001082 sp<MediaPlayerBase> p = getPlayer();
1083 if (p == 0) return UNKNOWN_ERROR;
1084 p->setLooping(mLoop);
1085 return p->start();
1086}
1087
1088status_t MediaPlayerService::Client::stop()
1089{
Steve Block3856b092011-10-20 11:56:00 +01001090 ALOGV("[%d] stop", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001091 sp<MediaPlayerBase> p = getPlayer();
1092 if (p == 0) return UNKNOWN_ERROR;
1093 return p->stop();
1094}
1095
1096status_t MediaPlayerService::Client::pause()
1097{
Steve Block3856b092011-10-20 11:56:00 +01001098 ALOGV("[%d] pause", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001099 sp<MediaPlayerBase> p = getPlayer();
1100 if (p == 0) return UNKNOWN_ERROR;
1101 return p->pause();
1102}
1103
1104status_t MediaPlayerService::Client::isPlaying(bool* state)
1105{
1106 *state = false;
1107 sp<MediaPlayerBase> p = getPlayer();
1108 if (p == 0) return UNKNOWN_ERROR;
1109 *state = p->isPlaying();
Steve Block3856b092011-10-20 11:56:00 +01001110 ALOGV("[%d] isPlaying: %d", mConnId, *state);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001111 return NO_ERROR;
1112}
1113
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001114status_t MediaPlayerService::Client::setPlaybackSettings(const AudioPlaybackRate& rate)
Wei Jia98160162015-02-04 17:01:11 -08001115{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001116 ALOGV("[%d] setPlaybackSettings(%f, %f, %d, %d)",
1117 mConnId, rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Wei Jia98160162015-02-04 17:01:11 -08001118 sp<MediaPlayerBase> p = getPlayer();
1119 if (p == 0) return UNKNOWN_ERROR;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001120 return p->setPlaybackSettings(rate);
1121}
1122
1123status_t MediaPlayerService::Client::getPlaybackSettings(AudioPlaybackRate* rate /* nonnull */)
1124{
1125 sp<MediaPlayerBase> p = getPlayer();
1126 if (p == 0) return UNKNOWN_ERROR;
1127 status_t ret = p->getPlaybackSettings(rate);
1128 if (ret == NO_ERROR) {
1129 ALOGV("[%d] getPlaybackSettings(%f, %f, %d, %d)",
1130 mConnId, rate->mSpeed, rate->mPitch, rate->mFallbackMode, rate->mStretchMode);
1131 } else {
1132 ALOGV("[%d] getPlaybackSettings returned %d", mConnId, ret);
1133 }
1134 return ret;
1135}
1136
1137status_t MediaPlayerService::Client::setSyncSettings(
1138 const AVSyncSettings& sync, float videoFpsHint)
1139{
1140 ALOGV("[%d] setSyncSettings(%u, %u, %f, %f)",
1141 mConnId, sync.mSource, sync.mAudioAdjustMode, sync.mTolerance, videoFpsHint);
1142 sp<MediaPlayerBase> p = getPlayer();
1143 if (p == 0) return UNKNOWN_ERROR;
1144 return p->setSyncSettings(sync, videoFpsHint);
1145}
1146
1147status_t MediaPlayerService::Client::getSyncSettings(
1148 AVSyncSettings* sync /* nonnull */, float* videoFps /* nonnull */)
1149{
1150 sp<MediaPlayerBase> p = getPlayer();
1151 if (p == 0) return UNKNOWN_ERROR;
1152 status_t ret = p->getSyncSettings(sync, videoFps);
1153 if (ret == NO_ERROR) {
1154 ALOGV("[%d] getSyncSettings(%u, %u, %f, %f)",
1155 mConnId, sync->mSource, sync->mAudioAdjustMode, sync->mTolerance, *videoFps);
1156 } else {
1157 ALOGV("[%d] getSyncSettings returned %d", mConnId, ret);
1158 }
1159 return ret;
Wei Jia98160162015-02-04 17:01:11 -08001160}
1161
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001162status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
1163{
Steve Block3856b092011-10-20 11:56:00 +01001164 ALOGV("getCurrentPosition");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001165 sp<MediaPlayerBase> p = getPlayer();
1166 if (p == 0) return UNKNOWN_ERROR;
1167 status_t ret = p->getCurrentPosition(msec);
1168 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001169 ALOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001170 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001171 ALOGE("getCurrentPosition returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001172 }
1173 return ret;
1174}
1175
1176status_t MediaPlayerService::Client::getDuration(int *msec)
1177{
Steve Block3856b092011-10-20 11:56:00 +01001178 ALOGV("getDuration");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001179 sp<MediaPlayerBase> p = getPlayer();
1180 if (p == 0) return UNKNOWN_ERROR;
1181 status_t ret = p->getDuration(msec);
1182 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001183 ALOGV("[%d] getDuration = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001184 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001185 ALOGE("getDuration returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001186 }
1187 return ret;
1188}
1189
Marco Nelissen6b74d672012-02-28 16:07:44 -08001190status_t MediaPlayerService::Client::setNextPlayer(const sp<IMediaPlayer>& player) {
1191 ALOGV("setNextPlayer");
1192 Mutex::Autolock l(mLock);
1193 sp<Client> c = static_cast<Client*>(player.get());
Wei Jia28284122016-08-30 13:49:06 -07001194 if (c != NULL && !mService->hasClient(c)) {
Robert Shihee0a0e32016-08-16 16:50:54 -07001195 return BAD_VALUE;
1196 }
1197
Marco Nelissen6b74d672012-02-28 16:07:44 -08001198 mNextClient = c;
John Grossman5f7e55e2012-08-24 14:47:25 -07001199
1200 if (c != NULL) {
1201 if (mAudioOutput != NULL) {
1202 mAudioOutput->setNextOutput(c->mAudioOutput);
1203 } else if ((mPlayer != NULL) && !mPlayer->hardwareOutput()) {
1204 ALOGE("no current audio output");
1205 }
1206
1207 if ((mPlayer != NULL) && (mNextClient->getPlayer() != NULL)) {
1208 mPlayer->setNextPlayer(mNextClient->getPlayer());
1209 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001210 }
John Grossman5f7e55e2012-08-24 14:47:25 -07001211
Marco Nelissen6b74d672012-02-28 16:07:44 -08001212 return OK;
1213}
1214
Andy Hung9fc8b5c2017-01-24 13:36:48 -08001215VolumeShaper::Status MediaPlayerService::Client::applyVolumeShaper(
1216 const sp<VolumeShaper::Configuration>& configuration,
1217 const sp<VolumeShaper::Operation>& operation) {
1218 // for hardware output, call player instead
1219 ALOGV("Client::applyVolumeShaper(%p)", this);
1220 sp<MediaPlayerBase> p = getPlayer();
1221 {
1222 Mutex::Autolock l(mLock);
1223 if (p != 0 && p->hardwareOutput()) {
1224 // TODO: investigate internal implementation
1225 return VolumeShaper::Status(INVALID_OPERATION);
1226 }
1227 if (mAudioOutput.get() != nullptr) {
1228 return mAudioOutput->applyVolumeShaper(configuration, operation);
1229 }
1230 }
1231 return VolumeShaper::Status(INVALID_OPERATION);
1232}
1233
1234sp<VolumeShaper::State> MediaPlayerService::Client::getVolumeShaperState(int id) {
1235 // for hardware output, call player instead
1236 ALOGV("Client::getVolumeShaperState(%p)", this);
1237 sp<MediaPlayerBase> p = getPlayer();
1238 {
1239 Mutex::Autolock l(mLock);
1240 if (p != 0 && p->hardwareOutput()) {
1241 // TODO: investigate internal implementation.
1242 return nullptr;
1243 }
1244 if (mAudioOutput.get() != nullptr) {
1245 return mAudioOutput->getVolumeShaperState(id);
1246 }
1247 }
1248 return nullptr;
1249}
1250
Wei Jiac5de0912016-11-18 10:22:14 -08001251status_t MediaPlayerService::Client::seekTo(int msec, MediaPlayerSeekMode mode)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001252{
Wei Jiac5de0912016-11-18 10:22:14 -08001253 ALOGV("[%d] seekTo(%d, %d)", mConnId, msec, mode);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001254 sp<MediaPlayerBase> p = getPlayer();
1255 if (p == 0) return UNKNOWN_ERROR;
Wei Jiac5de0912016-11-18 10:22:14 -08001256 return p->seekTo(msec, mode);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001257}
1258
1259status_t MediaPlayerService::Client::reset()
1260{
Steve Block3856b092011-10-20 11:56:00 +01001261 ALOGV("[%d] reset", mConnId);
John Grossmanc795b642012-02-22 15:38:35 -08001262 mRetransmitEndpointValid = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001263 sp<MediaPlayerBase> p = getPlayer();
1264 if (p == 0) return UNKNOWN_ERROR;
1265 return p->reset();
1266}
1267
Wei Jia52c28512017-09-13 18:17:51 -07001268status_t MediaPlayerService::Client::notifyAt(int64_t mediaTimeUs)
1269{
1270 ALOGV("[%d] notifyAt(%lld)", mConnId, (long long)mediaTimeUs);
1271 sp<MediaPlayerBase> p = getPlayer();
1272 if (p == 0) return UNKNOWN_ERROR;
1273 return p->notifyAt(mediaTimeUs);
1274}
1275
Glenn Kastenfff6d712012-01-12 16:38:12 -08001276status_t MediaPlayerService::Client::setAudioStreamType(audio_stream_type_t type)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001277{
Steve Block3856b092011-10-20 11:56:00 +01001278 ALOGV("[%d] setAudioStreamType(%d)", mConnId, type);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001279 // TODO: for hardware output, call player instead
1280 Mutex::Autolock l(mLock);
1281 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1282 return NO_ERROR;
1283}
1284
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001285status_t MediaPlayerService::Client::setAudioAttributes_l(const Parcel &parcel)
1286{
1287 if (mAudioAttributes != NULL) { free(mAudioAttributes); }
1288 mAudioAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001289 if (mAudioAttributes == NULL) {
1290 return NO_MEMORY;
1291 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001292 unmarshallAudioAttributes(parcel, mAudioAttributes);
1293
1294 ALOGV("setAudioAttributes_l() usage=%d content=%d flags=0x%x tags=%s",
1295 mAudioAttributes->usage, mAudioAttributes->content_type, mAudioAttributes->flags,
1296 mAudioAttributes->tags);
1297
1298 if (mAudioOutput != 0) {
1299 mAudioOutput->setAudioAttributes(mAudioAttributes);
1300 }
1301 return NO_ERROR;
1302}
1303
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001304status_t MediaPlayerService::Client::setLooping(int loop)
1305{
Steve Block3856b092011-10-20 11:56:00 +01001306 ALOGV("[%d] setLooping(%d)", mConnId, loop);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001307 mLoop = loop;
1308 sp<MediaPlayerBase> p = getPlayer();
1309 if (p != 0) return p->setLooping(loop);
1310 return NO_ERROR;
1311}
1312
1313status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1314{
Steve Block3856b092011-10-20 11:56:00 +01001315 ALOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
John Grossman761defc2012-02-09 15:09:05 -08001316
1317 // for hardware output, call player instead
1318 sp<MediaPlayerBase> p = getPlayer();
1319 {
1320 Mutex::Autolock l(mLock);
1321 if (p != 0 && p->hardwareOutput()) {
1322 MediaPlayerHWInterface* hwp =
1323 reinterpret_cast<MediaPlayerHWInterface*>(p.get());
1324 return hwp->setVolume(leftVolume, rightVolume);
1325 } else {
1326 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1327 return NO_ERROR;
1328 }
1329 }
1330
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001331 return NO_ERROR;
1332}
1333
Eric Laurent2beeb502010-07-16 07:43:46 -07001334status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1335{
Steve Block3856b092011-10-20 11:56:00 +01001336 ALOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
Eric Laurent2beeb502010-07-16 07:43:46 -07001337 Mutex::Autolock l(mLock);
1338 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1339 return NO_ERROR;
1340}
1341
1342status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1343{
Steve Block3856b092011-10-20 11:56:00 +01001344 ALOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
Eric Laurent2beeb502010-07-16 07:43:46 -07001345 Mutex::Autolock l(mLock);
1346 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1347 return NO_ERROR;
1348}
Nicolas Catania48290382009-07-10 13:53:06 -07001349
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001350status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
Steve Block3856b092011-10-20 11:56:00 +01001351 ALOGV("[%d] setParameter(%d)", mConnId, key);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001352 switch (key) {
1353 case KEY_PARAMETER_AUDIO_ATTRIBUTES:
1354 {
1355 Mutex::Autolock l(mLock);
1356 return setAudioAttributes_l(request);
1357 }
1358 default:
1359 sp<MediaPlayerBase> p = getPlayer();
1360 if (p == 0) { return UNKNOWN_ERROR; }
1361 return p->setParameter(key, request);
1362 }
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001363}
1364
1365status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
Steve Block3856b092011-10-20 11:56:00 +01001366 ALOGV("[%d] getParameter(%d)", mConnId, key);
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001367 sp<MediaPlayerBase> p = getPlayer();
1368 if (p == 0) return UNKNOWN_ERROR;
1369 return p->getParameter(key, reply);
1370}
1371
John Grossmanc795b642012-02-22 15:38:35 -08001372status_t MediaPlayerService::Client::setRetransmitEndpoint(
1373 const struct sockaddr_in* endpoint) {
1374
1375 if (NULL != endpoint) {
1376 uint32_t a = ntohl(endpoint->sin_addr.s_addr);
1377 uint16_t p = ntohs(endpoint->sin_port);
1378 ALOGV("[%d] setRetransmitEndpoint(%u.%u.%u.%u:%hu)", mConnId,
1379 (a >> 24), (a >> 16) & 0xFF, (a >> 8) & 0xFF, (a & 0xFF), p);
1380 } else {
1381 ALOGV("[%d] setRetransmitEndpoint = <none>", mConnId);
1382 }
1383
1384 sp<MediaPlayerBase> p = getPlayer();
1385
1386 // Right now, the only valid time to set a retransmit endpoint is before
1387 // player selection has been made (since the presence or absence of a
1388 // retransmit endpoint is going to determine which player is selected during
1389 // setDataSource).
1390 if (p != 0) return INVALID_OPERATION;
1391
1392 if (NULL != endpoint) {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001393 Mutex::Autolock lock(mLock);
John Grossmanc795b642012-02-22 15:38:35 -08001394 mRetransmitEndpoint = *endpoint;
1395 mRetransmitEndpointValid = true;
1396 } else {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001397 Mutex::Autolock lock(mLock);
John Grossmanc795b642012-02-22 15:38:35 -08001398 mRetransmitEndpointValid = false;
1399 }
1400
1401 return NO_ERROR;
1402}
1403
John Grossman44a7e422012-06-21 17:29:24 -07001404status_t MediaPlayerService::Client::getRetransmitEndpoint(
1405 struct sockaddr_in* endpoint)
1406{
1407 if (NULL == endpoint)
1408 return BAD_VALUE;
1409
1410 sp<MediaPlayerBase> p = getPlayer();
1411
1412 if (p != NULL)
1413 return p->getRetransmitEndpoint(endpoint);
1414
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001415 Mutex::Autolock lock(mLock);
John Grossman44a7e422012-06-21 17:29:24 -07001416 if (!mRetransmitEndpointValid)
1417 return NO_INIT;
1418
1419 *endpoint = mRetransmitEndpoint;
1420
1421 return NO_ERROR;
1422}
1423
Gloria Wangb483c472011-04-11 17:23:27 -07001424void MediaPlayerService::Client::notify(
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001425 int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001426{
James Dongb8a98252012-08-26 16:13:03 -07001427 sp<IMediaPlayerClient> c;
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001428 sp<Client> nextClient;
1429 status_t errStartNext = NO_ERROR;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001430 {
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001431 Mutex::Autolock l(mLock);
1432 c = mClient;
1433 if (msg == MEDIA_PLAYBACK_COMPLETE && mNextClient != NULL) {
1434 nextClient = mNextClient;
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001435
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001436 if (mAudioOutput != NULL)
1437 mAudioOutput->switchToNextOutput();
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001438
1439 errStartNext = nextClient->start();
1440 }
1441 }
1442
1443 if (nextClient != NULL) {
1444 sp<IMediaPlayerClient> nc;
1445 {
1446 Mutex::Autolock l(nextClient->mLock);
1447 nc = nextClient->mClient;
1448 }
1449 if (nc != NULL) {
1450 if (errStartNext == NO_ERROR) {
1451 nc->notify(MEDIA_INFO, MEDIA_INFO_STARTED_AS_NEXT, 0, obj);
1452 } else {
1453 nc->notify(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN , 0, obj);
1454 ALOGE("gapless:start playback for next track failed, err(%d)", errStartNext);
Wei Jia2afac0c2016-01-07 12:13:07 -08001455 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001456 }
1457 }
1458
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001459 if (MEDIA_INFO == msg &&
Nicolas Catania48290382009-07-10 13:53:06 -07001460 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikoa64c8c72009-07-20 15:07:26 -07001461 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania48290382009-07-10 13:53:06 -07001462
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001463 if(shouldDropMetadata(metadata_type)) {
Nicolas Catania48290382009-07-10 13:53:06 -07001464 return;
1465 }
1466
1467 // Update the list of metadata that have changed. getMetadata
1468 // also access mMetadataUpdated and clears it.
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001469 addNewMetadataUpdate(metadata_type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001470 }
James Dongb8a98252012-08-26 16:13:03 -07001471
1472 if (c != NULL) {
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001473 ALOGV("[%d] notify (%d, %d, %d)", mConnId, msg, ext1, ext2);
James Dongb8a98252012-08-26 16:13:03 -07001474 c->notify(msg, ext1, ext2, obj);
1475 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001476}
1477
Nicolas Catania48290382009-07-10 13:53:06 -07001478
nikoa64c8c72009-07-20 15:07:26 -07001479bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001480{
Nicolas Catania48290382009-07-10 13:53:06 -07001481 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001482
Nicolas Catania48290382009-07-10 13:53:06 -07001483 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001484 return true;
1485 }
1486
Nicolas Catania48290382009-07-10 13:53:06 -07001487 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001488 return false;
Nicolas Catania48290382009-07-10 13:53:06 -07001489 } else {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001490 return true;
1491 }
1492}
1493
Nicolas Catania48290382009-07-10 13:53:06 -07001494
nikoa64c8c72009-07-20 15:07:26 -07001495void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania48290382009-07-10 13:53:06 -07001496 Mutex::Autolock lock(mLock);
1497 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1498 mMetadataUpdated.add(metadata_type);
1499 }
1500}
1501
Hassan Shojaniacefac142017-02-06 21:02:02 -08001502// Modular DRM
1503status_t MediaPlayerService::Client::prepareDrm(const uint8_t uuid[16],
1504 const Vector<uint8_t>& drmSessionId)
1505{
1506 ALOGV("[%d] prepareDrm", mConnId);
1507 sp<MediaPlayerBase> p = getPlayer();
1508 if (p == 0) return UNKNOWN_ERROR;
1509
1510 status_t ret = p->prepareDrm(uuid, drmSessionId);
1511 ALOGV("prepareDrm ret: %d", ret);
1512
1513 return ret;
1514}
1515
1516status_t MediaPlayerService::Client::releaseDrm()
1517{
1518 ALOGV("[%d] releaseDrm", mConnId);
1519 sp<MediaPlayerBase> p = getPlayer();
1520 if (p == 0) return UNKNOWN_ERROR;
1521
1522 status_t ret = p->releaseDrm();
1523 ALOGV("releaseDrm ret: %d", ret);
1524
1525 return ret;
1526}
1527
jiabin156c6872017-10-06 09:47:15 -07001528status_t MediaPlayerService::Client::setOutputDevice(audio_port_handle_t deviceId)
1529{
1530 ALOGV("[%d] setOutputDevice", mConnId);
1531 {
1532 Mutex::Autolock l(mLock);
1533 if (mAudioOutput.get() != nullptr) {
1534 return mAudioOutput->setOutputDevice(deviceId);
1535 }
1536 }
1537 return NO_INIT;
1538}
1539
1540status_t MediaPlayerService::Client::getRoutedDeviceId(audio_port_handle_t* deviceId)
1541{
1542 ALOGV("[%d] getRoutedDeviceId", mConnId);
1543 {
1544 Mutex::Autolock l(mLock);
1545 if (mAudioOutput.get() != nullptr) {
1546 return mAudioOutput->getRoutedDeviceId(deviceId);
1547 }
1548 }
1549 return NO_INIT;
1550}
1551
1552status_t MediaPlayerService::Client::enableAudioDeviceCallback(bool enabled)
1553{
1554 ALOGV("[%d] enableAudioDeviceCallback, %d", mConnId, enabled);
1555 {
1556 Mutex::Autolock l(mLock);
1557 if (mAudioOutput.get() != nullptr) {
1558 return mAudioOutput->enableAudioDeviceCallback(enabled);
1559 }
1560 }
1561 return NO_INIT;
1562}
1563
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001564#if CALLBACK_ANTAGONIZER
1565const int Antagonizer::interval = 10000; // 10 msecs
1566
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001567Antagonizer::Antagonizer(const sp<MediaPlayerBase::Listener> &listener) :
1568 mExit(false), mActive(false), mListener(listener)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001569{
1570 createThread(callbackThread, this);
1571}
1572
1573void Antagonizer::kill()
1574{
1575 Mutex::Autolock _l(mLock);
1576 mActive = false;
1577 mExit = true;
1578 mCondition.wait(mLock);
1579}
1580
1581int Antagonizer::callbackThread(void* user)
1582{
Steve Blockb8a80522011-12-20 16:23:08 +00001583 ALOGD("Antagonizer started");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001584 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1585 while (!p->mExit) {
1586 if (p->mActive) {
Steve Block3856b092011-10-20 11:56:00 +01001587 ALOGV("send event");
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001588 p->mListener->notify(0, 0, 0, 0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001589 }
1590 usleep(interval);
1591 }
1592 Mutex::Autolock _l(p->mLock);
1593 p->mCondition.signal();
Steve Blockb8a80522011-12-20 16:23:08 +00001594 ALOGD("Antagonizer stopped");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001595 return 0;
1596}
1597#endif
1598
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001599#undef LOG_TAG
1600#define LOG_TAG "AudioSink"
Andy Hung1afd0982016-11-08 16:13:44 -08001601MediaPlayerService::AudioOutput::AudioOutput(audio_session_t sessionId, uid_t uid, int pid,
jiabin156c6872017-10-06 09:47:15 -07001602 const audio_attributes_t* attr, const sp<AudioSystem::AudioDeviceCallback>& deviceCallback)
Andreas Huber20111aa2009-07-14 16:56:47 -07001603 : mCallback(NULL),
Eric Laurenta514bdb2010-06-21 09:27:30 -07001604 mCallbackCookie(NULL),
Marco Nelissen6b74d672012-02-28 16:07:44 -08001605 mCallbackData(NULL),
Andy Hungd1c74342015-07-07 16:54:23 -07001606 mStreamType(AUDIO_STREAM_MUSIC),
Andy Hungd1c74342015-07-07 16:54:23 -07001607 mLeftVolume(1.0),
1608 mRightVolume(1.0),
1609 mPlaybackRate(AUDIO_PLAYBACK_RATE_DEFAULT),
1610 mSampleRateHz(0),
1611 mMsecsPerFrame(0),
1612 mFrameSize(0),
Eric Laurent1948eb32012-04-13 16:50:19 -07001613 mSessionId(sessionId),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001614 mUid(uid),
Marco Nelissend457c972014-02-11 08:47:07 -08001615 mPid(pid),
Andy Hungd1c74342015-07-07 16:54:23 -07001616 mSendLevel(0.0),
1617 mAuxEffectId(0),
Andy Hung4ef88d72017-02-21 19:47:53 -08001618 mFlags(AUDIO_OUTPUT_FLAG_NONE),
jiabin156c6872017-10-06 09:47:15 -07001619 mVolumeHandler(new media::VolumeHandler()),
1620 mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE),
jiabin161b64fc2017-11-17 09:31:48 -08001621 mRoutedDeviceId(AUDIO_PORT_HANDLE_NONE),
jiabin156c6872017-10-06 09:47:15 -07001622 mDeviceCallbackEnabled(false),
1623 mDeviceCallback(deviceCallback)
Andy Hungd1c74342015-07-07 16:54:23 -07001624{
Steve Block3856b092011-10-20 11:56:00 +01001625 ALOGV("AudioOutput(%d)", sessionId);
Eric Laurent43562692015-07-15 16:49:07 -07001626 if (attr != NULL) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001627 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1628 if (mAttributes != NULL) {
1629 memcpy(mAttributes, attr, sizeof(audio_attributes_t));
1630 mStreamType = audio_attributes_to_stream_type(attr);
1631 }
1632 } else {
1633 mAttributes = NULL;
Eric Laurent43562692015-07-15 16:49:07 -07001634 }
1635
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001636 setMinBufferCount();
1637}
1638
1639MediaPlayerService::AudioOutput::~AudioOutput()
1640{
1641 close();
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001642 free(mAttributes);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001643 delete mCallbackData;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001644}
1645
Andy Hungd1c74342015-07-07 16:54:23 -07001646//static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001647void MediaPlayerService::AudioOutput::setMinBufferCount()
1648{
1649 char value[PROPERTY_VALUE_MAX];
1650 if (property_get("ro.kernel.qemu", value, 0)) {
1651 mIsOnEmulator = true;
1652 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1653 }
1654}
1655
Andy Hungd1c74342015-07-07 16:54:23 -07001656// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001657bool MediaPlayerService::AudioOutput::isOnEmulator()
1658{
Andy Hungd1c74342015-07-07 16:54:23 -07001659 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001660 return mIsOnEmulator;
1661}
1662
Andy Hungd1c74342015-07-07 16:54:23 -07001663// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001664int MediaPlayerService::AudioOutput::getMinBufferCount()
1665{
Andy Hungd1c74342015-07-07 16:54:23 -07001666 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001667 return mMinBufferCount;
1668}
1669
1670ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1671{
Andy Hungd1c74342015-07-07 16:54:23 -07001672 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001673 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001674 return mTrack->frameCount() * mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001675}
1676
1677ssize_t MediaPlayerService::AudioOutput::frameCount() const
1678{
Andy Hungd1c74342015-07-07 16:54:23 -07001679 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001680 if (mTrack == 0) return NO_INIT;
1681 return mTrack->frameCount();
1682}
1683
1684ssize_t MediaPlayerService::AudioOutput::channelCount() const
1685{
Andy Hungd1c74342015-07-07 16:54:23 -07001686 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001687 if (mTrack == 0) return NO_INIT;
1688 return mTrack->channelCount();
1689}
1690
1691ssize_t MediaPlayerService::AudioOutput::frameSize() const
1692{
Andy Hungd1c74342015-07-07 16:54:23 -07001693 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001694 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001695 return mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001696}
1697
1698uint32_t MediaPlayerService::AudioOutput::latency () const
1699{
Andy Hungd1c74342015-07-07 16:54:23 -07001700 Mutex::Autolock lock(mLock);
Eric Laurentdb354e52012-03-05 17:27:11 -08001701 if (mTrack == 0) return 0;
1702 return mTrack->latency();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001703}
1704
1705float MediaPlayerService::AudioOutput::msecsPerFrame() const
1706{
Andy Hungd1c74342015-07-07 16:54:23 -07001707 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001708 return mMsecsPerFrame;
1709}
1710
Marco Nelissen4110c102012-03-29 09:31:28 -07001711status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position) const
Eric Laurent342e9cf2010-01-19 17:37:09 -08001712{
Andy Hungd1c74342015-07-07 16:54:23 -07001713 Mutex::Autolock lock(mLock);
Eric Laurent342e9cf2010-01-19 17:37:09 -08001714 if (mTrack == 0) return NO_INIT;
1715 return mTrack->getPosition(position);
1716}
1717
Lajos Molnar06ad1522014-08-28 07:27:44 -07001718status_t MediaPlayerService::AudioOutput::getTimestamp(AudioTimestamp &ts) const
1719{
Andy Hungd1c74342015-07-07 16:54:23 -07001720 Mutex::Autolock lock(mLock);
Lajos Molnar06ad1522014-08-28 07:27:44 -07001721 if (mTrack == 0) return NO_INIT;
1722 return mTrack->getTimestamp(ts);
1723}
1724
Wei Jiac4ac8172015-10-21 10:35:48 -07001725// TODO: Remove unnecessary calls to getPlayedOutDurationUs()
1726// as it acquires locks and may query the audio driver.
1727//
1728// Some calls could conceivably retrieve extrapolated data instead of
1729// accessing getTimestamp() or getPosition() every time a data buffer with
1730// a media time is received.
1731//
1732// Calculate duration of played samples if played at normal rate (i.e., 1.0).
1733int64_t MediaPlayerService::AudioOutput::getPlayedOutDurationUs(int64_t nowUs) const
1734{
1735 Mutex::Autolock lock(mLock);
1736 if (mTrack == 0 || mSampleRateHz == 0) {
Wei Jia213f4902015-10-22 08:55:25 -07001737 return 0;
Wei Jiac4ac8172015-10-21 10:35:48 -07001738 }
1739
1740 uint32_t numFramesPlayed;
Andy Hung5d313802016-10-10 15:09:39 -07001741 int64_t numFramesPlayedAtUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001742 AudioTimestamp ts;
Wei Jiac4ac8172015-10-21 10:35:48 -07001743
1744 status_t res = mTrack->getTimestamp(ts);
1745 if (res == OK) { // case 1: mixing audio tracks and offloaded tracks.
1746 numFramesPlayed = ts.mPosition;
Andy Hung5d313802016-10-10 15:09:39 -07001747 numFramesPlayedAtUs = ts.mTime.tv_sec * 1000000LL + ts.mTime.tv_nsec / 1000;
1748 //ALOGD("getTimestamp: OK %d %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001749 } else if (res == WOULD_BLOCK) { // case 2: transitory state on start of a new track
1750 numFramesPlayed = 0;
Andy Hung5d313802016-10-10 15:09:39 -07001751 numFramesPlayedAtUs = nowUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001752 //ALOGD("getTimestamp: WOULD_BLOCK %d %lld",
Andy Hung5d313802016-10-10 15:09:39 -07001753 // numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001754 } else { // case 3: transitory at new track or audio fast tracks.
1755 res = mTrack->getPosition(&numFramesPlayed);
1756 CHECK_EQ(res, (status_t)OK);
Andy Hung5d313802016-10-10 15:09:39 -07001757 numFramesPlayedAtUs = nowUs;
1758 numFramesPlayedAtUs += 1000LL * mTrack->latency() / 2; /* XXX */
1759 //ALOGD("getPosition: %u %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001760 }
1761
1762 // CHECK_EQ(numFramesPlayed & (1 << 31), 0); // can't be negative until 12.4 hrs, test
1763 // TODO: remove the (int32_t) casting below as it may overflow at 12.4 hours.
1764 int64_t durationUs = (int64_t)((int32_t)numFramesPlayed * 1000000LL / mSampleRateHz)
Andy Hung5d313802016-10-10 15:09:39 -07001765 + nowUs - numFramesPlayedAtUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001766 if (durationUs < 0) {
1767 // Occurs when numFramesPlayed position is very small and the following:
1768 // (1) In case 1, the time nowUs is computed before getTimestamp() is called and
Andy Hung5d313802016-10-10 15:09:39 -07001769 // numFramesPlayedAtUs is greater than nowUs by time more than numFramesPlayed.
Wei Jiac4ac8172015-10-21 10:35:48 -07001770 // (2) In case 3, using getPosition and adding mAudioSink->latency() to
Andy Hung5d313802016-10-10 15:09:39 -07001771 // numFramesPlayedAtUs, by a time amount greater than numFramesPlayed.
Wei Jiac4ac8172015-10-21 10:35:48 -07001772 //
1773 // Both of these are transitory conditions.
1774 ALOGV("getPlayedOutDurationUs: negative duration %lld set to zero", (long long)durationUs);
1775 durationUs = 0;
1776 }
1777 ALOGV("getPlayedOutDurationUs(%lld) nowUs(%lld) frames(%u) framesAt(%lld)",
Andy Hung5d313802016-10-10 15:09:39 -07001778 (long long)durationUs, (long long)nowUs,
1779 numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001780 return durationUs;
1781}
1782
Marco Nelissen4110c102012-03-29 09:31:28 -07001783status_t MediaPlayerService::AudioOutput::getFramesWritten(uint32_t *frameswritten) const
1784{
Andy Hungd1c74342015-07-07 16:54:23 -07001785 Mutex::Autolock lock(mLock);
Marco Nelissen4110c102012-03-29 09:31:28 -07001786 if (mTrack == 0) return NO_INIT;
Andy Hung2f6e73d2016-04-08 12:12:58 -07001787 ExtendedTimestamp ets;
1788 status_t status = mTrack->getTimestamp(&ets);
1789 if (status == OK || status == WOULD_BLOCK) {
1790 *frameswritten = (uint32_t)ets.mPosition[ExtendedTimestamp::LOCATION_CLIENT];
1791 }
1792 return status;
Marco Nelissen4110c102012-03-29 09:31:28 -07001793}
1794
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001795status_t MediaPlayerService::AudioOutput::setParameters(const String8& keyValuePairs)
1796{
Andy Hungd1c74342015-07-07 16:54:23 -07001797 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001798 if (mTrack == 0) return NO_INIT;
1799 return mTrack->setParameters(keyValuePairs);
1800}
1801
1802String8 MediaPlayerService::AudioOutput::getParameters(const String8& keys)
1803{
Andy Hungd1c74342015-07-07 16:54:23 -07001804 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001805 if (mTrack == 0) return String8::empty();
1806 return mTrack->getParameters(keys);
1807}
1808
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001809void MediaPlayerService::AudioOutput::setAudioAttributes(const audio_attributes_t * attributes) {
Andy Hungd1c74342015-07-07 16:54:23 -07001810 Mutex::Autolock lock(mLock);
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001811 if (attributes == NULL) {
1812 free(mAttributes);
1813 mAttributes = NULL;
1814 } else {
1815 if (mAttributes == NULL) {
1816 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1817 }
1818 memcpy(mAttributes, attributes, sizeof(audio_attributes_t));
Eric Laurent43562692015-07-15 16:49:07 -07001819 mStreamType = audio_attributes_to_stream_type(attributes);
1820 }
1821}
1822
1823void MediaPlayerService::AudioOutput::setAudioStreamType(audio_stream_type_t streamType)
1824{
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001825 Mutex::Autolock lock(mLock);
Eric Laurent43562692015-07-15 16:49:07 -07001826 // do not allow direct stream type modification if attributes have been set
1827 if (mAttributes == NULL) {
1828 mStreamType = streamType;
1829 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001830}
1831
Andy Hungd1c74342015-07-07 16:54:23 -07001832void MediaPlayerService::AudioOutput::deleteRecycledTrack_l()
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001833{
Andy Hungd1c74342015-07-07 16:54:23 -07001834 ALOGV("deleteRecycledTrack_l");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001835 if (mRecycledTrack != 0) {
1836
1837 if (mCallbackData != NULL) {
1838 mCallbackData->setOutput(NULL);
1839 mCallbackData->endTrackSwitch();
1840 }
1841
1842 if ((mRecycledTrack->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) {
Andy Hunge13f8a62016-03-30 14:20:42 -07001843 int32_t msec = 0;
1844 if (!mRecycledTrack->stopped()) { // check if active
1845 (void)mRecycledTrack->pendingDuration(&msec);
1846 }
1847 mRecycledTrack->stop(); // ensure full data drain
1848 ALOGD("deleting recycled track, waiting for data drain (%d msec)", msec);
1849 if (msec > 0) {
1850 static const int32_t WAIT_LIMIT_MS = 3000;
1851 if (msec > WAIT_LIMIT_MS) {
1852 msec = WAIT_LIMIT_MS;
1853 }
1854 usleep(msec * 1000LL);
1855 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001856 }
1857 // An offloaded track isn't flushed because the STREAM_END is reported
1858 // slightly prematurely to allow time for the gapless track switch
1859 // but this means that if we decide not to recycle the track there
1860 // could be a small amount of residual data still playing. We leave
1861 // AudioFlinger to drain the track.
1862
1863 mRecycledTrack.clear();
Andy Hungd1c74342015-07-07 16:54:23 -07001864 close_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001865 delete mCallbackData;
1866 mCallbackData = NULL;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001867 }
1868}
1869
Andy Hungd1c74342015-07-07 16:54:23 -07001870void MediaPlayerService::AudioOutput::close_l()
1871{
1872 mTrack.clear();
1873}
1874
Andreas Huber20111aa2009-07-14 16:56:47 -07001875status_t MediaPlayerService::AudioOutput::open(
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001876 uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
1877 audio_format_t format, int bufferCount,
Eric Laurent1948eb32012-04-13 16:50:19 -07001878 AudioCallback cb, void *cookie,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001879 audio_output_flags_t flags,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001880 const audio_offload_info_t *offloadInfo,
Andy Hung179652e2015-05-31 22:49:46 -07001881 bool doNotReconnect,
1882 uint32_t suggestedFrameCount)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001883{
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001884 ALOGV("open(%u, %d, 0x%x, 0x%x, %d, %d 0x%x)", sampleRate, channelCount, channelMask,
1885 format, bufferCount, mSessionId, flags);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001886
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001887 // offloading is only supported in callback mode for now.
1888 // offloadInfo must be present if offload flag is set
1889 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) &&
1890 ((cb == NULL) || (offloadInfo == NULL))) {
1891 return BAD_VALUE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001892 }
1893
Andy Hung179652e2015-05-31 22:49:46 -07001894 // compute frame count for the AudioTrack internal buffer
1895 size_t frameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001896 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1897 frameCount = 0; // AudioTrack will get frame count from AudioFlinger
1898 } else {
Andy Hung179652e2015-05-31 22:49:46 -07001899 // try to estimate the buffer processing fetch size from AudioFlinger.
1900 // framesPerBuffer is approximate and generally correct, except when it's not :-).
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001901 uint32_t afSampleRate;
1902 size_t afFrameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001903 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1904 return NO_INIT;
1905 }
1906 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1907 return NO_INIT;
1908 }
Ben Romberger259fb462018-08-07 17:58:53 -07001909 if (afSampleRate == 0) {
1910 return NO_INIT;
1911 }
Andy Hung179652e2015-05-31 22:49:46 -07001912 const size_t framesPerBuffer =
1913 (unsigned long long)sampleRate * afFrameCount / afSampleRate;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001914
Andy Hung179652e2015-05-31 22:49:46 -07001915 if (bufferCount == 0) {
Ben Romberger259fb462018-08-07 17:58:53 -07001916 if (framesPerBuffer == 0) {
1917 return NO_INIT;
1918 }
Andy Hung179652e2015-05-31 22:49:46 -07001919 // use suggestedFrameCount
1920 bufferCount = (suggestedFrameCount + framesPerBuffer - 1) / framesPerBuffer;
1921 }
1922 // Check argument bufferCount against the mininum buffer count
1923 if (bufferCount != 0 && bufferCount < mMinBufferCount) {
1924 ALOGV("bufferCount (%d) increased to %d", bufferCount, mMinBufferCount);
1925 bufferCount = mMinBufferCount;
1926 }
1927 // if frameCount is 0, then AudioTrack will get frame count from AudioFlinger
1928 // which will be the minimum size permitted.
1929 frameCount = bufferCount * framesPerBuffer;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001930 }
Andreas Huber20111aa2009-07-14 16:56:47 -07001931
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001932 if (channelMask == CHANNEL_MASK_USE_CHANNEL_ORDER) {
Glenn Kastenab334fd2012-03-14 12:56:06 -07001933 channelMask = audio_channel_out_mask_from_count(channelCount);
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001934 if (0 == channelMask) {
1935 ALOGE("open() error, can\'t derive mask for %d audio channels", channelCount);
1936 return NO_INIT;
1937 }
1938 }
Eric Laurent1948eb32012-04-13 16:50:19 -07001939
Andy Hungd1c74342015-07-07 16:54:23 -07001940 Mutex::Autolock lock(mLock);
Andy Hung179652e2015-05-31 22:49:46 -07001941 mCallback = cb;
1942 mCallbackCookie = cookie;
1943
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001944 // Check whether we can recycle the track
1945 bool reuse = false;
1946 bool bothOffloaded = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001947
Glenn Kasten2799d742013-05-30 14:33:29 -07001948 if (mRecycledTrack != 0) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001949 // check whether we are switching between two offloaded tracks
1950 bothOffloaded = (flags & mRecycledTrack->getFlags()
1951 & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0;
Marco Nelissen67295b52012-06-11 14:52:53 -07001952
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001953 // check if the existing track can be reused as-is, or if a new track needs to be created.
1954 reuse = true;
1955
Marco Nelissen67295b52012-06-11 14:52:53 -07001956 if ((mCallbackData == NULL && mCallback != NULL) ||
1957 (mCallbackData != NULL && mCallback == NULL)) {
1958 // recycled track uses callbacks but the caller wants to use writes, or vice versa
1959 ALOGV("can't chain callback and write");
1960 reuse = false;
1961 } else if ((mRecycledTrack->getSampleRate() != sampleRate) ||
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001962 (mRecycledTrack->channelCount() != (uint32_t)channelCount) ) {
1963 ALOGV("samplerate, channelcount differ: %u/%u Hz, %u/%d ch",
Marco Nelissen67295b52012-06-11 14:52:53 -07001964 mRecycledTrack->getSampleRate(), sampleRate,
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001965 mRecycledTrack->channelCount(), channelCount);
Marco Nelissen67295b52012-06-11 14:52:53 -07001966 reuse = false;
1967 } else if (flags != mFlags) {
1968 ALOGV("output flags differ %08x/%08x", flags, mFlags);
1969 reuse = false;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001970 } else if (mRecycledTrack->format() != format) {
1971 reuse = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001972 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001973 } else {
1974 ALOGV("no track available to recycle");
1975 }
1976
1977 ALOGV_IF(bothOffloaded, "both tracks offloaded");
1978
1979 // If we can't recycle and both tracks are offloaded
1980 // we must close the previous output before opening a new one
1981 if (bothOffloaded && !reuse) {
1982 ALOGV("both offloaded and not recycling");
Andy Hungd1c74342015-07-07 16:54:23 -07001983 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001984 }
1985
1986 sp<AudioTrack> t;
1987 CallbackData *newcbd = NULL;
1988
1989 // We don't attempt to create a new track if we are recycling an
1990 // offloaded track. But, if we are recycling a non-offloaded or we
1991 // are switching where one is offloaded and one isn't then we create
1992 // the new track in advance so that we can read additional stream info
1993
1994 if (!(reuse && bothOffloaded)) {
1995 ALOGV("creating new AudioTrack");
1996
1997 if (mCallback != NULL) {
1998 newcbd = new CallbackData(this);
1999 t = new AudioTrack(
2000 mStreamType,
2001 sampleRate,
2002 format,
2003 channelMask,
2004 frameCount,
2005 flags,
2006 CallbackWrapper,
2007 newcbd,
2008 0, // notification frames
2009 mSessionId,
2010 AudioTrack::TRANSFER_CALLBACK,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002011 offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -08002012 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07002013 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07002014 mAttributes,
jiabin156c6872017-10-06 09:47:15 -07002015 doNotReconnect,
2016 1.0f, // default value for maxRequiredSpeed
2017 mSelectedDeviceId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002018 } else {
Andy Hungff874dc2016-04-11 16:49:09 -07002019 // TODO: Due to buffer memory concerns, we use a max target playback speed
2020 // based on mPlaybackRate at the time of open (instead of kMaxRequiredSpeed),
2021 // also clamping the target speed to 1.0 <= targetSpeed <= kMaxRequiredSpeed.
2022 const float targetSpeed =
2023 std::min(std::max(mPlaybackRate.mSpeed, 1.0f), kMaxRequiredSpeed);
2024 ALOGW_IF(targetSpeed != mPlaybackRate.mSpeed,
2025 "track target speed:%f clamped from playback speed:%f",
2026 targetSpeed, mPlaybackRate.mSpeed);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002027 t = new AudioTrack(
2028 mStreamType,
2029 sampleRate,
2030 format,
2031 channelMask,
2032 frameCount,
2033 flags,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002034 NULL, // callback
2035 NULL, // user data
2036 0, // notification frames
2037 mSessionId,
2038 AudioTrack::TRANSFER_DEFAULT,
2039 NULL, // offload info
Marco Nelissend457c972014-02-11 08:47:07 -08002040 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07002041 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07002042 mAttributes,
Andy Hungff874dc2016-04-11 16:49:09 -07002043 doNotReconnect,
jiabin156c6872017-10-06 09:47:15 -07002044 targetSpeed,
2045 mSelectedDeviceId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002046 }
2047
2048 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
2049 ALOGE("Unable to create audio track");
2050 delete newcbd;
Glenn Kasten3e98ecd2015-05-18 13:13:24 -07002051 // t goes out of scope, so reference count drops to zero
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002052 return NO_INIT;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07002053 } else {
2054 // successful AudioTrack initialization implies a legacy stream type was generated
2055 // from the audio attributes
2056 mStreamType = t->streamType();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002057 }
2058 }
2059
2060 if (reuse) {
2061 CHECK(mRecycledTrack != NULL);
2062
2063 if (!bothOffloaded) {
2064 if (mRecycledTrack->frameCount() != t->frameCount()) {
Andy Hung833b4752016-04-04 17:15:48 -07002065 ALOGV("framecount differs: %zu/%zu frames",
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002066 mRecycledTrack->frameCount(), t->frameCount());
2067 reuse = false;
2068 }
2069 }
2070
Marco Nelissen67295b52012-06-11 14:52:53 -07002071 if (reuse) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002072 ALOGV("chaining to next output and recycling track");
Andy Hungd1c74342015-07-07 16:54:23 -07002073 close_l();
Marco Nelissen67295b52012-06-11 14:52:53 -07002074 mTrack = mRecycledTrack;
Glenn Kasten2799d742013-05-30 14:33:29 -07002075 mRecycledTrack.clear();
Marco Nelissen67295b52012-06-11 14:52:53 -07002076 if (mCallbackData != NULL) {
2077 mCallbackData->setOutput(this);
2078 }
Marco Nelissen67295b52012-06-11 14:52:53 -07002079 delete newcbd;
Wei Jiae0bbac92016-07-18 16:04:53 -07002080 return updateTrack();
Marco Nelissen67295b52012-06-11 14:52:53 -07002081 }
Marco Nelissen67295b52012-06-11 14:52:53 -07002082 }
2083
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002084 // we're not going to reuse the track, unblock and flush it
2085 // this was done earlier if both tracks are offloaded
2086 if (!bothOffloaded) {
Andy Hungd1c74342015-07-07 16:54:23 -07002087 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002088 }
2089
2090 CHECK((t != NULL) && ((mCallback == NULL) || (newcbd != NULL)));
2091
Marco Nelissen67295b52012-06-11 14:52:53 -07002092 mCallbackData = newcbd;
Steve Block3856b092011-10-20 11:56:00 +01002093 ALOGV("setVolume");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002094 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07002095
Andy Hung39399b62017-04-21 15:07:45 -07002096 // Restore VolumeShapers for the MediaPlayer in case the track was recreated
2097 // due to an output sink error (e.g. offload to non-offload switch).
2098 mVolumeHandler->forall([&t](const VolumeShaper &shaper) -> VolumeShaper::Status {
2099 sp<VolumeShaper::Operation> operationToEnd =
2100 new VolumeShaper::Operation(shaper.mOperation);
2101 // TODO: Ideally we would restore to the exact xOffset position
2102 // as returned by getVolumeShaperState(), but we don't have that
2103 // information when restoring at the client unless we periodically poll
2104 // the server or create shared memory state.
2105 //
2106 // For now, we simply advance to the end of the VolumeShaper effect
2107 // if it has been started.
2108 if (shaper.isStarted()) {
Andy Hungf3702642017-05-05 17:33:32 -07002109 operationToEnd->setNormalizedTime(1.f);
Andy Hung39399b62017-04-21 15:07:45 -07002110 }
2111 return t->applyVolumeShaper(shaper.mConfiguration, operationToEnd);
Andy Hung4ef88d72017-02-21 19:47:53 -08002112 });
Andy Hung4ef88d72017-02-21 19:47:53 -08002113
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002114 mSampleRateHz = sampleRate;
Preetam Singh Ranawat2e17eef2015-08-12 12:11:46 -07002115 mFlags = flags;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002116 mMsecsPerFrame = 1E3f / (mPlaybackRate.mSpeed * sampleRate);
Andy Hungd1c74342015-07-07 16:54:23 -07002117 mFrameSize = t->frameSize();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002118 mTrack = t;
Eric Laurent2beeb502010-07-16 07:43:46 -07002119
Wei Jiae0bbac92016-07-18 16:04:53 -07002120 return updateTrack();
2121}
2122
2123status_t MediaPlayerService::AudioOutput::updateTrack() {
2124 if (mTrack == NULL) {
2125 return NO_ERROR;
2126 }
2127
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002128 status_t res = NO_ERROR;
Wei Jia0162d002015-06-09 11:59:33 -07002129 // Note some output devices may give us a direct track even though we don't specify it.
2130 // Example: Line application b/17459982.
Wei Jiae0bbac92016-07-18 16:04:53 -07002131 if ((mTrack->getFlags()
2132 & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) {
2133 res = mTrack->setPlaybackRate(mPlaybackRate);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002134 if (res == NO_ERROR) {
Wei Jiae0bbac92016-07-18 16:04:53 -07002135 mTrack->setAuxEffectSendLevel(mSendLevel);
2136 res = mTrack->attachAuxEffect(mAuxEffectId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002137 }
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002138 }
jiabin156c6872017-10-06 09:47:15 -07002139 mTrack->setOutputDevice(mSelectedDeviceId);
2140 if (mDeviceCallbackEnabled) {
2141 mTrack->addAudioDeviceCallback(mDeviceCallback.promote());
2142 }
Wei Jiae0bbac92016-07-18 16:04:53 -07002143 ALOGV("updateTrack() DONE status %d", res);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002144 return res;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002145}
2146
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002147status_t MediaPlayerService::AudioOutput::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002148{
Steve Block3856b092011-10-20 11:56:00 +01002149 ALOGV("start");
Andy Hungd1c74342015-07-07 16:54:23 -07002150 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08002151 if (mCallbackData != NULL) {
2152 mCallbackData->endTrackSwitch();
2153 }
Glenn Kasten2799d742013-05-30 14:33:29 -07002154 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002155 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07002156 mTrack->setAuxEffectSendLevel(mSendLevel);
Andy Hung39399b62017-04-21 15:07:45 -07002157 status_t status = mTrack->start();
2158 if (status == NO_ERROR) {
2159 mVolumeHandler->setStarted();
2160 }
2161 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002162 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002163 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002164}
2165
Marco Nelissen6b74d672012-02-28 16:07:44 -08002166void MediaPlayerService::AudioOutput::setNextOutput(const sp<AudioOutput>& nextOutput) {
Andy Hungd1c74342015-07-07 16:54:23 -07002167 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08002168 mNextOutput = nextOutput;
2169}
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08002170
Marco Nelissen6b74d672012-02-28 16:07:44 -08002171void MediaPlayerService::AudioOutput::switchToNextOutput() {
2172 ALOGV("switchToNextOutput");
Andy Hungd1c74342015-07-07 16:54:23 -07002173
2174 // Try to acquire the callback lock before moving track (without incurring deadlock).
2175 const unsigned kMaxSwitchTries = 100;
2176 Mutex::Autolock lock(mLock);
2177 for (unsigned tries = 0;;) {
2178 if (mTrack == 0) {
2179 return;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002180 }
Andy Hungd1c74342015-07-07 16:54:23 -07002181 if (mNextOutput != NULL && mNextOutput != this) {
2182 if (mCallbackData != NULL) {
2183 // two alternative approaches
2184#if 1
2185 CallbackData *callbackData = mCallbackData;
2186 mLock.unlock();
2187 // proper acquisition sequence
2188 callbackData->lock();
2189 mLock.lock();
2190 // Caution: it is unlikely that someone deleted our callback or changed our target
2191 if (callbackData != mCallbackData || mNextOutput == NULL || mNextOutput == this) {
2192 // fatal if we are starved out.
2193 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2194 "switchToNextOutput() cannot obtain correct lock sequence");
2195 callbackData->unlock();
2196 continue;
2197 }
2198 callbackData->mSwitching = true; // begin track switch
Wei Jiaadee56a2016-08-05 15:40:34 -07002199 callbackData->setOutput(NULL);
Andy Hungd1c74342015-07-07 16:54:23 -07002200#else
2201 // tryBeginTrackSwitch() returns false if the callback has the lock.
2202 if (!mCallbackData->tryBeginTrackSwitch()) {
2203 // fatal if we are starved out.
2204 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2205 "switchToNextOutput() cannot obtain callback lock");
2206 mLock.unlock();
2207 usleep(5 * 1000 /* usec */); // allow callback to use AudioOutput
2208 mLock.lock();
2209 continue;
2210 }
2211#endif
2212 }
2213
2214 Mutex::Autolock nextLock(mNextOutput->mLock);
2215
2216 // If the next output track is not NULL, then it has been
2217 // opened already for playback.
2218 // This is possible even without the next player being started,
2219 // for example, the next player could be prepared and seeked.
2220 //
2221 // Presuming it isn't advisable to force the track over.
2222 if (mNextOutput->mTrack == NULL) {
2223 ALOGD("Recycling track for gapless playback");
2224 delete mNextOutput->mCallbackData;
2225 mNextOutput->mCallbackData = mCallbackData;
2226 mNextOutput->mRecycledTrack = mTrack;
2227 mNextOutput->mSampleRateHz = mSampleRateHz;
2228 mNextOutput->mMsecsPerFrame = mMsecsPerFrame;
Andy Hungd1c74342015-07-07 16:54:23 -07002229 mNextOutput->mFlags = mFlags;
2230 mNextOutput->mFrameSize = mFrameSize;
2231 close_l();
2232 mCallbackData = NULL; // destruction handled by mNextOutput
2233 } else {
2234 ALOGW("Ignoring gapless playback because next player has already started");
2235 // remove track in case resource needed for future players.
2236 if (mCallbackData != NULL) {
2237 mCallbackData->endTrackSwitch(); // release lock for callbacks before close.
2238 }
2239 close_l();
2240 }
2241 }
2242 break;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002243 }
2244}
2245
Wei Jia7d3f4df2015-03-03 15:28:00 -08002246ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002247{
Andy Hungd1c74342015-07-07 16:54:23 -07002248 Mutex::Autolock lock(mLock);
Glenn Kastenadad3d72014-02-21 14:51:43 -08002249 LOG_ALWAYS_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
Andreas Huber20111aa2009-07-14 16:56:47 -07002250
Steve Block3856b092011-10-20 11:56:00 +01002251 //ALOGV("write(%p, %u)", buffer, size);
Glenn Kasten2799d742013-05-30 14:33:29 -07002252 if (mTrack != 0) {
Andy Hung2f6e73d2016-04-08 12:12:58 -07002253 return mTrack->write(buffer, size, blocking);
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07002254 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002255 return NO_INIT;
2256}
2257
2258void MediaPlayerService::AudioOutput::stop()
2259{
Steve Block3856b092011-10-20 11:56:00 +01002260 ALOGV("stop");
Andy Hungd1c74342015-07-07 16:54:23 -07002261 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002262 if (mTrack != 0) mTrack->stop();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002263}
2264
2265void MediaPlayerService::AudioOutput::flush()
2266{
Steve Block3856b092011-10-20 11:56:00 +01002267 ALOGV("flush");
Andy Hungd1c74342015-07-07 16:54:23 -07002268 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002269 if (mTrack != 0) mTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002270}
2271
2272void MediaPlayerService::AudioOutput::pause()
2273{
Steve Block3856b092011-10-20 11:56:00 +01002274 ALOGV("pause");
Andy Hungd1c74342015-07-07 16:54:23 -07002275 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002276 if (mTrack != 0) mTrack->pause();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002277}
2278
2279void MediaPlayerService::AudioOutput::close()
2280{
Steve Block3856b092011-10-20 11:56:00 +01002281 ALOGV("close");
Erik Wolsheimer7845a1f2015-10-30 12:07:52 -07002282 sp<AudioTrack> track;
2283 {
2284 Mutex::Autolock lock(mLock);
2285 track = mTrack;
2286 close_l(); // clears mTrack
2287 }
2288 // destruction of the track occurs outside of mutex.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002289}
2290
2291void MediaPlayerService::AudioOutput::setVolume(float left, float right)
2292{
Steve Block3856b092011-10-20 11:56:00 +01002293 ALOGV("setVolume(%f, %f)", left, right);
Andy Hungd1c74342015-07-07 16:54:23 -07002294 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002295 mLeftVolume = left;
2296 mRightVolume = right;
Glenn Kasten2799d742013-05-30 14:33:29 -07002297 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002298 mTrack->setVolume(left, right);
2299 }
2300}
2301
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002302status_t MediaPlayerService::AudioOutput::setPlaybackRate(const AudioPlaybackRate &rate)
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002303{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002304 ALOGV("setPlaybackRate(%f %f %d %d)",
2305 rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Andy Hungd1c74342015-07-07 16:54:23 -07002306 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002307 if (mTrack == 0) {
2308 // remember rate so that we can set it when the track is opened
2309 mPlaybackRate = rate;
2310 return OK;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002311 }
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002312 status_t res = mTrack->setPlaybackRate(rate);
2313 if (res != NO_ERROR) {
2314 return res;
2315 }
2316 // rate.mSpeed is always greater than 0 if setPlaybackRate succeeded
2317 CHECK_GT(rate.mSpeed, 0.f);
2318 mPlaybackRate = rate;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002319 if (mSampleRateHz != 0) {
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002320 mMsecsPerFrame = 1E3f / (rate.mSpeed * mSampleRateHz);
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002321 }
2322 return res;
2323}
2324
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002325status_t MediaPlayerService::AudioOutput::getPlaybackRate(AudioPlaybackRate *rate)
2326{
2327 ALOGV("setPlaybackRate");
Andy Hungd1c74342015-07-07 16:54:23 -07002328 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002329 if (mTrack == 0) {
2330 return NO_INIT;
2331 }
2332 *rate = mTrack->getPlaybackRate();
2333 return NO_ERROR;
2334}
2335
Eric Laurent2beeb502010-07-16 07:43:46 -07002336status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
2337{
Steve Block3856b092011-10-20 11:56:00 +01002338 ALOGV("setAuxEffectSendLevel(%f)", level);
Andy Hungd1c74342015-07-07 16:54:23 -07002339 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002340 mSendLevel = level;
Glenn Kasten2799d742013-05-30 14:33:29 -07002341 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002342 return mTrack->setAuxEffectSendLevel(level);
2343 }
2344 return NO_ERROR;
2345}
2346
2347status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
2348{
Steve Block3856b092011-10-20 11:56:00 +01002349 ALOGV("attachAuxEffect(%d)", effectId);
Andy Hungd1c74342015-07-07 16:54:23 -07002350 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002351 mAuxEffectId = effectId;
Glenn Kasten2799d742013-05-30 14:33:29 -07002352 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002353 return mTrack->attachAuxEffect(effectId);
2354 }
2355 return NO_ERROR;
2356}
2357
jiabin156c6872017-10-06 09:47:15 -07002358status_t MediaPlayerService::AudioOutput::setOutputDevice(audio_port_handle_t deviceId)
2359{
2360 ALOGV("setOutputDevice(%d)", deviceId);
2361 Mutex::Autolock lock(mLock);
2362 mSelectedDeviceId = deviceId;
2363 if (mTrack != 0) {
2364 return mTrack->setOutputDevice(deviceId);
2365 }
2366 return NO_ERROR;
2367}
2368
2369status_t MediaPlayerService::AudioOutput::getRoutedDeviceId(audio_port_handle_t* deviceId)
2370{
2371 ALOGV("getRoutedDeviceId");
2372 Mutex::Autolock lock(mLock);
2373 if (mTrack != 0) {
jiabin161b64fc2017-11-17 09:31:48 -08002374 mRoutedDeviceId = mTrack->getRoutedDeviceId();
jiabin156c6872017-10-06 09:47:15 -07002375 }
jiabin161b64fc2017-11-17 09:31:48 -08002376 *deviceId = mRoutedDeviceId;
2377 return NO_ERROR;
jiabin156c6872017-10-06 09:47:15 -07002378}
2379
2380status_t MediaPlayerService::AudioOutput::enableAudioDeviceCallback(bool enabled)
2381{
2382 ALOGV("enableAudioDeviceCallback, %d", enabled);
2383 Mutex::Autolock lock(mLock);
2384 mDeviceCallbackEnabled = enabled;
2385 if (mTrack != 0) {
2386 status_t status;
2387 if (enabled) {
2388 status = mTrack->addAudioDeviceCallback(mDeviceCallback.promote());
2389 } else {
2390 status = mTrack->removeAudioDeviceCallback(mDeviceCallback.promote());
2391 }
2392 return status;
2393 }
2394 return NO_ERROR;
2395}
2396
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002397VolumeShaper::Status MediaPlayerService::AudioOutput::applyVolumeShaper(
2398 const sp<VolumeShaper::Configuration>& configuration,
2399 const sp<VolumeShaper::Operation>& operation)
2400{
2401 Mutex::Autolock lock(mLock);
2402 ALOGV("AudioOutput::applyVolumeShaper");
Andy Hung4ef88d72017-02-21 19:47:53 -08002403
Andy Hung4ef88d72017-02-21 19:47:53 -08002404 mVolumeHandler->setIdIfNecessary(configuration);
Andy Hung39399b62017-04-21 15:07:45 -07002405
2406 VolumeShaper::Status status;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002407 if (mTrack != 0) {
Andy Hung39399b62017-04-21 15:07:45 -07002408 status = mTrack->applyVolumeShaper(configuration, operation);
2409 if (status >= 0) {
2410 (void)mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hungf3702642017-05-05 17:33:32 -07002411 if (mTrack->isPlaying()) { // match local AudioTrack to properly restore.
2412 mVolumeHandler->setStarted();
2413 }
Andy Hung39399b62017-04-21 15:07:45 -07002414 }
Andy Hung4ef88d72017-02-21 19:47:53 -08002415 } else {
Andy Hungc01eddb2017-07-21 16:42:41 -07002416 // VolumeShapers are not affected when a track moves between players for
2417 // gapless playback (setNextMediaPlayer).
2418 // We forward VolumeShaper operations that do not change configuration
2419 // to the new player so that unducking may occur as expected.
2420 // Unducking is an idempotent operation, same if applied back-to-back.
2421 if (configuration->getType() == VolumeShaper::Configuration::TYPE_ID
2422 && mNextOutput != nullptr) {
2423 ALOGV("applyVolumeShaper: Attempting to forward missed operation: %s %s",
2424 configuration->toString().c_str(), operation->toString().c_str());
2425 Mutex::Autolock nextLock(mNextOutput->mLock);
2426
2427 // recycled track should be forwarded from this AudioSink by switchToNextOutput
2428 sp<AudioTrack> track = mNextOutput->mRecycledTrack;
2429 if (track != nullptr) {
2430 ALOGD("Forward VolumeShaper operation to recycled track %p", track.get());
2431 (void)track->applyVolumeShaper(configuration, operation);
2432 } else {
2433 // There is a small chance that the unduck occurs after the next
2434 // player has already started, but before it is registered to receive
2435 // the unduck command.
2436 track = mNextOutput->mTrack;
2437 if (track != nullptr) {
2438 ALOGD("Forward VolumeShaper operation to track %p", track.get());
2439 (void)track->applyVolumeShaper(configuration, operation);
2440 }
2441 }
2442 }
Andy Hung39399b62017-04-21 15:07:45 -07002443 status = mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002444 }
Andy Hung39399b62017-04-21 15:07:45 -07002445 return status;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002446}
2447
2448sp<VolumeShaper::State> MediaPlayerService::AudioOutput::getVolumeShaperState(int id)
2449{
2450 Mutex::Autolock lock(mLock);
2451 if (mTrack != 0) {
2452 return mTrack->getVolumeShaperState(id);
Andy Hung4ef88d72017-02-21 19:47:53 -08002453 } else {
2454 return mVolumeHandler->getVolumeShaperState(id);
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002455 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002456}
2457
Andreas Huber20111aa2009-07-14 16:56:47 -07002458// static
2459void MediaPlayerService::AudioOutput::CallbackWrapper(
Glenn Kastend217a8c2011-06-01 15:20:35 -07002460 int event, void *cookie, void *info) {
Steve Block3856b092011-10-20 11:56:00 +01002461 //ALOGV("callbackwrapper");
Marco Nelissen6b74d672012-02-28 16:07:44 -08002462 CallbackData *data = (CallbackData*)cookie;
Andy Hungd1c74342015-07-07 16:54:23 -07002463 // lock to ensure we aren't caught in the middle of a track switch.
Marco Nelissen6b74d672012-02-28 16:07:44 -08002464 data->lock();
2465 AudioOutput *me = data->getOutput();
Andreas Huber20111aa2009-07-14 16:56:47 -07002466 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002467 if (me == NULL) {
2468 // no output set, likely because the track was scheduled to be reused
2469 // by another player, but the format turned out to be incompatible.
2470 data->unlock();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002471 if (buffer != NULL) {
2472 buffer->size = 0;
2473 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08002474 return;
2475 }
Andreas Huber20111aa2009-07-14 16:56:47 -07002476
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002477 switch(event) {
2478 case AudioTrack::EVENT_MORE_DATA: {
2479 size_t actualSize = (*me->mCallback)(
2480 me, buffer->raw, buffer->size, me->mCallbackCookie,
2481 CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002482
Andy Hung719b46b2015-05-31 22:18:25 -07002483 // Log when no data is returned from the callback.
2484 // (1) We may have no data (especially with network streaming sources).
2485 // (2) We may have reached the EOS and the audio track is not stopped yet.
2486 // Note that AwesomePlayer/AudioPlayer will only return zero size when it reaches the EOS.
2487 // NuPlayerRenderer will return zero when it doesn't have data (it doesn't block to fill).
2488 //
2489 // This is a benign busy-wait, with the next data request generated 10 ms or more later;
2490 // nevertheless for power reasons, we don't want to see too many of these.
Andreas Huber2e8ffaf2010-02-18 16:45:13 -08002491
Andy Hung719b46b2015-05-31 22:18:25 -07002492 ALOGV_IF(actualSize == 0 && buffer->size > 0, "callbackwrapper: empty buffer returned");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002493
2494 buffer->size = actualSize;
2495 } break;
2496
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002497 case AudioTrack::EVENT_STREAM_END:
Andy Hung719b46b2015-05-31 22:18:25 -07002498 // currently only occurs for offloaded callbacks
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002499 ALOGV("callbackwrapper: deliver EVENT_STREAM_END");
2500 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2501 me->mCallbackCookie, CB_EVENT_STREAM_END);
2502 break;
2503
2504 case AudioTrack::EVENT_NEW_IAUDIOTRACK :
2505 ALOGV("callbackwrapper: deliver EVENT_TEAR_DOWN");
2506 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2507 me->mCallbackCookie, CB_EVENT_TEAR_DOWN);
2508 break;
2509
Glenn Kasten421743b2015-06-01 08:18:08 -07002510 case AudioTrack::EVENT_UNDERRUN:
Andy Hung719b46b2015-05-31 22:18:25 -07002511 // This occurs when there is no data available, typically
Glenn Kasten421743b2015-06-01 08:18:08 -07002512 // when there is a failure to supply data to the AudioTrack. It can also
2513 // occur in non-offloaded mode when the audio device comes out of standby.
2514 //
Andy Hung719b46b2015-05-31 22:18:25 -07002515 // If an AudioTrack underruns it outputs silence. Since this happens suddenly
2516 // it may sound like an audible pop or glitch.
2517 //
2518 // The underrun event is sent once per track underrun; the condition is reset
2519 // when more data is sent to the AudioTrack.
Eric Laurente93cc032016-05-05 10:15:10 -07002520 ALOGD("callbackwrapper: EVENT_UNDERRUN (discarded)");
Glenn Kasten421743b2015-06-01 08:18:08 -07002521 break;
2522
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002523 default:
2524 ALOGE("received unknown event type: %d inside CallbackWrapper !", event);
Andreas Huber51c1e0e2011-04-04 11:43:40 -07002525 }
2526
Marco Nelissen6b74d672012-02-28 16:07:44 -08002527 data->unlock();
Andreas Huber20111aa2009-07-14 16:56:47 -07002528}
2529
Glenn Kastend848eb42016-03-08 13:42:11 -08002530audio_session_t MediaPlayerService::AudioOutput::getSessionId() const
Eric Laurent8c563ed2010-10-07 18:23:03 -07002531{
Andy Hungd1c74342015-07-07 16:54:23 -07002532 Mutex::Autolock lock(mLock);
Eric Laurent8c563ed2010-10-07 18:23:03 -07002533 return mSessionId;
2534}
2535
Eric Laurent6f59db12013-07-26 17:16:50 -07002536uint32_t MediaPlayerService::AudioOutput::getSampleRate() const
2537{
Andy Hungd1c74342015-07-07 16:54:23 -07002538 Mutex::Autolock lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -07002539 if (mTrack == 0) return 0;
2540 return mTrack->getSampleRate();
2541}
2542
Andy Hungf2c87b32016-04-07 19:49:29 -07002543int64_t MediaPlayerService::AudioOutput::getBufferDurationInUs() const
2544{
2545 Mutex::Autolock lock(mLock);
2546 if (mTrack == 0) {
2547 return 0;
2548 }
2549 int64_t duration;
2550 if (mTrack->getBufferDurationInUs(&duration) != OK) {
2551 return 0;
2552 }
2553 return duration;
2554}
2555
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002556////////////////////////////////////////////////////////////////////////////////
2557
2558struct CallbackThread : public Thread {
2559 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
2560 MediaPlayerBase::AudioSink::AudioCallback cb,
2561 void *cookie);
2562
2563protected:
2564 virtual ~CallbackThread();
2565
2566 virtual bool threadLoop();
2567
2568private:
2569 wp<MediaPlayerBase::AudioSink> mSink;
2570 MediaPlayerBase::AudioSink::AudioCallback mCallback;
2571 void *mCookie;
2572 void *mBuffer;
2573 size_t mBufferSize;
2574
2575 CallbackThread(const CallbackThread &);
2576 CallbackThread &operator=(const CallbackThread &);
2577};
2578
2579CallbackThread::CallbackThread(
2580 const wp<MediaPlayerBase::AudioSink> &sink,
2581 MediaPlayerBase::AudioSink::AudioCallback cb,
2582 void *cookie)
2583 : mSink(sink),
2584 mCallback(cb),
2585 mCookie(cookie),
2586 mBuffer(NULL),
2587 mBufferSize(0) {
2588}
2589
2590CallbackThread::~CallbackThread() {
2591 if (mBuffer) {
2592 free(mBuffer);
2593 mBuffer = NULL;
2594 }
2595}
2596
2597bool CallbackThread::threadLoop() {
2598 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
2599 if (sink == NULL) {
2600 return false;
2601 }
2602
2603 if (mBuffer == NULL) {
2604 mBufferSize = sink->bufferSize();
2605 mBuffer = malloc(mBufferSize);
2606 }
2607
2608 size_t actualSize =
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002609 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie,
2610 MediaPlayerBase::AudioSink::CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002611
2612 if (actualSize > 0) {
2613 sink->write(mBuffer, actualSize);
Andy Hunga31335a2014-08-20 17:37:59 -07002614 // Could return false on sink->write() error or short count.
2615 // Not necessarily appropriate but would work for AudioCache behavior.
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002616 }
2617
2618 return true;
2619}
2620
2621////////////////////////////////////////////////////////////////////////////////
2622
Chong Zhange5b9b692017-05-11 11:44:56 -07002623void MediaPlayerService::addBatteryData(uint32_t params) {
2624 mBatteryTracker.addBatteryData(params);
2625}
2626
2627status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
2628 return mBatteryTracker.pullBatteryData(reply);
2629}
2630
2631MediaPlayerService::BatteryTracker::BatteryTracker() {
2632 mBatteryAudio.refCount = 0;
2633 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2634 mBatteryAudio.deviceOn[i] = 0;
2635 mBatteryAudio.lastTime[i] = 0;
2636 mBatteryAudio.totalTime[i] = 0;
2637 }
2638 // speaker is on by default
2639 mBatteryAudio.deviceOn[SPEAKER] = 1;
2640
2641 // reset battery stats
2642 // if the mediaserver has crashed, battery stats could be left
2643 // in bad state, reset the state upon service start.
2644 BatteryNotifier::getInstance().noteResetVideo();
2645}
2646
2647void MediaPlayerService::BatteryTracker::addBatteryData(uint32_t params)
Gloria Wang7cf180c2011-02-19 18:37:57 -08002648{
2649 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002650
2651 int32_t time = systemTime() / 1000000L;
2652
2653 // change audio output devices. This notification comes from AudioFlinger
2654 if ((params & kBatteryDataSpeakerOn)
2655 || (params & kBatteryDataOtherAudioDeviceOn)) {
2656
2657 int deviceOn[NUM_AUDIO_DEVICES];
2658 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2659 deviceOn[i] = 0;
2660 }
2661
2662 if ((params & kBatteryDataSpeakerOn)
2663 && (params & kBatteryDataOtherAudioDeviceOn)) {
2664 deviceOn[SPEAKER_AND_OTHER] = 1;
2665 } else if (params & kBatteryDataSpeakerOn) {
2666 deviceOn[SPEAKER] = 1;
2667 } else {
2668 deviceOn[OTHER_AUDIO_DEVICE] = 1;
2669 }
2670
2671 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2672 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
2673
2674 if (mBatteryAudio.refCount > 0) { // if playing audio
2675 if (!deviceOn[i]) {
2676 mBatteryAudio.lastTime[i] += time;
2677 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2678 mBatteryAudio.lastTime[i] = 0;
2679 } else {
2680 mBatteryAudio.lastTime[i] = 0 - time;
2681 }
2682 }
2683
2684 mBatteryAudio.deviceOn[i] = deviceOn[i];
2685 }
2686 }
2687 return;
2688 }
2689
Marco Nelissenb7848f12014-12-04 08:57:56 -08002690 // an audio stream is started
Gloria Wang9ee159b2011-02-24 14:51:45 -08002691 if (params & kBatteryDataAudioFlingerStart) {
2692 // record the start time only if currently no other audio
2693 // is being played
2694 if (mBatteryAudio.refCount == 0) {
2695 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2696 if (mBatteryAudio.deviceOn[i]) {
2697 mBatteryAudio.lastTime[i] -= time;
2698 }
2699 }
2700 }
2701
2702 mBatteryAudio.refCount ++;
2703 return;
2704
2705 } else if (params & kBatteryDataAudioFlingerStop) {
2706 if (mBatteryAudio.refCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002707 ALOGW("Battery track warning: refCount is <= 0");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002708 return;
2709 }
2710
2711 // record the stop time only if currently this is the only
2712 // audio being played
2713 if (mBatteryAudio.refCount == 1) {
2714 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2715 if (mBatteryAudio.deviceOn[i]) {
2716 mBatteryAudio.lastTime[i] += time;
2717 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2718 mBatteryAudio.lastTime[i] = 0;
2719 }
2720 }
2721 }
2722
2723 mBatteryAudio.refCount --;
2724 return;
2725 }
2726
Andy Hung1afd0982016-11-08 16:13:44 -08002727 uid_t uid = IPCThreadState::self()->getCallingUid();
Gloria Wang7cf180c2011-02-19 18:37:57 -08002728 if (uid == AID_MEDIA) {
2729 return;
2730 }
2731 int index = mBatteryData.indexOfKey(uid);
Gloria Wang7cf180c2011-02-19 18:37:57 -08002732
2733 if (index < 0) { // create a new entry for this UID
2734 BatteryUsageInfo info;
2735 info.audioTotalTime = 0;
2736 info.videoTotalTime = 0;
2737 info.audioLastTime = 0;
2738 info.videoLastTime = 0;
2739 info.refCount = 0;
2740
Gloria Wang9ee159b2011-02-24 14:51:45 -08002741 if (mBatteryData.add(uid, info) == NO_MEMORY) {
Steve Block29357bc2012-01-06 19:20:56 +00002742 ALOGE("Battery track error: no memory for new app");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002743 return;
2744 }
Gloria Wang7cf180c2011-02-19 18:37:57 -08002745 }
2746
2747 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
2748
2749 if (params & kBatteryDataCodecStarted) {
2750 if (params & kBatteryDataTrackAudio) {
2751 info.audioLastTime -= time;
2752 info.refCount ++;
2753 }
2754 if (params & kBatteryDataTrackVideo) {
2755 info.videoLastTime -= time;
2756 info.refCount ++;
2757 }
2758 } else {
2759 if (info.refCount == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002760 ALOGW("Battery track warning: refCount is already 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002761 return;
2762 } else if (info.refCount < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00002763 ALOGE("Battery track error: refCount < 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002764 mBatteryData.removeItem(uid);
2765 return;
2766 }
2767
2768 if (params & kBatteryDataTrackAudio) {
2769 info.audioLastTime += time;
2770 info.refCount --;
2771 }
2772 if (params & kBatteryDataTrackVideo) {
2773 info.videoLastTime += time;
2774 info.refCount --;
2775 }
2776
2777 // no stream is being played by this UID
2778 if (info.refCount == 0) {
2779 info.audioTotalTime += info.audioLastTime;
2780 info.audioLastTime = 0;
2781 info.videoTotalTime += info.videoLastTime;
2782 info.videoLastTime = 0;
2783 }
2784 }
2785}
2786
Chong Zhange5b9b692017-05-11 11:44:56 -07002787status_t MediaPlayerService::BatteryTracker::pullBatteryData(Parcel* reply) {
Gloria Wang7cf180c2011-02-19 18:37:57 -08002788 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002789
2790 // audio output devices usage
2791 int32_t time = systemTime() / 1000000L; //in ms
2792 int32_t totalTime;
2793
2794 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2795 totalTime = mBatteryAudio.totalTime[i];
2796
2797 if (mBatteryAudio.deviceOn[i]
2798 && (mBatteryAudio.lastTime[i] != 0)) {
2799 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
2800 totalTime += tmpTime;
2801 }
2802
2803 reply->writeInt32(totalTime);
2804 // reset the total time
2805 mBatteryAudio.totalTime[i] = 0;
2806 }
2807
2808 // codec usage
Gloria Wang7cf180c2011-02-19 18:37:57 -08002809 BatteryUsageInfo info;
2810 int size = mBatteryData.size();
2811
2812 reply->writeInt32(size);
2813 int i = 0;
2814
2815 while (i < size) {
2816 info = mBatteryData.valueAt(i);
2817
2818 reply->writeInt32(mBatteryData.keyAt(i)); //UID
2819 reply->writeInt32(info.audioTotalTime);
2820 reply->writeInt32(info.videoTotalTime);
2821
2822 info.audioTotalTime = 0;
2823 info.videoTotalTime = 0;
2824
2825 // remove the UID entry where no stream is being played
2826 if (info.refCount <= 0) {
2827 mBatteryData.removeItemsAt(i);
2828 size --;
2829 i --;
2830 }
2831 i++;
2832 }
2833 return NO_ERROR;
2834}
nikoa64c8c72009-07-20 15:07:26 -07002835} // namespace android