blob: 91887a1aa5538ed038eacedefe95c51035931a18 [file] [log] [blame]
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001/*
2**
3** Copyright 2008, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18// Proxy for media player implementations
19
20//#define LOG_NDEBUG 0
21#define LOG_TAG "MediaPlayerService"
22#include <utils/Log.h>
23
24#include <sys/types.h>
25#include <sys/stat.h>
Gloria Wang7cf180c2011-02-19 18:37:57 -080026#include <sys/time.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080027#include <dirent.h>
28#include <unistd.h>
29
30#include <string.h>
Mathias Agopian6f74b0c2009-06-03 17:32:49 -070031
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080032#include <cutils/atomic.h>
Nicolas Catania14d27472009-07-13 14:37:49 -070033#include <cutils/properties.h> // for property_get
Mathias Agopian6f74b0c2009-06-03 17:32:49 -070034
35#include <utils/misc.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080036
Mathias Agopian75624082009-05-19 19:08:10 -070037#include <binder/IPCThreadState.h>
38#include <binder/IServiceManager.h>
39#include <binder/MemoryHeapBase.h>
40#include <binder/MemoryBase.h>
Mathias Agopianb1e7cd12013-02-14 17:11:27 -080041#include <gui/Surface.h>
Nicolas Catania1d187f12009-05-12 23:25:55 -070042#include <utils/Errors.h> // for status_t
43#include <utils/String8.h>
Marco Nelissen10dbb8e2009-09-20 10:42:13 -070044#include <utils/SystemClock.h>
Lajos Molnar06ad1522014-08-28 07:27:44 -070045#include <utils/Timers.h>
Nicolas Catania1d187f12009-05-12 23:25:55 -070046#include <utils/Vector.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080047
Eric Laurent43562692015-07-15 16:49:07 -070048#include <media/AudioPolicyHelper.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080049#include <media/IMediaHTTPService.h>
Jeff Brown2013a542012-09-04 21:38:42 -070050#include <media/IRemoteDisplay.h>
51#include <media/IRemoteDisplayClient.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080052#include <media/MediaPlayerInterface.h>
53#include <media/mediarecorder.h>
54#include <media/MediaMetadataRetrieverInterface.h>
nikoa64c8c72009-07-20 15:07:26 -070055#include <media/Metadata.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080056#include <media/AudioTrack.h>
James Dong8635b7b2011-03-14 17:01:38 -070057#include <media/MemoryLeakTrackUtil.h>
Lajos Molnar1381d4b2014-08-07 15:18:35 -070058#include <media/stagefright/MediaCodecList.h>
Eric Laurent9cb839a2011-09-27 09:48:56 -070059#include <media/stagefright/MediaErrors.h>
Marco Nelissen83b0fd92015-09-16 13:48:07 -070060#include <media/stagefright/Utils.h>
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +010061#include <media/stagefright/foundation/ADebug.h>
Marco Nelissenf09611f2015-02-13 14:12:42 -080062#include <media/stagefright/foundation/ALooperRoster.h>
Chong Zhang181fd9b2017-02-16 15:53:03 -080063#include <media/stagefright/SurfaceUtils.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070064#include <mediautils/BatteryNotifier.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080065
Andy Hung53541292016-04-13 16:48:51 -070066#include <memunreachable/memunreachable.h>
Dima Zavin64760242011-05-11 14:15:23 -070067#include <system/audio.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070068
Gloria Wang7cf180c2011-02-19 18:37:57 -080069#include <private/android_filesystem_config.h>
70
James Dong559bf282012-03-28 10:29:14 -070071#include "ActivityManager.h"
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080072#include "MediaRecorderClient.h"
73#include "MediaPlayerService.h"
74#include "MetadataRetrieverClient.h"
John Grossman44a7e422012-06-21 17:29:24 -070075#include "MediaPlayerFactory.h"
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080076
Nicolas Catania14d27472009-07-13 14:37:49 -070077#include "TestPlayerStub.h"
Andreas Huberf9334412010-12-15 15:17:42 -080078#include "nuplayer/NuPlayerDriver.h"
Andreas Huber20111aa2009-07-14 16:56:47 -070079
Andreas Huber20111aa2009-07-14 16:56:47 -070080#include <OMX.h>
Nicolas Catania14d27472009-07-13 14:37:49 -070081
Andreas Huber59451f82012-09-18 10:36:32 -070082#include "HDCP.h"
Andreas Huberb7319a72013-05-29 14:20:52 -070083#include "HTTPBase.h"
Andreas Huber35213f12012-08-29 11:41:50 -070084#include "RemoteDisplay.h"
Andreas Hubered3e3e02012-03-26 11:13:27 -070085
Wei Jia502c2f42017-07-13 17:47:56 -070086static const int kDumpLockRetries = 50;
87static const int kDumpLockSleepUs = 20000;
88
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070089namespace {
nikoa64c8c72009-07-20 15:07:26 -070090using android::media::Metadata;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070091using android::status_t;
92using android::OK;
93using android::BAD_VALUE;
94using android::NOT_ENOUGH_DATA;
95using android::Parcel;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070096
97// Max number of entries in the filter.
98const int kMaxFilterSize = 64; // I pulled that out of thin air.
99
Andy Hungff874dc2016-04-11 16:49:09 -0700100const float kMaxRequiredSpeed = 8.0f; // for PCM tracks allow up to 8x speedup.
101
nikoa64c8c72009-07-20 15:07:26 -0700102// FIXME: Move all the metadata related function in the Metadata.cpp
nikod608a812009-07-16 16:39:53 -0700103
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700104
105// Unmarshall a filter from a Parcel.
106// Filter format in a parcel:
107//
108// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
109// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
110// | number of entries (n) |
111// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
112// | metadata type 1 |
113// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
114// | metadata type 2 |
115// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
116// ....
117// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
118// | metadata type n |
119// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
120//
121// @param p Parcel that should start with a filter.
122// @param[out] filter On exit contains the list of metadata type to be
123// filtered.
124// @param[out] status On exit contains the status code to be returned.
125// @return true if the parcel starts with a valid filter.
126bool unmarshallFilter(const Parcel& p,
nikoa64c8c72009-07-20 15:07:26 -0700127 Metadata::Filter *filter,
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700128 status_t *status)
129{
Nicolas Catania48290382009-07-10 13:53:06 -0700130 int32_t val;
131 if (p.readInt32(&val) != OK)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700132 {
Steve Block29357bc2012-01-06 19:20:56 +0000133 ALOGE("Failed to read filter's length");
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700134 *status = NOT_ENOUGH_DATA;
135 return false;
136 }
137
Nicolas Catania48290382009-07-10 13:53:06 -0700138 if( val > kMaxFilterSize || val < 0)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700139 {
Steve Block29357bc2012-01-06 19:20:56 +0000140 ALOGE("Invalid filter len %d", val);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700141 *status = BAD_VALUE;
142 return false;
143 }
144
Nicolas Catania48290382009-07-10 13:53:06 -0700145 const size_t num = val;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700146
147 filter->clear();
Nicolas Catania48290382009-07-10 13:53:06 -0700148 filter->setCapacity(num);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700149
nikoa64c8c72009-07-20 15:07:26 -0700150 size_t size = num * sizeof(Metadata::Type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700151
Nicolas Catania48290382009-07-10 13:53:06 -0700152
153 if (p.dataAvail() < size)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700154 {
Andy Hung833b4752016-04-04 17:15:48 -0700155 ALOGE("Filter too short expected %zu but got %zu", size, p.dataAvail());
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700156 *status = NOT_ENOUGH_DATA;
157 return false;
158 }
159
nikoa64c8c72009-07-20 15:07:26 -0700160 const Metadata::Type *data =
161 static_cast<const Metadata::Type*>(p.readInplace(size));
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700162
Nicolas Catania48290382009-07-10 13:53:06 -0700163 if (NULL == data)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700164 {
Steve Block29357bc2012-01-06 19:20:56 +0000165 ALOGE("Filter had no data");
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700166 *status = BAD_VALUE;
167 return false;
168 }
169
170 // TODO: The stl impl of vector would be more efficient here
171 // because it degenerates into a memcpy on pod types. Try to
172 // replace later or use stl::set.
Nicolas Catania48290382009-07-10 13:53:06 -0700173 for (size_t i = 0; i < num; ++i)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700174 {
Nicolas Catania48290382009-07-10 13:53:06 -0700175 filter->add(*data);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700176 ++data;
177 }
178 *status = OK;
179 return true;
180}
181
Nicolas Catania48290382009-07-10 13:53:06 -0700182// @param filter Of metadata type.
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700183// @param val To be searched.
184// @return true if a match was found.
nikoa64c8c72009-07-20 15:07:26 -0700185bool findMetadata(const Metadata::Filter& filter, const int32_t val)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700186{
187 // Deal with empty and ANY right away
188 if (filter.isEmpty()) return false;
nikoa64c8c72009-07-20 15:07:26 -0700189 if (filter[0] == Metadata::kAny) return true;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700190
Nicolas Catania48290382009-07-10 13:53:06 -0700191 return filter.indexOf(val) >= 0;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700192}
193
194} // anonymous namespace
195
196
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700197namespace {
198using android::Parcel;
199using android::String16;
200
201// marshalling tag indicating flattened utf16 tags
202// keep in sync with frameworks/base/media/java/android/media/AudioAttributes.java
203const int32_t kAudioAttributesMarshallTagFlattenTags = 1;
204
205// Audio attributes format in a parcel:
206//
207// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
208// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
209// | usage |
210// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
211// | content_type |
212// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Hyejin Kim4f418f92014-09-05 15:50:03 +0900213// | source |
214// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700215// | flags |
216// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
217// | kAudioAttributesMarshallTagFlattenTags | // ignore tags if not found
218// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
219// | flattened tags in UTF16 |
220// | ... |
221// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
222//
223// @param p Parcel that contains audio attributes.
224// @param[out] attributes On exit points to an initialized audio_attributes_t structure
225// @param[out] status On exit contains the status code to be returned.
226void unmarshallAudioAttributes(const Parcel& parcel, audio_attributes_t *attributes)
227{
228 attributes->usage = (audio_usage_t) parcel.readInt32();
229 attributes->content_type = (audio_content_type_t) parcel.readInt32();
Hyejin Kim4f418f92014-09-05 15:50:03 +0900230 attributes->source = (audio_source_t) parcel.readInt32();
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700231 attributes->flags = (audio_flags_mask_t) parcel.readInt32();
232 const bool hasFlattenedTag = (parcel.readInt32() == kAudioAttributesMarshallTagFlattenTags);
233 if (hasFlattenedTag) {
234 // the tags are UTF16, convert to UTF8
235 String16 tags = parcel.readString16();
236 ssize_t realTagSize = utf16_to_utf8_length(tags.string(), tags.size());
237 if (realTagSize <= 0) {
238 strcpy(attributes->tags, "");
239 } else {
240 // copy the flattened string into the attributes as the destination for the conversion:
241 // copying array size -1, array for tags was calloc'd, no need to NULL-terminate it
242 size_t tagSize = realTagSize > AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 ?
243 AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 : realTagSize;
Sergio Giro1d3f4272016-06-28 18:24:52 +0100244 utf16_to_utf8(tags.string(), tagSize, attributes->tags,
245 sizeof(attributes->tags) / sizeof(attributes->tags[0]));
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700246 }
247 } else {
248 ALOGE("unmarshallAudioAttributes() received unflattened tags, ignoring tag values");
249 strcpy(attributes->tags, "");
250 }
251}
252} // anonymous namespace
253
254
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800255namespace android {
256
Marco Nelissenf09611f2015-02-13 14:12:42 -0800257extern ALooperRoster gLooperRoster;
258
259
Dave Burked681bbb2011-08-30 14:39:17 +0100260static bool checkPermission(const char* permissionString) {
Dave Burked681bbb2011-08-30 14:39:17 +0100261 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
262 bool ok = checkCallingPermission(String16(permissionString));
Steve Block29357bc2012-01-06 19:20:56 +0000263 if (!ok) ALOGE("Request requires %s", permissionString);
Dave Burked681bbb2011-08-30 14:39:17 +0100264 return ok;
265}
266
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800267// TODO: Find real cause of Audio/Video delay in PV framework and remove this workaround
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800268/* static */ int MediaPlayerService::AudioOutput::mMinBufferCount = 4;
269/* static */ bool MediaPlayerService::AudioOutput::mIsOnEmulator = false;
270
271void MediaPlayerService::instantiate() {
272 defaultServiceManager()->addService(
273 String16("media.player"), new MediaPlayerService());
274}
275
276MediaPlayerService::MediaPlayerService()
277{
Steve Block3856b092011-10-20 11:56:00 +0100278 ALOGV("MediaPlayerService created");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800279 mNextConnId = 1;
Gloria Wang9ee159b2011-02-24 14:51:45 -0800280
John Grossman44a7e422012-06-21 17:29:24 -0700281 MediaPlayerFactory::registerBuiltinFactories();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800282}
283
284MediaPlayerService::~MediaPlayerService()
285{
Steve Block3856b092011-10-20 11:56:00 +0100286 ALOGV("MediaPlayerService destroyed");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800287}
288
Svet Ganovbe71aa22015-04-28 12:06:02 -0700289sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(const String16 &opPackageName)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800290{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800291 pid_t pid = IPCThreadState::self()->getCallingPid();
Svet Ganovbe71aa22015-04-28 12:06:02 -0700292 sp<MediaRecorderClient> recorder = new MediaRecorderClient(this, pid, opPackageName);
Gloria Wangdac6a312009-10-29 15:46:37 -0700293 wp<MediaRecorderClient> w = recorder;
294 Mutex::Autolock lock(mLock);
295 mMediaRecorderClients.add(w);
Steve Block3856b092011-10-20 11:56:00 +0100296 ALOGV("Create new media recorder client from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800297 return recorder;
298}
299
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -0700300void MediaPlayerService::removeMediaRecorderClient(const wp<MediaRecorderClient>& client)
Gloria Wangdac6a312009-10-29 15:46:37 -0700301{
302 Mutex::Autolock lock(mLock);
303 mMediaRecorderClients.remove(client);
Steve Block3856b092011-10-20 11:56:00 +0100304 ALOGV("Delete media recorder client");
Gloria Wangdac6a312009-10-29 15:46:37 -0700305}
306
Glenn Kastenf37971f2012-02-03 11:06:53 -0800307sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800308{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800309 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800310 sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
Steve Block3856b092011-10-20 11:56:00 +0100311 ALOGV("Create new media retriever from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800312 return retriever;
313}
314
Glenn Kastenf37971f2012-02-03 11:06:53 -0800315sp<IMediaPlayer> MediaPlayerService::create(const sp<IMediaPlayerClient>& client,
Glenn Kastend848eb42016-03-08 13:42:11 -0800316 audio_session_t audioSessionId)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800317{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800318 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800319 int32_t connId = android_atomic_inc(&mNextConnId);
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700320
321 sp<Client> c = new Client(
322 this, pid, connId, client, audioSessionId,
323 IPCThreadState::self()->getCallingUid());
324
Steve Block3856b092011-10-20 11:56:00 +0100325 ALOGV("Create new client(%d) from pid %d, uid %d, ", connId, pid,
Dave Burked681bbb2011-08-30 14:39:17 +0100326 IPCThreadState::self()->getCallingUid());
327
328 wp<Client> w = c;
329 {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800330 Mutex::Autolock lock(mLock);
331 mClients.add(w);
332 }
Andreas Hubere2b10282010-11-23 11:41:34 -0800333 return c;
334}
335
Lajos Molnar1381d4b2014-08-07 15:18:35 -0700336sp<IMediaCodecList> MediaPlayerService::getCodecList() const {
337 return MediaCodecList::getLocalInstance();
338}
339
Marco Nelissen260e56c2016-01-28 21:41:25 +0000340sp<IOMX> MediaPlayerService::getOMX() {
Marco Nelissen1900e772016-02-02 16:12:16 -0800341 ALOGI("MediaPlayerService::getOMX");
Marco Nelissen260e56c2016-01-28 21:41:25 +0000342 Mutex::Autolock autoLock(mLock);
343
344 if (mOMX.get() == NULL) {
345 mOMX = new OMX;
346 }
347
348 return mOMX;
349}
350
Andreas Huber279dcd82013-01-30 10:41:25 -0800351sp<IHDCP> MediaPlayerService::makeHDCP(bool createEncryptionModule) {
352 return new HDCP(createEncryptionModule);
Andreas Huber59451f82012-09-18 10:36:32 -0700353}
354
Jeff Brown2013a542012-09-04 21:38:42 -0700355sp<IRemoteDisplay> MediaPlayerService::listenForRemoteDisplay(
Svet Ganovbe71aa22015-04-28 12:06:02 -0700356 const String16 &opPackageName,
Jeff Brown2013a542012-09-04 21:38:42 -0700357 const sp<IRemoteDisplayClient>& client, const String8& iface) {
Jeff Brownaba33d52012-09-07 17:38:58 -0700358 if (!checkPermission("android.permission.CONTROL_WIFI_DISPLAY")) {
359 return NULL;
360 }
361
Svet Ganovbe71aa22015-04-28 12:06:02 -0700362 return new RemoteDisplay(opPackageName, client, iface.string());
Jeff Brown2013a542012-09-04 21:38:42 -0700363}
364
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800365status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
366{
367 const size_t SIZE = 256;
368 char buffer[SIZE];
369 String8 result;
370
371 result.append(" AudioOutput\n");
372 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n",
373 mStreamType, mLeftVolume, mRightVolume);
374 result.append(buffer);
375 snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n",
Eric Laurentdb354e52012-03-05 17:27:11 -0800376 mMsecsPerFrame, (mTrack != 0) ? mTrack->latency() : -1);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800377 result.append(buffer);
Eric Laurent2beeb502010-07-16 07:43:46 -0700378 snprintf(buffer, 255, " aux effect id(%d), send level (%f)\n",
379 mAuxEffectId, mSendLevel);
380 result.append(buffer);
381
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800382 ::write(fd, result.string(), result.size());
383 if (mTrack != 0) {
384 mTrack->dump(fd, args);
385 }
386 return NO_ERROR;
387}
388
Lajos Molnar6d339f12015-04-17 16:15:53 -0700389status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800390{
391 const size_t SIZE = 256;
392 char buffer[SIZE];
393 String8 result;
394 result.append(" Client\n");
395 snprintf(buffer, 255, " pid(%d), connId(%d), status(%d), looping(%s)\n",
396 mPid, mConnId, mStatus, mLoop?"true": "false");
397 result.append(buffer);
Wei Jia502c2f42017-07-13 17:47:56 -0700398
399 sp<MediaPlayerBase> p;
400 sp<AudioOutput> audioOutput;
401 bool locked = false;
402 for (int i = 0; i < kDumpLockRetries; ++i) {
403 if (mLock.tryLock() == NO_ERROR) {
404 locked = true;
405 break;
406 }
407 usleep(kDumpLockSleepUs);
Andreas Hubera0b1d4b2011-06-07 15:52:25 -0700408 }
Wei Jia502c2f42017-07-13 17:47:56 -0700409
410 if (locked) {
411 p = mPlayer;
412 audioOutput = mAudioOutput;
413 mLock.unlock();
414 } else {
415 result.append(" lock is taken, no dump from player and audio output\n");
416 }
417 write(fd, result.string(), result.size());
418
419 if (p != NULL) {
420 p->dump(fd, args);
421 }
422 if (audioOutput != 0) {
423 audioOutput->dump(fd, args);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800424 }
425 write(fd, "\n", 1);
426 return NO_ERROR;
427}
428
Marco Nelissenf09611f2015-02-13 14:12:42 -0800429/**
430 * The only arguments this understands right now are -c, -von and -voff,
431 * which are parsed by ALooperRoster::dump()
432 */
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800433status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
434{
435 const size_t SIZE = 256;
436 char buffer[SIZE];
437 String8 result;
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530438 SortedVector< sp<Client> > clients; //to serialise the mutex unlock & client destruction.
439 SortedVector< sp<MediaRecorderClient> > mediaRecorderClients;
440
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800441 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
442 snprintf(buffer, SIZE, "Permission Denial: "
443 "can't dump MediaPlayerService from pid=%d, uid=%d\n",
444 IPCThreadState::self()->getCallingPid(),
445 IPCThreadState::self()->getCallingUid());
446 result.append(buffer);
447 } else {
448 Mutex::Autolock lock(mLock);
449 for (int i = 0, n = mClients.size(); i < n; ++i) {
450 sp<Client> c = mClients[i].promote();
451 if (c != 0) c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530452 clients.add(c);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800453 }
James Dongb9141222010-07-08 11:16:11 -0700454 if (mMediaRecorderClients.size() == 0) {
455 result.append(" No media recorder client\n\n");
456 } else {
457 for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
458 sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
James Donge579e282011-10-18 22:29:20 -0700459 if (c != 0) {
460 snprintf(buffer, 255, " MediaRecorderClient pid(%d)\n", c->mPid);
461 result.append(buffer);
462 write(fd, result.string(), result.size());
463 result = "\n";
464 c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530465 mediaRecorderClients.add(c);
James Donge579e282011-10-18 22:29:20 -0700466 }
James Dongb9141222010-07-08 11:16:11 -0700467 }
Gloria Wangdac6a312009-10-29 15:46:37 -0700468 }
469
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800470 result.append(" Files opened and/or mapped:\n");
Marco Nelissenf09611f2015-02-13 14:12:42 -0800471 snprintf(buffer, SIZE, "/proc/%d/maps", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800472 FILE *f = fopen(buffer, "r");
473 if (f) {
474 while (!feof(f)) {
475 fgets(buffer, SIZE, f);
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700476 if (strstr(buffer, " /storage/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800477 strstr(buffer, " /system/sounds/") ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700478 strstr(buffer, " /data/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800479 strstr(buffer, " /system/media/")) {
480 result.append(" ");
481 result.append(buffer);
482 }
483 }
484 fclose(f);
485 } else {
486 result.append("couldn't open ");
487 result.append(buffer);
488 result.append("\n");
489 }
490
Marco Nelissenf09611f2015-02-13 14:12:42 -0800491 snprintf(buffer, SIZE, "/proc/%d/fd", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800492 DIR *d = opendir(buffer);
493 if (d) {
494 struct dirent *ent;
495 while((ent = readdir(d)) != NULL) {
496 if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
Marco Nelissenf09611f2015-02-13 14:12:42 -0800497 snprintf(buffer, SIZE, "/proc/%d/fd/%s", getpid(), ent->d_name);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800498 struct stat s;
499 if (lstat(buffer, &s) == 0) {
500 if ((s.st_mode & S_IFMT) == S_IFLNK) {
501 char linkto[256];
502 int len = readlink(buffer, linkto, sizeof(linkto));
503 if(len > 0) {
504 if(len > 255) {
505 linkto[252] = '.';
506 linkto[253] = '.';
507 linkto[254] = '.';
508 linkto[255] = 0;
509 } else {
510 linkto[len] = 0;
511 }
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700512 if (strstr(linkto, "/storage/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800513 strstr(linkto, "/system/sounds/") == linkto ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700514 strstr(linkto, "/data/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800515 strstr(linkto, "/system/media/") == linkto) {
516 result.append(" ");
517 result.append(buffer);
518 result.append(" -> ");
519 result.append(linkto);
520 result.append("\n");
521 }
522 }
523 } else {
524 result.append(" unexpected type for ");
525 result.append(buffer);
526 result.append("\n");
527 }
528 }
529 }
530 }
531 closedir(d);
532 } else {
533 result.append("couldn't open ");
534 result.append(buffer);
535 result.append("\n");
536 }
537
Marco Nelissenf09611f2015-02-13 14:12:42 -0800538 gLooperRoster.dump(fd, args);
539
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800540 bool dumpMem = false;
Andy Hung53541292016-04-13 16:48:51 -0700541 bool unreachableMemory = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800542 for (size_t i = 0; i < args.size(); i++) {
543 if (args[i] == String16("-m")) {
544 dumpMem = true;
Andy Hung53541292016-04-13 16:48:51 -0700545 } else if (args[i] == String16("--unreachable")) {
546 unreachableMemory = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800547 }
548 }
549 if (dumpMem) {
Andy Hung07b745e2016-05-23 16:21:07 -0700550 result.append("\nDumping memory:\n");
551 std::string s = dumpMemoryAddresses(100 /* limit */);
552 result.append(s.c_str(), s.size());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800553 }
Andy Hung53541292016-04-13 16:48:51 -0700554 if (unreachableMemory) {
555 result.append("\nDumping unreachable memory:\n");
556 // TODO - should limit be an argument parameter?
557 std::string s = GetUnreachableMemoryString(true /* contents */, 10000 /* limit */);
558 result.append(s.c_str(), s.size());
559 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800560 }
561 write(fd, result.string(), result.size());
562 return NO_ERROR;
563}
564
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -0700565void MediaPlayerService::removeClient(const wp<Client>& client)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800566{
567 Mutex::Autolock lock(mLock);
568 mClients.remove(client);
569}
570
Robert Shihee0a0e32016-08-16 16:50:54 -0700571bool MediaPlayerService::hasClient(wp<Client> client)
572{
573 Mutex::Autolock lock(mLock);
574 return mClients.indexOf(client) != NAME_NOT_FOUND;
575}
576
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700577MediaPlayerService::Client::Client(
578 const sp<MediaPlayerService>& service, pid_t pid,
579 int32_t connId, const sp<IMediaPlayerClient>& client,
Glenn Kastend848eb42016-03-08 13:42:11 -0800580 audio_session_t audioSessionId, uid_t uid)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800581{
Steve Block3856b092011-10-20 11:56:00 +0100582 ALOGV("Client(%d) constructor", connId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800583 mPid = pid;
584 mConnId = connId;
585 mService = service;
586 mClient = client;
587 mLoop = false;
588 mStatus = NO_INIT;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700589 mAudioSessionId = audioSessionId;
Andy Hung1afd0982016-11-08 16:13:44 -0800590 mUid = uid;
John Grossmanc795b642012-02-22 15:38:35 -0800591 mRetransmitEndpointValid = false;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700592 mAudioAttributes = NULL;
Pawin Vongmasa082e4f72017-12-17 02:31:18 -0800593 mListener = new Listener(this);
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");
Pawin Vongmasa082e4f72017-12-17 02:31:18 -0800597 mAntagonizer = new Antagonizer(mListener);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800598#endif
599}
600
601MediaPlayerService::Client::~Client()
602{
Steve Block3856b092011-10-20 11:56:00 +0100603 ALOGV("Client(%d) destructor pid = %d", mConnId, mPid);
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700604 mAudioOutput.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800605 wp<Client> client(this);
606 disconnect();
607 mService->removeClient(client);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700608 if (mAudioAttributes != NULL) {
609 free(mAudioAttributes);
610 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700611 clearDeathNotifiers_l();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800612}
613
614void MediaPlayerService::Client::disconnect()
615{
Steve Block3856b092011-10-20 11:56:00 +0100616 ALOGV("disconnect(%d) from pid %d", mConnId, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800617 // grab local reference and clear main reference to prevent future
618 // access to object
619 sp<MediaPlayerBase> p;
620 {
621 Mutex::Autolock l(mLock);
622 p = mPlayer;
beanzdcfefde2012-11-05 09:51:43 +0800623 mClient.clear();
Wei Jia502c2f42017-07-13 17:47:56 -0700624 mPlayer.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800625 }
Andreas Huber20111aa2009-07-14 16:56:47 -0700626
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800627 // clear the notification to prevent callbacks to dead client
628 // and reset the player. We assume the player will serialize
629 // access to itself if necessary.
630 if (p != 0) {
Pawin Vongmasa082e4f72017-12-17 02:31:18 -0800631 p->setNotifyCallback(0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800632#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000633 ALOGD("kill Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800634 mAntagonizer->kill();
635#endif
636 p->reset();
637 }
638
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700639 {
640 Mutex::Autolock l(mLock);
641 disconnectNativeWindow_l();
642 }
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700643
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) {
Pawin Vongmasa082e4f72017-12-17 02:31:18 -0800656 p = MediaPlayerFactory::createPlayer(playerType, mListener, 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
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700719void MediaPlayerService::Client::clearDeathNotifiers_l() {
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800720 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);
734
735 // create the right type of player
736 sp<MediaPlayerBase> p = createPlayer(playerType);
737 if (p == NULL) {
738 return p;
739 }
740
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700741 sp<IServiceManager> sm = defaultServiceManager();
742 sp<IBinder> binder = sm->getService(String16("media.extractor"));
Marco Nelissen1b5a7ee2016-09-30 13:54:30 -0700743 if (binder == NULL) {
744 ALOGE("extractor service not available");
745 return NULL;
746 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700747 sp<ServiceDeathNotifier> extractorDeathListener =
748 new ServiceDeathNotifier(binder, p, MEDIAEXTRACTOR_PROCESS_DEATH);
749 binder->linkToDeath(extractorDeathListener);
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700750
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700751 sp<ServiceDeathNotifier> codecDeathListener;
Pawin Vongmasad4e9ca42017-03-29 17:24:56 -0700752 if (property_get_bool("persist.media.treble_omx", true)) {
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800753 // Treble IOmx
754 sp<IOmx> omx = IOmx::getService();
755 if (omx == nullptr) {
756 ALOGE("Treble IOmx not available");
757 return NULL;
758 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700759 codecDeathListener = new ServiceDeathNotifier(omx, p, MEDIACODEC_PROCESS_DEATH);
760 omx->linkToDeath(codecDeathListener, 0);
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800761 } else {
762 // Legacy IOMX
763 binder = sm->getService(String16("media.codec"));
764 if (binder == NULL) {
765 ALOGE("codec service not available");
766 return NULL;
767 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700768 codecDeathListener = new ServiceDeathNotifier(binder, p, MEDIACODEC_PROCESS_DEATH);
769 binder->linkToDeath(codecDeathListener);
Marco Nelissen1b5a7ee2016-09-30 13:54:30 -0700770 }
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700771
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700772 Mutex::Autolock lock(mLock);
773
774 clearDeathNotifiers_l();
775 mExtractorDeathListener = extractorDeathListener;
776 mCodecDeathListener = codecDeathListener;
777
John Grossmanc795b642012-02-22 15:38:35 -0800778 if (!p->hardwareOutput()) {
Marco Nelissend457c972014-02-11 08:47:07 -0800779 mAudioOutput = new AudioOutput(mAudioSessionId, IPCThreadState::self()->getCallingUid(),
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700780 mPid, mAudioAttributes);
John Grossmanc795b642012-02-22 15:38:35 -0800781 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
782 }
783
784 return p;
785}
786
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700787status_t MediaPlayerService::Client::setDataSource_post(
John Grossmanc795b642012-02-22 15:38:35 -0800788 const sp<MediaPlayerBase>& p,
789 status_t status)
790{
791 ALOGV(" setDataSource");
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700792 if (status != OK) {
793 ALOGE(" error: %d", status);
794 return status;
John Grossmanc795b642012-02-22 15:38:35 -0800795 }
796
797 // Set the re-transmission endpoint if one was chosen.
798 if (mRetransmitEndpointValid) {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700799 status = p->setRetransmitEndpoint(&mRetransmitEndpoint);
800 if (status != NO_ERROR) {
801 ALOGE("setRetransmitEndpoint error: %d", status);
John Grossmanc795b642012-02-22 15:38:35 -0800802 }
803 }
804
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700805 if (status == OK) {
806 Mutex::Autolock lock(mLock);
John Grossmanc795b642012-02-22 15:38:35 -0800807 mPlayer = p;
808 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700809 return status;
John Grossmanc795b642012-02-22 15:38:35 -0800810}
811
Andreas Huber2db84552010-01-28 11:19:57 -0800812status_t MediaPlayerService::Client::setDataSource(
Andreas Huber1b86fe02014-01-29 11:13:26 -0800813 const sp<IMediaHTTPService> &httpService,
814 const char *url,
815 const KeyedVector<String8, String8> *headers)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800816{
Steve Block3856b092011-10-20 11:56:00 +0100817 ALOGV("setDataSource(%s)", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800818 if (url == NULL)
819 return UNKNOWN_ERROR;
820
Dave Burked681bbb2011-08-30 14:39:17 +0100821 if ((strncmp(url, "http://", 7) == 0) ||
822 (strncmp(url, "https://", 8) == 0) ||
823 (strncmp(url, "rtsp://", 7) == 0)) {
824 if (!checkPermission("android.permission.INTERNET")) {
825 return PERMISSION_DENIED;
826 }
827 }
828
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800829 if (strncmp(url, "content://", 10) == 0) {
830 // get a filedescriptor for the content Uri and
831 // pass it to the setDataSource(fd) method
832
833 String16 url16(url);
834 int fd = android::openContentProviderFile(url16);
835 if (fd < 0)
836 {
Steve Block29357bc2012-01-06 19:20:56 +0000837 ALOGE("Couldn't open fd for %s", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800838 return UNKNOWN_ERROR;
839 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700840 status_t status = setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800841 close(fd);
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700842 return mStatus = status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800843 } else {
John Grossman44a7e422012-06-21 17:29:24 -0700844 player_type playerType = MediaPlayerFactory::getPlayerType(this, url);
John Grossmanc795b642012-02-22 15:38:35 -0800845 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
846 if (p == NULL) {
847 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800848 }
849
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700850 return mStatus =
851 setDataSource_post(
852 p, p->setDataSource(httpService, url, headers));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800853 }
854}
855
856status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
857{
Marco Nelissen83b0fd92015-09-16 13:48:07 -0700858 ALOGV("setDataSource fd=%d (%s), offset=%lld, length=%lld",
859 fd, nameForFd(fd).c_str(), (long long) offset, (long long) length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800860 struct stat sb;
861 int ret = fstat(fd, &sb);
862 if (ret != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000863 ALOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800864 return UNKNOWN_ERROR;
865 }
866
Andy Hung833b4752016-04-04 17:15:48 -0700867 ALOGV("st_dev = %llu", static_cast<unsigned long long>(sb.st_dev));
Steve Block3856b092011-10-20 11:56:00 +0100868 ALOGV("st_mode = %u", sb.st_mode);
Mark Salyzyn77342f72014-06-18 16:31:32 -0700869 ALOGV("st_uid = %lu", static_cast<unsigned long>(sb.st_uid));
870 ALOGV("st_gid = %lu", static_cast<unsigned long>(sb.st_gid));
Andy Hung833b4752016-04-04 17:15:48 -0700871 ALOGV("st_size = %llu", static_cast<unsigned long long>(sb.st_size));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800872
873 if (offset >= sb.st_size) {
Steve Block29357bc2012-01-06 19:20:56 +0000874 ALOGE("offset error");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800875 return UNKNOWN_ERROR;
876 }
877 if (offset + length > sb.st_size) {
878 length = sb.st_size - offset;
Andy Hung833b4752016-04-04 17:15:48 -0700879 ALOGV("calculated length = %lld", (long long)length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800880 }
881
John Grossman44a7e422012-06-21 17:29:24 -0700882 player_type playerType = MediaPlayerFactory::getPlayerType(this,
883 fd,
884 offset,
885 length);
John Grossmanc795b642012-02-22 15:38:35 -0800886 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
887 if (p == NULL) {
888 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800889 }
890
891 // now set data source
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700892 return mStatus = setDataSource_post(p, p->setDataSource(fd, offset, length));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800893}
894
Andreas Hubere2b10282010-11-23 11:41:34 -0800895status_t MediaPlayerService::Client::setDataSource(
896 const sp<IStreamSource> &source) {
897 // create the right type of player
John Grossman44a7e422012-06-21 17:29:24 -0700898 player_type playerType = MediaPlayerFactory::getPlayerType(this, source);
John Grossmanc795b642012-02-22 15:38:35 -0800899 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
Andreas Hubere2b10282010-11-23 11:41:34 -0800900 if (p == NULL) {
901 return NO_INIT;
902 }
903
Andreas Hubere2b10282010-11-23 11:41:34 -0800904 // now set data source
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700905 return mStatus = setDataSource_post(p, p->setDataSource(source));
Andreas Hubere2b10282010-11-23 11:41:34 -0800906}
907
Chris Watkins99f31602015-03-20 13:06:33 -0700908status_t MediaPlayerService::Client::setDataSource(
909 const sp<IDataSource> &source) {
910 sp<DataSource> dataSource = DataSource::CreateFromIDataSource(source);
911 player_type playerType = MediaPlayerFactory::getPlayerType(this, dataSource);
912 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
913 if (p == NULL) {
914 return NO_INIT;
915 }
916 // now set data source
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700917 return mStatus = setDataSource_post(p, p->setDataSource(dataSource));
Chris Watkins99f31602015-03-20 13:06:33 -0700918}
919
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700920void MediaPlayerService::Client::disconnectNativeWindow_l() {
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700921 if (mConnectedWindow != NULL) {
Chong Zhang181fd9b2017-02-16 15:53:03 -0800922 status_t err = nativeWindowDisconnect(
923 mConnectedWindow.get(), "disconnectNativeWindow");
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700924
925 if (err != OK) {
Chong Zhang181fd9b2017-02-16 15:53:03 -0800926 ALOGW("nativeWindowDisconnect returned an error: %s (%d)",
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700927 strerror(-err), err);
928 }
929 }
930 mConnectedWindow.clear();
931}
932
Glenn Kasten11731182011-02-08 17:26:17 -0800933status_t MediaPlayerService::Client::setVideoSurfaceTexture(
Andy McFadden484566c2012-12-18 09:46:54 -0800934 const sp<IGraphicBufferProducer>& bufferProducer)
Glenn Kasten11731182011-02-08 17:26:17 -0800935{
Andy McFadden484566c2012-12-18 09:46:54 -0800936 ALOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, bufferProducer.get());
Glenn Kasten11731182011-02-08 17:26:17 -0800937 sp<MediaPlayerBase> p = getPlayer();
938 if (p == 0) return UNKNOWN_ERROR;
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700939
Marco Nelissenf8880202014-11-14 07:58:25 -0800940 sp<IBinder> binder(IInterface::asBinder(bufferProducer));
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700941 if (mConnectedWindowBinder == binder) {
942 return OK;
943 }
944
945 sp<ANativeWindow> anw;
Andy McFadden484566c2012-12-18 09:46:54 -0800946 if (bufferProducer != NULL) {
Marco Nelissenee08f7e2013-09-16 13:30:01 -0700947 anw = new Surface(bufferProducer, true /* controlledByApp */);
Chong Zhang181fd9b2017-02-16 15:53:03 -0800948 status_t err = nativeWindowConnect(anw.get(), "setVideoSurfaceTexture");
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700949
950 if (err != OK) {
Steve Block29357bc2012-01-06 19:20:56 +0000951 ALOGE("setVideoSurfaceTexture failed: %d", err);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700952 // Note that we must do the reset before disconnecting from the ANW.
953 // Otherwise queue/dequeue calls could be made on the disconnected
954 // ANW, which may result in errors.
955 reset();
956
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700957 Mutex::Autolock lock(mLock);
958 disconnectNativeWindow_l();
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700959
960 return err;
961 }
962 }
963
Andy McFadden484566c2012-12-18 09:46:54 -0800964 // Note that we must set the player's new GraphicBufferProducer before
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700965 // disconnecting the old one. Otherwise queue/dequeue calls could be made
966 // on the disconnected ANW, which may result in errors.
Andy McFadden484566c2012-12-18 09:46:54 -0800967 status_t err = p->setVideoSurfaceTexture(bufferProducer);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700968
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700969 mLock.lock();
970 disconnectNativeWindow_l();
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700971
972 if (err == OK) {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700973 mConnectedWindow = anw;
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700974 mConnectedWindowBinder = binder;
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700975 mLock.unlock();
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700976 } else {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700977 mLock.unlock();
978 status_t err = nativeWindowDisconnect(
979 anw.get(), "disconnectNativeWindow");
980
981 if (err != OK) {
982 ALOGW("nativeWindowDisconnect returned an error: %s (%d)",
983 strerror(-err), err);
984 }
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700985 }
986
987 return err;
Glenn Kasten11731182011-02-08 17:26:17 -0800988}
989
Nicolas Catania1d187f12009-05-12 23:25:55 -0700990status_t MediaPlayerService::Client::invoke(const Parcel& request,
991 Parcel *reply)
992{
993 sp<MediaPlayerBase> p = getPlayer();
994 if (p == NULL) return UNKNOWN_ERROR;
995 return p->invoke(request, reply);
996}
997
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700998// This call doesn't need to access the native player.
999status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
1000{
1001 status_t status;
nikoa64c8c72009-07-20 15:07:26 -07001002 media::Metadata::Filter allow, drop;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001003
Nicolas Catania48290382009-07-10 13:53:06 -07001004 if (unmarshallFilter(filter, &allow, &status) &&
1005 unmarshallFilter(filter, &drop, &status)) {
1006 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001007
1008 mMetadataAllow = allow;
1009 mMetadataDrop = drop;
1010 }
1011 return status;
1012}
1013
Nicolas Catania48290382009-07-10 13:53:06 -07001014status_t MediaPlayerService::Client::getMetadata(
Mark Salyzyn77342f72014-06-18 16:31:32 -07001015 bool update_only, bool /*apply_filter*/, Parcel *reply)
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001016{
nikoa64c8c72009-07-20 15:07:26 -07001017 sp<MediaPlayerBase> player = getPlayer();
1018 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania48290382009-07-10 13:53:06 -07001019
nikod608a812009-07-16 16:39:53 -07001020 status_t status;
1021 // Placeholder for the return code, updated by the caller.
1022 reply->writeInt32(-1);
1023
nikoa64c8c72009-07-20 15:07:26 -07001024 media::Metadata::Filter ids;
Nicolas Catania48290382009-07-10 13:53:06 -07001025
1026 // We don't block notifications while we fetch the data. We clear
1027 // mMetadataUpdated first so we don't lose notifications happening
1028 // during the rest of this call.
1029 {
1030 Mutex::Autolock lock(mLock);
1031 if (update_only) {
nikod608a812009-07-16 16:39:53 -07001032 ids = mMetadataUpdated;
Nicolas Catania48290382009-07-10 13:53:06 -07001033 }
1034 mMetadataUpdated.clear();
1035 }
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001036
nikoa64c8c72009-07-20 15:07:26 -07001037 media::Metadata metadata(reply);
Nicolas Catania48290382009-07-10 13:53:06 -07001038
nikoa64c8c72009-07-20 15:07:26 -07001039 metadata.appendHeader();
1040 status = player->getMetadata(ids, reply);
nikod608a812009-07-16 16:39:53 -07001041
1042 if (status != OK) {
nikoa64c8c72009-07-20 15:07:26 -07001043 metadata.resetParcel();
Steve Block29357bc2012-01-06 19:20:56 +00001044 ALOGE("getMetadata failed %d", status);
nikod608a812009-07-16 16:39:53 -07001045 return status;
1046 }
1047
1048 // FIXME: Implement filtering on the result. Not critical since
1049 // filtering takes place on the update notifications already. This
1050 // would be when all the metadata are fetch and a filter is set.
1051
nikod608a812009-07-16 16:39:53 -07001052 // Everything is fine, update the metadata length.
nikoa64c8c72009-07-20 15:07:26 -07001053 metadata.updateLength();
nikod608a812009-07-16 16:39:53 -07001054 return OK;
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001055}
1056
Wei Jiad399e7e2016-10-26 15:49:11 -07001057status_t MediaPlayerService::Client::setBufferingSettings(
1058 const BufferingSettings& buffering)
1059{
Wei Jiadc6f3402017-01-09 15:04:18 -08001060 ALOGV("[%d] setBufferingSettings{%s}",
1061 mConnId, buffering.toString().string());
Wei Jiad399e7e2016-10-26 15:49:11 -07001062 sp<MediaPlayerBase> p = getPlayer();
1063 if (p == 0) return UNKNOWN_ERROR;
1064 return p->setBufferingSettings(buffering);
1065}
1066
1067status_t MediaPlayerService::Client::getDefaultBufferingSettings(
1068 BufferingSettings* buffering /* nonnull */)
1069{
1070 sp<MediaPlayerBase> p = getPlayer();
1071 // TODO: create mPlayer on demand.
1072 if (p == 0) return UNKNOWN_ERROR;
1073 status_t ret = p->getDefaultBufferingSettings(buffering);
1074 if (ret == NO_ERROR) {
Wei Jiadc6f3402017-01-09 15:04:18 -08001075 ALOGV("[%d] getDefaultBufferingSettings{%s}",
1076 mConnId, buffering->toString().string());
Wei Jiad399e7e2016-10-26 15:49:11 -07001077 } else {
1078 ALOGV("[%d] getDefaultBufferingSettings returned %d", mConnId, ret);
1079 }
1080 return ret;
1081}
1082
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001083status_t MediaPlayerService::Client::prepareAsync()
1084{
Steve Block3856b092011-10-20 11:56:00 +01001085 ALOGV("[%d] prepareAsync", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001086 sp<MediaPlayerBase> p = getPlayer();
1087 if (p == 0) return UNKNOWN_ERROR;
1088 status_t ret = p->prepareAsync();
1089#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +00001090 ALOGD("start Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001091 if (ret == NO_ERROR) mAntagonizer->start();
1092#endif
1093 return ret;
1094}
1095
1096status_t MediaPlayerService::Client::start()
1097{
Steve Block3856b092011-10-20 11:56:00 +01001098 ALOGV("[%d] start", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001099 sp<MediaPlayerBase> p = getPlayer();
1100 if (p == 0) return UNKNOWN_ERROR;
1101 p->setLooping(mLoop);
1102 return p->start();
1103}
1104
1105status_t MediaPlayerService::Client::stop()
1106{
Steve Block3856b092011-10-20 11:56:00 +01001107 ALOGV("[%d] stop", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001108 sp<MediaPlayerBase> p = getPlayer();
1109 if (p == 0) return UNKNOWN_ERROR;
1110 return p->stop();
1111}
1112
1113status_t MediaPlayerService::Client::pause()
1114{
Steve Block3856b092011-10-20 11:56:00 +01001115 ALOGV("[%d] pause", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001116 sp<MediaPlayerBase> p = getPlayer();
1117 if (p == 0) return UNKNOWN_ERROR;
1118 return p->pause();
1119}
1120
1121status_t MediaPlayerService::Client::isPlaying(bool* state)
1122{
1123 *state = false;
1124 sp<MediaPlayerBase> p = getPlayer();
1125 if (p == 0) return UNKNOWN_ERROR;
1126 *state = p->isPlaying();
Steve Block3856b092011-10-20 11:56:00 +01001127 ALOGV("[%d] isPlaying: %d", mConnId, *state);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001128 return NO_ERROR;
1129}
1130
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001131status_t MediaPlayerService::Client::setPlaybackSettings(const AudioPlaybackRate& rate)
Wei Jia98160162015-02-04 17:01:11 -08001132{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001133 ALOGV("[%d] setPlaybackSettings(%f, %f, %d, %d)",
1134 mConnId, rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Wei Jia98160162015-02-04 17:01:11 -08001135 sp<MediaPlayerBase> p = getPlayer();
1136 if (p == 0) return UNKNOWN_ERROR;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001137 return p->setPlaybackSettings(rate);
1138}
1139
1140status_t MediaPlayerService::Client::getPlaybackSettings(AudioPlaybackRate* rate /* nonnull */)
1141{
1142 sp<MediaPlayerBase> p = getPlayer();
1143 if (p == 0) return UNKNOWN_ERROR;
1144 status_t ret = p->getPlaybackSettings(rate);
1145 if (ret == NO_ERROR) {
1146 ALOGV("[%d] getPlaybackSettings(%f, %f, %d, %d)",
1147 mConnId, rate->mSpeed, rate->mPitch, rate->mFallbackMode, rate->mStretchMode);
1148 } else {
1149 ALOGV("[%d] getPlaybackSettings returned %d", mConnId, ret);
1150 }
1151 return ret;
1152}
1153
1154status_t MediaPlayerService::Client::setSyncSettings(
1155 const AVSyncSettings& sync, float videoFpsHint)
1156{
1157 ALOGV("[%d] setSyncSettings(%u, %u, %f, %f)",
1158 mConnId, sync.mSource, sync.mAudioAdjustMode, sync.mTolerance, videoFpsHint);
1159 sp<MediaPlayerBase> p = getPlayer();
1160 if (p == 0) return UNKNOWN_ERROR;
1161 return p->setSyncSettings(sync, videoFpsHint);
1162}
1163
1164status_t MediaPlayerService::Client::getSyncSettings(
1165 AVSyncSettings* sync /* nonnull */, float* videoFps /* nonnull */)
1166{
1167 sp<MediaPlayerBase> p = getPlayer();
1168 if (p == 0) return UNKNOWN_ERROR;
1169 status_t ret = p->getSyncSettings(sync, videoFps);
1170 if (ret == NO_ERROR) {
1171 ALOGV("[%d] getSyncSettings(%u, %u, %f, %f)",
1172 mConnId, sync->mSource, sync->mAudioAdjustMode, sync->mTolerance, *videoFps);
1173 } else {
1174 ALOGV("[%d] getSyncSettings returned %d", mConnId, ret);
1175 }
1176 return ret;
Wei Jia98160162015-02-04 17:01:11 -08001177}
1178
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001179status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
1180{
Steve Block3856b092011-10-20 11:56:00 +01001181 ALOGV("getCurrentPosition");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001182 sp<MediaPlayerBase> p = getPlayer();
1183 if (p == 0) return UNKNOWN_ERROR;
1184 status_t ret = p->getCurrentPosition(msec);
1185 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001186 ALOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001187 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001188 ALOGE("getCurrentPosition returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001189 }
1190 return ret;
1191}
1192
1193status_t MediaPlayerService::Client::getDuration(int *msec)
1194{
Steve Block3856b092011-10-20 11:56:00 +01001195 ALOGV("getDuration");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001196 sp<MediaPlayerBase> p = getPlayer();
1197 if (p == 0) return UNKNOWN_ERROR;
1198 status_t ret = p->getDuration(msec);
1199 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001200 ALOGV("[%d] getDuration = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001201 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001202 ALOGE("getDuration returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001203 }
1204 return ret;
1205}
1206
Marco Nelissen6b74d672012-02-28 16:07:44 -08001207status_t MediaPlayerService::Client::setNextPlayer(const sp<IMediaPlayer>& player) {
1208 ALOGV("setNextPlayer");
1209 Mutex::Autolock l(mLock);
1210 sp<Client> c = static_cast<Client*>(player.get());
Wei Jia28284122016-08-30 13:49:06 -07001211 if (c != NULL && !mService->hasClient(c)) {
Robert Shihee0a0e32016-08-16 16:50:54 -07001212 return BAD_VALUE;
1213 }
1214
Marco Nelissen6b74d672012-02-28 16:07:44 -08001215 mNextClient = c;
John Grossman5f7e55e2012-08-24 14:47:25 -07001216
1217 if (c != NULL) {
1218 if (mAudioOutput != NULL) {
1219 mAudioOutput->setNextOutput(c->mAudioOutput);
1220 } else if ((mPlayer != NULL) && !mPlayer->hardwareOutput()) {
1221 ALOGE("no current audio output");
1222 }
1223
1224 if ((mPlayer != NULL) && (mNextClient->getPlayer() != NULL)) {
1225 mPlayer->setNextPlayer(mNextClient->getPlayer());
1226 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001227 }
John Grossman5f7e55e2012-08-24 14:47:25 -07001228
Marco Nelissen6b74d672012-02-28 16:07:44 -08001229 return OK;
1230}
1231
Andy Hung9fc8b5c2017-01-24 13:36:48 -08001232VolumeShaper::Status MediaPlayerService::Client::applyVolumeShaper(
1233 const sp<VolumeShaper::Configuration>& configuration,
1234 const sp<VolumeShaper::Operation>& operation) {
1235 // for hardware output, call player instead
1236 ALOGV("Client::applyVolumeShaper(%p)", this);
1237 sp<MediaPlayerBase> p = getPlayer();
1238 {
1239 Mutex::Autolock l(mLock);
1240 if (p != 0 && p->hardwareOutput()) {
1241 // TODO: investigate internal implementation
1242 return VolumeShaper::Status(INVALID_OPERATION);
1243 }
1244 if (mAudioOutput.get() != nullptr) {
1245 return mAudioOutput->applyVolumeShaper(configuration, operation);
1246 }
1247 }
1248 return VolumeShaper::Status(INVALID_OPERATION);
1249}
1250
1251sp<VolumeShaper::State> MediaPlayerService::Client::getVolumeShaperState(int id) {
1252 // for hardware output, call player instead
1253 ALOGV("Client::getVolumeShaperState(%p)", this);
1254 sp<MediaPlayerBase> p = getPlayer();
1255 {
1256 Mutex::Autolock l(mLock);
1257 if (p != 0 && p->hardwareOutput()) {
1258 // TODO: investigate internal implementation.
1259 return nullptr;
1260 }
1261 if (mAudioOutput.get() != nullptr) {
1262 return mAudioOutput->getVolumeShaperState(id);
1263 }
1264 }
1265 return nullptr;
1266}
1267
Wei Jiac5de0912016-11-18 10:22:14 -08001268status_t MediaPlayerService::Client::seekTo(int msec, MediaPlayerSeekMode mode)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001269{
Wei Jiac5de0912016-11-18 10:22:14 -08001270 ALOGV("[%d] seekTo(%d, %d)", mConnId, msec, mode);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001271 sp<MediaPlayerBase> p = getPlayer();
1272 if (p == 0) return UNKNOWN_ERROR;
Wei Jiac5de0912016-11-18 10:22:14 -08001273 return p->seekTo(msec, mode);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001274}
1275
1276status_t MediaPlayerService::Client::reset()
1277{
Steve Block3856b092011-10-20 11:56:00 +01001278 ALOGV("[%d] reset", mConnId);
John Grossmanc795b642012-02-22 15:38:35 -08001279 mRetransmitEndpointValid = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001280 sp<MediaPlayerBase> p = getPlayer();
1281 if (p == 0) return UNKNOWN_ERROR;
1282 return p->reset();
1283}
1284
Glenn Kastenfff6d712012-01-12 16:38:12 -08001285status_t MediaPlayerService::Client::setAudioStreamType(audio_stream_type_t type)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001286{
Steve Block3856b092011-10-20 11:56:00 +01001287 ALOGV("[%d] setAudioStreamType(%d)", mConnId, type);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001288 // TODO: for hardware output, call player instead
1289 Mutex::Autolock l(mLock);
1290 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1291 return NO_ERROR;
1292}
1293
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001294status_t MediaPlayerService::Client::setAudioAttributes_l(const Parcel &parcel)
1295{
1296 if (mAudioAttributes != NULL) { free(mAudioAttributes); }
1297 mAudioAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001298 if (mAudioAttributes == NULL) {
1299 return NO_MEMORY;
1300 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001301 unmarshallAudioAttributes(parcel, mAudioAttributes);
1302
1303 ALOGV("setAudioAttributes_l() usage=%d content=%d flags=0x%x tags=%s",
1304 mAudioAttributes->usage, mAudioAttributes->content_type, mAudioAttributes->flags,
1305 mAudioAttributes->tags);
1306
1307 if (mAudioOutput != 0) {
1308 mAudioOutput->setAudioAttributes(mAudioAttributes);
1309 }
1310 return NO_ERROR;
1311}
1312
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001313status_t MediaPlayerService::Client::setLooping(int loop)
1314{
Steve Block3856b092011-10-20 11:56:00 +01001315 ALOGV("[%d] setLooping(%d)", mConnId, loop);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001316 mLoop = loop;
1317 sp<MediaPlayerBase> p = getPlayer();
1318 if (p != 0) return p->setLooping(loop);
1319 return NO_ERROR;
1320}
1321
1322status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1323{
Steve Block3856b092011-10-20 11:56:00 +01001324 ALOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
John Grossman761defc2012-02-09 15:09:05 -08001325
1326 // for hardware output, call player instead
1327 sp<MediaPlayerBase> p = getPlayer();
1328 {
1329 Mutex::Autolock l(mLock);
1330 if (p != 0 && p->hardwareOutput()) {
1331 MediaPlayerHWInterface* hwp =
1332 reinterpret_cast<MediaPlayerHWInterface*>(p.get());
1333 return hwp->setVolume(leftVolume, rightVolume);
1334 } else {
1335 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1336 return NO_ERROR;
1337 }
1338 }
1339
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001340 return NO_ERROR;
1341}
1342
Eric Laurent2beeb502010-07-16 07:43:46 -07001343status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1344{
Steve Block3856b092011-10-20 11:56:00 +01001345 ALOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
Eric Laurent2beeb502010-07-16 07:43:46 -07001346 Mutex::Autolock l(mLock);
1347 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1348 return NO_ERROR;
1349}
1350
1351status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1352{
Steve Block3856b092011-10-20 11:56:00 +01001353 ALOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
Eric Laurent2beeb502010-07-16 07:43:46 -07001354 Mutex::Autolock l(mLock);
1355 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1356 return NO_ERROR;
1357}
Nicolas Catania48290382009-07-10 13:53:06 -07001358
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001359status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
Steve Block3856b092011-10-20 11:56:00 +01001360 ALOGV("[%d] setParameter(%d)", mConnId, key);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001361 switch (key) {
1362 case KEY_PARAMETER_AUDIO_ATTRIBUTES:
1363 {
1364 Mutex::Autolock l(mLock);
1365 return setAudioAttributes_l(request);
1366 }
1367 default:
1368 sp<MediaPlayerBase> p = getPlayer();
1369 if (p == 0) { return UNKNOWN_ERROR; }
1370 return p->setParameter(key, request);
1371 }
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001372}
1373
1374status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
Steve Block3856b092011-10-20 11:56:00 +01001375 ALOGV("[%d] getParameter(%d)", mConnId, key);
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001376 sp<MediaPlayerBase> p = getPlayer();
1377 if (p == 0) return UNKNOWN_ERROR;
1378 return p->getParameter(key, reply);
1379}
1380
John Grossmanc795b642012-02-22 15:38:35 -08001381status_t MediaPlayerService::Client::setRetransmitEndpoint(
1382 const struct sockaddr_in* endpoint) {
1383
1384 if (NULL != endpoint) {
1385 uint32_t a = ntohl(endpoint->sin_addr.s_addr);
1386 uint16_t p = ntohs(endpoint->sin_port);
1387 ALOGV("[%d] setRetransmitEndpoint(%u.%u.%u.%u:%hu)", mConnId,
1388 (a >> 24), (a >> 16) & 0xFF, (a >> 8) & 0xFF, (a & 0xFF), p);
1389 } else {
1390 ALOGV("[%d] setRetransmitEndpoint = <none>", mConnId);
1391 }
1392
1393 sp<MediaPlayerBase> p = getPlayer();
1394
1395 // Right now, the only valid time to set a retransmit endpoint is before
1396 // player selection has been made (since the presence or absence of a
1397 // retransmit endpoint is going to determine which player is selected during
1398 // setDataSource).
1399 if (p != 0) return INVALID_OPERATION;
1400
1401 if (NULL != endpoint) {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001402 Mutex::Autolock lock(mLock);
John Grossmanc795b642012-02-22 15:38:35 -08001403 mRetransmitEndpoint = *endpoint;
1404 mRetransmitEndpointValid = true;
1405 } else {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001406 Mutex::Autolock lock(mLock);
John Grossmanc795b642012-02-22 15:38:35 -08001407 mRetransmitEndpointValid = false;
1408 }
1409
1410 return NO_ERROR;
1411}
1412
John Grossman44a7e422012-06-21 17:29:24 -07001413status_t MediaPlayerService::Client::getRetransmitEndpoint(
1414 struct sockaddr_in* endpoint)
1415{
1416 if (NULL == endpoint)
1417 return BAD_VALUE;
1418
1419 sp<MediaPlayerBase> p = getPlayer();
1420
1421 if (p != NULL)
1422 return p->getRetransmitEndpoint(endpoint);
1423
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001424 Mutex::Autolock lock(mLock);
John Grossman44a7e422012-06-21 17:29:24 -07001425 if (!mRetransmitEndpointValid)
1426 return NO_INIT;
1427
1428 *endpoint = mRetransmitEndpoint;
1429
1430 return NO_ERROR;
1431}
1432
Gloria Wangb483c472011-04-11 17:23:27 -07001433void MediaPlayerService::Client::notify(
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001434 int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001435{
James Dongb8a98252012-08-26 16:13:03 -07001436 sp<IMediaPlayerClient> c;
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001437 sp<Client> nextClient;
1438 status_t errStartNext = NO_ERROR;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001439 {
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001440 Mutex::Autolock l(mLock);
1441 c = mClient;
1442 if (msg == MEDIA_PLAYBACK_COMPLETE && mNextClient != NULL) {
1443 nextClient = mNextClient;
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001444
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001445 if (mAudioOutput != NULL)
1446 mAudioOutput->switchToNextOutput();
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001447
1448 errStartNext = nextClient->start();
1449 }
1450 }
1451
1452 if (nextClient != NULL) {
1453 sp<IMediaPlayerClient> nc;
1454 {
1455 Mutex::Autolock l(nextClient->mLock);
1456 nc = nextClient->mClient;
1457 }
1458 if (nc != NULL) {
1459 if (errStartNext == NO_ERROR) {
1460 nc->notify(MEDIA_INFO, MEDIA_INFO_STARTED_AS_NEXT, 0, obj);
1461 } else {
1462 nc->notify(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN , 0, obj);
1463 ALOGE("gapless:start playback for next track failed, err(%d)", errStartNext);
Wei Jia2afac0c2016-01-07 12:13:07 -08001464 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001465 }
1466 }
1467
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001468 if (MEDIA_INFO == msg &&
Nicolas Catania48290382009-07-10 13:53:06 -07001469 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikoa64c8c72009-07-20 15:07:26 -07001470 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania48290382009-07-10 13:53:06 -07001471
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001472 if(shouldDropMetadata(metadata_type)) {
Nicolas Catania48290382009-07-10 13:53:06 -07001473 return;
1474 }
1475
1476 // Update the list of metadata that have changed. getMetadata
1477 // also access mMetadataUpdated and clears it.
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001478 addNewMetadataUpdate(metadata_type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001479 }
James Dongb8a98252012-08-26 16:13:03 -07001480
1481 if (c != NULL) {
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001482 ALOGV("[%d] notify (%d, %d, %d)", mConnId, msg, ext1, ext2);
James Dongb8a98252012-08-26 16:13:03 -07001483 c->notify(msg, ext1, ext2, obj);
1484 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001485}
1486
Nicolas Catania48290382009-07-10 13:53:06 -07001487
nikoa64c8c72009-07-20 15:07:26 -07001488bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001489{
Nicolas Catania48290382009-07-10 13:53:06 -07001490 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001491
Nicolas Catania48290382009-07-10 13:53:06 -07001492 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001493 return true;
1494 }
1495
Nicolas Catania48290382009-07-10 13:53:06 -07001496 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001497 return false;
Nicolas Catania48290382009-07-10 13:53:06 -07001498 } else {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001499 return true;
1500 }
1501}
1502
Nicolas Catania48290382009-07-10 13:53:06 -07001503
nikoa64c8c72009-07-20 15:07:26 -07001504void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania48290382009-07-10 13:53:06 -07001505 Mutex::Autolock lock(mLock);
1506 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1507 mMetadataUpdated.add(metadata_type);
1508 }
1509}
1510
Hassan Shojaniacefac142017-02-06 21:02:02 -08001511// Modular DRM
1512status_t MediaPlayerService::Client::prepareDrm(const uint8_t uuid[16],
1513 const Vector<uint8_t>& drmSessionId)
1514{
1515 ALOGV("[%d] prepareDrm", mConnId);
1516 sp<MediaPlayerBase> p = getPlayer();
1517 if (p == 0) return UNKNOWN_ERROR;
1518
1519 status_t ret = p->prepareDrm(uuid, drmSessionId);
1520 ALOGV("prepareDrm ret: %d", ret);
1521
1522 return ret;
1523}
1524
1525status_t MediaPlayerService::Client::releaseDrm()
1526{
1527 ALOGV("[%d] releaseDrm", mConnId);
1528 sp<MediaPlayerBase> p = getPlayer();
1529 if (p == 0) return UNKNOWN_ERROR;
1530
1531 status_t ret = p->releaseDrm();
1532 ALOGV("releaseDrm ret: %d", ret);
1533
1534 return ret;
1535}
1536
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001537#if CALLBACK_ANTAGONIZER
1538const int Antagonizer::interval = 10000; // 10 msecs
1539
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001540Antagonizer::Antagonizer(const sp<MediaPlayerBase::Listener> &listener) :
1541 mExit(false), mActive(false), mListener(listener)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001542{
1543 createThread(callbackThread, this);
1544}
1545
1546void Antagonizer::kill()
1547{
1548 Mutex::Autolock _l(mLock);
1549 mActive = false;
1550 mExit = true;
1551 mCondition.wait(mLock);
1552}
1553
1554int Antagonizer::callbackThread(void* user)
1555{
Steve Blockb8a80522011-12-20 16:23:08 +00001556 ALOGD("Antagonizer started");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001557 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1558 while (!p->mExit) {
1559 if (p->mActive) {
Steve Block3856b092011-10-20 11:56:00 +01001560 ALOGV("send event");
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001561 p->mListener->notify(0, 0, 0, 0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001562 }
1563 usleep(interval);
1564 }
1565 Mutex::Autolock _l(p->mLock);
1566 p->mCondition.signal();
Steve Blockb8a80522011-12-20 16:23:08 +00001567 ALOGD("Antagonizer stopped");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001568 return 0;
1569}
1570#endif
1571
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001572#undef LOG_TAG
1573#define LOG_TAG "AudioSink"
Andy Hung1afd0982016-11-08 16:13:44 -08001574MediaPlayerService::AudioOutput::AudioOutput(audio_session_t sessionId, uid_t uid, int pid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001575 const audio_attributes_t* attr)
Andreas Huber20111aa2009-07-14 16:56:47 -07001576 : mCallback(NULL),
Eric Laurenta514bdb2010-06-21 09:27:30 -07001577 mCallbackCookie(NULL),
Marco Nelissen6b74d672012-02-28 16:07:44 -08001578 mCallbackData(NULL),
Andy Hungd1c74342015-07-07 16:54:23 -07001579 mStreamType(AUDIO_STREAM_MUSIC),
Andy Hungd1c74342015-07-07 16:54:23 -07001580 mLeftVolume(1.0),
1581 mRightVolume(1.0),
1582 mPlaybackRate(AUDIO_PLAYBACK_RATE_DEFAULT),
1583 mSampleRateHz(0),
1584 mMsecsPerFrame(0),
1585 mFrameSize(0),
Eric Laurent1948eb32012-04-13 16:50:19 -07001586 mSessionId(sessionId),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001587 mUid(uid),
Marco Nelissend457c972014-02-11 08:47:07 -08001588 mPid(pid),
Andy Hungd1c74342015-07-07 16:54:23 -07001589 mSendLevel(0.0),
1590 mAuxEffectId(0),
Andy Hung4ef88d72017-02-21 19:47:53 -08001591 mFlags(AUDIO_OUTPUT_FLAG_NONE),
1592 mVolumeHandler(new VolumeHandler())
Andy Hungd1c74342015-07-07 16:54:23 -07001593{
Steve Block3856b092011-10-20 11:56:00 +01001594 ALOGV("AudioOutput(%d)", sessionId);
Eric Laurent43562692015-07-15 16:49:07 -07001595 if (attr != NULL) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001596 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1597 if (mAttributes != NULL) {
1598 memcpy(mAttributes, attr, sizeof(audio_attributes_t));
1599 mStreamType = audio_attributes_to_stream_type(attr);
1600 }
1601 } else {
1602 mAttributes = NULL;
Eric Laurent43562692015-07-15 16:49:07 -07001603 }
1604
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001605 setMinBufferCount();
1606}
1607
1608MediaPlayerService::AudioOutput::~AudioOutput()
1609{
1610 close();
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001611 free(mAttributes);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001612 delete mCallbackData;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001613}
1614
Andy Hungd1c74342015-07-07 16:54:23 -07001615//static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001616void MediaPlayerService::AudioOutput::setMinBufferCount()
1617{
1618 char value[PROPERTY_VALUE_MAX];
1619 if (property_get("ro.kernel.qemu", value, 0)) {
1620 mIsOnEmulator = true;
1621 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1622 }
1623}
1624
Andy Hungd1c74342015-07-07 16:54:23 -07001625// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001626bool MediaPlayerService::AudioOutput::isOnEmulator()
1627{
Andy Hungd1c74342015-07-07 16:54:23 -07001628 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001629 return mIsOnEmulator;
1630}
1631
Andy Hungd1c74342015-07-07 16:54:23 -07001632// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001633int MediaPlayerService::AudioOutput::getMinBufferCount()
1634{
Andy Hungd1c74342015-07-07 16:54:23 -07001635 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001636 return mMinBufferCount;
1637}
1638
1639ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1640{
Andy Hungd1c74342015-07-07 16:54:23 -07001641 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001642 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001643 return mTrack->frameCount() * mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001644}
1645
1646ssize_t MediaPlayerService::AudioOutput::frameCount() const
1647{
Andy Hungd1c74342015-07-07 16:54:23 -07001648 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001649 if (mTrack == 0) return NO_INIT;
1650 return mTrack->frameCount();
1651}
1652
1653ssize_t MediaPlayerService::AudioOutput::channelCount() const
1654{
Andy Hungd1c74342015-07-07 16:54:23 -07001655 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001656 if (mTrack == 0) return NO_INIT;
1657 return mTrack->channelCount();
1658}
1659
1660ssize_t MediaPlayerService::AudioOutput::frameSize() const
1661{
Andy Hungd1c74342015-07-07 16:54:23 -07001662 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001663 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001664 return mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001665}
1666
1667uint32_t MediaPlayerService::AudioOutput::latency () const
1668{
Andy Hungd1c74342015-07-07 16:54:23 -07001669 Mutex::Autolock lock(mLock);
Eric Laurentdb354e52012-03-05 17:27:11 -08001670 if (mTrack == 0) return 0;
1671 return mTrack->latency();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001672}
1673
1674float MediaPlayerService::AudioOutput::msecsPerFrame() const
1675{
Andy Hungd1c74342015-07-07 16:54:23 -07001676 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001677 return mMsecsPerFrame;
1678}
1679
Marco Nelissen4110c102012-03-29 09:31:28 -07001680status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position) const
Eric Laurent342e9cf2010-01-19 17:37:09 -08001681{
Andy Hungd1c74342015-07-07 16:54:23 -07001682 Mutex::Autolock lock(mLock);
Eric Laurent342e9cf2010-01-19 17:37:09 -08001683 if (mTrack == 0) return NO_INIT;
1684 return mTrack->getPosition(position);
1685}
1686
Lajos Molnar06ad1522014-08-28 07:27:44 -07001687status_t MediaPlayerService::AudioOutput::getTimestamp(AudioTimestamp &ts) const
1688{
Andy Hungd1c74342015-07-07 16:54:23 -07001689 Mutex::Autolock lock(mLock);
Lajos Molnar06ad1522014-08-28 07:27:44 -07001690 if (mTrack == 0) return NO_INIT;
1691 return mTrack->getTimestamp(ts);
1692}
1693
Wei Jiac4ac8172015-10-21 10:35:48 -07001694// TODO: Remove unnecessary calls to getPlayedOutDurationUs()
1695// as it acquires locks and may query the audio driver.
1696//
1697// Some calls could conceivably retrieve extrapolated data instead of
1698// accessing getTimestamp() or getPosition() every time a data buffer with
1699// a media time is received.
1700//
1701// Calculate duration of played samples if played at normal rate (i.e., 1.0).
1702int64_t MediaPlayerService::AudioOutput::getPlayedOutDurationUs(int64_t nowUs) const
1703{
1704 Mutex::Autolock lock(mLock);
1705 if (mTrack == 0 || mSampleRateHz == 0) {
Wei Jia213f4902015-10-22 08:55:25 -07001706 return 0;
Wei Jiac4ac8172015-10-21 10:35:48 -07001707 }
1708
1709 uint32_t numFramesPlayed;
Andy Hung5d313802016-10-10 15:09:39 -07001710 int64_t numFramesPlayedAtUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001711 AudioTimestamp ts;
Wei Jiac4ac8172015-10-21 10:35:48 -07001712
1713 status_t res = mTrack->getTimestamp(ts);
1714 if (res == OK) { // case 1: mixing audio tracks and offloaded tracks.
1715 numFramesPlayed = ts.mPosition;
Andy Hung5d313802016-10-10 15:09:39 -07001716 numFramesPlayedAtUs = ts.mTime.tv_sec * 1000000LL + ts.mTime.tv_nsec / 1000;
1717 //ALOGD("getTimestamp: OK %d %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001718 } else if (res == WOULD_BLOCK) { // case 2: transitory state on start of a new track
1719 numFramesPlayed = 0;
Andy Hung5d313802016-10-10 15:09:39 -07001720 numFramesPlayedAtUs = nowUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001721 //ALOGD("getTimestamp: WOULD_BLOCK %d %lld",
Andy Hung5d313802016-10-10 15:09:39 -07001722 // numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001723 } else { // case 3: transitory at new track or audio fast tracks.
1724 res = mTrack->getPosition(&numFramesPlayed);
1725 CHECK_EQ(res, (status_t)OK);
Andy Hung5d313802016-10-10 15:09:39 -07001726 numFramesPlayedAtUs = nowUs;
1727 numFramesPlayedAtUs += 1000LL * mTrack->latency() / 2; /* XXX */
1728 //ALOGD("getPosition: %u %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001729 }
1730
1731 // CHECK_EQ(numFramesPlayed & (1 << 31), 0); // can't be negative until 12.4 hrs, test
1732 // TODO: remove the (int32_t) casting below as it may overflow at 12.4 hours.
1733 int64_t durationUs = (int64_t)((int32_t)numFramesPlayed * 1000000LL / mSampleRateHz)
Andy Hung5d313802016-10-10 15:09:39 -07001734 + nowUs - numFramesPlayedAtUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001735 if (durationUs < 0) {
1736 // Occurs when numFramesPlayed position is very small and the following:
1737 // (1) In case 1, the time nowUs is computed before getTimestamp() is called and
Andy Hung5d313802016-10-10 15:09:39 -07001738 // numFramesPlayedAtUs is greater than nowUs by time more than numFramesPlayed.
Wei Jiac4ac8172015-10-21 10:35:48 -07001739 // (2) In case 3, using getPosition and adding mAudioSink->latency() to
Andy Hung5d313802016-10-10 15:09:39 -07001740 // numFramesPlayedAtUs, by a time amount greater than numFramesPlayed.
Wei Jiac4ac8172015-10-21 10:35:48 -07001741 //
1742 // Both of these are transitory conditions.
1743 ALOGV("getPlayedOutDurationUs: negative duration %lld set to zero", (long long)durationUs);
1744 durationUs = 0;
1745 }
1746 ALOGV("getPlayedOutDurationUs(%lld) nowUs(%lld) frames(%u) framesAt(%lld)",
Andy Hung5d313802016-10-10 15:09:39 -07001747 (long long)durationUs, (long long)nowUs,
1748 numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001749 return durationUs;
1750}
1751
Marco Nelissen4110c102012-03-29 09:31:28 -07001752status_t MediaPlayerService::AudioOutput::getFramesWritten(uint32_t *frameswritten) const
1753{
Andy Hungd1c74342015-07-07 16:54:23 -07001754 Mutex::Autolock lock(mLock);
Marco Nelissen4110c102012-03-29 09:31:28 -07001755 if (mTrack == 0) return NO_INIT;
Andy Hung2f6e73d2016-04-08 12:12:58 -07001756 ExtendedTimestamp ets;
1757 status_t status = mTrack->getTimestamp(&ets);
1758 if (status == OK || status == WOULD_BLOCK) {
1759 *frameswritten = (uint32_t)ets.mPosition[ExtendedTimestamp::LOCATION_CLIENT];
1760 }
1761 return status;
Marco Nelissen4110c102012-03-29 09:31:28 -07001762}
1763
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001764status_t MediaPlayerService::AudioOutput::setParameters(const String8& keyValuePairs)
1765{
Andy Hungd1c74342015-07-07 16:54:23 -07001766 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001767 if (mTrack == 0) return NO_INIT;
1768 return mTrack->setParameters(keyValuePairs);
1769}
1770
1771String8 MediaPlayerService::AudioOutput::getParameters(const String8& keys)
1772{
Andy Hungd1c74342015-07-07 16:54:23 -07001773 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001774 if (mTrack == 0) return String8::empty();
1775 return mTrack->getParameters(keys);
1776}
1777
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001778void MediaPlayerService::AudioOutput::setAudioAttributes(const audio_attributes_t * attributes) {
Andy Hungd1c74342015-07-07 16:54:23 -07001779 Mutex::Autolock lock(mLock);
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001780 if (attributes == NULL) {
1781 free(mAttributes);
1782 mAttributes = NULL;
1783 } else {
1784 if (mAttributes == NULL) {
1785 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1786 }
1787 memcpy(mAttributes, attributes, sizeof(audio_attributes_t));
Eric Laurent43562692015-07-15 16:49:07 -07001788 mStreamType = audio_attributes_to_stream_type(attributes);
1789 }
1790}
1791
1792void MediaPlayerService::AudioOutput::setAudioStreamType(audio_stream_type_t streamType)
1793{
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001794 Mutex::Autolock lock(mLock);
Eric Laurent43562692015-07-15 16:49:07 -07001795 // do not allow direct stream type modification if attributes have been set
1796 if (mAttributes == NULL) {
1797 mStreamType = streamType;
1798 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001799}
1800
Andy Hungd1c74342015-07-07 16:54:23 -07001801void MediaPlayerService::AudioOutput::deleteRecycledTrack_l()
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001802{
Andy Hungd1c74342015-07-07 16:54:23 -07001803 ALOGV("deleteRecycledTrack_l");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001804 if (mRecycledTrack != 0) {
1805
1806 if (mCallbackData != NULL) {
1807 mCallbackData->setOutput(NULL);
1808 mCallbackData->endTrackSwitch();
1809 }
1810
1811 if ((mRecycledTrack->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) {
Andy Hunge13f8a62016-03-30 14:20:42 -07001812 int32_t msec = 0;
1813 if (!mRecycledTrack->stopped()) { // check if active
1814 (void)mRecycledTrack->pendingDuration(&msec);
1815 }
1816 mRecycledTrack->stop(); // ensure full data drain
1817 ALOGD("deleting recycled track, waiting for data drain (%d msec)", msec);
1818 if (msec > 0) {
1819 static const int32_t WAIT_LIMIT_MS = 3000;
1820 if (msec > WAIT_LIMIT_MS) {
1821 msec = WAIT_LIMIT_MS;
1822 }
1823 usleep(msec * 1000LL);
1824 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001825 }
1826 // An offloaded track isn't flushed because the STREAM_END is reported
1827 // slightly prematurely to allow time for the gapless track switch
1828 // but this means that if we decide not to recycle the track there
1829 // could be a small amount of residual data still playing. We leave
1830 // AudioFlinger to drain the track.
1831
1832 mRecycledTrack.clear();
Andy Hungd1c74342015-07-07 16:54:23 -07001833 close_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001834 delete mCallbackData;
1835 mCallbackData = NULL;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001836 }
1837}
1838
Andy Hungd1c74342015-07-07 16:54:23 -07001839void MediaPlayerService::AudioOutput::close_l()
1840{
1841 mTrack.clear();
1842}
1843
Andreas Huber20111aa2009-07-14 16:56:47 -07001844status_t MediaPlayerService::AudioOutput::open(
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001845 uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
1846 audio_format_t format, int bufferCount,
Eric Laurent1948eb32012-04-13 16:50:19 -07001847 AudioCallback cb, void *cookie,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001848 audio_output_flags_t flags,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001849 const audio_offload_info_t *offloadInfo,
Andy Hung179652e2015-05-31 22:49:46 -07001850 bool doNotReconnect,
1851 uint32_t suggestedFrameCount)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001852{
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001853 ALOGV("open(%u, %d, 0x%x, 0x%x, %d, %d 0x%x)", sampleRate, channelCount, channelMask,
1854 format, bufferCount, mSessionId, flags);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001855
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001856 // offloading is only supported in callback mode for now.
1857 // offloadInfo must be present if offload flag is set
1858 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) &&
1859 ((cb == NULL) || (offloadInfo == NULL))) {
1860 return BAD_VALUE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001861 }
1862
Andy Hung179652e2015-05-31 22:49:46 -07001863 // compute frame count for the AudioTrack internal buffer
1864 size_t frameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001865 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1866 frameCount = 0; // AudioTrack will get frame count from AudioFlinger
1867 } else {
Andy Hung179652e2015-05-31 22:49:46 -07001868 // try to estimate the buffer processing fetch size from AudioFlinger.
1869 // framesPerBuffer is approximate and generally correct, except when it's not :-).
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001870 uint32_t afSampleRate;
1871 size_t afFrameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001872 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1873 return NO_INIT;
1874 }
1875 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1876 return NO_INIT;
1877 }
Andy Hung179652e2015-05-31 22:49:46 -07001878 const size_t framesPerBuffer =
1879 (unsigned long long)sampleRate * afFrameCount / afSampleRate;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001880
Andy Hung179652e2015-05-31 22:49:46 -07001881 if (bufferCount == 0) {
1882 // use suggestedFrameCount
1883 bufferCount = (suggestedFrameCount + framesPerBuffer - 1) / framesPerBuffer;
1884 }
1885 // Check argument bufferCount against the mininum buffer count
1886 if (bufferCount != 0 && bufferCount < mMinBufferCount) {
1887 ALOGV("bufferCount (%d) increased to %d", bufferCount, mMinBufferCount);
1888 bufferCount = mMinBufferCount;
1889 }
1890 // if frameCount is 0, then AudioTrack will get frame count from AudioFlinger
1891 // which will be the minimum size permitted.
1892 frameCount = bufferCount * framesPerBuffer;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001893 }
Andreas Huber20111aa2009-07-14 16:56:47 -07001894
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001895 if (channelMask == CHANNEL_MASK_USE_CHANNEL_ORDER) {
Glenn Kastenab334fd2012-03-14 12:56:06 -07001896 channelMask = audio_channel_out_mask_from_count(channelCount);
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001897 if (0 == channelMask) {
1898 ALOGE("open() error, can\'t derive mask for %d audio channels", channelCount);
1899 return NO_INIT;
1900 }
1901 }
Eric Laurent1948eb32012-04-13 16:50:19 -07001902
Andy Hungd1c74342015-07-07 16:54:23 -07001903 Mutex::Autolock lock(mLock);
Andy Hung179652e2015-05-31 22:49:46 -07001904 mCallback = cb;
1905 mCallbackCookie = cookie;
1906
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001907 // Check whether we can recycle the track
1908 bool reuse = false;
1909 bool bothOffloaded = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001910
Glenn Kasten2799d742013-05-30 14:33:29 -07001911 if (mRecycledTrack != 0) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001912 // check whether we are switching between two offloaded tracks
1913 bothOffloaded = (flags & mRecycledTrack->getFlags()
1914 & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0;
Marco Nelissen67295b52012-06-11 14:52:53 -07001915
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001916 // check if the existing track can be reused as-is, or if a new track needs to be created.
1917 reuse = true;
1918
Marco Nelissen67295b52012-06-11 14:52:53 -07001919 if ((mCallbackData == NULL && mCallback != NULL) ||
1920 (mCallbackData != NULL && mCallback == NULL)) {
1921 // recycled track uses callbacks but the caller wants to use writes, or vice versa
1922 ALOGV("can't chain callback and write");
1923 reuse = false;
1924 } else if ((mRecycledTrack->getSampleRate() != sampleRate) ||
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001925 (mRecycledTrack->channelCount() != (uint32_t)channelCount) ) {
1926 ALOGV("samplerate, channelcount differ: %u/%u Hz, %u/%d ch",
Marco Nelissen67295b52012-06-11 14:52:53 -07001927 mRecycledTrack->getSampleRate(), sampleRate,
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001928 mRecycledTrack->channelCount(), channelCount);
Marco Nelissen67295b52012-06-11 14:52:53 -07001929 reuse = false;
1930 } else if (flags != mFlags) {
1931 ALOGV("output flags differ %08x/%08x", flags, mFlags);
1932 reuse = false;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001933 } else if (mRecycledTrack->format() != format) {
1934 reuse = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001935 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001936 } else {
1937 ALOGV("no track available to recycle");
1938 }
1939
1940 ALOGV_IF(bothOffloaded, "both tracks offloaded");
1941
1942 // If we can't recycle and both tracks are offloaded
1943 // we must close the previous output before opening a new one
1944 if (bothOffloaded && !reuse) {
1945 ALOGV("both offloaded and not recycling");
Andy Hungd1c74342015-07-07 16:54:23 -07001946 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001947 }
1948
1949 sp<AudioTrack> t;
1950 CallbackData *newcbd = NULL;
1951
1952 // We don't attempt to create a new track if we are recycling an
1953 // offloaded track. But, if we are recycling a non-offloaded or we
1954 // are switching where one is offloaded and one isn't then we create
1955 // the new track in advance so that we can read additional stream info
1956
1957 if (!(reuse && bothOffloaded)) {
1958 ALOGV("creating new AudioTrack");
1959
1960 if (mCallback != NULL) {
1961 newcbd = new CallbackData(this);
1962 t = new AudioTrack(
1963 mStreamType,
1964 sampleRate,
1965 format,
1966 channelMask,
1967 frameCount,
1968 flags,
1969 CallbackWrapper,
1970 newcbd,
1971 0, // notification frames
1972 mSessionId,
1973 AudioTrack::TRANSFER_CALLBACK,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001974 offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -08001975 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001976 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001977 mAttributes,
1978 doNotReconnect);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001979 } else {
Andy Hungff874dc2016-04-11 16:49:09 -07001980 // TODO: Due to buffer memory concerns, we use a max target playback speed
1981 // based on mPlaybackRate at the time of open (instead of kMaxRequiredSpeed),
1982 // also clamping the target speed to 1.0 <= targetSpeed <= kMaxRequiredSpeed.
1983 const float targetSpeed =
1984 std::min(std::max(mPlaybackRate.mSpeed, 1.0f), kMaxRequiredSpeed);
1985 ALOGW_IF(targetSpeed != mPlaybackRate.mSpeed,
1986 "track target speed:%f clamped from playback speed:%f",
1987 targetSpeed, mPlaybackRate.mSpeed);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001988 t = new AudioTrack(
1989 mStreamType,
1990 sampleRate,
1991 format,
1992 channelMask,
1993 frameCount,
1994 flags,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001995 NULL, // callback
1996 NULL, // user data
1997 0, // notification frames
1998 mSessionId,
1999 AudioTrack::TRANSFER_DEFAULT,
2000 NULL, // offload info
Marco Nelissend457c972014-02-11 08:47:07 -08002001 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07002002 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07002003 mAttributes,
Andy Hungff874dc2016-04-11 16:49:09 -07002004 doNotReconnect,
2005 targetSpeed);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002006 }
2007
2008 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
2009 ALOGE("Unable to create audio track");
2010 delete newcbd;
Glenn Kasten3e98ecd2015-05-18 13:13:24 -07002011 // t goes out of scope, so reference count drops to zero
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002012 return NO_INIT;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07002013 } else {
2014 // successful AudioTrack initialization implies a legacy stream type was generated
2015 // from the audio attributes
2016 mStreamType = t->streamType();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002017 }
2018 }
2019
2020 if (reuse) {
2021 CHECK(mRecycledTrack != NULL);
2022
2023 if (!bothOffloaded) {
2024 if (mRecycledTrack->frameCount() != t->frameCount()) {
Andy Hung833b4752016-04-04 17:15:48 -07002025 ALOGV("framecount differs: %zu/%zu frames",
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002026 mRecycledTrack->frameCount(), t->frameCount());
2027 reuse = false;
2028 }
2029 }
2030
Marco Nelissen67295b52012-06-11 14:52:53 -07002031 if (reuse) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002032 ALOGV("chaining to next output and recycling track");
Andy Hungd1c74342015-07-07 16:54:23 -07002033 close_l();
Marco Nelissen67295b52012-06-11 14:52:53 -07002034 mTrack = mRecycledTrack;
Glenn Kasten2799d742013-05-30 14:33:29 -07002035 mRecycledTrack.clear();
Marco Nelissen67295b52012-06-11 14:52:53 -07002036 if (mCallbackData != NULL) {
2037 mCallbackData->setOutput(this);
2038 }
Marco Nelissen67295b52012-06-11 14:52:53 -07002039 delete newcbd;
Wei Jiae0bbac92016-07-18 16:04:53 -07002040 return updateTrack();
Marco Nelissen67295b52012-06-11 14:52:53 -07002041 }
Marco Nelissen67295b52012-06-11 14:52:53 -07002042 }
2043
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002044 // we're not going to reuse the track, unblock and flush it
2045 // this was done earlier if both tracks are offloaded
2046 if (!bothOffloaded) {
Andy Hungd1c74342015-07-07 16:54:23 -07002047 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002048 }
2049
2050 CHECK((t != NULL) && ((mCallback == NULL) || (newcbd != NULL)));
2051
Marco Nelissen67295b52012-06-11 14:52:53 -07002052 mCallbackData = newcbd;
Steve Block3856b092011-10-20 11:56:00 +01002053 ALOGV("setVolume");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002054 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07002055
Andy Hung39399b62017-04-21 15:07:45 -07002056 // Restore VolumeShapers for the MediaPlayer in case the track was recreated
2057 // due to an output sink error (e.g. offload to non-offload switch).
2058 mVolumeHandler->forall([&t](const VolumeShaper &shaper) -> VolumeShaper::Status {
2059 sp<VolumeShaper::Operation> operationToEnd =
2060 new VolumeShaper::Operation(shaper.mOperation);
2061 // TODO: Ideally we would restore to the exact xOffset position
2062 // as returned by getVolumeShaperState(), but we don't have that
2063 // information when restoring at the client unless we periodically poll
2064 // the server or create shared memory state.
2065 //
2066 // For now, we simply advance to the end of the VolumeShaper effect
2067 // if it has been started.
2068 if (shaper.isStarted()) {
Andy Hungf3702642017-05-05 17:33:32 -07002069 operationToEnd->setNormalizedTime(1.f);
Andy Hung39399b62017-04-21 15:07:45 -07002070 }
2071 return t->applyVolumeShaper(shaper.mConfiguration, operationToEnd);
Andy Hung4ef88d72017-02-21 19:47:53 -08002072 });
Andy Hung4ef88d72017-02-21 19:47:53 -08002073
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002074 mSampleRateHz = sampleRate;
Preetam Singh Ranawat2e17eef2015-08-12 12:11:46 -07002075 mFlags = flags;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002076 mMsecsPerFrame = 1E3f / (mPlaybackRate.mSpeed * sampleRate);
Andy Hungd1c74342015-07-07 16:54:23 -07002077 mFrameSize = t->frameSize();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002078 mTrack = t;
Eric Laurent2beeb502010-07-16 07:43:46 -07002079
Wei Jiae0bbac92016-07-18 16:04:53 -07002080 return updateTrack();
2081}
2082
2083status_t MediaPlayerService::AudioOutput::updateTrack() {
2084 if (mTrack == NULL) {
2085 return NO_ERROR;
2086 }
2087
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002088 status_t res = NO_ERROR;
Wei Jia0162d002015-06-09 11:59:33 -07002089 // Note some output devices may give us a direct track even though we don't specify it.
2090 // Example: Line application b/17459982.
Wei Jiae0bbac92016-07-18 16:04:53 -07002091 if ((mTrack->getFlags()
2092 & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) {
2093 res = mTrack->setPlaybackRate(mPlaybackRate);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002094 if (res == NO_ERROR) {
Wei Jiae0bbac92016-07-18 16:04:53 -07002095 mTrack->setAuxEffectSendLevel(mSendLevel);
2096 res = mTrack->attachAuxEffect(mAuxEffectId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002097 }
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002098 }
Wei Jiae0bbac92016-07-18 16:04:53 -07002099 ALOGV("updateTrack() DONE status %d", res);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002100 return res;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002101}
2102
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002103status_t MediaPlayerService::AudioOutput::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002104{
Steve Block3856b092011-10-20 11:56:00 +01002105 ALOGV("start");
Andy Hungd1c74342015-07-07 16:54:23 -07002106 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08002107 if (mCallbackData != NULL) {
2108 mCallbackData->endTrackSwitch();
2109 }
Glenn Kasten2799d742013-05-30 14:33:29 -07002110 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002111 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07002112 mTrack->setAuxEffectSendLevel(mSendLevel);
Andy Hung39399b62017-04-21 15:07:45 -07002113 status_t status = mTrack->start();
2114 if (status == NO_ERROR) {
2115 mVolumeHandler->setStarted();
2116 }
2117 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002118 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002119 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002120}
2121
Marco Nelissen6b74d672012-02-28 16:07:44 -08002122void MediaPlayerService::AudioOutput::setNextOutput(const sp<AudioOutput>& nextOutput) {
Andy Hungd1c74342015-07-07 16:54:23 -07002123 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08002124 mNextOutput = nextOutput;
2125}
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08002126
Marco Nelissen6b74d672012-02-28 16:07:44 -08002127void MediaPlayerService::AudioOutput::switchToNextOutput() {
2128 ALOGV("switchToNextOutput");
Andy Hungd1c74342015-07-07 16:54:23 -07002129
2130 // Try to acquire the callback lock before moving track (without incurring deadlock).
2131 const unsigned kMaxSwitchTries = 100;
2132 Mutex::Autolock lock(mLock);
2133 for (unsigned tries = 0;;) {
2134 if (mTrack == 0) {
2135 return;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002136 }
Andy Hungd1c74342015-07-07 16:54:23 -07002137 if (mNextOutput != NULL && mNextOutput != this) {
2138 if (mCallbackData != NULL) {
2139 // two alternative approaches
2140#if 1
2141 CallbackData *callbackData = mCallbackData;
2142 mLock.unlock();
2143 // proper acquisition sequence
2144 callbackData->lock();
2145 mLock.lock();
2146 // Caution: it is unlikely that someone deleted our callback or changed our target
2147 if (callbackData != mCallbackData || mNextOutput == NULL || mNextOutput == this) {
2148 // fatal if we are starved out.
2149 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2150 "switchToNextOutput() cannot obtain correct lock sequence");
2151 callbackData->unlock();
2152 continue;
2153 }
2154 callbackData->mSwitching = true; // begin track switch
Wei Jiaadee56a2016-08-05 15:40:34 -07002155 callbackData->setOutput(NULL);
Andy Hungd1c74342015-07-07 16:54:23 -07002156#else
2157 // tryBeginTrackSwitch() returns false if the callback has the lock.
2158 if (!mCallbackData->tryBeginTrackSwitch()) {
2159 // fatal if we are starved out.
2160 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2161 "switchToNextOutput() cannot obtain callback lock");
2162 mLock.unlock();
2163 usleep(5 * 1000 /* usec */); // allow callback to use AudioOutput
2164 mLock.lock();
2165 continue;
2166 }
2167#endif
2168 }
2169
2170 Mutex::Autolock nextLock(mNextOutput->mLock);
2171
2172 // If the next output track is not NULL, then it has been
2173 // opened already for playback.
2174 // This is possible even without the next player being started,
2175 // for example, the next player could be prepared and seeked.
2176 //
2177 // Presuming it isn't advisable to force the track over.
2178 if (mNextOutput->mTrack == NULL) {
2179 ALOGD("Recycling track for gapless playback");
2180 delete mNextOutput->mCallbackData;
2181 mNextOutput->mCallbackData = mCallbackData;
2182 mNextOutput->mRecycledTrack = mTrack;
2183 mNextOutput->mSampleRateHz = mSampleRateHz;
2184 mNextOutput->mMsecsPerFrame = mMsecsPerFrame;
Andy Hungd1c74342015-07-07 16:54:23 -07002185 mNextOutput->mFlags = mFlags;
2186 mNextOutput->mFrameSize = mFrameSize;
2187 close_l();
2188 mCallbackData = NULL; // destruction handled by mNextOutput
2189 } else {
2190 ALOGW("Ignoring gapless playback because next player has already started");
2191 // remove track in case resource needed for future players.
2192 if (mCallbackData != NULL) {
2193 mCallbackData->endTrackSwitch(); // release lock for callbacks before close.
2194 }
2195 close_l();
2196 }
2197 }
2198 break;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002199 }
2200}
2201
Wei Jia7d3f4df2015-03-03 15:28:00 -08002202ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002203{
Andy Hungd1c74342015-07-07 16:54:23 -07002204 Mutex::Autolock lock(mLock);
Glenn Kastenadad3d72014-02-21 14:51:43 -08002205 LOG_ALWAYS_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
Andreas Huber20111aa2009-07-14 16:56:47 -07002206
Steve Block3856b092011-10-20 11:56:00 +01002207 //ALOGV("write(%p, %u)", buffer, size);
Glenn Kasten2799d742013-05-30 14:33:29 -07002208 if (mTrack != 0) {
Andy Hung2f6e73d2016-04-08 12:12:58 -07002209 return mTrack->write(buffer, size, blocking);
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07002210 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002211 return NO_INIT;
2212}
2213
2214void MediaPlayerService::AudioOutput::stop()
2215{
Steve Block3856b092011-10-20 11:56:00 +01002216 ALOGV("stop");
Andy Hungd1c74342015-07-07 16:54:23 -07002217 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002218 if (mTrack != 0) mTrack->stop();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002219}
2220
2221void MediaPlayerService::AudioOutput::flush()
2222{
Steve Block3856b092011-10-20 11:56:00 +01002223 ALOGV("flush");
Andy Hungd1c74342015-07-07 16:54:23 -07002224 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002225 if (mTrack != 0) mTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002226}
2227
2228void MediaPlayerService::AudioOutput::pause()
2229{
Steve Block3856b092011-10-20 11:56:00 +01002230 ALOGV("pause");
Andy Hungd1c74342015-07-07 16:54:23 -07002231 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002232 if (mTrack != 0) mTrack->pause();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002233}
2234
2235void MediaPlayerService::AudioOutput::close()
2236{
Steve Block3856b092011-10-20 11:56:00 +01002237 ALOGV("close");
Erik Wolsheimer7845a1f2015-10-30 12:07:52 -07002238 sp<AudioTrack> track;
2239 {
2240 Mutex::Autolock lock(mLock);
2241 track = mTrack;
2242 close_l(); // clears mTrack
2243 }
2244 // destruction of the track occurs outside of mutex.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002245}
2246
2247void MediaPlayerService::AudioOutput::setVolume(float left, float right)
2248{
Steve Block3856b092011-10-20 11:56:00 +01002249 ALOGV("setVolume(%f, %f)", left, right);
Andy Hungd1c74342015-07-07 16:54:23 -07002250 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002251 mLeftVolume = left;
2252 mRightVolume = right;
Glenn Kasten2799d742013-05-30 14:33:29 -07002253 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002254 mTrack->setVolume(left, right);
2255 }
2256}
2257
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002258status_t MediaPlayerService::AudioOutput::setPlaybackRate(const AudioPlaybackRate &rate)
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002259{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002260 ALOGV("setPlaybackRate(%f %f %d %d)",
2261 rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Andy Hungd1c74342015-07-07 16:54:23 -07002262 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002263 if (mTrack == 0) {
2264 // remember rate so that we can set it when the track is opened
2265 mPlaybackRate = rate;
2266 return OK;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002267 }
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002268 status_t res = mTrack->setPlaybackRate(rate);
2269 if (res != NO_ERROR) {
2270 return res;
2271 }
2272 // rate.mSpeed is always greater than 0 if setPlaybackRate succeeded
2273 CHECK_GT(rate.mSpeed, 0.f);
2274 mPlaybackRate = rate;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002275 if (mSampleRateHz != 0) {
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002276 mMsecsPerFrame = 1E3f / (rate.mSpeed * mSampleRateHz);
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002277 }
2278 return res;
2279}
2280
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002281status_t MediaPlayerService::AudioOutput::getPlaybackRate(AudioPlaybackRate *rate)
2282{
2283 ALOGV("setPlaybackRate");
Andy Hungd1c74342015-07-07 16:54:23 -07002284 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002285 if (mTrack == 0) {
2286 return NO_INIT;
2287 }
2288 *rate = mTrack->getPlaybackRate();
2289 return NO_ERROR;
2290}
2291
Eric Laurent2beeb502010-07-16 07:43:46 -07002292status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
2293{
Steve Block3856b092011-10-20 11:56:00 +01002294 ALOGV("setAuxEffectSendLevel(%f)", level);
Andy Hungd1c74342015-07-07 16:54:23 -07002295 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002296 mSendLevel = level;
Glenn Kasten2799d742013-05-30 14:33:29 -07002297 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002298 return mTrack->setAuxEffectSendLevel(level);
2299 }
2300 return NO_ERROR;
2301}
2302
2303status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
2304{
Steve Block3856b092011-10-20 11:56:00 +01002305 ALOGV("attachAuxEffect(%d)", effectId);
Andy Hungd1c74342015-07-07 16:54:23 -07002306 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002307 mAuxEffectId = effectId;
Glenn Kasten2799d742013-05-30 14:33:29 -07002308 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002309 return mTrack->attachAuxEffect(effectId);
2310 }
2311 return NO_ERROR;
2312}
2313
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002314VolumeShaper::Status MediaPlayerService::AudioOutput::applyVolumeShaper(
2315 const sp<VolumeShaper::Configuration>& configuration,
2316 const sp<VolumeShaper::Operation>& operation)
2317{
2318 Mutex::Autolock lock(mLock);
2319 ALOGV("AudioOutput::applyVolumeShaper");
Andy Hung4ef88d72017-02-21 19:47:53 -08002320
Andy Hung4ef88d72017-02-21 19:47:53 -08002321 mVolumeHandler->setIdIfNecessary(configuration);
Andy Hung39399b62017-04-21 15:07:45 -07002322
2323 VolumeShaper::Status status;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002324 if (mTrack != 0) {
Andy Hung39399b62017-04-21 15:07:45 -07002325 status = mTrack->applyVolumeShaper(configuration, operation);
2326 if (status >= 0) {
2327 (void)mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hungf3702642017-05-05 17:33:32 -07002328 if (mTrack->isPlaying()) { // match local AudioTrack to properly restore.
2329 mVolumeHandler->setStarted();
2330 }
Andy Hung39399b62017-04-21 15:07:45 -07002331 }
Andy Hung4ef88d72017-02-21 19:47:53 -08002332 } else {
Andy Hungc01eddb2017-07-21 16:42:41 -07002333 // VolumeShapers are not affected when a track moves between players for
2334 // gapless playback (setNextMediaPlayer).
2335 // We forward VolumeShaper operations that do not change configuration
2336 // to the new player so that unducking may occur as expected.
2337 // Unducking is an idempotent operation, same if applied back-to-back.
2338 if (configuration->getType() == VolumeShaper::Configuration::TYPE_ID
2339 && mNextOutput != nullptr) {
2340 ALOGV("applyVolumeShaper: Attempting to forward missed operation: %s %s",
2341 configuration->toString().c_str(), operation->toString().c_str());
2342 Mutex::Autolock nextLock(mNextOutput->mLock);
2343
2344 // recycled track should be forwarded from this AudioSink by switchToNextOutput
2345 sp<AudioTrack> track = mNextOutput->mRecycledTrack;
2346 if (track != nullptr) {
2347 ALOGD("Forward VolumeShaper operation to recycled track %p", track.get());
2348 (void)track->applyVolumeShaper(configuration, operation);
2349 } else {
2350 // There is a small chance that the unduck occurs after the next
2351 // player has already started, but before it is registered to receive
2352 // the unduck command.
2353 track = mNextOutput->mTrack;
2354 if (track != nullptr) {
2355 ALOGD("Forward VolumeShaper operation to track %p", track.get());
2356 (void)track->applyVolumeShaper(configuration, operation);
2357 }
2358 }
2359 }
Andy Hung39399b62017-04-21 15:07:45 -07002360 status = mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002361 }
Andy Hung39399b62017-04-21 15:07:45 -07002362 return status;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002363}
2364
2365sp<VolumeShaper::State> MediaPlayerService::AudioOutput::getVolumeShaperState(int id)
2366{
2367 Mutex::Autolock lock(mLock);
2368 if (mTrack != 0) {
2369 return mTrack->getVolumeShaperState(id);
Andy Hung4ef88d72017-02-21 19:47:53 -08002370 } else {
2371 return mVolumeHandler->getVolumeShaperState(id);
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002372 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002373}
2374
Andreas Huber20111aa2009-07-14 16:56:47 -07002375// static
2376void MediaPlayerService::AudioOutput::CallbackWrapper(
Glenn Kastend217a8c2011-06-01 15:20:35 -07002377 int event, void *cookie, void *info) {
Steve Block3856b092011-10-20 11:56:00 +01002378 //ALOGV("callbackwrapper");
Marco Nelissen6b74d672012-02-28 16:07:44 -08002379 CallbackData *data = (CallbackData*)cookie;
Andy Hungd1c74342015-07-07 16:54:23 -07002380 // lock to ensure we aren't caught in the middle of a track switch.
Marco Nelissen6b74d672012-02-28 16:07:44 -08002381 data->lock();
2382 AudioOutput *me = data->getOutput();
Andreas Huber20111aa2009-07-14 16:56:47 -07002383 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002384 if (me == NULL) {
2385 // no output set, likely because the track was scheduled to be reused
2386 // by another player, but the format turned out to be incompatible.
2387 data->unlock();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002388 if (buffer != NULL) {
2389 buffer->size = 0;
2390 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08002391 return;
2392 }
Andreas Huber20111aa2009-07-14 16:56:47 -07002393
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002394 switch(event) {
2395 case AudioTrack::EVENT_MORE_DATA: {
2396 size_t actualSize = (*me->mCallback)(
2397 me, buffer->raw, buffer->size, me->mCallbackCookie,
2398 CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002399
Andy Hung719b46b2015-05-31 22:18:25 -07002400 // Log when no data is returned from the callback.
2401 // (1) We may have no data (especially with network streaming sources).
2402 // (2) We may have reached the EOS and the audio track is not stopped yet.
2403 // Note that AwesomePlayer/AudioPlayer will only return zero size when it reaches the EOS.
2404 // NuPlayerRenderer will return zero when it doesn't have data (it doesn't block to fill).
2405 //
2406 // This is a benign busy-wait, with the next data request generated 10 ms or more later;
2407 // nevertheless for power reasons, we don't want to see too many of these.
Andreas Huber2e8ffaf2010-02-18 16:45:13 -08002408
Andy Hung719b46b2015-05-31 22:18:25 -07002409 ALOGV_IF(actualSize == 0 && buffer->size > 0, "callbackwrapper: empty buffer returned");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002410
2411 buffer->size = actualSize;
2412 } break;
2413
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002414 case AudioTrack::EVENT_STREAM_END:
Andy Hung719b46b2015-05-31 22:18:25 -07002415 // currently only occurs for offloaded callbacks
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002416 ALOGV("callbackwrapper: deliver EVENT_STREAM_END");
2417 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2418 me->mCallbackCookie, CB_EVENT_STREAM_END);
2419 break;
2420
2421 case AudioTrack::EVENT_NEW_IAUDIOTRACK :
2422 ALOGV("callbackwrapper: deliver EVENT_TEAR_DOWN");
2423 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2424 me->mCallbackCookie, CB_EVENT_TEAR_DOWN);
2425 break;
2426
Glenn Kasten421743b2015-06-01 08:18:08 -07002427 case AudioTrack::EVENT_UNDERRUN:
Andy Hung719b46b2015-05-31 22:18:25 -07002428 // This occurs when there is no data available, typically
Glenn Kasten421743b2015-06-01 08:18:08 -07002429 // when there is a failure to supply data to the AudioTrack. It can also
2430 // occur in non-offloaded mode when the audio device comes out of standby.
2431 //
Andy Hung719b46b2015-05-31 22:18:25 -07002432 // If an AudioTrack underruns it outputs silence. Since this happens suddenly
2433 // it may sound like an audible pop or glitch.
2434 //
2435 // The underrun event is sent once per track underrun; the condition is reset
2436 // when more data is sent to the AudioTrack.
Eric Laurente93cc032016-05-05 10:15:10 -07002437 ALOGD("callbackwrapper: EVENT_UNDERRUN (discarded)");
Glenn Kasten421743b2015-06-01 08:18:08 -07002438 break;
2439
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002440 default:
2441 ALOGE("received unknown event type: %d inside CallbackWrapper !", event);
Andreas Huber51c1e0e2011-04-04 11:43:40 -07002442 }
2443
Marco Nelissen6b74d672012-02-28 16:07:44 -08002444 data->unlock();
Andreas Huber20111aa2009-07-14 16:56:47 -07002445}
2446
Glenn Kastend848eb42016-03-08 13:42:11 -08002447audio_session_t MediaPlayerService::AudioOutput::getSessionId() const
Eric Laurent8c563ed2010-10-07 18:23:03 -07002448{
Andy Hungd1c74342015-07-07 16:54:23 -07002449 Mutex::Autolock lock(mLock);
Eric Laurent8c563ed2010-10-07 18:23:03 -07002450 return mSessionId;
2451}
2452
Eric Laurent6f59db12013-07-26 17:16:50 -07002453uint32_t MediaPlayerService::AudioOutput::getSampleRate() const
2454{
Andy Hungd1c74342015-07-07 16:54:23 -07002455 Mutex::Autolock lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -07002456 if (mTrack == 0) return 0;
2457 return mTrack->getSampleRate();
2458}
2459
Andy Hungf2c87b32016-04-07 19:49:29 -07002460int64_t MediaPlayerService::AudioOutput::getBufferDurationInUs() const
2461{
2462 Mutex::Autolock lock(mLock);
2463 if (mTrack == 0) {
2464 return 0;
2465 }
2466 int64_t duration;
2467 if (mTrack->getBufferDurationInUs(&duration) != OK) {
2468 return 0;
2469 }
2470 return duration;
2471}
2472
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002473////////////////////////////////////////////////////////////////////////////////
2474
2475struct CallbackThread : public Thread {
2476 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
2477 MediaPlayerBase::AudioSink::AudioCallback cb,
2478 void *cookie);
2479
2480protected:
2481 virtual ~CallbackThread();
2482
2483 virtual bool threadLoop();
2484
2485private:
2486 wp<MediaPlayerBase::AudioSink> mSink;
2487 MediaPlayerBase::AudioSink::AudioCallback mCallback;
2488 void *mCookie;
2489 void *mBuffer;
2490 size_t mBufferSize;
2491
2492 CallbackThread(const CallbackThread &);
2493 CallbackThread &operator=(const CallbackThread &);
2494};
2495
2496CallbackThread::CallbackThread(
2497 const wp<MediaPlayerBase::AudioSink> &sink,
2498 MediaPlayerBase::AudioSink::AudioCallback cb,
2499 void *cookie)
2500 : mSink(sink),
2501 mCallback(cb),
2502 mCookie(cookie),
2503 mBuffer(NULL),
2504 mBufferSize(0) {
2505}
2506
2507CallbackThread::~CallbackThread() {
2508 if (mBuffer) {
2509 free(mBuffer);
2510 mBuffer = NULL;
2511 }
2512}
2513
2514bool CallbackThread::threadLoop() {
2515 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
2516 if (sink == NULL) {
2517 return false;
2518 }
2519
2520 if (mBuffer == NULL) {
2521 mBufferSize = sink->bufferSize();
2522 mBuffer = malloc(mBufferSize);
2523 }
2524
2525 size_t actualSize =
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002526 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie,
2527 MediaPlayerBase::AudioSink::CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002528
2529 if (actualSize > 0) {
2530 sink->write(mBuffer, actualSize);
Andy Hunga31335a2014-08-20 17:37:59 -07002531 // Could return false on sink->write() error or short count.
2532 // Not necessarily appropriate but would work for AudioCache behavior.
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002533 }
2534
2535 return true;
2536}
2537
2538////////////////////////////////////////////////////////////////////////////////
2539
Chong Zhange5b9b692017-05-11 11:44:56 -07002540void MediaPlayerService::addBatteryData(uint32_t params) {
2541 mBatteryTracker.addBatteryData(params);
2542}
2543
2544status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
2545 return mBatteryTracker.pullBatteryData(reply);
2546}
2547
2548MediaPlayerService::BatteryTracker::BatteryTracker() {
2549 mBatteryAudio.refCount = 0;
2550 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2551 mBatteryAudio.deviceOn[i] = 0;
2552 mBatteryAudio.lastTime[i] = 0;
2553 mBatteryAudio.totalTime[i] = 0;
2554 }
2555 // speaker is on by default
2556 mBatteryAudio.deviceOn[SPEAKER] = 1;
2557
2558 // reset battery stats
2559 // if the mediaserver has crashed, battery stats could be left
2560 // in bad state, reset the state upon service start.
2561 BatteryNotifier::getInstance().noteResetVideo();
2562}
2563
2564void MediaPlayerService::BatteryTracker::addBatteryData(uint32_t params)
Gloria Wang7cf180c2011-02-19 18:37:57 -08002565{
2566 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002567
2568 int32_t time = systemTime() / 1000000L;
2569
2570 // change audio output devices. This notification comes from AudioFlinger
2571 if ((params & kBatteryDataSpeakerOn)
2572 || (params & kBatteryDataOtherAudioDeviceOn)) {
2573
2574 int deviceOn[NUM_AUDIO_DEVICES];
2575 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2576 deviceOn[i] = 0;
2577 }
2578
2579 if ((params & kBatteryDataSpeakerOn)
2580 && (params & kBatteryDataOtherAudioDeviceOn)) {
2581 deviceOn[SPEAKER_AND_OTHER] = 1;
2582 } else if (params & kBatteryDataSpeakerOn) {
2583 deviceOn[SPEAKER] = 1;
2584 } else {
2585 deviceOn[OTHER_AUDIO_DEVICE] = 1;
2586 }
2587
2588 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2589 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
2590
2591 if (mBatteryAudio.refCount > 0) { // if playing audio
2592 if (!deviceOn[i]) {
2593 mBatteryAudio.lastTime[i] += time;
2594 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2595 mBatteryAudio.lastTime[i] = 0;
2596 } else {
2597 mBatteryAudio.lastTime[i] = 0 - time;
2598 }
2599 }
2600
2601 mBatteryAudio.deviceOn[i] = deviceOn[i];
2602 }
2603 }
2604 return;
2605 }
2606
Marco Nelissenb7848f12014-12-04 08:57:56 -08002607 // an audio stream is started
Gloria Wang9ee159b2011-02-24 14:51:45 -08002608 if (params & kBatteryDataAudioFlingerStart) {
2609 // record the start time only if currently no other audio
2610 // is being played
2611 if (mBatteryAudio.refCount == 0) {
2612 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2613 if (mBatteryAudio.deviceOn[i]) {
2614 mBatteryAudio.lastTime[i] -= time;
2615 }
2616 }
2617 }
2618
2619 mBatteryAudio.refCount ++;
2620 return;
2621
2622 } else if (params & kBatteryDataAudioFlingerStop) {
2623 if (mBatteryAudio.refCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002624 ALOGW("Battery track warning: refCount is <= 0");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002625 return;
2626 }
2627
2628 // record the stop time only if currently this is the only
2629 // audio being played
2630 if (mBatteryAudio.refCount == 1) {
2631 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2632 if (mBatteryAudio.deviceOn[i]) {
2633 mBatteryAudio.lastTime[i] += time;
2634 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2635 mBatteryAudio.lastTime[i] = 0;
2636 }
2637 }
2638 }
2639
2640 mBatteryAudio.refCount --;
2641 return;
2642 }
2643
Andy Hung1afd0982016-11-08 16:13:44 -08002644 uid_t uid = IPCThreadState::self()->getCallingUid();
Gloria Wang7cf180c2011-02-19 18:37:57 -08002645 if (uid == AID_MEDIA) {
2646 return;
2647 }
2648 int index = mBatteryData.indexOfKey(uid);
Gloria Wang7cf180c2011-02-19 18:37:57 -08002649
2650 if (index < 0) { // create a new entry for this UID
2651 BatteryUsageInfo info;
2652 info.audioTotalTime = 0;
2653 info.videoTotalTime = 0;
2654 info.audioLastTime = 0;
2655 info.videoLastTime = 0;
2656 info.refCount = 0;
2657
Gloria Wang9ee159b2011-02-24 14:51:45 -08002658 if (mBatteryData.add(uid, info) == NO_MEMORY) {
Steve Block29357bc2012-01-06 19:20:56 +00002659 ALOGE("Battery track error: no memory for new app");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002660 return;
2661 }
Gloria Wang7cf180c2011-02-19 18:37:57 -08002662 }
2663
2664 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
2665
2666 if (params & kBatteryDataCodecStarted) {
2667 if (params & kBatteryDataTrackAudio) {
2668 info.audioLastTime -= time;
2669 info.refCount ++;
2670 }
2671 if (params & kBatteryDataTrackVideo) {
2672 info.videoLastTime -= time;
2673 info.refCount ++;
2674 }
2675 } else {
2676 if (info.refCount == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002677 ALOGW("Battery track warning: refCount is already 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002678 return;
2679 } else if (info.refCount < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00002680 ALOGE("Battery track error: refCount < 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002681 mBatteryData.removeItem(uid);
2682 return;
2683 }
2684
2685 if (params & kBatteryDataTrackAudio) {
2686 info.audioLastTime += time;
2687 info.refCount --;
2688 }
2689 if (params & kBatteryDataTrackVideo) {
2690 info.videoLastTime += time;
2691 info.refCount --;
2692 }
2693
2694 // no stream is being played by this UID
2695 if (info.refCount == 0) {
2696 info.audioTotalTime += info.audioLastTime;
2697 info.audioLastTime = 0;
2698 info.videoTotalTime += info.videoLastTime;
2699 info.videoLastTime = 0;
2700 }
2701 }
2702}
2703
Chong Zhange5b9b692017-05-11 11:44:56 -07002704status_t MediaPlayerService::BatteryTracker::pullBatteryData(Parcel* reply) {
Gloria Wang7cf180c2011-02-19 18:37:57 -08002705 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002706
2707 // audio output devices usage
2708 int32_t time = systemTime() / 1000000L; //in ms
2709 int32_t totalTime;
2710
2711 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2712 totalTime = mBatteryAudio.totalTime[i];
2713
2714 if (mBatteryAudio.deviceOn[i]
2715 && (mBatteryAudio.lastTime[i] != 0)) {
2716 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
2717 totalTime += tmpTime;
2718 }
2719
2720 reply->writeInt32(totalTime);
2721 // reset the total time
2722 mBatteryAudio.totalTime[i] = 0;
2723 }
2724
2725 // codec usage
Gloria Wang7cf180c2011-02-19 18:37:57 -08002726 BatteryUsageInfo info;
2727 int size = mBatteryData.size();
2728
2729 reply->writeInt32(size);
2730 int i = 0;
2731
2732 while (i < size) {
2733 info = mBatteryData.valueAt(i);
2734
2735 reply->writeInt32(mBatteryData.keyAt(i)); //UID
2736 reply->writeInt32(info.audioTotalTime);
2737 reply->writeInt32(info.videoTotalTime);
2738
2739 info.audioTotalTime = 0;
2740 info.videoTotalTime = 0;
2741
2742 // remove the UID entry where no stream is being played
2743 if (info.refCount <= 0) {
2744 mBatteryData.removeItemsAt(i);
2745 size --;
2746 i --;
2747 }
2748 i++;
2749 }
2750 return NO_ERROR;
2751}
nikoa64c8c72009-07-20 15:07:26 -07002752} // namespace android