blob: d50e10e14096282099c19048015c001ab4682207 [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
Pawin Vongmasa255735a2017-07-19 11:24:56 -070080#include <media/stagefright/omx/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;
Ivan Lozano8cf3a072017-08-09 09:01:33 -070096using android::media::VolumeShaper;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070097
98// Max number of entries in the filter.
99const int kMaxFilterSize = 64; // I pulled that out of thin air.
100
Andy Hungff874dc2016-04-11 16:49:09 -0700101const float kMaxRequiredSpeed = 8.0f; // for PCM tracks allow up to 8x speedup.
102
nikoa64c8c72009-07-20 15:07:26 -0700103// FIXME: Move all the metadata related function in the Metadata.cpp
nikod608a812009-07-16 16:39:53 -0700104
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700105
106// Unmarshall a filter from a Parcel.
107// Filter format in a parcel:
108//
109// 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
110// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
111// | number of entries (n) |
112// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
113// | metadata type 1 |
114// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
115// | metadata type 2 |
116// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
117// ....
118// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
119// | metadata type n |
120// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
121//
122// @param p Parcel that should start with a filter.
123// @param[out] filter On exit contains the list of metadata type to be
124// filtered.
125// @param[out] status On exit contains the status code to be returned.
126// @return true if the parcel starts with a valid filter.
127bool unmarshallFilter(const Parcel& p,
nikoa64c8c72009-07-20 15:07:26 -0700128 Metadata::Filter *filter,
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700129 status_t *status)
130{
Nicolas Catania48290382009-07-10 13:53:06 -0700131 int32_t val;
132 if (p.readInt32(&val) != OK)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700133 {
Steve Block29357bc2012-01-06 19:20:56 +0000134 ALOGE("Failed to read filter's length");
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700135 *status = NOT_ENOUGH_DATA;
136 return false;
137 }
138
Nicolas Catania48290382009-07-10 13:53:06 -0700139 if( val > kMaxFilterSize || val < 0)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700140 {
Steve Block29357bc2012-01-06 19:20:56 +0000141 ALOGE("Invalid filter len %d", val);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700142 *status = BAD_VALUE;
143 return false;
144 }
145
Nicolas Catania48290382009-07-10 13:53:06 -0700146 const size_t num = val;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700147
148 filter->clear();
Nicolas Catania48290382009-07-10 13:53:06 -0700149 filter->setCapacity(num);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700150
nikoa64c8c72009-07-20 15:07:26 -0700151 size_t size = num * sizeof(Metadata::Type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700152
Nicolas Catania48290382009-07-10 13:53:06 -0700153
154 if (p.dataAvail() < size)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700155 {
Andy Hung833b4752016-04-04 17:15:48 -0700156 ALOGE("Filter too short expected %zu but got %zu", size, p.dataAvail());
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700157 *status = NOT_ENOUGH_DATA;
158 return false;
159 }
160
nikoa64c8c72009-07-20 15:07:26 -0700161 const Metadata::Type *data =
162 static_cast<const Metadata::Type*>(p.readInplace(size));
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700163
Nicolas Catania48290382009-07-10 13:53:06 -0700164 if (NULL == data)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700165 {
Steve Block29357bc2012-01-06 19:20:56 +0000166 ALOGE("Filter had no data");
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700167 *status = BAD_VALUE;
168 return false;
169 }
170
171 // TODO: The stl impl of vector would be more efficient here
172 // because it degenerates into a memcpy on pod types. Try to
173 // replace later or use stl::set.
Nicolas Catania48290382009-07-10 13:53:06 -0700174 for (size_t i = 0; i < num; ++i)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700175 {
Nicolas Catania48290382009-07-10 13:53:06 -0700176 filter->add(*data);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700177 ++data;
178 }
179 *status = OK;
180 return true;
181}
182
Nicolas Catania48290382009-07-10 13:53:06 -0700183// @param filter Of metadata type.
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700184// @param val To be searched.
185// @return true if a match was found.
nikoa64c8c72009-07-20 15:07:26 -0700186bool findMetadata(const Metadata::Filter& filter, const int32_t val)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700187{
188 // Deal with empty and ANY right away
189 if (filter.isEmpty()) return false;
nikoa64c8c72009-07-20 15:07:26 -0700190 if (filter[0] == Metadata::kAny) return true;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700191
Nicolas Catania48290382009-07-10 13:53:06 -0700192 return filter.indexOf(val) >= 0;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700193}
194
195} // anonymous namespace
196
197
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700198namespace {
199using android::Parcel;
200using android::String16;
201
202// marshalling tag indicating flattened utf16 tags
203// keep in sync with frameworks/base/media/java/android/media/AudioAttributes.java
204const int32_t kAudioAttributesMarshallTagFlattenTags = 1;
205
206// Audio attributes format in a parcel:
207//
208// 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
209// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
210// | usage |
211// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
212// | content_type |
213// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Hyejin Kim4f418f92014-09-05 15:50:03 +0900214// | source |
215// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700216// | flags |
217// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
218// | kAudioAttributesMarshallTagFlattenTags | // ignore tags if not found
219// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
220// | flattened tags in UTF16 |
221// | ... |
222// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
223//
224// @param p Parcel that contains audio attributes.
225// @param[out] attributes On exit points to an initialized audio_attributes_t structure
226// @param[out] status On exit contains the status code to be returned.
227void unmarshallAudioAttributes(const Parcel& parcel, audio_attributes_t *attributes)
228{
229 attributes->usage = (audio_usage_t) parcel.readInt32();
230 attributes->content_type = (audio_content_type_t) parcel.readInt32();
Hyejin Kim4f418f92014-09-05 15:50:03 +0900231 attributes->source = (audio_source_t) parcel.readInt32();
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700232 attributes->flags = (audio_flags_mask_t) parcel.readInt32();
233 const bool hasFlattenedTag = (parcel.readInt32() == kAudioAttributesMarshallTagFlattenTags);
234 if (hasFlattenedTag) {
235 // the tags are UTF16, convert to UTF8
236 String16 tags = parcel.readString16();
237 ssize_t realTagSize = utf16_to_utf8_length(tags.string(), tags.size());
238 if (realTagSize <= 0) {
239 strcpy(attributes->tags, "");
240 } else {
241 // copy the flattened string into the attributes as the destination for the conversion:
242 // copying array size -1, array for tags was calloc'd, no need to NULL-terminate it
243 size_t tagSize = realTagSize > AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 ?
244 AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 : realTagSize;
Sergio Giro1d3f4272016-06-28 18:24:52 +0100245 utf16_to_utf8(tags.string(), tagSize, attributes->tags,
246 sizeof(attributes->tags) / sizeof(attributes->tags[0]));
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700247 }
248 } else {
249 ALOGE("unmarshallAudioAttributes() received unflattened tags, ignoring tag values");
250 strcpy(attributes->tags, "");
251 }
252}
253} // anonymous namespace
254
255
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800256namespace android {
257
Marco Nelissenf09611f2015-02-13 14:12:42 -0800258extern ALooperRoster gLooperRoster;
259
260
Dave Burked681bbb2011-08-30 14:39:17 +0100261static bool checkPermission(const char* permissionString) {
Dave Burked681bbb2011-08-30 14:39:17 +0100262 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
263 bool ok = checkCallingPermission(String16(permissionString));
Steve Block29357bc2012-01-06 19:20:56 +0000264 if (!ok) ALOGE("Request requires %s", permissionString);
Dave Burked681bbb2011-08-30 14:39:17 +0100265 return ok;
266}
267
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800268// 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 -0800269/* static */ int MediaPlayerService::AudioOutput::mMinBufferCount = 4;
270/* static */ bool MediaPlayerService::AudioOutput::mIsOnEmulator = false;
271
272void MediaPlayerService::instantiate() {
273 defaultServiceManager()->addService(
274 String16("media.player"), new MediaPlayerService());
275}
276
277MediaPlayerService::MediaPlayerService()
278{
Steve Block3856b092011-10-20 11:56:00 +0100279 ALOGV("MediaPlayerService created");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800280 mNextConnId = 1;
Gloria Wang9ee159b2011-02-24 14:51:45 -0800281
John Grossman44a7e422012-06-21 17:29:24 -0700282 MediaPlayerFactory::registerBuiltinFactories();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800283}
284
285MediaPlayerService::~MediaPlayerService()
286{
Steve Block3856b092011-10-20 11:56:00 +0100287 ALOGV("MediaPlayerService destroyed");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800288}
289
Svet Ganovbe71aa22015-04-28 12:06:02 -0700290sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(const String16 &opPackageName)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800291{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800292 pid_t pid = IPCThreadState::self()->getCallingPid();
Svet Ganovbe71aa22015-04-28 12:06:02 -0700293 sp<MediaRecorderClient> recorder = new MediaRecorderClient(this, pid, opPackageName);
Gloria Wangdac6a312009-10-29 15:46:37 -0700294 wp<MediaRecorderClient> w = recorder;
295 Mutex::Autolock lock(mLock);
296 mMediaRecorderClients.add(w);
Steve Block3856b092011-10-20 11:56:00 +0100297 ALOGV("Create new media recorder client from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800298 return recorder;
299}
300
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -0700301void MediaPlayerService::removeMediaRecorderClient(const wp<MediaRecorderClient>& client)
Gloria Wangdac6a312009-10-29 15:46:37 -0700302{
303 Mutex::Autolock lock(mLock);
304 mMediaRecorderClients.remove(client);
Steve Block3856b092011-10-20 11:56:00 +0100305 ALOGV("Delete media recorder client");
Gloria Wangdac6a312009-10-29 15:46:37 -0700306}
307
Glenn Kastenf37971f2012-02-03 11:06:53 -0800308sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800309{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800310 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800311 sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
Steve Block3856b092011-10-20 11:56:00 +0100312 ALOGV("Create new media retriever from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800313 return retriever;
314}
315
Glenn Kastenf37971f2012-02-03 11:06:53 -0800316sp<IMediaPlayer> MediaPlayerService::create(const sp<IMediaPlayerClient>& client,
Glenn Kastend848eb42016-03-08 13:42:11 -0800317 audio_session_t audioSessionId)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800318{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800319 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800320 int32_t connId = android_atomic_inc(&mNextConnId);
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700321
322 sp<Client> c = new Client(
323 this, pid, connId, client, audioSessionId,
324 IPCThreadState::self()->getCallingUid());
325
Steve Block3856b092011-10-20 11:56:00 +0100326 ALOGV("Create new client(%d) from pid %d, uid %d, ", connId, pid,
Dave Burked681bbb2011-08-30 14:39:17 +0100327 IPCThreadState::self()->getCallingUid());
328
329 wp<Client> w = c;
330 {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800331 Mutex::Autolock lock(mLock);
332 mClients.add(w);
333 }
Andreas Hubere2b10282010-11-23 11:41:34 -0800334 return c;
335}
336
Lajos Molnar1381d4b2014-08-07 15:18:35 -0700337sp<IMediaCodecList> MediaPlayerService::getCodecList() const {
338 return MediaCodecList::getLocalInstance();
339}
340
Marco Nelissen260e56c2016-01-28 21:41:25 +0000341sp<IOMX> MediaPlayerService::getOMX() {
Marco Nelissen1900e772016-02-02 16:12:16 -0800342 ALOGI("MediaPlayerService::getOMX");
Marco Nelissen260e56c2016-01-28 21:41:25 +0000343 Mutex::Autolock autoLock(mLock);
344
345 if (mOMX.get() == NULL) {
346 mOMX = new OMX;
347 }
348
349 return mOMX;
350}
351
Andreas Huber279dcd82013-01-30 10:41:25 -0800352sp<IHDCP> MediaPlayerService::makeHDCP(bool createEncryptionModule) {
353 return new HDCP(createEncryptionModule);
Andreas Huber59451f82012-09-18 10:36:32 -0700354}
355
Jeff Brown2013a542012-09-04 21:38:42 -0700356sp<IRemoteDisplay> MediaPlayerService::listenForRemoteDisplay(
Svet Ganovbe71aa22015-04-28 12:06:02 -0700357 const String16 &opPackageName,
Jeff Brown2013a542012-09-04 21:38:42 -0700358 const sp<IRemoteDisplayClient>& client, const String8& iface) {
Jeff Brownaba33d52012-09-07 17:38:58 -0700359 if (!checkPermission("android.permission.CONTROL_WIFI_DISPLAY")) {
360 return NULL;
361 }
362
Svet Ganovbe71aa22015-04-28 12:06:02 -0700363 return new RemoteDisplay(opPackageName, client, iface.string());
Jeff Brown2013a542012-09-04 21:38:42 -0700364}
365
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800366status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
367{
368 const size_t SIZE = 256;
369 char buffer[SIZE];
370 String8 result;
371
372 result.append(" AudioOutput\n");
373 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n",
374 mStreamType, mLeftVolume, mRightVolume);
375 result.append(buffer);
376 snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n",
Eric Laurentdb354e52012-03-05 17:27:11 -0800377 mMsecsPerFrame, (mTrack != 0) ? mTrack->latency() : -1);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800378 result.append(buffer);
Eric Laurent2beeb502010-07-16 07:43:46 -0700379 snprintf(buffer, 255, " aux effect id(%d), send level (%f)\n",
380 mAuxEffectId, mSendLevel);
381 result.append(buffer);
382
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800383 ::write(fd, result.string(), result.size());
384 if (mTrack != 0) {
385 mTrack->dump(fd, args);
386 }
387 return NO_ERROR;
388}
389
Lajos Molnar6d339f12015-04-17 16:15:53 -0700390status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800391{
392 const size_t SIZE = 256;
393 char buffer[SIZE];
394 String8 result;
395 result.append(" Client\n");
396 snprintf(buffer, 255, " pid(%d), connId(%d), status(%d), looping(%s)\n",
397 mPid, mConnId, mStatus, mLoop?"true": "false");
398 result.append(buffer);
Wei Jia502c2f42017-07-13 17:47:56 -0700399
400 sp<MediaPlayerBase> p;
401 sp<AudioOutput> audioOutput;
402 bool locked = false;
403 for (int i = 0; i < kDumpLockRetries; ++i) {
404 if (mLock.tryLock() == NO_ERROR) {
405 locked = true;
406 break;
407 }
408 usleep(kDumpLockSleepUs);
Andreas Hubera0b1d4b2011-06-07 15:52:25 -0700409 }
Wei Jia502c2f42017-07-13 17:47:56 -0700410
411 if (locked) {
412 p = mPlayer;
413 audioOutput = mAudioOutput;
414 mLock.unlock();
415 } else {
416 result.append(" lock is taken, no dump from player and audio output\n");
417 }
418 write(fd, result.string(), result.size());
419
420 if (p != NULL) {
421 p->dump(fd, args);
422 }
423 if (audioOutput != 0) {
424 audioOutput->dump(fd, args);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800425 }
426 write(fd, "\n", 1);
427 return NO_ERROR;
428}
429
Marco Nelissenf09611f2015-02-13 14:12:42 -0800430/**
431 * The only arguments this understands right now are -c, -von and -voff,
432 * which are parsed by ALooperRoster::dump()
433 */
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800434status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
435{
436 const size_t SIZE = 256;
437 char buffer[SIZE];
438 String8 result;
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530439 SortedVector< sp<Client> > clients; //to serialise the mutex unlock & client destruction.
440 SortedVector< sp<MediaRecorderClient> > mediaRecorderClients;
441
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800442 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
443 snprintf(buffer, SIZE, "Permission Denial: "
444 "can't dump MediaPlayerService from pid=%d, uid=%d\n",
445 IPCThreadState::self()->getCallingPid(),
446 IPCThreadState::self()->getCallingUid());
447 result.append(buffer);
448 } else {
449 Mutex::Autolock lock(mLock);
450 for (int i = 0, n = mClients.size(); i < n; ++i) {
451 sp<Client> c = mClients[i].promote();
452 if (c != 0) c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530453 clients.add(c);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800454 }
James Dongb9141222010-07-08 11:16:11 -0700455 if (mMediaRecorderClients.size() == 0) {
456 result.append(" No media recorder client\n\n");
457 } else {
458 for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
459 sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
James Donge579e282011-10-18 22:29:20 -0700460 if (c != 0) {
461 snprintf(buffer, 255, " MediaRecorderClient pid(%d)\n", c->mPid);
462 result.append(buffer);
463 write(fd, result.string(), result.size());
464 result = "\n";
465 c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530466 mediaRecorderClients.add(c);
James Donge579e282011-10-18 22:29:20 -0700467 }
James Dongb9141222010-07-08 11:16:11 -0700468 }
Gloria Wangdac6a312009-10-29 15:46:37 -0700469 }
470
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800471 result.append(" Files opened and/or mapped:\n");
Marco Nelissenf09611f2015-02-13 14:12:42 -0800472 snprintf(buffer, SIZE, "/proc/%d/maps", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800473 FILE *f = fopen(buffer, "r");
474 if (f) {
475 while (!feof(f)) {
476 fgets(buffer, SIZE, f);
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700477 if (strstr(buffer, " /storage/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800478 strstr(buffer, " /system/sounds/") ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700479 strstr(buffer, " /data/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800480 strstr(buffer, " /system/media/")) {
481 result.append(" ");
482 result.append(buffer);
483 }
484 }
485 fclose(f);
486 } else {
487 result.append("couldn't open ");
488 result.append(buffer);
489 result.append("\n");
490 }
491
Marco Nelissenf09611f2015-02-13 14:12:42 -0800492 snprintf(buffer, SIZE, "/proc/%d/fd", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800493 DIR *d = opendir(buffer);
494 if (d) {
495 struct dirent *ent;
496 while((ent = readdir(d)) != NULL) {
497 if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
Marco Nelissenf09611f2015-02-13 14:12:42 -0800498 snprintf(buffer, SIZE, "/proc/%d/fd/%s", getpid(), ent->d_name);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800499 struct stat s;
500 if (lstat(buffer, &s) == 0) {
501 if ((s.st_mode & S_IFMT) == S_IFLNK) {
502 char linkto[256];
503 int len = readlink(buffer, linkto, sizeof(linkto));
504 if(len > 0) {
505 if(len > 255) {
506 linkto[252] = '.';
507 linkto[253] = '.';
508 linkto[254] = '.';
509 linkto[255] = 0;
510 } else {
511 linkto[len] = 0;
512 }
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700513 if (strstr(linkto, "/storage/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800514 strstr(linkto, "/system/sounds/") == linkto ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700515 strstr(linkto, "/data/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800516 strstr(linkto, "/system/media/") == linkto) {
517 result.append(" ");
518 result.append(buffer);
519 result.append(" -> ");
520 result.append(linkto);
521 result.append("\n");
522 }
523 }
524 } else {
525 result.append(" unexpected type for ");
526 result.append(buffer);
527 result.append("\n");
528 }
529 }
530 }
531 }
532 closedir(d);
533 } else {
534 result.append("couldn't open ");
535 result.append(buffer);
536 result.append("\n");
537 }
538
Marco Nelissenf09611f2015-02-13 14:12:42 -0800539 gLooperRoster.dump(fd, args);
540
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800541 bool dumpMem = false;
Andy Hung53541292016-04-13 16:48:51 -0700542 bool unreachableMemory = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800543 for (size_t i = 0; i < args.size(); i++) {
544 if (args[i] == String16("-m")) {
545 dumpMem = true;
Andy Hung53541292016-04-13 16:48:51 -0700546 } else if (args[i] == String16("--unreachable")) {
547 unreachableMemory = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800548 }
549 }
550 if (dumpMem) {
Andy Hung07b745e2016-05-23 16:21:07 -0700551 result.append("\nDumping memory:\n");
552 std::string s = dumpMemoryAddresses(100 /* limit */);
553 result.append(s.c_str(), s.size());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800554 }
Andy Hung53541292016-04-13 16:48:51 -0700555 if (unreachableMemory) {
556 result.append("\nDumping unreachable memory:\n");
557 // TODO - should limit be an argument parameter?
558 std::string s = GetUnreachableMemoryString(true /* contents */, 10000 /* limit */);
559 result.append(s.c_str(), s.size());
560 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800561 }
562 write(fd, result.string(), result.size());
563 return NO_ERROR;
564}
565
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -0700566void MediaPlayerService::removeClient(const wp<Client>& client)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800567{
568 Mutex::Autolock lock(mLock);
569 mClients.remove(client);
570}
571
Robert Shihee0a0e32016-08-16 16:50:54 -0700572bool MediaPlayerService::hasClient(wp<Client> client)
573{
574 Mutex::Autolock lock(mLock);
575 return mClients.indexOf(client) != NAME_NOT_FOUND;
576}
577
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700578MediaPlayerService::Client::Client(
579 const sp<MediaPlayerService>& service, pid_t pid,
580 int32_t connId, const sp<IMediaPlayerClient>& client,
Glenn Kastend848eb42016-03-08 13:42:11 -0800581 audio_session_t audioSessionId, uid_t uid)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800582{
Steve Block3856b092011-10-20 11:56:00 +0100583 ALOGV("Client(%d) constructor", connId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800584 mPid = pid;
585 mConnId = connId;
586 mService = service;
587 mClient = client;
588 mLoop = false;
589 mStatus = NO_INIT;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700590 mAudioSessionId = audioSessionId;
Andy Hung1afd0982016-11-08 16:13:44 -0800591 mUid = uid;
John Grossmanc795b642012-02-22 15:38:35 -0800592 mRetransmitEndpointValid = false;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700593 mAudioAttributes = NULL;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700594
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800595#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000596 ALOGD("create Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800597 mAntagonizer = new Antagonizer(notify, this);
598#endif
599}
600
601MediaPlayerService::Client::~Client()
602{
Steve Block3856b092011-10-20 11:56:00 +0100603 ALOGV("Client(%d) destructor pid = %d", mConnId, mPid);
Wei Jia502c2f42017-07-13 17:47:56 -0700604 {
605 Mutex::Autolock l(mLock);
606 mAudioOutput.clear();
607 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800608 wp<Client> client(this);
609 disconnect();
610 mService->removeClient(client);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700611 if (mAudioAttributes != NULL) {
612 free(mAudioAttributes);
613 }
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800614 clearDeathNotifiers();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800615}
616
617void MediaPlayerService::Client::disconnect()
618{
Steve Block3856b092011-10-20 11:56:00 +0100619 ALOGV("disconnect(%d) from pid %d", mConnId, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800620 // grab local reference and clear main reference to prevent future
621 // access to object
622 sp<MediaPlayerBase> p;
623 {
624 Mutex::Autolock l(mLock);
625 p = mPlayer;
beanzdcfefde2012-11-05 09:51:43 +0800626 mClient.clear();
Wei Jia502c2f42017-07-13 17:47:56 -0700627 mPlayer.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800628 }
Andreas Huber20111aa2009-07-14 16:56:47 -0700629
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800630 // clear the notification to prevent callbacks to dead client
631 // and reset the player. We assume the player will serialize
632 // access to itself if necessary.
633 if (p != 0) {
634 p->setNotifyCallback(0, 0);
635#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000636 ALOGD("kill Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800637 mAntagonizer->kill();
638#endif
639 p->reset();
640 }
641
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700642 disconnectNativeWindow();
643
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800644 IPCThreadState::self()->flushCommands();
645}
646
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800647sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
648{
649 // determine if we have the right player type
Wei Jia502c2f42017-07-13 17:47:56 -0700650 sp<MediaPlayerBase> p = getPlayer();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800651 if ((p != NULL) && (p->playerType() != playerType)) {
Steve Block3856b092011-10-20 11:56:00 +0100652 ALOGV("delete player");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800653 p.clear();
654 }
655 if (p == NULL) {
Ronghua Wu68845c12015-07-21 09:50:48 -0700656 p = MediaPlayerFactory::createPlayer(playerType, this, notify, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800657 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700658
Jason Simmonsdb29e522011-08-12 13:46:55 -0700659 if (p != NULL) {
Andy Hung1afd0982016-11-08 16:13:44 -0800660 p->setUID(mUid);
Jason Simmonsdb29e522011-08-12 13:46:55 -0700661 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700662
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800663 return p;
664}
665
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700666MediaPlayerService::Client::ServiceDeathNotifier::ServiceDeathNotifier(
667 const sp<IBinder>& service,
668 const sp<MediaPlayerBase>& listener,
669 int which) {
670 mService = service;
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800671 mOmx = nullptr;
672 mListener = listener;
673 mWhich = which;
674}
675
676MediaPlayerService::Client::ServiceDeathNotifier::ServiceDeathNotifier(
677 const sp<IOmx>& omx,
678 const sp<MediaPlayerBase>& listener,
679 int which) {
680 mService = nullptr;
681 mOmx = omx;
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700682 mListener = listener;
683 mWhich = which;
684}
685
686MediaPlayerService::Client::ServiceDeathNotifier::~ServiceDeathNotifier() {
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700687}
688
689void MediaPlayerService::Client::ServiceDeathNotifier::binderDied(const wp<IBinder>& /*who*/) {
690 sp<MediaPlayerBase> listener = mListener.promote();
691 if (listener != NULL) {
692 listener->sendEvent(MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED, mWhich);
693 } else {
694 ALOGW("listener for process %d death is gone", mWhich);
695 }
696}
697
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800698void MediaPlayerService::Client::ServiceDeathNotifier::serviceDied(
699 uint64_t /* cookie */,
700 const wp<::android::hidl::base::V1_0::IBase>& /* who */) {
701 sp<MediaPlayerBase> listener = mListener.promote();
702 if (listener != NULL) {
703 listener->sendEvent(MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED, mWhich);
704 } else {
705 ALOGW("listener for process %d death is gone", mWhich);
706 }
707}
708
709void MediaPlayerService::Client::ServiceDeathNotifier::unlinkToDeath() {
710 if (mService != nullptr) {
711 mService->unlinkToDeath(this);
712 mService = nullptr;
713 } else if (mOmx != nullptr) {
714 mOmx->unlinkToDeath(this);
715 mOmx = nullptr;
716 }
717}
718
719void MediaPlayerService::Client::clearDeathNotifiers() {
720 if (mExtractorDeathListener != nullptr) {
721 mExtractorDeathListener->unlinkToDeath();
722 mExtractorDeathListener = nullptr;
723 }
724 if (mCodecDeathListener != nullptr) {
725 mCodecDeathListener->unlinkToDeath();
726 mCodecDeathListener = nullptr;
727 }
728}
729
John Grossmanc795b642012-02-22 15:38:35 -0800730sp<MediaPlayerBase> MediaPlayerService::Client::setDataSource_pre(
731 player_type playerType)
732{
733 ALOGV("player type = %d", playerType);
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800734 clearDeathNotifiers();
John Grossmanc795b642012-02-22 15:38:35 -0800735
736 // create the right type of player
737 sp<MediaPlayerBase> p = createPlayer(playerType);
738 if (p == NULL) {
739 return p;
740 }
741
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700742 sp<IServiceManager> sm = defaultServiceManager();
743 sp<IBinder> binder = sm->getService(String16("media.extractor"));
Marco Nelissen1b5a7ee2016-09-30 13:54:30 -0700744 if (binder == NULL) {
745 ALOGE("extractor service not available");
746 return NULL;
747 }
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700748 mExtractorDeathListener = new ServiceDeathNotifier(binder, p, MEDIAEXTRACTOR_PROCESS_DEATH);
749 binder->linkToDeath(mExtractorDeathListener);
750
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 }
758 mCodecDeathListener = new ServiceDeathNotifier(omx, p, MEDIACODEC_PROCESS_DEATH);
759 omx->linkToDeath(mCodecDeathListener, 0);
760 } 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 }
767 mCodecDeathListener = new ServiceDeathNotifier(binder, p, MEDIACODEC_PROCESS_DEATH);
768 binder->linkToDeath(mCodecDeathListener);
Marco Nelissen1b5a7ee2016-09-30 13:54:30 -0700769 }
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700770
John Grossmanc795b642012-02-22 15:38:35 -0800771 if (!p->hardwareOutput()) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -0700772 Mutex::Autolock l(mLock);
Marco Nelissend457c972014-02-11 08:47:07 -0800773 mAudioOutput = new AudioOutput(mAudioSessionId, IPCThreadState::self()->getCallingUid(),
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700774 mPid, mAudioAttributes);
John Grossmanc795b642012-02-22 15:38:35 -0800775 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
776 }
777
778 return p;
779}
780
781void MediaPlayerService::Client::setDataSource_post(
782 const sp<MediaPlayerBase>& p,
783 status_t status)
784{
785 ALOGV(" setDataSource");
786 mStatus = status;
787 if (mStatus != OK) {
788 ALOGE(" error: %d", mStatus);
789 return;
790 }
791
792 // Set the re-transmission endpoint if one was chosen.
793 if (mRetransmitEndpointValid) {
794 mStatus = p->setRetransmitEndpoint(&mRetransmitEndpoint);
795 if (mStatus != NO_ERROR) {
796 ALOGE("setRetransmitEndpoint error: %d", mStatus);
797 }
798 }
799
800 if (mStatus == OK) {
Wei Jia502c2f42017-07-13 17:47:56 -0700801 Mutex::Autolock l(mLock);
John Grossmanc795b642012-02-22 15:38:35 -0800802 mPlayer = p;
803 }
804}
805
Andreas Huber2db84552010-01-28 11:19:57 -0800806status_t MediaPlayerService::Client::setDataSource(
Andreas Huber1b86fe02014-01-29 11:13:26 -0800807 const sp<IMediaHTTPService> &httpService,
808 const char *url,
809 const KeyedVector<String8, String8> *headers)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800810{
Steve Block3856b092011-10-20 11:56:00 +0100811 ALOGV("setDataSource(%s)", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800812 if (url == NULL)
813 return UNKNOWN_ERROR;
814
Dave Burked681bbb2011-08-30 14:39:17 +0100815 if ((strncmp(url, "http://", 7) == 0) ||
816 (strncmp(url, "https://", 8) == 0) ||
817 (strncmp(url, "rtsp://", 7) == 0)) {
818 if (!checkPermission("android.permission.INTERNET")) {
819 return PERMISSION_DENIED;
820 }
821 }
822
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800823 if (strncmp(url, "content://", 10) == 0) {
824 // get a filedescriptor for the content Uri and
825 // pass it to the setDataSource(fd) method
826
827 String16 url16(url);
828 int fd = android::openContentProviderFile(url16);
829 if (fd < 0)
830 {
Steve Block29357bc2012-01-06 19:20:56 +0000831 ALOGE("Couldn't open fd for %s", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800832 return UNKNOWN_ERROR;
833 }
834 setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
835 close(fd);
836 return mStatus;
837 } else {
John Grossman44a7e422012-06-21 17:29:24 -0700838 player_type playerType = MediaPlayerFactory::getPlayerType(this, url);
John Grossmanc795b642012-02-22 15:38:35 -0800839 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
840 if (p == NULL) {
841 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800842 }
843
Andreas Huber1b86fe02014-01-29 11:13:26 -0800844 setDataSource_post(p, p->setDataSource(httpService, url, headers));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800845 return mStatus;
846 }
847}
848
849status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
850{
Marco Nelissen83b0fd92015-09-16 13:48:07 -0700851 ALOGV("setDataSource fd=%d (%s), offset=%lld, length=%lld",
852 fd, nameForFd(fd).c_str(), (long long) offset, (long long) length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800853 struct stat sb;
854 int ret = fstat(fd, &sb);
855 if (ret != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000856 ALOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800857 return UNKNOWN_ERROR;
858 }
859
Andy Hung833b4752016-04-04 17:15:48 -0700860 ALOGV("st_dev = %llu", static_cast<unsigned long long>(sb.st_dev));
Steve Block3856b092011-10-20 11:56:00 +0100861 ALOGV("st_mode = %u", sb.st_mode);
Mark Salyzyn77342f72014-06-18 16:31:32 -0700862 ALOGV("st_uid = %lu", static_cast<unsigned long>(sb.st_uid));
863 ALOGV("st_gid = %lu", static_cast<unsigned long>(sb.st_gid));
Andy Hung833b4752016-04-04 17:15:48 -0700864 ALOGV("st_size = %llu", static_cast<unsigned long long>(sb.st_size));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800865
866 if (offset >= sb.st_size) {
Steve Block29357bc2012-01-06 19:20:56 +0000867 ALOGE("offset error");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800868 return UNKNOWN_ERROR;
869 }
870 if (offset + length > sb.st_size) {
871 length = sb.st_size - offset;
Andy Hung833b4752016-04-04 17:15:48 -0700872 ALOGV("calculated length = %lld", (long long)length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800873 }
874
John Grossman44a7e422012-06-21 17:29:24 -0700875 player_type playerType = MediaPlayerFactory::getPlayerType(this,
876 fd,
877 offset,
878 length);
John Grossmanc795b642012-02-22 15:38:35 -0800879 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
880 if (p == NULL) {
881 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800882 }
883
884 // now set data source
John Grossmanc795b642012-02-22 15:38:35 -0800885 setDataSource_post(p, p->setDataSource(fd, offset, length));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800886 return mStatus;
887}
888
Andreas Hubere2b10282010-11-23 11:41:34 -0800889status_t MediaPlayerService::Client::setDataSource(
890 const sp<IStreamSource> &source) {
891 // create the right type of player
John Grossman44a7e422012-06-21 17:29:24 -0700892 player_type playerType = MediaPlayerFactory::getPlayerType(this, source);
John Grossmanc795b642012-02-22 15:38:35 -0800893 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
Andreas Hubere2b10282010-11-23 11:41:34 -0800894 if (p == NULL) {
895 return NO_INIT;
896 }
897
Andreas Hubere2b10282010-11-23 11:41:34 -0800898 // now set data source
John Grossmanc795b642012-02-22 15:38:35 -0800899 setDataSource_post(p, p->setDataSource(source));
Andreas Hubere2b10282010-11-23 11:41:34 -0800900 return mStatus;
901}
902
Chris Watkins99f31602015-03-20 13:06:33 -0700903status_t MediaPlayerService::Client::setDataSource(
904 const sp<IDataSource> &source) {
905 sp<DataSource> dataSource = DataSource::CreateFromIDataSource(source);
906 player_type playerType = MediaPlayerFactory::getPlayerType(this, dataSource);
907 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
908 if (p == NULL) {
909 return NO_INIT;
910 }
911 // now set data source
912 setDataSource_post(p, p->setDataSource(dataSource));
913 return mStatus;
914}
915
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700916void MediaPlayerService::Client::disconnectNativeWindow() {
917 if (mConnectedWindow != NULL) {
Chong Zhang181fd9b2017-02-16 15:53:03 -0800918 status_t err = nativeWindowDisconnect(
919 mConnectedWindow.get(), "disconnectNativeWindow");
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700920
921 if (err != OK) {
Chong Zhang181fd9b2017-02-16 15:53:03 -0800922 ALOGW("nativeWindowDisconnect returned an error: %s (%d)",
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700923 strerror(-err), err);
924 }
925 }
926 mConnectedWindow.clear();
927}
928
Glenn Kasten11731182011-02-08 17:26:17 -0800929status_t MediaPlayerService::Client::setVideoSurfaceTexture(
Andy McFadden484566c2012-12-18 09:46:54 -0800930 const sp<IGraphicBufferProducer>& bufferProducer)
Glenn Kasten11731182011-02-08 17:26:17 -0800931{
Andy McFadden484566c2012-12-18 09:46:54 -0800932 ALOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, bufferProducer.get());
Glenn Kasten11731182011-02-08 17:26:17 -0800933 sp<MediaPlayerBase> p = getPlayer();
934 if (p == 0) return UNKNOWN_ERROR;
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700935
Marco Nelissenf8880202014-11-14 07:58:25 -0800936 sp<IBinder> binder(IInterface::asBinder(bufferProducer));
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700937 if (mConnectedWindowBinder == binder) {
938 return OK;
939 }
940
941 sp<ANativeWindow> anw;
Andy McFadden484566c2012-12-18 09:46:54 -0800942 if (bufferProducer != NULL) {
Marco Nelissenee08f7e2013-09-16 13:30:01 -0700943 anw = new Surface(bufferProducer, true /* controlledByApp */);
Chong Zhang181fd9b2017-02-16 15:53:03 -0800944 status_t err = nativeWindowConnect(anw.get(), "setVideoSurfaceTexture");
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700945
946 if (err != OK) {
Steve Block29357bc2012-01-06 19:20:56 +0000947 ALOGE("setVideoSurfaceTexture failed: %d", err);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700948 // Note that we must do the reset before disconnecting from the ANW.
949 // Otherwise queue/dequeue calls could be made on the disconnected
950 // ANW, which may result in errors.
951 reset();
952
953 disconnectNativeWindow();
954
955 return err;
956 }
957 }
958
Andy McFadden484566c2012-12-18 09:46:54 -0800959 // Note that we must set the player's new GraphicBufferProducer before
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700960 // disconnecting the old one. Otherwise queue/dequeue calls could be made
961 // on the disconnected ANW, which may result in errors.
Andy McFadden484566c2012-12-18 09:46:54 -0800962 status_t err = p->setVideoSurfaceTexture(bufferProducer);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700963
964 disconnectNativeWindow();
965
966 mConnectedWindow = anw;
967
968 if (err == OK) {
969 mConnectedWindowBinder = binder;
970 } else {
971 disconnectNativeWindow();
972 }
973
974 return err;
Glenn Kasten11731182011-02-08 17:26:17 -0800975}
976
Nicolas Catania1d187f12009-05-12 23:25:55 -0700977status_t MediaPlayerService::Client::invoke(const Parcel& request,
978 Parcel *reply)
979{
980 sp<MediaPlayerBase> p = getPlayer();
981 if (p == NULL) return UNKNOWN_ERROR;
982 return p->invoke(request, reply);
983}
984
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700985// This call doesn't need to access the native player.
986status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
987{
988 status_t status;
nikoa64c8c72009-07-20 15:07:26 -0700989 media::Metadata::Filter allow, drop;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700990
Nicolas Catania48290382009-07-10 13:53:06 -0700991 if (unmarshallFilter(filter, &allow, &status) &&
992 unmarshallFilter(filter, &drop, &status)) {
993 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700994
995 mMetadataAllow = allow;
996 mMetadataDrop = drop;
997 }
998 return status;
999}
1000
Nicolas Catania48290382009-07-10 13:53:06 -07001001status_t MediaPlayerService::Client::getMetadata(
Mark Salyzyn77342f72014-06-18 16:31:32 -07001002 bool update_only, bool /*apply_filter*/, Parcel *reply)
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001003{
nikoa64c8c72009-07-20 15:07:26 -07001004 sp<MediaPlayerBase> player = getPlayer();
1005 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania48290382009-07-10 13:53:06 -07001006
nikod608a812009-07-16 16:39:53 -07001007 status_t status;
1008 // Placeholder for the return code, updated by the caller.
1009 reply->writeInt32(-1);
1010
nikoa64c8c72009-07-20 15:07:26 -07001011 media::Metadata::Filter ids;
Nicolas Catania48290382009-07-10 13:53:06 -07001012
1013 // We don't block notifications while we fetch the data. We clear
1014 // mMetadataUpdated first so we don't lose notifications happening
1015 // during the rest of this call.
1016 {
1017 Mutex::Autolock lock(mLock);
1018 if (update_only) {
nikod608a812009-07-16 16:39:53 -07001019 ids = mMetadataUpdated;
Nicolas Catania48290382009-07-10 13:53:06 -07001020 }
1021 mMetadataUpdated.clear();
1022 }
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001023
nikoa64c8c72009-07-20 15:07:26 -07001024 media::Metadata metadata(reply);
Nicolas Catania48290382009-07-10 13:53:06 -07001025
nikoa64c8c72009-07-20 15:07:26 -07001026 metadata.appendHeader();
1027 status = player->getMetadata(ids, reply);
nikod608a812009-07-16 16:39:53 -07001028
1029 if (status != OK) {
nikoa64c8c72009-07-20 15:07:26 -07001030 metadata.resetParcel();
Steve Block29357bc2012-01-06 19:20:56 +00001031 ALOGE("getMetadata failed %d", status);
nikod608a812009-07-16 16:39:53 -07001032 return status;
1033 }
1034
1035 // FIXME: Implement filtering on the result. Not critical since
1036 // filtering takes place on the update notifications already. This
1037 // would be when all the metadata are fetch and a filter is set.
1038
nikod608a812009-07-16 16:39:53 -07001039 // Everything is fine, update the metadata length.
nikoa64c8c72009-07-20 15:07:26 -07001040 metadata.updateLength();
nikod608a812009-07-16 16:39:53 -07001041 return OK;
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001042}
1043
Wei Jiad399e7e2016-10-26 15:49:11 -07001044status_t MediaPlayerService::Client::setBufferingSettings(
1045 const BufferingSettings& buffering)
1046{
Wei Jiadc6f3402017-01-09 15:04:18 -08001047 ALOGV("[%d] setBufferingSettings{%s}",
1048 mConnId, buffering.toString().string());
Wei Jiad399e7e2016-10-26 15:49:11 -07001049 sp<MediaPlayerBase> p = getPlayer();
1050 if (p == 0) return UNKNOWN_ERROR;
1051 return p->setBufferingSettings(buffering);
1052}
1053
1054status_t MediaPlayerService::Client::getDefaultBufferingSettings(
1055 BufferingSettings* buffering /* nonnull */)
1056{
1057 sp<MediaPlayerBase> p = getPlayer();
1058 // TODO: create mPlayer on demand.
1059 if (p == 0) return UNKNOWN_ERROR;
1060 status_t ret = p->getDefaultBufferingSettings(buffering);
1061 if (ret == NO_ERROR) {
Wei Jiadc6f3402017-01-09 15:04:18 -08001062 ALOGV("[%d] getDefaultBufferingSettings{%s}",
1063 mConnId, buffering->toString().string());
Wei Jiad399e7e2016-10-26 15:49:11 -07001064 } else {
1065 ALOGV("[%d] getDefaultBufferingSettings returned %d", mConnId, ret);
1066 }
1067 return ret;
1068}
1069
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001070status_t MediaPlayerService::Client::prepareAsync()
1071{
Steve Block3856b092011-10-20 11:56:00 +01001072 ALOGV("[%d] prepareAsync", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001073 sp<MediaPlayerBase> p = getPlayer();
1074 if (p == 0) return UNKNOWN_ERROR;
1075 status_t ret = p->prepareAsync();
1076#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +00001077 ALOGD("start Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001078 if (ret == NO_ERROR) mAntagonizer->start();
1079#endif
1080 return ret;
1081}
1082
1083status_t MediaPlayerService::Client::start()
1084{
Steve Block3856b092011-10-20 11:56:00 +01001085 ALOGV("[%d] start", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001086 sp<MediaPlayerBase> p = getPlayer();
1087 if (p == 0) return UNKNOWN_ERROR;
1088 p->setLooping(mLoop);
1089 return p->start();
1090}
1091
1092status_t MediaPlayerService::Client::stop()
1093{
Steve Block3856b092011-10-20 11:56:00 +01001094 ALOGV("[%d] stop", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001095 sp<MediaPlayerBase> p = getPlayer();
1096 if (p == 0) return UNKNOWN_ERROR;
1097 return p->stop();
1098}
1099
1100status_t MediaPlayerService::Client::pause()
1101{
Steve Block3856b092011-10-20 11:56:00 +01001102 ALOGV("[%d] pause", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001103 sp<MediaPlayerBase> p = getPlayer();
1104 if (p == 0) return UNKNOWN_ERROR;
1105 return p->pause();
1106}
1107
1108status_t MediaPlayerService::Client::isPlaying(bool* state)
1109{
1110 *state = false;
1111 sp<MediaPlayerBase> p = getPlayer();
1112 if (p == 0) return UNKNOWN_ERROR;
1113 *state = p->isPlaying();
Steve Block3856b092011-10-20 11:56:00 +01001114 ALOGV("[%d] isPlaying: %d", mConnId, *state);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001115 return NO_ERROR;
1116}
1117
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001118status_t MediaPlayerService::Client::setPlaybackSettings(const AudioPlaybackRate& rate)
Wei Jia98160162015-02-04 17:01:11 -08001119{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001120 ALOGV("[%d] setPlaybackSettings(%f, %f, %d, %d)",
1121 mConnId, rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Wei Jia98160162015-02-04 17:01:11 -08001122 sp<MediaPlayerBase> p = getPlayer();
1123 if (p == 0) return UNKNOWN_ERROR;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001124 return p->setPlaybackSettings(rate);
1125}
1126
1127status_t MediaPlayerService::Client::getPlaybackSettings(AudioPlaybackRate* rate /* nonnull */)
1128{
1129 sp<MediaPlayerBase> p = getPlayer();
1130 if (p == 0) return UNKNOWN_ERROR;
1131 status_t ret = p->getPlaybackSettings(rate);
1132 if (ret == NO_ERROR) {
1133 ALOGV("[%d] getPlaybackSettings(%f, %f, %d, %d)",
1134 mConnId, rate->mSpeed, rate->mPitch, rate->mFallbackMode, rate->mStretchMode);
1135 } else {
1136 ALOGV("[%d] getPlaybackSettings returned %d", mConnId, ret);
1137 }
1138 return ret;
1139}
1140
1141status_t MediaPlayerService::Client::setSyncSettings(
1142 const AVSyncSettings& sync, float videoFpsHint)
1143{
1144 ALOGV("[%d] setSyncSettings(%u, %u, %f, %f)",
1145 mConnId, sync.mSource, sync.mAudioAdjustMode, sync.mTolerance, videoFpsHint);
1146 sp<MediaPlayerBase> p = getPlayer();
1147 if (p == 0) return UNKNOWN_ERROR;
1148 return p->setSyncSettings(sync, videoFpsHint);
1149}
1150
1151status_t MediaPlayerService::Client::getSyncSettings(
1152 AVSyncSettings* sync /* nonnull */, float* videoFps /* nonnull */)
1153{
1154 sp<MediaPlayerBase> p = getPlayer();
1155 if (p == 0) return UNKNOWN_ERROR;
1156 status_t ret = p->getSyncSettings(sync, videoFps);
1157 if (ret == NO_ERROR) {
1158 ALOGV("[%d] getSyncSettings(%u, %u, %f, %f)",
1159 mConnId, sync->mSource, sync->mAudioAdjustMode, sync->mTolerance, *videoFps);
1160 } else {
1161 ALOGV("[%d] getSyncSettings returned %d", mConnId, ret);
1162 }
1163 return ret;
Wei Jia98160162015-02-04 17:01:11 -08001164}
1165
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001166status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
1167{
Steve Block3856b092011-10-20 11:56:00 +01001168 ALOGV("getCurrentPosition");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001169 sp<MediaPlayerBase> p = getPlayer();
1170 if (p == 0) return UNKNOWN_ERROR;
1171 status_t ret = p->getCurrentPosition(msec);
1172 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001173 ALOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001174 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001175 ALOGE("getCurrentPosition returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001176 }
1177 return ret;
1178}
1179
1180status_t MediaPlayerService::Client::getDuration(int *msec)
1181{
Steve Block3856b092011-10-20 11:56:00 +01001182 ALOGV("getDuration");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001183 sp<MediaPlayerBase> p = getPlayer();
1184 if (p == 0) return UNKNOWN_ERROR;
1185 status_t ret = p->getDuration(msec);
1186 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001187 ALOGV("[%d] getDuration = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001188 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001189 ALOGE("getDuration returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001190 }
1191 return ret;
1192}
1193
Marco Nelissen6b74d672012-02-28 16:07:44 -08001194status_t MediaPlayerService::Client::setNextPlayer(const sp<IMediaPlayer>& player) {
1195 ALOGV("setNextPlayer");
1196 Mutex::Autolock l(mLock);
1197 sp<Client> c = static_cast<Client*>(player.get());
Wei Jia28284122016-08-30 13:49:06 -07001198 if (c != NULL && !mService->hasClient(c)) {
Robert Shihee0a0e32016-08-16 16:50:54 -07001199 return BAD_VALUE;
1200 }
1201
Marco Nelissen6b74d672012-02-28 16:07:44 -08001202 mNextClient = c;
John Grossman5f7e55e2012-08-24 14:47:25 -07001203
1204 if (c != NULL) {
1205 if (mAudioOutput != NULL) {
1206 mAudioOutput->setNextOutput(c->mAudioOutput);
1207 } else if ((mPlayer != NULL) && !mPlayer->hardwareOutput()) {
1208 ALOGE("no current audio output");
1209 }
1210
1211 if ((mPlayer != NULL) && (mNextClient->getPlayer() != NULL)) {
1212 mPlayer->setNextPlayer(mNextClient->getPlayer());
1213 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001214 }
John Grossman5f7e55e2012-08-24 14:47:25 -07001215
Marco Nelissen6b74d672012-02-28 16:07:44 -08001216 return OK;
1217}
1218
Andy Hung9fc8b5c2017-01-24 13:36:48 -08001219VolumeShaper::Status MediaPlayerService::Client::applyVolumeShaper(
1220 const sp<VolumeShaper::Configuration>& configuration,
1221 const sp<VolumeShaper::Operation>& operation) {
1222 // for hardware output, call player instead
1223 ALOGV("Client::applyVolumeShaper(%p)", this);
1224 sp<MediaPlayerBase> p = getPlayer();
1225 {
1226 Mutex::Autolock l(mLock);
1227 if (p != 0 && p->hardwareOutput()) {
1228 // TODO: investigate internal implementation
1229 return VolumeShaper::Status(INVALID_OPERATION);
1230 }
1231 if (mAudioOutput.get() != nullptr) {
1232 return mAudioOutput->applyVolumeShaper(configuration, operation);
1233 }
1234 }
1235 return VolumeShaper::Status(INVALID_OPERATION);
1236}
1237
1238sp<VolumeShaper::State> MediaPlayerService::Client::getVolumeShaperState(int id) {
1239 // for hardware output, call player instead
1240 ALOGV("Client::getVolumeShaperState(%p)", this);
1241 sp<MediaPlayerBase> p = getPlayer();
1242 {
1243 Mutex::Autolock l(mLock);
1244 if (p != 0 && p->hardwareOutput()) {
1245 // TODO: investigate internal implementation.
1246 return nullptr;
1247 }
1248 if (mAudioOutput.get() != nullptr) {
1249 return mAudioOutput->getVolumeShaperState(id);
1250 }
1251 }
1252 return nullptr;
1253}
1254
Wei Jiac5de0912016-11-18 10:22:14 -08001255status_t MediaPlayerService::Client::seekTo(int msec, MediaPlayerSeekMode mode)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001256{
Wei Jiac5de0912016-11-18 10:22:14 -08001257 ALOGV("[%d] seekTo(%d, %d)", mConnId, msec, mode);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001258 sp<MediaPlayerBase> p = getPlayer();
1259 if (p == 0) return UNKNOWN_ERROR;
Wei Jiac5de0912016-11-18 10:22:14 -08001260 return p->seekTo(msec, mode);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001261}
1262
1263status_t MediaPlayerService::Client::reset()
1264{
Steve Block3856b092011-10-20 11:56:00 +01001265 ALOGV("[%d] reset", mConnId);
John Grossmanc795b642012-02-22 15:38:35 -08001266 mRetransmitEndpointValid = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001267 sp<MediaPlayerBase> p = getPlayer();
1268 if (p == 0) return UNKNOWN_ERROR;
1269 return p->reset();
1270}
1271
Wei Jia52c28512017-09-13 18:17:51 -07001272status_t MediaPlayerService::Client::notifyAt(int64_t mediaTimeUs)
1273{
1274 ALOGV("[%d] notifyAt(%lld)", mConnId, (long long)mediaTimeUs);
1275 sp<MediaPlayerBase> p = getPlayer();
1276 if (p == 0) return UNKNOWN_ERROR;
1277 return p->notifyAt(mediaTimeUs);
1278}
1279
Glenn Kastenfff6d712012-01-12 16:38:12 -08001280status_t MediaPlayerService::Client::setAudioStreamType(audio_stream_type_t type)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001281{
Steve Block3856b092011-10-20 11:56:00 +01001282 ALOGV("[%d] setAudioStreamType(%d)", mConnId, type);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001283 // TODO: for hardware output, call player instead
1284 Mutex::Autolock l(mLock);
1285 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1286 return NO_ERROR;
1287}
1288
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001289status_t MediaPlayerService::Client::setAudioAttributes_l(const Parcel &parcel)
1290{
1291 if (mAudioAttributes != NULL) { free(mAudioAttributes); }
1292 mAudioAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001293 if (mAudioAttributes == NULL) {
1294 return NO_MEMORY;
1295 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001296 unmarshallAudioAttributes(parcel, mAudioAttributes);
1297
1298 ALOGV("setAudioAttributes_l() usage=%d content=%d flags=0x%x tags=%s",
1299 mAudioAttributes->usage, mAudioAttributes->content_type, mAudioAttributes->flags,
1300 mAudioAttributes->tags);
1301
1302 if (mAudioOutput != 0) {
1303 mAudioOutput->setAudioAttributes(mAudioAttributes);
1304 }
1305 return NO_ERROR;
1306}
1307
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001308status_t MediaPlayerService::Client::setLooping(int loop)
1309{
Steve Block3856b092011-10-20 11:56:00 +01001310 ALOGV("[%d] setLooping(%d)", mConnId, loop);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001311 mLoop = loop;
1312 sp<MediaPlayerBase> p = getPlayer();
1313 if (p != 0) return p->setLooping(loop);
1314 return NO_ERROR;
1315}
1316
1317status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1318{
Steve Block3856b092011-10-20 11:56:00 +01001319 ALOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
John Grossman761defc2012-02-09 15:09:05 -08001320
1321 // for hardware output, call player instead
1322 sp<MediaPlayerBase> p = getPlayer();
1323 {
1324 Mutex::Autolock l(mLock);
1325 if (p != 0 && p->hardwareOutput()) {
1326 MediaPlayerHWInterface* hwp =
1327 reinterpret_cast<MediaPlayerHWInterface*>(p.get());
1328 return hwp->setVolume(leftVolume, rightVolume);
1329 } else {
1330 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1331 return NO_ERROR;
1332 }
1333 }
1334
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001335 return NO_ERROR;
1336}
1337
Eric Laurent2beeb502010-07-16 07:43:46 -07001338status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1339{
Steve Block3856b092011-10-20 11:56:00 +01001340 ALOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
Eric Laurent2beeb502010-07-16 07:43:46 -07001341 Mutex::Autolock l(mLock);
1342 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1343 return NO_ERROR;
1344}
1345
1346status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1347{
Steve Block3856b092011-10-20 11:56:00 +01001348 ALOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
Eric Laurent2beeb502010-07-16 07:43:46 -07001349 Mutex::Autolock l(mLock);
1350 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1351 return NO_ERROR;
1352}
Nicolas Catania48290382009-07-10 13:53:06 -07001353
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001354status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
Steve Block3856b092011-10-20 11:56:00 +01001355 ALOGV("[%d] setParameter(%d)", mConnId, key);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001356 switch (key) {
1357 case KEY_PARAMETER_AUDIO_ATTRIBUTES:
1358 {
1359 Mutex::Autolock l(mLock);
1360 return setAudioAttributes_l(request);
1361 }
1362 default:
1363 sp<MediaPlayerBase> p = getPlayer();
1364 if (p == 0) { return UNKNOWN_ERROR; }
1365 return p->setParameter(key, request);
1366 }
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001367}
1368
1369status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
Steve Block3856b092011-10-20 11:56:00 +01001370 ALOGV("[%d] getParameter(%d)", mConnId, key);
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001371 sp<MediaPlayerBase> p = getPlayer();
1372 if (p == 0) return UNKNOWN_ERROR;
1373 return p->getParameter(key, reply);
1374}
1375
John Grossmanc795b642012-02-22 15:38:35 -08001376status_t MediaPlayerService::Client::setRetransmitEndpoint(
1377 const struct sockaddr_in* endpoint) {
1378
1379 if (NULL != endpoint) {
1380 uint32_t a = ntohl(endpoint->sin_addr.s_addr);
1381 uint16_t p = ntohs(endpoint->sin_port);
1382 ALOGV("[%d] setRetransmitEndpoint(%u.%u.%u.%u:%hu)", mConnId,
1383 (a >> 24), (a >> 16) & 0xFF, (a >> 8) & 0xFF, (a & 0xFF), p);
1384 } else {
1385 ALOGV("[%d] setRetransmitEndpoint = <none>", mConnId);
1386 }
1387
1388 sp<MediaPlayerBase> p = getPlayer();
1389
1390 // Right now, the only valid time to set a retransmit endpoint is before
1391 // player selection has been made (since the presence or absence of a
1392 // retransmit endpoint is going to determine which player is selected during
1393 // setDataSource).
1394 if (p != 0) return INVALID_OPERATION;
1395
1396 if (NULL != endpoint) {
1397 mRetransmitEndpoint = *endpoint;
1398 mRetransmitEndpointValid = true;
1399 } else {
1400 mRetransmitEndpointValid = false;
1401 }
1402
1403 return NO_ERROR;
1404}
1405
John Grossman44a7e422012-06-21 17:29:24 -07001406status_t MediaPlayerService::Client::getRetransmitEndpoint(
1407 struct sockaddr_in* endpoint)
1408{
1409 if (NULL == endpoint)
1410 return BAD_VALUE;
1411
1412 sp<MediaPlayerBase> p = getPlayer();
1413
1414 if (p != NULL)
1415 return p->getRetransmitEndpoint(endpoint);
1416
1417 if (!mRetransmitEndpointValid)
1418 return NO_INIT;
1419
1420 *endpoint = mRetransmitEndpoint;
1421
1422 return NO_ERROR;
1423}
1424
Gloria Wangb483c472011-04-11 17:23:27 -07001425void MediaPlayerService::Client::notify(
1426 void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001427{
1428 Client* client = static_cast<Client*>(cookie);
James Dongb8a98252012-08-26 16:13:03 -07001429 if (client == NULL) {
1430 return;
1431 }
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001432
James Dongb8a98252012-08-26 16:13:03 -07001433 sp<IMediaPlayerClient> c;
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001434 sp<Client> nextClient;
1435 status_t errStartNext = NO_ERROR;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001436 {
1437 Mutex::Autolock l(client->mLock);
James Dongb8a98252012-08-26 16:13:03 -07001438 c = client->mClient;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001439 if (msg == MEDIA_PLAYBACK_COMPLETE && client->mNextClient != NULL) {
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001440 nextClient = client->mNextClient;
1441
John Grossmancb0b7552012-08-23 17:47:31 -07001442 if (client->mAudioOutput != NULL)
1443 client->mAudioOutput->switchToNextOutput();
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001444
1445 errStartNext = nextClient->start();
1446 }
1447 }
1448
1449 if (nextClient != NULL) {
1450 sp<IMediaPlayerClient> nc;
1451 {
1452 Mutex::Autolock l(nextClient->mLock);
1453 nc = nextClient->mClient;
1454 }
1455 if (nc != NULL) {
1456 if (errStartNext == NO_ERROR) {
1457 nc->notify(MEDIA_INFO, MEDIA_INFO_STARTED_AS_NEXT, 0, obj);
1458 } else {
1459 nc->notify(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN , 0, obj);
1460 ALOGE("gapless:start playback for next track failed, err(%d)", errStartNext);
Wei Jia2afac0c2016-01-07 12:13:07 -08001461 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001462 }
1463 }
1464
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001465 if (MEDIA_INFO == msg &&
Nicolas Catania48290382009-07-10 13:53:06 -07001466 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikoa64c8c72009-07-20 15:07:26 -07001467 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania48290382009-07-10 13:53:06 -07001468
1469 if(client->shouldDropMetadata(metadata_type)) {
1470 return;
1471 }
1472
1473 // Update the list of metadata that have changed. getMetadata
1474 // also access mMetadataUpdated and clears it.
1475 client->addNewMetadataUpdate(metadata_type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001476 }
James Dongb8a98252012-08-26 16:13:03 -07001477
1478 if (c != NULL) {
1479 ALOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
1480 c->notify(msg, ext1, ext2, obj);
1481 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001482}
1483
Nicolas Catania48290382009-07-10 13:53:06 -07001484
nikoa64c8c72009-07-20 15:07:26 -07001485bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001486{
Nicolas Catania48290382009-07-10 13:53:06 -07001487 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001488
Nicolas Catania48290382009-07-10 13:53:06 -07001489 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001490 return true;
1491 }
1492
Nicolas Catania48290382009-07-10 13:53:06 -07001493 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001494 return false;
Nicolas Catania48290382009-07-10 13:53:06 -07001495 } else {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001496 return true;
1497 }
1498}
1499
Nicolas Catania48290382009-07-10 13:53:06 -07001500
nikoa64c8c72009-07-20 15:07:26 -07001501void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania48290382009-07-10 13:53:06 -07001502 Mutex::Autolock lock(mLock);
1503 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1504 mMetadataUpdated.add(metadata_type);
1505 }
1506}
1507
Hassan Shojaniacefac142017-02-06 21:02:02 -08001508// Modular DRM
1509status_t MediaPlayerService::Client::prepareDrm(const uint8_t uuid[16],
1510 const Vector<uint8_t>& drmSessionId)
1511{
1512 ALOGV("[%d] prepareDrm", mConnId);
1513 sp<MediaPlayerBase> p = getPlayer();
1514 if (p == 0) return UNKNOWN_ERROR;
1515
1516 status_t ret = p->prepareDrm(uuid, drmSessionId);
1517 ALOGV("prepareDrm ret: %d", ret);
1518
1519 return ret;
1520}
1521
1522status_t MediaPlayerService::Client::releaseDrm()
1523{
1524 ALOGV("[%d] releaseDrm", mConnId);
1525 sp<MediaPlayerBase> p = getPlayer();
1526 if (p == 0) return UNKNOWN_ERROR;
1527
1528 status_t ret = p->releaseDrm();
1529 ALOGV("releaseDrm ret: %d", ret);
1530
1531 return ret;
1532}
1533
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001534#if CALLBACK_ANTAGONIZER
1535const int Antagonizer::interval = 10000; // 10 msecs
1536
1537Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1538 mExit(false), mActive(false), mClient(client), mCb(cb)
1539{
1540 createThread(callbackThread, this);
1541}
1542
1543void Antagonizer::kill()
1544{
1545 Mutex::Autolock _l(mLock);
1546 mActive = false;
1547 mExit = true;
1548 mCondition.wait(mLock);
1549}
1550
1551int Antagonizer::callbackThread(void* user)
1552{
Steve Blockb8a80522011-12-20 16:23:08 +00001553 ALOGD("Antagonizer started");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001554 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1555 while (!p->mExit) {
1556 if (p->mActive) {
Steve Block3856b092011-10-20 11:56:00 +01001557 ALOGV("send event");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001558 p->mCb(p->mClient, 0, 0, 0);
1559 }
1560 usleep(interval);
1561 }
1562 Mutex::Autolock _l(p->mLock);
1563 p->mCondition.signal();
Steve Blockb8a80522011-12-20 16:23:08 +00001564 ALOGD("Antagonizer stopped");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001565 return 0;
1566}
1567#endif
1568
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001569#undef LOG_TAG
1570#define LOG_TAG "AudioSink"
Andy Hung1afd0982016-11-08 16:13:44 -08001571MediaPlayerService::AudioOutput::AudioOutput(audio_session_t sessionId, uid_t uid, int pid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001572 const audio_attributes_t* attr)
Andreas Huber20111aa2009-07-14 16:56:47 -07001573 : mCallback(NULL),
Eric Laurenta514bdb2010-06-21 09:27:30 -07001574 mCallbackCookie(NULL),
Marco Nelissen6b74d672012-02-28 16:07:44 -08001575 mCallbackData(NULL),
Andy Hungd1c74342015-07-07 16:54:23 -07001576 mStreamType(AUDIO_STREAM_MUSIC),
Andy Hungd1c74342015-07-07 16:54:23 -07001577 mLeftVolume(1.0),
1578 mRightVolume(1.0),
1579 mPlaybackRate(AUDIO_PLAYBACK_RATE_DEFAULT),
1580 mSampleRateHz(0),
1581 mMsecsPerFrame(0),
1582 mFrameSize(0),
Eric Laurent1948eb32012-04-13 16:50:19 -07001583 mSessionId(sessionId),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001584 mUid(uid),
Marco Nelissend457c972014-02-11 08:47:07 -08001585 mPid(pid),
Andy Hungd1c74342015-07-07 16:54:23 -07001586 mSendLevel(0.0),
1587 mAuxEffectId(0),
Andy Hung4ef88d72017-02-21 19:47:53 -08001588 mFlags(AUDIO_OUTPUT_FLAG_NONE),
Ivan Lozano8cf3a072017-08-09 09:01:33 -07001589 mVolumeHandler(new media::VolumeHandler())
Andy Hungd1c74342015-07-07 16:54:23 -07001590{
Steve Block3856b092011-10-20 11:56:00 +01001591 ALOGV("AudioOutput(%d)", sessionId);
Eric Laurent43562692015-07-15 16:49:07 -07001592 if (attr != NULL) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001593 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1594 if (mAttributes != NULL) {
1595 memcpy(mAttributes, attr, sizeof(audio_attributes_t));
1596 mStreamType = audio_attributes_to_stream_type(attr);
1597 }
1598 } else {
1599 mAttributes = NULL;
Eric Laurent43562692015-07-15 16:49:07 -07001600 }
1601
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001602 setMinBufferCount();
1603}
1604
1605MediaPlayerService::AudioOutput::~AudioOutput()
1606{
1607 close();
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001608 free(mAttributes);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001609 delete mCallbackData;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001610}
1611
Andy Hungd1c74342015-07-07 16:54:23 -07001612//static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001613void MediaPlayerService::AudioOutput::setMinBufferCount()
1614{
1615 char value[PROPERTY_VALUE_MAX];
1616 if (property_get("ro.kernel.qemu", value, 0)) {
1617 mIsOnEmulator = true;
1618 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1619 }
1620}
1621
Andy Hungd1c74342015-07-07 16:54:23 -07001622// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001623bool MediaPlayerService::AudioOutput::isOnEmulator()
1624{
Andy Hungd1c74342015-07-07 16:54:23 -07001625 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001626 return mIsOnEmulator;
1627}
1628
Andy Hungd1c74342015-07-07 16:54:23 -07001629// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001630int MediaPlayerService::AudioOutput::getMinBufferCount()
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 mMinBufferCount;
1634}
1635
1636ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1637{
Andy Hungd1c74342015-07-07 16:54:23 -07001638 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001639 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001640 return mTrack->frameCount() * mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001641}
1642
1643ssize_t MediaPlayerService::AudioOutput::frameCount() 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;
1647 return mTrack->frameCount();
1648}
1649
1650ssize_t MediaPlayerService::AudioOutput::channelCount() 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->channelCount();
1655}
1656
1657ssize_t MediaPlayerService::AudioOutput::frameSize() 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;
Andy Hungd1c74342015-07-07 16:54:23 -07001661 return mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001662}
1663
1664uint32_t MediaPlayerService::AudioOutput::latency () const
1665{
Andy Hungd1c74342015-07-07 16:54:23 -07001666 Mutex::Autolock lock(mLock);
Eric Laurentdb354e52012-03-05 17:27:11 -08001667 if (mTrack == 0) return 0;
1668 return mTrack->latency();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001669}
1670
1671float MediaPlayerService::AudioOutput::msecsPerFrame() const
1672{
Andy Hungd1c74342015-07-07 16:54:23 -07001673 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001674 return mMsecsPerFrame;
1675}
1676
Marco Nelissen4110c102012-03-29 09:31:28 -07001677status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position) const
Eric Laurent342e9cf2010-01-19 17:37:09 -08001678{
Andy Hungd1c74342015-07-07 16:54:23 -07001679 Mutex::Autolock lock(mLock);
Eric Laurent342e9cf2010-01-19 17:37:09 -08001680 if (mTrack == 0) return NO_INIT;
1681 return mTrack->getPosition(position);
1682}
1683
Lajos Molnar06ad1522014-08-28 07:27:44 -07001684status_t MediaPlayerService::AudioOutput::getTimestamp(AudioTimestamp &ts) const
1685{
Andy Hungd1c74342015-07-07 16:54:23 -07001686 Mutex::Autolock lock(mLock);
Lajos Molnar06ad1522014-08-28 07:27:44 -07001687 if (mTrack == 0) return NO_INIT;
1688 return mTrack->getTimestamp(ts);
1689}
1690
Wei Jiac4ac8172015-10-21 10:35:48 -07001691// TODO: Remove unnecessary calls to getPlayedOutDurationUs()
1692// as it acquires locks and may query the audio driver.
1693//
1694// Some calls could conceivably retrieve extrapolated data instead of
1695// accessing getTimestamp() or getPosition() every time a data buffer with
1696// a media time is received.
1697//
1698// Calculate duration of played samples if played at normal rate (i.e., 1.0).
1699int64_t MediaPlayerService::AudioOutput::getPlayedOutDurationUs(int64_t nowUs) const
1700{
1701 Mutex::Autolock lock(mLock);
1702 if (mTrack == 0 || mSampleRateHz == 0) {
Wei Jia213f4902015-10-22 08:55:25 -07001703 return 0;
Wei Jiac4ac8172015-10-21 10:35:48 -07001704 }
1705
1706 uint32_t numFramesPlayed;
Andy Hung5d313802016-10-10 15:09:39 -07001707 int64_t numFramesPlayedAtUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001708 AudioTimestamp ts;
Wei Jiac4ac8172015-10-21 10:35:48 -07001709
1710 status_t res = mTrack->getTimestamp(ts);
1711 if (res == OK) { // case 1: mixing audio tracks and offloaded tracks.
1712 numFramesPlayed = ts.mPosition;
Andy Hung5d313802016-10-10 15:09:39 -07001713 numFramesPlayedAtUs = ts.mTime.tv_sec * 1000000LL + ts.mTime.tv_nsec / 1000;
1714 //ALOGD("getTimestamp: OK %d %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001715 } else if (res == WOULD_BLOCK) { // case 2: transitory state on start of a new track
1716 numFramesPlayed = 0;
Andy Hung5d313802016-10-10 15:09:39 -07001717 numFramesPlayedAtUs = nowUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001718 //ALOGD("getTimestamp: WOULD_BLOCK %d %lld",
Andy Hung5d313802016-10-10 15:09:39 -07001719 // numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001720 } else { // case 3: transitory at new track or audio fast tracks.
1721 res = mTrack->getPosition(&numFramesPlayed);
1722 CHECK_EQ(res, (status_t)OK);
Andy Hung5d313802016-10-10 15:09:39 -07001723 numFramesPlayedAtUs = nowUs;
1724 numFramesPlayedAtUs += 1000LL * mTrack->latency() / 2; /* XXX */
1725 //ALOGD("getPosition: %u %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001726 }
1727
1728 // CHECK_EQ(numFramesPlayed & (1 << 31), 0); // can't be negative until 12.4 hrs, test
1729 // TODO: remove the (int32_t) casting below as it may overflow at 12.4 hours.
1730 int64_t durationUs = (int64_t)((int32_t)numFramesPlayed * 1000000LL / mSampleRateHz)
Andy Hung5d313802016-10-10 15:09:39 -07001731 + nowUs - numFramesPlayedAtUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001732 if (durationUs < 0) {
1733 // Occurs when numFramesPlayed position is very small and the following:
1734 // (1) In case 1, the time nowUs is computed before getTimestamp() is called and
Andy Hung5d313802016-10-10 15:09:39 -07001735 // numFramesPlayedAtUs is greater than nowUs by time more than numFramesPlayed.
Wei Jiac4ac8172015-10-21 10:35:48 -07001736 // (2) In case 3, using getPosition and adding mAudioSink->latency() to
Andy Hung5d313802016-10-10 15:09:39 -07001737 // numFramesPlayedAtUs, by a time amount greater than numFramesPlayed.
Wei Jiac4ac8172015-10-21 10:35:48 -07001738 //
1739 // Both of these are transitory conditions.
1740 ALOGV("getPlayedOutDurationUs: negative duration %lld set to zero", (long long)durationUs);
1741 durationUs = 0;
1742 }
1743 ALOGV("getPlayedOutDurationUs(%lld) nowUs(%lld) frames(%u) framesAt(%lld)",
Andy Hung5d313802016-10-10 15:09:39 -07001744 (long long)durationUs, (long long)nowUs,
1745 numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001746 return durationUs;
1747}
1748
Marco Nelissen4110c102012-03-29 09:31:28 -07001749status_t MediaPlayerService::AudioOutput::getFramesWritten(uint32_t *frameswritten) const
1750{
Andy Hungd1c74342015-07-07 16:54:23 -07001751 Mutex::Autolock lock(mLock);
Marco Nelissen4110c102012-03-29 09:31:28 -07001752 if (mTrack == 0) return NO_INIT;
Andy Hung2f6e73d2016-04-08 12:12:58 -07001753 ExtendedTimestamp ets;
1754 status_t status = mTrack->getTimestamp(&ets);
1755 if (status == OK || status == WOULD_BLOCK) {
1756 *frameswritten = (uint32_t)ets.mPosition[ExtendedTimestamp::LOCATION_CLIENT];
1757 }
1758 return status;
Marco Nelissen4110c102012-03-29 09:31:28 -07001759}
1760
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001761status_t MediaPlayerService::AudioOutput::setParameters(const String8& keyValuePairs)
1762{
Andy Hungd1c74342015-07-07 16:54:23 -07001763 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001764 if (mTrack == 0) return NO_INIT;
1765 return mTrack->setParameters(keyValuePairs);
1766}
1767
1768String8 MediaPlayerService::AudioOutput::getParameters(const String8& keys)
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 String8::empty();
1772 return mTrack->getParameters(keys);
1773}
1774
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001775void MediaPlayerService::AudioOutput::setAudioAttributes(const audio_attributes_t * attributes) {
Andy Hungd1c74342015-07-07 16:54:23 -07001776 Mutex::Autolock lock(mLock);
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001777 if (attributes == NULL) {
1778 free(mAttributes);
1779 mAttributes = NULL;
1780 } else {
1781 if (mAttributes == NULL) {
1782 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1783 }
1784 memcpy(mAttributes, attributes, sizeof(audio_attributes_t));
Eric Laurent43562692015-07-15 16:49:07 -07001785 mStreamType = audio_attributes_to_stream_type(attributes);
1786 }
1787}
1788
1789void MediaPlayerService::AudioOutput::setAudioStreamType(audio_stream_type_t streamType)
1790{
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001791 Mutex::Autolock lock(mLock);
Eric Laurent43562692015-07-15 16:49:07 -07001792 // do not allow direct stream type modification if attributes have been set
1793 if (mAttributes == NULL) {
1794 mStreamType = streamType;
1795 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001796}
1797
Andy Hungd1c74342015-07-07 16:54:23 -07001798void MediaPlayerService::AudioOutput::deleteRecycledTrack_l()
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001799{
Andy Hungd1c74342015-07-07 16:54:23 -07001800 ALOGV("deleteRecycledTrack_l");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001801 if (mRecycledTrack != 0) {
1802
1803 if (mCallbackData != NULL) {
1804 mCallbackData->setOutput(NULL);
1805 mCallbackData->endTrackSwitch();
1806 }
1807
1808 if ((mRecycledTrack->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) {
Andy Hunge13f8a62016-03-30 14:20:42 -07001809 int32_t msec = 0;
1810 if (!mRecycledTrack->stopped()) { // check if active
1811 (void)mRecycledTrack->pendingDuration(&msec);
1812 }
1813 mRecycledTrack->stop(); // ensure full data drain
1814 ALOGD("deleting recycled track, waiting for data drain (%d msec)", msec);
1815 if (msec > 0) {
1816 static const int32_t WAIT_LIMIT_MS = 3000;
1817 if (msec > WAIT_LIMIT_MS) {
1818 msec = WAIT_LIMIT_MS;
1819 }
1820 usleep(msec * 1000LL);
1821 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001822 }
1823 // An offloaded track isn't flushed because the STREAM_END is reported
1824 // slightly prematurely to allow time for the gapless track switch
1825 // but this means that if we decide not to recycle the track there
1826 // could be a small amount of residual data still playing. We leave
1827 // AudioFlinger to drain the track.
1828
1829 mRecycledTrack.clear();
Andy Hungd1c74342015-07-07 16:54:23 -07001830 close_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001831 delete mCallbackData;
1832 mCallbackData = NULL;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001833 }
1834}
1835
Andy Hungd1c74342015-07-07 16:54:23 -07001836void MediaPlayerService::AudioOutput::close_l()
1837{
1838 mTrack.clear();
1839}
1840
Andreas Huber20111aa2009-07-14 16:56:47 -07001841status_t MediaPlayerService::AudioOutput::open(
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001842 uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
1843 audio_format_t format, int bufferCount,
Eric Laurent1948eb32012-04-13 16:50:19 -07001844 AudioCallback cb, void *cookie,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001845 audio_output_flags_t flags,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001846 const audio_offload_info_t *offloadInfo,
Andy Hung179652e2015-05-31 22:49:46 -07001847 bool doNotReconnect,
1848 uint32_t suggestedFrameCount)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001849{
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001850 ALOGV("open(%u, %d, 0x%x, 0x%x, %d, %d 0x%x)", sampleRate, channelCount, channelMask,
1851 format, bufferCount, mSessionId, flags);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001852
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001853 // offloading is only supported in callback mode for now.
1854 // offloadInfo must be present if offload flag is set
1855 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) &&
1856 ((cb == NULL) || (offloadInfo == NULL))) {
1857 return BAD_VALUE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001858 }
1859
Andy Hung179652e2015-05-31 22:49:46 -07001860 // compute frame count for the AudioTrack internal buffer
1861 size_t frameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001862 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1863 frameCount = 0; // AudioTrack will get frame count from AudioFlinger
1864 } else {
Andy Hung179652e2015-05-31 22:49:46 -07001865 // try to estimate the buffer processing fetch size from AudioFlinger.
1866 // framesPerBuffer is approximate and generally correct, except when it's not :-).
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001867 uint32_t afSampleRate;
1868 size_t afFrameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001869 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1870 return NO_INIT;
1871 }
1872 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1873 return NO_INIT;
1874 }
Andy Hung179652e2015-05-31 22:49:46 -07001875 const size_t framesPerBuffer =
1876 (unsigned long long)sampleRate * afFrameCount / afSampleRate;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001877
Andy Hung179652e2015-05-31 22:49:46 -07001878 if (bufferCount == 0) {
1879 // use suggestedFrameCount
1880 bufferCount = (suggestedFrameCount + framesPerBuffer - 1) / framesPerBuffer;
1881 }
1882 // Check argument bufferCount against the mininum buffer count
1883 if (bufferCount != 0 && bufferCount < mMinBufferCount) {
1884 ALOGV("bufferCount (%d) increased to %d", bufferCount, mMinBufferCount);
1885 bufferCount = mMinBufferCount;
1886 }
1887 // if frameCount is 0, then AudioTrack will get frame count from AudioFlinger
1888 // which will be the minimum size permitted.
1889 frameCount = bufferCount * framesPerBuffer;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001890 }
Andreas Huber20111aa2009-07-14 16:56:47 -07001891
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001892 if (channelMask == CHANNEL_MASK_USE_CHANNEL_ORDER) {
Glenn Kastenab334fd2012-03-14 12:56:06 -07001893 channelMask = audio_channel_out_mask_from_count(channelCount);
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001894 if (0 == channelMask) {
1895 ALOGE("open() error, can\'t derive mask for %d audio channels", channelCount);
1896 return NO_INIT;
1897 }
1898 }
Eric Laurent1948eb32012-04-13 16:50:19 -07001899
Andy Hungd1c74342015-07-07 16:54:23 -07001900 Mutex::Autolock lock(mLock);
Andy Hung179652e2015-05-31 22:49:46 -07001901 mCallback = cb;
1902 mCallbackCookie = cookie;
1903
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001904 // Check whether we can recycle the track
1905 bool reuse = false;
1906 bool bothOffloaded = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001907
Glenn Kasten2799d742013-05-30 14:33:29 -07001908 if (mRecycledTrack != 0) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001909 // check whether we are switching between two offloaded tracks
1910 bothOffloaded = (flags & mRecycledTrack->getFlags()
1911 & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0;
Marco Nelissen67295b52012-06-11 14:52:53 -07001912
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001913 // check if the existing track can be reused as-is, or if a new track needs to be created.
1914 reuse = true;
1915
Marco Nelissen67295b52012-06-11 14:52:53 -07001916 if ((mCallbackData == NULL && mCallback != NULL) ||
1917 (mCallbackData != NULL && mCallback == NULL)) {
1918 // recycled track uses callbacks but the caller wants to use writes, or vice versa
1919 ALOGV("can't chain callback and write");
1920 reuse = false;
1921 } else if ((mRecycledTrack->getSampleRate() != sampleRate) ||
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001922 (mRecycledTrack->channelCount() != (uint32_t)channelCount) ) {
1923 ALOGV("samplerate, channelcount differ: %u/%u Hz, %u/%d ch",
Marco Nelissen67295b52012-06-11 14:52:53 -07001924 mRecycledTrack->getSampleRate(), sampleRate,
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001925 mRecycledTrack->channelCount(), channelCount);
Marco Nelissen67295b52012-06-11 14:52:53 -07001926 reuse = false;
1927 } else if (flags != mFlags) {
1928 ALOGV("output flags differ %08x/%08x", flags, mFlags);
1929 reuse = false;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001930 } else if (mRecycledTrack->format() != format) {
1931 reuse = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001932 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001933 } else {
1934 ALOGV("no track available to recycle");
1935 }
1936
1937 ALOGV_IF(bothOffloaded, "both tracks offloaded");
1938
1939 // If we can't recycle and both tracks are offloaded
1940 // we must close the previous output before opening a new one
1941 if (bothOffloaded && !reuse) {
1942 ALOGV("both offloaded and not recycling");
Andy Hungd1c74342015-07-07 16:54:23 -07001943 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001944 }
1945
1946 sp<AudioTrack> t;
1947 CallbackData *newcbd = NULL;
1948
1949 // We don't attempt to create a new track if we are recycling an
1950 // offloaded track. But, if we are recycling a non-offloaded or we
1951 // are switching where one is offloaded and one isn't then we create
1952 // the new track in advance so that we can read additional stream info
1953
1954 if (!(reuse && bothOffloaded)) {
1955 ALOGV("creating new AudioTrack");
1956
1957 if (mCallback != NULL) {
1958 newcbd = new CallbackData(this);
1959 t = new AudioTrack(
1960 mStreamType,
1961 sampleRate,
1962 format,
1963 channelMask,
1964 frameCount,
1965 flags,
1966 CallbackWrapper,
1967 newcbd,
1968 0, // notification frames
1969 mSessionId,
1970 AudioTrack::TRANSFER_CALLBACK,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001971 offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -08001972 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001973 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001974 mAttributes,
1975 doNotReconnect);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001976 } else {
Andy Hungff874dc2016-04-11 16:49:09 -07001977 // TODO: Due to buffer memory concerns, we use a max target playback speed
1978 // based on mPlaybackRate at the time of open (instead of kMaxRequiredSpeed),
1979 // also clamping the target speed to 1.0 <= targetSpeed <= kMaxRequiredSpeed.
1980 const float targetSpeed =
1981 std::min(std::max(mPlaybackRate.mSpeed, 1.0f), kMaxRequiredSpeed);
1982 ALOGW_IF(targetSpeed != mPlaybackRate.mSpeed,
1983 "track target speed:%f clamped from playback speed:%f",
1984 targetSpeed, mPlaybackRate.mSpeed);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001985 t = new AudioTrack(
1986 mStreamType,
1987 sampleRate,
1988 format,
1989 channelMask,
1990 frameCount,
1991 flags,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001992 NULL, // callback
1993 NULL, // user data
1994 0, // notification frames
1995 mSessionId,
1996 AudioTrack::TRANSFER_DEFAULT,
1997 NULL, // offload info
Marco Nelissend457c972014-02-11 08:47:07 -08001998 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001999 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07002000 mAttributes,
Andy Hungff874dc2016-04-11 16:49:09 -07002001 doNotReconnect,
2002 targetSpeed);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002003 }
2004
2005 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
2006 ALOGE("Unable to create audio track");
2007 delete newcbd;
Glenn Kasten3e98ecd2015-05-18 13:13:24 -07002008 // t goes out of scope, so reference count drops to zero
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002009 return NO_INIT;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07002010 } else {
2011 // successful AudioTrack initialization implies a legacy stream type was generated
2012 // from the audio attributes
2013 mStreamType = t->streamType();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002014 }
2015 }
2016
2017 if (reuse) {
2018 CHECK(mRecycledTrack != NULL);
2019
2020 if (!bothOffloaded) {
2021 if (mRecycledTrack->frameCount() != t->frameCount()) {
Andy Hung833b4752016-04-04 17:15:48 -07002022 ALOGV("framecount differs: %zu/%zu frames",
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002023 mRecycledTrack->frameCount(), t->frameCount());
2024 reuse = false;
2025 }
2026 }
2027
Marco Nelissen67295b52012-06-11 14:52:53 -07002028 if (reuse) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002029 ALOGV("chaining to next output and recycling track");
Andy Hungd1c74342015-07-07 16:54:23 -07002030 close_l();
Marco Nelissen67295b52012-06-11 14:52:53 -07002031 mTrack = mRecycledTrack;
Glenn Kasten2799d742013-05-30 14:33:29 -07002032 mRecycledTrack.clear();
Marco Nelissen67295b52012-06-11 14:52:53 -07002033 if (mCallbackData != NULL) {
2034 mCallbackData->setOutput(this);
2035 }
Marco Nelissen67295b52012-06-11 14:52:53 -07002036 delete newcbd;
Wei Jiae0bbac92016-07-18 16:04:53 -07002037 return updateTrack();
Marco Nelissen67295b52012-06-11 14:52:53 -07002038 }
Marco Nelissen67295b52012-06-11 14:52:53 -07002039 }
2040
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002041 // we're not going to reuse the track, unblock and flush it
2042 // this was done earlier if both tracks are offloaded
2043 if (!bothOffloaded) {
Andy Hungd1c74342015-07-07 16:54:23 -07002044 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002045 }
2046
2047 CHECK((t != NULL) && ((mCallback == NULL) || (newcbd != NULL)));
2048
Marco Nelissen67295b52012-06-11 14:52:53 -07002049 mCallbackData = newcbd;
Steve Block3856b092011-10-20 11:56:00 +01002050 ALOGV("setVolume");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002051 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07002052
Andy Hung39399b62017-04-21 15:07:45 -07002053 // Restore VolumeShapers for the MediaPlayer in case the track was recreated
2054 // due to an output sink error (e.g. offload to non-offload switch).
2055 mVolumeHandler->forall([&t](const VolumeShaper &shaper) -> VolumeShaper::Status {
2056 sp<VolumeShaper::Operation> operationToEnd =
2057 new VolumeShaper::Operation(shaper.mOperation);
2058 // TODO: Ideally we would restore to the exact xOffset position
2059 // as returned by getVolumeShaperState(), but we don't have that
2060 // information when restoring at the client unless we periodically poll
2061 // the server or create shared memory state.
2062 //
2063 // For now, we simply advance to the end of the VolumeShaper effect
2064 // if it has been started.
2065 if (shaper.isStarted()) {
Andy Hungf3702642017-05-05 17:33:32 -07002066 operationToEnd->setNormalizedTime(1.f);
Andy Hung39399b62017-04-21 15:07:45 -07002067 }
2068 return t->applyVolumeShaper(shaper.mConfiguration, operationToEnd);
Andy Hung4ef88d72017-02-21 19:47:53 -08002069 });
Andy Hung4ef88d72017-02-21 19:47:53 -08002070
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002071 mSampleRateHz = sampleRate;
Preetam Singh Ranawat2e17eef2015-08-12 12:11:46 -07002072 mFlags = flags;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002073 mMsecsPerFrame = 1E3f / (mPlaybackRate.mSpeed * sampleRate);
Andy Hungd1c74342015-07-07 16:54:23 -07002074 mFrameSize = t->frameSize();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002075 mTrack = t;
Eric Laurent2beeb502010-07-16 07:43:46 -07002076
Wei Jiae0bbac92016-07-18 16:04:53 -07002077 return updateTrack();
2078}
2079
2080status_t MediaPlayerService::AudioOutput::updateTrack() {
2081 if (mTrack == NULL) {
2082 return NO_ERROR;
2083 }
2084
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002085 status_t res = NO_ERROR;
Wei Jia0162d002015-06-09 11:59:33 -07002086 // Note some output devices may give us a direct track even though we don't specify it.
2087 // Example: Line application b/17459982.
Wei Jiae0bbac92016-07-18 16:04:53 -07002088 if ((mTrack->getFlags()
2089 & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) {
2090 res = mTrack->setPlaybackRate(mPlaybackRate);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002091 if (res == NO_ERROR) {
Wei Jiae0bbac92016-07-18 16:04:53 -07002092 mTrack->setAuxEffectSendLevel(mSendLevel);
2093 res = mTrack->attachAuxEffect(mAuxEffectId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002094 }
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002095 }
Wei Jiae0bbac92016-07-18 16:04:53 -07002096 ALOGV("updateTrack() DONE status %d", res);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002097 return res;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002098}
2099
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002100status_t MediaPlayerService::AudioOutput::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002101{
Steve Block3856b092011-10-20 11:56:00 +01002102 ALOGV("start");
Andy Hungd1c74342015-07-07 16:54:23 -07002103 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08002104 if (mCallbackData != NULL) {
2105 mCallbackData->endTrackSwitch();
2106 }
Glenn Kasten2799d742013-05-30 14:33:29 -07002107 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002108 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07002109 mTrack->setAuxEffectSendLevel(mSendLevel);
Andy Hung39399b62017-04-21 15:07:45 -07002110 status_t status = mTrack->start();
2111 if (status == NO_ERROR) {
2112 mVolumeHandler->setStarted();
2113 }
2114 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002115 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002116 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002117}
2118
Marco Nelissen6b74d672012-02-28 16:07:44 -08002119void MediaPlayerService::AudioOutput::setNextOutput(const sp<AudioOutput>& nextOutput) {
Andy Hungd1c74342015-07-07 16:54:23 -07002120 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08002121 mNextOutput = nextOutput;
2122}
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08002123
Marco Nelissen6b74d672012-02-28 16:07:44 -08002124void MediaPlayerService::AudioOutput::switchToNextOutput() {
2125 ALOGV("switchToNextOutput");
Andy Hungd1c74342015-07-07 16:54:23 -07002126
2127 // Try to acquire the callback lock before moving track (without incurring deadlock).
2128 const unsigned kMaxSwitchTries = 100;
2129 Mutex::Autolock lock(mLock);
2130 for (unsigned tries = 0;;) {
2131 if (mTrack == 0) {
2132 return;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002133 }
Andy Hungd1c74342015-07-07 16:54:23 -07002134 if (mNextOutput != NULL && mNextOutput != this) {
2135 if (mCallbackData != NULL) {
2136 // two alternative approaches
2137#if 1
2138 CallbackData *callbackData = mCallbackData;
2139 mLock.unlock();
2140 // proper acquisition sequence
2141 callbackData->lock();
2142 mLock.lock();
2143 // Caution: it is unlikely that someone deleted our callback or changed our target
2144 if (callbackData != mCallbackData || mNextOutput == NULL || mNextOutput == this) {
2145 // fatal if we are starved out.
2146 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2147 "switchToNextOutput() cannot obtain correct lock sequence");
2148 callbackData->unlock();
2149 continue;
2150 }
2151 callbackData->mSwitching = true; // begin track switch
Wei Jiaadee56a2016-08-05 15:40:34 -07002152 callbackData->setOutput(NULL);
Andy Hungd1c74342015-07-07 16:54:23 -07002153#else
2154 // tryBeginTrackSwitch() returns false if the callback has the lock.
2155 if (!mCallbackData->tryBeginTrackSwitch()) {
2156 // fatal if we are starved out.
2157 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2158 "switchToNextOutput() cannot obtain callback lock");
2159 mLock.unlock();
2160 usleep(5 * 1000 /* usec */); // allow callback to use AudioOutput
2161 mLock.lock();
2162 continue;
2163 }
2164#endif
2165 }
2166
2167 Mutex::Autolock nextLock(mNextOutput->mLock);
2168
2169 // If the next output track is not NULL, then it has been
2170 // opened already for playback.
2171 // This is possible even without the next player being started,
2172 // for example, the next player could be prepared and seeked.
2173 //
2174 // Presuming it isn't advisable to force the track over.
2175 if (mNextOutput->mTrack == NULL) {
2176 ALOGD("Recycling track for gapless playback");
2177 delete mNextOutput->mCallbackData;
2178 mNextOutput->mCallbackData = mCallbackData;
2179 mNextOutput->mRecycledTrack = mTrack;
2180 mNextOutput->mSampleRateHz = mSampleRateHz;
2181 mNextOutput->mMsecsPerFrame = mMsecsPerFrame;
Andy Hungd1c74342015-07-07 16:54:23 -07002182 mNextOutput->mFlags = mFlags;
2183 mNextOutput->mFrameSize = mFrameSize;
2184 close_l();
2185 mCallbackData = NULL; // destruction handled by mNextOutput
2186 } else {
2187 ALOGW("Ignoring gapless playback because next player has already started");
2188 // remove track in case resource needed for future players.
2189 if (mCallbackData != NULL) {
2190 mCallbackData->endTrackSwitch(); // release lock for callbacks before close.
2191 }
2192 close_l();
2193 }
2194 }
2195 break;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002196 }
2197}
2198
Wei Jia7d3f4df2015-03-03 15:28:00 -08002199ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002200{
Andy Hungd1c74342015-07-07 16:54:23 -07002201 Mutex::Autolock lock(mLock);
Glenn Kastenadad3d72014-02-21 14:51:43 -08002202 LOG_ALWAYS_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
Andreas Huber20111aa2009-07-14 16:56:47 -07002203
Steve Block3856b092011-10-20 11:56:00 +01002204 //ALOGV("write(%p, %u)", buffer, size);
Glenn Kasten2799d742013-05-30 14:33:29 -07002205 if (mTrack != 0) {
Andy Hung2f6e73d2016-04-08 12:12:58 -07002206 return mTrack->write(buffer, size, blocking);
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07002207 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002208 return NO_INIT;
2209}
2210
2211void MediaPlayerService::AudioOutput::stop()
2212{
Steve Block3856b092011-10-20 11:56:00 +01002213 ALOGV("stop");
Andy Hungd1c74342015-07-07 16:54:23 -07002214 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002215 if (mTrack != 0) mTrack->stop();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002216}
2217
2218void MediaPlayerService::AudioOutput::flush()
2219{
Steve Block3856b092011-10-20 11:56:00 +01002220 ALOGV("flush");
Andy Hungd1c74342015-07-07 16:54:23 -07002221 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002222 if (mTrack != 0) mTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002223}
2224
2225void MediaPlayerService::AudioOutput::pause()
2226{
Steve Block3856b092011-10-20 11:56:00 +01002227 ALOGV("pause");
Andy Hungd1c74342015-07-07 16:54:23 -07002228 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002229 if (mTrack != 0) mTrack->pause();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002230}
2231
2232void MediaPlayerService::AudioOutput::close()
2233{
Steve Block3856b092011-10-20 11:56:00 +01002234 ALOGV("close");
Erik Wolsheimer7845a1f2015-10-30 12:07:52 -07002235 sp<AudioTrack> track;
2236 {
2237 Mutex::Autolock lock(mLock);
2238 track = mTrack;
2239 close_l(); // clears mTrack
2240 }
2241 // destruction of the track occurs outside of mutex.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002242}
2243
2244void MediaPlayerService::AudioOutput::setVolume(float left, float right)
2245{
Steve Block3856b092011-10-20 11:56:00 +01002246 ALOGV("setVolume(%f, %f)", left, right);
Andy Hungd1c74342015-07-07 16:54:23 -07002247 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002248 mLeftVolume = left;
2249 mRightVolume = right;
Glenn Kasten2799d742013-05-30 14:33:29 -07002250 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002251 mTrack->setVolume(left, right);
2252 }
2253}
2254
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002255status_t MediaPlayerService::AudioOutput::setPlaybackRate(const AudioPlaybackRate &rate)
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002256{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002257 ALOGV("setPlaybackRate(%f %f %d %d)",
2258 rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Andy Hungd1c74342015-07-07 16:54:23 -07002259 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002260 if (mTrack == 0) {
2261 // remember rate so that we can set it when the track is opened
2262 mPlaybackRate = rate;
2263 return OK;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002264 }
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002265 status_t res = mTrack->setPlaybackRate(rate);
2266 if (res != NO_ERROR) {
2267 return res;
2268 }
2269 // rate.mSpeed is always greater than 0 if setPlaybackRate succeeded
2270 CHECK_GT(rate.mSpeed, 0.f);
2271 mPlaybackRate = rate;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002272 if (mSampleRateHz != 0) {
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002273 mMsecsPerFrame = 1E3f / (rate.mSpeed * mSampleRateHz);
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002274 }
2275 return res;
2276}
2277
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002278status_t MediaPlayerService::AudioOutput::getPlaybackRate(AudioPlaybackRate *rate)
2279{
2280 ALOGV("setPlaybackRate");
Andy Hungd1c74342015-07-07 16:54:23 -07002281 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002282 if (mTrack == 0) {
2283 return NO_INIT;
2284 }
2285 *rate = mTrack->getPlaybackRate();
2286 return NO_ERROR;
2287}
2288
Eric Laurent2beeb502010-07-16 07:43:46 -07002289status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
2290{
Steve Block3856b092011-10-20 11:56:00 +01002291 ALOGV("setAuxEffectSendLevel(%f)", level);
Andy Hungd1c74342015-07-07 16:54:23 -07002292 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002293 mSendLevel = level;
Glenn Kasten2799d742013-05-30 14:33:29 -07002294 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002295 return mTrack->setAuxEffectSendLevel(level);
2296 }
2297 return NO_ERROR;
2298}
2299
2300status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
2301{
Steve Block3856b092011-10-20 11:56:00 +01002302 ALOGV("attachAuxEffect(%d)", effectId);
Andy Hungd1c74342015-07-07 16:54:23 -07002303 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002304 mAuxEffectId = effectId;
Glenn Kasten2799d742013-05-30 14:33:29 -07002305 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002306 return mTrack->attachAuxEffect(effectId);
2307 }
2308 return NO_ERROR;
2309}
2310
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002311VolumeShaper::Status MediaPlayerService::AudioOutput::applyVolumeShaper(
2312 const sp<VolumeShaper::Configuration>& configuration,
2313 const sp<VolumeShaper::Operation>& operation)
2314{
2315 Mutex::Autolock lock(mLock);
2316 ALOGV("AudioOutput::applyVolumeShaper");
Andy Hung4ef88d72017-02-21 19:47:53 -08002317
Andy Hung4ef88d72017-02-21 19:47:53 -08002318 mVolumeHandler->setIdIfNecessary(configuration);
Andy Hung39399b62017-04-21 15:07:45 -07002319
2320 VolumeShaper::Status status;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002321 if (mTrack != 0) {
Andy Hung39399b62017-04-21 15:07:45 -07002322 status = mTrack->applyVolumeShaper(configuration, operation);
2323 if (status >= 0) {
2324 (void)mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hungf3702642017-05-05 17:33:32 -07002325 if (mTrack->isPlaying()) { // match local AudioTrack to properly restore.
2326 mVolumeHandler->setStarted();
2327 }
Andy Hung39399b62017-04-21 15:07:45 -07002328 }
Andy Hung4ef88d72017-02-21 19:47:53 -08002329 } else {
Andy Hungc01eddb2017-07-21 16:42:41 -07002330 // VolumeShapers are not affected when a track moves between players for
2331 // gapless playback (setNextMediaPlayer).
2332 // We forward VolumeShaper operations that do not change configuration
2333 // to the new player so that unducking may occur as expected.
2334 // Unducking is an idempotent operation, same if applied back-to-back.
2335 if (configuration->getType() == VolumeShaper::Configuration::TYPE_ID
2336 && mNextOutput != nullptr) {
2337 ALOGV("applyVolumeShaper: Attempting to forward missed operation: %s %s",
2338 configuration->toString().c_str(), operation->toString().c_str());
2339 Mutex::Autolock nextLock(mNextOutput->mLock);
2340
2341 // recycled track should be forwarded from this AudioSink by switchToNextOutput
2342 sp<AudioTrack> track = mNextOutput->mRecycledTrack;
2343 if (track != nullptr) {
2344 ALOGD("Forward VolumeShaper operation to recycled track %p", track.get());
2345 (void)track->applyVolumeShaper(configuration, operation);
2346 } else {
2347 // There is a small chance that the unduck occurs after the next
2348 // player has already started, but before it is registered to receive
2349 // the unduck command.
2350 track = mNextOutput->mTrack;
2351 if (track != nullptr) {
2352 ALOGD("Forward VolumeShaper operation to track %p", track.get());
2353 (void)track->applyVolumeShaper(configuration, operation);
2354 }
2355 }
2356 }
Andy Hung39399b62017-04-21 15:07:45 -07002357 status = mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002358 }
Andy Hung39399b62017-04-21 15:07:45 -07002359 return status;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002360}
2361
2362sp<VolumeShaper::State> MediaPlayerService::AudioOutput::getVolumeShaperState(int id)
2363{
2364 Mutex::Autolock lock(mLock);
2365 if (mTrack != 0) {
2366 return mTrack->getVolumeShaperState(id);
Andy Hung4ef88d72017-02-21 19:47:53 -08002367 } else {
2368 return mVolumeHandler->getVolumeShaperState(id);
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002369 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002370}
2371
Andreas Huber20111aa2009-07-14 16:56:47 -07002372// static
2373void MediaPlayerService::AudioOutput::CallbackWrapper(
Glenn Kastend217a8c2011-06-01 15:20:35 -07002374 int event, void *cookie, void *info) {
Steve Block3856b092011-10-20 11:56:00 +01002375 //ALOGV("callbackwrapper");
Marco Nelissen6b74d672012-02-28 16:07:44 -08002376 CallbackData *data = (CallbackData*)cookie;
Andy Hungd1c74342015-07-07 16:54:23 -07002377 // lock to ensure we aren't caught in the middle of a track switch.
Marco Nelissen6b74d672012-02-28 16:07:44 -08002378 data->lock();
2379 AudioOutput *me = data->getOutput();
Andreas Huber20111aa2009-07-14 16:56:47 -07002380 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002381 if (me == NULL) {
2382 // no output set, likely because the track was scheduled to be reused
2383 // by another player, but the format turned out to be incompatible.
2384 data->unlock();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002385 if (buffer != NULL) {
2386 buffer->size = 0;
2387 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08002388 return;
2389 }
Andreas Huber20111aa2009-07-14 16:56:47 -07002390
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002391 switch(event) {
2392 case AudioTrack::EVENT_MORE_DATA: {
2393 size_t actualSize = (*me->mCallback)(
2394 me, buffer->raw, buffer->size, me->mCallbackCookie,
2395 CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002396
Andy Hung719b46b2015-05-31 22:18:25 -07002397 // Log when no data is returned from the callback.
2398 // (1) We may have no data (especially with network streaming sources).
2399 // (2) We may have reached the EOS and the audio track is not stopped yet.
2400 // Note that AwesomePlayer/AudioPlayer will only return zero size when it reaches the EOS.
2401 // NuPlayerRenderer will return zero when it doesn't have data (it doesn't block to fill).
2402 //
2403 // This is a benign busy-wait, with the next data request generated 10 ms or more later;
2404 // nevertheless for power reasons, we don't want to see too many of these.
Andreas Huber2e8ffaf2010-02-18 16:45:13 -08002405
Andy Hung719b46b2015-05-31 22:18:25 -07002406 ALOGV_IF(actualSize == 0 && buffer->size > 0, "callbackwrapper: empty buffer returned");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002407
2408 buffer->size = actualSize;
2409 } break;
2410
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002411 case AudioTrack::EVENT_STREAM_END:
Andy Hung719b46b2015-05-31 22:18:25 -07002412 // currently only occurs for offloaded callbacks
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002413 ALOGV("callbackwrapper: deliver EVENT_STREAM_END");
2414 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2415 me->mCallbackCookie, CB_EVENT_STREAM_END);
2416 break;
2417
2418 case AudioTrack::EVENT_NEW_IAUDIOTRACK :
2419 ALOGV("callbackwrapper: deliver EVENT_TEAR_DOWN");
2420 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2421 me->mCallbackCookie, CB_EVENT_TEAR_DOWN);
2422 break;
2423
Glenn Kasten421743b2015-06-01 08:18:08 -07002424 case AudioTrack::EVENT_UNDERRUN:
Andy Hung719b46b2015-05-31 22:18:25 -07002425 // This occurs when there is no data available, typically
Glenn Kasten421743b2015-06-01 08:18:08 -07002426 // when there is a failure to supply data to the AudioTrack. It can also
2427 // occur in non-offloaded mode when the audio device comes out of standby.
2428 //
Andy Hung719b46b2015-05-31 22:18:25 -07002429 // If an AudioTrack underruns it outputs silence. Since this happens suddenly
2430 // it may sound like an audible pop or glitch.
2431 //
2432 // The underrun event is sent once per track underrun; the condition is reset
2433 // when more data is sent to the AudioTrack.
Eric Laurente93cc032016-05-05 10:15:10 -07002434 ALOGD("callbackwrapper: EVENT_UNDERRUN (discarded)");
Glenn Kasten421743b2015-06-01 08:18:08 -07002435 break;
2436
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002437 default:
2438 ALOGE("received unknown event type: %d inside CallbackWrapper !", event);
Andreas Huber51c1e0e2011-04-04 11:43:40 -07002439 }
2440
Marco Nelissen6b74d672012-02-28 16:07:44 -08002441 data->unlock();
Andreas Huber20111aa2009-07-14 16:56:47 -07002442}
2443
Glenn Kastend848eb42016-03-08 13:42:11 -08002444audio_session_t MediaPlayerService::AudioOutput::getSessionId() const
Eric Laurent8c563ed2010-10-07 18:23:03 -07002445{
Andy Hungd1c74342015-07-07 16:54:23 -07002446 Mutex::Autolock lock(mLock);
Eric Laurent8c563ed2010-10-07 18:23:03 -07002447 return mSessionId;
2448}
2449
Eric Laurent6f59db12013-07-26 17:16:50 -07002450uint32_t MediaPlayerService::AudioOutput::getSampleRate() const
2451{
Andy Hungd1c74342015-07-07 16:54:23 -07002452 Mutex::Autolock lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -07002453 if (mTrack == 0) return 0;
2454 return mTrack->getSampleRate();
2455}
2456
Andy Hungf2c87b32016-04-07 19:49:29 -07002457int64_t MediaPlayerService::AudioOutput::getBufferDurationInUs() const
2458{
2459 Mutex::Autolock lock(mLock);
2460 if (mTrack == 0) {
2461 return 0;
2462 }
2463 int64_t duration;
2464 if (mTrack->getBufferDurationInUs(&duration) != OK) {
2465 return 0;
2466 }
2467 return duration;
2468}
2469
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002470////////////////////////////////////////////////////////////////////////////////
2471
2472struct CallbackThread : public Thread {
2473 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
2474 MediaPlayerBase::AudioSink::AudioCallback cb,
2475 void *cookie);
2476
2477protected:
2478 virtual ~CallbackThread();
2479
2480 virtual bool threadLoop();
2481
2482private:
2483 wp<MediaPlayerBase::AudioSink> mSink;
2484 MediaPlayerBase::AudioSink::AudioCallback mCallback;
2485 void *mCookie;
2486 void *mBuffer;
2487 size_t mBufferSize;
2488
2489 CallbackThread(const CallbackThread &);
2490 CallbackThread &operator=(const CallbackThread &);
2491};
2492
2493CallbackThread::CallbackThread(
2494 const wp<MediaPlayerBase::AudioSink> &sink,
2495 MediaPlayerBase::AudioSink::AudioCallback cb,
2496 void *cookie)
2497 : mSink(sink),
2498 mCallback(cb),
2499 mCookie(cookie),
2500 mBuffer(NULL),
2501 mBufferSize(0) {
2502}
2503
2504CallbackThread::~CallbackThread() {
2505 if (mBuffer) {
2506 free(mBuffer);
2507 mBuffer = NULL;
2508 }
2509}
2510
2511bool CallbackThread::threadLoop() {
2512 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
2513 if (sink == NULL) {
2514 return false;
2515 }
2516
2517 if (mBuffer == NULL) {
2518 mBufferSize = sink->bufferSize();
2519 mBuffer = malloc(mBufferSize);
2520 }
2521
2522 size_t actualSize =
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002523 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie,
2524 MediaPlayerBase::AudioSink::CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002525
2526 if (actualSize > 0) {
2527 sink->write(mBuffer, actualSize);
Andy Hunga31335a2014-08-20 17:37:59 -07002528 // Could return false on sink->write() error or short count.
2529 // Not necessarily appropriate but would work for AudioCache behavior.
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002530 }
2531
2532 return true;
2533}
2534
2535////////////////////////////////////////////////////////////////////////////////
2536
Chong Zhange5b9b692017-05-11 11:44:56 -07002537void MediaPlayerService::addBatteryData(uint32_t params) {
2538 mBatteryTracker.addBatteryData(params);
2539}
2540
2541status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
2542 return mBatteryTracker.pullBatteryData(reply);
2543}
2544
2545MediaPlayerService::BatteryTracker::BatteryTracker() {
2546 mBatteryAudio.refCount = 0;
2547 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2548 mBatteryAudio.deviceOn[i] = 0;
2549 mBatteryAudio.lastTime[i] = 0;
2550 mBatteryAudio.totalTime[i] = 0;
2551 }
2552 // speaker is on by default
2553 mBatteryAudio.deviceOn[SPEAKER] = 1;
2554
2555 // reset battery stats
2556 // if the mediaserver has crashed, battery stats could be left
2557 // in bad state, reset the state upon service start.
2558 BatteryNotifier::getInstance().noteResetVideo();
2559}
2560
2561void MediaPlayerService::BatteryTracker::addBatteryData(uint32_t params)
Gloria Wang7cf180c2011-02-19 18:37:57 -08002562{
2563 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002564
2565 int32_t time = systemTime() / 1000000L;
2566
2567 // change audio output devices. This notification comes from AudioFlinger
2568 if ((params & kBatteryDataSpeakerOn)
2569 || (params & kBatteryDataOtherAudioDeviceOn)) {
2570
2571 int deviceOn[NUM_AUDIO_DEVICES];
2572 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2573 deviceOn[i] = 0;
2574 }
2575
2576 if ((params & kBatteryDataSpeakerOn)
2577 && (params & kBatteryDataOtherAudioDeviceOn)) {
2578 deviceOn[SPEAKER_AND_OTHER] = 1;
2579 } else if (params & kBatteryDataSpeakerOn) {
2580 deviceOn[SPEAKER] = 1;
2581 } else {
2582 deviceOn[OTHER_AUDIO_DEVICE] = 1;
2583 }
2584
2585 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2586 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
2587
2588 if (mBatteryAudio.refCount > 0) { // if playing audio
2589 if (!deviceOn[i]) {
2590 mBatteryAudio.lastTime[i] += time;
2591 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2592 mBatteryAudio.lastTime[i] = 0;
2593 } else {
2594 mBatteryAudio.lastTime[i] = 0 - time;
2595 }
2596 }
2597
2598 mBatteryAudio.deviceOn[i] = deviceOn[i];
2599 }
2600 }
2601 return;
2602 }
2603
Marco Nelissenb7848f12014-12-04 08:57:56 -08002604 // an audio stream is started
Gloria Wang9ee159b2011-02-24 14:51:45 -08002605 if (params & kBatteryDataAudioFlingerStart) {
2606 // record the start time only if currently no other audio
2607 // is being played
2608 if (mBatteryAudio.refCount == 0) {
2609 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2610 if (mBatteryAudio.deviceOn[i]) {
2611 mBatteryAudio.lastTime[i] -= time;
2612 }
2613 }
2614 }
2615
2616 mBatteryAudio.refCount ++;
2617 return;
2618
2619 } else if (params & kBatteryDataAudioFlingerStop) {
2620 if (mBatteryAudio.refCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002621 ALOGW("Battery track warning: refCount is <= 0");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002622 return;
2623 }
2624
2625 // record the stop time only if currently this is the only
2626 // audio being played
2627 if (mBatteryAudio.refCount == 1) {
2628 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2629 if (mBatteryAudio.deviceOn[i]) {
2630 mBatteryAudio.lastTime[i] += time;
2631 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2632 mBatteryAudio.lastTime[i] = 0;
2633 }
2634 }
2635 }
2636
2637 mBatteryAudio.refCount --;
2638 return;
2639 }
2640
Andy Hung1afd0982016-11-08 16:13:44 -08002641 uid_t uid = IPCThreadState::self()->getCallingUid();
Gloria Wang7cf180c2011-02-19 18:37:57 -08002642 if (uid == AID_MEDIA) {
2643 return;
2644 }
2645 int index = mBatteryData.indexOfKey(uid);
Gloria Wang7cf180c2011-02-19 18:37:57 -08002646
2647 if (index < 0) { // create a new entry for this UID
2648 BatteryUsageInfo info;
2649 info.audioTotalTime = 0;
2650 info.videoTotalTime = 0;
2651 info.audioLastTime = 0;
2652 info.videoLastTime = 0;
2653 info.refCount = 0;
2654
Gloria Wang9ee159b2011-02-24 14:51:45 -08002655 if (mBatteryData.add(uid, info) == NO_MEMORY) {
Steve Block29357bc2012-01-06 19:20:56 +00002656 ALOGE("Battery track error: no memory for new app");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002657 return;
2658 }
Gloria Wang7cf180c2011-02-19 18:37:57 -08002659 }
2660
2661 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
2662
2663 if (params & kBatteryDataCodecStarted) {
2664 if (params & kBatteryDataTrackAudio) {
2665 info.audioLastTime -= time;
2666 info.refCount ++;
2667 }
2668 if (params & kBatteryDataTrackVideo) {
2669 info.videoLastTime -= time;
2670 info.refCount ++;
2671 }
2672 } else {
2673 if (info.refCount == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002674 ALOGW("Battery track warning: refCount is already 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002675 return;
2676 } else if (info.refCount < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00002677 ALOGE("Battery track error: refCount < 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002678 mBatteryData.removeItem(uid);
2679 return;
2680 }
2681
2682 if (params & kBatteryDataTrackAudio) {
2683 info.audioLastTime += time;
2684 info.refCount --;
2685 }
2686 if (params & kBatteryDataTrackVideo) {
2687 info.videoLastTime += time;
2688 info.refCount --;
2689 }
2690
2691 // no stream is being played by this UID
2692 if (info.refCount == 0) {
2693 info.audioTotalTime += info.audioLastTime;
2694 info.audioLastTime = 0;
2695 info.videoTotalTime += info.videoLastTime;
2696 info.videoLastTime = 0;
2697 }
2698 }
2699}
2700
Chong Zhange5b9b692017-05-11 11:44:56 -07002701status_t MediaPlayerService::BatteryTracker::pullBatteryData(Parcel* reply) {
Gloria Wang7cf180c2011-02-19 18:37:57 -08002702 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002703
2704 // audio output devices usage
2705 int32_t time = systemTime() / 1000000L; //in ms
2706 int32_t totalTime;
2707
2708 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2709 totalTime = mBatteryAudio.totalTime[i];
2710
2711 if (mBatteryAudio.deviceOn[i]
2712 && (mBatteryAudio.lastTime[i] != 0)) {
2713 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
2714 totalTime += tmpTime;
2715 }
2716
2717 reply->writeInt32(totalTime);
2718 // reset the total time
2719 mBatteryAudio.totalTime[i] = 0;
2720 }
2721
2722 // codec usage
Gloria Wang7cf180c2011-02-19 18:37:57 -08002723 BatteryUsageInfo info;
2724 int size = mBatteryData.size();
2725
2726 reply->writeInt32(size);
2727 int i = 0;
2728
2729 while (i < size) {
2730 info = mBatteryData.valueAt(i);
2731
2732 reply->writeInt32(mBatteryData.keyAt(i)); //UID
2733 reply->writeInt32(info.audioTotalTime);
2734 reply->writeInt32(info.videoTotalTime);
2735
2736 info.audioTotalTime = 0;
2737 info.videoTotalTime = 0;
2738
2739 // remove the UID entry where no stream is being played
2740 if (info.refCount <= 0) {
2741 mBatteryData.removeItemsAt(i);
2742 size --;
2743 i --;
2744 }
2745 i++;
2746 }
2747 return NO_ERROR;
2748}
nikoa64c8c72009-07-20 15:07:26 -07002749} // namespace android