blob: 11f29cb983f56f6acb15e14b977e2b70bca1a645 [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>
Lajos Molnar1381d4b2014-08-07 15:18:35 -070058#include <media/stagefright/MediaCodecList.h>
Eric Laurent9cb839a2011-09-27 09:48:56 -070059#include <media/stagefright/MediaErrors.h>
Marco Nelissen83b0fd92015-09-16 13:48:07 -070060#include <media/stagefright/Utils.h>
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +010061#include <media/stagefright/foundation/ADebug.h>
Marco Nelissenf09611f2015-02-13 14:12:42 -080062#include <media/stagefright/foundation/ALooperRoster.h>
Chong Zhang181fd9b2017-02-16 15:53:03 -080063#include <media/stagefright/SurfaceUtils.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070064#include <mediautils/BatteryNotifier.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080065
Andy Hung53541292016-04-13 16:48:51 -070066#include <memunreachable/memunreachable.h>
Dima Zavin64760242011-05-11 14:15:23 -070067#include <system/audio.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070068
Gloria Wang7cf180c2011-02-19 18:37:57 -080069#include <private/android_filesystem_config.h>
70
James Dong559bf282012-03-28 10:29:14 -070071#include "ActivityManager.h"
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080072#include "MediaRecorderClient.h"
73#include "MediaPlayerService.h"
74#include "MetadataRetrieverClient.h"
John Grossman44a7e422012-06-21 17:29:24 -070075#include "MediaPlayerFactory.h"
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080076
Nicolas Catania14d27472009-07-13 14:37:49 -070077#include "TestPlayerStub.h"
Andreas Huberf9334412010-12-15 15:17:42 -080078#include "nuplayer/NuPlayerDriver.h"
Andreas Huber20111aa2009-07-14 16:56:47 -070079
Andreas Huber20111aa2009-07-14 16:56:47 -070080#include <OMX.h>
Nicolas Catania14d27472009-07-13 14:37:49 -070081
Andreas Huber59451f82012-09-18 10:36:32 -070082#include "HDCP.h"
Andreas Huberb7319a72013-05-29 14:20:52 -070083#include "HTTPBase.h"
Andreas Huber35213f12012-08-29 11:41:50 -070084#include "RemoteDisplay.h"
Andreas Hubered3e3e02012-03-26 11:13:27 -070085
Wei Jia502c2f42017-07-13 17:47:56 -070086static const int kDumpLockRetries = 50;
87static const int kDumpLockSleepUs = 20000;
88
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070089namespace {
nikoa64c8c72009-07-20 15:07:26 -070090using android::media::Metadata;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070091using android::status_t;
92using android::OK;
93using android::BAD_VALUE;
94using android::NOT_ENOUGH_DATA;
95using android::Parcel;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070096
97// Max number of entries in the filter.
98const int kMaxFilterSize = 64; // I pulled that out of thin air.
99
Andy Hungff874dc2016-04-11 16:49:09 -0700100const float kMaxRequiredSpeed = 8.0f; // for PCM tracks allow up to 8x speedup.
101
nikoa64c8c72009-07-20 15:07:26 -0700102// FIXME: Move all the metadata related function in the Metadata.cpp
nikod608a812009-07-16 16:39:53 -0700103
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700104
105// Unmarshall a filter from a Parcel.
106// Filter format in a parcel:
107//
108// 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
109// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
110// | number of entries (n) |
111// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
112// | metadata type 1 |
113// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
114// | metadata type 2 |
115// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
116// ....
117// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
118// | metadata type n |
119// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
120//
121// @param p Parcel that should start with a filter.
122// @param[out] filter On exit contains the list of metadata type to be
123// filtered.
124// @param[out] status On exit contains the status code to be returned.
125// @return true if the parcel starts with a valid filter.
126bool unmarshallFilter(const Parcel& p,
nikoa64c8c72009-07-20 15:07:26 -0700127 Metadata::Filter *filter,
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700128 status_t *status)
129{
Nicolas Catania48290382009-07-10 13:53:06 -0700130 int32_t val;
131 if (p.readInt32(&val) != OK)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700132 {
Steve Block29357bc2012-01-06 19:20:56 +0000133 ALOGE("Failed to read filter's length");
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700134 *status = NOT_ENOUGH_DATA;
135 return false;
136 }
137
Nicolas Catania48290382009-07-10 13:53:06 -0700138 if( val > kMaxFilterSize || val < 0)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700139 {
Steve Block29357bc2012-01-06 19:20:56 +0000140 ALOGE("Invalid filter len %d", val);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700141 *status = BAD_VALUE;
142 return false;
143 }
144
Nicolas Catania48290382009-07-10 13:53:06 -0700145 const size_t num = val;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700146
147 filter->clear();
Nicolas Catania48290382009-07-10 13:53:06 -0700148 filter->setCapacity(num);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700149
nikoa64c8c72009-07-20 15:07:26 -0700150 size_t size = num * sizeof(Metadata::Type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700151
Nicolas Catania48290382009-07-10 13:53:06 -0700152
153 if (p.dataAvail() < size)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700154 {
Andy Hung833b4752016-04-04 17:15:48 -0700155 ALOGE("Filter too short expected %zu but got %zu", size, p.dataAvail());
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700156 *status = NOT_ENOUGH_DATA;
157 return false;
158 }
159
nikoa64c8c72009-07-20 15:07:26 -0700160 const Metadata::Type *data =
161 static_cast<const Metadata::Type*>(p.readInplace(size));
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700162
Nicolas Catania48290382009-07-10 13:53:06 -0700163 if (NULL == data)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700164 {
Steve Block29357bc2012-01-06 19:20:56 +0000165 ALOGE("Filter had no data");
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700166 *status = BAD_VALUE;
167 return false;
168 }
169
170 // TODO: The stl impl of vector would be more efficient here
171 // because it degenerates into a memcpy on pod types. Try to
172 // replace later or use stl::set.
Nicolas Catania48290382009-07-10 13:53:06 -0700173 for (size_t i = 0; i < num; ++i)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700174 {
Nicolas Catania48290382009-07-10 13:53:06 -0700175 filter->add(*data);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700176 ++data;
177 }
178 *status = OK;
179 return true;
180}
181
Nicolas Catania48290382009-07-10 13:53:06 -0700182// @param filter Of metadata type.
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700183// @param val To be searched.
184// @return true if a match was found.
nikoa64c8c72009-07-20 15:07:26 -0700185bool findMetadata(const Metadata::Filter& filter, const int32_t val)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700186{
187 // Deal with empty and ANY right away
188 if (filter.isEmpty()) return false;
nikoa64c8c72009-07-20 15:07:26 -0700189 if (filter[0] == Metadata::kAny) return true;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700190
Nicolas Catania48290382009-07-10 13:53:06 -0700191 return filter.indexOf(val) >= 0;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700192}
193
194} // anonymous namespace
195
196
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700197namespace {
198using android::Parcel;
199using android::String16;
200
201// marshalling tag indicating flattened utf16 tags
202// keep in sync with frameworks/base/media/java/android/media/AudioAttributes.java
203const int32_t kAudioAttributesMarshallTagFlattenTags = 1;
204
205// Audio attributes format in a parcel:
206//
207// 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
208// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
209// | usage |
210// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
211// | content_type |
212// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Hyejin Kim4f418f92014-09-05 15:50:03 +0900213// | source |
214// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700215// | flags |
216// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
217// | kAudioAttributesMarshallTagFlattenTags | // ignore tags if not found
218// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
219// | flattened tags in UTF16 |
220// | ... |
221// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
222//
223// @param p Parcel that contains audio attributes.
224// @param[out] attributes On exit points to an initialized audio_attributes_t structure
225// @param[out] status On exit contains the status code to be returned.
226void unmarshallAudioAttributes(const Parcel& parcel, audio_attributes_t *attributes)
227{
228 attributes->usage = (audio_usage_t) parcel.readInt32();
229 attributes->content_type = (audio_content_type_t) parcel.readInt32();
Hyejin Kim4f418f92014-09-05 15:50:03 +0900230 attributes->source = (audio_source_t) parcel.readInt32();
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700231 attributes->flags = (audio_flags_mask_t) parcel.readInt32();
232 const bool hasFlattenedTag = (parcel.readInt32() == kAudioAttributesMarshallTagFlattenTags);
233 if (hasFlattenedTag) {
234 // the tags are UTF16, convert to UTF8
235 String16 tags = parcel.readString16();
236 ssize_t realTagSize = utf16_to_utf8_length(tags.string(), tags.size());
237 if (realTagSize <= 0) {
238 strcpy(attributes->tags, "");
239 } else {
240 // copy the flattened string into the attributes as the destination for the conversion:
241 // copying array size -1, array for tags was calloc'd, no need to NULL-terminate it
242 size_t tagSize = realTagSize > AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 ?
243 AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 : realTagSize;
Sergio Giro1d3f4272016-06-28 18:24:52 +0100244 utf16_to_utf8(tags.string(), tagSize, attributes->tags,
245 sizeof(attributes->tags) / sizeof(attributes->tags[0]));
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700246 }
247 } else {
248 ALOGE("unmarshallAudioAttributes() received unflattened tags, ignoring tag values");
249 strcpy(attributes->tags, "");
250 }
251}
252} // anonymous namespace
253
254
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800255namespace android {
256
Marco Nelissenf09611f2015-02-13 14:12:42 -0800257extern ALooperRoster gLooperRoster;
258
259
Dave Burked681bbb2011-08-30 14:39:17 +0100260static bool checkPermission(const char* permissionString) {
Dave Burked681bbb2011-08-30 14:39:17 +0100261 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
262 bool ok = checkCallingPermission(String16(permissionString));
Steve Block29357bc2012-01-06 19:20:56 +0000263 if (!ok) ALOGE("Request requires %s", permissionString);
Dave Burked681bbb2011-08-30 14:39:17 +0100264 return ok;
265}
266
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800267// 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 -0800268/* static */ int MediaPlayerService::AudioOutput::mMinBufferCount = 4;
269/* static */ bool MediaPlayerService::AudioOutput::mIsOnEmulator = false;
270
271void MediaPlayerService::instantiate() {
272 defaultServiceManager()->addService(
273 String16("media.player"), new MediaPlayerService());
274}
275
276MediaPlayerService::MediaPlayerService()
277{
Steve Block3856b092011-10-20 11:56:00 +0100278 ALOGV("MediaPlayerService created");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800279 mNextConnId = 1;
Gloria Wang9ee159b2011-02-24 14:51:45 -0800280
John Grossman44a7e422012-06-21 17:29:24 -0700281 MediaPlayerFactory::registerBuiltinFactories();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800282}
283
284MediaPlayerService::~MediaPlayerService()
285{
Steve Block3856b092011-10-20 11:56:00 +0100286 ALOGV("MediaPlayerService destroyed");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800287}
288
Svet Ganovbe71aa22015-04-28 12:06:02 -0700289sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(const String16 &opPackageName)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800290{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800291 pid_t pid = IPCThreadState::self()->getCallingPid();
Svet Ganovbe71aa22015-04-28 12:06:02 -0700292 sp<MediaRecorderClient> recorder = new MediaRecorderClient(this, pid, opPackageName);
Gloria Wangdac6a312009-10-29 15:46:37 -0700293 wp<MediaRecorderClient> w = recorder;
294 Mutex::Autolock lock(mLock);
295 mMediaRecorderClients.add(w);
Steve Block3856b092011-10-20 11:56:00 +0100296 ALOGV("Create new media recorder client from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800297 return recorder;
298}
299
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -0700300void MediaPlayerService::removeMediaRecorderClient(const wp<MediaRecorderClient>& client)
Gloria Wangdac6a312009-10-29 15:46:37 -0700301{
302 Mutex::Autolock lock(mLock);
303 mMediaRecorderClients.remove(client);
Steve Block3856b092011-10-20 11:56:00 +0100304 ALOGV("Delete media recorder client");
Gloria Wangdac6a312009-10-29 15:46:37 -0700305}
306
Glenn Kastenf37971f2012-02-03 11:06:53 -0800307sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800308{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800309 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800310 sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
Steve Block3856b092011-10-20 11:56:00 +0100311 ALOGV("Create new media retriever from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800312 return retriever;
313}
314
Glenn Kastenf37971f2012-02-03 11:06:53 -0800315sp<IMediaPlayer> MediaPlayerService::create(const sp<IMediaPlayerClient>& client,
Glenn Kastend848eb42016-03-08 13:42:11 -0800316 audio_session_t audioSessionId)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800317{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800318 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800319 int32_t connId = android_atomic_inc(&mNextConnId);
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700320
321 sp<Client> c = new Client(
322 this, pid, connId, client, audioSessionId,
323 IPCThreadState::self()->getCallingUid());
324
Steve Block3856b092011-10-20 11:56:00 +0100325 ALOGV("Create new client(%d) from pid %d, uid %d, ", connId, pid,
Dave Burked681bbb2011-08-30 14:39:17 +0100326 IPCThreadState::self()->getCallingUid());
327
328 wp<Client> w = c;
329 {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800330 Mutex::Autolock lock(mLock);
331 mClients.add(w);
332 }
Andreas Hubere2b10282010-11-23 11:41:34 -0800333 return c;
334}
335
Lajos Molnar1381d4b2014-08-07 15:18:35 -0700336sp<IMediaCodecList> MediaPlayerService::getCodecList() const {
337 return MediaCodecList::getLocalInstance();
338}
339
Marco Nelissen260e56c2016-01-28 21:41:25 +0000340sp<IOMX> MediaPlayerService::getOMX() {
Marco Nelissen1900e772016-02-02 16:12:16 -0800341 ALOGI("MediaPlayerService::getOMX");
Marco Nelissen260e56c2016-01-28 21:41:25 +0000342 Mutex::Autolock autoLock(mLock);
343
344 if (mOMX.get() == NULL) {
345 mOMX = new OMX;
346 }
347
348 return mOMX;
349}
350
Andreas Huber279dcd82013-01-30 10:41:25 -0800351sp<IHDCP> MediaPlayerService::makeHDCP(bool createEncryptionModule) {
352 return new HDCP(createEncryptionModule);
Andreas Huber59451f82012-09-18 10:36:32 -0700353}
354
Jeff Brown2013a542012-09-04 21:38:42 -0700355sp<IRemoteDisplay> MediaPlayerService::listenForRemoteDisplay(
Svet Ganovbe71aa22015-04-28 12:06:02 -0700356 const String16 &opPackageName,
Jeff Brown2013a542012-09-04 21:38:42 -0700357 const sp<IRemoteDisplayClient>& client, const String8& iface) {
Jeff Brownaba33d52012-09-07 17:38:58 -0700358 if (!checkPermission("android.permission.CONTROL_WIFI_DISPLAY")) {
359 return NULL;
360 }
361
Svet Ganovbe71aa22015-04-28 12:06:02 -0700362 return new RemoteDisplay(opPackageName, client, iface.string());
Jeff Brown2013a542012-09-04 21:38:42 -0700363}
364
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800365status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
366{
367 const size_t SIZE = 256;
368 char buffer[SIZE];
369 String8 result;
370
371 result.append(" AudioOutput\n");
372 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n",
373 mStreamType, mLeftVolume, mRightVolume);
374 result.append(buffer);
375 snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n",
Eric Laurentdb354e52012-03-05 17:27:11 -0800376 mMsecsPerFrame, (mTrack != 0) ? mTrack->latency() : -1);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800377 result.append(buffer);
Eric Laurent2beeb502010-07-16 07:43:46 -0700378 snprintf(buffer, 255, " aux effect id(%d), send level (%f)\n",
379 mAuxEffectId, mSendLevel);
380 result.append(buffer);
381
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800382 ::write(fd, result.string(), result.size());
383 if (mTrack != 0) {
384 mTrack->dump(fd, args);
385 }
386 return NO_ERROR;
387}
388
Lajos Molnar6d339f12015-04-17 16:15:53 -0700389status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800390{
391 const size_t SIZE = 256;
392 char buffer[SIZE];
393 String8 result;
394 result.append(" Client\n");
395 snprintf(buffer, 255, " pid(%d), connId(%d), status(%d), looping(%s)\n",
396 mPid, mConnId, mStatus, mLoop?"true": "false");
397 result.append(buffer);
Wei Jia502c2f42017-07-13 17:47:56 -0700398
399 sp<MediaPlayerBase> p;
400 sp<AudioOutput> audioOutput;
401 bool locked = false;
402 for (int i = 0; i < kDumpLockRetries; ++i) {
403 if (mLock.tryLock() == NO_ERROR) {
404 locked = true;
405 break;
406 }
407 usleep(kDumpLockSleepUs);
Andreas Hubera0b1d4b2011-06-07 15:52:25 -0700408 }
Wei Jia502c2f42017-07-13 17:47:56 -0700409
410 if (locked) {
411 p = mPlayer;
412 audioOutput = mAudioOutput;
413 mLock.unlock();
414 } else {
415 result.append(" lock is taken, no dump from player and audio output\n");
416 }
417 write(fd, result.string(), result.size());
418
419 if (p != NULL) {
420 p->dump(fd, args);
421 }
422 if (audioOutput != 0) {
423 audioOutput->dump(fd, args);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800424 }
425 write(fd, "\n", 1);
426 return NO_ERROR;
427}
428
Marco Nelissenf09611f2015-02-13 14:12:42 -0800429/**
430 * The only arguments this understands right now are -c, -von and -voff,
431 * which are parsed by ALooperRoster::dump()
432 */
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800433status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
434{
435 const size_t SIZE = 256;
436 char buffer[SIZE];
437 String8 result;
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530438 SortedVector< sp<Client> > clients; //to serialise the mutex unlock & client destruction.
439 SortedVector< sp<MediaRecorderClient> > mediaRecorderClients;
440
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800441 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
442 snprintf(buffer, SIZE, "Permission Denial: "
443 "can't dump MediaPlayerService from pid=%d, uid=%d\n",
444 IPCThreadState::self()->getCallingPid(),
445 IPCThreadState::self()->getCallingUid());
446 result.append(buffer);
447 } else {
448 Mutex::Autolock lock(mLock);
449 for (int i = 0, n = mClients.size(); i < n; ++i) {
450 sp<Client> c = mClients[i].promote();
451 if (c != 0) c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530452 clients.add(c);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800453 }
James Dongb9141222010-07-08 11:16:11 -0700454 if (mMediaRecorderClients.size() == 0) {
455 result.append(" No media recorder client\n\n");
456 } else {
457 for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
458 sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
James Donge579e282011-10-18 22:29:20 -0700459 if (c != 0) {
460 snprintf(buffer, 255, " MediaRecorderClient pid(%d)\n", c->mPid);
461 result.append(buffer);
462 write(fd, result.string(), result.size());
463 result = "\n";
464 c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530465 mediaRecorderClients.add(c);
James Donge579e282011-10-18 22:29:20 -0700466 }
James Dongb9141222010-07-08 11:16:11 -0700467 }
Gloria Wangdac6a312009-10-29 15:46:37 -0700468 }
469
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800470 result.append(" Files opened and/or mapped:\n");
Marco Nelissenf09611f2015-02-13 14:12:42 -0800471 snprintf(buffer, SIZE, "/proc/%d/maps", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800472 FILE *f = fopen(buffer, "r");
473 if (f) {
474 while (!feof(f)) {
475 fgets(buffer, SIZE, f);
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700476 if (strstr(buffer, " /storage/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800477 strstr(buffer, " /system/sounds/") ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700478 strstr(buffer, " /data/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800479 strstr(buffer, " /system/media/")) {
480 result.append(" ");
481 result.append(buffer);
482 }
483 }
484 fclose(f);
485 } else {
486 result.append("couldn't open ");
487 result.append(buffer);
488 result.append("\n");
489 }
490
Marco Nelissenf09611f2015-02-13 14:12:42 -0800491 snprintf(buffer, SIZE, "/proc/%d/fd", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800492 DIR *d = opendir(buffer);
493 if (d) {
494 struct dirent *ent;
495 while((ent = readdir(d)) != NULL) {
496 if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
Marco Nelissenf09611f2015-02-13 14:12:42 -0800497 snprintf(buffer, SIZE, "/proc/%d/fd/%s", getpid(), ent->d_name);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800498 struct stat s;
499 if (lstat(buffer, &s) == 0) {
500 if ((s.st_mode & S_IFMT) == S_IFLNK) {
501 char linkto[256];
502 int len = readlink(buffer, linkto, sizeof(linkto));
503 if(len > 0) {
504 if(len > 255) {
505 linkto[252] = '.';
506 linkto[253] = '.';
507 linkto[254] = '.';
508 linkto[255] = 0;
509 } else {
510 linkto[len] = 0;
511 }
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700512 if (strstr(linkto, "/storage/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800513 strstr(linkto, "/system/sounds/") == linkto ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700514 strstr(linkto, "/data/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800515 strstr(linkto, "/system/media/") == linkto) {
516 result.append(" ");
517 result.append(buffer);
518 result.append(" -> ");
519 result.append(linkto);
520 result.append("\n");
521 }
522 }
523 } else {
524 result.append(" unexpected type for ");
525 result.append(buffer);
526 result.append("\n");
527 }
528 }
529 }
530 }
531 closedir(d);
532 } else {
533 result.append("couldn't open ");
534 result.append(buffer);
535 result.append("\n");
536 }
537
Marco Nelissenf09611f2015-02-13 14:12:42 -0800538 gLooperRoster.dump(fd, args);
539
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800540 bool dumpMem = false;
Andy Hung53541292016-04-13 16:48:51 -0700541 bool unreachableMemory = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800542 for (size_t i = 0; i < args.size(); i++) {
543 if (args[i] == String16("-m")) {
544 dumpMem = true;
Andy Hung53541292016-04-13 16:48:51 -0700545 } else if (args[i] == String16("--unreachable")) {
546 unreachableMemory = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800547 }
548 }
549 if (dumpMem) {
Andy Hung07b745e2016-05-23 16:21:07 -0700550 result.append("\nDumping memory:\n");
551 std::string s = dumpMemoryAddresses(100 /* limit */);
552 result.append(s.c_str(), s.size());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800553 }
Andy Hung53541292016-04-13 16:48:51 -0700554 if (unreachableMemory) {
555 result.append("\nDumping unreachable memory:\n");
556 // TODO - should limit be an argument parameter?
557 std::string s = GetUnreachableMemoryString(true /* contents */, 10000 /* limit */);
558 result.append(s.c_str(), s.size());
559 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800560 }
561 write(fd, result.string(), result.size());
562 return NO_ERROR;
563}
564
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -0700565void MediaPlayerService::removeClient(const wp<Client>& client)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800566{
567 Mutex::Autolock lock(mLock);
568 mClients.remove(client);
569}
570
Robert Shihee0a0e32016-08-16 16:50:54 -0700571bool MediaPlayerService::hasClient(wp<Client> client)
572{
573 Mutex::Autolock lock(mLock);
574 return mClients.indexOf(client) != NAME_NOT_FOUND;
575}
576
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700577MediaPlayerService::Client::Client(
578 const sp<MediaPlayerService>& service, pid_t pid,
579 int32_t connId, const sp<IMediaPlayerClient>& client,
Glenn Kastend848eb42016-03-08 13:42:11 -0800580 audio_session_t audioSessionId, uid_t uid)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800581{
Steve Block3856b092011-10-20 11:56:00 +0100582 ALOGV("Client(%d) constructor", connId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800583 mPid = pid;
584 mConnId = connId;
585 mService = service;
586 mClient = client;
587 mLoop = false;
588 mStatus = NO_INIT;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700589 mAudioSessionId = audioSessionId;
Andy Hung1afd0982016-11-08 16:13:44 -0800590 mUid = uid;
John Grossmanc795b642012-02-22 15:38:35 -0800591 mRetransmitEndpointValid = false;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700592 mAudioAttributes = NULL;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700593
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800594#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000595 ALOGD("create Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800596 mAntagonizer = new Antagonizer(notify, this);
597#endif
598}
599
600MediaPlayerService::Client::~Client()
601{
Steve Block3856b092011-10-20 11:56:00 +0100602 ALOGV("Client(%d) destructor pid = %d", mConnId, mPid);
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700603 mAudioOutput.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800604 wp<Client> client(this);
605 disconnect();
606 mService->removeClient(client);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700607 if (mAudioAttributes != NULL) {
608 free(mAudioAttributes);
609 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700610 clearDeathNotifiers_l();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800611}
612
613void MediaPlayerService::Client::disconnect()
614{
Steve Block3856b092011-10-20 11:56:00 +0100615 ALOGV("disconnect(%d) from pid %d", mConnId, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800616 // grab local reference and clear main reference to prevent future
617 // access to object
618 sp<MediaPlayerBase> p;
619 {
620 Mutex::Autolock l(mLock);
621 p = mPlayer;
beanzdcfefde2012-11-05 09:51:43 +0800622 mClient.clear();
Wei Jia502c2f42017-07-13 17:47:56 -0700623 mPlayer.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800624 }
Andreas Huber20111aa2009-07-14 16:56:47 -0700625
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800626 // clear the notification to prevent callbacks to dead client
627 // and reset the player. We assume the player will serialize
628 // access to itself if necessary.
629 if (p != 0) {
630 p->setNotifyCallback(0, 0);
631#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000632 ALOGD("kill Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800633 mAntagonizer->kill();
634#endif
635 p->reset();
636 }
637
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700638 {
639 Mutex::Autolock l(mLock);
640 disconnectNativeWindow_l();
641 }
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700642
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800643 IPCThreadState::self()->flushCommands();
644}
645
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800646sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
647{
648 // determine if we have the right player type
Wei Jia502c2f42017-07-13 17:47:56 -0700649 sp<MediaPlayerBase> p = getPlayer();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800650 if ((p != NULL) && (p->playerType() != playerType)) {
Steve Block3856b092011-10-20 11:56:00 +0100651 ALOGV("delete player");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800652 p.clear();
653 }
654 if (p == NULL) {
Ronghua Wu68845c12015-07-21 09:50:48 -0700655 p = MediaPlayerFactory::createPlayer(playerType, this, notify, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800656 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700657
Jason Simmonsdb29e522011-08-12 13:46:55 -0700658 if (p != NULL) {
Andy Hung1afd0982016-11-08 16:13:44 -0800659 p->setUID(mUid);
Jason Simmonsdb29e522011-08-12 13:46:55 -0700660 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700661
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800662 return p;
663}
664
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700665MediaPlayerService::Client::ServiceDeathNotifier::ServiceDeathNotifier(
666 const sp<IBinder>& service,
667 const sp<MediaPlayerBase>& listener,
668 int which) {
669 mService = service;
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800670 mOmx = nullptr;
671 mListener = listener;
672 mWhich = which;
673}
674
675MediaPlayerService::Client::ServiceDeathNotifier::ServiceDeathNotifier(
676 const sp<IOmx>& omx,
677 const sp<MediaPlayerBase>& listener,
678 int which) {
679 mService = nullptr;
680 mOmx = omx;
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700681 mListener = listener;
682 mWhich = which;
683}
684
685MediaPlayerService::Client::ServiceDeathNotifier::~ServiceDeathNotifier() {
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700686}
687
688void MediaPlayerService::Client::ServiceDeathNotifier::binderDied(const wp<IBinder>& /*who*/) {
689 sp<MediaPlayerBase> listener = mListener.promote();
690 if (listener != NULL) {
691 listener->sendEvent(MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED, mWhich);
692 } else {
693 ALOGW("listener for process %d death is gone", mWhich);
694 }
695}
696
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800697void MediaPlayerService::Client::ServiceDeathNotifier::serviceDied(
698 uint64_t /* cookie */,
699 const wp<::android::hidl::base::V1_0::IBase>& /* who */) {
700 sp<MediaPlayerBase> listener = mListener.promote();
701 if (listener != NULL) {
702 listener->sendEvent(MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED, mWhich);
703 } else {
704 ALOGW("listener for process %d death is gone", mWhich);
705 }
706}
707
708void MediaPlayerService::Client::ServiceDeathNotifier::unlinkToDeath() {
709 if (mService != nullptr) {
710 mService->unlinkToDeath(this);
711 mService = nullptr;
712 } else if (mOmx != nullptr) {
713 mOmx->unlinkToDeath(this);
714 mOmx = nullptr;
715 }
716}
717
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700718void MediaPlayerService::Client::clearDeathNotifiers_l() {
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800719 if (mExtractorDeathListener != nullptr) {
720 mExtractorDeathListener->unlinkToDeath();
721 mExtractorDeathListener = nullptr;
722 }
723 if (mCodecDeathListener != nullptr) {
724 mCodecDeathListener->unlinkToDeath();
725 mCodecDeathListener = nullptr;
726 }
727}
728
John Grossmanc795b642012-02-22 15:38:35 -0800729sp<MediaPlayerBase> MediaPlayerService::Client::setDataSource_pre(
730 player_type playerType)
731{
732 ALOGV("player type = %d", playerType);
733
734 // create the right type of player
735 sp<MediaPlayerBase> p = createPlayer(playerType);
736 if (p == NULL) {
737 return p;
738 }
739
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700740 sp<IServiceManager> sm = defaultServiceManager();
741 sp<IBinder> binder = sm->getService(String16("media.extractor"));
Marco Nelissen1b5a7ee2016-09-30 13:54:30 -0700742 if (binder == NULL) {
743 ALOGE("extractor service not available");
744 return NULL;
745 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700746 sp<ServiceDeathNotifier> extractorDeathListener =
747 new ServiceDeathNotifier(binder, p, MEDIAEXTRACTOR_PROCESS_DEATH);
748 binder->linkToDeath(extractorDeathListener);
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700749
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700750 sp<ServiceDeathNotifier> codecDeathListener;
Pawin Vongmasad4e9ca42017-03-29 17:24:56 -0700751 if (property_get_bool("persist.media.treble_omx", true)) {
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800752 // Treble IOmx
753 sp<IOmx> omx = IOmx::getService();
754 if (omx == nullptr) {
755 ALOGE("Treble IOmx not available");
756 return NULL;
757 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700758 codecDeathListener = new ServiceDeathNotifier(omx, p, MEDIACODEC_PROCESS_DEATH);
759 omx->linkToDeath(codecDeathListener, 0);
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800760 } else {
761 // Legacy IOMX
762 binder = sm->getService(String16("media.codec"));
763 if (binder == NULL) {
764 ALOGE("codec service not available");
765 return NULL;
766 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700767 codecDeathListener = new ServiceDeathNotifier(binder, p, MEDIACODEC_PROCESS_DEATH);
768 binder->linkToDeath(codecDeathListener);
Marco Nelissen1b5a7ee2016-09-30 13:54:30 -0700769 }
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700770
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700771 Mutex::Autolock lock(mLock);
772
773 clearDeathNotifiers_l();
774 mExtractorDeathListener = extractorDeathListener;
775 mCodecDeathListener = codecDeathListener;
776
John Grossmanc795b642012-02-22 15:38:35 -0800777 if (!p->hardwareOutput()) {
Marco Nelissend457c972014-02-11 08:47:07 -0800778 mAudioOutput = new AudioOutput(mAudioSessionId, IPCThreadState::self()->getCallingUid(),
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700779 mPid, mAudioAttributes);
John Grossmanc795b642012-02-22 15:38:35 -0800780 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
781 }
782
783 return p;
784}
785
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700786status_t MediaPlayerService::Client::setDataSource_post(
John Grossmanc795b642012-02-22 15:38:35 -0800787 const sp<MediaPlayerBase>& p,
788 status_t status)
789{
790 ALOGV(" setDataSource");
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700791 if (status != OK) {
792 ALOGE(" error: %d", status);
793 return status;
John Grossmanc795b642012-02-22 15:38:35 -0800794 }
795
796 // Set the re-transmission endpoint if one was chosen.
797 if (mRetransmitEndpointValid) {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700798 status = p->setRetransmitEndpoint(&mRetransmitEndpoint);
799 if (status != NO_ERROR) {
800 ALOGE("setRetransmitEndpoint error: %d", status);
John Grossmanc795b642012-02-22 15:38:35 -0800801 }
802 }
803
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700804 if (status == OK) {
805 Mutex::Autolock lock(mLock);
John Grossmanc795b642012-02-22 15:38:35 -0800806 mPlayer = p;
807 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700808 return status;
John Grossmanc795b642012-02-22 15:38:35 -0800809}
810
Andreas Huber2db84552010-01-28 11:19:57 -0800811status_t MediaPlayerService::Client::setDataSource(
Andreas Huber1b86fe02014-01-29 11:13:26 -0800812 const sp<IMediaHTTPService> &httpService,
813 const char *url,
814 const KeyedVector<String8, String8> *headers)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800815{
Steve Block3856b092011-10-20 11:56:00 +0100816 ALOGV("setDataSource(%s)", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800817 if (url == NULL)
818 return UNKNOWN_ERROR;
819
Dave Burked681bbb2011-08-30 14:39:17 +0100820 if ((strncmp(url, "http://", 7) == 0) ||
821 (strncmp(url, "https://", 8) == 0) ||
822 (strncmp(url, "rtsp://", 7) == 0)) {
823 if (!checkPermission("android.permission.INTERNET")) {
824 return PERMISSION_DENIED;
825 }
826 }
827
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800828 if (strncmp(url, "content://", 10) == 0) {
829 // get a filedescriptor for the content Uri and
830 // pass it to the setDataSource(fd) method
831
832 String16 url16(url);
833 int fd = android::openContentProviderFile(url16);
834 if (fd < 0)
835 {
Steve Block29357bc2012-01-06 19:20:56 +0000836 ALOGE("Couldn't open fd for %s", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800837 return UNKNOWN_ERROR;
838 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700839 status_t status = setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800840 close(fd);
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700841 return mStatus = status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800842 } else {
John Grossman44a7e422012-06-21 17:29:24 -0700843 player_type playerType = MediaPlayerFactory::getPlayerType(this, url);
John Grossmanc795b642012-02-22 15:38:35 -0800844 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
845 if (p == NULL) {
846 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800847 }
848
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700849 return mStatus =
850 setDataSource_post(
851 p, p->setDataSource(httpService, url, headers));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800852 }
853}
854
855status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
856{
Marco Nelissen83b0fd92015-09-16 13:48:07 -0700857 ALOGV("setDataSource fd=%d (%s), offset=%lld, length=%lld",
858 fd, nameForFd(fd).c_str(), (long long) offset, (long long) length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800859 struct stat sb;
860 int ret = fstat(fd, &sb);
861 if (ret != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000862 ALOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800863 return UNKNOWN_ERROR;
864 }
865
Andy Hung833b4752016-04-04 17:15:48 -0700866 ALOGV("st_dev = %llu", static_cast<unsigned long long>(sb.st_dev));
Steve Block3856b092011-10-20 11:56:00 +0100867 ALOGV("st_mode = %u", sb.st_mode);
Mark Salyzyn77342f72014-06-18 16:31:32 -0700868 ALOGV("st_uid = %lu", static_cast<unsigned long>(sb.st_uid));
869 ALOGV("st_gid = %lu", static_cast<unsigned long>(sb.st_gid));
Andy Hung833b4752016-04-04 17:15:48 -0700870 ALOGV("st_size = %llu", static_cast<unsigned long long>(sb.st_size));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800871
872 if (offset >= sb.st_size) {
Steve Block29357bc2012-01-06 19:20:56 +0000873 ALOGE("offset error");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800874 return UNKNOWN_ERROR;
875 }
876 if (offset + length > sb.st_size) {
877 length = sb.st_size - offset;
Andy Hung833b4752016-04-04 17:15:48 -0700878 ALOGV("calculated length = %lld", (long long)length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800879 }
880
John Grossman44a7e422012-06-21 17:29:24 -0700881 player_type playerType = MediaPlayerFactory::getPlayerType(this,
882 fd,
883 offset,
884 length);
John Grossmanc795b642012-02-22 15:38:35 -0800885 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
886 if (p == NULL) {
887 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800888 }
889
890 // now set data source
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700891 return mStatus = setDataSource_post(p, p->setDataSource(fd, offset, length));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800892}
893
Andreas Hubere2b10282010-11-23 11:41:34 -0800894status_t MediaPlayerService::Client::setDataSource(
895 const sp<IStreamSource> &source) {
896 // create the right type of player
John Grossman44a7e422012-06-21 17:29:24 -0700897 player_type playerType = MediaPlayerFactory::getPlayerType(this, source);
John Grossmanc795b642012-02-22 15:38:35 -0800898 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
Andreas Hubere2b10282010-11-23 11:41:34 -0800899 if (p == NULL) {
900 return NO_INIT;
901 }
902
Andreas Hubere2b10282010-11-23 11:41:34 -0800903 // now set data source
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700904 return mStatus = setDataSource_post(p, p->setDataSource(source));
Andreas Hubere2b10282010-11-23 11:41:34 -0800905}
906
Chris Watkins99f31602015-03-20 13:06:33 -0700907status_t MediaPlayerService::Client::setDataSource(
908 const sp<IDataSource> &source) {
909 sp<DataSource> dataSource = DataSource::CreateFromIDataSource(source);
910 player_type playerType = MediaPlayerFactory::getPlayerType(this, dataSource);
911 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
912 if (p == NULL) {
913 return NO_INIT;
914 }
915 // now set data source
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700916 return mStatus = setDataSource_post(p, p->setDataSource(dataSource));
Chris Watkins99f31602015-03-20 13:06:33 -0700917}
918
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700919void MediaPlayerService::Client::disconnectNativeWindow_l() {
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700920 if (mConnectedWindow != NULL) {
Chong Zhang181fd9b2017-02-16 15:53:03 -0800921 status_t err = nativeWindowDisconnect(
922 mConnectedWindow.get(), "disconnectNativeWindow");
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700923
924 if (err != OK) {
Chong Zhang181fd9b2017-02-16 15:53:03 -0800925 ALOGW("nativeWindowDisconnect returned an error: %s (%d)",
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700926 strerror(-err), err);
927 }
928 }
929 mConnectedWindow.clear();
930}
931
Glenn Kasten11731182011-02-08 17:26:17 -0800932status_t MediaPlayerService::Client::setVideoSurfaceTexture(
Andy McFadden484566c2012-12-18 09:46:54 -0800933 const sp<IGraphicBufferProducer>& bufferProducer)
Glenn Kasten11731182011-02-08 17:26:17 -0800934{
Andy McFadden484566c2012-12-18 09:46:54 -0800935 ALOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, bufferProducer.get());
Glenn Kasten11731182011-02-08 17:26:17 -0800936 sp<MediaPlayerBase> p = getPlayer();
937 if (p == 0) return UNKNOWN_ERROR;
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700938
Marco Nelissenf8880202014-11-14 07:58:25 -0800939 sp<IBinder> binder(IInterface::asBinder(bufferProducer));
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700940 if (mConnectedWindowBinder == binder) {
941 return OK;
942 }
943
944 sp<ANativeWindow> anw;
Andy McFadden484566c2012-12-18 09:46:54 -0800945 if (bufferProducer != NULL) {
Marco Nelissenee08f7e2013-09-16 13:30:01 -0700946 anw = new Surface(bufferProducer, true /* controlledByApp */);
Chong Zhang181fd9b2017-02-16 15:53:03 -0800947 status_t err = nativeWindowConnect(anw.get(), "setVideoSurfaceTexture");
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700948
949 if (err != OK) {
Steve Block29357bc2012-01-06 19:20:56 +0000950 ALOGE("setVideoSurfaceTexture failed: %d", err);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700951 // Note that we must do the reset before disconnecting from the ANW.
952 // Otherwise queue/dequeue calls could be made on the disconnected
953 // ANW, which may result in errors.
954 reset();
955
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700956 Mutex::Autolock lock(mLock);
957 disconnectNativeWindow_l();
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700958
959 return err;
960 }
961 }
962
Andy McFadden484566c2012-12-18 09:46:54 -0800963 // Note that we must set the player's new GraphicBufferProducer before
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700964 // disconnecting the old one. Otherwise queue/dequeue calls could be made
965 // on the disconnected ANW, which may result in errors.
Andy McFadden484566c2012-12-18 09:46:54 -0800966 status_t err = p->setVideoSurfaceTexture(bufferProducer);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700967
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700968 mLock.lock();
969 disconnectNativeWindow_l();
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700970
971 if (err == OK) {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700972 mConnectedWindow = anw;
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700973 mConnectedWindowBinder = binder;
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700974 mLock.unlock();
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700975 } else {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700976 mLock.unlock();
977 status_t err = nativeWindowDisconnect(
978 anw.get(), "disconnectNativeWindow");
979
980 if (err != OK) {
981 ALOGW("nativeWindowDisconnect returned an error: %s (%d)",
982 strerror(-err), err);
983 }
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700984 }
985
986 return err;
Glenn Kasten11731182011-02-08 17:26:17 -0800987}
988
Nicolas Catania1d187f12009-05-12 23:25:55 -0700989status_t MediaPlayerService::Client::invoke(const Parcel& request,
990 Parcel *reply)
991{
992 sp<MediaPlayerBase> p = getPlayer();
993 if (p == NULL) return UNKNOWN_ERROR;
994 return p->invoke(request, reply);
995}
996
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700997// This call doesn't need to access the native player.
998status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
999{
1000 status_t status;
nikoa64c8c72009-07-20 15:07:26 -07001001 media::Metadata::Filter allow, drop;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001002
Nicolas Catania48290382009-07-10 13:53:06 -07001003 if (unmarshallFilter(filter, &allow, &status) &&
1004 unmarshallFilter(filter, &drop, &status)) {
1005 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001006
1007 mMetadataAllow = allow;
1008 mMetadataDrop = drop;
1009 }
1010 return status;
1011}
1012
Nicolas Catania48290382009-07-10 13:53:06 -07001013status_t MediaPlayerService::Client::getMetadata(
Mark Salyzyn77342f72014-06-18 16:31:32 -07001014 bool update_only, bool /*apply_filter*/, Parcel *reply)
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001015{
nikoa64c8c72009-07-20 15:07:26 -07001016 sp<MediaPlayerBase> player = getPlayer();
1017 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania48290382009-07-10 13:53:06 -07001018
nikod608a812009-07-16 16:39:53 -07001019 status_t status;
1020 // Placeholder for the return code, updated by the caller.
1021 reply->writeInt32(-1);
1022
nikoa64c8c72009-07-20 15:07:26 -07001023 media::Metadata::Filter ids;
Nicolas Catania48290382009-07-10 13:53:06 -07001024
1025 // We don't block notifications while we fetch the data. We clear
1026 // mMetadataUpdated first so we don't lose notifications happening
1027 // during the rest of this call.
1028 {
1029 Mutex::Autolock lock(mLock);
1030 if (update_only) {
nikod608a812009-07-16 16:39:53 -07001031 ids = mMetadataUpdated;
Nicolas Catania48290382009-07-10 13:53:06 -07001032 }
1033 mMetadataUpdated.clear();
1034 }
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001035
nikoa64c8c72009-07-20 15:07:26 -07001036 media::Metadata metadata(reply);
Nicolas Catania48290382009-07-10 13:53:06 -07001037
nikoa64c8c72009-07-20 15:07:26 -07001038 metadata.appendHeader();
1039 status = player->getMetadata(ids, reply);
nikod608a812009-07-16 16:39:53 -07001040
1041 if (status != OK) {
nikoa64c8c72009-07-20 15:07:26 -07001042 metadata.resetParcel();
Steve Block29357bc2012-01-06 19:20:56 +00001043 ALOGE("getMetadata failed %d", status);
nikod608a812009-07-16 16:39:53 -07001044 return status;
1045 }
1046
1047 // FIXME: Implement filtering on the result. Not critical since
1048 // filtering takes place on the update notifications already. This
1049 // would be when all the metadata are fetch and a filter is set.
1050
nikod608a812009-07-16 16:39:53 -07001051 // Everything is fine, update the metadata length.
nikoa64c8c72009-07-20 15:07:26 -07001052 metadata.updateLength();
nikod608a812009-07-16 16:39:53 -07001053 return OK;
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001054}
1055
Wei Jiad399e7e2016-10-26 15:49:11 -07001056status_t MediaPlayerService::Client::setBufferingSettings(
1057 const BufferingSettings& buffering)
1058{
Wei Jiadc6f3402017-01-09 15:04:18 -08001059 ALOGV("[%d] setBufferingSettings{%s}",
1060 mConnId, buffering.toString().string());
Wei Jiad399e7e2016-10-26 15:49:11 -07001061 sp<MediaPlayerBase> p = getPlayer();
1062 if (p == 0) return UNKNOWN_ERROR;
1063 return p->setBufferingSettings(buffering);
1064}
1065
1066status_t MediaPlayerService::Client::getDefaultBufferingSettings(
1067 BufferingSettings* buffering /* nonnull */)
1068{
1069 sp<MediaPlayerBase> p = getPlayer();
1070 // TODO: create mPlayer on demand.
1071 if (p == 0) return UNKNOWN_ERROR;
1072 status_t ret = p->getDefaultBufferingSettings(buffering);
1073 if (ret == NO_ERROR) {
Wei Jiadc6f3402017-01-09 15:04:18 -08001074 ALOGV("[%d] getDefaultBufferingSettings{%s}",
1075 mConnId, buffering->toString().string());
Wei Jiad399e7e2016-10-26 15:49:11 -07001076 } else {
1077 ALOGV("[%d] getDefaultBufferingSettings returned %d", mConnId, ret);
1078 }
1079 return ret;
1080}
1081
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001082status_t MediaPlayerService::Client::prepareAsync()
1083{
Steve Block3856b092011-10-20 11:56:00 +01001084 ALOGV("[%d] prepareAsync", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001085 sp<MediaPlayerBase> p = getPlayer();
1086 if (p == 0) return UNKNOWN_ERROR;
1087 status_t ret = p->prepareAsync();
1088#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +00001089 ALOGD("start Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001090 if (ret == NO_ERROR) mAntagonizer->start();
1091#endif
1092 return ret;
1093}
1094
1095status_t MediaPlayerService::Client::start()
1096{
Steve Block3856b092011-10-20 11:56:00 +01001097 ALOGV("[%d] start", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001098 sp<MediaPlayerBase> p = getPlayer();
1099 if (p == 0) return UNKNOWN_ERROR;
1100 p->setLooping(mLoop);
1101 return p->start();
1102}
1103
1104status_t MediaPlayerService::Client::stop()
1105{
Steve Block3856b092011-10-20 11:56:00 +01001106 ALOGV("[%d] stop", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001107 sp<MediaPlayerBase> p = getPlayer();
1108 if (p == 0) return UNKNOWN_ERROR;
1109 return p->stop();
1110}
1111
1112status_t MediaPlayerService::Client::pause()
1113{
Steve Block3856b092011-10-20 11:56:00 +01001114 ALOGV("[%d] pause", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001115 sp<MediaPlayerBase> p = getPlayer();
1116 if (p == 0) return UNKNOWN_ERROR;
1117 return p->pause();
1118}
1119
1120status_t MediaPlayerService::Client::isPlaying(bool* state)
1121{
1122 *state = false;
1123 sp<MediaPlayerBase> p = getPlayer();
1124 if (p == 0) return UNKNOWN_ERROR;
1125 *state = p->isPlaying();
Steve Block3856b092011-10-20 11:56:00 +01001126 ALOGV("[%d] isPlaying: %d", mConnId, *state);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001127 return NO_ERROR;
1128}
1129
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001130status_t MediaPlayerService::Client::setPlaybackSettings(const AudioPlaybackRate& rate)
Wei Jia98160162015-02-04 17:01:11 -08001131{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001132 ALOGV("[%d] setPlaybackSettings(%f, %f, %d, %d)",
1133 mConnId, rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Wei Jia98160162015-02-04 17:01:11 -08001134 sp<MediaPlayerBase> p = getPlayer();
1135 if (p == 0) return UNKNOWN_ERROR;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001136 return p->setPlaybackSettings(rate);
1137}
1138
1139status_t MediaPlayerService::Client::getPlaybackSettings(AudioPlaybackRate* rate /* nonnull */)
1140{
1141 sp<MediaPlayerBase> p = getPlayer();
1142 if (p == 0) return UNKNOWN_ERROR;
1143 status_t ret = p->getPlaybackSettings(rate);
1144 if (ret == NO_ERROR) {
1145 ALOGV("[%d] getPlaybackSettings(%f, %f, %d, %d)",
1146 mConnId, rate->mSpeed, rate->mPitch, rate->mFallbackMode, rate->mStretchMode);
1147 } else {
1148 ALOGV("[%d] getPlaybackSettings returned %d", mConnId, ret);
1149 }
1150 return ret;
1151}
1152
1153status_t MediaPlayerService::Client::setSyncSettings(
1154 const AVSyncSettings& sync, float videoFpsHint)
1155{
1156 ALOGV("[%d] setSyncSettings(%u, %u, %f, %f)",
1157 mConnId, sync.mSource, sync.mAudioAdjustMode, sync.mTolerance, videoFpsHint);
1158 sp<MediaPlayerBase> p = getPlayer();
1159 if (p == 0) return UNKNOWN_ERROR;
1160 return p->setSyncSettings(sync, videoFpsHint);
1161}
1162
1163status_t MediaPlayerService::Client::getSyncSettings(
1164 AVSyncSettings* sync /* nonnull */, float* videoFps /* nonnull */)
1165{
1166 sp<MediaPlayerBase> p = getPlayer();
1167 if (p == 0) return UNKNOWN_ERROR;
1168 status_t ret = p->getSyncSettings(sync, videoFps);
1169 if (ret == NO_ERROR) {
1170 ALOGV("[%d] getSyncSettings(%u, %u, %f, %f)",
1171 mConnId, sync->mSource, sync->mAudioAdjustMode, sync->mTolerance, *videoFps);
1172 } else {
1173 ALOGV("[%d] getSyncSettings returned %d", mConnId, ret);
1174 }
1175 return ret;
Wei Jia98160162015-02-04 17:01:11 -08001176}
1177
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001178status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
1179{
Steve Block3856b092011-10-20 11:56:00 +01001180 ALOGV("getCurrentPosition");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001181 sp<MediaPlayerBase> p = getPlayer();
1182 if (p == 0) return UNKNOWN_ERROR;
1183 status_t ret = p->getCurrentPosition(msec);
1184 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001185 ALOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001186 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001187 ALOGE("getCurrentPosition returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001188 }
1189 return ret;
1190}
1191
1192status_t MediaPlayerService::Client::getDuration(int *msec)
1193{
Steve Block3856b092011-10-20 11:56:00 +01001194 ALOGV("getDuration");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001195 sp<MediaPlayerBase> p = getPlayer();
1196 if (p == 0) return UNKNOWN_ERROR;
1197 status_t ret = p->getDuration(msec);
1198 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001199 ALOGV("[%d] getDuration = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001200 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001201 ALOGE("getDuration returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001202 }
1203 return ret;
1204}
1205
Marco Nelissen6b74d672012-02-28 16:07:44 -08001206status_t MediaPlayerService::Client::setNextPlayer(const sp<IMediaPlayer>& player) {
1207 ALOGV("setNextPlayer");
1208 Mutex::Autolock l(mLock);
1209 sp<Client> c = static_cast<Client*>(player.get());
Wei Jia28284122016-08-30 13:49:06 -07001210 if (c != NULL && !mService->hasClient(c)) {
Robert Shihee0a0e32016-08-16 16:50:54 -07001211 return BAD_VALUE;
1212 }
1213
Marco Nelissen6b74d672012-02-28 16:07:44 -08001214 mNextClient = c;
John Grossman5f7e55e2012-08-24 14:47:25 -07001215
1216 if (c != NULL) {
1217 if (mAudioOutput != NULL) {
1218 mAudioOutput->setNextOutput(c->mAudioOutput);
1219 } else if ((mPlayer != NULL) && !mPlayer->hardwareOutput()) {
1220 ALOGE("no current audio output");
1221 }
1222
1223 if ((mPlayer != NULL) && (mNextClient->getPlayer() != NULL)) {
1224 mPlayer->setNextPlayer(mNextClient->getPlayer());
1225 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001226 }
John Grossman5f7e55e2012-08-24 14:47:25 -07001227
Marco Nelissen6b74d672012-02-28 16:07:44 -08001228 return OK;
1229}
1230
Andy Hung9fc8b5c2017-01-24 13:36:48 -08001231VolumeShaper::Status MediaPlayerService::Client::applyVolumeShaper(
1232 const sp<VolumeShaper::Configuration>& configuration,
1233 const sp<VolumeShaper::Operation>& operation) {
1234 // for hardware output, call player instead
1235 ALOGV("Client::applyVolumeShaper(%p)", this);
1236 sp<MediaPlayerBase> p = getPlayer();
1237 {
1238 Mutex::Autolock l(mLock);
1239 if (p != 0 && p->hardwareOutput()) {
1240 // TODO: investigate internal implementation
1241 return VolumeShaper::Status(INVALID_OPERATION);
1242 }
1243 if (mAudioOutput.get() != nullptr) {
1244 return mAudioOutput->applyVolumeShaper(configuration, operation);
1245 }
1246 }
1247 return VolumeShaper::Status(INVALID_OPERATION);
1248}
1249
1250sp<VolumeShaper::State> MediaPlayerService::Client::getVolumeShaperState(int id) {
1251 // for hardware output, call player instead
1252 ALOGV("Client::getVolumeShaperState(%p)", this);
1253 sp<MediaPlayerBase> p = getPlayer();
1254 {
1255 Mutex::Autolock l(mLock);
1256 if (p != 0 && p->hardwareOutput()) {
1257 // TODO: investigate internal implementation.
1258 return nullptr;
1259 }
1260 if (mAudioOutput.get() != nullptr) {
1261 return mAudioOutput->getVolumeShaperState(id);
1262 }
1263 }
1264 return nullptr;
1265}
1266
Wei Jiac5de0912016-11-18 10:22:14 -08001267status_t MediaPlayerService::Client::seekTo(int msec, MediaPlayerSeekMode mode)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001268{
Wei Jiac5de0912016-11-18 10:22:14 -08001269 ALOGV("[%d] seekTo(%d, %d)", mConnId, msec, mode);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001270 sp<MediaPlayerBase> p = getPlayer();
1271 if (p == 0) return UNKNOWN_ERROR;
Wei Jiac5de0912016-11-18 10:22:14 -08001272 return p->seekTo(msec, mode);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001273}
1274
1275status_t MediaPlayerService::Client::reset()
1276{
Steve Block3856b092011-10-20 11:56:00 +01001277 ALOGV("[%d] reset", mConnId);
John Grossmanc795b642012-02-22 15:38:35 -08001278 mRetransmitEndpointValid = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001279 sp<MediaPlayerBase> p = getPlayer();
1280 if (p == 0) return UNKNOWN_ERROR;
1281 return p->reset();
1282}
1283
Glenn Kastenfff6d712012-01-12 16:38:12 -08001284status_t MediaPlayerService::Client::setAudioStreamType(audio_stream_type_t type)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001285{
Steve Block3856b092011-10-20 11:56:00 +01001286 ALOGV("[%d] setAudioStreamType(%d)", mConnId, type);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001287 // TODO: for hardware output, call player instead
1288 Mutex::Autolock l(mLock);
1289 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1290 return NO_ERROR;
1291}
1292
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001293status_t MediaPlayerService::Client::setAudioAttributes_l(const Parcel &parcel)
1294{
1295 if (mAudioAttributes != NULL) { free(mAudioAttributes); }
1296 mAudioAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001297 if (mAudioAttributes == NULL) {
1298 return NO_MEMORY;
1299 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001300 unmarshallAudioAttributes(parcel, mAudioAttributes);
1301
1302 ALOGV("setAudioAttributes_l() usage=%d content=%d flags=0x%x tags=%s",
1303 mAudioAttributes->usage, mAudioAttributes->content_type, mAudioAttributes->flags,
1304 mAudioAttributes->tags);
1305
1306 if (mAudioOutput != 0) {
1307 mAudioOutput->setAudioAttributes(mAudioAttributes);
1308 }
1309 return NO_ERROR;
1310}
1311
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001312status_t MediaPlayerService::Client::setLooping(int loop)
1313{
Steve Block3856b092011-10-20 11:56:00 +01001314 ALOGV("[%d] setLooping(%d)", mConnId, loop);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001315 mLoop = loop;
1316 sp<MediaPlayerBase> p = getPlayer();
1317 if (p != 0) return p->setLooping(loop);
1318 return NO_ERROR;
1319}
1320
1321status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1322{
Steve Block3856b092011-10-20 11:56:00 +01001323 ALOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
John Grossman761defc2012-02-09 15:09:05 -08001324
1325 // for hardware output, call player instead
1326 sp<MediaPlayerBase> p = getPlayer();
1327 {
1328 Mutex::Autolock l(mLock);
1329 if (p != 0 && p->hardwareOutput()) {
1330 MediaPlayerHWInterface* hwp =
1331 reinterpret_cast<MediaPlayerHWInterface*>(p.get());
1332 return hwp->setVolume(leftVolume, rightVolume);
1333 } else {
1334 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1335 return NO_ERROR;
1336 }
1337 }
1338
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001339 return NO_ERROR;
1340}
1341
Eric Laurent2beeb502010-07-16 07:43:46 -07001342status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1343{
Steve Block3856b092011-10-20 11:56:00 +01001344 ALOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
Eric Laurent2beeb502010-07-16 07:43:46 -07001345 Mutex::Autolock l(mLock);
1346 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1347 return NO_ERROR;
1348}
1349
1350status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1351{
Steve Block3856b092011-10-20 11:56:00 +01001352 ALOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
Eric Laurent2beeb502010-07-16 07:43:46 -07001353 Mutex::Autolock l(mLock);
1354 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1355 return NO_ERROR;
1356}
Nicolas Catania48290382009-07-10 13:53:06 -07001357
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001358status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
Steve Block3856b092011-10-20 11:56:00 +01001359 ALOGV("[%d] setParameter(%d)", mConnId, key);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001360 switch (key) {
1361 case KEY_PARAMETER_AUDIO_ATTRIBUTES:
1362 {
1363 Mutex::Autolock l(mLock);
1364 return setAudioAttributes_l(request);
1365 }
1366 default:
1367 sp<MediaPlayerBase> p = getPlayer();
1368 if (p == 0) { return UNKNOWN_ERROR; }
1369 return p->setParameter(key, request);
1370 }
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001371}
1372
1373status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
Steve Block3856b092011-10-20 11:56:00 +01001374 ALOGV("[%d] getParameter(%d)", mConnId, key);
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001375 sp<MediaPlayerBase> p = getPlayer();
1376 if (p == 0) return UNKNOWN_ERROR;
1377 return p->getParameter(key, reply);
1378}
1379
John Grossmanc795b642012-02-22 15:38:35 -08001380status_t MediaPlayerService::Client::setRetransmitEndpoint(
1381 const struct sockaddr_in* endpoint) {
1382
1383 if (NULL != endpoint) {
1384 uint32_t a = ntohl(endpoint->sin_addr.s_addr);
1385 uint16_t p = ntohs(endpoint->sin_port);
1386 ALOGV("[%d] setRetransmitEndpoint(%u.%u.%u.%u:%hu)", mConnId,
1387 (a >> 24), (a >> 16) & 0xFF, (a >> 8) & 0xFF, (a & 0xFF), p);
1388 } else {
1389 ALOGV("[%d] setRetransmitEndpoint = <none>", mConnId);
1390 }
1391
1392 sp<MediaPlayerBase> p = getPlayer();
1393
1394 // Right now, the only valid time to set a retransmit endpoint is before
1395 // player selection has been made (since the presence or absence of a
1396 // retransmit endpoint is going to determine which player is selected during
1397 // setDataSource).
1398 if (p != 0) return INVALID_OPERATION;
1399
1400 if (NULL != endpoint) {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001401 Mutex::Autolock lock(mLock);
John Grossmanc795b642012-02-22 15:38:35 -08001402 mRetransmitEndpoint = *endpoint;
1403 mRetransmitEndpointValid = true;
1404 } else {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001405 Mutex::Autolock lock(mLock);
John Grossmanc795b642012-02-22 15:38:35 -08001406 mRetransmitEndpointValid = false;
1407 }
1408
1409 return NO_ERROR;
1410}
1411
John Grossman44a7e422012-06-21 17:29:24 -07001412status_t MediaPlayerService::Client::getRetransmitEndpoint(
1413 struct sockaddr_in* endpoint)
1414{
1415 if (NULL == endpoint)
1416 return BAD_VALUE;
1417
1418 sp<MediaPlayerBase> p = getPlayer();
1419
1420 if (p != NULL)
1421 return p->getRetransmitEndpoint(endpoint);
1422
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001423 Mutex::Autolock lock(mLock);
John Grossman44a7e422012-06-21 17:29:24 -07001424 if (!mRetransmitEndpointValid)
1425 return NO_INIT;
1426
1427 *endpoint = mRetransmitEndpoint;
1428
1429 return NO_ERROR;
1430}
1431
Gloria Wangb483c472011-04-11 17:23:27 -07001432void MediaPlayerService::Client::notify(
1433 void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001434{
1435 Client* client = static_cast<Client*>(cookie);
James Dongb8a98252012-08-26 16:13:03 -07001436 if (client == NULL) {
1437 return;
1438 }
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001439
James Dongb8a98252012-08-26 16:13:03 -07001440 sp<IMediaPlayerClient> c;
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001441 sp<Client> nextClient;
1442 status_t errStartNext = NO_ERROR;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001443 {
1444 Mutex::Autolock l(client->mLock);
James Dongb8a98252012-08-26 16:13:03 -07001445 c = client->mClient;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001446 if (msg == MEDIA_PLAYBACK_COMPLETE && client->mNextClient != NULL) {
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001447 nextClient = client->mNextClient;
1448
John Grossmancb0b7552012-08-23 17:47:31 -07001449 if (client->mAudioOutput != NULL)
1450 client->mAudioOutput->switchToNextOutput();
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001451
1452 errStartNext = nextClient->start();
1453 }
1454 }
1455
1456 if (nextClient != NULL) {
1457 sp<IMediaPlayerClient> nc;
1458 {
1459 Mutex::Autolock l(nextClient->mLock);
1460 nc = nextClient->mClient;
1461 }
1462 if (nc != NULL) {
1463 if (errStartNext == NO_ERROR) {
1464 nc->notify(MEDIA_INFO, MEDIA_INFO_STARTED_AS_NEXT, 0, obj);
1465 } else {
1466 nc->notify(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN , 0, obj);
1467 ALOGE("gapless:start playback for next track failed, err(%d)", errStartNext);
Wei Jia2afac0c2016-01-07 12:13:07 -08001468 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001469 }
1470 }
1471
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001472 if (MEDIA_INFO == msg &&
Nicolas Catania48290382009-07-10 13:53:06 -07001473 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikoa64c8c72009-07-20 15:07:26 -07001474 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania48290382009-07-10 13:53:06 -07001475
1476 if(client->shouldDropMetadata(metadata_type)) {
1477 return;
1478 }
1479
1480 // Update the list of metadata that have changed. getMetadata
1481 // also access mMetadataUpdated and clears it.
1482 client->addNewMetadataUpdate(metadata_type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001483 }
James Dongb8a98252012-08-26 16:13:03 -07001484
1485 if (c != NULL) {
1486 ALOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
1487 c->notify(msg, ext1, ext2, obj);
1488 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001489}
1490
Nicolas Catania48290382009-07-10 13:53:06 -07001491
nikoa64c8c72009-07-20 15:07:26 -07001492bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001493{
Nicolas Catania48290382009-07-10 13:53:06 -07001494 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001495
Nicolas Catania48290382009-07-10 13:53:06 -07001496 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001497 return true;
1498 }
1499
Nicolas Catania48290382009-07-10 13:53:06 -07001500 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001501 return false;
Nicolas Catania48290382009-07-10 13:53:06 -07001502 } else {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001503 return true;
1504 }
1505}
1506
Nicolas Catania48290382009-07-10 13:53:06 -07001507
nikoa64c8c72009-07-20 15:07:26 -07001508void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania48290382009-07-10 13:53:06 -07001509 Mutex::Autolock lock(mLock);
1510 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1511 mMetadataUpdated.add(metadata_type);
1512 }
1513}
1514
Hassan Shojaniacefac142017-02-06 21:02:02 -08001515// Modular DRM
1516status_t MediaPlayerService::Client::prepareDrm(const uint8_t uuid[16],
1517 const Vector<uint8_t>& drmSessionId)
1518{
1519 ALOGV("[%d] prepareDrm", mConnId);
1520 sp<MediaPlayerBase> p = getPlayer();
1521 if (p == 0) return UNKNOWN_ERROR;
1522
1523 status_t ret = p->prepareDrm(uuid, drmSessionId);
1524 ALOGV("prepareDrm ret: %d", ret);
1525
1526 return ret;
1527}
1528
1529status_t MediaPlayerService::Client::releaseDrm()
1530{
1531 ALOGV("[%d] releaseDrm", mConnId);
1532 sp<MediaPlayerBase> p = getPlayer();
1533 if (p == 0) return UNKNOWN_ERROR;
1534
1535 status_t ret = p->releaseDrm();
1536 ALOGV("releaseDrm ret: %d", ret);
1537
1538 return ret;
1539}
1540
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001541#if CALLBACK_ANTAGONIZER
1542const int Antagonizer::interval = 10000; // 10 msecs
1543
1544Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1545 mExit(false), mActive(false), mClient(client), mCb(cb)
1546{
1547 createThread(callbackThread, this);
1548}
1549
1550void Antagonizer::kill()
1551{
1552 Mutex::Autolock _l(mLock);
1553 mActive = false;
1554 mExit = true;
1555 mCondition.wait(mLock);
1556}
1557
1558int Antagonizer::callbackThread(void* user)
1559{
Steve Blockb8a80522011-12-20 16:23:08 +00001560 ALOGD("Antagonizer started");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001561 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1562 while (!p->mExit) {
1563 if (p->mActive) {
Steve Block3856b092011-10-20 11:56:00 +01001564 ALOGV("send event");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001565 p->mCb(p->mClient, 0, 0, 0);
1566 }
1567 usleep(interval);
1568 }
1569 Mutex::Autolock _l(p->mLock);
1570 p->mCondition.signal();
Steve Blockb8a80522011-12-20 16:23:08 +00001571 ALOGD("Antagonizer stopped");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001572 return 0;
1573}
1574#endif
1575
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001576#undef LOG_TAG
1577#define LOG_TAG "AudioSink"
Andy Hung1afd0982016-11-08 16:13:44 -08001578MediaPlayerService::AudioOutput::AudioOutput(audio_session_t sessionId, uid_t uid, int pid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001579 const audio_attributes_t* attr)
Andreas Huber20111aa2009-07-14 16:56:47 -07001580 : mCallback(NULL),
Eric Laurenta514bdb2010-06-21 09:27:30 -07001581 mCallbackCookie(NULL),
Marco Nelissen6b74d672012-02-28 16:07:44 -08001582 mCallbackData(NULL),
Andy Hungd1c74342015-07-07 16:54:23 -07001583 mStreamType(AUDIO_STREAM_MUSIC),
Andy Hungd1c74342015-07-07 16:54:23 -07001584 mLeftVolume(1.0),
1585 mRightVolume(1.0),
1586 mPlaybackRate(AUDIO_PLAYBACK_RATE_DEFAULT),
1587 mSampleRateHz(0),
1588 mMsecsPerFrame(0),
1589 mFrameSize(0),
Eric Laurent1948eb32012-04-13 16:50:19 -07001590 mSessionId(sessionId),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001591 mUid(uid),
Marco Nelissend457c972014-02-11 08:47:07 -08001592 mPid(pid),
Andy Hungd1c74342015-07-07 16:54:23 -07001593 mSendLevel(0.0),
1594 mAuxEffectId(0),
Andy Hung4ef88d72017-02-21 19:47:53 -08001595 mFlags(AUDIO_OUTPUT_FLAG_NONE),
1596 mVolumeHandler(new VolumeHandler())
Andy Hungd1c74342015-07-07 16:54:23 -07001597{
Steve Block3856b092011-10-20 11:56:00 +01001598 ALOGV("AudioOutput(%d)", sessionId);
Eric Laurent43562692015-07-15 16:49:07 -07001599 if (attr != NULL) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001600 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1601 if (mAttributes != NULL) {
1602 memcpy(mAttributes, attr, sizeof(audio_attributes_t));
1603 mStreamType = audio_attributes_to_stream_type(attr);
1604 }
1605 } else {
1606 mAttributes = NULL;
Eric Laurent43562692015-07-15 16:49:07 -07001607 }
1608
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001609 setMinBufferCount();
1610}
1611
1612MediaPlayerService::AudioOutput::~AudioOutput()
1613{
1614 close();
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001615 free(mAttributes);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001616 delete mCallbackData;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001617}
1618
Andy Hungd1c74342015-07-07 16:54:23 -07001619//static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001620void MediaPlayerService::AudioOutput::setMinBufferCount()
1621{
1622 char value[PROPERTY_VALUE_MAX];
1623 if (property_get("ro.kernel.qemu", value, 0)) {
1624 mIsOnEmulator = true;
1625 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1626 }
1627}
1628
Andy Hungd1c74342015-07-07 16:54:23 -07001629// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001630bool MediaPlayerService::AudioOutput::isOnEmulator()
1631{
Andy Hungd1c74342015-07-07 16:54:23 -07001632 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001633 return mIsOnEmulator;
1634}
1635
Andy Hungd1c74342015-07-07 16:54:23 -07001636// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001637int MediaPlayerService::AudioOutput::getMinBufferCount()
1638{
Andy Hungd1c74342015-07-07 16:54:23 -07001639 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001640 return mMinBufferCount;
1641}
1642
1643ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1644{
Andy Hungd1c74342015-07-07 16:54:23 -07001645 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001646 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001647 return mTrack->frameCount() * mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001648}
1649
1650ssize_t MediaPlayerService::AudioOutput::frameCount() const
1651{
Andy Hungd1c74342015-07-07 16:54:23 -07001652 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001653 if (mTrack == 0) return NO_INIT;
1654 return mTrack->frameCount();
1655}
1656
1657ssize_t MediaPlayerService::AudioOutput::channelCount() const
1658{
Andy Hungd1c74342015-07-07 16:54:23 -07001659 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001660 if (mTrack == 0) return NO_INIT;
1661 return mTrack->channelCount();
1662}
1663
1664ssize_t MediaPlayerService::AudioOutput::frameSize() const
1665{
Andy Hungd1c74342015-07-07 16:54:23 -07001666 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001667 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001668 return mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001669}
1670
1671uint32_t MediaPlayerService::AudioOutput::latency () const
1672{
Andy Hungd1c74342015-07-07 16:54:23 -07001673 Mutex::Autolock lock(mLock);
Eric Laurentdb354e52012-03-05 17:27:11 -08001674 if (mTrack == 0) return 0;
1675 return mTrack->latency();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001676}
1677
1678float MediaPlayerService::AudioOutput::msecsPerFrame() const
1679{
Andy Hungd1c74342015-07-07 16:54:23 -07001680 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001681 return mMsecsPerFrame;
1682}
1683
Marco Nelissen4110c102012-03-29 09:31:28 -07001684status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position) const
Eric Laurent342e9cf2010-01-19 17:37:09 -08001685{
Andy Hungd1c74342015-07-07 16:54:23 -07001686 Mutex::Autolock lock(mLock);
Eric Laurent342e9cf2010-01-19 17:37:09 -08001687 if (mTrack == 0) return NO_INIT;
1688 return mTrack->getPosition(position);
1689}
1690
Lajos Molnar06ad1522014-08-28 07:27:44 -07001691status_t MediaPlayerService::AudioOutput::getTimestamp(AudioTimestamp &ts) const
1692{
Andy Hungd1c74342015-07-07 16:54:23 -07001693 Mutex::Autolock lock(mLock);
Lajos Molnar06ad1522014-08-28 07:27:44 -07001694 if (mTrack == 0) return NO_INIT;
1695 return mTrack->getTimestamp(ts);
1696}
1697
Wei Jiac4ac8172015-10-21 10:35:48 -07001698// TODO: Remove unnecessary calls to getPlayedOutDurationUs()
1699// as it acquires locks and may query the audio driver.
1700//
1701// Some calls could conceivably retrieve extrapolated data instead of
1702// accessing getTimestamp() or getPosition() every time a data buffer with
1703// a media time is received.
1704//
1705// Calculate duration of played samples if played at normal rate (i.e., 1.0).
1706int64_t MediaPlayerService::AudioOutput::getPlayedOutDurationUs(int64_t nowUs) const
1707{
1708 Mutex::Autolock lock(mLock);
1709 if (mTrack == 0 || mSampleRateHz == 0) {
Wei Jia213f4902015-10-22 08:55:25 -07001710 return 0;
Wei Jiac4ac8172015-10-21 10:35:48 -07001711 }
1712
1713 uint32_t numFramesPlayed;
Andy Hung5d313802016-10-10 15:09:39 -07001714 int64_t numFramesPlayedAtUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001715 AudioTimestamp ts;
Wei Jiac4ac8172015-10-21 10:35:48 -07001716
1717 status_t res = mTrack->getTimestamp(ts);
1718 if (res == OK) { // case 1: mixing audio tracks and offloaded tracks.
1719 numFramesPlayed = ts.mPosition;
Andy Hung5d313802016-10-10 15:09:39 -07001720 numFramesPlayedAtUs = ts.mTime.tv_sec * 1000000LL + ts.mTime.tv_nsec / 1000;
1721 //ALOGD("getTimestamp: OK %d %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001722 } else if (res == WOULD_BLOCK) { // case 2: transitory state on start of a new track
1723 numFramesPlayed = 0;
Andy Hung5d313802016-10-10 15:09:39 -07001724 numFramesPlayedAtUs = nowUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001725 //ALOGD("getTimestamp: WOULD_BLOCK %d %lld",
Andy Hung5d313802016-10-10 15:09:39 -07001726 // numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001727 } else { // case 3: transitory at new track or audio fast tracks.
1728 res = mTrack->getPosition(&numFramesPlayed);
1729 CHECK_EQ(res, (status_t)OK);
Andy Hung5d313802016-10-10 15:09:39 -07001730 numFramesPlayedAtUs = nowUs;
1731 numFramesPlayedAtUs += 1000LL * mTrack->latency() / 2; /* XXX */
1732 //ALOGD("getPosition: %u %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001733 }
1734
1735 // CHECK_EQ(numFramesPlayed & (1 << 31), 0); // can't be negative until 12.4 hrs, test
1736 // TODO: remove the (int32_t) casting below as it may overflow at 12.4 hours.
1737 int64_t durationUs = (int64_t)((int32_t)numFramesPlayed * 1000000LL / mSampleRateHz)
Andy Hung5d313802016-10-10 15:09:39 -07001738 + nowUs - numFramesPlayedAtUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001739 if (durationUs < 0) {
1740 // Occurs when numFramesPlayed position is very small and the following:
1741 // (1) In case 1, the time nowUs is computed before getTimestamp() is called and
Andy Hung5d313802016-10-10 15:09:39 -07001742 // numFramesPlayedAtUs is greater than nowUs by time more than numFramesPlayed.
Wei Jiac4ac8172015-10-21 10:35:48 -07001743 // (2) In case 3, using getPosition and adding mAudioSink->latency() to
Andy Hung5d313802016-10-10 15:09:39 -07001744 // numFramesPlayedAtUs, by a time amount greater than numFramesPlayed.
Wei Jiac4ac8172015-10-21 10:35:48 -07001745 //
1746 // Both of these are transitory conditions.
1747 ALOGV("getPlayedOutDurationUs: negative duration %lld set to zero", (long long)durationUs);
1748 durationUs = 0;
1749 }
1750 ALOGV("getPlayedOutDurationUs(%lld) nowUs(%lld) frames(%u) framesAt(%lld)",
Andy Hung5d313802016-10-10 15:09:39 -07001751 (long long)durationUs, (long long)nowUs,
1752 numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001753 return durationUs;
1754}
1755
Marco Nelissen4110c102012-03-29 09:31:28 -07001756status_t MediaPlayerService::AudioOutput::getFramesWritten(uint32_t *frameswritten) const
1757{
Andy Hungd1c74342015-07-07 16:54:23 -07001758 Mutex::Autolock lock(mLock);
Marco Nelissen4110c102012-03-29 09:31:28 -07001759 if (mTrack == 0) return NO_INIT;
Andy Hung2f6e73d2016-04-08 12:12:58 -07001760 ExtendedTimestamp ets;
1761 status_t status = mTrack->getTimestamp(&ets);
1762 if (status == OK || status == WOULD_BLOCK) {
1763 *frameswritten = (uint32_t)ets.mPosition[ExtendedTimestamp::LOCATION_CLIENT];
1764 }
1765 return status;
Marco Nelissen4110c102012-03-29 09:31:28 -07001766}
1767
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001768status_t MediaPlayerService::AudioOutput::setParameters(const String8& keyValuePairs)
1769{
Andy Hungd1c74342015-07-07 16:54:23 -07001770 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001771 if (mTrack == 0) return NO_INIT;
1772 return mTrack->setParameters(keyValuePairs);
1773}
1774
1775String8 MediaPlayerService::AudioOutput::getParameters(const String8& keys)
1776{
Andy Hungd1c74342015-07-07 16:54:23 -07001777 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001778 if (mTrack == 0) return String8::empty();
1779 return mTrack->getParameters(keys);
1780}
1781
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001782void MediaPlayerService::AudioOutput::setAudioAttributes(const audio_attributes_t * attributes) {
Andy Hungd1c74342015-07-07 16:54:23 -07001783 Mutex::Autolock lock(mLock);
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001784 if (attributes == NULL) {
1785 free(mAttributes);
1786 mAttributes = NULL;
1787 } else {
1788 if (mAttributes == NULL) {
1789 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1790 }
1791 memcpy(mAttributes, attributes, sizeof(audio_attributes_t));
Eric Laurent43562692015-07-15 16:49:07 -07001792 mStreamType = audio_attributes_to_stream_type(attributes);
1793 }
1794}
1795
1796void MediaPlayerService::AudioOutput::setAudioStreamType(audio_stream_type_t streamType)
1797{
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001798 Mutex::Autolock lock(mLock);
Eric Laurent43562692015-07-15 16:49:07 -07001799 // do not allow direct stream type modification if attributes have been set
1800 if (mAttributes == NULL) {
1801 mStreamType = streamType;
1802 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001803}
1804
Andy Hungd1c74342015-07-07 16:54:23 -07001805void MediaPlayerService::AudioOutput::deleteRecycledTrack_l()
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001806{
Andy Hungd1c74342015-07-07 16:54:23 -07001807 ALOGV("deleteRecycledTrack_l");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001808 if (mRecycledTrack != 0) {
1809
1810 if (mCallbackData != NULL) {
1811 mCallbackData->setOutput(NULL);
1812 mCallbackData->endTrackSwitch();
1813 }
1814
1815 if ((mRecycledTrack->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) {
Andy Hunge13f8a62016-03-30 14:20:42 -07001816 int32_t msec = 0;
1817 if (!mRecycledTrack->stopped()) { // check if active
1818 (void)mRecycledTrack->pendingDuration(&msec);
1819 }
1820 mRecycledTrack->stop(); // ensure full data drain
1821 ALOGD("deleting recycled track, waiting for data drain (%d msec)", msec);
1822 if (msec > 0) {
1823 static const int32_t WAIT_LIMIT_MS = 3000;
1824 if (msec > WAIT_LIMIT_MS) {
1825 msec = WAIT_LIMIT_MS;
1826 }
1827 usleep(msec * 1000LL);
1828 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001829 }
1830 // An offloaded track isn't flushed because the STREAM_END is reported
1831 // slightly prematurely to allow time for the gapless track switch
1832 // but this means that if we decide not to recycle the track there
1833 // could be a small amount of residual data still playing. We leave
1834 // AudioFlinger to drain the track.
1835
1836 mRecycledTrack.clear();
Andy Hungd1c74342015-07-07 16:54:23 -07001837 close_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001838 delete mCallbackData;
1839 mCallbackData = NULL;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001840 }
1841}
1842
Andy Hungd1c74342015-07-07 16:54:23 -07001843void MediaPlayerService::AudioOutput::close_l()
1844{
1845 mTrack.clear();
1846}
1847
Andreas Huber20111aa2009-07-14 16:56:47 -07001848status_t MediaPlayerService::AudioOutput::open(
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001849 uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
1850 audio_format_t format, int bufferCount,
Eric Laurent1948eb32012-04-13 16:50:19 -07001851 AudioCallback cb, void *cookie,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001852 audio_output_flags_t flags,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001853 const audio_offload_info_t *offloadInfo,
Andy Hung179652e2015-05-31 22:49:46 -07001854 bool doNotReconnect,
1855 uint32_t suggestedFrameCount)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001856{
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001857 ALOGV("open(%u, %d, 0x%x, 0x%x, %d, %d 0x%x)", sampleRate, channelCount, channelMask,
1858 format, bufferCount, mSessionId, flags);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001859
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001860 // offloading is only supported in callback mode for now.
1861 // offloadInfo must be present if offload flag is set
1862 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) &&
1863 ((cb == NULL) || (offloadInfo == NULL))) {
1864 return BAD_VALUE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001865 }
1866
Andy Hung179652e2015-05-31 22:49:46 -07001867 // compute frame count for the AudioTrack internal buffer
1868 size_t frameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001869 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1870 frameCount = 0; // AudioTrack will get frame count from AudioFlinger
1871 } else {
Andy Hung179652e2015-05-31 22:49:46 -07001872 // try to estimate the buffer processing fetch size from AudioFlinger.
1873 // framesPerBuffer is approximate and generally correct, except when it's not :-).
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001874 uint32_t afSampleRate;
1875 size_t afFrameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001876 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1877 return NO_INIT;
1878 }
1879 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1880 return NO_INIT;
1881 }
Andy Hung179652e2015-05-31 22:49:46 -07001882 const size_t framesPerBuffer =
1883 (unsigned long long)sampleRate * afFrameCount / afSampleRate;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001884
Andy Hung179652e2015-05-31 22:49:46 -07001885 if (bufferCount == 0) {
1886 // use suggestedFrameCount
1887 bufferCount = (suggestedFrameCount + framesPerBuffer - 1) / framesPerBuffer;
1888 }
1889 // Check argument bufferCount against the mininum buffer count
1890 if (bufferCount != 0 && bufferCount < mMinBufferCount) {
1891 ALOGV("bufferCount (%d) increased to %d", bufferCount, mMinBufferCount);
1892 bufferCount = mMinBufferCount;
1893 }
1894 // if frameCount is 0, then AudioTrack will get frame count from AudioFlinger
1895 // which will be the minimum size permitted.
1896 frameCount = bufferCount * framesPerBuffer;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001897 }
Andreas Huber20111aa2009-07-14 16:56:47 -07001898
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001899 if (channelMask == CHANNEL_MASK_USE_CHANNEL_ORDER) {
Glenn Kastenab334fd2012-03-14 12:56:06 -07001900 channelMask = audio_channel_out_mask_from_count(channelCount);
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001901 if (0 == channelMask) {
1902 ALOGE("open() error, can\'t derive mask for %d audio channels", channelCount);
1903 return NO_INIT;
1904 }
1905 }
Eric Laurent1948eb32012-04-13 16:50:19 -07001906
Andy Hungd1c74342015-07-07 16:54:23 -07001907 Mutex::Autolock lock(mLock);
Andy Hung179652e2015-05-31 22:49:46 -07001908 mCallback = cb;
1909 mCallbackCookie = cookie;
1910
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001911 // Check whether we can recycle the track
1912 bool reuse = false;
1913 bool bothOffloaded = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001914
Glenn Kasten2799d742013-05-30 14:33:29 -07001915 if (mRecycledTrack != 0) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001916 // check whether we are switching between two offloaded tracks
1917 bothOffloaded = (flags & mRecycledTrack->getFlags()
1918 & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0;
Marco Nelissen67295b52012-06-11 14:52:53 -07001919
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001920 // check if the existing track can be reused as-is, or if a new track needs to be created.
1921 reuse = true;
1922
Marco Nelissen67295b52012-06-11 14:52:53 -07001923 if ((mCallbackData == NULL && mCallback != NULL) ||
1924 (mCallbackData != NULL && mCallback == NULL)) {
1925 // recycled track uses callbacks but the caller wants to use writes, or vice versa
1926 ALOGV("can't chain callback and write");
1927 reuse = false;
1928 } else if ((mRecycledTrack->getSampleRate() != sampleRate) ||
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001929 (mRecycledTrack->channelCount() != (uint32_t)channelCount) ) {
1930 ALOGV("samplerate, channelcount differ: %u/%u Hz, %u/%d ch",
Marco Nelissen67295b52012-06-11 14:52:53 -07001931 mRecycledTrack->getSampleRate(), sampleRate,
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001932 mRecycledTrack->channelCount(), channelCount);
Marco Nelissen67295b52012-06-11 14:52:53 -07001933 reuse = false;
1934 } else if (flags != mFlags) {
1935 ALOGV("output flags differ %08x/%08x", flags, mFlags);
1936 reuse = false;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001937 } else if (mRecycledTrack->format() != format) {
1938 reuse = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001939 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001940 } else {
1941 ALOGV("no track available to recycle");
1942 }
1943
1944 ALOGV_IF(bothOffloaded, "both tracks offloaded");
1945
1946 // If we can't recycle and both tracks are offloaded
1947 // we must close the previous output before opening a new one
1948 if (bothOffloaded && !reuse) {
1949 ALOGV("both offloaded and not recycling");
Andy Hungd1c74342015-07-07 16:54:23 -07001950 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001951 }
1952
1953 sp<AudioTrack> t;
1954 CallbackData *newcbd = NULL;
1955
1956 // We don't attempt to create a new track if we are recycling an
1957 // offloaded track. But, if we are recycling a non-offloaded or we
1958 // are switching where one is offloaded and one isn't then we create
1959 // the new track in advance so that we can read additional stream info
1960
1961 if (!(reuse && bothOffloaded)) {
1962 ALOGV("creating new AudioTrack");
1963
1964 if (mCallback != NULL) {
1965 newcbd = new CallbackData(this);
1966 t = new AudioTrack(
1967 mStreamType,
1968 sampleRate,
1969 format,
1970 channelMask,
1971 frameCount,
1972 flags,
1973 CallbackWrapper,
1974 newcbd,
1975 0, // notification frames
1976 mSessionId,
1977 AudioTrack::TRANSFER_CALLBACK,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001978 offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -08001979 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001980 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001981 mAttributes,
1982 doNotReconnect);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001983 } else {
Andy Hungff874dc2016-04-11 16:49:09 -07001984 // TODO: Due to buffer memory concerns, we use a max target playback speed
1985 // based on mPlaybackRate at the time of open (instead of kMaxRequiredSpeed),
1986 // also clamping the target speed to 1.0 <= targetSpeed <= kMaxRequiredSpeed.
1987 const float targetSpeed =
1988 std::min(std::max(mPlaybackRate.mSpeed, 1.0f), kMaxRequiredSpeed);
1989 ALOGW_IF(targetSpeed != mPlaybackRate.mSpeed,
1990 "track target speed:%f clamped from playback speed:%f",
1991 targetSpeed, mPlaybackRate.mSpeed);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001992 t = new AudioTrack(
1993 mStreamType,
1994 sampleRate,
1995 format,
1996 channelMask,
1997 frameCount,
1998 flags,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001999 NULL, // callback
2000 NULL, // user data
2001 0, // notification frames
2002 mSessionId,
2003 AudioTrack::TRANSFER_DEFAULT,
2004 NULL, // offload info
Marco Nelissend457c972014-02-11 08:47:07 -08002005 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07002006 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07002007 mAttributes,
Andy Hungff874dc2016-04-11 16:49:09 -07002008 doNotReconnect,
2009 targetSpeed);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002010 }
2011
2012 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
2013 ALOGE("Unable to create audio track");
2014 delete newcbd;
Glenn Kasten3e98ecd2015-05-18 13:13:24 -07002015 // t goes out of scope, so reference count drops to zero
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002016 return NO_INIT;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07002017 } else {
2018 // successful AudioTrack initialization implies a legacy stream type was generated
2019 // from the audio attributes
2020 mStreamType = t->streamType();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002021 }
2022 }
2023
2024 if (reuse) {
2025 CHECK(mRecycledTrack != NULL);
2026
2027 if (!bothOffloaded) {
2028 if (mRecycledTrack->frameCount() != t->frameCount()) {
Andy Hung833b4752016-04-04 17:15:48 -07002029 ALOGV("framecount differs: %zu/%zu frames",
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002030 mRecycledTrack->frameCount(), t->frameCount());
2031 reuse = false;
2032 }
2033 }
2034
Marco Nelissen67295b52012-06-11 14:52:53 -07002035 if (reuse) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002036 ALOGV("chaining to next output and recycling track");
Andy Hungd1c74342015-07-07 16:54:23 -07002037 close_l();
Marco Nelissen67295b52012-06-11 14:52:53 -07002038 mTrack = mRecycledTrack;
Glenn Kasten2799d742013-05-30 14:33:29 -07002039 mRecycledTrack.clear();
Marco Nelissen67295b52012-06-11 14:52:53 -07002040 if (mCallbackData != NULL) {
2041 mCallbackData->setOutput(this);
2042 }
Marco Nelissen67295b52012-06-11 14:52:53 -07002043 delete newcbd;
Wei Jiae0bbac92016-07-18 16:04:53 -07002044 return updateTrack();
Marco Nelissen67295b52012-06-11 14:52:53 -07002045 }
Marco Nelissen67295b52012-06-11 14:52:53 -07002046 }
2047
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002048 // we're not going to reuse the track, unblock and flush it
2049 // this was done earlier if both tracks are offloaded
2050 if (!bothOffloaded) {
Andy Hungd1c74342015-07-07 16:54:23 -07002051 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002052 }
2053
2054 CHECK((t != NULL) && ((mCallback == NULL) || (newcbd != NULL)));
2055
Marco Nelissen67295b52012-06-11 14:52:53 -07002056 mCallbackData = newcbd;
Steve Block3856b092011-10-20 11:56:00 +01002057 ALOGV("setVolume");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002058 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07002059
Andy Hung39399b62017-04-21 15:07:45 -07002060 // Restore VolumeShapers for the MediaPlayer in case the track was recreated
2061 // due to an output sink error (e.g. offload to non-offload switch).
2062 mVolumeHandler->forall([&t](const VolumeShaper &shaper) -> VolumeShaper::Status {
2063 sp<VolumeShaper::Operation> operationToEnd =
2064 new VolumeShaper::Operation(shaper.mOperation);
2065 // TODO: Ideally we would restore to the exact xOffset position
2066 // as returned by getVolumeShaperState(), but we don't have that
2067 // information when restoring at the client unless we periodically poll
2068 // the server or create shared memory state.
2069 //
2070 // For now, we simply advance to the end of the VolumeShaper effect
2071 // if it has been started.
2072 if (shaper.isStarted()) {
Andy Hungf3702642017-05-05 17:33:32 -07002073 operationToEnd->setNormalizedTime(1.f);
Andy Hung39399b62017-04-21 15:07:45 -07002074 }
2075 return t->applyVolumeShaper(shaper.mConfiguration, operationToEnd);
Andy Hung4ef88d72017-02-21 19:47:53 -08002076 });
Andy Hung4ef88d72017-02-21 19:47:53 -08002077
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002078 mSampleRateHz = sampleRate;
Preetam Singh Ranawat2e17eef2015-08-12 12:11:46 -07002079 mFlags = flags;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002080 mMsecsPerFrame = 1E3f / (mPlaybackRate.mSpeed * sampleRate);
Andy Hungd1c74342015-07-07 16:54:23 -07002081 mFrameSize = t->frameSize();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002082 mTrack = t;
Eric Laurent2beeb502010-07-16 07:43:46 -07002083
Wei Jiae0bbac92016-07-18 16:04:53 -07002084 return updateTrack();
2085}
2086
2087status_t MediaPlayerService::AudioOutput::updateTrack() {
2088 if (mTrack == NULL) {
2089 return NO_ERROR;
2090 }
2091
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002092 status_t res = NO_ERROR;
Wei Jia0162d002015-06-09 11:59:33 -07002093 // Note some output devices may give us a direct track even though we don't specify it.
2094 // Example: Line application b/17459982.
Wei Jiae0bbac92016-07-18 16:04:53 -07002095 if ((mTrack->getFlags()
2096 & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) {
2097 res = mTrack->setPlaybackRate(mPlaybackRate);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002098 if (res == NO_ERROR) {
Wei Jiae0bbac92016-07-18 16:04:53 -07002099 mTrack->setAuxEffectSendLevel(mSendLevel);
2100 res = mTrack->attachAuxEffect(mAuxEffectId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002101 }
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002102 }
Wei Jiae0bbac92016-07-18 16:04:53 -07002103 ALOGV("updateTrack() DONE status %d", res);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002104 return res;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002105}
2106
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002107status_t MediaPlayerService::AudioOutput::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002108{
Steve Block3856b092011-10-20 11:56:00 +01002109 ALOGV("start");
Andy Hungd1c74342015-07-07 16:54:23 -07002110 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08002111 if (mCallbackData != NULL) {
2112 mCallbackData->endTrackSwitch();
2113 }
Glenn Kasten2799d742013-05-30 14:33:29 -07002114 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002115 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07002116 mTrack->setAuxEffectSendLevel(mSendLevel);
Andy Hung39399b62017-04-21 15:07:45 -07002117 status_t status = mTrack->start();
2118 if (status == NO_ERROR) {
2119 mVolumeHandler->setStarted();
2120 }
2121 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002122 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002123 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002124}
2125
Marco Nelissen6b74d672012-02-28 16:07:44 -08002126void MediaPlayerService::AudioOutput::setNextOutput(const sp<AudioOutput>& nextOutput) {
Andy Hungd1c74342015-07-07 16:54:23 -07002127 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08002128 mNextOutput = nextOutput;
2129}
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08002130
Marco Nelissen6b74d672012-02-28 16:07:44 -08002131void MediaPlayerService::AudioOutput::switchToNextOutput() {
2132 ALOGV("switchToNextOutput");
Andy Hungd1c74342015-07-07 16:54:23 -07002133
2134 // Try to acquire the callback lock before moving track (without incurring deadlock).
2135 const unsigned kMaxSwitchTries = 100;
2136 Mutex::Autolock lock(mLock);
2137 for (unsigned tries = 0;;) {
2138 if (mTrack == 0) {
2139 return;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002140 }
Andy Hungd1c74342015-07-07 16:54:23 -07002141 if (mNextOutput != NULL && mNextOutput != this) {
2142 if (mCallbackData != NULL) {
2143 // two alternative approaches
2144#if 1
2145 CallbackData *callbackData = mCallbackData;
2146 mLock.unlock();
2147 // proper acquisition sequence
2148 callbackData->lock();
2149 mLock.lock();
2150 // Caution: it is unlikely that someone deleted our callback or changed our target
2151 if (callbackData != mCallbackData || mNextOutput == NULL || mNextOutput == this) {
2152 // fatal if we are starved out.
2153 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2154 "switchToNextOutput() cannot obtain correct lock sequence");
2155 callbackData->unlock();
2156 continue;
2157 }
2158 callbackData->mSwitching = true; // begin track switch
Wei Jiaadee56a2016-08-05 15:40:34 -07002159 callbackData->setOutput(NULL);
Andy Hungd1c74342015-07-07 16:54:23 -07002160#else
2161 // tryBeginTrackSwitch() returns false if the callback has the lock.
2162 if (!mCallbackData->tryBeginTrackSwitch()) {
2163 // fatal if we are starved out.
2164 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2165 "switchToNextOutput() cannot obtain callback lock");
2166 mLock.unlock();
2167 usleep(5 * 1000 /* usec */); // allow callback to use AudioOutput
2168 mLock.lock();
2169 continue;
2170 }
2171#endif
2172 }
2173
2174 Mutex::Autolock nextLock(mNextOutput->mLock);
2175
2176 // If the next output track is not NULL, then it has been
2177 // opened already for playback.
2178 // This is possible even without the next player being started,
2179 // for example, the next player could be prepared and seeked.
2180 //
2181 // Presuming it isn't advisable to force the track over.
2182 if (mNextOutput->mTrack == NULL) {
2183 ALOGD("Recycling track for gapless playback");
2184 delete mNextOutput->mCallbackData;
2185 mNextOutput->mCallbackData = mCallbackData;
2186 mNextOutput->mRecycledTrack = mTrack;
2187 mNextOutput->mSampleRateHz = mSampleRateHz;
2188 mNextOutput->mMsecsPerFrame = mMsecsPerFrame;
Andy Hungd1c74342015-07-07 16:54:23 -07002189 mNextOutput->mFlags = mFlags;
2190 mNextOutput->mFrameSize = mFrameSize;
2191 close_l();
2192 mCallbackData = NULL; // destruction handled by mNextOutput
2193 } else {
2194 ALOGW("Ignoring gapless playback because next player has already started");
2195 // remove track in case resource needed for future players.
2196 if (mCallbackData != NULL) {
2197 mCallbackData->endTrackSwitch(); // release lock for callbacks before close.
2198 }
2199 close_l();
2200 }
2201 }
2202 break;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002203 }
2204}
2205
Wei Jia7d3f4df2015-03-03 15:28:00 -08002206ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002207{
Andy Hungd1c74342015-07-07 16:54:23 -07002208 Mutex::Autolock lock(mLock);
Glenn Kastenadad3d72014-02-21 14:51:43 -08002209 LOG_ALWAYS_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
Andreas Huber20111aa2009-07-14 16:56:47 -07002210
Steve Block3856b092011-10-20 11:56:00 +01002211 //ALOGV("write(%p, %u)", buffer, size);
Glenn Kasten2799d742013-05-30 14:33:29 -07002212 if (mTrack != 0) {
Andy Hung2f6e73d2016-04-08 12:12:58 -07002213 return mTrack->write(buffer, size, blocking);
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07002214 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002215 return NO_INIT;
2216}
2217
2218void MediaPlayerService::AudioOutput::stop()
2219{
Steve Block3856b092011-10-20 11:56:00 +01002220 ALOGV("stop");
Andy Hungd1c74342015-07-07 16:54:23 -07002221 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002222 if (mTrack != 0) mTrack->stop();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002223}
2224
2225void MediaPlayerService::AudioOutput::flush()
2226{
Steve Block3856b092011-10-20 11:56:00 +01002227 ALOGV("flush");
Andy Hungd1c74342015-07-07 16:54:23 -07002228 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002229 if (mTrack != 0) mTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002230}
2231
2232void MediaPlayerService::AudioOutput::pause()
2233{
Steve Block3856b092011-10-20 11:56:00 +01002234 ALOGV("pause");
Andy Hungd1c74342015-07-07 16:54:23 -07002235 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002236 if (mTrack != 0) mTrack->pause();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002237}
2238
2239void MediaPlayerService::AudioOutput::close()
2240{
Steve Block3856b092011-10-20 11:56:00 +01002241 ALOGV("close");
Erik Wolsheimer7845a1f2015-10-30 12:07:52 -07002242 sp<AudioTrack> track;
2243 {
2244 Mutex::Autolock lock(mLock);
2245 track = mTrack;
2246 close_l(); // clears mTrack
2247 }
2248 // destruction of the track occurs outside of mutex.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002249}
2250
2251void MediaPlayerService::AudioOutput::setVolume(float left, float right)
2252{
Steve Block3856b092011-10-20 11:56:00 +01002253 ALOGV("setVolume(%f, %f)", left, right);
Andy Hungd1c74342015-07-07 16:54:23 -07002254 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002255 mLeftVolume = left;
2256 mRightVolume = right;
Glenn Kasten2799d742013-05-30 14:33:29 -07002257 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002258 mTrack->setVolume(left, right);
2259 }
2260}
2261
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002262status_t MediaPlayerService::AudioOutput::setPlaybackRate(const AudioPlaybackRate &rate)
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002263{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002264 ALOGV("setPlaybackRate(%f %f %d %d)",
2265 rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Andy Hungd1c74342015-07-07 16:54:23 -07002266 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002267 if (mTrack == 0) {
2268 // remember rate so that we can set it when the track is opened
2269 mPlaybackRate = rate;
2270 return OK;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002271 }
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002272 status_t res = mTrack->setPlaybackRate(rate);
2273 if (res != NO_ERROR) {
2274 return res;
2275 }
2276 // rate.mSpeed is always greater than 0 if setPlaybackRate succeeded
2277 CHECK_GT(rate.mSpeed, 0.f);
2278 mPlaybackRate = rate;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002279 if (mSampleRateHz != 0) {
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002280 mMsecsPerFrame = 1E3f / (rate.mSpeed * mSampleRateHz);
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002281 }
2282 return res;
2283}
2284
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002285status_t MediaPlayerService::AudioOutput::getPlaybackRate(AudioPlaybackRate *rate)
2286{
2287 ALOGV("setPlaybackRate");
Andy Hungd1c74342015-07-07 16:54:23 -07002288 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002289 if (mTrack == 0) {
2290 return NO_INIT;
2291 }
2292 *rate = mTrack->getPlaybackRate();
2293 return NO_ERROR;
2294}
2295
Eric Laurent2beeb502010-07-16 07:43:46 -07002296status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
2297{
Steve Block3856b092011-10-20 11:56:00 +01002298 ALOGV("setAuxEffectSendLevel(%f)", level);
Andy Hungd1c74342015-07-07 16:54:23 -07002299 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002300 mSendLevel = level;
Glenn Kasten2799d742013-05-30 14:33:29 -07002301 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002302 return mTrack->setAuxEffectSendLevel(level);
2303 }
2304 return NO_ERROR;
2305}
2306
2307status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
2308{
Steve Block3856b092011-10-20 11:56:00 +01002309 ALOGV("attachAuxEffect(%d)", effectId);
Andy Hungd1c74342015-07-07 16:54:23 -07002310 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002311 mAuxEffectId = effectId;
Glenn Kasten2799d742013-05-30 14:33:29 -07002312 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002313 return mTrack->attachAuxEffect(effectId);
2314 }
2315 return NO_ERROR;
2316}
2317
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002318VolumeShaper::Status MediaPlayerService::AudioOutput::applyVolumeShaper(
2319 const sp<VolumeShaper::Configuration>& configuration,
2320 const sp<VolumeShaper::Operation>& operation)
2321{
2322 Mutex::Autolock lock(mLock);
2323 ALOGV("AudioOutput::applyVolumeShaper");
Andy Hung4ef88d72017-02-21 19:47:53 -08002324
Andy Hung4ef88d72017-02-21 19:47:53 -08002325 mVolumeHandler->setIdIfNecessary(configuration);
Andy Hung39399b62017-04-21 15:07:45 -07002326
2327 VolumeShaper::Status status;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002328 if (mTrack != 0) {
Andy Hung39399b62017-04-21 15:07:45 -07002329 status = mTrack->applyVolumeShaper(configuration, operation);
2330 if (status >= 0) {
2331 (void)mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hungf3702642017-05-05 17:33:32 -07002332 if (mTrack->isPlaying()) { // match local AudioTrack to properly restore.
2333 mVolumeHandler->setStarted();
2334 }
Andy Hung39399b62017-04-21 15:07:45 -07002335 }
Andy Hung4ef88d72017-02-21 19:47:53 -08002336 } else {
Andy Hung39399b62017-04-21 15:07:45 -07002337 status = mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002338 }
Andy Hung39399b62017-04-21 15:07:45 -07002339 return status;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002340}
2341
2342sp<VolumeShaper::State> MediaPlayerService::AudioOutput::getVolumeShaperState(int id)
2343{
2344 Mutex::Autolock lock(mLock);
2345 if (mTrack != 0) {
2346 return mTrack->getVolumeShaperState(id);
Andy Hung4ef88d72017-02-21 19:47:53 -08002347 } else {
2348 return mVolumeHandler->getVolumeShaperState(id);
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002349 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002350}
2351
Andreas Huber20111aa2009-07-14 16:56:47 -07002352// static
2353void MediaPlayerService::AudioOutput::CallbackWrapper(
Glenn Kastend217a8c2011-06-01 15:20:35 -07002354 int event, void *cookie, void *info) {
Steve Block3856b092011-10-20 11:56:00 +01002355 //ALOGV("callbackwrapper");
Marco Nelissen6b74d672012-02-28 16:07:44 -08002356 CallbackData *data = (CallbackData*)cookie;
Andy Hungd1c74342015-07-07 16:54:23 -07002357 // lock to ensure we aren't caught in the middle of a track switch.
Marco Nelissen6b74d672012-02-28 16:07:44 -08002358 data->lock();
2359 AudioOutput *me = data->getOutput();
Andreas Huber20111aa2009-07-14 16:56:47 -07002360 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002361 if (me == NULL) {
2362 // no output set, likely because the track was scheduled to be reused
2363 // by another player, but the format turned out to be incompatible.
2364 data->unlock();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002365 if (buffer != NULL) {
2366 buffer->size = 0;
2367 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08002368 return;
2369 }
Andreas Huber20111aa2009-07-14 16:56:47 -07002370
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002371 switch(event) {
2372 case AudioTrack::EVENT_MORE_DATA: {
2373 size_t actualSize = (*me->mCallback)(
2374 me, buffer->raw, buffer->size, me->mCallbackCookie,
2375 CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002376
Andy Hung719b46b2015-05-31 22:18:25 -07002377 // Log when no data is returned from the callback.
2378 // (1) We may have no data (especially with network streaming sources).
2379 // (2) We may have reached the EOS and the audio track is not stopped yet.
2380 // Note that AwesomePlayer/AudioPlayer will only return zero size when it reaches the EOS.
2381 // NuPlayerRenderer will return zero when it doesn't have data (it doesn't block to fill).
2382 //
2383 // This is a benign busy-wait, with the next data request generated 10 ms or more later;
2384 // nevertheless for power reasons, we don't want to see too many of these.
Andreas Huber2e8ffaf2010-02-18 16:45:13 -08002385
Andy Hung719b46b2015-05-31 22:18:25 -07002386 ALOGV_IF(actualSize == 0 && buffer->size > 0, "callbackwrapper: empty buffer returned");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002387
2388 buffer->size = actualSize;
2389 } break;
2390
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002391 case AudioTrack::EVENT_STREAM_END:
Andy Hung719b46b2015-05-31 22:18:25 -07002392 // currently only occurs for offloaded callbacks
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002393 ALOGV("callbackwrapper: deliver EVENT_STREAM_END");
2394 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2395 me->mCallbackCookie, CB_EVENT_STREAM_END);
2396 break;
2397
2398 case AudioTrack::EVENT_NEW_IAUDIOTRACK :
2399 ALOGV("callbackwrapper: deliver EVENT_TEAR_DOWN");
2400 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2401 me->mCallbackCookie, CB_EVENT_TEAR_DOWN);
2402 break;
2403
Glenn Kasten421743b2015-06-01 08:18:08 -07002404 case AudioTrack::EVENT_UNDERRUN:
Andy Hung719b46b2015-05-31 22:18:25 -07002405 // This occurs when there is no data available, typically
Glenn Kasten421743b2015-06-01 08:18:08 -07002406 // when there is a failure to supply data to the AudioTrack. It can also
2407 // occur in non-offloaded mode when the audio device comes out of standby.
2408 //
Andy Hung719b46b2015-05-31 22:18:25 -07002409 // If an AudioTrack underruns it outputs silence. Since this happens suddenly
2410 // it may sound like an audible pop or glitch.
2411 //
2412 // The underrun event is sent once per track underrun; the condition is reset
2413 // when more data is sent to the AudioTrack.
Eric Laurente93cc032016-05-05 10:15:10 -07002414 ALOGD("callbackwrapper: EVENT_UNDERRUN (discarded)");
Glenn Kasten421743b2015-06-01 08:18:08 -07002415 break;
2416
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002417 default:
2418 ALOGE("received unknown event type: %d inside CallbackWrapper !", event);
Andreas Huber51c1e0e2011-04-04 11:43:40 -07002419 }
2420
Marco Nelissen6b74d672012-02-28 16:07:44 -08002421 data->unlock();
Andreas Huber20111aa2009-07-14 16:56:47 -07002422}
2423
Glenn Kastend848eb42016-03-08 13:42:11 -08002424audio_session_t MediaPlayerService::AudioOutput::getSessionId() const
Eric Laurent8c563ed2010-10-07 18:23:03 -07002425{
Andy Hungd1c74342015-07-07 16:54:23 -07002426 Mutex::Autolock lock(mLock);
Eric Laurent8c563ed2010-10-07 18:23:03 -07002427 return mSessionId;
2428}
2429
Eric Laurent6f59db12013-07-26 17:16:50 -07002430uint32_t MediaPlayerService::AudioOutput::getSampleRate() const
2431{
Andy Hungd1c74342015-07-07 16:54:23 -07002432 Mutex::Autolock lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -07002433 if (mTrack == 0) return 0;
2434 return mTrack->getSampleRate();
2435}
2436
Andy Hungf2c87b32016-04-07 19:49:29 -07002437int64_t MediaPlayerService::AudioOutput::getBufferDurationInUs() const
2438{
2439 Mutex::Autolock lock(mLock);
2440 if (mTrack == 0) {
2441 return 0;
2442 }
2443 int64_t duration;
2444 if (mTrack->getBufferDurationInUs(&duration) != OK) {
2445 return 0;
2446 }
2447 return duration;
2448}
2449
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002450////////////////////////////////////////////////////////////////////////////////
2451
2452struct CallbackThread : public Thread {
2453 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
2454 MediaPlayerBase::AudioSink::AudioCallback cb,
2455 void *cookie);
2456
2457protected:
2458 virtual ~CallbackThread();
2459
2460 virtual bool threadLoop();
2461
2462private:
2463 wp<MediaPlayerBase::AudioSink> mSink;
2464 MediaPlayerBase::AudioSink::AudioCallback mCallback;
2465 void *mCookie;
2466 void *mBuffer;
2467 size_t mBufferSize;
2468
2469 CallbackThread(const CallbackThread &);
2470 CallbackThread &operator=(const CallbackThread &);
2471};
2472
2473CallbackThread::CallbackThread(
2474 const wp<MediaPlayerBase::AudioSink> &sink,
2475 MediaPlayerBase::AudioSink::AudioCallback cb,
2476 void *cookie)
2477 : mSink(sink),
2478 mCallback(cb),
2479 mCookie(cookie),
2480 mBuffer(NULL),
2481 mBufferSize(0) {
2482}
2483
2484CallbackThread::~CallbackThread() {
2485 if (mBuffer) {
2486 free(mBuffer);
2487 mBuffer = NULL;
2488 }
2489}
2490
2491bool CallbackThread::threadLoop() {
2492 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
2493 if (sink == NULL) {
2494 return false;
2495 }
2496
2497 if (mBuffer == NULL) {
2498 mBufferSize = sink->bufferSize();
2499 mBuffer = malloc(mBufferSize);
2500 }
2501
2502 size_t actualSize =
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002503 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie,
2504 MediaPlayerBase::AudioSink::CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002505
2506 if (actualSize > 0) {
2507 sink->write(mBuffer, actualSize);
Andy Hunga31335a2014-08-20 17:37:59 -07002508 // Could return false on sink->write() error or short count.
2509 // Not necessarily appropriate but would work for AudioCache behavior.
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002510 }
2511
2512 return true;
2513}
2514
2515////////////////////////////////////////////////////////////////////////////////
2516
Chong Zhange5b9b692017-05-11 11:44:56 -07002517void MediaPlayerService::addBatteryData(uint32_t params) {
2518 mBatteryTracker.addBatteryData(params);
2519}
2520
2521status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
2522 return mBatteryTracker.pullBatteryData(reply);
2523}
2524
2525MediaPlayerService::BatteryTracker::BatteryTracker() {
2526 mBatteryAudio.refCount = 0;
2527 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2528 mBatteryAudio.deviceOn[i] = 0;
2529 mBatteryAudio.lastTime[i] = 0;
2530 mBatteryAudio.totalTime[i] = 0;
2531 }
2532 // speaker is on by default
2533 mBatteryAudio.deviceOn[SPEAKER] = 1;
2534
2535 // reset battery stats
2536 // if the mediaserver has crashed, battery stats could be left
2537 // in bad state, reset the state upon service start.
2538 BatteryNotifier::getInstance().noteResetVideo();
2539}
2540
2541void MediaPlayerService::BatteryTracker::addBatteryData(uint32_t params)
Gloria Wang7cf180c2011-02-19 18:37:57 -08002542{
2543 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002544
2545 int32_t time = systemTime() / 1000000L;
2546
2547 // change audio output devices. This notification comes from AudioFlinger
2548 if ((params & kBatteryDataSpeakerOn)
2549 || (params & kBatteryDataOtherAudioDeviceOn)) {
2550
2551 int deviceOn[NUM_AUDIO_DEVICES];
2552 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2553 deviceOn[i] = 0;
2554 }
2555
2556 if ((params & kBatteryDataSpeakerOn)
2557 && (params & kBatteryDataOtherAudioDeviceOn)) {
2558 deviceOn[SPEAKER_AND_OTHER] = 1;
2559 } else if (params & kBatteryDataSpeakerOn) {
2560 deviceOn[SPEAKER] = 1;
2561 } else {
2562 deviceOn[OTHER_AUDIO_DEVICE] = 1;
2563 }
2564
2565 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2566 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
2567
2568 if (mBatteryAudio.refCount > 0) { // if playing audio
2569 if (!deviceOn[i]) {
2570 mBatteryAudio.lastTime[i] += time;
2571 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2572 mBatteryAudio.lastTime[i] = 0;
2573 } else {
2574 mBatteryAudio.lastTime[i] = 0 - time;
2575 }
2576 }
2577
2578 mBatteryAudio.deviceOn[i] = deviceOn[i];
2579 }
2580 }
2581 return;
2582 }
2583
Marco Nelissenb7848f12014-12-04 08:57:56 -08002584 // an audio stream is started
Gloria Wang9ee159b2011-02-24 14:51:45 -08002585 if (params & kBatteryDataAudioFlingerStart) {
2586 // record the start time only if currently no other audio
2587 // is being played
2588 if (mBatteryAudio.refCount == 0) {
2589 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2590 if (mBatteryAudio.deviceOn[i]) {
2591 mBatteryAudio.lastTime[i] -= time;
2592 }
2593 }
2594 }
2595
2596 mBatteryAudio.refCount ++;
2597 return;
2598
2599 } else if (params & kBatteryDataAudioFlingerStop) {
2600 if (mBatteryAudio.refCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002601 ALOGW("Battery track warning: refCount is <= 0");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002602 return;
2603 }
2604
2605 // record the stop time only if currently this is the only
2606 // audio being played
2607 if (mBatteryAudio.refCount == 1) {
2608 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2609 if (mBatteryAudio.deviceOn[i]) {
2610 mBatteryAudio.lastTime[i] += time;
2611 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2612 mBatteryAudio.lastTime[i] = 0;
2613 }
2614 }
2615 }
2616
2617 mBatteryAudio.refCount --;
2618 return;
2619 }
2620
Andy Hung1afd0982016-11-08 16:13:44 -08002621 uid_t uid = IPCThreadState::self()->getCallingUid();
Gloria Wang7cf180c2011-02-19 18:37:57 -08002622 if (uid == AID_MEDIA) {
2623 return;
2624 }
2625 int index = mBatteryData.indexOfKey(uid);
Gloria Wang7cf180c2011-02-19 18:37:57 -08002626
2627 if (index < 0) { // create a new entry for this UID
2628 BatteryUsageInfo info;
2629 info.audioTotalTime = 0;
2630 info.videoTotalTime = 0;
2631 info.audioLastTime = 0;
2632 info.videoLastTime = 0;
2633 info.refCount = 0;
2634
Gloria Wang9ee159b2011-02-24 14:51:45 -08002635 if (mBatteryData.add(uid, info) == NO_MEMORY) {
Steve Block29357bc2012-01-06 19:20:56 +00002636 ALOGE("Battery track error: no memory for new app");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002637 return;
2638 }
Gloria Wang7cf180c2011-02-19 18:37:57 -08002639 }
2640
2641 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
2642
2643 if (params & kBatteryDataCodecStarted) {
2644 if (params & kBatteryDataTrackAudio) {
2645 info.audioLastTime -= time;
2646 info.refCount ++;
2647 }
2648 if (params & kBatteryDataTrackVideo) {
2649 info.videoLastTime -= time;
2650 info.refCount ++;
2651 }
2652 } else {
2653 if (info.refCount == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002654 ALOGW("Battery track warning: refCount is already 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002655 return;
2656 } else if (info.refCount < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00002657 ALOGE("Battery track error: refCount < 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002658 mBatteryData.removeItem(uid);
2659 return;
2660 }
2661
2662 if (params & kBatteryDataTrackAudio) {
2663 info.audioLastTime += time;
2664 info.refCount --;
2665 }
2666 if (params & kBatteryDataTrackVideo) {
2667 info.videoLastTime += time;
2668 info.refCount --;
2669 }
2670
2671 // no stream is being played by this UID
2672 if (info.refCount == 0) {
2673 info.audioTotalTime += info.audioLastTime;
2674 info.audioLastTime = 0;
2675 info.videoTotalTime += info.videoLastTime;
2676 info.videoLastTime = 0;
2677 }
2678 }
2679}
2680
Chong Zhange5b9b692017-05-11 11:44:56 -07002681status_t MediaPlayerService::BatteryTracker::pullBatteryData(Parcel* reply) {
Gloria Wang7cf180c2011-02-19 18:37:57 -08002682 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002683
2684 // audio output devices usage
2685 int32_t time = systemTime() / 1000000L; //in ms
2686 int32_t totalTime;
2687
2688 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2689 totalTime = mBatteryAudio.totalTime[i];
2690
2691 if (mBatteryAudio.deviceOn[i]
2692 && (mBatteryAudio.lastTime[i] != 0)) {
2693 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
2694 totalTime += tmpTime;
2695 }
2696
2697 reply->writeInt32(totalTime);
2698 // reset the total time
2699 mBatteryAudio.totalTime[i] = 0;
2700 }
2701
2702 // codec usage
Gloria Wang7cf180c2011-02-19 18:37:57 -08002703 BatteryUsageInfo info;
2704 int size = mBatteryData.size();
2705
2706 reply->writeInt32(size);
2707 int i = 0;
2708
2709 while (i < size) {
2710 info = mBatteryData.valueAt(i);
2711
2712 reply->writeInt32(mBatteryData.keyAt(i)); //UID
2713 reply->writeInt32(info.audioTotalTime);
2714 reply->writeInt32(info.videoTotalTime);
2715
2716 info.audioTotalTime = 0;
2717 info.videoTotalTime = 0;
2718
2719 // remove the UID entry where no stream is being played
2720 if (info.refCount <= 0) {
2721 mBatteryData.removeItemsAt(i);
2722 size --;
2723 i --;
2724 }
2725 i++;
2726 }
2727 return NO_ERROR;
2728}
nikoa64c8c72009-07-20 15:07:26 -07002729} // namespace android