blob: ba98f18e47ad5def43a92eb18940bef533b8e9d6 [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
Glenn Kastenfff6d712012-01-12 16:38:12 -08001272status_t MediaPlayerService::Client::setAudioStreamType(audio_stream_type_t type)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001273{
Steve Block3856b092011-10-20 11:56:00 +01001274 ALOGV("[%d] setAudioStreamType(%d)", mConnId, type);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001275 // TODO: for hardware output, call player instead
1276 Mutex::Autolock l(mLock);
1277 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1278 return NO_ERROR;
1279}
1280
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001281status_t MediaPlayerService::Client::setAudioAttributes_l(const Parcel &parcel)
1282{
1283 if (mAudioAttributes != NULL) { free(mAudioAttributes); }
1284 mAudioAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001285 if (mAudioAttributes == NULL) {
1286 return NO_MEMORY;
1287 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001288 unmarshallAudioAttributes(parcel, mAudioAttributes);
1289
1290 ALOGV("setAudioAttributes_l() usage=%d content=%d flags=0x%x tags=%s",
1291 mAudioAttributes->usage, mAudioAttributes->content_type, mAudioAttributes->flags,
1292 mAudioAttributes->tags);
1293
1294 if (mAudioOutput != 0) {
1295 mAudioOutput->setAudioAttributes(mAudioAttributes);
1296 }
1297 return NO_ERROR;
1298}
1299
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001300status_t MediaPlayerService::Client::setLooping(int loop)
1301{
Steve Block3856b092011-10-20 11:56:00 +01001302 ALOGV("[%d] setLooping(%d)", mConnId, loop);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001303 mLoop = loop;
1304 sp<MediaPlayerBase> p = getPlayer();
1305 if (p != 0) return p->setLooping(loop);
1306 return NO_ERROR;
1307}
1308
1309status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1310{
Steve Block3856b092011-10-20 11:56:00 +01001311 ALOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
John Grossman761defc2012-02-09 15:09:05 -08001312
1313 // for hardware output, call player instead
1314 sp<MediaPlayerBase> p = getPlayer();
1315 {
1316 Mutex::Autolock l(mLock);
1317 if (p != 0 && p->hardwareOutput()) {
1318 MediaPlayerHWInterface* hwp =
1319 reinterpret_cast<MediaPlayerHWInterface*>(p.get());
1320 return hwp->setVolume(leftVolume, rightVolume);
1321 } else {
1322 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1323 return NO_ERROR;
1324 }
1325 }
1326
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001327 return NO_ERROR;
1328}
1329
Eric Laurent2beeb502010-07-16 07:43:46 -07001330status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1331{
Steve Block3856b092011-10-20 11:56:00 +01001332 ALOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
Eric Laurent2beeb502010-07-16 07:43:46 -07001333 Mutex::Autolock l(mLock);
1334 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1335 return NO_ERROR;
1336}
1337
1338status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1339{
Steve Block3856b092011-10-20 11:56:00 +01001340 ALOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
Eric Laurent2beeb502010-07-16 07:43:46 -07001341 Mutex::Autolock l(mLock);
1342 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1343 return NO_ERROR;
1344}
Nicolas Catania48290382009-07-10 13:53:06 -07001345
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001346status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
Steve Block3856b092011-10-20 11:56:00 +01001347 ALOGV("[%d] setParameter(%d)", mConnId, key);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001348 switch (key) {
1349 case KEY_PARAMETER_AUDIO_ATTRIBUTES:
1350 {
1351 Mutex::Autolock l(mLock);
1352 return setAudioAttributes_l(request);
1353 }
1354 default:
1355 sp<MediaPlayerBase> p = getPlayer();
1356 if (p == 0) { return UNKNOWN_ERROR; }
1357 return p->setParameter(key, request);
1358 }
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001359}
1360
1361status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
Steve Block3856b092011-10-20 11:56:00 +01001362 ALOGV("[%d] getParameter(%d)", mConnId, key);
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001363 sp<MediaPlayerBase> p = getPlayer();
1364 if (p == 0) return UNKNOWN_ERROR;
1365 return p->getParameter(key, reply);
1366}
1367
John Grossmanc795b642012-02-22 15:38:35 -08001368status_t MediaPlayerService::Client::setRetransmitEndpoint(
1369 const struct sockaddr_in* endpoint) {
1370
1371 if (NULL != endpoint) {
1372 uint32_t a = ntohl(endpoint->sin_addr.s_addr);
1373 uint16_t p = ntohs(endpoint->sin_port);
1374 ALOGV("[%d] setRetransmitEndpoint(%u.%u.%u.%u:%hu)", mConnId,
1375 (a >> 24), (a >> 16) & 0xFF, (a >> 8) & 0xFF, (a & 0xFF), p);
1376 } else {
1377 ALOGV("[%d] setRetransmitEndpoint = <none>", mConnId);
1378 }
1379
1380 sp<MediaPlayerBase> p = getPlayer();
1381
1382 // Right now, the only valid time to set a retransmit endpoint is before
1383 // player selection has been made (since the presence or absence of a
1384 // retransmit endpoint is going to determine which player is selected during
1385 // setDataSource).
1386 if (p != 0) return INVALID_OPERATION;
1387
1388 if (NULL != endpoint) {
1389 mRetransmitEndpoint = *endpoint;
1390 mRetransmitEndpointValid = true;
1391 } else {
1392 mRetransmitEndpointValid = false;
1393 }
1394
1395 return NO_ERROR;
1396}
1397
John Grossman44a7e422012-06-21 17:29:24 -07001398status_t MediaPlayerService::Client::getRetransmitEndpoint(
1399 struct sockaddr_in* endpoint)
1400{
1401 if (NULL == endpoint)
1402 return BAD_VALUE;
1403
1404 sp<MediaPlayerBase> p = getPlayer();
1405
1406 if (p != NULL)
1407 return p->getRetransmitEndpoint(endpoint);
1408
1409 if (!mRetransmitEndpointValid)
1410 return NO_INIT;
1411
1412 *endpoint = mRetransmitEndpoint;
1413
1414 return NO_ERROR;
1415}
1416
Gloria Wangb483c472011-04-11 17:23:27 -07001417void MediaPlayerService::Client::notify(
1418 void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001419{
1420 Client* client = static_cast<Client*>(cookie);
James Dongb8a98252012-08-26 16:13:03 -07001421 if (client == NULL) {
1422 return;
1423 }
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001424
James Dongb8a98252012-08-26 16:13:03 -07001425 sp<IMediaPlayerClient> c;
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001426 sp<Client> nextClient;
1427 status_t errStartNext = NO_ERROR;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001428 {
1429 Mutex::Autolock l(client->mLock);
James Dongb8a98252012-08-26 16:13:03 -07001430 c = client->mClient;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001431 if (msg == MEDIA_PLAYBACK_COMPLETE && client->mNextClient != NULL) {
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001432 nextClient = client->mNextClient;
1433
John Grossmancb0b7552012-08-23 17:47:31 -07001434 if (client->mAudioOutput != NULL)
1435 client->mAudioOutput->switchToNextOutput();
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001436
1437 errStartNext = nextClient->start();
1438 }
1439 }
1440
1441 if (nextClient != NULL) {
1442 sp<IMediaPlayerClient> nc;
1443 {
1444 Mutex::Autolock l(nextClient->mLock);
1445 nc = nextClient->mClient;
1446 }
1447 if (nc != NULL) {
1448 if (errStartNext == NO_ERROR) {
1449 nc->notify(MEDIA_INFO, MEDIA_INFO_STARTED_AS_NEXT, 0, obj);
1450 } else {
1451 nc->notify(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN , 0, obj);
1452 ALOGE("gapless:start playback for next track failed, err(%d)", errStartNext);
Wei Jia2afac0c2016-01-07 12:13:07 -08001453 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001454 }
1455 }
1456
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001457 if (MEDIA_INFO == msg &&
Nicolas Catania48290382009-07-10 13:53:06 -07001458 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikoa64c8c72009-07-20 15:07:26 -07001459 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania48290382009-07-10 13:53:06 -07001460
1461 if(client->shouldDropMetadata(metadata_type)) {
1462 return;
1463 }
1464
1465 // Update the list of metadata that have changed. getMetadata
1466 // also access mMetadataUpdated and clears it.
1467 client->addNewMetadataUpdate(metadata_type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001468 }
James Dongb8a98252012-08-26 16:13:03 -07001469
1470 if (c != NULL) {
1471 ALOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
1472 c->notify(msg, ext1, ext2, obj);
1473 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001474}
1475
Nicolas Catania48290382009-07-10 13:53:06 -07001476
nikoa64c8c72009-07-20 15:07:26 -07001477bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001478{
Nicolas Catania48290382009-07-10 13:53:06 -07001479 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001480
Nicolas Catania48290382009-07-10 13:53:06 -07001481 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001482 return true;
1483 }
1484
Nicolas Catania48290382009-07-10 13:53:06 -07001485 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001486 return false;
Nicolas Catania48290382009-07-10 13:53:06 -07001487 } else {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001488 return true;
1489 }
1490}
1491
Nicolas Catania48290382009-07-10 13:53:06 -07001492
nikoa64c8c72009-07-20 15:07:26 -07001493void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania48290382009-07-10 13:53:06 -07001494 Mutex::Autolock lock(mLock);
1495 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1496 mMetadataUpdated.add(metadata_type);
1497 }
1498}
1499
Hassan Shojaniacefac142017-02-06 21:02:02 -08001500// Modular DRM
1501status_t MediaPlayerService::Client::prepareDrm(const uint8_t uuid[16],
1502 const Vector<uint8_t>& drmSessionId)
1503{
1504 ALOGV("[%d] prepareDrm", mConnId);
1505 sp<MediaPlayerBase> p = getPlayer();
1506 if (p == 0) return UNKNOWN_ERROR;
1507
1508 status_t ret = p->prepareDrm(uuid, drmSessionId);
1509 ALOGV("prepareDrm ret: %d", ret);
1510
1511 return ret;
1512}
1513
1514status_t MediaPlayerService::Client::releaseDrm()
1515{
1516 ALOGV("[%d] releaseDrm", mConnId);
1517 sp<MediaPlayerBase> p = getPlayer();
1518 if (p == 0) return UNKNOWN_ERROR;
1519
1520 status_t ret = p->releaseDrm();
1521 ALOGV("releaseDrm ret: %d", ret);
1522
1523 return ret;
1524}
1525
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001526#if CALLBACK_ANTAGONIZER
1527const int Antagonizer::interval = 10000; // 10 msecs
1528
1529Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1530 mExit(false), mActive(false), mClient(client), mCb(cb)
1531{
1532 createThread(callbackThread, this);
1533}
1534
1535void Antagonizer::kill()
1536{
1537 Mutex::Autolock _l(mLock);
1538 mActive = false;
1539 mExit = true;
1540 mCondition.wait(mLock);
1541}
1542
1543int Antagonizer::callbackThread(void* user)
1544{
Steve Blockb8a80522011-12-20 16:23:08 +00001545 ALOGD("Antagonizer started");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001546 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1547 while (!p->mExit) {
1548 if (p->mActive) {
Steve Block3856b092011-10-20 11:56:00 +01001549 ALOGV("send event");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001550 p->mCb(p->mClient, 0, 0, 0);
1551 }
1552 usleep(interval);
1553 }
1554 Mutex::Autolock _l(p->mLock);
1555 p->mCondition.signal();
Steve Blockb8a80522011-12-20 16:23:08 +00001556 ALOGD("Antagonizer stopped");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001557 return 0;
1558}
1559#endif
1560
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001561#undef LOG_TAG
1562#define LOG_TAG "AudioSink"
Andy Hung1afd0982016-11-08 16:13:44 -08001563MediaPlayerService::AudioOutput::AudioOutput(audio_session_t sessionId, uid_t uid, int pid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001564 const audio_attributes_t* attr)
Andreas Huber20111aa2009-07-14 16:56:47 -07001565 : mCallback(NULL),
Eric Laurenta514bdb2010-06-21 09:27:30 -07001566 mCallbackCookie(NULL),
Marco Nelissen6b74d672012-02-28 16:07:44 -08001567 mCallbackData(NULL),
Andy Hungd1c74342015-07-07 16:54:23 -07001568 mStreamType(AUDIO_STREAM_MUSIC),
Andy Hungd1c74342015-07-07 16:54:23 -07001569 mLeftVolume(1.0),
1570 mRightVolume(1.0),
1571 mPlaybackRate(AUDIO_PLAYBACK_RATE_DEFAULT),
1572 mSampleRateHz(0),
1573 mMsecsPerFrame(0),
1574 mFrameSize(0),
Eric Laurent1948eb32012-04-13 16:50:19 -07001575 mSessionId(sessionId),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001576 mUid(uid),
Marco Nelissend457c972014-02-11 08:47:07 -08001577 mPid(pid),
Andy Hungd1c74342015-07-07 16:54:23 -07001578 mSendLevel(0.0),
1579 mAuxEffectId(0),
Andy Hung4ef88d72017-02-21 19:47:53 -08001580 mFlags(AUDIO_OUTPUT_FLAG_NONE),
Ivan Lozano8cf3a072017-08-09 09:01:33 -07001581 mVolumeHandler(new media::VolumeHandler())
Andy Hungd1c74342015-07-07 16:54:23 -07001582{
Steve Block3856b092011-10-20 11:56:00 +01001583 ALOGV("AudioOutput(%d)", sessionId);
Eric Laurent43562692015-07-15 16:49:07 -07001584 if (attr != NULL) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001585 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1586 if (mAttributes != NULL) {
1587 memcpy(mAttributes, attr, sizeof(audio_attributes_t));
1588 mStreamType = audio_attributes_to_stream_type(attr);
1589 }
1590 } else {
1591 mAttributes = NULL;
Eric Laurent43562692015-07-15 16:49:07 -07001592 }
1593
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001594 setMinBufferCount();
1595}
1596
1597MediaPlayerService::AudioOutput::~AudioOutput()
1598{
1599 close();
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001600 free(mAttributes);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001601 delete mCallbackData;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001602}
1603
Andy Hungd1c74342015-07-07 16:54:23 -07001604//static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001605void MediaPlayerService::AudioOutput::setMinBufferCount()
1606{
1607 char value[PROPERTY_VALUE_MAX];
1608 if (property_get("ro.kernel.qemu", value, 0)) {
1609 mIsOnEmulator = true;
1610 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1611 }
1612}
1613
Andy Hungd1c74342015-07-07 16:54:23 -07001614// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001615bool MediaPlayerService::AudioOutput::isOnEmulator()
1616{
Andy Hungd1c74342015-07-07 16:54:23 -07001617 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001618 return mIsOnEmulator;
1619}
1620
Andy Hungd1c74342015-07-07 16:54:23 -07001621// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001622int MediaPlayerService::AudioOutput::getMinBufferCount()
1623{
Andy Hungd1c74342015-07-07 16:54:23 -07001624 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001625 return mMinBufferCount;
1626}
1627
1628ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1629{
Andy Hungd1c74342015-07-07 16:54:23 -07001630 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001631 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001632 return mTrack->frameCount() * mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001633}
1634
1635ssize_t MediaPlayerService::AudioOutput::frameCount() const
1636{
Andy Hungd1c74342015-07-07 16:54:23 -07001637 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001638 if (mTrack == 0) return NO_INIT;
1639 return mTrack->frameCount();
1640}
1641
1642ssize_t MediaPlayerService::AudioOutput::channelCount() const
1643{
Andy Hungd1c74342015-07-07 16:54:23 -07001644 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001645 if (mTrack == 0) return NO_INIT;
1646 return mTrack->channelCount();
1647}
1648
1649ssize_t MediaPlayerService::AudioOutput::frameSize() const
1650{
Andy Hungd1c74342015-07-07 16:54:23 -07001651 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001652 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001653 return mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001654}
1655
1656uint32_t MediaPlayerService::AudioOutput::latency () const
1657{
Andy Hungd1c74342015-07-07 16:54:23 -07001658 Mutex::Autolock lock(mLock);
Eric Laurentdb354e52012-03-05 17:27:11 -08001659 if (mTrack == 0) return 0;
1660 return mTrack->latency();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001661}
1662
1663float MediaPlayerService::AudioOutput::msecsPerFrame() const
1664{
Andy Hungd1c74342015-07-07 16:54:23 -07001665 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001666 return mMsecsPerFrame;
1667}
1668
Marco Nelissen4110c102012-03-29 09:31:28 -07001669status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position) const
Eric Laurent342e9cf2010-01-19 17:37:09 -08001670{
Andy Hungd1c74342015-07-07 16:54:23 -07001671 Mutex::Autolock lock(mLock);
Eric Laurent342e9cf2010-01-19 17:37:09 -08001672 if (mTrack == 0) return NO_INIT;
1673 return mTrack->getPosition(position);
1674}
1675
Lajos Molnar06ad1522014-08-28 07:27:44 -07001676status_t MediaPlayerService::AudioOutput::getTimestamp(AudioTimestamp &ts) const
1677{
Andy Hungd1c74342015-07-07 16:54:23 -07001678 Mutex::Autolock lock(mLock);
Lajos Molnar06ad1522014-08-28 07:27:44 -07001679 if (mTrack == 0) return NO_INIT;
1680 return mTrack->getTimestamp(ts);
1681}
1682
Wei Jiac4ac8172015-10-21 10:35:48 -07001683// TODO: Remove unnecessary calls to getPlayedOutDurationUs()
1684// as it acquires locks and may query the audio driver.
1685//
1686// Some calls could conceivably retrieve extrapolated data instead of
1687// accessing getTimestamp() or getPosition() every time a data buffer with
1688// a media time is received.
1689//
1690// Calculate duration of played samples if played at normal rate (i.e., 1.0).
1691int64_t MediaPlayerService::AudioOutput::getPlayedOutDurationUs(int64_t nowUs) const
1692{
1693 Mutex::Autolock lock(mLock);
1694 if (mTrack == 0 || mSampleRateHz == 0) {
Wei Jia213f4902015-10-22 08:55:25 -07001695 return 0;
Wei Jiac4ac8172015-10-21 10:35:48 -07001696 }
1697
1698 uint32_t numFramesPlayed;
Andy Hung5d313802016-10-10 15:09:39 -07001699 int64_t numFramesPlayedAtUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001700 AudioTimestamp ts;
Wei Jiac4ac8172015-10-21 10:35:48 -07001701
1702 status_t res = mTrack->getTimestamp(ts);
1703 if (res == OK) { // case 1: mixing audio tracks and offloaded tracks.
1704 numFramesPlayed = ts.mPosition;
Andy Hung5d313802016-10-10 15:09:39 -07001705 numFramesPlayedAtUs = ts.mTime.tv_sec * 1000000LL + ts.mTime.tv_nsec / 1000;
1706 //ALOGD("getTimestamp: OK %d %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001707 } else if (res == WOULD_BLOCK) { // case 2: transitory state on start of a new track
1708 numFramesPlayed = 0;
Andy Hung5d313802016-10-10 15:09:39 -07001709 numFramesPlayedAtUs = nowUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001710 //ALOGD("getTimestamp: WOULD_BLOCK %d %lld",
Andy Hung5d313802016-10-10 15:09:39 -07001711 // numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001712 } else { // case 3: transitory at new track or audio fast tracks.
1713 res = mTrack->getPosition(&numFramesPlayed);
1714 CHECK_EQ(res, (status_t)OK);
Andy Hung5d313802016-10-10 15:09:39 -07001715 numFramesPlayedAtUs = nowUs;
1716 numFramesPlayedAtUs += 1000LL * mTrack->latency() / 2; /* XXX */
1717 //ALOGD("getPosition: %u %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001718 }
1719
1720 // CHECK_EQ(numFramesPlayed & (1 << 31), 0); // can't be negative until 12.4 hrs, test
1721 // TODO: remove the (int32_t) casting below as it may overflow at 12.4 hours.
1722 int64_t durationUs = (int64_t)((int32_t)numFramesPlayed * 1000000LL / mSampleRateHz)
Andy Hung5d313802016-10-10 15:09:39 -07001723 + nowUs - numFramesPlayedAtUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001724 if (durationUs < 0) {
1725 // Occurs when numFramesPlayed position is very small and the following:
1726 // (1) In case 1, the time nowUs is computed before getTimestamp() is called and
Andy Hung5d313802016-10-10 15:09:39 -07001727 // numFramesPlayedAtUs is greater than nowUs by time more than numFramesPlayed.
Wei Jiac4ac8172015-10-21 10:35:48 -07001728 // (2) In case 3, using getPosition and adding mAudioSink->latency() to
Andy Hung5d313802016-10-10 15:09:39 -07001729 // numFramesPlayedAtUs, by a time amount greater than numFramesPlayed.
Wei Jiac4ac8172015-10-21 10:35:48 -07001730 //
1731 // Both of these are transitory conditions.
1732 ALOGV("getPlayedOutDurationUs: negative duration %lld set to zero", (long long)durationUs);
1733 durationUs = 0;
1734 }
1735 ALOGV("getPlayedOutDurationUs(%lld) nowUs(%lld) frames(%u) framesAt(%lld)",
Andy Hung5d313802016-10-10 15:09:39 -07001736 (long long)durationUs, (long long)nowUs,
1737 numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001738 return durationUs;
1739}
1740
Marco Nelissen4110c102012-03-29 09:31:28 -07001741status_t MediaPlayerService::AudioOutput::getFramesWritten(uint32_t *frameswritten) const
1742{
Andy Hungd1c74342015-07-07 16:54:23 -07001743 Mutex::Autolock lock(mLock);
Marco Nelissen4110c102012-03-29 09:31:28 -07001744 if (mTrack == 0) return NO_INIT;
Andy Hung2f6e73d2016-04-08 12:12:58 -07001745 ExtendedTimestamp ets;
1746 status_t status = mTrack->getTimestamp(&ets);
1747 if (status == OK || status == WOULD_BLOCK) {
1748 *frameswritten = (uint32_t)ets.mPosition[ExtendedTimestamp::LOCATION_CLIENT];
1749 }
1750 return status;
Marco Nelissen4110c102012-03-29 09:31:28 -07001751}
1752
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001753status_t MediaPlayerService::AudioOutput::setParameters(const String8& keyValuePairs)
1754{
Andy Hungd1c74342015-07-07 16:54:23 -07001755 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001756 if (mTrack == 0) return NO_INIT;
1757 return mTrack->setParameters(keyValuePairs);
1758}
1759
1760String8 MediaPlayerService::AudioOutput::getParameters(const String8& keys)
1761{
Andy Hungd1c74342015-07-07 16:54:23 -07001762 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001763 if (mTrack == 0) return String8::empty();
1764 return mTrack->getParameters(keys);
1765}
1766
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001767void MediaPlayerService::AudioOutput::setAudioAttributes(const audio_attributes_t * attributes) {
Andy Hungd1c74342015-07-07 16:54:23 -07001768 Mutex::Autolock lock(mLock);
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001769 if (attributes == NULL) {
1770 free(mAttributes);
1771 mAttributes = NULL;
1772 } else {
1773 if (mAttributes == NULL) {
1774 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1775 }
1776 memcpy(mAttributes, attributes, sizeof(audio_attributes_t));
Eric Laurent43562692015-07-15 16:49:07 -07001777 mStreamType = audio_attributes_to_stream_type(attributes);
1778 }
1779}
1780
1781void MediaPlayerService::AudioOutput::setAudioStreamType(audio_stream_type_t streamType)
1782{
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001783 Mutex::Autolock lock(mLock);
Eric Laurent43562692015-07-15 16:49:07 -07001784 // do not allow direct stream type modification if attributes have been set
1785 if (mAttributes == NULL) {
1786 mStreamType = streamType;
1787 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001788}
1789
Andy Hungd1c74342015-07-07 16:54:23 -07001790void MediaPlayerService::AudioOutput::deleteRecycledTrack_l()
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001791{
Andy Hungd1c74342015-07-07 16:54:23 -07001792 ALOGV("deleteRecycledTrack_l");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001793 if (mRecycledTrack != 0) {
1794
1795 if (mCallbackData != NULL) {
1796 mCallbackData->setOutput(NULL);
1797 mCallbackData->endTrackSwitch();
1798 }
1799
1800 if ((mRecycledTrack->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) {
Andy Hunge13f8a62016-03-30 14:20:42 -07001801 int32_t msec = 0;
1802 if (!mRecycledTrack->stopped()) { // check if active
1803 (void)mRecycledTrack->pendingDuration(&msec);
1804 }
1805 mRecycledTrack->stop(); // ensure full data drain
1806 ALOGD("deleting recycled track, waiting for data drain (%d msec)", msec);
1807 if (msec > 0) {
1808 static const int32_t WAIT_LIMIT_MS = 3000;
1809 if (msec > WAIT_LIMIT_MS) {
1810 msec = WAIT_LIMIT_MS;
1811 }
1812 usleep(msec * 1000LL);
1813 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001814 }
1815 // An offloaded track isn't flushed because the STREAM_END is reported
1816 // slightly prematurely to allow time for the gapless track switch
1817 // but this means that if we decide not to recycle the track there
1818 // could be a small amount of residual data still playing. We leave
1819 // AudioFlinger to drain the track.
1820
1821 mRecycledTrack.clear();
Andy Hungd1c74342015-07-07 16:54:23 -07001822 close_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001823 delete mCallbackData;
1824 mCallbackData = NULL;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001825 }
1826}
1827
Andy Hungd1c74342015-07-07 16:54:23 -07001828void MediaPlayerService::AudioOutput::close_l()
1829{
1830 mTrack.clear();
1831}
1832
Andreas Huber20111aa2009-07-14 16:56:47 -07001833status_t MediaPlayerService::AudioOutput::open(
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001834 uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
1835 audio_format_t format, int bufferCount,
Eric Laurent1948eb32012-04-13 16:50:19 -07001836 AudioCallback cb, void *cookie,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001837 audio_output_flags_t flags,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001838 const audio_offload_info_t *offloadInfo,
Andy Hung179652e2015-05-31 22:49:46 -07001839 bool doNotReconnect,
1840 uint32_t suggestedFrameCount)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001841{
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001842 ALOGV("open(%u, %d, 0x%x, 0x%x, %d, %d 0x%x)", sampleRate, channelCount, channelMask,
1843 format, bufferCount, mSessionId, flags);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001844
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001845 // offloading is only supported in callback mode for now.
1846 // offloadInfo must be present if offload flag is set
1847 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) &&
1848 ((cb == NULL) || (offloadInfo == NULL))) {
1849 return BAD_VALUE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001850 }
1851
Andy Hung179652e2015-05-31 22:49:46 -07001852 // compute frame count for the AudioTrack internal buffer
1853 size_t frameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001854 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1855 frameCount = 0; // AudioTrack will get frame count from AudioFlinger
1856 } else {
Andy Hung179652e2015-05-31 22:49:46 -07001857 // try to estimate the buffer processing fetch size from AudioFlinger.
1858 // framesPerBuffer is approximate and generally correct, except when it's not :-).
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001859 uint32_t afSampleRate;
1860 size_t afFrameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001861 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1862 return NO_INIT;
1863 }
1864 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1865 return NO_INIT;
1866 }
Andy Hung179652e2015-05-31 22:49:46 -07001867 const size_t framesPerBuffer =
1868 (unsigned long long)sampleRate * afFrameCount / afSampleRate;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001869
Andy Hung179652e2015-05-31 22:49:46 -07001870 if (bufferCount == 0) {
1871 // use suggestedFrameCount
1872 bufferCount = (suggestedFrameCount + framesPerBuffer - 1) / framesPerBuffer;
1873 }
1874 // Check argument bufferCount against the mininum buffer count
1875 if (bufferCount != 0 && bufferCount < mMinBufferCount) {
1876 ALOGV("bufferCount (%d) increased to %d", bufferCount, mMinBufferCount);
1877 bufferCount = mMinBufferCount;
1878 }
1879 // if frameCount is 0, then AudioTrack will get frame count from AudioFlinger
1880 // which will be the minimum size permitted.
1881 frameCount = bufferCount * framesPerBuffer;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001882 }
Andreas Huber20111aa2009-07-14 16:56:47 -07001883
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001884 if (channelMask == CHANNEL_MASK_USE_CHANNEL_ORDER) {
Glenn Kastenab334fd2012-03-14 12:56:06 -07001885 channelMask = audio_channel_out_mask_from_count(channelCount);
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001886 if (0 == channelMask) {
1887 ALOGE("open() error, can\'t derive mask for %d audio channels", channelCount);
1888 return NO_INIT;
1889 }
1890 }
Eric Laurent1948eb32012-04-13 16:50:19 -07001891
Andy Hungd1c74342015-07-07 16:54:23 -07001892 Mutex::Autolock lock(mLock);
Andy Hung179652e2015-05-31 22:49:46 -07001893 mCallback = cb;
1894 mCallbackCookie = cookie;
1895
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001896 // Check whether we can recycle the track
1897 bool reuse = false;
1898 bool bothOffloaded = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001899
Glenn Kasten2799d742013-05-30 14:33:29 -07001900 if (mRecycledTrack != 0) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001901 // check whether we are switching between two offloaded tracks
1902 bothOffloaded = (flags & mRecycledTrack->getFlags()
1903 & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0;
Marco Nelissen67295b52012-06-11 14:52:53 -07001904
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001905 // check if the existing track can be reused as-is, or if a new track needs to be created.
1906 reuse = true;
1907
Marco Nelissen67295b52012-06-11 14:52:53 -07001908 if ((mCallbackData == NULL && mCallback != NULL) ||
1909 (mCallbackData != NULL && mCallback == NULL)) {
1910 // recycled track uses callbacks but the caller wants to use writes, or vice versa
1911 ALOGV("can't chain callback and write");
1912 reuse = false;
1913 } else if ((mRecycledTrack->getSampleRate() != sampleRate) ||
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001914 (mRecycledTrack->channelCount() != (uint32_t)channelCount) ) {
1915 ALOGV("samplerate, channelcount differ: %u/%u Hz, %u/%d ch",
Marco Nelissen67295b52012-06-11 14:52:53 -07001916 mRecycledTrack->getSampleRate(), sampleRate,
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001917 mRecycledTrack->channelCount(), channelCount);
Marco Nelissen67295b52012-06-11 14:52:53 -07001918 reuse = false;
1919 } else if (flags != mFlags) {
1920 ALOGV("output flags differ %08x/%08x", flags, mFlags);
1921 reuse = false;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001922 } else if (mRecycledTrack->format() != format) {
1923 reuse = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001924 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001925 } else {
1926 ALOGV("no track available to recycle");
1927 }
1928
1929 ALOGV_IF(bothOffloaded, "both tracks offloaded");
1930
1931 // If we can't recycle and both tracks are offloaded
1932 // we must close the previous output before opening a new one
1933 if (bothOffloaded && !reuse) {
1934 ALOGV("both offloaded and not recycling");
Andy Hungd1c74342015-07-07 16:54:23 -07001935 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001936 }
1937
1938 sp<AudioTrack> t;
1939 CallbackData *newcbd = NULL;
1940
1941 // We don't attempt to create a new track if we are recycling an
1942 // offloaded track. But, if we are recycling a non-offloaded or we
1943 // are switching where one is offloaded and one isn't then we create
1944 // the new track in advance so that we can read additional stream info
1945
1946 if (!(reuse && bothOffloaded)) {
1947 ALOGV("creating new AudioTrack");
1948
1949 if (mCallback != NULL) {
1950 newcbd = new CallbackData(this);
1951 t = new AudioTrack(
1952 mStreamType,
1953 sampleRate,
1954 format,
1955 channelMask,
1956 frameCount,
1957 flags,
1958 CallbackWrapper,
1959 newcbd,
1960 0, // notification frames
1961 mSessionId,
1962 AudioTrack::TRANSFER_CALLBACK,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001963 offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -08001964 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001965 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001966 mAttributes,
1967 doNotReconnect);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001968 } else {
Andy Hungff874dc2016-04-11 16:49:09 -07001969 // TODO: Due to buffer memory concerns, we use a max target playback speed
1970 // based on mPlaybackRate at the time of open (instead of kMaxRequiredSpeed),
1971 // also clamping the target speed to 1.0 <= targetSpeed <= kMaxRequiredSpeed.
1972 const float targetSpeed =
1973 std::min(std::max(mPlaybackRate.mSpeed, 1.0f), kMaxRequiredSpeed);
1974 ALOGW_IF(targetSpeed != mPlaybackRate.mSpeed,
1975 "track target speed:%f clamped from playback speed:%f",
1976 targetSpeed, mPlaybackRate.mSpeed);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001977 t = new AudioTrack(
1978 mStreamType,
1979 sampleRate,
1980 format,
1981 channelMask,
1982 frameCount,
1983 flags,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001984 NULL, // callback
1985 NULL, // user data
1986 0, // notification frames
1987 mSessionId,
1988 AudioTrack::TRANSFER_DEFAULT,
1989 NULL, // offload info
Marco Nelissend457c972014-02-11 08:47:07 -08001990 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001991 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001992 mAttributes,
Andy Hungff874dc2016-04-11 16:49:09 -07001993 doNotReconnect,
1994 targetSpeed);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001995 }
1996
1997 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1998 ALOGE("Unable to create audio track");
1999 delete newcbd;
Glenn Kasten3e98ecd2015-05-18 13:13:24 -07002000 // t goes out of scope, so reference count drops to zero
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002001 return NO_INIT;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07002002 } else {
2003 // successful AudioTrack initialization implies a legacy stream type was generated
2004 // from the audio attributes
2005 mStreamType = t->streamType();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002006 }
2007 }
2008
2009 if (reuse) {
2010 CHECK(mRecycledTrack != NULL);
2011
2012 if (!bothOffloaded) {
2013 if (mRecycledTrack->frameCount() != t->frameCount()) {
Andy Hung833b4752016-04-04 17:15:48 -07002014 ALOGV("framecount differs: %zu/%zu frames",
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002015 mRecycledTrack->frameCount(), t->frameCount());
2016 reuse = false;
2017 }
2018 }
2019
Marco Nelissen67295b52012-06-11 14:52:53 -07002020 if (reuse) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002021 ALOGV("chaining to next output and recycling track");
Andy Hungd1c74342015-07-07 16:54:23 -07002022 close_l();
Marco Nelissen67295b52012-06-11 14:52:53 -07002023 mTrack = mRecycledTrack;
Glenn Kasten2799d742013-05-30 14:33:29 -07002024 mRecycledTrack.clear();
Marco Nelissen67295b52012-06-11 14:52:53 -07002025 if (mCallbackData != NULL) {
2026 mCallbackData->setOutput(this);
2027 }
Marco Nelissen67295b52012-06-11 14:52:53 -07002028 delete newcbd;
Wei Jiae0bbac92016-07-18 16:04:53 -07002029 return updateTrack();
Marco Nelissen67295b52012-06-11 14:52:53 -07002030 }
Marco Nelissen67295b52012-06-11 14:52:53 -07002031 }
2032
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002033 // we're not going to reuse the track, unblock and flush it
2034 // this was done earlier if both tracks are offloaded
2035 if (!bothOffloaded) {
Andy Hungd1c74342015-07-07 16:54:23 -07002036 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002037 }
2038
2039 CHECK((t != NULL) && ((mCallback == NULL) || (newcbd != NULL)));
2040
Marco Nelissen67295b52012-06-11 14:52:53 -07002041 mCallbackData = newcbd;
Steve Block3856b092011-10-20 11:56:00 +01002042 ALOGV("setVolume");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002043 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07002044
Andy Hung39399b62017-04-21 15:07:45 -07002045 // Restore VolumeShapers for the MediaPlayer in case the track was recreated
2046 // due to an output sink error (e.g. offload to non-offload switch).
2047 mVolumeHandler->forall([&t](const VolumeShaper &shaper) -> VolumeShaper::Status {
2048 sp<VolumeShaper::Operation> operationToEnd =
2049 new VolumeShaper::Operation(shaper.mOperation);
2050 // TODO: Ideally we would restore to the exact xOffset position
2051 // as returned by getVolumeShaperState(), but we don't have that
2052 // information when restoring at the client unless we periodically poll
2053 // the server or create shared memory state.
2054 //
2055 // For now, we simply advance to the end of the VolumeShaper effect
2056 // if it has been started.
2057 if (shaper.isStarted()) {
Andy Hungf3702642017-05-05 17:33:32 -07002058 operationToEnd->setNormalizedTime(1.f);
Andy Hung39399b62017-04-21 15:07:45 -07002059 }
2060 return t->applyVolumeShaper(shaper.mConfiguration, operationToEnd);
Andy Hung4ef88d72017-02-21 19:47:53 -08002061 });
Andy Hung4ef88d72017-02-21 19:47:53 -08002062
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002063 mSampleRateHz = sampleRate;
Preetam Singh Ranawat2e17eef2015-08-12 12:11:46 -07002064 mFlags = flags;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002065 mMsecsPerFrame = 1E3f / (mPlaybackRate.mSpeed * sampleRate);
Andy Hungd1c74342015-07-07 16:54:23 -07002066 mFrameSize = t->frameSize();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002067 mTrack = t;
Eric Laurent2beeb502010-07-16 07:43:46 -07002068
Wei Jiae0bbac92016-07-18 16:04:53 -07002069 return updateTrack();
2070}
2071
2072status_t MediaPlayerService::AudioOutput::updateTrack() {
2073 if (mTrack == NULL) {
2074 return NO_ERROR;
2075 }
2076
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002077 status_t res = NO_ERROR;
Wei Jia0162d002015-06-09 11:59:33 -07002078 // Note some output devices may give us a direct track even though we don't specify it.
2079 // Example: Line application b/17459982.
Wei Jiae0bbac92016-07-18 16:04:53 -07002080 if ((mTrack->getFlags()
2081 & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) {
2082 res = mTrack->setPlaybackRate(mPlaybackRate);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002083 if (res == NO_ERROR) {
Wei Jiae0bbac92016-07-18 16:04:53 -07002084 mTrack->setAuxEffectSendLevel(mSendLevel);
2085 res = mTrack->attachAuxEffect(mAuxEffectId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002086 }
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002087 }
Wei Jiae0bbac92016-07-18 16:04:53 -07002088 ALOGV("updateTrack() DONE status %d", res);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002089 return res;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002090}
2091
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002092status_t MediaPlayerService::AudioOutput::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002093{
Steve Block3856b092011-10-20 11:56:00 +01002094 ALOGV("start");
Andy Hungd1c74342015-07-07 16:54:23 -07002095 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08002096 if (mCallbackData != NULL) {
2097 mCallbackData->endTrackSwitch();
2098 }
Glenn Kasten2799d742013-05-30 14:33:29 -07002099 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002100 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07002101 mTrack->setAuxEffectSendLevel(mSendLevel);
Andy Hung39399b62017-04-21 15:07:45 -07002102 status_t status = mTrack->start();
2103 if (status == NO_ERROR) {
2104 mVolumeHandler->setStarted();
2105 }
2106 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002107 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002108 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002109}
2110
Marco Nelissen6b74d672012-02-28 16:07:44 -08002111void MediaPlayerService::AudioOutput::setNextOutput(const sp<AudioOutput>& nextOutput) {
Andy Hungd1c74342015-07-07 16:54:23 -07002112 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08002113 mNextOutput = nextOutput;
2114}
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08002115
Marco Nelissen6b74d672012-02-28 16:07:44 -08002116void MediaPlayerService::AudioOutput::switchToNextOutput() {
2117 ALOGV("switchToNextOutput");
Andy Hungd1c74342015-07-07 16:54:23 -07002118
2119 // Try to acquire the callback lock before moving track (without incurring deadlock).
2120 const unsigned kMaxSwitchTries = 100;
2121 Mutex::Autolock lock(mLock);
2122 for (unsigned tries = 0;;) {
2123 if (mTrack == 0) {
2124 return;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002125 }
Andy Hungd1c74342015-07-07 16:54:23 -07002126 if (mNextOutput != NULL && mNextOutput != this) {
2127 if (mCallbackData != NULL) {
2128 // two alternative approaches
2129#if 1
2130 CallbackData *callbackData = mCallbackData;
2131 mLock.unlock();
2132 // proper acquisition sequence
2133 callbackData->lock();
2134 mLock.lock();
2135 // Caution: it is unlikely that someone deleted our callback or changed our target
2136 if (callbackData != mCallbackData || mNextOutput == NULL || mNextOutput == this) {
2137 // fatal if we are starved out.
2138 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2139 "switchToNextOutput() cannot obtain correct lock sequence");
2140 callbackData->unlock();
2141 continue;
2142 }
2143 callbackData->mSwitching = true; // begin track switch
Wei Jiaadee56a2016-08-05 15:40:34 -07002144 callbackData->setOutput(NULL);
Andy Hungd1c74342015-07-07 16:54:23 -07002145#else
2146 // tryBeginTrackSwitch() returns false if the callback has the lock.
2147 if (!mCallbackData->tryBeginTrackSwitch()) {
2148 // fatal if we are starved out.
2149 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2150 "switchToNextOutput() cannot obtain callback lock");
2151 mLock.unlock();
2152 usleep(5 * 1000 /* usec */); // allow callback to use AudioOutput
2153 mLock.lock();
2154 continue;
2155 }
2156#endif
2157 }
2158
2159 Mutex::Autolock nextLock(mNextOutput->mLock);
2160
2161 // If the next output track is not NULL, then it has been
2162 // opened already for playback.
2163 // This is possible even without the next player being started,
2164 // for example, the next player could be prepared and seeked.
2165 //
2166 // Presuming it isn't advisable to force the track over.
2167 if (mNextOutput->mTrack == NULL) {
2168 ALOGD("Recycling track for gapless playback");
2169 delete mNextOutput->mCallbackData;
2170 mNextOutput->mCallbackData = mCallbackData;
2171 mNextOutput->mRecycledTrack = mTrack;
2172 mNextOutput->mSampleRateHz = mSampleRateHz;
2173 mNextOutput->mMsecsPerFrame = mMsecsPerFrame;
Andy Hungd1c74342015-07-07 16:54:23 -07002174 mNextOutput->mFlags = mFlags;
2175 mNextOutput->mFrameSize = mFrameSize;
2176 close_l();
2177 mCallbackData = NULL; // destruction handled by mNextOutput
2178 } else {
2179 ALOGW("Ignoring gapless playback because next player has already started");
2180 // remove track in case resource needed for future players.
2181 if (mCallbackData != NULL) {
2182 mCallbackData->endTrackSwitch(); // release lock for callbacks before close.
2183 }
2184 close_l();
2185 }
2186 }
2187 break;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002188 }
2189}
2190
Wei Jia7d3f4df2015-03-03 15:28:00 -08002191ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002192{
Andy Hungd1c74342015-07-07 16:54:23 -07002193 Mutex::Autolock lock(mLock);
Glenn Kastenadad3d72014-02-21 14:51:43 -08002194 LOG_ALWAYS_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
Andreas Huber20111aa2009-07-14 16:56:47 -07002195
Steve Block3856b092011-10-20 11:56:00 +01002196 //ALOGV("write(%p, %u)", buffer, size);
Glenn Kasten2799d742013-05-30 14:33:29 -07002197 if (mTrack != 0) {
Andy Hung2f6e73d2016-04-08 12:12:58 -07002198 return mTrack->write(buffer, size, blocking);
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07002199 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002200 return NO_INIT;
2201}
2202
2203void MediaPlayerService::AudioOutput::stop()
2204{
Steve Block3856b092011-10-20 11:56:00 +01002205 ALOGV("stop");
Andy Hungd1c74342015-07-07 16:54:23 -07002206 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002207 if (mTrack != 0) mTrack->stop();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002208}
2209
2210void MediaPlayerService::AudioOutput::flush()
2211{
Steve Block3856b092011-10-20 11:56:00 +01002212 ALOGV("flush");
Andy Hungd1c74342015-07-07 16:54:23 -07002213 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002214 if (mTrack != 0) mTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002215}
2216
2217void MediaPlayerService::AudioOutput::pause()
2218{
Steve Block3856b092011-10-20 11:56:00 +01002219 ALOGV("pause");
Andy Hungd1c74342015-07-07 16:54:23 -07002220 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002221 if (mTrack != 0) mTrack->pause();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002222}
2223
2224void MediaPlayerService::AudioOutput::close()
2225{
Steve Block3856b092011-10-20 11:56:00 +01002226 ALOGV("close");
Erik Wolsheimer7845a1f2015-10-30 12:07:52 -07002227 sp<AudioTrack> track;
2228 {
2229 Mutex::Autolock lock(mLock);
2230 track = mTrack;
2231 close_l(); // clears mTrack
2232 }
2233 // destruction of the track occurs outside of mutex.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002234}
2235
2236void MediaPlayerService::AudioOutput::setVolume(float left, float right)
2237{
Steve Block3856b092011-10-20 11:56:00 +01002238 ALOGV("setVolume(%f, %f)", left, right);
Andy Hungd1c74342015-07-07 16:54:23 -07002239 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002240 mLeftVolume = left;
2241 mRightVolume = right;
Glenn Kasten2799d742013-05-30 14:33:29 -07002242 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002243 mTrack->setVolume(left, right);
2244 }
2245}
2246
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002247status_t MediaPlayerService::AudioOutput::setPlaybackRate(const AudioPlaybackRate &rate)
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002248{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002249 ALOGV("setPlaybackRate(%f %f %d %d)",
2250 rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Andy Hungd1c74342015-07-07 16:54:23 -07002251 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002252 if (mTrack == 0) {
2253 // remember rate so that we can set it when the track is opened
2254 mPlaybackRate = rate;
2255 return OK;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002256 }
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002257 status_t res = mTrack->setPlaybackRate(rate);
2258 if (res != NO_ERROR) {
2259 return res;
2260 }
2261 // rate.mSpeed is always greater than 0 if setPlaybackRate succeeded
2262 CHECK_GT(rate.mSpeed, 0.f);
2263 mPlaybackRate = rate;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002264 if (mSampleRateHz != 0) {
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002265 mMsecsPerFrame = 1E3f / (rate.mSpeed * mSampleRateHz);
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002266 }
2267 return res;
2268}
2269
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002270status_t MediaPlayerService::AudioOutput::getPlaybackRate(AudioPlaybackRate *rate)
2271{
2272 ALOGV("setPlaybackRate");
Andy Hungd1c74342015-07-07 16:54:23 -07002273 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002274 if (mTrack == 0) {
2275 return NO_INIT;
2276 }
2277 *rate = mTrack->getPlaybackRate();
2278 return NO_ERROR;
2279}
2280
Eric Laurent2beeb502010-07-16 07:43:46 -07002281status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
2282{
Steve Block3856b092011-10-20 11:56:00 +01002283 ALOGV("setAuxEffectSendLevel(%f)", level);
Andy Hungd1c74342015-07-07 16:54:23 -07002284 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002285 mSendLevel = level;
Glenn Kasten2799d742013-05-30 14:33:29 -07002286 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002287 return mTrack->setAuxEffectSendLevel(level);
2288 }
2289 return NO_ERROR;
2290}
2291
2292status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
2293{
Steve Block3856b092011-10-20 11:56:00 +01002294 ALOGV("attachAuxEffect(%d)", effectId);
Andy Hungd1c74342015-07-07 16:54:23 -07002295 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002296 mAuxEffectId = effectId;
Glenn Kasten2799d742013-05-30 14:33:29 -07002297 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002298 return mTrack->attachAuxEffect(effectId);
2299 }
2300 return NO_ERROR;
2301}
2302
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002303VolumeShaper::Status MediaPlayerService::AudioOutput::applyVolumeShaper(
2304 const sp<VolumeShaper::Configuration>& configuration,
2305 const sp<VolumeShaper::Operation>& operation)
2306{
2307 Mutex::Autolock lock(mLock);
2308 ALOGV("AudioOutput::applyVolumeShaper");
Andy Hung4ef88d72017-02-21 19:47:53 -08002309
Andy Hung4ef88d72017-02-21 19:47:53 -08002310 mVolumeHandler->setIdIfNecessary(configuration);
Andy Hung39399b62017-04-21 15:07:45 -07002311
2312 VolumeShaper::Status status;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002313 if (mTrack != 0) {
Andy Hung39399b62017-04-21 15:07:45 -07002314 status = mTrack->applyVolumeShaper(configuration, operation);
2315 if (status >= 0) {
2316 (void)mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hungf3702642017-05-05 17:33:32 -07002317 if (mTrack->isPlaying()) { // match local AudioTrack to properly restore.
2318 mVolumeHandler->setStarted();
2319 }
Andy Hung39399b62017-04-21 15:07:45 -07002320 }
Andy Hung4ef88d72017-02-21 19:47:53 -08002321 } else {
Andy Hungc01eddb2017-07-21 16:42:41 -07002322 // VolumeShapers are not affected when a track moves between players for
2323 // gapless playback (setNextMediaPlayer).
2324 // We forward VolumeShaper operations that do not change configuration
2325 // to the new player so that unducking may occur as expected.
2326 // Unducking is an idempotent operation, same if applied back-to-back.
2327 if (configuration->getType() == VolumeShaper::Configuration::TYPE_ID
2328 && mNextOutput != nullptr) {
2329 ALOGV("applyVolumeShaper: Attempting to forward missed operation: %s %s",
2330 configuration->toString().c_str(), operation->toString().c_str());
2331 Mutex::Autolock nextLock(mNextOutput->mLock);
2332
2333 // recycled track should be forwarded from this AudioSink by switchToNextOutput
2334 sp<AudioTrack> track = mNextOutput->mRecycledTrack;
2335 if (track != nullptr) {
2336 ALOGD("Forward VolumeShaper operation to recycled track %p", track.get());
2337 (void)track->applyVolumeShaper(configuration, operation);
2338 } else {
2339 // There is a small chance that the unduck occurs after the next
2340 // player has already started, but before it is registered to receive
2341 // the unduck command.
2342 track = mNextOutput->mTrack;
2343 if (track != nullptr) {
2344 ALOGD("Forward VolumeShaper operation to track %p", track.get());
2345 (void)track->applyVolumeShaper(configuration, operation);
2346 }
2347 }
2348 }
Andy Hung39399b62017-04-21 15:07:45 -07002349 status = mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002350 }
Andy Hung39399b62017-04-21 15:07:45 -07002351 return status;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002352}
2353
2354sp<VolumeShaper::State> MediaPlayerService::AudioOutput::getVolumeShaperState(int id)
2355{
2356 Mutex::Autolock lock(mLock);
2357 if (mTrack != 0) {
2358 return mTrack->getVolumeShaperState(id);
Andy Hung4ef88d72017-02-21 19:47:53 -08002359 } else {
2360 return mVolumeHandler->getVolumeShaperState(id);
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002361 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002362}
2363
Andreas Huber20111aa2009-07-14 16:56:47 -07002364// static
2365void MediaPlayerService::AudioOutput::CallbackWrapper(
Glenn Kastend217a8c2011-06-01 15:20:35 -07002366 int event, void *cookie, void *info) {
Steve Block3856b092011-10-20 11:56:00 +01002367 //ALOGV("callbackwrapper");
Marco Nelissen6b74d672012-02-28 16:07:44 -08002368 CallbackData *data = (CallbackData*)cookie;
Andy Hungd1c74342015-07-07 16:54:23 -07002369 // lock to ensure we aren't caught in the middle of a track switch.
Marco Nelissen6b74d672012-02-28 16:07:44 -08002370 data->lock();
2371 AudioOutput *me = data->getOutput();
Andreas Huber20111aa2009-07-14 16:56:47 -07002372 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002373 if (me == NULL) {
2374 // no output set, likely because the track was scheduled to be reused
2375 // by another player, but the format turned out to be incompatible.
2376 data->unlock();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002377 if (buffer != NULL) {
2378 buffer->size = 0;
2379 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08002380 return;
2381 }
Andreas Huber20111aa2009-07-14 16:56:47 -07002382
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002383 switch(event) {
2384 case AudioTrack::EVENT_MORE_DATA: {
2385 size_t actualSize = (*me->mCallback)(
2386 me, buffer->raw, buffer->size, me->mCallbackCookie,
2387 CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002388
Andy Hung719b46b2015-05-31 22:18:25 -07002389 // Log when no data is returned from the callback.
2390 // (1) We may have no data (especially with network streaming sources).
2391 // (2) We may have reached the EOS and the audio track is not stopped yet.
2392 // Note that AwesomePlayer/AudioPlayer will only return zero size when it reaches the EOS.
2393 // NuPlayerRenderer will return zero when it doesn't have data (it doesn't block to fill).
2394 //
2395 // This is a benign busy-wait, with the next data request generated 10 ms or more later;
2396 // nevertheless for power reasons, we don't want to see too many of these.
Andreas Huber2e8ffaf2010-02-18 16:45:13 -08002397
Andy Hung719b46b2015-05-31 22:18:25 -07002398 ALOGV_IF(actualSize == 0 && buffer->size > 0, "callbackwrapper: empty buffer returned");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002399
2400 buffer->size = actualSize;
2401 } break;
2402
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002403 case AudioTrack::EVENT_STREAM_END:
Andy Hung719b46b2015-05-31 22:18:25 -07002404 // currently only occurs for offloaded callbacks
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002405 ALOGV("callbackwrapper: deliver EVENT_STREAM_END");
2406 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2407 me->mCallbackCookie, CB_EVENT_STREAM_END);
2408 break;
2409
2410 case AudioTrack::EVENT_NEW_IAUDIOTRACK :
2411 ALOGV("callbackwrapper: deliver EVENT_TEAR_DOWN");
2412 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2413 me->mCallbackCookie, CB_EVENT_TEAR_DOWN);
2414 break;
2415
Glenn Kasten421743b2015-06-01 08:18:08 -07002416 case AudioTrack::EVENT_UNDERRUN:
Andy Hung719b46b2015-05-31 22:18:25 -07002417 // This occurs when there is no data available, typically
Glenn Kasten421743b2015-06-01 08:18:08 -07002418 // when there is a failure to supply data to the AudioTrack. It can also
2419 // occur in non-offloaded mode when the audio device comes out of standby.
2420 //
Andy Hung719b46b2015-05-31 22:18:25 -07002421 // If an AudioTrack underruns it outputs silence. Since this happens suddenly
2422 // it may sound like an audible pop or glitch.
2423 //
2424 // The underrun event is sent once per track underrun; the condition is reset
2425 // when more data is sent to the AudioTrack.
Eric Laurente93cc032016-05-05 10:15:10 -07002426 ALOGD("callbackwrapper: EVENT_UNDERRUN (discarded)");
Glenn Kasten421743b2015-06-01 08:18:08 -07002427 break;
2428
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002429 default:
2430 ALOGE("received unknown event type: %d inside CallbackWrapper !", event);
Andreas Huber51c1e0e2011-04-04 11:43:40 -07002431 }
2432
Marco Nelissen6b74d672012-02-28 16:07:44 -08002433 data->unlock();
Andreas Huber20111aa2009-07-14 16:56:47 -07002434}
2435
Glenn Kastend848eb42016-03-08 13:42:11 -08002436audio_session_t MediaPlayerService::AudioOutput::getSessionId() const
Eric Laurent8c563ed2010-10-07 18:23:03 -07002437{
Andy Hungd1c74342015-07-07 16:54:23 -07002438 Mutex::Autolock lock(mLock);
Eric Laurent8c563ed2010-10-07 18:23:03 -07002439 return mSessionId;
2440}
2441
Eric Laurent6f59db12013-07-26 17:16:50 -07002442uint32_t MediaPlayerService::AudioOutput::getSampleRate() const
2443{
Andy Hungd1c74342015-07-07 16:54:23 -07002444 Mutex::Autolock lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -07002445 if (mTrack == 0) return 0;
2446 return mTrack->getSampleRate();
2447}
2448
Andy Hungf2c87b32016-04-07 19:49:29 -07002449int64_t MediaPlayerService::AudioOutput::getBufferDurationInUs() const
2450{
2451 Mutex::Autolock lock(mLock);
2452 if (mTrack == 0) {
2453 return 0;
2454 }
2455 int64_t duration;
2456 if (mTrack->getBufferDurationInUs(&duration) != OK) {
2457 return 0;
2458 }
2459 return duration;
2460}
2461
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002462////////////////////////////////////////////////////////////////////////////////
2463
2464struct CallbackThread : public Thread {
2465 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
2466 MediaPlayerBase::AudioSink::AudioCallback cb,
2467 void *cookie);
2468
2469protected:
2470 virtual ~CallbackThread();
2471
2472 virtual bool threadLoop();
2473
2474private:
2475 wp<MediaPlayerBase::AudioSink> mSink;
2476 MediaPlayerBase::AudioSink::AudioCallback mCallback;
2477 void *mCookie;
2478 void *mBuffer;
2479 size_t mBufferSize;
2480
2481 CallbackThread(const CallbackThread &);
2482 CallbackThread &operator=(const CallbackThread &);
2483};
2484
2485CallbackThread::CallbackThread(
2486 const wp<MediaPlayerBase::AudioSink> &sink,
2487 MediaPlayerBase::AudioSink::AudioCallback cb,
2488 void *cookie)
2489 : mSink(sink),
2490 mCallback(cb),
2491 mCookie(cookie),
2492 mBuffer(NULL),
2493 mBufferSize(0) {
2494}
2495
2496CallbackThread::~CallbackThread() {
2497 if (mBuffer) {
2498 free(mBuffer);
2499 mBuffer = NULL;
2500 }
2501}
2502
2503bool CallbackThread::threadLoop() {
2504 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
2505 if (sink == NULL) {
2506 return false;
2507 }
2508
2509 if (mBuffer == NULL) {
2510 mBufferSize = sink->bufferSize();
2511 mBuffer = malloc(mBufferSize);
2512 }
2513
2514 size_t actualSize =
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002515 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie,
2516 MediaPlayerBase::AudioSink::CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002517
2518 if (actualSize > 0) {
2519 sink->write(mBuffer, actualSize);
Andy Hunga31335a2014-08-20 17:37:59 -07002520 // Could return false on sink->write() error or short count.
2521 // Not necessarily appropriate but would work for AudioCache behavior.
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002522 }
2523
2524 return true;
2525}
2526
2527////////////////////////////////////////////////////////////////////////////////
2528
Chong Zhange5b9b692017-05-11 11:44:56 -07002529void MediaPlayerService::addBatteryData(uint32_t params) {
2530 mBatteryTracker.addBatteryData(params);
2531}
2532
2533status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
2534 return mBatteryTracker.pullBatteryData(reply);
2535}
2536
2537MediaPlayerService::BatteryTracker::BatteryTracker() {
2538 mBatteryAudio.refCount = 0;
2539 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2540 mBatteryAudio.deviceOn[i] = 0;
2541 mBatteryAudio.lastTime[i] = 0;
2542 mBatteryAudio.totalTime[i] = 0;
2543 }
2544 // speaker is on by default
2545 mBatteryAudio.deviceOn[SPEAKER] = 1;
2546
2547 // reset battery stats
2548 // if the mediaserver has crashed, battery stats could be left
2549 // in bad state, reset the state upon service start.
2550 BatteryNotifier::getInstance().noteResetVideo();
2551}
2552
2553void MediaPlayerService::BatteryTracker::addBatteryData(uint32_t params)
Gloria Wang7cf180c2011-02-19 18:37:57 -08002554{
2555 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002556
2557 int32_t time = systemTime() / 1000000L;
2558
2559 // change audio output devices. This notification comes from AudioFlinger
2560 if ((params & kBatteryDataSpeakerOn)
2561 || (params & kBatteryDataOtherAudioDeviceOn)) {
2562
2563 int deviceOn[NUM_AUDIO_DEVICES];
2564 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2565 deviceOn[i] = 0;
2566 }
2567
2568 if ((params & kBatteryDataSpeakerOn)
2569 && (params & kBatteryDataOtherAudioDeviceOn)) {
2570 deviceOn[SPEAKER_AND_OTHER] = 1;
2571 } else if (params & kBatteryDataSpeakerOn) {
2572 deviceOn[SPEAKER] = 1;
2573 } else {
2574 deviceOn[OTHER_AUDIO_DEVICE] = 1;
2575 }
2576
2577 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2578 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
2579
2580 if (mBatteryAudio.refCount > 0) { // if playing audio
2581 if (!deviceOn[i]) {
2582 mBatteryAudio.lastTime[i] += time;
2583 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2584 mBatteryAudio.lastTime[i] = 0;
2585 } else {
2586 mBatteryAudio.lastTime[i] = 0 - time;
2587 }
2588 }
2589
2590 mBatteryAudio.deviceOn[i] = deviceOn[i];
2591 }
2592 }
2593 return;
2594 }
2595
Marco Nelissenb7848f12014-12-04 08:57:56 -08002596 // an audio stream is started
Gloria Wang9ee159b2011-02-24 14:51:45 -08002597 if (params & kBatteryDataAudioFlingerStart) {
2598 // record the start time only if currently no other audio
2599 // is being played
2600 if (mBatteryAudio.refCount == 0) {
2601 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2602 if (mBatteryAudio.deviceOn[i]) {
2603 mBatteryAudio.lastTime[i] -= time;
2604 }
2605 }
2606 }
2607
2608 mBatteryAudio.refCount ++;
2609 return;
2610
2611 } else if (params & kBatteryDataAudioFlingerStop) {
2612 if (mBatteryAudio.refCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002613 ALOGW("Battery track warning: refCount is <= 0");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002614 return;
2615 }
2616
2617 // record the stop time only if currently this is the only
2618 // audio being played
2619 if (mBatteryAudio.refCount == 1) {
2620 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2621 if (mBatteryAudio.deviceOn[i]) {
2622 mBatteryAudio.lastTime[i] += time;
2623 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2624 mBatteryAudio.lastTime[i] = 0;
2625 }
2626 }
2627 }
2628
2629 mBatteryAudio.refCount --;
2630 return;
2631 }
2632
Andy Hung1afd0982016-11-08 16:13:44 -08002633 uid_t uid = IPCThreadState::self()->getCallingUid();
Gloria Wang7cf180c2011-02-19 18:37:57 -08002634 if (uid == AID_MEDIA) {
2635 return;
2636 }
2637 int index = mBatteryData.indexOfKey(uid);
Gloria Wang7cf180c2011-02-19 18:37:57 -08002638
2639 if (index < 0) { // create a new entry for this UID
2640 BatteryUsageInfo info;
2641 info.audioTotalTime = 0;
2642 info.videoTotalTime = 0;
2643 info.audioLastTime = 0;
2644 info.videoLastTime = 0;
2645 info.refCount = 0;
2646
Gloria Wang9ee159b2011-02-24 14:51:45 -08002647 if (mBatteryData.add(uid, info) == NO_MEMORY) {
Steve Block29357bc2012-01-06 19:20:56 +00002648 ALOGE("Battery track error: no memory for new app");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002649 return;
2650 }
Gloria Wang7cf180c2011-02-19 18:37:57 -08002651 }
2652
2653 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
2654
2655 if (params & kBatteryDataCodecStarted) {
2656 if (params & kBatteryDataTrackAudio) {
2657 info.audioLastTime -= time;
2658 info.refCount ++;
2659 }
2660 if (params & kBatteryDataTrackVideo) {
2661 info.videoLastTime -= time;
2662 info.refCount ++;
2663 }
2664 } else {
2665 if (info.refCount == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002666 ALOGW("Battery track warning: refCount is already 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002667 return;
2668 } else if (info.refCount < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00002669 ALOGE("Battery track error: refCount < 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002670 mBatteryData.removeItem(uid);
2671 return;
2672 }
2673
2674 if (params & kBatteryDataTrackAudio) {
2675 info.audioLastTime += time;
2676 info.refCount --;
2677 }
2678 if (params & kBatteryDataTrackVideo) {
2679 info.videoLastTime += time;
2680 info.refCount --;
2681 }
2682
2683 // no stream is being played by this UID
2684 if (info.refCount == 0) {
2685 info.audioTotalTime += info.audioLastTime;
2686 info.audioLastTime = 0;
2687 info.videoTotalTime += info.videoLastTime;
2688 info.videoLastTime = 0;
2689 }
2690 }
2691}
2692
Chong Zhange5b9b692017-05-11 11:44:56 -07002693status_t MediaPlayerService::BatteryTracker::pullBatteryData(Parcel* reply) {
Gloria Wang7cf180c2011-02-19 18:37:57 -08002694 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002695
2696 // audio output devices usage
2697 int32_t time = systemTime() / 1000000L; //in ms
2698 int32_t totalTime;
2699
2700 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2701 totalTime = mBatteryAudio.totalTime[i];
2702
2703 if (mBatteryAudio.deviceOn[i]
2704 && (mBatteryAudio.lastTime[i] != 0)) {
2705 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
2706 totalTime += tmpTime;
2707 }
2708
2709 reply->writeInt32(totalTime);
2710 // reset the total time
2711 mBatteryAudio.totalTime[i] = 0;
2712 }
2713
2714 // codec usage
Gloria Wang7cf180c2011-02-19 18:37:57 -08002715 BatteryUsageInfo info;
2716 int size = mBatteryData.size();
2717
2718 reply->writeInt32(size);
2719 int i = 0;
2720
2721 while (i < size) {
2722 info = mBatteryData.valueAt(i);
2723
2724 reply->writeInt32(mBatteryData.keyAt(i)); //UID
2725 reply->writeInt32(info.audioTotalTime);
2726 reply->writeInt32(info.videoTotalTime);
2727
2728 info.audioTotalTime = 0;
2729 info.videoTotalTime = 0;
2730
2731 // remove the UID entry where no stream is being played
2732 if (info.refCount <= 0) {
2733 mBatteryData.removeItemsAt(i);
2734 size --;
2735 i --;
2736 }
2737 i++;
2738 }
2739 return NO_ERROR;
2740}
nikoa64c8c72009-07-20 15:07:26 -07002741} // namespace android