blob: 44ab5da45aaa682a5c1da0dee7b6ce05c3fa10a9 [file] [log] [blame]
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001/*
2**
3** Copyright 2008, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18// Proxy for media player implementations
19
20//#define LOG_NDEBUG 0
21#define LOG_TAG "MediaPlayerService"
22#include <utils/Log.h>
23
24#include <sys/types.h>
25#include <sys/stat.h>
Gloria Wang7cf180c2011-02-19 18:37:57 -080026#include <sys/time.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080027#include <dirent.h>
28#include <unistd.h>
29
30#include <string.h>
Mathias Agopian6f74b0c2009-06-03 17:32:49 -070031
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080032#include <cutils/atomic.h>
Nicolas Catania14d27472009-07-13 14:37:49 -070033#include <cutils/properties.h> // for property_get
Mathias Agopian6f74b0c2009-06-03 17:32:49 -070034
35#include <utils/misc.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080036
Mathias Agopian75624082009-05-19 19:08:10 -070037#include <binder/IPCThreadState.h>
38#include <binder/IServiceManager.h>
39#include <binder/MemoryHeapBase.h>
40#include <binder/MemoryBase.h>
Mathias Agopianb1e7cd12013-02-14 17:11:27 -080041#include <gui/Surface.h>
Nicolas Catania1d187f12009-05-12 23:25:55 -070042#include <utils/Errors.h> // for status_t
43#include <utils/String8.h>
Marco Nelissen10dbb8e2009-09-20 10:42:13 -070044#include <utils/SystemClock.h>
Lajos Molnar06ad1522014-08-28 07:27:44 -070045#include <utils/Timers.h>
Nicolas Catania1d187f12009-05-12 23:25:55 -070046#include <utils/Vector.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080047
Eric Laurent43562692015-07-15 16:49:07 -070048#include <media/AudioPolicyHelper.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080049#include <media/IMediaHTTPService.h>
Jeff Brown2013a542012-09-04 21:38:42 -070050#include <media/IRemoteDisplay.h>
51#include <media/IRemoteDisplayClient.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080052#include <media/MediaPlayerInterface.h>
53#include <media/mediarecorder.h>
54#include <media/MediaMetadataRetrieverInterface.h>
nikoa64c8c72009-07-20 15:07:26 -070055#include <media/Metadata.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080056#include <media/AudioTrack.h>
James Dong8635b7b2011-03-14 17:01:38 -070057#include <media/MemoryLeakTrackUtil.h>
Lajos Molnar1381d4b2014-08-07 15:18:35 -070058#include <media/stagefright/MediaCodecList.h>
Eric Laurent9cb839a2011-09-27 09:48:56 -070059#include <media/stagefright/MediaErrors.h>
Marco Nelissen83b0fd92015-09-16 13:48:07 -070060#include <media/stagefright/Utils.h>
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +010061#include <media/stagefright/foundation/ADebug.h>
Marco Nelissenf09611f2015-02-13 14:12:42 -080062#include <media/stagefright/foundation/ALooperRoster.h>
Chong Zhang181fd9b2017-02-16 15:53:03 -080063#include <media/stagefright/SurfaceUtils.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070064#include <mediautils/BatteryNotifier.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080065
Andy Hung53541292016-04-13 16:48:51 -070066#include <memunreachable/memunreachable.h>
Dima Zavin64760242011-05-11 14:15:23 -070067#include <system/audio.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070068
Gloria Wang7cf180c2011-02-19 18:37:57 -080069#include <private/android_filesystem_config.h>
70
James Dong559bf282012-03-28 10:29:14 -070071#include "ActivityManager.h"
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080072#include "MediaRecorderClient.h"
73#include "MediaPlayerService.h"
74#include "MetadataRetrieverClient.h"
John Grossman44a7e422012-06-21 17:29:24 -070075#include "MediaPlayerFactory.h"
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080076
Nicolas Catania14d27472009-07-13 14:37:49 -070077#include "TestPlayerStub.h"
Andreas Huberf9334412010-12-15 15:17:42 -080078#include "nuplayer/NuPlayerDriver.h"
Andreas Huber20111aa2009-07-14 16:56:47 -070079
Pawin Vongmasa255735a2017-07-19 11:24:56 -070080#include <media/stagefright/omx/OMX.h>
Nicolas Catania14d27472009-07-13 14:37:49 -070081
Andreas Huberb7319a72013-05-29 14:20:52 -070082#include "HTTPBase.h"
Andreas Hubered3e3e02012-03-26 11:13:27 -070083
Wei Jia502c2f42017-07-13 17:47:56 -070084static const int kDumpLockRetries = 50;
85static const int kDumpLockSleepUs = 20000;
86
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070087namespace {
nikoa64c8c72009-07-20 15:07:26 -070088using android::media::Metadata;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070089using android::status_t;
90using android::OK;
91using android::BAD_VALUE;
92using android::NOT_ENOUGH_DATA;
93using android::Parcel;
Ivan Lozano8cf3a072017-08-09 09:01:33 -070094using android::media::VolumeShaper;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070095
96// Max number of entries in the filter.
97const int kMaxFilterSize = 64; // I pulled that out of thin air.
98
Andy Hungff874dc2016-04-11 16:49:09 -070099const float kMaxRequiredSpeed = 8.0f; // for PCM tracks allow up to 8x speedup.
100
nikoa64c8c72009-07-20 15:07:26 -0700101// FIXME: Move all the metadata related function in the Metadata.cpp
nikod608a812009-07-16 16:39:53 -0700102
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700103
104// Unmarshall a filter from a Parcel.
105// Filter format in a parcel:
106//
107// 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
108// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
109// | number of entries (n) |
110// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
111// | metadata type 1 |
112// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
113// | metadata type 2 |
114// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
115// ....
116// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
117// | metadata type n |
118// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
119//
120// @param p Parcel that should start with a filter.
121// @param[out] filter On exit contains the list of metadata type to be
122// filtered.
123// @param[out] status On exit contains the status code to be returned.
124// @return true if the parcel starts with a valid filter.
125bool unmarshallFilter(const Parcel& p,
nikoa64c8c72009-07-20 15:07:26 -0700126 Metadata::Filter *filter,
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700127 status_t *status)
128{
Nicolas Catania48290382009-07-10 13:53:06 -0700129 int32_t val;
130 if (p.readInt32(&val) != OK)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700131 {
Steve Block29357bc2012-01-06 19:20:56 +0000132 ALOGE("Failed to read filter's length");
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700133 *status = NOT_ENOUGH_DATA;
134 return false;
135 }
136
Nicolas Catania48290382009-07-10 13:53:06 -0700137 if( val > kMaxFilterSize || val < 0)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700138 {
Steve Block29357bc2012-01-06 19:20:56 +0000139 ALOGE("Invalid filter len %d", val);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700140 *status = BAD_VALUE;
141 return false;
142 }
143
Nicolas Catania48290382009-07-10 13:53:06 -0700144 const size_t num = val;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700145
146 filter->clear();
Nicolas Catania48290382009-07-10 13:53:06 -0700147 filter->setCapacity(num);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700148
nikoa64c8c72009-07-20 15:07:26 -0700149 size_t size = num * sizeof(Metadata::Type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700150
Nicolas Catania48290382009-07-10 13:53:06 -0700151
152 if (p.dataAvail() < size)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700153 {
Andy Hung833b4752016-04-04 17:15:48 -0700154 ALOGE("Filter too short expected %zu but got %zu", size, p.dataAvail());
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700155 *status = NOT_ENOUGH_DATA;
156 return false;
157 }
158
nikoa64c8c72009-07-20 15:07:26 -0700159 const Metadata::Type *data =
160 static_cast<const Metadata::Type*>(p.readInplace(size));
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700161
Nicolas Catania48290382009-07-10 13:53:06 -0700162 if (NULL == data)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700163 {
Steve Block29357bc2012-01-06 19:20:56 +0000164 ALOGE("Filter had no data");
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700165 *status = BAD_VALUE;
166 return false;
167 }
168
169 // TODO: The stl impl of vector would be more efficient here
170 // because it degenerates into a memcpy on pod types. Try to
171 // replace later or use stl::set.
Nicolas Catania48290382009-07-10 13:53:06 -0700172 for (size_t i = 0; i < num; ++i)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700173 {
Nicolas Catania48290382009-07-10 13:53:06 -0700174 filter->add(*data);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700175 ++data;
176 }
177 *status = OK;
178 return true;
179}
180
Nicolas Catania48290382009-07-10 13:53:06 -0700181// @param filter Of metadata type.
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700182// @param val To be searched.
183// @return true if a match was found.
nikoa64c8c72009-07-20 15:07:26 -0700184bool findMetadata(const Metadata::Filter& filter, const int32_t val)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700185{
186 // Deal with empty and ANY right away
187 if (filter.isEmpty()) return false;
nikoa64c8c72009-07-20 15:07:26 -0700188 if (filter[0] == Metadata::kAny) return true;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700189
Nicolas Catania48290382009-07-10 13:53:06 -0700190 return filter.indexOf(val) >= 0;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700191}
192
193} // anonymous namespace
194
195
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700196namespace {
197using android::Parcel;
198using android::String16;
199
200// marshalling tag indicating flattened utf16 tags
201// keep in sync with frameworks/base/media/java/android/media/AudioAttributes.java
202const int32_t kAudioAttributesMarshallTagFlattenTags = 1;
203
204// Audio attributes format in a parcel:
205//
206// 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
207// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
208// | usage |
209// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
210// | content_type |
211// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Hyejin Kim4f418f92014-09-05 15:50:03 +0900212// | source |
213// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700214// | flags |
215// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
216// | kAudioAttributesMarshallTagFlattenTags | // ignore tags if not found
217// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
218// | flattened tags in UTF16 |
219// | ... |
220// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
221//
222// @param p Parcel that contains audio attributes.
223// @param[out] attributes On exit points to an initialized audio_attributes_t structure
224// @param[out] status On exit contains the status code to be returned.
225void unmarshallAudioAttributes(const Parcel& parcel, audio_attributes_t *attributes)
226{
227 attributes->usage = (audio_usage_t) parcel.readInt32();
228 attributes->content_type = (audio_content_type_t) parcel.readInt32();
Hyejin Kim4f418f92014-09-05 15:50:03 +0900229 attributes->source = (audio_source_t) parcel.readInt32();
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700230 attributes->flags = (audio_flags_mask_t) parcel.readInt32();
231 const bool hasFlattenedTag = (parcel.readInt32() == kAudioAttributesMarshallTagFlattenTags);
232 if (hasFlattenedTag) {
233 // the tags are UTF16, convert to UTF8
234 String16 tags = parcel.readString16();
235 ssize_t realTagSize = utf16_to_utf8_length(tags.string(), tags.size());
236 if (realTagSize <= 0) {
237 strcpy(attributes->tags, "");
238 } else {
239 // copy the flattened string into the attributes as the destination for the conversion:
240 // copying array size -1, array for tags was calloc'd, no need to NULL-terminate it
241 size_t tagSize = realTagSize > AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 ?
242 AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 : realTagSize;
Sergio Giro1d3f4272016-06-28 18:24:52 +0100243 utf16_to_utf8(tags.string(), tagSize, attributes->tags,
244 sizeof(attributes->tags) / sizeof(attributes->tags[0]));
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700245 }
246 } else {
247 ALOGE("unmarshallAudioAttributes() received unflattened tags, ignoring tag values");
248 strcpy(attributes->tags, "");
249 }
250}
251} // anonymous namespace
252
253
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800254namespace android {
255
Marco Nelissenf09611f2015-02-13 14:12:42 -0800256extern ALooperRoster gLooperRoster;
257
258
Dave Burked681bbb2011-08-30 14:39:17 +0100259static bool checkPermission(const char* permissionString) {
Dave Burked681bbb2011-08-30 14:39:17 +0100260 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
261 bool ok = checkCallingPermission(String16(permissionString));
Steve Block29357bc2012-01-06 19:20:56 +0000262 if (!ok) ALOGE("Request requires %s", permissionString);
Dave Burked681bbb2011-08-30 14:39:17 +0100263 return ok;
264}
265
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800266// 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 -0800267/* static */ int MediaPlayerService::AudioOutput::mMinBufferCount = 4;
268/* static */ bool MediaPlayerService::AudioOutput::mIsOnEmulator = false;
269
270void MediaPlayerService::instantiate() {
271 defaultServiceManager()->addService(
272 String16("media.player"), new MediaPlayerService());
273}
274
275MediaPlayerService::MediaPlayerService()
276{
Steve Block3856b092011-10-20 11:56:00 +0100277 ALOGV("MediaPlayerService created");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800278 mNextConnId = 1;
Gloria Wang9ee159b2011-02-24 14:51:45 -0800279
John Grossman44a7e422012-06-21 17:29:24 -0700280 MediaPlayerFactory::registerBuiltinFactories();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800281}
282
283MediaPlayerService::~MediaPlayerService()
284{
Steve Block3856b092011-10-20 11:56:00 +0100285 ALOGV("MediaPlayerService destroyed");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800286}
287
Svet Ganovbe71aa22015-04-28 12:06:02 -0700288sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(const String16 &opPackageName)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800289{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800290 pid_t pid = IPCThreadState::self()->getCallingPid();
Svet Ganovbe71aa22015-04-28 12:06:02 -0700291 sp<MediaRecorderClient> recorder = new MediaRecorderClient(this, pid, opPackageName);
Gloria Wangdac6a312009-10-29 15:46:37 -0700292 wp<MediaRecorderClient> w = recorder;
293 Mutex::Autolock lock(mLock);
294 mMediaRecorderClients.add(w);
Steve Block3856b092011-10-20 11:56:00 +0100295 ALOGV("Create new media recorder client from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800296 return recorder;
297}
298
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -0700299void MediaPlayerService::removeMediaRecorderClient(const wp<MediaRecorderClient>& client)
Gloria Wangdac6a312009-10-29 15:46:37 -0700300{
301 Mutex::Autolock lock(mLock);
302 mMediaRecorderClients.remove(client);
Steve Block3856b092011-10-20 11:56:00 +0100303 ALOGV("Delete media recorder client");
Gloria Wangdac6a312009-10-29 15:46:37 -0700304}
305
Glenn Kastenf37971f2012-02-03 11:06:53 -0800306sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800307{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800308 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800309 sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
Steve Block3856b092011-10-20 11:56:00 +0100310 ALOGV("Create new media retriever from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800311 return retriever;
312}
313
Glenn Kastenf37971f2012-02-03 11:06:53 -0800314sp<IMediaPlayer> MediaPlayerService::create(const sp<IMediaPlayerClient>& client,
Glenn Kastend848eb42016-03-08 13:42:11 -0800315 audio_session_t audioSessionId)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800316{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800317 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800318 int32_t connId = android_atomic_inc(&mNextConnId);
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700319
320 sp<Client> c = new Client(
321 this, pid, connId, client, audioSessionId,
322 IPCThreadState::self()->getCallingUid());
323
Steve Block3856b092011-10-20 11:56:00 +0100324 ALOGV("Create new client(%d) from pid %d, uid %d, ", connId, pid,
Dave Burked681bbb2011-08-30 14:39:17 +0100325 IPCThreadState::self()->getCallingUid());
326
327 wp<Client> w = c;
328 {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800329 Mutex::Autolock lock(mLock);
330 mClients.add(w);
331 }
Andreas Hubere2b10282010-11-23 11:41:34 -0800332 return c;
333}
334
Lajos Molnar1381d4b2014-08-07 15:18:35 -0700335sp<IMediaCodecList> MediaPlayerService::getCodecList() const {
336 return MediaCodecList::getLocalInstance();
337}
338
Marco Nelissen260e56c2016-01-28 21:41:25 +0000339sp<IOMX> MediaPlayerService::getOMX() {
Marco Nelissen1900e772016-02-02 16:12:16 -0800340 ALOGI("MediaPlayerService::getOMX");
Marco Nelissen260e56c2016-01-28 21:41:25 +0000341 Mutex::Autolock autoLock(mLock);
342
343 if (mOMX.get() == NULL) {
344 mOMX = new OMX;
345 }
346
347 return mOMX;
348}
349
Jeff Brown2013a542012-09-04 21:38:42 -0700350sp<IRemoteDisplay> MediaPlayerService::listenForRemoteDisplay(
Chong Zhangd0a98fa2017-09-14 17:43:10 -0700351 const String16 &/*opPackageName*/,
352 const sp<IRemoteDisplayClient>& /*client*/,
353 const String8& /*iface*/) {
354 ALOGE("listenForRemoteDisplay is no longer supported!");
Jeff Brownaba33d52012-09-07 17:38:58 -0700355
Chong Zhangd0a98fa2017-09-14 17:43:10 -0700356 return NULL;
Jeff Brown2013a542012-09-04 21:38:42 -0700357}
358
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800359status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
360{
361 const size_t SIZE = 256;
362 char buffer[SIZE];
363 String8 result;
364
365 result.append(" AudioOutput\n");
366 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n",
367 mStreamType, mLeftVolume, mRightVolume);
368 result.append(buffer);
369 snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n",
Eric Laurentdb354e52012-03-05 17:27:11 -0800370 mMsecsPerFrame, (mTrack != 0) ? mTrack->latency() : -1);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800371 result.append(buffer);
Eric Laurent2beeb502010-07-16 07:43:46 -0700372 snprintf(buffer, 255, " aux effect id(%d), send level (%f)\n",
373 mAuxEffectId, mSendLevel);
374 result.append(buffer);
375
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800376 ::write(fd, result.string(), result.size());
377 if (mTrack != 0) {
378 mTrack->dump(fd, args);
379 }
380 return NO_ERROR;
381}
382
Lajos Molnar6d339f12015-04-17 16:15:53 -0700383status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800384{
385 const size_t SIZE = 256;
386 char buffer[SIZE];
387 String8 result;
388 result.append(" Client\n");
389 snprintf(buffer, 255, " pid(%d), connId(%d), status(%d), looping(%s)\n",
390 mPid, mConnId, mStatus, mLoop?"true": "false");
391 result.append(buffer);
Wei Jia502c2f42017-07-13 17:47:56 -0700392
393 sp<MediaPlayerBase> p;
394 sp<AudioOutput> audioOutput;
395 bool locked = false;
396 for (int i = 0; i < kDumpLockRetries; ++i) {
397 if (mLock.tryLock() == NO_ERROR) {
398 locked = true;
399 break;
400 }
401 usleep(kDumpLockSleepUs);
Andreas Hubera0b1d4b2011-06-07 15:52:25 -0700402 }
Wei Jia502c2f42017-07-13 17:47:56 -0700403
404 if (locked) {
405 p = mPlayer;
406 audioOutput = mAudioOutput;
407 mLock.unlock();
408 } else {
409 result.append(" lock is taken, no dump from player and audio output\n");
410 }
411 write(fd, result.string(), result.size());
412
413 if (p != NULL) {
414 p->dump(fd, args);
415 }
416 if (audioOutput != 0) {
417 audioOutput->dump(fd, args);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800418 }
419 write(fd, "\n", 1);
420 return NO_ERROR;
421}
422
Marco Nelissenf09611f2015-02-13 14:12:42 -0800423/**
424 * The only arguments this understands right now are -c, -von and -voff,
425 * which are parsed by ALooperRoster::dump()
426 */
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800427status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
428{
429 const size_t SIZE = 256;
430 char buffer[SIZE];
431 String8 result;
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530432 SortedVector< sp<Client> > clients; //to serialise the mutex unlock & client destruction.
433 SortedVector< sp<MediaRecorderClient> > mediaRecorderClients;
434
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800435 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
436 snprintf(buffer, SIZE, "Permission Denial: "
437 "can't dump MediaPlayerService from pid=%d, uid=%d\n",
438 IPCThreadState::self()->getCallingPid(),
439 IPCThreadState::self()->getCallingUid());
440 result.append(buffer);
441 } else {
442 Mutex::Autolock lock(mLock);
443 for (int i = 0, n = mClients.size(); i < n; ++i) {
444 sp<Client> c = mClients[i].promote();
445 if (c != 0) c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530446 clients.add(c);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800447 }
James Dongb9141222010-07-08 11:16:11 -0700448 if (mMediaRecorderClients.size() == 0) {
449 result.append(" No media recorder client\n\n");
450 } else {
451 for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
452 sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
James Donge579e282011-10-18 22:29:20 -0700453 if (c != 0) {
454 snprintf(buffer, 255, " MediaRecorderClient pid(%d)\n", c->mPid);
455 result.append(buffer);
456 write(fd, result.string(), result.size());
457 result = "\n";
458 c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530459 mediaRecorderClients.add(c);
James Donge579e282011-10-18 22:29:20 -0700460 }
James Dongb9141222010-07-08 11:16:11 -0700461 }
Gloria Wangdac6a312009-10-29 15:46:37 -0700462 }
463
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800464 result.append(" Files opened and/or mapped:\n");
Marco Nelissenf09611f2015-02-13 14:12:42 -0800465 snprintf(buffer, SIZE, "/proc/%d/maps", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800466 FILE *f = fopen(buffer, "r");
467 if (f) {
468 while (!feof(f)) {
469 fgets(buffer, SIZE, f);
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700470 if (strstr(buffer, " /storage/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800471 strstr(buffer, " /system/sounds/") ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700472 strstr(buffer, " /data/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800473 strstr(buffer, " /system/media/")) {
474 result.append(" ");
475 result.append(buffer);
476 }
477 }
478 fclose(f);
479 } else {
480 result.append("couldn't open ");
481 result.append(buffer);
482 result.append("\n");
483 }
484
Marco Nelissenf09611f2015-02-13 14:12:42 -0800485 snprintf(buffer, SIZE, "/proc/%d/fd", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800486 DIR *d = opendir(buffer);
487 if (d) {
488 struct dirent *ent;
489 while((ent = readdir(d)) != NULL) {
490 if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
Marco Nelissenf09611f2015-02-13 14:12:42 -0800491 snprintf(buffer, SIZE, "/proc/%d/fd/%s", getpid(), ent->d_name);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800492 struct stat s;
493 if (lstat(buffer, &s) == 0) {
494 if ((s.st_mode & S_IFMT) == S_IFLNK) {
495 char linkto[256];
496 int len = readlink(buffer, linkto, sizeof(linkto));
497 if(len > 0) {
498 if(len > 255) {
499 linkto[252] = '.';
500 linkto[253] = '.';
501 linkto[254] = '.';
502 linkto[255] = 0;
503 } else {
504 linkto[len] = 0;
505 }
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700506 if (strstr(linkto, "/storage/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800507 strstr(linkto, "/system/sounds/") == linkto ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700508 strstr(linkto, "/data/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800509 strstr(linkto, "/system/media/") == linkto) {
510 result.append(" ");
511 result.append(buffer);
512 result.append(" -> ");
513 result.append(linkto);
514 result.append("\n");
515 }
516 }
517 } else {
518 result.append(" unexpected type for ");
519 result.append(buffer);
520 result.append("\n");
521 }
522 }
523 }
524 }
525 closedir(d);
526 } else {
527 result.append("couldn't open ");
528 result.append(buffer);
529 result.append("\n");
530 }
531
Marco Nelissenf09611f2015-02-13 14:12:42 -0800532 gLooperRoster.dump(fd, args);
533
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800534 bool dumpMem = false;
Andy Hung53541292016-04-13 16:48:51 -0700535 bool unreachableMemory = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800536 for (size_t i = 0; i < args.size(); i++) {
537 if (args[i] == String16("-m")) {
538 dumpMem = true;
Andy Hung53541292016-04-13 16:48:51 -0700539 } else if (args[i] == String16("--unreachable")) {
540 unreachableMemory = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800541 }
542 }
543 if (dumpMem) {
Andy Hung07b745e2016-05-23 16:21:07 -0700544 result.append("\nDumping memory:\n");
545 std::string s = dumpMemoryAddresses(100 /* limit */);
546 result.append(s.c_str(), s.size());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800547 }
Andy Hung53541292016-04-13 16:48:51 -0700548 if (unreachableMemory) {
549 result.append("\nDumping unreachable memory:\n");
550 // TODO - should limit be an argument parameter?
551 std::string s = GetUnreachableMemoryString(true /* contents */, 10000 /* limit */);
552 result.append(s.c_str(), s.size());
553 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800554 }
555 write(fd, result.string(), result.size());
556 return NO_ERROR;
557}
558
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -0700559void MediaPlayerService::removeClient(const wp<Client>& client)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800560{
561 Mutex::Autolock lock(mLock);
562 mClients.remove(client);
563}
564
Robert Shihee0a0e32016-08-16 16:50:54 -0700565bool MediaPlayerService::hasClient(wp<Client> client)
566{
567 Mutex::Autolock lock(mLock);
568 return mClients.indexOf(client) != NAME_NOT_FOUND;
569}
570
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700571MediaPlayerService::Client::Client(
572 const sp<MediaPlayerService>& service, pid_t pid,
573 int32_t connId, const sp<IMediaPlayerClient>& client,
Glenn Kastend848eb42016-03-08 13:42:11 -0800574 audio_session_t audioSessionId, uid_t uid)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800575{
Steve Block3856b092011-10-20 11:56:00 +0100576 ALOGV("Client(%d) constructor", connId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800577 mPid = pid;
578 mConnId = connId;
579 mService = service;
580 mClient = client;
581 mLoop = false;
582 mStatus = NO_INIT;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700583 mAudioSessionId = audioSessionId;
Andy Hung1afd0982016-11-08 16:13:44 -0800584 mUid = uid;
John Grossmanc795b642012-02-22 15:38:35 -0800585 mRetransmitEndpointValid = false;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700586 mAudioAttributes = NULL;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700587
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800588#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000589 ALOGD("create Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800590 mAntagonizer = new Antagonizer(notify, this);
591#endif
592}
593
594MediaPlayerService::Client::~Client()
595{
Steve Block3856b092011-10-20 11:56:00 +0100596 ALOGV("Client(%d) destructor pid = %d", mConnId, mPid);
Wei Jia502c2f42017-07-13 17:47:56 -0700597 {
598 Mutex::Autolock l(mLock);
599 mAudioOutput.clear();
600 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800601 wp<Client> client(this);
602 disconnect();
603 mService->removeClient(client);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700604 if (mAudioAttributes != NULL) {
605 free(mAudioAttributes);
606 }
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800607 clearDeathNotifiers();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800608}
609
610void MediaPlayerService::Client::disconnect()
611{
Steve Block3856b092011-10-20 11:56:00 +0100612 ALOGV("disconnect(%d) from pid %d", mConnId, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800613 // grab local reference and clear main reference to prevent future
614 // access to object
615 sp<MediaPlayerBase> p;
616 {
617 Mutex::Autolock l(mLock);
618 p = mPlayer;
beanzdcfefde2012-11-05 09:51:43 +0800619 mClient.clear();
Wei Jia502c2f42017-07-13 17:47:56 -0700620 mPlayer.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800621 }
Andreas Huber20111aa2009-07-14 16:56:47 -0700622
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800623 // clear the notification to prevent callbacks to dead client
624 // and reset the player. We assume the player will serialize
625 // access to itself if necessary.
626 if (p != 0) {
627 p->setNotifyCallback(0, 0);
628#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000629 ALOGD("kill Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800630 mAntagonizer->kill();
631#endif
632 p->reset();
633 }
634
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700635 disconnectNativeWindow();
636
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800637 IPCThreadState::self()->flushCommands();
638}
639
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800640sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
641{
642 // determine if we have the right player type
Wei Jia502c2f42017-07-13 17:47:56 -0700643 sp<MediaPlayerBase> p = getPlayer();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800644 if ((p != NULL) && (p->playerType() != playerType)) {
Steve Block3856b092011-10-20 11:56:00 +0100645 ALOGV("delete player");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800646 p.clear();
647 }
648 if (p == NULL) {
Ronghua Wu68845c12015-07-21 09:50:48 -0700649 p = MediaPlayerFactory::createPlayer(playerType, this, notify, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800650 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700651
Jason Simmonsdb29e522011-08-12 13:46:55 -0700652 if (p != NULL) {
Andy Hung1afd0982016-11-08 16:13:44 -0800653 p->setUID(mUid);
Jason Simmonsdb29e522011-08-12 13:46:55 -0700654 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700655
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800656 return p;
657}
658
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700659MediaPlayerService::Client::ServiceDeathNotifier::ServiceDeathNotifier(
660 const sp<IBinder>& service,
661 const sp<MediaPlayerBase>& listener,
662 int which) {
663 mService = service;
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800664 mOmx = nullptr;
665 mListener = listener;
666 mWhich = which;
667}
668
669MediaPlayerService::Client::ServiceDeathNotifier::ServiceDeathNotifier(
670 const sp<IOmx>& omx,
671 const sp<MediaPlayerBase>& listener,
672 int which) {
673 mService = nullptr;
674 mOmx = omx;
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700675 mListener = listener;
676 mWhich = which;
677}
678
679MediaPlayerService::Client::ServiceDeathNotifier::~ServiceDeathNotifier() {
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700680}
681
682void MediaPlayerService::Client::ServiceDeathNotifier::binderDied(const wp<IBinder>& /*who*/) {
683 sp<MediaPlayerBase> listener = mListener.promote();
684 if (listener != NULL) {
685 listener->sendEvent(MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED, mWhich);
686 } else {
687 ALOGW("listener for process %d death is gone", mWhich);
688 }
689}
690
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800691void MediaPlayerService::Client::ServiceDeathNotifier::serviceDied(
692 uint64_t /* cookie */,
693 const wp<::android::hidl::base::V1_0::IBase>& /* who */) {
694 sp<MediaPlayerBase> listener = mListener.promote();
695 if (listener != NULL) {
696 listener->sendEvent(MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED, mWhich);
697 } else {
698 ALOGW("listener for process %d death is gone", mWhich);
699 }
700}
701
702void MediaPlayerService::Client::ServiceDeathNotifier::unlinkToDeath() {
703 if (mService != nullptr) {
704 mService->unlinkToDeath(this);
705 mService = nullptr;
706 } else if (mOmx != nullptr) {
707 mOmx->unlinkToDeath(this);
708 mOmx = nullptr;
709 }
710}
711
712void MediaPlayerService::Client::clearDeathNotifiers() {
713 if (mExtractorDeathListener != nullptr) {
714 mExtractorDeathListener->unlinkToDeath();
715 mExtractorDeathListener = nullptr;
716 }
717 if (mCodecDeathListener != nullptr) {
718 mCodecDeathListener->unlinkToDeath();
719 mCodecDeathListener = nullptr;
720 }
721}
722
John Grossmanc795b642012-02-22 15:38:35 -0800723sp<MediaPlayerBase> MediaPlayerService::Client::setDataSource_pre(
724 player_type playerType)
725{
726 ALOGV("player type = %d", playerType);
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800727 clearDeathNotifiers();
John Grossmanc795b642012-02-22 15:38:35 -0800728
729 // create the right type of player
730 sp<MediaPlayerBase> p = createPlayer(playerType);
731 if (p == NULL) {
732 return p;
733 }
734
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700735 sp<IServiceManager> sm = defaultServiceManager();
736 sp<IBinder> binder = sm->getService(String16("media.extractor"));
Marco Nelissen1b5a7ee2016-09-30 13:54:30 -0700737 if (binder == NULL) {
738 ALOGE("extractor service not available");
739 return NULL;
740 }
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700741 mExtractorDeathListener = new ServiceDeathNotifier(binder, p, MEDIAEXTRACTOR_PROCESS_DEATH);
742 binder->linkToDeath(mExtractorDeathListener);
743
Pawin Vongmasad4e9ca42017-03-29 17:24:56 -0700744 if (property_get_bool("persist.media.treble_omx", true)) {
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800745 // Treble IOmx
746 sp<IOmx> omx = IOmx::getService();
747 if (omx == nullptr) {
748 ALOGE("Treble IOmx not available");
749 return NULL;
750 }
751 mCodecDeathListener = new ServiceDeathNotifier(omx, p, MEDIACODEC_PROCESS_DEATH);
752 omx->linkToDeath(mCodecDeathListener, 0);
753 } else {
754 // Legacy IOMX
755 binder = sm->getService(String16("media.codec"));
756 if (binder == NULL) {
757 ALOGE("codec service not available");
758 return NULL;
759 }
760 mCodecDeathListener = new ServiceDeathNotifier(binder, p, MEDIACODEC_PROCESS_DEATH);
761 binder->linkToDeath(mCodecDeathListener);
Marco Nelissen1b5a7ee2016-09-30 13:54:30 -0700762 }
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700763
John Grossmanc795b642012-02-22 15:38:35 -0800764 if (!p->hardwareOutput()) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -0700765 Mutex::Autolock l(mLock);
Marco Nelissend457c972014-02-11 08:47:07 -0800766 mAudioOutput = new AudioOutput(mAudioSessionId, IPCThreadState::self()->getCallingUid(),
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700767 mPid, mAudioAttributes);
John Grossmanc795b642012-02-22 15:38:35 -0800768 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
769 }
770
771 return p;
772}
773
774void MediaPlayerService::Client::setDataSource_post(
775 const sp<MediaPlayerBase>& p,
776 status_t status)
777{
778 ALOGV(" setDataSource");
779 mStatus = status;
780 if (mStatus != OK) {
781 ALOGE(" error: %d", mStatus);
782 return;
783 }
784
785 // Set the re-transmission endpoint if one was chosen.
786 if (mRetransmitEndpointValid) {
787 mStatus = p->setRetransmitEndpoint(&mRetransmitEndpoint);
788 if (mStatus != NO_ERROR) {
789 ALOGE("setRetransmitEndpoint error: %d", mStatus);
790 }
791 }
792
793 if (mStatus == OK) {
Wei Jia502c2f42017-07-13 17:47:56 -0700794 Mutex::Autolock l(mLock);
John Grossmanc795b642012-02-22 15:38:35 -0800795 mPlayer = p;
796 }
797}
798
Andreas Huber2db84552010-01-28 11:19:57 -0800799status_t MediaPlayerService::Client::setDataSource(
Andreas Huber1b86fe02014-01-29 11:13:26 -0800800 const sp<IMediaHTTPService> &httpService,
801 const char *url,
802 const KeyedVector<String8, String8> *headers)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800803{
Steve Block3856b092011-10-20 11:56:00 +0100804 ALOGV("setDataSource(%s)", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800805 if (url == NULL)
806 return UNKNOWN_ERROR;
807
Dave Burked681bbb2011-08-30 14:39:17 +0100808 if ((strncmp(url, "http://", 7) == 0) ||
809 (strncmp(url, "https://", 8) == 0) ||
810 (strncmp(url, "rtsp://", 7) == 0)) {
811 if (!checkPermission("android.permission.INTERNET")) {
812 return PERMISSION_DENIED;
813 }
814 }
815
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800816 if (strncmp(url, "content://", 10) == 0) {
817 // get a filedescriptor for the content Uri and
818 // pass it to the setDataSource(fd) method
819
820 String16 url16(url);
821 int fd = android::openContentProviderFile(url16);
822 if (fd < 0)
823 {
Steve Block29357bc2012-01-06 19:20:56 +0000824 ALOGE("Couldn't open fd for %s", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800825 return UNKNOWN_ERROR;
826 }
827 setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
828 close(fd);
829 return mStatus;
830 } else {
John Grossman44a7e422012-06-21 17:29:24 -0700831 player_type playerType = MediaPlayerFactory::getPlayerType(this, url);
John Grossmanc795b642012-02-22 15:38:35 -0800832 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
833 if (p == NULL) {
834 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800835 }
836
Andreas Huber1b86fe02014-01-29 11:13:26 -0800837 setDataSource_post(p, p->setDataSource(httpService, url, headers));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800838 return mStatus;
839 }
840}
841
842status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
843{
Marco Nelissen83b0fd92015-09-16 13:48:07 -0700844 ALOGV("setDataSource fd=%d (%s), offset=%lld, length=%lld",
845 fd, nameForFd(fd).c_str(), (long long) offset, (long long) length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800846 struct stat sb;
847 int ret = fstat(fd, &sb);
848 if (ret != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000849 ALOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800850 return UNKNOWN_ERROR;
851 }
852
Andy Hung833b4752016-04-04 17:15:48 -0700853 ALOGV("st_dev = %llu", static_cast<unsigned long long>(sb.st_dev));
Steve Block3856b092011-10-20 11:56:00 +0100854 ALOGV("st_mode = %u", sb.st_mode);
Mark Salyzyn77342f72014-06-18 16:31:32 -0700855 ALOGV("st_uid = %lu", static_cast<unsigned long>(sb.st_uid));
856 ALOGV("st_gid = %lu", static_cast<unsigned long>(sb.st_gid));
Andy Hung833b4752016-04-04 17:15:48 -0700857 ALOGV("st_size = %llu", static_cast<unsigned long long>(sb.st_size));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800858
859 if (offset >= sb.st_size) {
Steve Block29357bc2012-01-06 19:20:56 +0000860 ALOGE("offset error");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800861 return UNKNOWN_ERROR;
862 }
863 if (offset + length > sb.st_size) {
864 length = sb.st_size - offset;
Andy Hung833b4752016-04-04 17:15:48 -0700865 ALOGV("calculated length = %lld", (long long)length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800866 }
867
John Grossman44a7e422012-06-21 17:29:24 -0700868 player_type playerType = MediaPlayerFactory::getPlayerType(this,
869 fd,
870 offset,
871 length);
John Grossmanc795b642012-02-22 15:38:35 -0800872 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
873 if (p == NULL) {
874 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800875 }
876
877 // now set data source
John Grossmanc795b642012-02-22 15:38:35 -0800878 setDataSource_post(p, p->setDataSource(fd, offset, length));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800879 return mStatus;
880}
881
Andreas Hubere2b10282010-11-23 11:41:34 -0800882status_t MediaPlayerService::Client::setDataSource(
883 const sp<IStreamSource> &source) {
884 // create the right type of player
John Grossman44a7e422012-06-21 17:29:24 -0700885 player_type playerType = MediaPlayerFactory::getPlayerType(this, source);
John Grossmanc795b642012-02-22 15:38:35 -0800886 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
Andreas Hubere2b10282010-11-23 11:41:34 -0800887 if (p == NULL) {
888 return NO_INIT;
889 }
890
Andreas Hubere2b10282010-11-23 11:41:34 -0800891 // now set data source
John Grossmanc795b642012-02-22 15:38:35 -0800892 setDataSource_post(p, p->setDataSource(source));
Andreas Hubere2b10282010-11-23 11:41:34 -0800893 return mStatus;
894}
895
Chris Watkins99f31602015-03-20 13:06:33 -0700896status_t MediaPlayerService::Client::setDataSource(
897 const sp<IDataSource> &source) {
898 sp<DataSource> dataSource = DataSource::CreateFromIDataSource(source);
899 player_type playerType = MediaPlayerFactory::getPlayerType(this, dataSource);
900 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
901 if (p == NULL) {
902 return NO_INIT;
903 }
904 // now set data source
905 setDataSource_post(p, p->setDataSource(dataSource));
906 return mStatus;
907}
908
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700909void MediaPlayerService::Client::disconnectNativeWindow() {
910 if (mConnectedWindow != NULL) {
Chong Zhang181fd9b2017-02-16 15:53:03 -0800911 status_t err = nativeWindowDisconnect(
912 mConnectedWindow.get(), "disconnectNativeWindow");
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700913
914 if (err != OK) {
Chong Zhang181fd9b2017-02-16 15:53:03 -0800915 ALOGW("nativeWindowDisconnect returned an error: %s (%d)",
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700916 strerror(-err), err);
917 }
918 }
919 mConnectedWindow.clear();
920}
921
Glenn Kasten11731182011-02-08 17:26:17 -0800922status_t MediaPlayerService::Client::setVideoSurfaceTexture(
Andy McFadden484566c2012-12-18 09:46:54 -0800923 const sp<IGraphicBufferProducer>& bufferProducer)
Glenn Kasten11731182011-02-08 17:26:17 -0800924{
Andy McFadden484566c2012-12-18 09:46:54 -0800925 ALOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, bufferProducer.get());
Glenn Kasten11731182011-02-08 17:26:17 -0800926 sp<MediaPlayerBase> p = getPlayer();
927 if (p == 0) return UNKNOWN_ERROR;
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700928
Marco Nelissenf8880202014-11-14 07:58:25 -0800929 sp<IBinder> binder(IInterface::asBinder(bufferProducer));
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700930 if (mConnectedWindowBinder == binder) {
931 return OK;
932 }
933
934 sp<ANativeWindow> anw;
Andy McFadden484566c2012-12-18 09:46:54 -0800935 if (bufferProducer != NULL) {
Marco Nelissenee08f7e2013-09-16 13:30:01 -0700936 anw = new Surface(bufferProducer, true /* controlledByApp */);
Chong Zhang181fd9b2017-02-16 15:53:03 -0800937 status_t err = nativeWindowConnect(anw.get(), "setVideoSurfaceTexture");
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700938
939 if (err != OK) {
Steve Block29357bc2012-01-06 19:20:56 +0000940 ALOGE("setVideoSurfaceTexture failed: %d", err);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700941 // Note that we must do the reset before disconnecting from the ANW.
942 // Otherwise queue/dequeue calls could be made on the disconnected
943 // ANW, which may result in errors.
944 reset();
945
946 disconnectNativeWindow();
947
948 return err;
949 }
950 }
951
Andy McFadden484566c2012-12-18 09:46:54 -0800952 // Note that we must set the player's new GraphicBufferProducer before
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700953 // disconnecting the old one. Otherwise queue/dequeue calls could be made
954 // on the disconnected ANW, which may result in errors.
Andy McFadden484566c2012-12-18 09:46:54 -0800955 status_t err = p->setVideoSurfaceTexture(bufferProducer);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700956
957 disconnectNativeWindow();
958
959 mConnectedWindow = anw;
960
961 if (err == OK) {
962 mConnectedWindowBinder = binder;
963 } else {
964 disconnectNativeWindow();
965 }
966
967 return err;
Glenn Kasten11731182011-02-08 17:26:17 -0800968}
969
Nicolas Catania1d187f12009-05-12 23:25:55 -0700970status_t MediaPlayerService::Client::invoke(const Parcel& request,
971 Parcel *reply)
972{
973 sp<MediaPlayerBase> p = getPlayer();
974 if (p == NULL) return UNKNOWN_ERROR;
975 return p->invoke(request, reply);
976}
977
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700978// This call doesn't need to access the native player.
979status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
980{
981 status_t status;
nikoa64c8c72009-07-20 15:07:26 -0700982 media::Metadata::Filter allow, drop;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700983
Nicolas Catania48290382009-07-10 13:53:06 -0700984 if (unmarshallFilter(filter, &allow, &status) &&
985 unmarshallFilter(filter, &drop, &status)) {
986 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700987
988 mMetadataAllow = allow;
989 mMetadataDrop = drop;
990 }
991 return status;
992}
993
Nicolas Catania48290382009-07-10 13:53:06 -0700994status_t MediaPlayerService::Client::getMetadata(
Mark Salyzyn77342f72014-06-18 16:31:32 -0700995 bool update_only, bool /*apply_filter*/, Parcel *reply)
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700996{
nikoa64c8c72009-07-20 15:07:26 -0700997 sp<MediaPlayerBase> player = getPlayer();
998 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania48290382009-07-10 13:53:06 -0700999
nikod608a812009-07-16 16:39:53 -07001000 status_t status;
1001 // Placeholder for the return code, updated by the caller.
1002 reply->writeInt32(-1);
1003
nikoa64c8c72009-07-20 15:07:26 -07001004 media::Metadata::Filter ids;
Nicolas Catania48290382009-07-10 13:53:06 -07001005
1006 // We don't block notifications while we fetch the data. We clear
1007 // mMetadataUpdated first so we don't lose notifications happening
1008 // during the rest of this call.
1009 {
1010 Mutex::Autolock lock(mLock);
1011 if (update_only) {
nikod608a812009-07-16 16:39:53 -07001012 ids = mMetadataUpdated;
Nicolas Catania48290382009-07-10 13:53:06 -07001013 }
1014 mMetadataUpdated.clear();
1015 }
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001016
nikoa64c8c72009-07-20 15:07:26 -07001017 media::Metadata metadata(reply);
Nicolas Catania48290382009-07-10 13:53:06 -07001018
nikoa64c8c72009-07-20 15:07:26 -07001019 metadata.appendHeader();
1020 status = player->getMetadata(ids, reply);
nikod608a812009-07-16 16:39:53 -07001021
1022 if (status != OK) {
nikoa64c8c72009-07-20 15:07:26 -07001023 metadata.resetParcel();
Steve Block29357bc2012-01-06 19:20:56 +00001024 ALOGE("getMetadata failed %d", status);
nikod608a812009-07-16 16:39:53 -07001025 return status;
1026 }
1027
1028 // FIXME: Implement filtering on the result. Not critical since
1029 // filtering takes place on the update notifications already. This
1030 // would be when all the metadata are fetch and a filter is set.
1031
nikod608a812009-07-16 16:39:53 -07001032 // Everything is fine, update the metadata length.
nikoa64c8c72009-07-20 15:07:26 -07001033 metadata.updateLength();
nikod608a812009-07-16 16:39:53 -07001034 return OK;
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001035}
1036
Wei Jiad399e7e2016-10-26 15:49:11 -07001037status_t MediaPlayerService::Client::setBufferingSettings(
1038 const BufferingSettings& buffering)
1039{
Wei Jiadc6f3402017-01-09 15:04:18 -08001040 ALOGV("[%d] setBufferingSettings{%s}",
1041 mConnId, buffering.toString().string());
Wei Jiad399e7e2016-10-26 15:49:11 -07001042 sp<MediaPlayerBase> p = getPlayer();
1043 if (p == 0) return UNKNOWN_ERROR;
1044 return p->setBufferingSettings(buffering);
1045}
1046
1047status_t MediaPlayerService::Client::getDefaultBufferingSettings(
1048 BufferingSettings* buffering /* nonnull */)
1049{
1050 sp<MediaPlayerBase> p = getPlayer();
1051 // TODO: create mPlayer on demand.
1052 if (p == 0) return UNKNOWN_ERROR;
1053 status_t ret = p->getDefaultBufferingSettings(buffering);
1054 if (ret == NO_ERROR) {
Wei Jiadc6f3402017-01-09 15:04:18 -08001055 ALOGV("[%d] getDefaultBufferingSettings{%s}",
1056 mConnId, buffering->toString().string());
Wei Jiad399e7e2016-10-26 15:49:11 -07001057 } else {
1058 ALOGV("[%d] getDefaultBufferingSettings returned %d", mConnId, ret);
1059 }
1060 return ret;
1061}
1062
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001063status_t MediaPlayerService::Client::prepareAsync()
1064{
Steve Block3856b092011-10-20 11:56:00 +01001065 ALOGV("[%d] prepareAsync", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001066 sp<MediaPlayerBase> p = getPlayer();
1067 if (p == 0) return UNKNOWN_ERROR;
1068 status_t ret = p->prepareAsync();
1069#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +00001070 ALOGD("start Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001071 if (ret == NO_ERROR) mAntagonizer->start();
1072#endif
1073 return ret;
1074}
1075
1076status_t MediaPlayerService::Client::start()
1077{
Steve Block3856b092011-10-20 11:56:00 +01001078 ALOGV("[%d] start", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001079 sp<MediaPlayerBase> p = getPlayer();
1080 if (p == 0) return UNKNOWN_ERROR;
1081 p->setLooping(mLoop);
1082 return p->start();
1083}
1084
1085status_t MediaPlayerService::Client::stop()
1086{
Steve Block3856b092011-10-20 11:56:00 +01001087 ALOGV("[%d] stop", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001088 sp<MediaPlayerBase> p = getPlayer();
1089 if (p == 0) return UNKNOWN_ERROR;
1090 return p->stop();
1091}
1092
1093status_t MediaPlayerService::Client::pause()
1094{
Steve Block3856b092011-10-20 11:56:00 +01001095 ALOGV("[%d] pause", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001096 sp<MediaPlayerBase> p = getPlayer();
1097 if (p == 0) return UNKNOWN_ERROR;
1098 return p->pause();
1099}
1100
1101status_t MediaPlayerService::Client::isPlaying(bool* state)
1102{
1103 *state = false;
1104 sp<MediaPlayerBase> p = getPlayer();
1105 if (p == 0) return UNKNOWN_ERROR;
1106 *state = p->isPlaying();
Steve Block3856b092011-10-20 11:56:00 +01001107 ALOGV("[%d] isPlaying: %d", mConnId, *state);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001108 return NO_ERROR;
1109}
1110
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001111status_t MediaPlayerService::Client::setPlaybackSettings(const AudioPlaybackRate& rate)
Wei Jia98160162015-02-04 17:01:11 -08001112{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001113 ALOGV("[%d] setPlaybackSettings(%f, %f, %d, %d)",
1114 mConnId, rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Wei Jia98160162015-02-04 17:01:11 -08001115 sp<MediaPlayerBase> p = getPlayer();
1116 if (p == 0) return UNKNOWN_ERROR;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001117 return p->setPlaybackSettings(rate);
1118}
1119
1120status_t MediaPlayerService::Client::getPlaybackSettings(AudioPlaybackRate* rate /* nonnull */)
1121{
1122 sp<MediaPlayerBase> p = getPlayer();
1123 if (p == 0) return UNKNOWN_ERROR;
1124 status_t ret = p->getPlaybackSettings(rate);
1125 if (ret == NO_ERROR) {
1126 ALOGV("[%d] getPlaybackSettings(%f, %f, %d, %d)",
1127 mConnId, rate->mSpeed, rate->mPitch, rate->mFallbackMode, rate->mStretchMode);
1128 } else {
1129 ALOGV("[%d] getPlaybackSettings returned %d", mConnId, ret);
1130 }
1131 return ret;
1132}
1133
1134status_t MediaPlayerService::Client::setSyncSettings(
1135 const AVSyncSettings& sync, float videoFpsHint)
1136{
1137 ALOGV("[%d] setSyncSettings(%u, %u, %f, %f)",
1138 mConnId, sync.mSource, sync.mAudioAdjustMode, sync.mTolerance, videoFpsHint);
1139 sp<MediaPlayerBase> p = getPlayer();
1140 if (p == 0) return UNKNOWN_ERROR;
1141 return p->setSyncSettings(sync, videoFpsHint);
1142}
1143
1144status_t MediaPlayerService::Client::getSyncSettings(
1145 AVSyncSettings* sync /* nonnull */, float* videoFps /* nonnull */)
1146{
1147 sp<MediaPlayerBase> p = getPlayer();
1148 if (p == 0) return UNKNOWN_ERROR;
1149 status_t ret = p->getSyncSettings(sync, videoFps);
1150 if (ret == NO_ERROR) {
1151 ALOGV("[%d] getSyncSettings(%u, %u, %f, %f)",
1152 mConnId, sync->mSource, sync->mAudioAdjustMode, sync->mTolerance, *videoFps);
1153 } else {
1154 ALOGV("[%d] getSyncSettings returned %d", mConnId, ret);
1155 }
1156 return ret;
Wei Jia98160162015-02-04 17:01:11 -08001157}
1158
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001159status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
1160{
Steve Block3856b092011-10-20 11:56:00 +01001161 ALOGV("getCurrentPosition");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001162 sp<MediaPlayerBase> p = getPlayer();
1163 if (p == 0) return UNKNOWN_ERROR;
1164 status_t ret = p->getCurrentPosition(msec);
1165 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001166 ALOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001167 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001168 ALOGE("getCurrentPosition returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001169 }
1170 return ret;
1171}
1172
1173status_t MediaPlayerService::Client::getDuration(int *msec)
1174{
Steve Block3856b092011-10-20 11:56:00 +01001175 ALOGV("getDuration");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001176 sp<MediaPlayerBase> p = getPlayer();
1177 if (p == 0) return UNKNOWN_ERROR;
1178 status_t ret = p->getDuration(msec);
1179 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001180 ALOGV("[%d] getDuration = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001181 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001182 ALOGE("getDuration returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001183 }
1184 return ret;
1185}
1186
Marco Nelissen6b74d672012-02-28 16:07:44 -08001187status_t MediaPlayerService::Client::setNextPlayer(const sp<IMediaPlayer>& player) {
1188 ALOGV("setNextPlayer");
1189 Mutex::Autolock l(mLock);
1190 sp<Client> c = static_cast<Client*>(player.get());
Wei Jia28284122016-08-30 13:49:06 -07001191 if (c != NULL && !mService->hasClient(c)) {
Robert Shihee0a0e32016-08-16 16:50:54 -07001192 return BAD_VALUE;
1193 }
1194
Marco Nelissen6b74d672012-02-28 16:07:44 -08001195 mNextClient = c;
John Grossman5f7e55e2012-08-24 14:47:25 -07001196
1197 if (c != NULL) {
1198 if (mAudioOutput != NULL) {
1199 mAudioOutput->setNextOutput(c->mAudioOutput);
1200 } else if ((mPlayer != NULL) && !mPlayer->hardwareOutput()) {
1201 ALOGE("no current audio output");
1202 }
1203
1204 if ((mPlayer != NULL) && (mNextClient->getPlayer() != NULL)) {
1205 mPlayer->setNextPlayer(mNextClient->getPlayer());
1206 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001207 }
John Grossman5f7e55e2012-08-24 14:47:25 -07001208
Marco Nelissen6b74d672012-02-28 16:07:44 -08001209 return OK;
1210}
1211
Andy Hung9fc8b5c2017-01-24 13:36:48 -08001212VolumeShaper::Status MediaPlayerService::Client::applyVolumeShaper(
1213 const sp<VolumeShaper::Configuration>& configuration,
1214 const sp<VolumeShaper::Operation>& operation) {
1215 // for hardware output, call player instead
1216 ALOGV("Client::applyVolumeShaper(%p)", this);
1217 sp<MediaPlayerBase> p = getPlayer();
1218 {
1219 Mutex::Autolock l(mLock);
1220 if (p != 0 && p->hardwareOutput()) {
1221 // TODO: investigate internal implementation
1222 return VolumeShaper::Status(INVALID_OPERATION);
1223 }
1224 if (mAudioOutput.get() != nullptr) {
1225 return mAudioOutput->applyVolumeShaper(configuration, operation);
1226 }
1227 }
1228 return VolumeShaper::Status(INVALID_OPERATION);
1229}
1230
1231sp<VolumeShaper::State> MediaPlayerService::Client::getVolumeShaperState(int id) {
1232 // for hardware output, call player instead
1233 ALOGV("Client::getVolumeShaperState(%p)", this);
1234 sp<MediaPlayerBase> p = getPlayer();
1235 {
1236 Mutex::Autolock l(mLock);
1237 if (p != 0 && p->hardwareOutput()) {
1238 // TODO: investigate internal implementation.
1239 return nullptr;
1240 }
1241 if (mAudioOutput.get() != nullptr) {
1242 return mAudioOutput->getVolumeShaperState(id);
1243 }
1244 }
1245 return nullptr;
1246}
1247
Wei Jiac5de0912016-11-18 10:22:14 -08001248status_t MediaPlayerService::Client::seekTo(int msec, MediaPlayerSeekMode mode)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001249{
Wei Jiac5de0912016-11-18 10:22:14 -08001250 ALOGV("[%d] seekTo(%d, %d)", mConnId, msec, mode);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001251 sp<MediaPlayerBase> p = getPlayer();
1252 if (p == 0) return UNKNOWN_ERROR;
Wei Jiac5de0912016-11-18 10:22:14 -08001253 return p->seekTo(msec, mode);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001254}
1255
1256status_t MediaPlayerService::Client::reset()
1257{
Steve Block3856b092011-10-20 11:56:00 +01001258 ALOGV("[%d] reset", mConnId);
John Grossmanc795b642012-02-22 15:38:35 -08001259 mRetransmitEndpointValid = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001260 sp<MediaPlayerBase> p = getPlayer();
1261 if (p == 0) return UNKNOWN_ERROR;
1262 return p->reset();
1263}
1264
Wei Jia52c28512017-09-13 18:17:51 -07001265status_t MediaPlayerService::Client::notifyAt(int64_t mediaTimeUs)
1266{
1267 ALOGV("[%d] notifyAt(%lld)", mConnId, (long long)mediaTimeUs);
1268 sp<MediaPlayerBase> p = getPlayer();
1269 if (p == 0) return UNKNOWN_ERROR;
1270 return p->notifyAt(mediaTimeUs);
1271}
1272
Glenn Kastenfff6d712012-01-12 16:38:12 -08001273status_t MediaPlayerService::Client::setAudioStreamType(audio_stream_type_t type)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001274{
Steve Block3856b092011-10-20 11:56:00 +01001275 ALOGV("[%d] setAudioStreamType(%d)", mConnId, type);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001276 // TODO: for hardware output, call player instead
1277 Mutex::Autolock l(mLock);
1278 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1279 return NO_ERROR;
1280}
1281
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001282status_t MediaPlayerService::Client::setAudioAttributes_l(const Parcel &parcel)
1283{
1284 if (mAudioAttributes != NULL) { free(mAudioAttributes); }
1285 mAudioAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001286 if (mAudioAttributes == NULL) {
1287 return NO_MEMORY;
1288 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001289 unmarshallAudioAttributes(parcel, mAudioAttributes);
1290
1291 ALOGV("setAudioAttributes_l() usage=%d content=%d flags=0x%x tags=%s",
1292 mAudioAttributes->usage, mAudioAttributes->content_type, mAudioAttributes->flags,
1293 mAudioAttributes->tags);
1294
1295 if (mAudioOutput != 0) {
1296 mAudioOutput->setAudioAttributes(mAudioAttributes);
1297 }
1298 return NO_ERROR;
1299}
1300
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001301status_t MediaPlayerService::Client::setLooping(int loop)
1302{
Steve Block3856b092011-10-20 11:56:00 +01001303 ALOGV("[%d] setLooping(%d)", mConnId, loop);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001304 mLoop = loop;
1305 sp<MediaPlayerBase> p = getPlayer();
1306 if (p != 0) return p->setLooping(loop);
1307 return NO_ERROR;
1308}
1309
1310status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1311{
Steve Block3856b092011-10-20 11:56:00 +01001312 ALOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
John Grossman761defc2012-02-09 15:09:05 -08001313
1314 // for hardware output, call player instead
1315 sp<MediaPlayerBase> p = getPlayer();
1316 {
1317 Mutex::Autolock l(mLock);
1318 if (p != 0 && p->hardwareOutput()) {
1319 MediaPlayerHWInterface* hwp =
1320 reinterpret_cast<MediaPlayerHWInterface*>(p.get());
1321 return hwp->setVolume(leftVolume, rightVolume);
1322 } else {
1323 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1324 return NO_ERROR;
1325 }
1326 }
1327
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001328 return NO_ERROR;
1329}
1330
Eric Laurent2beeb502010-07-16 07:43:46 -07001331status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1332{
Steve Block3856b092011-10-20 11:56:00 +01001333 ALOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
Eric Laurent2beeb502010-07-16 07:43:46 -07001334 Mutex::Autolock l(mLock);
1335 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1336 return NO_ERROR;
1337}
1338
1339status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1340{
Steve Block3856b092011-10-20 11:56:00 +01001341 ALOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
Eric Laurent2beeb502010-07-16 07:43:46 -07001342 Mutex::Autolock l(mLock);
1343 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1344 return NO_ERROR;
1345}
Nicolas Catania48290382009-07-10 13:53:06 -07001346
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001347status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
Steve Block3856b092011-10-20 11:56:00 +01001348 ALOGV("[%d] setParameter(%d)", mConnId, key);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001349 switch (key) {
1350 case KEY_PARAMETER_AUDIO_ATTRIBUTES:
1351 {
1352 Mutex::Autolock l(mLock);
1353 return setAudioAttributes_l(request);
1354 }
1355 default:
1356 sp<MediaPlayerBase> p = getPlayer();
1357 if (p == 0) { return UNKNOWN_ERROR; }
1358 return p->setParameter(key, request);
1359 }
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001360}
1361
1362status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
Steve Block3856b092011-10-20 11:56:00 +01001363 ALOGV("[%d] getParameter(%d)", mConnId, key);
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001364 sp<MediaPlayerBase> p = getPlayer();
1365 if (p == 0) return UNKNOWN_ERROR;
1366 return p->getParameter(key, reply);
1367}
1368
John Grossmanc795b642012-02-22 15:38:35 -08001369status_t MediaPlayerService::Client::setRetransmitEndpoint(
1370 const struct sockaddr_in* endpoint) {
1371
1372 if (NULL != endpoint) {
1373 uint32_t a = ntohl(endpoint->sin_addr.s_addr);
1374 uint16_t p = ntohs(endpoint->sin_port);
1375 ALOGV("[%d] setRetransmitEndpoint(%u.%u.%u.%u:%hu)", mConnId,
1376 (a >> 24), (a >> 16) & 0xFF, (a >> 8) & 0xFF, (a & 0xFF), p);
1377 } else {
1378 ALOGV("[%d] setRetransmitEndpoint = <none>", mConnId);
1379 }
1380
1381 sp<MediaPlayerBase> p = getPlayer();
1382
1383 // Right now, the only valid time to set a retransmit endpoint is before
1384 // player selection has been made (since the presence or absence of a
1385 // retransmit endpoint is going to determine which player is selected during
1386 // setDataSource).
1387 if (p != 0) return INVALID_OPERATION;
1388
1389 if (NULL != endpoint) {
1390 mRetransmitEndpoint = *endpoint;
1391 mRetransmitEndpointValid = true;
1392 } else {
1393 mRetransmitEndpointValid = false;
1394 }
1395
1396 return NO_ERROR;
1397}
1398
John Grossman44a7e422012-06-21 17:29:24 -07001399status_t MediaPlayerService::Client::getRetransmitEndpoint(
1400 struct sockaddr_in* endpoint)
1401{
1402 if (NULL == endpoint)
1403 return BAD_VALUE;
1404
1405 sp<MediaPlayerBase> p = getPlayer();
1406
1407 if (p != NULL)
1408 return p->getRetransmitEndpoint(endpoint);
1409
1410 if (!mRetransmitEndpointValid)
1411 return NO_INIT;
1412
1413 *endpoint = mRetransmitEndpoint;
1414
1415 return NO_ERROR;
1416}
1417
Gloria Wangb483c472011-04-11 17:23:27 -07001418void MediaPlayerService::Client::notify(
1419 void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001420{
1421 Client* client = static_cast<Client*>(cookie);
James Dongb8a98252012-08-26 16:13:03 -07001422 if (client == NULL) {
1423 return;
1424 }
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001425
James Dongb8a98252012-08-26 16:13:03 -07001426 sp<IMediaPlayerClient> c;
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001427 sp<Client> nextClient;
1428 status_t errStartNext = NO_ERROR;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001429 {
1430 Mutex::Autolock l(client->mLock);
James Dongb8a98252012-08-26 16:13:03 -07001431 c = client->mClient;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001432 if (msg == MEDIA_PLAYBACK_COMPLETE && client->mNextClient != NULL) {
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001433 nextClient = client->mNextClient;
1434
John Grossmancb0b7552012-08-23 17:47:31 -07001435 if (client->mAudioOutput != NULL)
1436 client->mAudioOutput->switchToNextOutput();
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001437
1438 errStartNext = nextClient->start();
1439 }
1440 }
1441
1442 if (nextClient != NULL) {
1443 sp<IMediaPlayerClient> nc;
1444 {
1445 Mutex::Autolock l(nextClient->mLock);
1446 nc = nextClient->mClient;
1447 }
1448 if (nc != NULL) {
1449 if (errStartNext == NO_ERROR) {
1450 nc->notify(MEDIA_INFO, MEDIA_INFO_STARTED_AS_NEXT, 0, obj);
1451 } else {
1452 nc->notify(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN , 0, obj);
1453 ALOGE("gapless:start playback for next track failed, err(%d)", errStartNext);
Wei Jia2afac0c2016-01-07 12:13:07 -08001454 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001455 }
1456 }
1457
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001458 if (MEDIA_INFO == msg &&
Nicolas Catania48290382009-07-10 13:53:06 -07001459 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikoa64c8c72009-07-20 15:07:26 -07001460 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania48290382009-07-10 13:53:06 -07001461
1462 if(client->shouldDropMetadata(metadata_type)) {
1463 return;
1464 }
1465
1466 // Update the list of metadata that have changed. getMetadata
1467 // also access mMetadataUpdated and clears it.
1468 client->addNewMetadataUpdate(metadata_type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001469 }
James Dongb8a98252012-08-26 16:13:03 -07001470
1471 if (c != NULL) {
1472 ALOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
1473 c->notify(msg, ext1, ext2, obj);
1474 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001475}
1476
Nicolas Catania48290382009-07-10 13:53:06 -07001477
nikoa64c8c72009-07-20 15:07:26 -07001478bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001479{
Nicolas Catania48290382009-07-10 13:53:06 -07001480 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001481
Nicolas Catania48290382009-07-10 13:53:06 -07001482 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001483 return true;
1484 }
1485
Nicolas Catania48290382009-07-10 13:53:06 -07001486 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001487 return false;
Nicolas Catania48290382009-07-10 13:53:06 -07001488 } else {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001489 return true;
1490 }
1491}
1492
Nicolas Catania48290382009-07-10 13:53:06 -07001493
nikoa64c8c72009-07-20 15:07:26 -07001494void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania48290382009-07-10 13:53:06 -07001495 Mutex::Autolock lock(mLock);
1496 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1497 mMetadataUpdated.add(metadata_type);
1498 }
1499}
1500
Hassan Shojaniacefac142017-02-06 21:02:02 -08001501// Modular DRM
1502status_t MediaPlayerService::Client::prepareDrm(const uint8_t uuid[16],
1503 const Vector<uint8_t>& drmSessionId)
1504{
1505 ALOGV("[%d] prepareDrm", mConnId);
1506 sp<MediaPlayerBase> p = getPlayer();
1507 if (p == 0) return UNKNOWN_ERROR;
1508
1509 status_t ret = p->prepareDrm(uuid, drmSessionId);
1510 ALOGV("prepareDrm ret: %d", ret);
1511
1512 return ret;
1513}
1514
1515status_t MediaPlayerService::Client::releaseDrm()
1516{
1517 ALOGV("[%d] releaseDrm", mConnId);
1518 sp<MediaPlayerBase> p = getPlayer();
1519 if (p == 0) return UNKNOWN_ERROR;
1520
1521 status_t ret = p->releaseDrm();
1522 ALOGV("releaseDrm ret: %d", ret);
1523
1524 return ret;
1525}
1526
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001527#if CALLBACK_ANTAGONIZER
1528const int Antagonizer::interval = 10000; // 10 msecs
1529
1530Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1531 mExit(false), mActive(false), mClient(client), mCb(cb)
1532{
1533 createThread(callbackThread, this);
1534}
1535
1536void Antagonizer::kill()
1537{
1538 Mutex::Autolock _l(mLock);
1539 mActive = false;
1540 mExit = true;
1541 mCondition.wait(mLock);
1542}
1543
1544int Antagonizer::callbackThread(void* user)
1545{
Steve Blockb8a80522011-12-20 16:23:08 +00001546 ALOGD("Antagonizer started");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001547 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1548 while (!p->mExit) {
1549 if (p->mActive) {
Steve Block3856b092011-10-20 11:56:00 +01001550 ALOGV("send event");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001551 p->mCb(p->mClient, 0, 0, 0);
1552 }
1553 usleep(interval);
1554 }
1555 Mutex::Autolock _l(p->mLock);
1556 p->mCondition.signal();
Steve Blockb8a80522011-12-20 16:23:08 +00001557 ALOGD("Antagonizer stopped");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001558 return 0;
1559}
1560#endif
1561
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001562#undef LOG_TAG
1563#define LOG_TAG "AudioSink"
Andy Hung1afd0982016-11-08 16:13:44 -08001564MediaPlayerService::AudioOutput::AudioOutput(audio_session_t sessionId, uid_t uid, int pid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001565 const audio_attributes_t* attr)
Andreas Huber20111aa2009-07-14 16:56:47 -07001566 : mCallback(NULL),
Eric Laurenta514bdb2010-06-21 09:27:30 -07001567 mCallbackCookie(NULL),
Marco Nelissen6b74d672012-02-28 16:07:44 -08001568 mCallbackData(NULL),
Andy Hungd1c74342015-07-07 16:54:23 -07001569 mStreamType(AUDIO_STREAM_MUSIC),
Andy Hungd1c74342015-07-07 16:54:23 -07001570 mLeftVolume(1.0),
1571 mRightVolume(1.0),
1572 mPlaybackRate(AUDIO_PLAYBACK_RATE_DEFAULT),
1573 mSampleRateHz(0),
1574 mMsecsPerFrame(0),
1575 mFrameSize(0),
Eric Laurent1948eb32012-04-13 16:50:19 -07001576 mSessionId(sessionId),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001577 mUid(uid),
Marco Nelissend457c972014-02-11 08:47:07 -08001578 mPid(pid),
Andy Hungd1c74342015-07-07 16:54:23 -07001579 mSendLevel(0.0),
1580 mAuxEffectId(0),
Andy Hung4ef88d72017-02-21 19:47:53 -08001581 mFlags(AUDIO_OUTPUT_FLAG_NONE),
Ivan Lozano8cf3a072017-08-09 09:01:33 -07001582 mVolumeHandler(new media::VolumeHandler())
Andy Hungd1c74342015-07-07 16:54:23 -07001583{
Steve Block3856b092011-10-20 11:56:00 +01001584 ALOGV("AudioOutput(%d)", sessionId);
Eric Laurent43562692015-07-15 16:49:07 -07001585 if (attr != NULL) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001586 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1587 if (mAttributes != NULL) {
1588 memcpy(mAttributes, attr, sizeof(audio_attributes_t));
1589 mStreamType = audio_attributes_to_stream_type(attr);
1590 }
1591 } else {
1592 mAttributes = NULL;
Eric Laurent43562692015-07-15 16:49:07 -07001593 }
1594
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001595 setMinBufferCount();
1596}
1597
1598MediaPlayerService::AudioOutput::~AudioOutput()
1599{
1600 close();
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001601 free(mAttributes);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001602 delete mCallbackData;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001603}
1604
Andy Hungd1c74342015-07-07 16:54:23 -07001605//static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001606void MediaPlayerService::AudioOutput::setMinBufferCount()
1607{
1608 char value[PROPERTY_VALUE_MAX];
1609 if (property_get("ro.kernel.qemu", value, 0)) {
1610 mIsOnEmulator = true;
1611 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1612 }
1613}
1614
Andy Hungd1c74342015-07-07 16:54:23 -07001615// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001616bool MediaPlayerService::AudioOutput::isOnEmulator()
1617{
Andy Hungd1c74342015-07-07 16:54:23 -07001618 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001619 return mIsOnEmulator;
1620}
1621
Andy Hungd1c74342015-07-07 16:54:23 -07001622// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001623int MediaPlayerService::AudioOutput::getMinBufferCount()
1624{
Andy Hungd1c74342015-07-07 16:54:23 -07001625 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001626 return mMinBufferCount;
1627}
1628
1629ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1630{
Andy Hungd1c74342015-07-07 16:54:23 -07001631 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001632 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001633 return mTrack->frameCount() * mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001634}
1635
1636ssize_t MediaPlayerService::AudioOutput::frameCount() const
1637{
Andy Hungd1c74342015-07-07 16:54:23 -07001638 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001639 if (mTrack == 0) return NO_INIT;
1640 return mTrack->frameCount();
1641}
1642
1643ssize_t MediaPlayerService::AudioOutput::channelCount() const
1644{
Andy Hungd1c74342015-07-07 16:54:23 -07001645 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001646 if (mTrack == 0) return NO_INIT;
1647 return mTrack->channelCount();
1648}
1649
1650ssize_t MediaPlayerService::AudioOutput::frameSize() const
1651{
Andy Hungd1c74342015-07-07 16:54:23 -07001652 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001653 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001654 return mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001655}
1656
1657uint32_t MediaPlayerService::AudioOutput::latency () const
1658{
Andy Hungd1c74342015-07-07 16:54:23 -07001659 Mutex::Autolock lock(mLock);
Eric Laurentdb354e52012-03-05 17:27:11 -08001660 if (mTrack == 0) return 0;
1661 return mTrack->latency();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001662}
1663
1664float MediaPlayerService::AudioOutput::msecsPerFrame() const
1665{
Andy Hungd1c74342015-07-07 16:54:23 -07001666 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001667 return mMsecsPerFrame;
1668}
1669
Marco Nelissen4110c102012-03-29 09:31:28 -07001670status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position) const
Eric Laurent342e9cf2010-01-19 17:37:09 -08001671{
Andy Hungd1c74342015-07-07 16:54:23 -07001672 Mutex::Autolock lock(mLock);
Eric Laurent342e9cf2010-01-19 17:37:09 -08001673 if (mTrack == 0) return NO_INIT;
1674 return mTrack->getPosition(position);
1675}
1676
Lajos Molnar06ad1522014-08-28 07:27:44 -07001677status_t MediaPlayerService::AudioOutput::getTimestamp(AudioTimestamp &ts) const
1678{
Andy Hungd1c74342015-07-07 16:54:23 -07001679 Mutex::Autolock lock(mLock);
Lajos Molnar06ad1522014-08-28 07:27:44 -07001680 if (mTrack == 0) return NO_INIT;
1681 return mTrack->getTimestamp(ts);
1682}
1683
Wei Jiac4ac8172015-10-21 10:35:48 -07001684// TODO: Remove unnecessary calls to getPlayedOutDurationUs()
1685// as it acquires locks and may query the audio driver.
1686//
1687// Some calls could conceivably retrieve extrapolated data instead of
1688// accessing getTimestamp() or getPosition() every time a data buffer with
1689// a media time is received.
1690//
1691// Calculate duration of played samples if played at normal rate (i.e., 1.0).
1692int64_t MediaPlayerService::AudioOutput::getPlayedOutDurationUs(int64_t nowUs) const
1693{
1694 Mutex::Autolock lock(mLock);
1695 if (mTrack == 0 || mSampleRateHz == 0) {
Wei Jia213f4902015-10-22 08:55:25 -07001696 return 0;
Wei Jiac4ac8172015-10-21 10:35:48 -07001697 }
1698
1699 uint32_t numFramesPlayed;
Andy Hung5d313802016-10-10 15:09:39 -07001700 int64_t numFramesPlayedAtUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001701 AudioTimestamp ts;
Wei Jiac4ac8172015-10-21 10:35:48 -07001702
1703 status_t res = mTrack->getTimestamp(ts);
1704 if (res == OK) { // case 1: mixing audio tracks and offloaded tracks.
1705 numFramesPlayed = ts.mPosition;
Andy Hung5d313802016-10-10 15:09:39 -07001706 numFramesPlayedAtUs = ts.mTime.tv_sec * 1000000LL + ts.mTime.tv_nsec / 1000;
1707 //ALOGD("getTimestamp: OK %d %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001708 } else if (res == WOULD_BLOCK) { // case 2: transitory state on start of a new track
1709 numFramesPlayed = 0;
Andy Hung5d313802016-10-10 15:09:39 -07001710 numFramesPlayedAtUs = nowUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001711 //ALOGD("getTimestamp: WOULD_BLOCK %d %lld",
Andy Hung5d313802016-10-10 15:09:39 -07001712 // numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001713 } else { // case 3: transitory at new track or audio fast tracks.
1714 res = mTrack->getPosition(&numFramesPlayed);
1715 CHECK_EQ(res, (status_t)OK);
Andy Hung5d313802016-10-10 15:09:39 -07001716 numFramesPlayedAtUs = nowUs;
1717 numFramesPlayedAtUs += 1000LL * mTrack->latency() / 2; /* XXX */
1718 //ALOGD("getPosition: %u %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001719 }
1720
1721 // CHECK_EQ(numFramesPlayed & (1 << 31), 0); // can't be negative until 12.4 hrs, test
1722 // TODO: remove the (int32_t) casting below as it may overflow at 12.4 hours.
1723 int64_t durationUs = (int64_t)((int32_t)numFramesPlayed * 1000000LL / mSampleRateHz)
Andy Hung5d313802016-10-10 15:09:39 -07001724 + nowUs - numFramesPlayedAtUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001725 if (durationUs < 0) {
1726 // Occurs when numFramesPlayed position is very small and the following:
1727 // (1) In case 1, the time nowUs is computed before getTimestamp() is called and
Andy Hung5d313802016-10-10 15:09:39 -07001728 // numFramesPlayedAtUs is greater than nowUs by time more than numFramesPlayed.
Wei Jiac4ac8172015-10-21 10:35:48 -07001729 // (2) In case 3, using getPosition and adding mAudioSink->latency() to
Andy Hung5d313802016-10-10 15:09:39 -07001730 // numFramesPlayedAtUs, by a time amount greater than numFramesPlayed.
Wei Jiac4ac8172015-10-21 10:35:48 -07001731 //
1732 // Both of these are transitory conditions.
1733 ALOGV("getPlayedOutDurationUs: negative duration %lld set to zero", (long long)durationUs);
1734 durationUs = 0;
1735 }
1736 ALOGV("getPlayedOutDurationUs(%lld) nowUs(%lld) frames(%u) framesAt(%lld)",
Andy Hung5d313802016-10-10 15:09:39 -07001737 (long long)durationUs, (long long)nowUs,
1738 numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001739 return durationUs;
1740}
1741
Marco Nelissen4110c102012-03-29 09:31:28 -07001742status_t MediaPlayerService::AudioOutput::getFramesWritten(uint32_t *frameswritten) const
1743{
Andy Hungd1c74342015-07-07 16:54:23 -07001744 Mutex::Autolock lock(mLock);
Marco Nelissen4110c102012-03-29 09:31:28 -07001745 if (mTrack == 0) return NO_INIT;
Andy Hung2f6e73d2016-04-08 12:12:58 -07001746 ExtendedTimestamp ets;
1747 status_t status = mTrack->getTimestamp(&ets);
1748 if (status == OK || status == WOULD_BLOCK) {
1749 *frameswritten = (uint32_t)ets.mPosition[ExtendedTimestamp::LOCATION_CLIENT];
1750 }
1751 return status;
Marco Nelissen4110c102012-03-29 09:31:28 -07001752}
1753
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001754status_t MediaPlayerService::AudioOutput::setParameters(const String8& keyValuePairs)
1755{
Andy Hungd1c74342015-07-07 16:54:23 -07001756 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001757 if (mTrack == 0) return NO_INIT;
1758 return mTrack->setParameters(keyValuePairs);
1759}
1760
1761String8 MediaPlayerService::AudioOutput::getParameters(const String8& keys)
1762{
Andy Hungd1c74342015-07-07 16:54:23 -07001763 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001764 if (mTrack == 0) return String8::empty();
1765 return mTrack->getParameters(keys);
1766}
1767
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001768void MediaPlayerService::AudioOutput::setAudioAttributes(const audio_attributes_t * attributes) {
Andy Hungd1c74342015-07-07 16:54:23 -07001769 Mutex::Autolock lock(mLock);
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001770 if (attributes == NULL) {
1771 free(mAttributes);
1772 mAttributes = NULL;
1773 } else {
1774 if (mAttributes == NULL) {
1775 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1776 }
1777 memcpy(mAttributes, attributes, sizeof(audio_attributes_t));
Eric Laurent43562692015-07-15 16:49:07 -07001778 mStreamType = audio_attributes_to_stream_type(attributes);
1779 }
1780}
1781
1782void MediaPlayerService::AudioOutput::setAudioStreamType(audio_stream_type_t streamType)
1783{
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001784 Mutex::Autolock lock(mLock);
Eric Laurent43562692015-07-15 16:49:07 -07001785 // do not allow direct stream type modification if attributes have been set
1786 if (mAttributes == NULL) {
1787 mStreamType = streamType;
1788 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001789}
1790
Andy Hungd1c74342015-07-07 16:54:23 -07001791void MediaPlayerService::AudioOutput::deleteRecycledTrack_l()
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001792{
Andy Hungd1c74342015-07-07 16:54:23 -07001793 ALOGV("deleteRecycledTrack_l");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001794 if (mRecycledTrack != 0) {
1795
1796 if (mCallbackData != NULL) {
1797 mCallbackData->setOutput(NULL);
1798 mCallbackData->endTrackSwitch();
1799 }
1800
1801 if ((mRecycledTrack->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) {
Andy Hunge13f8a62016-03-30 14:20:42 -07001802 int32_t msec = 0;
1803 if (!mRecycledTrack->stopped()) { // check if active
1804 (void)mRecycledTrack->pendingDuration(&msec);
1805 }
1806 mRecycledTrack->stop(); // ensure full data drain
1807 ALOGD("deleting recycled track, waiting for data drain (%d msec)", msec);
1808 if (msec > 0) {
1809 static const int32_t WAIT_LIMIT_MS = 3000;
1810 if (msec > WAIT_LIMIT_MS) {
1811 msec = WAIT_LIMIT_MS;
1812 }
1813 usleep(msec * 1000LL);
1814 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001815 }
1816 // An offloaded track isn't flushed because the STREAM_END is reported
1817 // slightly prematurely to allow time for the gapless track switch
1818 // but this means that if we decide not to recycle the track there
1819 // could be a small amount of residual data still playing. We leave
1820 // AudioFlinger to drain the track.
1821
1822 mRecycledTrack.clear();
Andy Hungd1c74342015-07-07 16:54:23 -07001823 close_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001824 delete mCallbackData;
1825 mCallbackData = NULL;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001826 }
1827}
1828
Andy Hungd1c74342015-07-07 16:54:23 -07001829void MediaPlayerService::AudioOutput::close_l()
1830{
1831 mTrack.clear();
1832}
1833
Andreas Huber20111aa2009-07-14 16:56:47 -07001834status_t MediaPlayerService::AudioOutput::open(
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001835 uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
1836 audio_format_t format, int bufferCount,
Eric Laurent1948eb32012-04-13 16:50:19 -07001837 AudioCallback cb, void *cookie,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001838 audio_output_flags_t flags,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001839 const audio_offload_info_t *offloadInfo,
Andy Hung179652e2015-05-31 22:49:46 -07001840 bool doNotReconnect,
1841 uint32_t suggestedFrameCount)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001842{
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001843 ALOGV("open(%u, %d, 0x%x, 0x%x, %d, %d 0x%x)", sampleRate, channelCount, channelMask,
1844 format, bufferCount, mSessionId, flags);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001845
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001846 // offloading is only supported in callback mode for now.
1847 // offloadInfo must be present if offload flag is set
1848 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) &&
1849 ((cb == NULL) || (offloadInfo == NULL))) {
1850 return BAD_VALUE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001851 }
1852
Andy Hung179652e2015-05-31 22:49:46 -07001853 // compute frame count for the AudioTrack internal buffer
1854 size_t frameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001855 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1856 frameCount = 0; // AudioTrack will get frame count from AudioFlinger
1857 } else {
Andy Hung179652e2015-05-31 22:49:46 -07001858 // try to estimate the buffer processing fetch size from AudioFlinger.
1859 // framesPerBuffer is approximate and generally correct, except when it's not :-).
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001860 uint32_t afSampleRate;
1861 size_t afFrameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001862 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1863 return NO_INIT;
1864 }
1865 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1866 return NO_INIT;
1867 }
Andy Hung179652e2015-05-31 22:49:46 -07001868 const size_t framesPerBuffer =
1869 (unsigned long long)sampleRate * afFrameCount / afSampleRate;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001870
Andy Hung179652e2015-05-31 22:49:46 -07001871 if (bufferCount == 0) {
1872 // use suggestedFrameCount
1873 bufferCount = (suggestedFrameCount + framesPerBuffer - 1) / framesPerBuffer;
1874 }
1875 // Check argument bufferCount against the mininum buffer count
1876 if (bufferCount != 0 && bufferCount < mMinBufferCount) {
1877 ALOGV("bufferCount (%d) increased to %d", bufferCount, mMinBufferCount);
1878 bufferCount = mMinBufferCount;
1879 }
1880 // if frameCount is 0, then AudioTrack will get frame count from AudioFlinger
1881 // which will be the minimum size permitted.
1882 frameCount = bufferCount * framesPerBuffer;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001883 }
Andreas Huber20111aa2009-07-14 16:56:47 -07001884
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001885 if (channelMask == CHANNEL_MASK_USE_CHANNEL_ORDER) {
Glenn Kastenab334fd2012-03-14 12:56:06 -07001886 channelMask = audio_channel_out_mask_from_count(channelCount);
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001887 if (0 == channelMask) {
1888 ALOGE("open() error, can\'t derive mask for %d audio channels", channelCount);
1889 return NO_INIT;
1890 }
1891 }
Eric Laurent1948eb32012-04-13 16:50:19 -07001892
Andy Hungd1c74342015-07-07 16:54:23 -07001893 Mutex::Autolock lock(mLock);
Andy Hung179652e2015-05-31 22:49:46 -07001894 mCallback = cb;
1895 mCallbackCookie = cookie;
1896
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001897 // Check whether we can recycle the track
1898 bool reuse = false;
1899 bool bothOffloaded = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001900
Glenn Kasten2799d742013-05-30 14:33:29 -07001901 if (mRecycledTrack != 0) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001902 // check whether we are switching between two offloaded tracks
1903 bothOffloaded = (flags & mRecycledTrack->getFlags()
1904 & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0;
Marco Nelissen67295b52012-06-11 14:52:53 -07001905
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001906 // check if the existing track can be reused as-is, or if a new track needs to be created.
1907 reuse = true;
1908
Marco Nelissen67295b52012-06-11 14:52:53 -07001909 if ((mCallbackData == NULL && mCallback != NULL) ||
1910 (mCallbackData != NULL && mCallback == NULL)) {
1911 // recycled track uses callbacks but the caller wants to use writes, or vice versa
1912 ALOGV("can't chain callback and write");
1913 reuse = false;
1914 } else if ((mRecycledTrack->getSampleRate() != sampleRate) ||
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001915 (mRecycledTrack->channelCount() != (uint32_t)channelCount) ) {
1916 ALOGV("samplerate, channelcount differ: %u/%u Hz, %u/%d ch",
Marco Nelissen67295b52012-06-11 14:52:53 -07001917 mRecycledTrack->getSampleRate(), sampleRate,
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001918 mRecycledTrack->channelCount(), channelCount);
Marco Nelissen67295b52012-06-11 14:52:53 -07001919 reuse = false;
1920 } else if (flags != mFlags) {
1921 ALOGV("output flags differ %08x/%08x", flags, mFlags);
1922 reuse = false;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001923 } else if (mRecycledTrack->format() != format) {
1924 reuse = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001925 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001926 } else {
1927 ALOGV("no track available to recycle");
1928 }
1929
1930 ALOGV_IF(bothOffloaded, "both tracks offloaded");
1931
1932 // If we can't recycle and both tracks are offloaded
1933 // we must close the previous output before opening a new one
1934 if (bothOffloaded && !reuse) {
1935 ALOGV("both offloaded and not recycling");
Andy Hungd1c74342015-07-07 16:54:23 -07001936 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001937 }
1938
1939 sp<AudioTrack> t;
1940 CallbackData *newcbd = NULL;
1941
1942 // We don't attempt to create a new track if we are recycling an
1943 // offloaded track. But, if we are recycling a non-offloaded or we
1944 // are switching where one is offloaded and one isn't then we create
1945 // the new track in advance so that we can read additional stream info
1946
1947 if (!(reuse && bothOffloaded)) {
1948 ALOGV("creating new AudioTrack");
1949
1950 if (mCallback != NULL) {
1951 newcbd = new CallbackData(this);
1952 t = new AudioTrack(
1953 mStreamType,
1954 sampleRate,
1955 format,
1956 channelMask,
1957 frameCount,
1958 flags,
1959 CallbackWrapper,
1960 newcbd,
1961 0, // notification frames
1962 mSessionId,
1963 AudioTrack::TRANSFER_CALLBACK,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001964 offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -08001965 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001966 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001967 mAttributes,
1968 doNotReconnect);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001969 } else {
Andy Hungff874dc2016-04-11 16:49:09 -07001970 // TODO: Due to buffer memory concerns, we use a max target playback speed
1971 // based on mPlaybackRate at the time of open (instead of kMaxRequiredSpeed),
1972 // also clamping the target speed to 1.0 <= targetSpeed <= kMaxRequiredSpeed.
1973 const float targetSpeed =
1974 std::min(std::max(mPlaybackRate.mSpeed, 1.0f), kMaxRequiredSpeed);
1975 ALOGW_IF(targetSpeed != mPlaybackRate.mSpeed,
1976 "track target speed:%f clamped from playback speed:%f",
1977 targetSpeed, mPlaybackRate.mSpeed);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001978 t = new AudioTrack(
1979 mStreamType,
1980 sampleRate,
1981 format,
1982 channelMask,
1983 frameCount,
1984 flags,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001985 NULL, // callback
1986 NULL, // user data
1987 0, // notification frames
1988 mSessionId,
1989 AudioTrack::TRANSFER_DEFAULT,
1990 NULL, // offload info
Marco Nelissend457c972014-02-11 08:47:07 -08001991 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001992 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001993 mAttributes,
Andy Hungff874dc2016-04-11 16:49:09 -07001994 doNotReconnect,
1995 targetSpeed);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001996 }
1997
1998 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1999 ALOGE("Unable to create audio track");
2000 delete newcbd;
Glenn Kasten3e98ecd2015-05-18 13:13:24 -07002001 // t goes out of scope, so reference count drops to zero
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002002 return NO_INIT;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07002003 } else {
2004 // successful AudioTrack initialization implies a legacy stream type was generated
2005 // from the audio attributes
2006 mStreamType = t->streamType();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002007 }
2008 }
2009
2010 if (reuse) {
2011 CHECK(mRecycledTrack != NULL);
2012
2013 if (!bothOffloaded) {
2014 if (mRecycledTrack->frameCount() != t->frameCount()) {
Andy Hung833b4752016-04-04 17:15:48 -07002015 ALOGV("framecount differs: %zu/%zu frames",
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002016 mRecycledTrack->frameCount(), t->frameCount());
2017 reuse = false;
2018 }
2019 }
2020
Marco Nelissen67295b52012-06-11 14:52:53 -07002021 if (reuse) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002022 ALOGV("chaining to next output and recycling track");
Andy Hungd1c74342015-07-07 16:54:23 -07002023 close_l();
Marco Nelissen67295b52012-06-11 14:52:53 -07002024 mTrack = mRecycledTrack;
Glenn Kasten2799d742013-05-30 14:33:29 -07002025 mRecycledTrack.clear();
Marco Nelissen67295b52012-06-11 14:52:53 -07002026 if (mCallbackData != NULL) {
2027 mCallbackData->setOutput(this);
2028 }
Marco Nelissen67295b52012-06-11 14:52:53 -07002029 delete newcbd;
Wei Jiae0bbac92016-07-18 16:04:53 -07002030 return updateTrack();
Marco Nelissen67295b52012-06-11 14:52:53 -07002031 }
Marco Nelissen67295b52012-06-11 14:52:53 -07002032 }
2033
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002034 // we're not going to reuse the track, unblock and flush it
2035 // this was done earlier if both tracks are offloaded
2036 if (!bothOffloaded) {
Andy Hungd1c74342015-07-07 16:54:23 -07002037 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002038 }
2039
2040 CHECK((t != NULL) && ((mCallback == NULL) || (newcbd != NULL)));
2041
Marco Nelissen67295b52012-06-11 14:52:53 -07002042 mCallbackData = newcbd;
Steve Block3856b092011-10-20 11:56:00 +01002043 ALOGV("setVolume");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002044 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07002045
Andy Hung39399b62017-04-21 15:07:45 -07002046 // Restore VolumeShapers for the MediaPlayer in case the track was recreated
2047 // due to an output sink error (e.g. offload to non-offload switch).
2048 mVolumeHandler->forall([&t](const VolumeShaper &shaper) -> VolumeShaper::Status {
2049 sp<VolumeShaper::Operation> operationToEnd =
2050 new VolumeShaper::Operation(shaper.mOperation);
2051 // TODO: Ideally we would restore to the exact xOffset position
2052 // as returned by getVolumeShaperState(), but we don't have that
2053 // information when restoring at the client unless we periodically poll
2054 // the server or create shared memory state.
2055 //
2056 // For now, we simply advance to the end of the VolumeShaper effect
2057 // if it has been started.
2058 if (shaper.isStarted()) {
Andy Hungf3702642017-05-05 17:33:32 -07002059 operationToEnd->setNormalizedTime(1.f);
Andy Hung39399b62017-04-21 15:07:45 -07002060 }
2061 return t->applyVolumeShaper(shaper.mConfiguration, operationToEnd);
Andy Hung4ef88d72017-02-21 19:47:53 -08002062 });
Andy Hung4ef88d72017-02-21 19:47:53 -08002063
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002064 mSampleRateHz = sampleRate;
Preetam Singh Ranawat2e17eef2015-08-12 12:11:46 -07002065 mFlags = flags;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002066 mMsecsPerFrame = 1E3f / (mPlaybackRate.mSpeed * sampleRate);
Andy Hungd1c74342015-07-07 16:54:23 -07002067 mFrameSize = t->frameSize();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002068 mTrack = t;
Eric Laurent2beeb502010-07-16 07:43:46 -07002069
Wei Jiae0bbac92016-07-18 16:04:53 -07002070 return updateTrack();
2071}
2072
2073status_t MediaPlayerService::AudioOutput::updateTrack() {
2074 if (mTrack == NULL) {
2075 return NO_ERROR;
2076 }
2077
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002078 status_t res = NO_ERROR;
Wei Jia0162d002015-06-09 11:59:33 -07002079 // Note some output devices may give us a direct track even though we don't specify it.
2080 // Example: Line application b/17459982.
Wei Jiae0bbac92016-07-18 16:04:53 -07002081 if ((mTrack->getFlags()
2082 & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) {
2083 res = mTrack->setPlaybackRate(mPlaybackRate);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002084 if (res == NO_ERROR) {
Wei Jiae0bbac92016-07-18 16:04:53 -07002085 mTrack->setAuxEffectSendLevel(mSendLevel);
2086 res = mTrack->attachAuxEffect(mAuxEffectId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002087 }
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002088 }
Wei Jiae0bbac92016-07-18 16:04:53 -07002089 ALOGV("updateTrack() DONE status %d", res);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002090 return res;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002091}
2092
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002093status_t MediaPlayerService::AudioOutput::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002094{
Steve Block3856b092011-10-20 11:56:00 +01002095 ALOGV("start");
Andy Hungd1c74342015-07-07 16:54:23 -07002096 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08002097 if (mCallbackData != NULL) {
2098 mCallbackData->endTrackSwitch();
2099 }
Glenn Kasten2799d742013-05-30 14:33:29 -07002100 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002101 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07002102 mTrack->setAuxEffectSendLevel(mSendLevel);
Andy Hung39399b62017-04-21 15:07:45 -07002103 status_t status = mTrack->start();
2104 if (status == NO_ERROR) {
2105 mVolumeHandler->setStarted();
2106 }
2107 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002108 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002109 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002110}
2111
Marco Nelissen6b74d672012-02-28 16:07:44 -08002112void MediaPlayerService::AudioOutput::setNextOutput(const sp<AudioOutput>& nextOutput) {
Andy Hungd1c74342015-07-07 16:54:23 -07002113 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08002114 mNextOutput = nextOutput;
2115}
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08002116
Marco Nelissen6b74d672012-02-28 16:07:44 -08002117void MediaPlayerService::AudioOutput::switchToNextOutput() {
2118 ALOGV("switchToNextOutput");
Andy Hungd1c74342015-07-07 16:54:23 -07002119
2120 // Try to acquire the callback lock before moving track (without incurring deadlock).
2121 const unsigned kMaxSwitchTries = 100;
2122 Mutex::Autolock lock(mLock);
2123 for (unsigned tries = 0;;) {
2124 if (mTrack == 0) {
2125 return;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002126 }
Andy Hungd1c74342015-07-07 16:54:23 -07002127 if (mNextOutput != NULL && mNextOutput != this) {
2128 if (mCallbackData != NULL) {
2129 // two alternative approaches
2130#if 1
2131 CallbackData *callbackData = mCallbackData;
2132 mLock.unlock();
2133 // proper acquisition sequence
2134 callbackData->lock();
2135 mLock.lock();
2136 // Caution: it is unlikely that someone deleted our callback or changed our target
2137 if (callbackData != mCallbackData || mNextOutput == NULL || mNextOutput == this) {
2138 // fatal if we are starved out.
2139 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2140 "switchToNextOutput() cannot obtain correct lock sequence");
2141 callbackData->unlock();
2142 continue;
2143 }
2144 callbackData->mSwitching = true; // begin track switch
Wei Jiaadee56a2016-08-05 15:40:34 -07002145 callbackData->setOutput(NULL);
Andy Hungd1c74342015-07-07 16:54:23 -07002146#else
2147 // tryBeginTrackSwitch() returns false if the callback has the lock.
2148 if (!mCallbackData->tryBeginTrackSwitch()) {
2149 // fatal if we are starved out.
2150 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2151 "switchToNextOutput() cannot obtain callback lock");
2152 mLock.unlock();
2153 usleep(5 * 1000 /* usec */); // allow callback to use AudioOutput
2154 mLock.lock();
2155 continue;
2156 }
2157#endif
2158 }
2159
2160 Mutex::Autolock nextLock(mNextOutput->mLock);
2161
2162 // If the next output track is not NULL, then it has been
2163 // opened already for playback.
2164 // This is possible even without the next player being started,
2165 // for example, the next player could be prepared and seeked.
2166 //
2167 // Presuming it isn't advisable to force the track over.
2168 if (mNextOutput->mTrack == NULL) {
2169 ALOGD("Recycling track for gapless playback");
2170 delete mNextOutput->mCallbackData;
2171 mNextOutput->mCallbackData = mCallbackData;
2172 mNextOutput->mRecycledTrack = mTrack;
2173 mNextOutput->mSampleRateHz = mSampleRateHz;
2174 mNextOutput->mMsecsPerFrame = mMsecsPerFrame;
Andy Hungd1c74342015-07-07 16:54:23 -07002175 mNextOutput->mFlags = mFlags;
2176 mNextOutput->mFrameSize = mFrameSize;
2177 close_l();
2178 mCallbackData = NULL; // destruction handled by mNextOutput
2179 } else {
2180 ALOGW("Ignoring gapless playback because next player has already started");
2181 // remove track in case resource needed for future players.
2182 if (mCallbackData != NULL) {
2183 mCallbackData->endTrackSwitch(); // release lock for callbacks before close.
2184 }
2185 close_l();
2186 }
2187 }
2188 break;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002189 }
2190}
2191
Wei Jia7d3f4df2015-03-03 15:28:00 -08002192ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002193{
Andy Hungd1c74342015-07-07 16:54:23 -07002194 Mutex::Autolock lock(mLock);
Glenn Kastenadad3d72014-02-21 14:51:43 -08002195 LOG_ALWAYS_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
Andreas Huber20111aa2009-07-14 16:56:47 -07002196
Steve Block3856b092011-10-20 11:56:00 +01002197 //ALOGV("write(%p, %u)", buffer, size);
Glenn Kasten2799d742013-05-30 14:33:29 -07002198 if (mTrack != 0) {
Andy Hung2f6e73d2016-04-08 12:12:58 -07002199 return mTrack->write(buffer, size, blocking);
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07002200 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002201 return NO_INIT;
2202}
2203
2204void MediaPlayerService::AudioOutput::stop()
2205{
Steve Block3856b092011-10-20 11:56:00 +01002206 ALOGV("stop");
Andy Hungd1c74342015-07-07 16:54:23 -07002207 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002208 if (mTrack != 0) mTrack->stop();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002209}
2210
2211void MediaPlayerService::AudioOutput::flush()
2212{
Steve Block3856b092011-10-20 11:56:00 +01002213 ALOGV("flush");
Andy Hungd1c74342015-07-07 16:54:23 -07002214 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002215 if (mTrack != 0) mTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002216}
2217
2218void MediaPlayerService::AudioOutput::pause()
2219{
Steve Block3856b092011-10-20 11:56:00 +01002220 ALOGV("pause");
Andy Hungd1c74342015-07-07 16:54:23 -07002221 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002222 if (mTrack != 0) mTrack->pause();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002223}
2224
2225void MediaPlayerService::AudioOutput::close()
2226{
Steve Block3856b092011-10-20 11:56:00 +01002227 ALOGV("close");
Erik Wolsheimer7845a1f2015-10-30 12:07:52 -07002228 sp<AudioTrack> track;
2229 {
2230 Mutex::Autolock lock(mLock);
2231 track = mTrack;
2232 close_l(); // clears mTrack
2233 }
2234 // destruction of the track occurs outside of mutex.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002235}
2236
2237void MediaPlayerService::AudioOutput::setVolume(float left, float right)
2238{
Steve Block3856b092011-10-20 11:56:00 +01002239 ALOGV("setVolume(%f, %f)", left, right);
Andy Hungd1c74342015-07-07 16:54:23 -07002240 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002241 mLeftVolume = left;
2242 mRightVolume = right;
Glenn Kasten2799d742013-05-30 14:33:29 -07002243 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002244 mTrack->setVolume(left, right);
2245 }
2246}
2247
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002248status_t MediaPlayerService::AudioOutput::setPlaybackRate(const AudioPlaybackRate &rate)
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002249{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002250 ALOGV("setPlaybackRate(%f %f %d %d)",
2251 rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Andy Hungd1c74342015-07-07 16:54:23 -07002252 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002253 if (mTrack == 0) {
2254 // remember rate so that we can set it when the track is opened
2255 mPlaybackRate = rate;
2256 return OK;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002257 }
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002258 status_t res = mTrack->setPlaybackRate(rate);
2259 if (res != NO_ERROR) {
2260 return res;
2261 }
2262 // rate.mSpeed is always greater than 0 if setPlaybackRate succeeded
2263 CHECK_GT(rate.mSpeed, 0.f);
2264 mPlaybackRate = rate;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002265 if (mSampleRateHz != 0) {
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002266 mMsecsPerFrame = 1E3f / (rate.mSpeed * mSampleRateHz);
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002267 }
2268 return res;
2269}
2270
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002271status_t MediaPlayerService::AudioOutput::getPlaybackRate(AudioPlaybackRate *rate)
2272{
2273 ALOGV("setPlaybackRate");
Andy Hungd1c74342015-07-07 16:54:23 -07002274 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002275 if (mTrack == 0) {
2276 return NO_INIT;
2277 }
2278 *rate = mTrack->getPlaybackRate();
2279 return NO_ERROR;
2280}
2281
Eric Laurent2beeb502010-07-16 07:43:46 -07002282status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
2283{
Steve Block3856b092011-10-20 11:56:00 +01002284 ALOGV("setAuxEffectSendLevel(%f)", level);
Andy Hungd1c74342015-07-07 16:54:23 -07002285 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002286 mSendLevel = level;
Glenn Kasten2799d742013-05-30 14:33:29 -07002287 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002288 return mTrack->setAuxEffectSendLevel(level);
2289 }
2290 return NO_ERROR;
2291}
2292
2293status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
2294{
Steve Block3856b092011-10-20 11:56:00 +01002295 ALOGV("attachAuxEffect(%d)", effectId);
Andy Hungd1c74342015-07-07 16:54:23 -07002296 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002297 mAuxEffectId = effectId;
Glenn Kasten2799d742013-05-30 14:33:29 -07002298 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002299 return mTrack->attachAuxEffect(effectId);
2300 }
2301 return NO_ERROR;
2302}
2303
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002304VolumeShaper::Status MediaPlayerService::AudioOutput::applyVolumeShaper(
2305 const sp<VolumeShaper::Configuration>& configuration,
2306 const sp<VolumeShaper::Operation>& operation)
2307{
2308 Mutex::Autolock lock(mLock);
2309 ALOGV("AudioOutput::applyVolumeShaper");
Andy Hung4ef88d72017-02-21 19:47:53 -08002310
Andy Hung4ef88d72017-02-21 19:47:53 -08002311 mVolumeHandler->setIdIfNecessary(configuration);
Andy Hung39399b62017-04-21 15:07:45 -07002312
2313 VolumeShaper::Status status;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002314 if (mTrack != 0) {
Andy Hung39399b62017-04-21 15:07:45 -07002315 status = mTrack->applyVolumeShaper(configuration, operation);
2316 if (status >= 0) {
2317 (void)mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hungf3702642017-05-05 17:33:32 -07002318 if (mTrack->isPlaying()) { // match local AudioTrack to properly restore.
2319 mVolumeHandler->setStarted();
2320 }
Andy Hung39399b62017-04-21 15:07:45 -07002321 }
Andy Hung4ef88d72017-02-21 19:47:53 -08002322 } else {
Andy Hungc01eddb2017-07-21 16:42:41 -07002323 // VolumeShapers are not affected when a track moves between players for
2324 // gapless playback (setNextMediaPlayer).
2325 // We forward VolumeShaper operations that do not change configuration
2326 // to the new player so that unducking may occur as expected.
2327 // Unducking is an idempotent operation, same if applied back-to-back.
2328 if (configuration->getType() == VolumeShaper::Configuration::TYPE_ID
2329 && mNextOutput != nullptr) {
2330 ALOGV("applyVolumeShaper: Attempting to forward missed operation: %s %s",
2331 configuration->toString().c_str(), operation->toString().c_str());
2332 Mutex::Autolock nextLock(mNextOutput->mLock);
2333
2334 // recycled track should be forwarded from this AudioSink by switchToNextOutput
2335 sp<AudioTrack> track = mNextOutput->mRecycledTrack;
2336 if (track != nullptr) {
2337 ALOGD("Forward VolumeShaper operation to recycled track %p", track.get());
2338 (void)track->applyVolumeShaper(configuration, operation);
2339 } else {
2340 // There is a small chance that the unduck occurs after the next
2341 // player has already started, but before it is registered to receive
2342 // the unduck command.
2343 track = mNextOutput->mTrack;
2344 if (track != nullptr) {
2345 ALOGD("Forward VolumeShaper operation to track %p", track.get());
2346 (void)track->applyVolumeShaper(configuration, operation);
2347 }
2348 }
2349 }
Andy Hung39399b62017-04-21 15:07:45 -07002350 status = mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002351 }
Andy Hung39399b62017-04-21 15:07:45 -07002352 return status;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002353}
2354
2355sp<VolumeShaper::State> MediaPlayerService::AudioOutput::getVolumeShaperState(int id)
2356{
2357 Mutex::Autolock lock(mLock);
2358 if (mTrack != 0) {
2359 return mTrack->getVolumeShaperState(id);
Andy Hung4ef88d72017-02-21 19:47:53 -08002360 } else {
2361 return mVolumeHandler->getVolumeShaperState(id);
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002362 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002363}
2364
Andreas Huber20111aa2009-07-14 16:56:47 -07002365// static
2366void MediaPlayerService::AudioOutput::CallbackWrapper(
Glenn Kastend217a8c2011-06-01 15:20:35 -07002367 int event, void *cookie, void *info) {
Steve Block3856b092011-10-20 11:56:00 +01002368 //ALOGV("callbackwrapper");
Marco Nelissen6b74d672012-02-28 16:07:44 -08002369 CallbackData *data = (CallbackData*)cookie;
Andy Hungd1c74342015-07-07 16:54:23 -07002370 // lock to ensure we aren't caught in the middle of a track switch.
Marco Nelissen6b74d672012-02-28 16:07:44 -08002371 data->lock();
2372 AudioOutput *me = data->getOutput();
Andreas Huber20111aa2009-07-14 16:56:47 -07002373 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002374 if (me == NULL) {
2375 // no output set, likely because the track was scheduled to be reused
2376 // by another player, but the format turned out to be incompatible.
2377 data->unlock();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002378 if (buffer != NULL) {
2379 buffer->size = 0;
2380 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08002381 return;
2382 }
Andreas Huber20111aa2009-07-14 16:56:47 -07002383
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002384 switch(event) {
2385 case AudioTrack::EVENT_MORE_DATA: {
2386 size_t actualSize = (*me->mCallback)(
2387 me, buffer->raw, buffer->size, me->mCallbackCookie,
2388 CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002389
Andy Hung719b46b2015-05-31 22:18:25 -07002390 // Log when no data is returned from the callback.
2391 // (1) We may have no data (especially with network streaming sources).
2392 // (2) We may have reached the EOS and the audio track is not stopped yet.
2393 // Note that AwesomePlayer/AudioPlayer will only return zero size when it reaches the EOS.
2394 // NuPlayerRenderer will return zero when it doesn't have data (it doesn't block to fill).
2395 //
2396 // This is a benign busy-wait, with the next data request generated 10 ms or more later;
2397 // nevertheless for power reasons, we don't want to see too many of these.
Andreas Huber2e8ffaf2010-02-18 16:45:13 -08002398
Andy Hung719b46b2015-05-31 22:18:25 -07002399 ALOGV_IF(actualSize == 0 && buffer->size > 0, "callbackwrapper: empty buffer returned");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002400
2401 buffer->size = actualSize;
2402 } break;
2403
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002404 case AudioTrack::EVENT_STREAM_END:
Andy Hung719b46b2015-05-31 22:18:25 -07002405 // currently only occurs for offloaded callbacks
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002406 ALOGV("callbackwrapper: deliver EVENT_STREAM_END");
2407 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2408 me->mCallbackCookie, CB_EVENT_STREAM_END);
2409 break;
2410
2411 case AudioTrack::EVENT_NEW_IAUDIOTRACK :
2412 ALOGV("callbackwrapper: deliver EVENT_TEAR_DOWN");
2413 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2414 me->mCallbackCookie, CB_EVENT_TEAR_DOWN);
2415 break;
2416
Glenn Kasten421743b2015-06-01 08:18:08 -07002417 case AudioTrack::EVENT_UNDERRUN:
Andy Hung719b46b2015-05-31 22:18:25 -07002418 // This occurs when there is no data available, typically
Glenn Kasten421743b2015-06-01 08:18:08 -07002419 // when there is a failure to supply data to the AudioTrack. It can also
2420 // occur in non-offloaded mode when the audio device comes out of standby.
2421 //
Andy Hung719b46b2015-05-31 22:18:25 -07002422 // If an AudioTrack underruns it outputs silence. Since this happens suddenly
2423 // it may sound like an audible pop or glitch.
2424 //
2425 // The underrun event is sent once per track underrun; the condition is reset
2426 // when more data is sent to the AudioTrack.
Eric Laurente93cc032016-05-05 10:15:10 -07002427 ALOGD("callbackwrapper: EVENT_UNDERRUN (discarded)");
Glenn Kasten421743b2015-06-01 08:18:08 -07002428 break;
2429
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002430 default:
2431 ALOGE("received unknown event type: %d inside CallbackWrapper !", event);
Andreas Huber51c1e0e2011-04-04 11:43:40 -07002432 }
2433
Marco Nelissen6b74d672012-02-28 16:07:44 -08002434 data->unlock();
Andreas Huber20111aa2009-07-14 16:56:47 -07002435}
2436
Glenn Kastend848eb42016-03-08 13:42:11 -08002437audio_session_t MediaPlayerService::AudioOutput::getSessionId() const
Eric Laurent8c563ed2010-10-07 18:23:03 -07002438{
Andy Hungd1c74342015-07-07 16:54:23 -07002439 Mutex::Autolock lock(mLock);
Eric Laurent8c563ed2010-10-07 18:23:03 -07002440 return mSessionId;
2441}
2442
Eric Laurent6f59db12013-07-26 17:16:50 -07002443uint32_t MediaPlayerService::AudioOutput::getSampleRate() const
2444{
Andy Hungd1c74342015-07-07 16:54:23 -07002445 Mutex::Autolock lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -07002446 if (mTrack == 0) return 0;
2447 return mTrack->getSampleRate();
2448}
2449
Andy Hungf2c87b32016-04-07 19:49:29 -07002450int64_t MediaPlayerService::AudioOutput::getBufferDurationInUs() const
2451{
2452 Mutex::Autolock lock(mLock);
2453 if (mTrack == 0) {
2454 return 0;
2455 }
2456 int64_t duration;
2457 if (mTrack->getBufferDurationInUs(&duration) != OK) {
2458 return 0;
2459 }
2460 return duration;
2461}
2462
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002463////////////////////////////////////////////////////////////////////////////////
2464
2465struct CallbackThread : public Thread {
2466 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
2467 MediaPlayerBase::AudioSink::AudioCallback cb,
2468 void *cookie);
2469
2470protected:
2471 virtual ~CallbackThread();
2472
2473 virtual bool threadLoop();
2474
2475private:
2476 wp<MediaPlayerBase::AudioSink> mSink;
2477 MediaPlayerBase::AudioSink::AudioCallback mCallback;
2478 void *mCookie;
2479 void *mBuffer;
2480 size_t mBufferSize;
2481
2482 CallbackThread(const CallbackThread &);
2483 CallbackThread &operator=(const CallbackThread &);
2484};
2485
2486CallbackThread::CallbackThread(
2487 const wp<MediaPlayerBase::AudioSink> &sink,
2488 MediaPlayerBase::AudioSink::AudioCallback cb,
2489 void *cookie)
2490 : mSink(sink),
2491 mCallback(cb),
2492 mCookie(cookie),
2493 mBuffer(NULL),
2494 mBufferSize(0) {
2495}
2496
2497CallbackThread::~CallbackThread() {
2498 if (mBuffer) {
2499 free(mBuffer);
2500 mBuffer = NULL;
2501 }
2502}
2503
2504bool CallbackThread::threadLoop() {
2505 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
2506 if (sink == NULL) {
2507 return false;
2508 }
2509
2510 if (mBuffer == NULL) {
2511 mBufferSize = sink->bufferSize();
2512 mBuffer = malloc(mBufferSize);
2513 }
2514
2515 size_t actualSize =
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002516 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie,
2517 MediaPlayerBase::AudioSink::CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002518
2519 if (actualSize > 0) {
2520 sink->write(mBuffer, actualSize);
Andy Hunga31335a2014-08-20 17:37:59 -07002521 // Could return false on sink->write() error or short count.
2522 // Not necessarily appropriate but would work for AudioCache behavior.
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002523 }
2524
2525 return true;
2526}
2527
2528////////////////////////////////////////////////////////////////////////////////
2529
Chong Zhange5b9b692017-05-11 11:44:56 -07002530void MediaPlayerService::addBatteryData(uint32_t params) {
2531 mBatteryTracker.addBatteryData(params);
2532}
2533
2534status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
2535 return mBatteryTracker.pullBatteryData(reply);
2536}
2537
2538MediaPlayerService::BatteryTracker::BatteryTracker() {
2539 mBatteryAudio.refCount = 0;
2540 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2541 mBatteryAudio.deviceOn[i] = 0;
2542 mBatteryAudio.lastTime[i] = 0;
2543 mBatteryAudio.totalTime[i] = 0;
2544 }
2545 // speaker is on by default
2546 mBatteryAudio.deviceOn[SPEAKER] = 1;
2547
2548 // reset battery stats
2549 // if the mediaserver has crashed, battery stats could be left
2550 // in bad state, reset the state upon service start.
2551 BatteryNotifier::getInstance().noteResetVideo();
2552}
2553
2554void MediaPlayerService::BatteryTracker::addBatteryData(uint32_t params)
Gloria Wang7cf180c2011-02-19 18:37:57 -08002555{
2556 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002557
2558 int32_t time = systemTime() / 1000000L;
2559
2560 // change audio output devices. This notification comes from AudioFlinger
2561 if ((params & kBatteryDataSpeakerOn)
2562 || (params & kBatteryDataOtherAudioDeviceOn)) {
2563
2564 int deviceOn[NUM_AUDIO_DEVICES];
2565 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2566 deviceOn[i] = 0;
2567 }
2568
2569 if ((params & kBatteryDataSpeakerOn)
2570 && (params & kBatteryDataOtherAudioDeviceOn)) {
2571 deviceOn[SPEAKER_AND_OTHER] = 1;
2572 } else if (params & kBatteryDataSpeakerOn) {
2573 deviceOn[SPEAKER] = 1;
2574 } else {
2575 deviceOn[OTHER_AUDIO_DEVICE] = 1;
2576 }
2577
2578 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2579 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
2580
2581 if (mBatteryAudio.refCount > 0) { // if playing audio
2582 if (!deviceOn[i]) {
2583 mBatteryAudio.lastTime[i] += time;
2584 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2585 mBatteryAudio.lastTime[i] = 0;
2586 } else {
2587 mBatteryAudio.lastTime[i] = 0 - time;
2588 }
2589 }
2590
2591 mBatteryAudio.deviceOn[i] = deviceOn[i];
2592 }
2593 }
2594 return;
2595 }
2596
Marco Nelissenb7848f12014-12-04 08:57:56 -08002597 // an audio stream is started
Gloria Wang9ee159b2011-02-24 14:51:45 -08002598 if (params & kBatteryDataAudioFlingerStart) {
2599 // record the start time only if currently no other audio
2600 // is being played
2601 if (mBatteryAudio.refCount == 0) {
2602 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2603 if (mBatteryAudio.deviceOn[i]) {
2604 mBatteryAudio.lastTime[i] -= time;
2605 }
2606 }
2607 }
2608
2609 mBatteryAudio.refCount ++;
2610 return;
2611
2612 } else if (params & kBatteryDataAudioFlingerStop) {
2613 if (mBatteryAudio.refCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002614 ALOGW("Battery track warning: refCount is <= 0");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002615 return;
2616 }
2617
2618 // record the stop time only if currently this is the only
2619 // audio being played
2620 if (mBatteryAudio.refCount == 1) {
2621 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2622 if (mBatteryAudio.deviceOn[i]) {
2623 mBatteryAudio.lastTime[i] += time;
2624 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2625 mBatteryAudio.lastTime[i] = 0;
2626 }
2627 }
2628 }
2629
2630 mBatteryAudio.refCount --;
2631 return;
2632 }
2633
Andy Hung1afd0982016-11-08 16:13:44 -08002634 uid_t uid = IPCThreadState::self()->getCallingUid();
Gloria Wang7cf180c2011-02-19 18:37:57 -08002635 if (uid == AID_MEDIA) {
2636 return;
2637 }
2638 int index = mBatteryData.indexOfKey(uid);
Gloria Wang7cf180c2011-02-19 18:37:57 -08002639
2640 if (index < 0) { // create a new entry for this UID
2641 BatteryUsageInfo info;
2642 info.audioTotalTime = 0;
2643 info.videoTotalTime = 0;
2644 info.audioLastTime = 0;
2645 info.videoLastTime = 0;
2646 info.refCount = 0;
2647
Gloria Wang9ee159b2011-02-24 14:51:45 -08002648 if (mBatteryData.add(uid, info) == NO_MEMORY) {
Steve Block29357bc2012-01-06 19:20:56 +00002649 ALOGE("Battery track error: no memory for new app");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002650 return;
2651 }
Gloria Wang7cf180c2011-02-19 18:37:57 -08002652 }
2653
2654 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
2655
2656 if (params & kBatteryDataCodecStarted) {
2657 if (params & kBatteryDataTrackAudio) {
2658 info.audioLastTime -= time;
2659 info.refCount ++;
2660 }
2661 if (params & kBatteryDataTrackVideo) {
2662 info.videoLastTime -= time;
2663 info.refCount ++;
2664 }
2665 } else {
2666 if (info.refCount == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002667 ALOGW("Battery track warning: refCount is already 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002668 return;
2669 } else if (info.refCount < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00002670 ALOGE("Battery track error: refCount < 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002671 mBatteryData.removeItem(uid);
2672 return;
2673 }
2674
2675 if (params & kBatteryDataTrackAudio) {
2676 info.audioLastTime += time;
2677 info.refCount --;
2678 }
2679 if (params & kBatteryDataTrackVideo) {
2680 info.videoLastTime += time;
2681 info.refCount --;
2682 }
2683
2684 // no stream is being played by this UID
2685 if (info.refCount == 0) {
2686 info.audioTotalTime += info.audioLastTime;
2687 info.audioLastTime = 0;
2688 info.videoTotalTime += info.videoLastTime;
2689 info.videoLastTime = 0;
2690 }
2691 }
2692}
2693
Chong Zhange5b9b692017-05-11 11:44:56 -07002694status_t MediaPlayerService::BatteryTracker::pullBatteryData(Parcel* reply) {
Gloria Wang7cf180c2011-02-19 18:37:57 -08002695 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002696
2697 // audio output devices usage
2698 int32_t time = systemTime() / 1000000L; //in ms
2699 int32_t totalTime;
2700
2701 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2702 totalTime = mBatteryAudio.totalTime[i];
2703
2704 if (mBatteryAudio.deviceOn[i]
2705 && (mBatteryAudio.lastTime[i] != 0)) {
2706 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
2707 totalTime += tmpTime;
2708 }
2709
2710 reply->writeInt32(totalTime);
2711 // reset the total time
2712 mBatteryAudio.totalTime[i] = 0;
2713 }
2714
2715 // codec usage
Gloria Wang7cf180c2011-02-19 18:37:57 -08002716 BatteryUsageInfo info;
2717 int size = mBatteryData.size();
2718
2719 reply->writeInt32(size);
2720 int i = 0;
2721
2722 while (i < size) {
2723 info = mBatteryData.valueAt(i);
2724
2725 reply->writeInt32(mBatteryData.keyAt(i)); //UID
2726 reply->writeInt32(info.audioTotalTime);
2727 reply->writeInt32(info.videoTotalTime);
2728
2729 info.audioTotalTime = 0;
2730 info.videoTotalTime = 0;
2731
2732 // remove the UID entry where no stream is being played
2733 if (info.refCount <= 0) {
2734 mBatteryData.removeItemsAt(i);
2735 size --;
2736 i --;
2737 }
2738 i++;
2739 }
2740 return NO_ERROR;
2741}
nikoa64c8c72009-07-20 15:07:26 -07002742} // namespace android