blob: 246c746614c331db9be37809b08b21427a440c03 [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>
Dongwon Kangd91dc5a2017-10-10 00:07:09 -070058#include <media/stagefright/InterfaceUtils.h>
Lajos Molnar1381d4b2014-08-07 15:18:35 -070059#include <media/stagefright/MediaCodecList.h>
Eric Laurent9cb839a2011-09-27 09:48:56 -070060#include <media/stagefright/MediaErrors.h>
Marco Nelissen83b0fd92015-09-16 13:48:07 -070061#include <media/stagefright/Utils.h>
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +010062#include <media/stagefright/foundation/ADebug.h>
Marco Nelissenf09611f2015-02-13 14:12:42 -080063#include <media/stagefright/foundation/ALooperRoster.h>
Chong Zhang181fd9b2017-02-16 15:53:03 -080064#include <media/stagefright/SurfaceUtils.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070065#include <mediautils/BatteryNotifier.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080066
Andy Hung53541292016-04-13 16:48:51 -070067#include <memunreachable/memunreachable.h>
Dima Zavin64760242011-05-11 14:15:23 -070068#include <system/audio.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070069
Gloria Wang7cf180c2011-02-19 18:37:57 -080070#include <private/android_filesystem_config.h>
71
James Dong559bf282012-03-28 10:29:14 -070072#include "ActivityManager.h"
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080073#include "MediaRecorderClient.h"
74#include "MediaPlayerService.h"
75#include "MetadataRetrieverClient.h"
John Grossman44a7e422012-06-21 17:29:24 -070076#include "MediaPlayerFactory.h"
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080077
Nicolas Catania14d27472009-07-13 14:37:49 -070078#include "TestPlayerStub.h"
Andreas Huberf9334412010-12-15 15:17:42 -080079#include "nuplayer/NuPlayerDriver.h"
Andreas Huber20111aa2009-07-14 16:56:47 -070080
Andreas Huberb7319a72013-05-29 14:20:52 -070081#include "HTTPBase.h"
Andreas Hubered3e3e02012-03-26 11:13:27 -070082
Wei Jia502c2f42017-07-13 17:47:56 -070083static const int kDumpLockRetries = 50;
84static const int kDumpLockSleepUs = 20000;
85
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070086namespace {
nikoa64c8c72009-07-20 15:07:26 -070087using android::media::Metadata;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070088using android::status_t;
89using android::OK;
90using android::BAD_VALUE;
91using android::NOT_ENOUGH_DATA;
92using android::Parcel;
Ivan Lozano8cf3a072017-08-09 09:01:33 -070093using android::media::VolumeShaper;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070094
95// Max number of entries in the filter.
96const int kMaxFilterSize = 64; // I pulled that out of thin air.
97
Andy Hungff874dc2016-04-11 16:49:09 -070098const float kMaxRequiredSpeed = 8.0f; // for PCM tracks allow up to 8x speedup.
99
nikoa64c8c72009-07-20 15:07:26 -0700100// FIXME: Move all the metadata related function in the Metadata.cpp
nikod608a812009-07-16 16:39:53 -0700101
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700102
103// Unmarshall a filter from a Parcel.
104// Filter format in a parcel:
105//
106// 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
107// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
108// | number of entries (n) |
109// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
110// | metadata type 1 |
111// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
112// | metadata type 2 |
113// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
114// ....
115// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
116// | metadata type n |
117// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
118//
119// @param p Parcel that should start with a filter.
120// @param[out] filter On exit contains the list of metadata type to be
121// filtered.
122// @param[out] status On exit contains the status code to be returned.
123// @return true if the parcel starts with a valid filter.
124bool unmarshallFilter(const Parcel& p,
nikoa64c8c72009-07-20 15:07:26 -0700125 Metadata::Filter *filter,
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700126 status_t *status)
127{
Nicolas Catania48290382009-07-10 13:53:06 -0700128 int32_t val;
129 if (p.readInt32(&val) != OK)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700130 {
Steve Block29357bc2012-01-06 19:20:56 +0000131 ALOGE("Failed to read filter's length");
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700132 *status = NOT_ENOUGH_DATA;
133 return false;
134 }
135
Nicolas Catania48290382009-07-10 13:53:06 -0700136 if( val > kMaxFilterSize || val < 0)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700137 {
Steve Block29357bc2012-01-06 19:20:56 +0000138 ALOGE("Invalid filter len %d", val);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700139 *status = BAD_VALUE;
140 return false;
141 }
142
Nicolas Catania48290382009-07-10 13:53:06 -0700143 const size_t num = val;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700144
145 filter->clear();
Nicolas Catania48290382009-07-10 13:53:06 -0700146 filter->setCapacity(num);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700147
nikoa64c8c72009-07-20 15:07:26 -0700148 size_t size = num * sizeof(Metadata::Type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700149
Nicolas Catania48290382009-07-10 13:53:06 -0700150
151 if (p.dataAvail() < size)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700152 {
Andy Hung833b4752016-04-04 17:15:48 -0700153 ALOGE("Filter too short expected %zu but got %zu", size, p.dataAvail());
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700154 *status = NOT_ENOUGH_DATA;
155 return false;
156 }
157
nikoa64c8c72009-07-20 15:07:26 -0700158 const Metadata::Type *data =
159 static_cast<const Metadata::Type*>(p.readInplace(size));
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700160
Nicolas Catania48290382009-07-10 13:53:06 -0700161 if (NULL == data)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700162 {
Steve Block29357bc2012-01-06 19:20:56 +0000163 ALOGE("Filter had no data");
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700164 *status = BAD_VALUE;
165 return false;
166 }
167
168 // TODO: The stl impl of vector would be more efficient here
169 // because it degenerates into a memcpy on pod types. Try to
170 // replace later or use stl::set.
Nicolas Catania48290382009-07-10 13:53:06 -0700171 for (size_t i = 0; i < num; ++i)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700172 {
Nicolas Catania48290382009-07-10 13:53:06 -0700173 filter->add(*data);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700174 ++data;
175 }
176 *status = OK;
177 return true;
178}
179
Nicolas Catania48290382009-07-10 13:53:06 -0700180// @param filter Of metadata type.
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700181// @param val To be searched.
182// @return true if a match was found.
nikoa64c8c72009-07-20 15:07:26 -0700183bool findMetadata(const Metadata::Filter& filter, const int32_t val)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700184{
185 // Deal with empty and ANY right away
186 if (filter.isEmpty()) return false;
nikoa64c8c72009-07-20 15:07:26 -0700187 if (filter[0] == Metadata::kAny) return true;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700188
Nicolas Catania48290382009-07-10 13:53:06 -0700189 return filter.indexOf(val) >= 0;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700190}
191
192} // anonymous namespace
193
194
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700195namespace {
196using android::Parcel;
197using android::String16;
198
199// marshalling tag indicating flattened utf16 tags
200// keep in sync with frameworks/base/media/java/android/media/AudioAttributes.java
201const int32_t kAudioAttributesMarshallTagFlattenTags = 1;
202
203// Audio attributes format in a parcel:
204//
205// 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
206// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
207// | usage |
208// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
209// | content_type |
210// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Hyejin Kim4f418f92014-09-05 15:50:03 +0900211// | source |
212// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700213// | flags |
214// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
215// | kAudioAttributesMarshallTagFlattenTags | // ignore tags if not found
216// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
217// | flattened tags in UTF16 |
218// | ... |
219// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
220//
221// @param p Parcel that contains audio attributes.
222// @param[out] attributes On exit points to an initialized audio_attributes_t structure
223// @param[out] status On exit contains the status code to be returned.
224void unmarshallAudioAttributes(const Parcel& parcel, audio_attributes_t *attributes)
225{
226 attributes->usage = (audio_usage_t) parcel.readInt32();
227 attributes->content_type = (audio_content_type_t) parcel.readInt32();
Hyejin Kim4f418f92014-09-05 15:50:03 +0900228 attributes->source = (audio_source_t) parcel.readInt32();
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700229 attributes->flags = (audio_flags_mask_t) parcel.readInt32();
230 const bool hasFlattenedTag = (parcel.readInt32() == kAudioAttributesMarshallTagFlattenTags);
231 if (hasFlattenedTag) {
232 // the tags are UTF16, convert to UTF8
233 String16 tags = parcel.readString16();
234 ssize_t realTagSize = utf16_to_utf8_length(tags.string(), tags.size());
235 if (realTagSize <= 0) {
236 strcpy(attributes->tags, "");
237 } else {
238 // copy the flattened string into the attributes as the destination for the conversion:
239 // copying array size -1, array for tags was calloc'd, no need to NULL-terminate it
240 size_t tagSize = realTagSize > AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 ?
241 AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 : realTagSize;
Sergio Giro1d3f4272016-06-28 18:24:52 +0100242 utf16_to_utf8(tags.string(), tagSize, attributes->tags,
243 sizeof(attributes->tags) / sizeof(attributes->tags[0]));
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700244 }
245 } else {
246 ALOGE("unmarshallAudioAttributes() received unflattened tags, ignoring tag values");
247 strcpy(attributes->tags, "");
248 }
249}
250} // anonymous namespace
251
252
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800253namespace android {
254
Marco Nelissenf09611f2015-02-13 14:12:42 -0800255extern ALooperRoster gLooperRoster;
256
257
Dave Burked681bbb2011-08-30 14:39:17 +0100258static bool checkPermission(const char* permissionString) {
Dave Burked681bbb2011-08-30 14:39:17 +0100259 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
260 bool ok = checkCallingPermission(String16(permissionString));
Steve Block29357bc2012-01-06 19:20:56 +0000261 if (!ok) ALOGE("Request requires %s", permissionString);
Dave Burked681bbb2011-08-30 14:39:17 +0100262 return ok;
263}
264
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800265// 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 -0800266/* static */ int MediaPlayerService::AudioOutput::mMinBufferCount = 4;
267/* static */ bool MediaPlayerService::AudioOutput::mIsOnEmulator = false;
268
269void MediaPlayerService::instantiate() {
270 defaultServiceManager()->addService(
271 String16("media.player"), new MediaPlayerService());
272}
273
274MediaPlayerService::MediaPlayerService()
275{
Steve Block3856b092011-10-20 11:56:00 +0100276 ALOGV("MediaPlayerService created");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800277 mNextConnId = 1;
Gloria Wang9ee159b2011-02-24 14:51:45 -0800278
John Grossman44a7e422012-06-21 17:29:24 -0700279 MediaPlayerFactory::registerBuiltinFactories();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800280}
281
282MediaPlayerService::~MediaPlayerService()
283{
Steve Block3856b092011-10-20 11:56:00 +0100284 ALOGV("MediaPlayerService destroyed");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800285}
286
Svet Ganovbe71aa22015-04-28 12:06:02 -0700287sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(const String16 &opPackageName)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800288{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800289 pid_t pid = IPCThreadState::self()->getCallingPid();
Svet Ganovbe71aa22015-04-28 12:06:02 -0700290 sp<MediaRecorderClient> recorder = new MediaRecorderClient(this, pid, opPackageName);
Gloria Wangdac6a312009-10-29 15:46:37 -0700291 wp<MediaRecorderClient> w = recorder;
292 Mutex::Autolock lock(mLock);
293 mMediaRecorderClients.add(w);
Steve Block3856b092011-10-20 11:56:00 +0100294 ALOGV("Create new media recorder client from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800295 return recorder;
296}
297
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -0700298void MediaPlayerService::removeMediaRecorderClient(const wp<MediaRecorderClient>& client)
Gloria Wangdac6a312009-10-29 15:46:37 -0700299{
300 Mutex::Autolock lock(mLock);
301 mMediaRecorderClients.remove(client);
Steve Block3856b092011-10-20 11:56:00 +0100302 ALOGV("Delete media recorder client");
Gloria Wangdac6a312009-10-29 15:46:37 -0700303}
304
Glenn Kastenf37971f2012-02-03 11:06:53 -0800305sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800306{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800307 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800308 sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
Steve Block3856b092011-10-20 11:56:00 +0100309 ALOGV("Create new media retriever from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800310 return retriever;
311}
312
Glenn Kastenf37971f2012-02-03 11:06:53 -0800313sp<IMediaPlayer> MediaPlayerService::create(const sp<IMediaPlayerClient>& client,
Glenn Kastend848eb42016-03-08 13:42:11 -0800314 audio_session_t audioSessionId)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800315{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800316 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800317 int32_t connId = android_atomic_inc(&mNextConnId);
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700318
319 sp<Client> c = new Client(
320 this, pid, connId, client, audioSessionId,
321 IPCThreadState::self()->getCallingUid());
322
Steve Block3856b092011-10-20 11:56:00 +0100323 ALOGV("Create new client(%d) from pid %d, uid %d, ", connId, pid,
Dave Burked681bbb2011-08-30 14:39:17 +0100324 IPCThreadState::self()->getCallingUid());
325
326 wp<Client> w = c;
327 {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800328 Mutex::Autolock lock(mLock);
329 mClients.add(w);
330 }
Andreas Hubere2b10282010-11-23 11:41:34 -0800331 return c;
332}
333
Lajos Molnar1381d4b2014-08-07 15:18:35 -0700334sp<IMediaCodecList> MediaPlayerService::getCodecList() const {
335 return MediaCodecList::getLocalInstance();
336}
337
Jeff Brown2013a542012-09-04 21:38:42 -0700338sp<IRemoteDisplay> MediaPlayerService::listenForRemoteDisplay(
Chong Zhangd0a98fa2017-09-14 17:43:10 -0700339 const String16 &/*opPackageName*/,
340 const sp<IRemoteDisplayClient>& /*client*/,
341 const String8& /*iface*/) {
342 ALOGE("listenForRemoteDisplay is no longer supported!");
Jeff Brownaba33d52012-09-07 17:38:58 -0700343
Chong Zhangd0a98fa2017-09-14 17:43:10 -0700344 return NULL;
Jeff Brown2013a542012-09-04 21:38:42 -0700345}
346
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800347status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
348{
349 const size_t SIZE = 256;
350 char buffer[SIZE];
351 String8 result;
352
353 result.append(" AudioOutput\n");
354 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n",
355 mStreamType, mLeftVolume, mRightVolume);
356 result.append(buffer);
357 snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n",
Eric Laurentdb354e52012-03-05 17:27:11 -0800358 mMsecsPerFrame, (mTrack != 0) ? mTrack->latency() : -1);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800359 result.append(buffer);
Eric Laurent2beeb502010-07-16 07:43:46 -0700360 snprintf(buffer, 255, " aux effect id(%d), send level (%f)\n",
361 mAuxEffectId, mSendLevel);
362 result.append(buffer);
363
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800364 ::write(fd, result.string(), result.size());
365 if (mTrack != 0) {
366 mTrack->dump(fd, args);
367 }
368 return NO_ERROR;
369}
370
Lajos Molnar6d339f12015-04-17 16:15:53 -0700371status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800372{
373 const size_t SIZE = 256;
374 char buffer[SIZE];
375 String8 result;
376 result.append(" Client\n");
377 snprintf(buffer, 255, " pid(%d), connId(%d), status(%d), looping(%s)\n",
378 mPid, mConnId, mStatus, mLoop?"true": "false");
379 result.append(buffer);
Wei Jia502c2f42017-07-13 17:47:56 -0700380
381 sp<MediaPlayerBase> p;
382 sp<AudioOutput> audioOutput;
383 bool locked = false;
384 for (int i = 0; i < kDumpLockRetries; ++i) {
385 if (mLock.tryLock() == NO_ERROR) {
386 locked = true;
387 break;
388 }
389 usleep(kDumpLockSleepUs);
Andreas Hubera0b1d4b2011-06-07 15:52:25 -0700390 }
Wei Jia502c2f42017-07-13 17:47:56 -0700391
392 if (locked) {
393 p = mPlayer;
394 audioOutput = mAudioOutput;
395 mLock.unlock();
396 } else {
397 result.append(" lock is taken, no dump from player and audio output\n");
398 }
399 write(fd, result.string(), result.size());
400
401 if (p != NULL) {
402 p->dump(fd, args);
403 }
404 if (audioOutput != 0) {
405 audioOutput->dump(fd, args);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800406 }
407 write(fd, "\n", 1);
408 return NO_ERROR;
409}
410
Marco Nelissenf09611f2015-02-13 14:12:42 -0800411/**
412 * The only arguments this understands right now are -c, -von and -voff,
413 * which are parsed by ALooperRoster::dump()
414 */
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800415status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
416{
417 const size_t SIZE = 256;
418 char buffer[SIZE];
419 String8 result;
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530420 SortedVector< sp<Client> > clients; //to serialise the mutex unlock & client destruction.
421 SortedVector< sp<MediaRecorderClient> > mediaRecorderClients;
422
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800423 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
424 snprintf(buffer, SIZE, "Permission Denial: "
425 "can't dump MediaPlayerService from pid=%d, uid=%d\n",
426 IPCThreadState::self()->getCallingPid(),
427 IPCThreadState::self()->getCallingUid());
428 result.append(buffer);
429 } else {
430 Mutex::Autolock lock(mLock);
431 for (int i = 0, n = mClients.size(); i < n; ++i) {
432 sp<Client> c = mClients[i].promote();
433 if (c != 0) c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530434 clients.add(c);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800435 }
James Dongb9141222010-07-08 11:16:11 -0700436 if (mMediaRecorderClients.size() == 0) {
437 result.append(" No media recorder client\n\n");
438 } else {
439 for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
440 sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
James Donge579e282011-10-18 22:29:20 -0700441 if (c != 0) {
442 snprintf(buffer, 255, " MediaRecorderClient pid(%d)\n", c->mPid);
443 result.append(buffer);
444 write(fd, result.string(), result.size());
445 result = "\n";
446 c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530447 mediaRecorderClients.add(c);
James Donge579e282011-10-18 22:29:20 -0700448 }
James Dongb9141222010-07-08 11:16:11 -0700449 }
Gloria Wangdac6a312009-10-29 15:46:37 -0700450 }
451
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800452 result.append(" Files opened and/or mapped:\n");
Marco Nelissenf09611f2015-02-13 14:12:42 -0800453 snprintf(buffer, SIZE, "/proc/%d/maps", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800454 FILE *f = fopen(buffer, "r");
455 if (f) {
456 while (!feof(f)) {
457 fgets(buffer, SIZE, f);
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700458 if (strstr(buffer, " /storage/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800459 strstr(buffer, " /system/sounds/") ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700460 strstr(buffer, " /data/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800461 strstr(buffer, " /system/media/")) {
462 result.append(" ");
463 result.append(buffer);
464 }
465 }
466 fclose(f);
467 } else {
468 result.append("couldn't open ");
469 result.append(buffer);
470 result.append("\n");
471 }
472
Marco Nelissenf09611f2015-02-13 14:12:42 -0800473 snprintf(buffer, SIZE, "/proc/%d/fd", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800474 DIR *d = opendir(buffer);
475 if (d) {
476 struct dirent *ent;
477 while((ent = readdir(d)) != NULL) {
478 if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
Marco Nelissenf09611f2015-02-13 14:12:42 -0800479 snprintf(buffer, SIZE, "/proc/%d/fd/%s", getpid(), ent->d_name);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800480 struct stat s;
481 if (lstat(buffer, &s) == 0) {
482 if ((s.st_mode & S_IFMT) == S_IFLNK) {
483 char linkto[256];
484 int len = readlink(buffer, linkto, sizeof(linkto));
485 if(len > 0) {
486 if(len > 255) {
487 linkto[252] = '.';
488 linkto[253] = '.';
489 linkto[254] = '.';
490 linkto[255] = 0;
491 } else {
492 linkto[len] = 0;
493 }
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700494 if (strstr(linkto, "/storage/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800495 strstr(linkto, "/system/sounds/") == linkto ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700496 strstr(linkto, "/data/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800497 strstr(linkto, "/system/media/") == linkto) {
498 result.append(" ");
499 result.append(buffer);
500 result.append(" -> ");
501 result.append(linkto);
502 result.append("\n");
503 }
504 }
505 } else {
506 result.append(" unexpected type for ");
507 result.append(buffer);
508 result.append("\n");
509 }
510 }
511 }
512 }
513 closedir(d);
514 } else {
515 result.append("couldn't open ");
516 result.append(buffer);
517 result.append("\n");
518 }
519
Marco Nelissenf09611f2015-02-13 14:12:42 -0800520 gLooperRoster.dump(fd, args);
521
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800522 bool dumpMem = false;
Andy Hung53541292016-04-13 16:48:51 -0700523 bool unreachableMemory = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800524 for (size_t i = 0; i < args.size(); i++) {
525 if (args[i] == String16("-m")) {
526 dumpMem = true;
Andy Hung53541292016-04-13 16:48:51 -0700527 } else if (args[i] == String16("--unreachable")) {
528 unreachableMemory = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800529 }
530 }
531 if (dumpMem) {
Andy Hung07b745e2016-05-23 16:21:07 -0700532 result.append("\nDumping memory:\n");
533 std::string s = dumpMemoryAddresses(100 /* limit */);
534 result.append(s.c_str(), s.size());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800535 }
Andy Hung53541292016-04-13 16:48:51 -0700536 if (unreachableMemory) {
537 result.append("\nDumping unreachable memory:\n");
538 // TODO - should limit be an argument parameter?
539 std::string s = GetUnreachableMemoryString(true /* contents */, 10000 /* limit */);
540 result.append(s.c_str(), s.size());
541 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800542 }
543 write(fd, result.string(), result.size());
544 return NO_ERROR;
545}
546
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -0700547void MediaPlayerService::removeClient(const wp<Client>& client)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800548{
549 Mutex::Autolock lock(mLock);
550 mClients.remove(client);
551}
552
Robert Shihee0a0e32016-08-16 16:50:54 -0700553bool MediaPlayerService::hasClient(wp<Client> client)
554{
555 Mutex::Autolock lock(mLock);
556 return mClients.indexOf(client) != NAME_NOT_FOUND;
557}
558
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700559MediaPlayerService::Client::Client(
560 const sp<MediaPlayerService>& service, pid_t pid,
561 int32_t connId, const sp<IMediaPlayerClient>& client,
Glenn Kastend848eb42016-03-08 13:42:11 -0800562 audio_session_t audioSessionId, uid_t uid)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800563{
Steve Block3856b092011-10-20 11:56:00 +0100564 ALOGV("Client(%d) constructor", connId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800565 mPid = pid;
566 mConnId = connId;
567 mService = service;
568 mClient = client;
569 mLoop = false;
570 mStatus = NO_INIT;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700571 mAudioSessionId = audioSessionId;
Andy Hung1afd0982016-11-08 16:13:44 -0800572 mUid = uid;
John Grossmanc795b642012-02-22 15:38:35 -0800573 mRetransmitEndpointValid = false;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700574 mAudioAttributes = NULL;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700575
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800576#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000577 ALOGD("create Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800578 mAntagonizer = new Antagonizer(notify, this);
579#endif
580}
581
582MediaPlayerService::Client::~Client()
583{
Steve Block3856b092011-10-20 11:56:00 +0100584 ALOGV("Client(%d) destructor pid = %d", mConnId, mPid);
Wei Jia502c2f42017-07-13 17:47:56 -0700585 {
586 Mutex::Autolock l(mLock);
587 mAudioOutput.clear();
588 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800589 wp<Client> client(this);
590 disconnect();
591 mService->removeClient(client);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700592 if (mAudioAttributes != NULL) {
593 free(mAudioAttributes);
594 }
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800595 clearDeathNotifiers();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800596}
597
598void MediaPlayerService::Client::disconnect()
599{
Steve Block3856b092011-10-20 11:56:00 +0100600 ALOGV("disconnect(%d) from pid %d", mConnId, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800601 // grab local reference and clear main reference to prevent future
602 // access to object
603 sp<MediaPlayerBase> p;
604 {
605 Mutex::Autolock l(mLock);
606 p = mPlayer;
beanzdcfefde2012-11-05 09:51:43 +0800607 mClient.clear();
Wei Jia502c2f42017-07-13 17:47:56 -0700608 mPlayer.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800609 }
Andreas Huber20111aa2009-07-14 16:56:47 -0700610
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800611 // clear the notification to prevent callbacks to dead client
612 // and reset the player. We assume the player will serialize
613 // access to itself if necessary.
614 if (p != 0) {
615 p->setNotifyCallback(0, 0);
616#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000617 ALOGD("kill Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800618 mAntagonizer->kill();
619#endif
620 p->reset();
621 }
622
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700623 disconnectNativeWindow();
624
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800625 IPCThreadState::self()->flushCommands();
626}
627
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800628sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
629{
630 // determine if we have the right player type
Wei Jia502c2f42017-07-13 17:47:56 -0700631 sp<MediaPlayerBase> p = getPlayer();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800632 if ((p != NULL) && (p->playerType() != playerType)) {
Steve Block3856b092011-10-20 11:56:00 +0100633 ALOGV("delete player");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800634 p.clear();
635 }
636 if (p == NULL) {
Ronghua Wu68845c12015-07-21 09:50:48 -0700637 p = MediaPlayerFactory::createPlayer(playerType, this, notify, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800638 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700639
Jason Simmonsdb29e522011-08-12 13:46:55 -0700640 if (p != NULL) {
Andy Hung1afd0982016-11-08 16:13:44 -0800641 p->setUID(mUid);
Jason Simmonsdb29e522011-08-12 13:46:55 -0700642 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700643
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800644 return p;
645}
646
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700647MediaPlayerService::Client::ServiceDeathNotifier::ServiceDeathNotifier(
648 const sp<IBinder>& service,
649 const sp<MediaPlayerBase>& listener,
650 int which) {
651 mService = service;
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800652 mOmx = nullptr;
653 mListener = listener;
654 mWhich = which;
655}
656
657MediaPlayerService::Client::ServiceDeathNotifier::ServiceDeathNotifier(
658 const sp<IOmx>& omx,
659 const sp<MediaPlayerBase>& listener,
660 int which) {
661 mService = nullptr;
662 mOmx = omx;
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700663 mListener = listener;
664 mWhich = which;
665}
666
667MediaPlayerService::Client::ServiceDeathNotifier::~ServiceDeathNotifier() {
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700668}
669
670void MediaPlayerService::Client::ServiceDeathNotifier::binderDied(const wp<IBinder>& /*who*/) {
671 sp<MediaPlayerBase> listener = mListener.promote();
672 if (listener != NULL) {
673 listener->sendEvent(MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED, mWhich);
674 } else {
675 ALOGW("listener for process %d death is gone", mWhich);
676 }
677}
678
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800679void MediaPlayerService::Client::ServiceDeathNotifier::serviceDied(
680 uint64_t /* cookie */,
681 const wp<::android::hidl::base::V1_0::IBase>& /* who */) {
682 sp<MediaPlayerBase> listener = mListener.promote();
683 if (listener != NULL) {
684 listener->sendEvent(MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED, mWhich);
685 } else {
686 ALOGW("listener for process %d death is gone", mWhich);
687 }
688}
689
690void MediaPlayerService::Client::ServiceDeathNotifier::unlinkToDeath() {
691 if (mService != nullptr) {
692 mService->unlinkToDeath(this);
693 mService = nullptr;
694 } else if (mOmx != nullptr) {
695 mOmx->unlinkToDeath(this);
696 mOmx = nullptr;
697 }
698}
699
700void MediaPlayerService::Client::clearDeathNotifiers() {
701 if (mExtractorDeathListener != nullptr) {
702 mExtractorDeathListener->unlinkToDeath();
703 mExtractorDeathListener = nullptr;
704 }
705 if (mCodecDeathListener != nullptr) {
706 mCodecDeathListener->unlinkToDeath();
707 mCodecDeathListener = nullptr;
708 }
709}
710
John Grossmanc795b642012-02-22 15:38:35 -0800711sp<MediaPlayerBase> MediaPlayerService::Client::setDataSource_pre(
712 player_type playerType)
713{
714 ALOGV("player type = %d", playerType);
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800715 clearDeathNotifiers();
John Grossmanc795b642012-02-22 15:38:35 -0800716
717 // create the right type of player
718 sp<MediaPlayerBase> p = createPlayer(playerType);
719 if (p == NULL) {
720 return p;
721 }
722
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700723 sp<IServiceManager> sm = defaultServiceManager();
724 sp<IBinder> binder = sm->getService(String16("media.extractor"));
Marco Nelissen1b5a7ee2016-09-30 13:54:30 -0700725 if (binder == NULL) {
726 ALOGE("extractor service not available");
727 return NULL;
728 }
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700729 mExtractorDeathListener = new ServiceDeathNotifier(binder, p, MEDIAEXTRACTOR_PROCESS_DEATH);
730 binder->linkToDeath(mExtractorDeathListener);
731
Colin Cross85e88d92017-10-26 16:16:55 -0700732 if (property_get_bool("persist.media.treble_omx", true)) {
733 // Treble IOmx
734 sp<IOmx> omx = IOmx::getService();
735 if (omx == nullptr) {
736 ALOGE("Treble IOmx not available");
737 return NULL;
738 }
739 mCodecDeathListener = new ServiceDeathNotifier(omx, p, MEDIACODEC_PROCESS_DEATH);
740 omx->linkToDeath(mCodecDeathListener, 0);
741 } else {
742 // Legacy IOMX
743 binder = sm->getService(String16("media.codec"));
744 if (binder == NULL) {
745 ALOGE("codec service not available");
746 return NULL;
747 }
748 mCodecDeathListener = new ServiceDeathNotifier(binder, p, MEDIACODEC_PROCESS_DEATH);
749 binder->linkToDeath(mCodecDeathListener);
Marco Nelissen1b5a7ee2016-09-30 13:54:30 -0700750 }
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700751
John Grossmanc795b642012-02-22 15:38:35 -0800752 if (!p->hardwareOutput()) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -0700753 Mutex::Autolock l(mLock);
Marco Nelissend457c972014-02-11 08:47:07 -0800754 mAudioOutput = new AudioOutput(mAudioSessionId, IPCThreadState::self()->getCallingUid(),
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700755 mPid, mAudioAttributes);
John Grossmanc795b642012-02-22 15:38:35 -0800756 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
757 }
758
759 return p;
760}
761
762void MediaPlayerService::Client::setDataSource_post(
763 const sp<MediaPlayerBase>& p,
764 status_t status)
765{
766 ALOGV(" setDataSource");
767 mStatus = status;
768 if (mStatus != OK) {
769 ALOGE(" error: %d", mStatus);
770 return;
771 }
772
773 // Set the re-transmission endpoint if one was chosen.
774 if (mRetransmitEndpointValid) {
775 mStatus = p->setRetransmitEndpoint(&mRetransmitEndpoint);
776 if (mStatus != NO_ERROR) {
777 ALOGE("setRetransmitEndpoint error: %d", mStatus);
778 }
779 }
780
781 if (mStatus == OK) {
Wei Jia502c2f42017-07-13 17:47:56 -0700782 Mutex::Autolock l(mLock);
John Grossmanc795b642012-02-22 15:38:35 -0800783 mPlayer = p;
784 }
785}
786
Andreas Huber2db84552010-01-28 11:19:57 -0800787status_t MediaPlayerService::Client::setDataSource(
Andreas Huber1b86fe02014-01-29 11:13:26 -0800788 const sp<IMediaHTTPService> &httpService,
789 const char *url,
790 const KeyedVector<String8, String8> *headers)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800791{
Steve Block3856b092011-10-20 11:56:00 +0100792 ALOGV("setDataSource(%s)", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800793 if (url == NULL)
794 return UNKNOWN_ERROR;
795
Dave Burked681bbb2011-08-30 14:39:17 +0100796 if ((strncmp(url, "http://", 7) == 0) ||
797 (strncmp(url, "https://", 8) == 0) ||
798 (strncmp(url, "rtsp://", 7) == 0)) {
799 if (!checkPermission("android.permission.INTERNET")) {
800 return PERMISSION_DENIED;
801 }
802 }
803
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800804 if (strncmp(url, "content://", 10) == 0) {
805 // get a filedescriptor for the content Uri and
806 // pass it to the setDataSource(fd) method
807
808 String16 url16(url);
809 int fd = android::openContentProviderFile(url16);
810 if (fd < 0)
811 {
Steve Block29357bc2012-01-06 19:20:56 +0000812 ALOGE("Couldn't open fd for %s", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800813 return UNKNOWN_ERROR;
814 }
815 setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
816 close(fd);
817 return mStatus;
818 } else {
John Grossman44a7e422012-06-21 17:29:24 -0700819 player_type playerType = MediaPlayerFactory::getPlayerType(this, url);
John Grossmanc795b642012-02-22 15:38:35 -0800820 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
821 if (p == NULL) {
822 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800823 }
824
Andreas Huber1b86fe02014-01-29 11:13:26 -0800825 setDataSource_post(p, p->setDataSource(httpService, url, headers));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800826 return mStatus;
827 }
828}
829
830status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
831{
Marco Nelissen83b0fd92015-09-16 13:48:07 -0700832 ALOGV("setDataSource fd=%d (%s), offset=%lld, length=%lld",
833 fd, nameForFd(fd).c_str(), (long long) offset, (long long) length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800834 struct stat sb;
835 int ret = fstat(fd, &sb);
836 if (ret != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000837 ALOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800838 return UNKNOWN_ERROR;
839 }
840
Andy Hung833b4752016-04-04 17:15:48 -0700841 ALOGV("st_dev = %llu", static_cast<unsigned long long>(sb.st_dev));
Steve Block3856b092011-10-20 11:56:00 +0100842 ALOGV("st_mode = %u", sb.st_mode);
Mark Salyzyn77342f72014-06-18 16:31:32 -0700843 ALOGV("st_uid = %lu", static_cast<unsigned long>(sb.st_uid));
844 ALOGV("st_gid = %lu", static_cast<unsigned long>(sb.st_gid));
Andy Hung833b4752016-04-04 17:15:48 -0700845 ALOGV("st_size = %llu", static_cast<unsigned long long>(sb.st_size));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800846
847 if (offset >= sb.st_size) {
Steve Block29357bc2012-01-06 19:20:56 +0000848 ALOGE("offset error");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800849 return UNKNOWN_ERROR;
850 }
851 if (offset + length > sb.st_size) {
852 length = sb.st_size - offset;
Andy Hung833b4752016-04-04 17:15:48 -0700853 ALOGV("calculated length = %lld", (long long)length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800854 }
855
John Grossman44a7e422012-06-21 17:29:24 -0700856 player_type playerType = MediaPlayerFactory::getPlayerType(this,
857 fd,
858 offset,
859 length);
John Grossmanc795b642012-02-22 15:38:35 -0800860 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
861 if (p == NULL) {
862 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800863 }
864
865 // now set data source
John Grossmanc795b642012-02-22 15:38:35 -0800866 setDataSource_post(p, p->setDataSource(fd, offset, length));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800867 return mStatus;
868}
869
Andreas Hubere2b10282010-11-23 11:41:34 -0800870status_t MediaPlayerService::Client::setDataSource(
871 const sp<IStreamSource> &source) {
872 // create the right type of player
John Grossman44a7e422012-06-21 17:29:24 -0700873 player_type playerType = MediaPlayerFactory::getPlayerType(this, source);
John Grossmanc795b642012-02-22 15:38:35 -0800874 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
Andreas Hubere2b10282010-11-23 11:41:34 -0800875 if (p == NULL) {
876 return NO_INIT;
877 }
878
Andreas Hubere2b10282010-11-23 11:41:34 -0800879 // now set data source
John Grossmanc795b642012-02-22 15:38:35 -0800880 setDataSource_post(p, p->setDataSource(source));
Andreas Hubere2b10282010-11-23 11:41:34 -0800881 return mStatus;
882}
883
Chris Watkins99f31602015-03-20 13:06:33 -0700884status_t MediaPlayerService::Client::setDataSource(
885 const sp<IDataSource> &source) {
Dongwon Kangd91dc5a2017-10-10 00:07:09 -0700886 sp<DataSource> dataSource = CreateDataSourceFromIDataSource(source);
Chris Watkins99f31602015-03-20 13:06:33 -0700887 player_type playerType = MediaPlayerFactory::getPlayerType(this, dataSource);
888 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
889 if (p == NULL) {
890 return NO_INIT;
891 }
892 // now set data source
893 setDataSource_post(p, p->setDataSource(dataSource));
894 return mStatus;
895}
896
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700897void MediaPlayerService::Client::disconnectNativeWindow() {
898 if (mConnectedWindow != NULL) {
Chong Zhang181fd9b2017-02-16 15:53:03 -0800899 status_t err = nativeWindowDisconnect(
900 mConnectedWindow.get(), "disconnectNativeWindow");
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700901
902 if (err != OK) {
Chong Zhang181fd9b2017-02-16 15:53:03 -0800903 ALOGW("nativeWindowDisconnect returned an error: %s (%d)",
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700904 strerror(-err), err);
905 }
906 }
907 mConnectedWindow.clear();
908}
909
Glenn Kasten11731182011-02-08 17:26:17 -0800910status_t MediaPlayerService::Client::setVideoSurfaceTexture(
Andy McFadden484566c2012-12-18 09:46:54 -0800911 const sp<IGraphicBufferProducer>& bufferProducer)
Glenn Kasten11731182011-02-08 17:26:17 -0800912{
Andy McFadden484566c2012-12-18 09:46:54 -0800913 ALOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, bufferProducer.get());
Glenn Kasten11731182011-02-08 17:26:17 -0800914 sp<MediaPlayerBase> p = getPlayer();
915 if (p == 0) return UNKNOWN_ERROR;
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700916
Marco Nelissenf8880202014-11-14 07:58:25 -0800917 sp<IBinder> binder(IInterface::asBinder(bufferProducer));
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700918 if (mConnectedWindowBinder == binder) {
919 return OK;
920 }
921
922 sp<ANativeWindow> anw;
Andy McFadden484566c2012-12-18 09:46:54 -0800923 if (bufferProducer != NULL) {
Marco Nelissenee08f7e2013-09-16 13:30:01 -0700924 anw = new Surface(bufferProducer, true /* controlledByApp */);
Chong Zhang181fd9b2017-02-16 15:53:03 -0800925 status_t err = nativeWindowConnect(anw.get(), "setVideoSurfaceTexture");
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700926
927 if (err != OK) {
Steve Block29357bc2012-01-06 19:20:56 +0000928 ALOGE("setVideoSurfaceTexture failed: %d", err);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700929 // Note that we must do the reset before disconnecting from the ANW.
930 // Otherwise queue/dequeue calls could be made on the disconnected
931 // ANW, which may result in errors.
932 reset();
933
934 disconnectNativeWindow();
935
936 return err;
937 }
938 }
939
Andy McFadden484566c2012-12-18 09:46:54 -0800940 // Note that we must set the player's new GraphicBufferProducer before
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700941 // disconnecting the old one. Otherwise queue/dequeue calls could be made
942 // on the disconnected ANW, which may result in errors.
Andy McFadden484566c2012-12-18 09:46:54 -0800943 status_t err = p->setVideoSurfaceTexture(bufferProducer);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700944
945 disconnectNativeWindow();
946
947 mConnectedWindow = anw;
948
949 if (err == OK) {
950 mConnectedWindowBinder = binder;
951 } else {
952 disconnectNativeWindow();
953 }
954
955 return err;
Glenn Kasten11731182011-02-08 17:26:17 -0800956}
957
Nicolas Catania1d187f12009-05-12 23:25:55 -0700958status_t MediaPlayerService::Client::invoke(const Parcel& request,
959 Parcel *reply)
960{
961 sp<MediaPlayerBase> p = getPlayer();
962 if (p == NULL) return UNKNOWN_ERROR;
963 return p->invoke(request, reply);
964}
965
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700966// This call doesn't need to access the native player.
967status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
968{
969 status_t status;
nikoa64c8c72009-07-20 15:07:26 -0700970 media::Metadata::Filter allow, drop;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700971
Nicolas Catania48290382009-07-10 13:53:06 -0700972 if (unmarshallFilter(filter, &allow, &status) &&
973 unmarshallFilter(filter, &drop, &status)) {
974 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700975
976 mMetadataAllow = allow;
977 mMetadataDrop = drop;
978 }
979 return status;
980}
981
Nicolas Catania48290382009-07-10 13:53:06 -0700982status_t MediaPlayerService::Client::getMetadata(
Mark Salyzyn77342f72014-06-18 16:31:32 -0700983 bool update_only, bool /*apply_filter*/, Parcel *reply)
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700984{
nikoa64c8c72009-07-20 15:07:26 -0700985 sp<MediaPlayerBase> player = getPlayer();
986 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania48290382009-07-10 13:53:06 -0700987
nikod608a812009-07-16 16:39:53 -0700988 status_t status;
989 // Placeholder for the return code, updated by the caller.
990 reply->writeInt32(-1);
991
nikoa64c8c72009-07-20 15:07:26 -0700992 media::Metadata::Filter ids;
Nicolas Catania48290382009-07-10 13:53:06 -0700993
994 // We don't block notifications while we fetch the data. We clear
995 // mMetadataUpdated first so we don't lose notifications happening
996 // during the rest of this call.
997 {
998 Mutex::Autolock lock(mLock);
999 if (update_only) {
nikod608a812009-07-16 16:39:53 -07001000 ids = mMetadataUpdated;
Nicolas Catania48290382009-07-10 13:53:06 -07001001 }
1002 mMetadataUpdated.clear();
1003 }
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001004
nikoa64c8c72009-07-20 15:07:26 -07001005 media::Metadata metadata(reply);
Nicolas Catania48290382009-07-10 13:53:06 -07001006
nikoa64c8c72009-07-20 15:07:26 -07001007 metadata.appendHeader();
1008 status = player->getMetadata(ids, reply);
nikod608a812009-07-16 16:39:53 -07001009
1010 if (status != OK) {
nikoa64c8c72009-07-20 15:07:26 -07001011 metadata.resetParcel();
Steve Block29357bc2012-01-06 19:20:56 +00001012 ALOGE("getMetadata failed %d", status);
nikod608a812009-07-16 16:39:53 -07001013 return status;
1014 }
1015
1016 // FIXME: Implement filtering on the result. Not critical since
1017 // filtering takes place on the update notifications already. This
1018 // would be when all the metadata are fetch and a filter is set.
1019
nikod608a812009-07-16 16:39:53 -07001020 // Everything is fine, update the metadata length.
nikoa64c8c72009-07-20 15:07:26 -07001021 metadata.updateLength();
nikod608a812009-07-16 16:39:53 -07001022 return OK;
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001023}
1024
Wei Jiad399e7e2016-10-26 15:49:11 -07001025status_t MediaPlayerService::Client::setBufferingSettings(
1026 const BufferingSettings& buffering)
1027{
Wei Jiadc6f3402017-01-09 15:04:18 -08001028 ALOGV("[%d] setBufferingSettings{%s}",
1029 mConnId, buffering.toString().string());
Wei Jiad399e7e2016-10-26 15:49:11 -07001030 sp<MediaPlayerBase> p = getPlayer();
1031 if (p == 0) return UNKNOWN_ERROR;
1032 return p->setBufferingSettings(buffering);
1033}
1034
1035status_t MediaPlayerService::Client::getDefaultBufferingSettings(
1036 BufferingSettings* buffering /* nonnull */)
1037{
1038 sp<MediaPlayerBase> p = getPlayer();
1039 // TODO: create mPlayer on demand.
1040 if (p == 0) return UNKNOWN_ERROR;
1041 status_t ret = p->getDefaultBufferingSettings(buffering);
1042 if (ret == NO_ERROR) {
Wei Jiadc6f3402017-01-09 15:04:18 -08001043 ALOGV("[%d] getDefaultBufferingSettings{%s}",
1044 mConnId, buffering->toString().string());
Wei Jiad399e7e2016-10-26 15:49:11 -07001045 } else {
1046 ALOGV("[%d] getDefaultBufferingSettings returned %d", mConnId, ret);
1047 }
1048 return ret;
1049}
1050
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001051status_t MediaPlayerService::Client::prepareAsync()
1052{
Steve Block3856b092011-10-20 11:56:00 +01001053 ALOGV("[%d] prepareAsync", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001054 sp<MediaPlayerBase> p = getPlayer();
1055 if (p == 0) return UNKNOWN_ERROR;
1056 status_t ret = p->prepareAsync();
1057#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +00001058 ALOGD("start Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001059 if (ret == NO_ERROR) mAntagonizer->start();
1060#endif
1061 return ret;
1062}
1063
1064status_t MediaPlayerService::Client::start()
1065{
Steve Block3856b092011-10-20 11:56:00 +01001066 ALOGV("[%d] start", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001067 sp<MediaPlayerBase> p = getPlayer();
1068 if (p == 0) return UNKNOWN_ERROR;
1069 p->setLooping(mLoop);
1070 return p->start();
1071}
1072
1073status_t MediaPlayerService::Client::stop()
1074{
Steve Block3856b092011-10-20 11:56:00 +01001075 ALOGV("[%d] stop", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001076 sp<MediaPlayerBase> p = getPlayer();
1077 if (p == 0) return UNKNOWN_ERROR;
1078 return p->stop();
1079}
1080
1081status_t MediaPlayerService::Client::pause()
1082{
Steve Block3856b092011-10-20 11:56:00 +01001083 ALOGV("[%d] pause", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001084 sp<MediaPlayerBase> p = getPlayer();
1085 if (p == 0) return UNKNOWN_ERROR;
1086 return p->pause();
1087}
1088
1089status_t MediaPlayerService::Client::isPlaying(bool* state)
1090{
1091 *state = false;
1092 sp<MediaPlayerBase> p = getPlayer();
1093 if (p == 0) return UNKNOWN_ERROR;
1094 *state = p->isPlaying();
Steve Block3856b092011-10-20 11:56:00 +01001095 ALOGV("[%d] isPlaying: %d", mConnId, *state);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001096 return NO_ERROR;
1097}
1098
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001099status_t MediaPlayerService::Client::setPlaybackSettings(const AudioPlaybackRate& rate)
Wei Jia98160162015-02-04 17:01:11 -08001100{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001101 ALOGV("[%d] setPlaybackSettings(%f, %f, %d, %d)",
1102 mConnId, rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Wei Jia98160162015-02-04 17:01:11 -08001103 sp<MediaPlayerBase> p = getPlayer();
1104 if (p == 0) return UNKNOWN_ERROR;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001105 return p->setPlaybackSettings(rate);
1106}
1107
1108status_t MediaPlayerService::Client::getPlaybackSettings(AudioPlaybackRate* rate /* nonnull */)
1109{
1110 sp<MediaPlayerBase> p = getPlayer();
1111 if (p == 0) return UNKNOWN_ERROR;
1112 status_t ret = p->getPlaybackSettings(rate);
1113 if (ret == NO_ERROR) {
1114 ALOGV("[%d] getPlaybackSettings(%f, %f, %d, %d)",
1115 mConnId, rate->mSpeed, rate->mPitch, rate->mFallbackMode, rate->mStretchMode);
1116 } else {
1117 ALOGV("[%d] getPlaybackSettings returned %d", mConnId, ret);
1118 }
1119 return ret;
1120}
1121
1122status_t MediaPlayerService::Client::setSyncSettings(
1123 const AVSyncSettings& sync, float videoFpsHint)
1124{
1125 ALOGV("[%d] setSyncSettings(%u, %u, %f, %f)",
1126 mConnId, sync.mSource, sync.mAudioAdjustMode, sync.mTolerance, videoFpsHint);
1127 sp<MediaPlayerBase> p = getPlayer();
1128 if (p == 0) return UNKNOWN_ERROR;
1129 return p->setSyncSettings(sync, videoFpsHint);
1130}
1131
1132status_t MediaPlayerService::Client::getSyncSettings(
1133 AVSyncSettings* sync /* nonnull */, float* videoFps /* nonnull */)
1134{
1135 sp<MediaPlayerBase> p = getPlayer();
1136 if (p == 0) return UNKNOWN_ERROR;
1137 status_t ret = p->getSyncSettings(sync, videoFps);
1138 if (ret == NO_ERROR) {
1139 ALOGV("[%d] getSyncSettings(%u, %u, %f, %f)",
1140 mConnId, sync->mSource, sync->mAudioAdjustMode, sync->mTolerance, *videoFps);
1141 } else {
1142 ALOGV("[%d] getSyncSettings returned %d", mConnId, ret);
1143 }
1144 return ret;
Wei Jia98160162015-02-04 17:01:11 -08001145}
1146
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001147status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
1148{
Steve Block3856b092011-10-20 11:56:00 +01001149 ALOGV("getCurrentPosition");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001150 sp<MediaPlayerBase> p = getPlayer();
1151 if (p == 0) return UNKNOWN_ERROR;
1152 status_t ret = p->getCurrentPosition(msec);
1153 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001154 ALOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001155 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001156 ALOGE("getCurrentPosition returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001157 }
1158 return ret;
1159}
1160
1161status_t MediaPlayerService::Client::getDuration(int *msec)
1162{
Steve Block3856b092011-10-20 11:56:00 +01001163 ALOGV("getDuration");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001164 sp<MediaPlayerBase> p = getPlayer();
1165 if (p == 0) return UNKNOWN_ERROR;
1166 status_t ret = p->getDuration(msec);
1167 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001168 ALOGV("[%d] getDuration = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001169 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001170 ALOGE("getDuration returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001171 }
1172 return ret;
1173}
1174
Marco Nelissen6b74d672012-02-28 16:07:44 -08001175status_t MediaPlayerService::Client::setNextPlayer(const sp<IMediaPlayer>& player) {
1176 ALOGV("setNextPlayer");
1177 Mutex::Autolock l(mLock);
1178 sp<Client> c = static_cast<Client*>(player.get());
Wei Jia28284122016-08-30 13:49:06 -07001179 if (c != NULL && !mService->hasClient(c)) {
Robert Shihee0a0e32016-08-16 16:50:54 -07001180 return BAD_VALUE;
1181 }
1182
Marco Nelissen6b74d672012-02-28 16:07:44 -08001183 mNextClient = c;
John Grossman5f7e55e2012-08-24 14:47:25 -07001184
1185 if (c != NULL) {
1186 if (mAudioOutput != NULL) {
1187 mAudioOutput->setNextOutput(c->mAudioOutput);
1188 } else if ((mPlayer != NULL) && !mPlayer->hardwareOutput()) {
1189 ALOGE("no current audio output");
1190 }
1191
1192 if ((mPlayer != NULL) && (mNextClient->getPlayer() != NULL)) {
1193 mPlayer->setNextPlayer(mNextClient->getPlayer());
1194 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001195 }
John Grossman5f7e55e2012-08-24 14:47:25 -07001196
Marco Nelissen6b74d672012-02-28 16:07:44 -08001197 return OK;
1198}
1199
Andy Hung9fc8b5c2017-01-24 13:36:48 -08001200VolumeShaper::Status MediaPlayerService::Client::applyVolumeShaper(
1201 const sp<VolumeShaper::Configuration>& configuration,
1202 const sp<VolumeShaper::Operation>& operation) {
1203 // for hardware output, call player instead
1204 ALOGV("Client::applyVolumeShaper(%p)", this);
1205 sp<MediaPlayerBase> p = getPlayer();
1206 {
1207 Mutex::Autolock l(mLock);
1208 if (p != 0 && p->hardwareOutput()) {
1209 // TODO: investigate internal implementation
1210 return VolumeShaper::Status(INVALID_OPERATION);
1211 }
1212 if (mAudioOutput.get() != nullptr) {
1213 return mAudioOutput->applyVolumeShaper(configuration, operation);
1214 }
1215 }
1216 return VolumeShaper::Status(INVALID_OPERATION);
1217}
1218
1219sp<VolumeShaper::State> MediaPlayerService::Client::getVolumeShaperState(int id) {
1220 // for hardware output, call player instead
1221 ALOGV("Client::getVolumeShaperState(%p)", this);
1222 sp<MediaPlayerBase> p = getPlayer();
1223 {
1224 Mutex::Autolock l(mLock);
1225 if (p != 0 && p->hardwareOutput()) {
1226 // TODO: investigate internal implementation.
1227 return nullptr;
1228 }
1229 if (mAudioOutput.get() != nullptr) {
1230 return mAudioOutput->getVolumeShaperState(id);
1231 }
1232 }
1233 return nullptr;
1234}
1235
Wei Jiac5de0912016-11-18 10:22:14 -08001236status_t MediaPlayerService::Client::seekTo(int msec, MediaPlayerSeekMode mode)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001237{
Wei Jiac5de0912016-11-18 10:22:14 -08001238 ALOGV("[%d] seekTo(%d, %d)", mConnId, msec, mode);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001239 sp<MediaPlayerBase> p = getPlayer();
1240 if (p == 0) return UNKNOWN_ERROR;
Wei Jiac5de0912016-11-18 10:22:14 -08001241 return p->seekTo(msec, mode);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001242}
1243
1244status_t MediaPlayerService::Client::reset()
1245{
Steve Block3856b092011-10-20 11:56:00 +01001246 ALOGV("[%d] reset", mConnId);
John Grossmanc795b642012-02-22 15:38:35 -08001247 mRetransmitEndpointValid = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001248 sp<MediaPlayerBase> p = getPlayer();
1249 if (p == 0) return UNKNOWN_ERROR;
1250 return p->reset();
1251}
1252
Wei Jia52c28512017-09-13 18:17:51 -07001253status_t MediaPlayerService::Client::notifyAt(int64_t mediaTimeUs)
1254{
1255 ALOGV("[%d] notifyAt(%lld)", mConnId, (long long)mediaTimeUs);
1256 sp<MediaPlayerBase> p = getPlayer();
1257 if (p == 0) return UNKNOWN_ERROR;
1258 return p->notifyAt(mediaTimeUs);
1259}
1260
Glenn Kastenfff6d712012-01-12 16:38:12 -08001261status_t MediaPlayerService::Client::setAudioStreamType(audio_stream_type_t type)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001262{
Steve Block3856b092011-10-20 11:56:00 +01001263 ALOGV("[%d] setAudioStreamType(%d)", mConnId, type);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001264 // TODO: for hardware output, call player instead
1265 Mutex::Autolock l(mLock);
1266 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1267 return NO_ERROR;
1268}
1269
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001270status_t MediaPlayerService::Client::setAudioAttributes_l(const Parcel &parcel)
1271{
1272 if (mAudioAttributes != NULL) { free(mAudioAttributes); }
1273 mAudioAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001274 if (mAudioAttributes == NULL) {
1275 return NO_MEMORY;
1276 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001277 unmarshallAudioAttributes(parcel, mAudioAttributes);
1278
1279 ALOGV("setAudioAttributes_l() usage=%d content=%d flags=0x%x tags=%s",
1280 mAudioAttributes->usage, mAudioAttributes->content_type, mAudioAttributes->flags,
1281 mAudioAttributes->tags);
1282
1283 if (mAudioOutput != 0) {
1284 mAudioOutput->setAudioAttributes(mAudioAttributes);
1285 }
1286 return NO_ERROR;
1287}
1288
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001289status_t MediaPlayerService::Client::setLooping(int loop)
1290{
Steve Block3856b092011-10-20 11:56:00 +01001291 ALOGV("[%d] setLooping(%d)", mConnId, loop);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001292 mLoop = loop;
1293 sp<MediaPlayerBase> p = getPlayer();
1294 if (p != 0) return p->setLooping(loop);
1295 return NO_ERROR;
1296}
1297
1298status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1299{
Steve Block3856b092011-10-20 11:56:00 +01001300 ALOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
John Grossman761defc2012-02-09 15:09:05 -08001301
1302 // for hardware output, call player instead
1303 sp<MediaPlayerBase> p = getPlayer();
1304 {
1305 Mutex::Autolock l(mLock);
1306 if (p != 0 && p->hardwareOutput()) {
1307 MediaPlayerHWInterface* hwp =
1308 reinterpret_cast<MediaPlayerHWInterface*>(p.get());
1309 return hwp->setVolume(leftVolume, rightVolume);
1310 } else {
1311 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1312 return NO_ERROR;
1313 }
1314 }
1315
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001316 return NO_ERROR;
1317}
1318
Eric Laurent2beeb502010-07-16 07:43:46 -07001319status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1320{
Steve Block3856b092011-10-20 11:56:00 +01001321 ALOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
Eric Laurent2beeb502010-07-16 07:43:46 -07001322 Mutex::Autolock l(mLock);
1323 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1324 return NO_ERROR;
1325}
1326
1327status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1328{
Steve Block3856b092011-10-20 11:56:00 +01001329 ALOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
Eric Laurent2beeb502010-07-16 07:43:46 -07001330 Mutex::Autolock l(mLock);
1331 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1332 return NO_ERROR;
1333}
Nicolas Catania48290382009-07-10 13:53:06 -07001334
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001335status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
Steve Block3856b092011-10-20 11:56:00 +01001336 ALOGV("[%d] setParameter(%d)", mConnId, key);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001337 switch (key) {
1338 case KEY_PARAMETER_AUDIO_ATTRIBUTES:
1339 {
1340 Mutex::Autolock l(mLock);
1341 return setAudioAttributes_l(request);
1342 }
1343 default:
1344 sp<MediaPlayerBase> p = getPlayer();
1345 if (p == 0) { return UNKNOWN_ERROR; }
1346 return p->setParameter(key, request);
1347 }
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001348}
1349
1350status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
Steve Block3856b092011-10-20 11:56:00 +01001351 ALOGV("[%d] getParameter(%d)", mConnId, key);
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001352 sp<MediaPlayerBase> p = getPlayer();
1353 if (p == 0) return UNKNOWN_ERROR;
1354 return p->getParameter(key, reply);
1355}
1356
John Grossmanc795b642012-02-22 15:38:35 -08001357status_t MediaPlayerService::Client::setRetransmitEndpoint(
1358 const struct sockaddr_in* endpoint) {
1359
1360 if (NULL != endpoint) {
1361 uint32_t a = ntohl(endpoint->sin_addr.s_addr);
1362 uint16_t p = ntohs(endpoint->sin_port);
1363 ALOGV("[%d] setRetransmitEndpoint(%u.%u.%u.%u:%hu)", mConnId,
1364 (a >> 24), (a >> 16) & 0xFF, (a >> 8) & 0xFF, (a & 0xFF), p);
1365 } else {
1366 ALOGV("[%d] setRetransmitEndpoint = <none>", mConnId);
1367 }
1368
1369 sp<MediaPlayerBase> p = getPlayer();
1370
1371 // Right now, the only valid time to set a retransmit endpoint is before
1372 // player selection has been made (since the presence or absence of a
1373 // retransmit endpoint is going to determine which player is selected during
1374 // setDataSource).
1375 if (p != 0) return INVALID_OPERATION;
1376
1377 if (NULL != endpoint) {
1378 mRetransmitEndpoint = *endpoint;
1379 mRetransmitEndpointValid = true;
1380 } else {
1381 mRetransmitEndpointValid = false;
1382 }
1383
1384 return NO_ERROR;
1385}
1386
John Grossman44a7e422012-06-21 17:29:24 -07001387status_t MediaPlayerService::Client::getRetransmitEndpoint(
1388 struct sockaddr_in* endpoint)
1389{
1390 if (NULL == endpoint)
1391 return BAD_VALUE;
1392
1393 sp<MediaPlayerBase> p = getPlayer();
1394
1395 if (p != NULL)
1396 return p->getRetransmitEndpoint(endpoint);
1397
1398 if (!mRetransmitEndpointValid)
1399 return NO_INIT;
1400
1401 *endpoint = mRetransmitEndpoint;
1402
1403 return NO_ERROR;
1404}
1405
Gloria Wangb483c472011-04-11 17:23:27 -07001406void MediaPlayerService::Client::notify(
1407 void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001408{
1409 Client* client = static_cast<Client*>(cookie);
James Dongb8a98252012-08-26 16:13:03 -07001410 if (client == NULL) {
1411 return;
1412 }
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001413
James Dongb8a98252012-08-26 16:13:03 -07001414 sp<IMediaPlayerClient> c;
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001415 sp<Client> nextClient;
1416 status_t errStartNext = NO_ERROR;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001417 {
1418 Mutex::Autolock l(client->mLock);
James Dongb8a98252012-08-26 16:13:03 -07001419 c = client->mClient;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001420 if (msg == MEDIA_PLAYBACK_COMPLETE && client->mNextClient != NULL) {
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001421 nextClient = client->mNextClient;
1422
John Grossmancb0b7552012-08-23 17:47:31 -07001423 if (client->mAudioOutput != NULL)
1424 client->mAudioOutput->switchToNextOutput();
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001425
1426 errStartNext = nextClient->start();
1427 }
1428 }
1429
1430 if (nextClient != NULL) {
1431 sp<IMediaPlayerClient> nc;
1432 {
1433 Mutex::Autolock l(nextClient->mLock);
1434 nc = nextClient->mClient;
1435 }
1436 if (nc != NULL) {
1437 if (errStartNext == NO_ERROR) {
1438 nc->notify(MEDIA_INFO, MEDIA_INFO_STARTED_AS_NEXT, 0, obj);
1439 } else {
1440 nc->notify(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN , 0, obj);
1441 ALOGE("gapless:start playback for next track failed, err(%d)", errStartNext);
Wei Jia2afac0c2016-01-07 12:13:07 -08001442 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001443 }
1444 }
1445
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001446 if (MEDIA_INFO == msg &&
Nicolas Catania48290382009-07-10 13:53:06 -07001447 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikoa64c8c72009-07-20 15:07:26 -07001448 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania48290382009-07-10 13:53:06 -07001449
1450 if(client->shouldDropMetadata(metadata_type)) {
1451 return;
1452 }
1453
1454 // Update the list of metadata that have changed. getMetadata
1455 // also access mMetadataUpdated and clears it.
1456 client->addNewMetadataUpdate(metadata_type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001457 }
James Dongb8a98252012-08-26 16:13:03 -07001458
1459 if (c != NULL) {
1460 ALOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
1461 c->notify(msg, ext1, ext2, obj);
1462 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001463}
1464
Nicolas Catania48290382009-07-10 13:53:06 -07001465
nikoa64c8c72009-07-20 15:07:26 -07001466bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001467{
Nicolas Catania48290382009-07-10 13:53:06 -07001468 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001469
Nicolas Catania48290382009-07-10 13:53:06 -07001470 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001471 return true;
1472 }
1473
Nicolas Catania48290382009-07-10 13:53:06 -07001474 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001475 return false;
Nicolas Catania48290382009-07-10 13:53:06 -07001476 } else {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001477 return true;
1478 }
1479}
1480
Nicolas Catania48290382009-07-10 13:53:06 -07001481
nikoa64c8c72009-07-20 15:07:26 -07001482void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania48290382009-07-10 13:53:06 -07001483 Mutex::Autolock lock(mLock);
1484 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1485 mMetadataUpdated.add(metadata_type);
1486 }
1487}
1488
Hassan Shojaniacefac142017-02-06 21:02:02 -08001489// Modular DRM
1490status_t MediaPlayerService::Client::prepareDrm(const uint8_t uuid[16],
1491 const Vector<uint8_t>& drmSessionId)
1492{
1493 ALOGV("[%d] prepareDrm", mConnId);
1494 sp<MediaPlayerBase> p = getPlayer();
1495 if (p == 0) return UNKNOWN_ERROR;
1496
1497 status_t ret = p->prepareDrm(uuid, drmSessionId);
1498 ALOGV("prepareDrm ret: %d", ret);
1499
1500 return ret;
1501}
1502
1503status_t MediaPlayerService::Client::releaseDrm()
1504{
1505 ALOGV("[%d] releaseDrm", mConnId);
1506 sp<MediaPlayerBase> p = getPlayer();
1507 if (p == 0) return UNKNOWN_ERROR;
1508
1509 status_t ret = p->releaseDrm();
1510 ALOGV("releaseDrm ret: %d", ret);
1511
1512 return ret;
1513}
1514
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001515#if CALLBACK_ANTAGONIZER
1516const int Antagonizer::interval = 10000; // 10 msecs
1517
1518Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1519 mExit(false), mActive(false), mClient(client), mCb(cb)
1520{
1521 createThread(callbackThread, this);
1522}
1523
1524void Antagonizer::kill()
1525{
1526 Mutex::Autolock _l(mLock);
1527 mActive = false;
1528 mExit = true;
1529 mCondition.wait(mLock);
1530}
1531
1532int Antagonizer::callbackThread(void* user)
1533{
Steve Blockb8a80522011-12-20 16:23:08 +00001534 ALOGD("Antagonizer started");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001535 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1536 while (!p->mExit) {
1537 if (p->mActive) {
Steve Block3856b092011-10-20 11:56:00 +01001538 ALOGV("send event");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001539 p->mCb(p->mClient, 0, 0, 0);
1540 }
1541 usleep(interval);
1542 }
1543 Mutex::Autolock _l(p->mLock);
1544 p->mCondition.signal();
Steve Blockb8a80522011-12-20 16:23:08 +00001545 ALOGD("Antagonizer stopped");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001546 return 0;
1547}
1548#endif
1549
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001550#undef LOG_TAG
1551#define LOG_TAG "AudioSink"
Andy Hung1afd0982016-11-08 16:13:44 -08001552MediaPlayerService::AudioOutput::AudioOutput(audio_session_t sessionId, uid_t uid, int pid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001553 const audio_attributes_t* attr)
Andreas Huber20111aa2009-07-14 16:56:47 -07001554 : mCallback(NULL),
Eric Laurenta514bdb2010-06-21 09:27:30 -07001555 mCallbackCookie(NULL),
Marco Nelissen6b74d672012-02-28 16:07:44 -08001556 mCallbackData(NULL),
Andy Hungd1c74342015-07-07 16:54:23 -07001557 mStreamType(AUDIO_STREAM_MUSIC),
Andy Hungd1c74342015-07-07 16:54:23 -07001558 mLeftVolume(1.0),
1559 mRightVolume(1.0),
1560 mPlaybackRate(AUDIO_PLAYBACK_RATE_DEFAULT),
1561 mSampleRateHz(0),
1562 mMsecsPerFrame(0),
1563 mFrameSize(0),
Eric Laurent1948eb32012-04-13 16:50:19 -07001564 mSessionId(sessionId),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001565 mUid(uid),
Marco Nelissend457c972014-02-11 08:47:07 -08001566 mPid(pid),
Andy Hungd1c74342015-07-07 16:54:23 -07001567 mSendLevel(0.0),
1568 mAuxEffectId(0),
Andy Hung4ef88d72017-02-21 19:47:53 -08001569 mFlags(AUDIO_OUTPUT_FLAG_NONE),
Ivan Lozano8cf3a072017-08-09 09:01:33 -07001570 mVolumeHandler(new media::VolumeHandler())
Andy Hungd1c74342015-07-07 16:54:23 -07001571{
Steve Block3856b092011-10-20 11:56:00 +01001572 ALOGV("AudioOutput(%d)", sessionId);
Eric Laurent43562692015-07-15 16:49:07 -07001573 if (attr != NULL) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001574 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1575 if (mAttributes != NULL) {
1576 memcpy(mAttributes, attr, sizeof(audio_attributes_t));
1577 mStreamType = audio_attributes_to_stream_type(attr);
1578 }
1579 } else {
1580 mAttributes = NULL;
Eric Laurent43562692015-07-15 16:49:07 -07001581 }
1582
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001583 setMinBufferCount();
1584}
1585
1586MediaPlayerService::AudioOutput::~AudioOutput()
1587{
1588 close();
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001589 free(mAttributes);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001590 delete mCallbackData;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001591}
1592
Andy Hungd1c74342015-07-07 16:54:23 -07001593//static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001594void MediaPlayerService::AudioOutput::setMinBufferCount()
1595{
1596 char value[PROPERTY_VALUE_MAX];
1597 if (property_get("ro.kernel.qemu", value, 0)) {
1598 mIsOnEmulator = true;
1599 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1600 }
1601}
1602
Andy Hungd1c74342015-07-07 16:54:23 -07001603// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001604bool MediaPlayerService::AudioOutput::isOnEmulator()
1605{
Andy Hungd1c74342015-07-07 16:54:23 -07001606 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001607 return mIsOnEmulator;
1608}
1609
Andy Hungd1c74342015-07-07 16:54:23 -07001610// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001611int MediaPlayerService::AudioOutput::getMinBufferCount()
1612{
Andy Hungd1c74342015-07-07 16:54:23 -07001613 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001614 return mMinBufferCount;
1615}
1616
1617ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1618{
Andy Hungd1c74342015-07-07 16:54:23 -07001619 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001620 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001621 return mTrack->frameCount() * mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001622}
1623
1624ssize_t MediaPlayerService::AudioOutput::frameCount() const
1625{
Andy Hungd1c74342015-07-07 16:54:23 -07001626 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001627 if (mTrack == 0) return NO_INIT;
1628 return mTrack->frameCount();
1629}
1630
1631ssize_t MediaPlayerService::AudioOutput::channelCount() const
1632{
Andy Hungd1c74342015-07-07 16:54:23 -07001633 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001634 if (mTrack == 0) return NO_INIT;
1635 return mTrack->channelCount();
1636}
1637
1638ssize_t MediaPlayerService::AudioOutput::frameSize() const
1639{
Andy Hungd1c74342015-07-07 16:54:23 -07001640 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001641 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001642 return mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001643}
1644
1645uint32_t MediaPlayerService::AudioOutput::latency () const
1646{
Andy Hungd1c74342015-07-07 16:54:23 -07001647 Mutex::Autolock lock(mLock);
Eric Laurentdb354e52012-03-05 17:27:11 -08001648 if (mTrack == 0) return 0;
1649 return mTrack->latency();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001650}
1651
1652float MediaPlayerService::AudioOutput::msecsPerFrame() const
1653{
Andy Hungd1c74342015-07-07 16:54:23 -07001654 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001655 return mMsecsPerFrame;
1656}
1657
Marco Nelissen4110c102012-03-29 09:31:28 -07001658status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position) const
Eric Laurent342e9cf2010-01-19 17:37:09 -08001659{
Andy Hungd1c74342015-07-07 16:54:23 -07001660 Mutex::Autolock lock(mLock);
Eric Laurent342e9cf2010-01-19 17:37:09 -08001661 if (mTrack == 0) return NO_INIT;
1662 return mTrack->getPosition(position);
1663}
1664
Lajos Molnar06ad1522014-08-28 07:27:44 -07001665status_t MediaPlayerService::AudioOutput::getTimestamp(AudioTimestamp &ts) const
1666{
Andy Hungd1c74342015-07-07 16:54:23 -07001667 Mutex::Autolock lock(mLock);
Lajos Molnar06ad1522014-08-28 07:27:44 -07001668 if (mTrack == 0) return NO_INIT;
1669 return mTrack->getTimestamp(ts);
1670}
1671
Wei Jiac4ac8172015-10-21 10:35:48 -07001672// TODO: Remove unnecessary calls to getPlayedOutDurationUs()
1673// as it acquires locks and may query the audio driver.
1674//
1675// Some calls could conceivably retrieve extrapolated data instead of
1676// accessing getTimestamp() or getPosition() every time a data buffer with
1677// a media time is received.
1678//
1679// Calculate duration of played samples if played at normal rate (i.e., 1.0).
1680int64_t MediaPlayerService::AudioOutput::getPlayedOutDurationUs(int64_t nowUs) const
1681{
1682 Mutex::Autolock lock(mLock);
1683 if (mTrack == 0 || mSampleRateHz == 0) {
Wei Jia213f4902015-10-22 08:55:25 -07001684 return 0;
Wei Jiac4ac8172015-10-21 10:35:48 -07001685 }
1686
1687 uint32_t numFramesPlayed;
Andy Hung5d313802016-10-10 15:09:39 -07001688 int64_t numFramesPlayedAtUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001689 AudioTimestamp ts;
Wei Jiac4ac8172015-10-21 10:35:48 -07001690
1691 status_t res = mTrack->getTimestamp(ts);
1692 if (res == OK) { // case 1: mixing audio tracks and offloaded tracks.
1693 numFramesPlayed = ts.mPosition;
Andy Hung5d313802016-10-10 15:09:39 -07001694 numFramesPlayedAtUs = ts.mTime.tv_sec * 1000000LL + ts.mTime.tv_nsec / 1000;
1695 //ALOGD("getTimestamp: OK %d %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001696 } else if (res == WOULD_BLOCK) { // case 2: transitory state on start of a new track
1697 numFramesPlayed = 0;
Andy Hung5d313802016-10-10 15:09:39 -07001698 numFramesPlayedAtUs = nowUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001699 //ALOGD("getTimestamp: WOULD_BLOCK %d %lld",
Andy Hung5d313802016-10-10 15:09:39 -07001700 // numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001701 } else { // case 3: transitory at new track or audio fast tracks.
1702 res = mTrack->getPosition(&numFramesPlayed);
1703 CHECK_EQ(res, (status_t)OK);
Andy Hung5d313802016-10-10 15:09:39 -07001704 numFramesPlayedAtUs = nowUs;
1705 numFramesPlayedAtUs += 1000LL * mTrack->latency() / 2; /* XXX */
1706 //ALOGD("getPosition: %u %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001707 }
1708
1709 // CHECK_EQ(numFramesPlayed & (1 << 31), 0); // can't be negative until 12.4 hrs, test
1710 // TODO: remove the (int32_t) casting below as it may overflow at 12.4 hours.
1711 int64_t durationUs = (int64_t)((int32_t)numFramesPlayed * 1000000LL / mSampleRateHz)
Andy Hung5d313802016-10-10 15:09:39 -07001712 + nowUs - numFramesPlayedAtUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001713 if (durationUs < 0) {
1714 // Occurs when numFramesPlayed position is very small and the following:
1715 // (1) In case 1, the time nowUs is computed before getTimestamp() is called and
Andy Hung5d313802016-10-10 15:09:39 -07001716 // numFramesPlayedAtUs is greater than nowUs by time more than numFramesPlayed.
Wei Jiac4ac8172015-10-21 10:35:48 -07001717 // (2) In case 3, using getPosition and adding mAudioSink->latency() to
Andy Hung5d313802016-10-10 15:09:39 -07001718 // numFramesPlayedAtUs, by a time amount greater than numFramesPlayed.
Wei Jiac4ac8172015-10-21 10:35:48 -07001719 //
1720 // Both of these are transitory conditions.
1721 ALOGV("getPlayedOutDurationUs: negative duration %lld set to zero", (long long)durationUs);
1722 durationUs = 0;
1723 }
1724 ALOGV("getPlayedOutDurationUs(%lld) nowUs(%lld) frames(%u) framesAt(%lld)",
Andy Hung5d313802016-10-10 15:09:39 -07001725 (long long)durationUs, (long long)nowUs,
1726 numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001727 return durationUs;
1728}
1729
Marco Nelissen4110c102012-03-29 09:31:28 -07001730status_t MediaPlayerService::AudioOutput::getFramesWritten(uint32_t *frameswritten) const
1731{
Andy Hungd1c74342015-07-07 16:54:23 -07001732 Mutex::Autolock lock(mLock);
Marco Nelissen4110c102012-03-29 09:31:28 -07001733 if (mTrack == 0) return NO_INIT;
Andy Hung2f6e73d2016-04-08 12:12:58 -07001734 ExtendedTimestamp ets;
1735 status_t status = mTrack->getTimestamp(&ets);
1736 if (status == OK || status == WOULD_BLOCK) {
1737 *frameswritten = (uint32_t)ets.mPosition[ExtendedTimestamp::LOCATION_CLIENT];
1738 }
1739 return status;
Marco Nelissen4110c102012-03-29 09:31:28 -07001740}
1741
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001742status_t MediaPlayerService::AudioOutput::setParameters(const String8& keyValuePairs)
1743{
Andy Hungd1c74342015-07-07 16:54:23 -07001744 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001745 if (mTrack == 0) return NO_INIT;
1746 return mTrack->setParameters(keyValuePairs);
1747}
1748
1749String8 MediaPlayerService::AudioOutput::getParameters(const String8& keys)
1750{
Andy Hungd1c74342015-07-07 16:54:23 -07001751 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001752 if (mTrack == 0) return String8::empty();
1753 return mTrack->getParameters(keys);
1754}
1755
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001756void MediaPlayerService::AudioOutput::setAudioAttributes(const audio_attributes_t * attributes) {
Andy Hungd1c74342015-07-07 16:54:23 -07001757 Mutex::Autolock lock(mLock);
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001758 if (attributes == NULL) {
1759 free(mAttributes);
1760 mAttributes = NULL;
1761 } else {
1762 if (mAttributes == NULL) {
1763 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1764 }
1765 memcpy(mAttributes, attributes, sizeof(audio_attributes_t));
Eric Laurent43562692015-07-15 16:49:07 -07001766 mStreamType = audio_attributes_to_stream_type(attributes);
1767 }
1768}
1769
1770void MediaPlayerService::AudioOutput::setAudioStreamType(audio_stream_type_t streamType)
1771{
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001772 Mutex::Autolock lock(mLock);
Eric Laurent43562692015-07-15 16:49:07 -07001773 // do not allow direct stream type modification if attributes have been set
1774 if (mAttributes == NULL) {
1775 mStreamType = streamType;
1776 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001777}
1778
Andy Hungd1c74342015-07-07 16:54:23 -07001779void MediaPlayerService::AudioOutput::deleteRecycledTrack_l()
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001780{
Andy Hungd1c74342015-07-07 16:54:23 -07001781 ALOGV("deleteRecycledTrack_l");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001782 if (mRecycledTrack != 0) {
1783
1784 if (mCallbackData != NULL) {
1785 mCallbackData->setOutput(NULL);
1786 mCallbackData->endTrackSwitch();
1787 }
1788
1789 if ((mRecycledTrack->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) {
Andy Hunge13f8a62016-03-30 14:20:42 -07001790 int32_t msec = 0;
1791 if (!mRecycledTrack->stopped()) { // check if active
1792 (void)mRecycledTrack->pendingDuration(&msec);
1793 }
1794 mRecycledTrack->stop(); // ensure full data drain
1795 ALOGD("deleting recycled track, waiting for data drain (%d msec)", msec);
1796 if (msec > 0) {
1797 static const int32_t WAIT_LIMIT_MS = 3000;
1798 if (msec > WAIT_LIMIT_MS) {
1799 msec = WAIT_LIMIT_MS;
1800 }
1801 usleep(msec * 1000LL);
1802 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001803 }
1804 // An offloaded track isn't flushed because the STREAM_END is reported
1805 // slightly prematurely to allow time for the gapless track switch
1806 // but this means that if we decide not to recycle the track there
1807 // could be a small amount of residual data still playing. We leave
1808 // AudioFlinger to drain the track.
1809
1810 mRecycledTrack.clear();
Andy Hungd1c74342015-07-07 16:54:23 -07001811 close_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001812 delete mCallbackData;
1813 mCallbackData = NULL;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001814 }
1815}
1816
Andy Hungd1c74342015-07-07 16:54:23 -07001817void MediaPlayerService::AudioOutput::close_l()
1818{
1819 mTrack.clear();
1820}
1821
Andreas Huber20111aa2009-07-14 16:56:47 -07001822status_t MediaPlayerService::AudioOutput::open(
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001823 uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
1824 audio_format_t format, int bufferCount,
Eric Laurent1948eb32012-04-13 16:50:19 -07001825 AudioCallback cb, void *cookie,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001826 audio_output_flags_t flags,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001827 const audio_offload_info_t *offloadInfo,
Andy Hung179652e2015-05-31 22:49:46 -07001828 bool doNotReconnect,
1829 uint32_t suggestedFrameCount)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001830{
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001831 ALOGV("open(%u, %d, 0x%x, 0x%x, %d, %d 0x%x)", sampleRate, channelCount, channelMask,
1832 format, bufferCount, mSessionId, flags);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001833
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001834 // offloading is only supported in callback mode for now.
1835 // offloadInfo must be present if offload flag is set
1836 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) &&
1837 ((cb == NULL) || (offloadInfo == NULL))) {
1838 return BAD_VALUE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001839 }
1840
Andy Hung179652e2015-05-31 22:49:46 -07001841 // compute frame count for the AudioTrack internal buffer
1842 size_t frameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001843 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1844 frameCount = 0; // AudioTrack will get frame count from AudioFlinger
1845 } else {
Andy Hung179652e2015-05-31 22:49:46 -07001846 // try to estimate the buffer processing fetch size from AudioFlinger.
1847 // framesPerBuffer is approximate and generally correct, except when it's not :-).
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001848 uint32_t afSampleRate;
1849 size_t afFrameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001850 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1851 return NO_INIT;
1852 }
1853 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1854 return NO_INIT;
1855 }
Andy Hung179652e2015-05-31 22:49:46 -07001856 const size_t framesPerBuffer =
1857 (unsigned long long)sampleRate * afFrameCount / afSampleRate;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001858
Andy Hung179652e2015-05-31 22:49:46 -07001859 if (bufferCount == 0) {
1860 // use suggestedFrameCount
1861 bufferCount = (suggestedFrameCount + framesPerBuffer - 1) / framesPerBuffer;
1862 }
1863 // Check argument bufferCount against the mininum buffer count
1864 if (bufferCount != 0 && bufferCount < mMinBufferCount) {
1865 ALOGV("bufferCount (%d) increased to %d", bufferCount, mMinBufferCount);
1866 bufferCount = mMinBufferCount;
1867 }
1868 // if frameCount is 0, then AudioTrack will get frame count from AudioFlinger
1869 // which will be the minimum size permitted.
1870 frameCount = bufferCount * framesPerBuffer;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001871 }
Andreas Huber20111aa2009-07-14 16:56:47 -07001872
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001873 if (channelMask == CHANNEL_MASK_USE_CHANNEL_ORDER) {
Glenn Kastenab334fd2012-03-14 12:56:06 -07001874 channelMask = audio_channel_out_mask_from_count(channelCount);
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001875 if (0 == channelMask) {
1876 ALOGE("open() error, can\'t derive mask for %d audio channels", channelCount);
1877 return NO_INIT;
1878 }
1879 }
Eric Laurent1948eb32012-04-13 16:50:19 -07001880
Andy Hungd1c74342015-07-07 16:54:23 -07001881 Mutex::Autolock lock(mLock);
Andy Hung179652e2015-05-31 22:49:46 -07001882 mCallback = cb;
1883 mCallbackCookie = cookie;
1884
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001885 // Check whether we can recycle the track
1886 bool reuse = false;
1887 bool bothOffloaded = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001888
Glenn Kasten2799d742013-05-30 14:33:29 -07001889 if (mRecycledTrack != 0) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001890 // check whether we are switching between two offloaded tracks
1891 bothOffloaded = (flags & mRecycledTrack->getFlags()
1892 & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0;
Marco Nelissen67295b52012-06-11 14:52:53 -07001893
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001894 // check if the existing track can be reused as-is, or if a new track needs to be created.
1895 reuse = true;
1896
Marco Nelissen67295b52012-06-11 14:52:53 -07001897 if ((mCallbackData == NULL && mCallback != NULL) ||
1898 (mCallbackData != NULL && mCallback == NULL)) {
1899 // recycled track uses callbacks but the caller wants to use writes, or vice versa
1900 ALOGV("can't chain callback and write");
1901 reuse = false;
1902 } else if ((mRecycledTrack->getSampleRate() != sampleRate) ||
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001903 (mRecycledTrack->channelCount() != (uint32_t)channelCount) ) {
1904 ALOGV("samplerate, channelcount differ: %u/%u Hz, %u/%d ch",
Marco Nelissen67295b52012-06-11 14:52:53 -07001905 mRecycledTrack->getSampleRate(), sampleRate,
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001906 mRecycledTrack->channelCount(), channelCount);
Marco Nelissen67295b52012-06-11 14:52:53 -07001907 reuse = false;
1908 } else if (flags != mFlags) {
1909 ALOGV("output flags differ %08x/%08x", flags, mFlags);
1910 reuse = false;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001911 } else if (mRecycledTrack->format() != format) {
1912 reuse = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001913 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001914 } else {
1915 ALOGV("no track available to recycle");
1916 }
1917
1918 ALOGV_IF(bothOffloaded, "both tracks offloaded");
1919
1920 // If we can't recycle and both tracks are offloaded
1921 // we must close the previous output before opening a new one
1922 if (bothOffloaded && !reuse) {
1923 ALOGV("both offloaded and not recycling");
Andy Hungd1c74342015-07-07 16:54:23 -07001924 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001925 }
1926
1927 sp<AudioTrack> t;
1928 CallbackData *newcbd = NULL;
1929
1930 // We don't attempt to create a new track if we are recycling an
1931 // offloaded track. But, if we are recycling a non-offloaded or we
1932 // are switching where one is offloaded and one isn't then we create
1933 // the new track in advance so that we can read additional stream info
1934
1935 if (!(reuse && bothOffloaded)) {
1936 ALOGV("creating new AudioTrack");
1937
1938 if (mCallback != NULL) {
1939 newcbd = new CallbackData(this);
1940 t = new AudioTrack(
1941 mStreamType,
1942 sampleRate,
1943 format,
1944 channelMask,
1945 frameCount,
1946 flags,
1947 CallbackWrapper,
1948 newcbd,
1949 0, // notification frames
1950 mSessionId,
1951 AudioTrack::TRANSFER_CALLBACK,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001952 offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -08001953 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001954 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001955 mAttributes,
1956 doNotReconnect);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001957 } else {
Andy Hungff874dc2016-04-11 16:49:09 -07001958 // TODO: Due to buffer memory concerns, we use a max target playback speed
1959 // based on mPlaybackRate at the time of open (instead of kMaxRequiredSpeed),
1960 // also clamping the target speed to 1.0 <= targetSpeed <= kMaxRequiredSpeed.
1961 const float targetSpeed =
1962 std::min(std::max(mPlaybackRate.mSpeed, 1.0f), kMaxRequiredSpeed);
1963 ALOGW_IF(targetSpeed != mPlaybackRate.mSpeed,
1964 "track target speed:%f clamped from playback speed:%f",
1965 targetSpeed, mPlaybackRate.mSpeed);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001966 t = new AudioTrack(
1967 mStreamType,
1968 sampleRate,
1969 format,
1970 channelMask,
1971 frameCount,
1972 flags,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001973 NULL, // callback
1974 NULL, // user data
1975 0, // notification frames
1976 mSessionId,
1977 AudioTrack::TRANSFER_DEFAULT,
1978 NULL, // offload info
Marco Nelissend457c972014-02-11 08:47:07 -08001979 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001980 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001981 mAttributes,
Andy Hungff874dc2016-04-11 16:49:09 -07001982 doNotReconnect,
1983 targetSpeed);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001984 }
1985
1986 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1987 ALOGE("Unable to create audio track");
1988 delete newcbd;
Glenn Kasten3e98ecd2015-05-18 13:13:24 -07001989 // t goes out of scope, so reference count drops to zero
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001990 return NO_INIT;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001991 } else {
1992 // successful AudioTrack initialization implies a legacy stream type was generated
1993 // from the audio attributes
1994 mStreamType = t->streamType();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001995 }
1996 }
1997
1998 if (reuse) {
1999 CHECK(mRecycledTrack != NULL);
2000
2001 if (!bothOffloaded) {
2002 if (mRecycledTrack->frameCount() != t->frameCount()) {
Andy Hung833b4752016-04-04 17:15:48 -07002003 ALOGV("framecount differs: %zu/%zu frames",
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002004 mRecycledTrack->frameCount(), t->frameCount());
2005 reuse = false;
2006 }
2007 }
2008
Marco Nelissen67295b52012-06-11 14:52:53 -07002009 if (reuse) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002010 ALOGV("chaining to next output and recycling track");
Andy Hungd1c74342015-07-07 16:54:23 -07002011 close_l();
Marco Nelissen67295b52012-06-11 14:52:53 -07002012 mTrack = mRecycledTrack;
Glenn Kasten2799d742013-05-30 14:33:29 -07002013 mRecycledTrack.clear();
Marco Nelissen67295b52012-06-11 14:52:53 -07002014 if (mCallbackData != NULL) {
2015 mCallbackData->setOutput(this);
2016 }
Marco Nelissen67295b52012-06-11 14:52:53 -07002017 delete newcbd;
Wei Jiae0bbac92016-07-18 16:04:53 -07002018 return updateTrack();
Marco Nelissen67295b52012-06-11 14:52:53 -07002019 }
Marco Nelissen67295b52012-06-11 14:52:53 -07002020 }
2021
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002022 // we're not going to reuse the track, unblock and flush it
2023 // this was done earlier if both tracks are offloaded
2024 if (!bothOffloaded) {
Andy Hungd1c74342015-07-07 16:54:23 -07002025 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002026 }
2027
2028 CHECK((t != NULL) && ((mCallback == NULL) || (newcbd != NULL)));
2029
Marco Nelissen67295b52012-06-11 14:52:53 -07002030 mCallbackData = newcbd;
Steve Block3856b092011-10-20 11:56:00 +01002031 ALOGV("setVolume");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002032 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07002033
Andy Hung39399b62017-04-21 15:07:45 -07002034 // Restore VolumeShapers for the MediaPlayer in case the track was recreated
2035 // due to an output sink error (e.g. offload to non-offload switch).
2036 mVolumeHandler->forall([&t](const VolumeShaper &shaper) -> VolumeShaper::Status {
2037 sp<VolumeShaper::Operation> operationToEnd =
2038 new VolumeShaper::Operation(shaper.mOperation);
2039 // TODO: Ideally we would restore to the exact xOffset position
2040 // as returned by getVolumeShaperState(), but we don't have that
2041 // information when restoring at the client unless we periodically poll
2042 // the server or create shared memory state.
2043 //
2044 // For now, we simply advance to the end of the VolumeShaper effect
2045 // if it has been started.
2046 if (shaper.isStarted()) {
Andy Hungf3702642017-05-05 17:33:32 -07002047 operationToEnd->setNormalizedTime(1.f);
Andy Hung39399b62017-04-21 15:07:45 -07002048 }
2049 return t->applyVolumeShaper(shaper.mConfiguration, operationToEnd);
Andy Hung4ef88d72017-02-21 19:47:53 -08002050 });
Andy Hung4ef88d72017-02-21 19:47:53 -08002051
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002052 mSampleRateHz = sampleRate;
Preetam Singh Ranawat2e17eef2015-08-12 12:11:46 -07002053 mFlags = flags;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002054 mMsecsPerFrame = 1E3f / (mPlaybackRate.mSpeed * sampleRate);
Andy Hungd1c74342015-07-07 16:54:23 -07002055 mFrameSize = t->frameSize();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002056 mTrack = t;
Eric Laurent2beeb502010-07-16 07:43:46 -07002057
Wei Jiae0bbac92016-07-18 16:04:53 -07002058 return updateTrack();
2059}
2060
2061status_t MediaPlayerService::AudioOutput::updateTrack() {
2062 if (mTrack == NULL) {
2063 return NO_ERROR;
2064 }
2065
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002066 status_t res = NO_ERROR;
Wei Jia0162d002015-06-09 11:59:33 -07002067 // Note some output devices may give us a direct track even though we don't specify it.
2068 // Example: Line application b/17459982.
Wei Jiae0bbac92016-07-18 16:04:53 -07002069 if ((mTrack->getFlags()
2070 & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) {
2071 res = mTrack->setPlaybackRate(mPlaybackRate);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002072 if (res == NO_ERROR) {
Wei Jiae0bbac92016-07-18 16:04:53 -07002073 mTrack->setAuxEffectSendLevel(mSendLevel);
2074 res = mTrack->attachAuxEffect(mAuxEffectId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002075 }
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002076 }
Wei Jiae0bbac92016-07-18 16:04:53 -07002077 ALOGV("updateTrack() DONE status %d", res);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002078 return res;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002079}
2080
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002081status_t MediaPlayerService::AudioOutput::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002082{
Steve Block3856b092011-10-20 11:56:00 +01002083 ALOGV("start");
Andy Hungd1c74342015-07-07 16:54:23 -07002084 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08002085 if (mCallbackData != NULL) {
2086 mCallbackData->endTrackSwitch();
2087 }
Glenn Kasten2799d742013-05-30 14:33:29 -07002088 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002089 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07002090 mTrack->setAuxEffectSendLevel(mSendLevel);
Andy Hung39399b62017-04-21 15:07:45 -07002091 status_t status = mTrack->start();
2092 if (status == NO_ERROR) {
2093 mVolumeHandler->setStarted();
2094 }
2095 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002096 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002097 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002098}
2099
Marco Nelissen6b74d672012-02-28 16:07:44 -08002100void MediaPlayerService::AudioOutput::setNextOutput(const sp<AudioOutput>& nextOutput) {
Andy Hungd1c74342015-07-07 16:54:23 -07002101 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08002102 mNextOutput = nextOutput;
2103}
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08002104
Marco Nelissen6b74d672012-02-28 16:07:44 -08002105void MediaPlayerService::AudioOutput::switchToNextOutput() {
2106 ALOGV("switchToNextOutput");
Andy Hungd1c74342015-07-07 16:54:23 -07002107
2108 // Try to acquire the callback lock before moving track (without incurring deadlock).
2109 const unsigned kMaxSwitchTries = 100;
2110 Mutex::Autolock lock(mLock);
2111 for (unsigned tries = 0;;) {
2112 if (mTrack == 0) {
2113 return;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002114 }
Andy Hungd1c74342015-07-07 16:54:23 -07002115 if (mNextOutput != NULL && mNextOutput != this) {
2116 if (mCallbackData != NULL) {
2117 // two alternative approaches
2118#if 1
2119 CallbackData *callbackData = mCallbackData;
2120 mLock.unlock();
2121 // proper acquisition sequence
2122 callbackData->lock();
2123 mLock.lock();
2124 // Caution: it is unlikely that someone deleted our callback or changed our target
2125 if (callbackData != mCallbackData || mNextOutput == NULL || mNextOutput == this) {
2126 // fatal if we are starved out.
2127 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2128 "switchToNextOutput() cannot obtain correct lock sequence");
2129 callbackData->unlock();
2130 continue;
2131 }
2132 callbackData->mSwitching = true; // begin track switch
Wei Jiaadee56a2016-08-05 15:40:34 -07002133 callbackData->setOutput(NULL);
Andy Hungd1c74342015-07-07 16:54:23 -07002134#else
2135 // tryBeginTrackSwitch() returns false if the callback has the lock.
2136 if (!mCallbackData->tryBeginTrackSwitch()) {
2137 // fatal if we are starved out.
2138 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2139 "switchToNextOutput() cannot obtain callback lock");
2140 mLock.unlock();
2141 usleep(5 * 1000 /* usec */); // allow callback to use AudioOutput
2142 mLock.lock();
2143 continue;
2144 }
2145#endif
2146 }
2147
2148 Mutex::Autolock nextLock(mNextOutput->mLock);
2149
2150 // If the next output track is not NULL, then it has been
2151 // opened already for playback.
2152 // This is possible even without the next player being started,
2153 // for example, the next player could be prepared and seeked.
2154 //
2155 // Presuming it isn't advisable to force the track over.
2156 if (mNextOutput->mTrack == NULL) {
2157 ALOGD("Recycling track for gapless playback");
2158 delete mNextOutput->mCallbackData;
2159 mNextOutput->mCallbackData = mCallbackData;
2160 mNextOutput->mRecycledTrack = mTrack;
2161 mNextOutput->mSampleRateHz = mSampleRateHz;
2162 mNextOutput->mMsecsPerFrame = mMsecsPerFrame;
Andy Hungd1c74342015-07-07 16:54:23 -07002163 mNextOutput->mFlags = mFlags;
2164 mNextOutput->mFrameSize = mFrameSize;
2165 close_l();
2166 mCallbackData = NULL; // destruction handled by mNextOutput
2167 } else {
2168 ALOGW("Ignoring gapless playback because next player has already started");
2169 // remove track in case resource needed for future players.
2170 if (mCallbackData != NULL) {
2171 mCallbackData->endTrackSwitch(); // release lock for callbacks before close.
2172 }
2173 close_l();
2174 }
2175 }
2176 break;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002177 }
2178}
2179
Wei Jia7d3f4df2015-03-03 15:28:00 -08002180ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002181{
Andy Hungd1c74342015-07-07 16:54:23 -07002182 Mutex::Autolock lock(mLock);
Glenn Kastenadad3d72014-02-21 14:51:43 -08002183 LOG_ALWAYS_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
Andreas Huber20111aa2009-07-14 16:56:47 -07002184
Steve Block3856b092011-10-20 11:56:00 +01002185 //ALOGV("write(%p, %u)", buffer, size);
Glenn Kasten2799d742013-05-30 14:33:29 -07002186 if (mTrack != 0) {
Andy Hung2f6e73d2016-04-08 12:12:58 -07002187 return mTrack->write(buffer, size, blocking);
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07002188 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002189 return NO_INIT;
2190}
2191
2192void MediaPlayerService::AudioOutput::stop()
2193{
Steve Block3856b092011-10-20 11:56:00 +01002194 ALOGV("stop");
Andy Hungd1c74342015-07-07 16:54:23 -07002195 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002196 if (mTrack != 0) mTrack->stop();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002197}
2198
2199void MediaPlayerService::AudioOutput::flush()
2200{
Steve Block3856b092011-10-20 11:56:00 +01002201 ALOGV("flush");
Andy Hungd1c74342015-07-07 16:54:23 -07002202 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002203 if (mTrack != 0) mTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002204}
2205
2206void MediaPlayerService::AudioOutput::pause()
2207{
Steve Block3856b092011-10-20 11:56:00 +01002208 ALOGV("pause");
Andy Hungd1c74342015-07-07 16:54:23 -07002209 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002210 if (mTrack != 0) mTrack->pause();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002211}
2212
2213void MediaPlayerService::AudioOutput::close()
2214{
Steve Block3856b092011-10-20 11:56:00 +01002215 ALOGV("close");
Erik Wolsheimer7845a1f2015-10-30 12:07:52 -07002216 sp<AudioTrack> track;
2217 {
2218 Mutex::Autolock lock(mLock);
2219 track = mTrack;
2220 close_l(); // clears mTrack
2221 }
2222 // destruction of the track occurs outside of mutex.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002223}
2224
2225void MediaPlayerService::AudioOutput::setVolume(float left, float right)
2226{
Steve Block3856b092011-10-20 11:56:00 +01002227 ALOGV("setVolume(%f, %f)", left, right);
Andy Hungd1c74342015-07-07 16:54:23 -07002228 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002229 mLeftVolume = left;
2230 mRightVolume = right;
Glenn Kasten2799d742013-05-30 14:33:29 -07002231 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002232 mTrack->setVolume(left, right);
2233 }
2234}
2235
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002236status_t MediaPlayerService::AudioOutput::setPlaybackRate(const AudioPlaybackRate &rate)
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002237{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002238 ALOGV("setPlaybackRate(%f %f %d %d)",
2239 rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Andy Hungd1c74342015-07-07 16:54:23 -07002240 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002241 if (mTrack == 0) {
2242 // remember rate so that we can set it when the track is opened
2243 mPlaybackRate = rate;
2244 return OK;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002245 }
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002246 status_t res = mTrack->setPlaybackRate(rate);
2247 if (res != NO_ERROR) {
2248 return res;
2249 }
2250 // rate.mSpeed is always greater than 0 if setPlaybackRate succeeded
2251 CHECK_GT(rate.mSpeed, 0.f);
2252 mPlaybackRate = rate;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002253 if (mSampleRateHz != 0) {
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002254 mMsecsPerFrame = 1E3f / (rate.mSpeed * mSampleRateHz);
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002255 }
2256 return res;
2257}
2258
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002259status_t MediaPlayerService::AudioOutput::getPlaybackRate(AudioPlaybackRate *rate)
2260{
2261 ALOGV("setPlaybackRate");
Andy Hungd1c74342015-07-07 16:54:23 -07002262 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002263 if (mTrack == 0) {
2264 return NO_INIT;
2265 }
2266 *rate = mTrack->getPlaybackRate();
2267 return NO_ERROR;
2268}
2269
Eric Laurent2beeb502010-07-16 07:43:46 -07002270status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
2271{
Steve Block3856b092011-10-20 11:56:00 +01002272 ALOGV("setAuxEffectSendLevel(%f)", level);
Andy Hungd1c74342015-07-07 16:54:23 -07002273 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002274 mSendLevel = level;
Glenn Kasten2799d742013-05-30 14:33:29 -07002275 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002276 return mTrack->setAuxEffectSendLevel(level);
2277 }
2278 return NO_ERROR;
2279}
2280
2281status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
2282{
Steve Block3856b092011-10-20 11:56:00 +01002283 ALOGV("attachAuxEffect(%d)", effectId);
Andy Hungd1c74342015-07-07 16:54:23 -07002284 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002285 mAuxEffectId = effectId;
Glenn Kasten2799d742013-05-30 14:33:29 -07002286 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002287 return mTrack->attachAuxEffect(effectId);
2288 }
2289 return NO_ERROR;
2290}
2291
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002292VolumeShaper::Status MediaPlayerService::AudioOutput::applyVolumeShaper(
2293 const sp<VolumeShaper::Configuration>& configuration,
2294 const sp<VolumeShaper::Operation>& operation)
2295{
2296 Mutex::Autolock lock(mLock);
2297 ALOGV("AudioOutput::applyVolumeShaper");
Andy Hung4ef88d72017-02-21 19:47:53 -08002298
Andy Hung4ef88d72017-02-21 19:47:53 -08002299 mVolumeHandler->setIdIfNecessary(configuration);
Andy Hung39399b62017-04-21 15:07:45 -07002300
2301 VolumeShaper::Status status;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002302 if (mTrack != 0) {
Andy Hung39399b62017-04-21 15:07:45 -07002303 status = mTrack->applyVolumeShaper(configuration, operation);
2304 if (status >= 0) {
2305 (void)mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hungf3702642017-05-05 17:33:32 -07002306 if (mTrack->isPlaying()) { // match local AudioTrack to properly restore.
2307 mVolumeHandler->setStarted();
2308 }
Andy Hung39399b62017-04-21 15:07:45 -07002309 }
Andy Hung4ef88d72017-02-21 19:47:53 -08002310 } else {
Andy Hungc01eddb2017-07-21 16:42:41 -07002311 // VolumeShapers are not affected when a track moves between players for
2312 // gapless playback (setNextMediaPlayer).
2313 // We forward VolumeShaper operations that do not change configuration
2314 // to the new player so that unducking may occur as expected.
2315 // Unducking is an idempotent operation, same if applied back-to-back.
2316 if (configuration->getType() == VolumeShaper::Configuration::TYPE_ID
2317 && mNextOutput != nullptr) {
2318 ALOGV("applyVolumeShaper: Attempting to forward missed operation: %s %s",
2319 configuration->toString().c_str(), operation->toString().c_str());
2320 Mutex::Autolock nextLock(mNextOutput->mLock);
2321
2322 // recycled track should be forwarded from this AudioSink by switchToNextOutput
2323 sp<AudioTrack> track = mNextOutput->mRecycledTrack;
2324 if (track != nullptr) {
2325 ALOGD("Forward VolumeShaper operation to recycled track %p", track.get());
2326 (void)track->applyVolumeShaper(configuration, operation);
2327 } else {
2328 // There is a small chance that the unduck occurs after the next
2329 // player has already started, but before it is registered to receive
2330 // the unduck command.
2331 track = mNextOutput->mTrack;
2332 if (track != nullptr) {
2333 ALOGD("Forward VolumeShaper operation to track %p", track.get());
2334 (void)track->applyVolumeShaper(configuration, operation);
2335 }
2336 }
2337 }
Andy Hung39399b62017-04-21 15:07:45 -07002338 status = mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002339 }
Andy Hung39399b62017-04-21 15:07:45 -07002340 return status;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002341}
2342
2343sp<VolumeShaper::State> MediaPlayerService::AudioOutput::getVolumeShaperState(int id)
2344{
2345 Mutex::Autolock lock(mLock);
2346 if (mTrack != 0) {
2347 return mTrack->getVolumeShaperState(id);
Andy Hung4ef88d72017-02-21 19:47:53 -08002348 } else {
2349 return mVolumeHandler->getVolumeShaperState(id);
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002350 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002351}
2352
Andreas Huber20111aa2009-07-14 16:56:47 -07002353// static
2354void MediaPlayerService::AudioOutput::CallbackWrapper(
Glenn Kastend217a8c2011-06-01 15:20:35 -07002355 int event, void *cookie, void *info) {
Steve Block3856b092011-10-20 11:56:00 +01002356 //ALOGV("callbackwrapper");
Marco Nelissen6b74d672012-02-28 16:07:44 -08002357 CallbackData *data = (CallbackData*)cookie;
Andy Hungd1c74342015-07-07 16:54:23 -07002358 // lock to ensure we aren't caught in the middle of a track switch.
Marco Nelissen6b74d672012-02-28 16:07:44 -08002359 data->lock();
2360 AudioOutput *me = data->getOutput();
Andreas Huber20111aa2009-07-14 16:56:47 -07002361 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002362 if (me == NULL) {
2363 // no output set, likely because the track was scheduled to be reused
2364 // by another player, but the format turned out to be incompatible.
2365 data->unlock();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002366 if (buffer != NULL) {
2367 buffer->size = 0;
2368 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08002369 return;
2370 }
Andreas Huber20111aa2009-07-14 16:56:47 -07002371
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002372 switch(event) {
2373 case AudioTrack::EVENT_MORE_DATA: {
2374 size_t actualSize = (*me->mCallback)(
2375 me, buffer->raw, buffer->size, me->mCallbackCookie,
2376 CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002377
Andy Hung719b46b2015-05-31 22:18:25 -07002378 // Log when no data is returned from the callback.
2379 // (1) We may have no data (especially with network streaming sources).
2380 // (2) We may have reached the EOS and the audio track is not stopped yet.
2381 // Note that AwesomePlayer/AudioPlayer will only return zero size when it reaches the EOS.
2382 // NuPlayerRenderer will return zero when it doesn't have data (it doesn't block to fill).
2383 //
2384 // This is a benign busy-wait, with the next data request generated 10 ms or more later;
2385 // nevertheless for power reasons, we don't want to see too many of these.
Andreas Huber2e8ffaf2010-02-18 16:45:13 -08002386
Andy Hung719b46b2015-05-31 22:18:25 -07002387 ALOGV_IF(actualSize == 0 && buffer->size > 0, "callbackwrapper: empty buffer returned");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002388
2389 buffer->size = actualSize;
2390 } break;
2391
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002392 case AudioTrack::EVENT_STREAM_END:
Andy Hung719b46b2015-05-31 22:18:25 -07002393 // currently only occurs for offloaded callbacks
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002394 ALOGV("callbackwrapper: deliver EVENT_STREAM_END");
2395 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2396 me->mCallbackCookie, CB_EVENT_STREAM_END);
2397 break;
2398
2399 case AudioTrack::EVENT_NEW_IAUDIOTRACK :
2400 ALOGV("callbackwrapper: deliver EVENT_TEAR_DOWN");
2401 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2402 me->mCallbackCookie, CB_EVENT_TEAR_DOWN);
2403 break;
2404
Glenn Kasten421743b2015-06-01 08:18:08 -07002405 case AudioTrack::EVENT_UNDERRUN:
Andy Hung719b46b2015-05-31 22:18:25 -07002406 // This occurs when there is no data available, typically
Glenn Kasten421743b2015-06-01 08:18:08 -07002407 // when there is a failure to supply data to the AudioTrack. It can also
2408 // occur in non-offloaded mode when the audio device comes out of standby.
2409 //
Andy Hung719b46b2015-05-31 22:18:25 -07002410 // If an AudioTrack underruns it outputs silence. Since this happens suddenly
2411 // it may sound like an audible pop or glitch.
2412 //
2413 // The underrun event is sent once per track underrun; the condition is reset
2414 // when more data is sent to the AudioTrack.
Eric Laurente93cc032016-05-05 10:15:10 -07002415 ALOGD("callbackwrapper: EVENT_UNDERRUN (discarded)");
Glenn Kasten421743b2015-06-01 08:18:08 -07002416 break;
2417
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002418 default:
2419 ALOGE("received unknown event type: %d inside CallbackWrapper !", event);
Andreas Huber51c1e0e2011-04-04 11:43:40 -07002420 }
2421
Marco Nelissen6b74d672012-02-28 16:07:44 -08002422 data->unlock();
Andreas Huber20111aa2009-07-14 16:56:47 -07002423}
2424
Glenn Kastend848eb42016-03-08 13:42:11 -08002425audio_session_t MediaPlayerService::AudioOutput::getSessionId() const
Eric Laurent8c563ed2010-10-07 18:23:03 -07002426{
Andy Hungd1c74342015-07-07 16:54:23 -07002427 Mutex::Autolock lock(mLock);
Eric Laurent8c563ed2010-10-07 18:23:03 -07002428 return mSessionId;
2429}
2430
Eric Laurent6f59db12013-07-26 17:16:50 -07002431uint32_t MediaPlayerService::AudioOutput::getSampleRate() const
2432{
Andy Hungd1c74342015-07-07 16:54:23 -07002433 Mutex::Autolock lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -07002434 if (mTrack == 0) return 0;
2435 return mTrack->getSampleRate();
2436}
2437
Andy Hungf2c87b32016-04-07 19:49:29 -07002438int64_t MediaPlayerService::AudioOutput::getBufferDurationInUs() const
2439{
2440 Mutex::Autolock lock(mLock);
2441 if (mTrack == 0) {
2442 return 0;
2443 }
2444 int64_t duration;
2445 if (mTrack->getBufferDurationInUs(&duration) != OK) {
2446 return 0;
2447 }
2448 return duration;
2449}
2450
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002451////////////////////////////////////////////////////////////////////////////////
2452
2453struct CallbackThread : public Thread {
2454 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
2455 MediaPlayerBase::AudioSink::AudioCallback cb,
2456 void *cookie);
2457
2458protected:
2459 virtual ~CallbackThread();
2460
2461 virtual bool threadLoop();
2462
2463private:
2464 wp<MediaPlayerBase::AudioSink> mSink;
2465 MediaPlayerBase::AudioSink::AudioCallback mCallback;
2466 void *mCookie;
2467 void *mBuffer;
2468 size_t mBufferSize;
2469
2470 CallbackThread(const CallbackThread &);
2471 CallbackThread &operator=(const CallbackThread &);
2472};
2473
2474CallbackThread::CallbackThread(
2475 const wp<MediaPlayerBase::AudioSink> &sink,
2476 MediaPlayerBase::AudioSink::AudioCallback cb,
2477 void *cookie)
2478 : mSink(sink),
2479 mCallback(cb),
2480 mCookie(cookie),
2481 mBuffer(NULL),
2482 mBufferSize(0) {
2483}
2484
2485CallbackThread::~CallbackThread() {
2486 if (mBuffer) {
2487 free(mBuffer);
2488 mBuffer = NULL;
2489 }
2490}
2491
2492bool CallbackThread::threadLoop() {
2493 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
2494 if (sink == NULL) {
2495 return false;
2496 }
2497
2498 if (mBuffer == NULL) {
2499 mBufferSize = sink->bufferSize();
2500 mBuffer = malloc(mBufferSize);
2501 }
2502
2503 size_t actualSize =
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002504 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie,
2505 MediaPlayerBase::AudioSink::CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002506
2507 if (actualSize > 0) {
2508 sink->write(mBuffer, actualSize);
Andy Hunga31335a2014-08-20 17:37:59 -07002509 // Could return false on sink->write() error or short count.
2510 // Not necessarily appropriate but would work for AudioCache behavior.
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002511 }
2512
2513 return true;
2514}
2515
2516////////////////////////////////////////////////////////////////////////////////
2517
Chong Zhange5b9b692017-05-11 11:44:56 -07002518void MediaPlayerService::addBatteryData(uint32_t params) {
2519 mBatteryTracker.addBatteryData(params);
2520}
2521
2522status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
2523 return mBatteryTracker.pullBatteryData(reply);
2524}
2525
2526MediaPlayerService::BatteryTracker::BatteryTracker() {
2527 mBatteryAudio.refCount = 0;
2528 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2529 mBatteryAudio.deviceOn[i] = 0;
2530 mBatteryAudio.lastTime[i] = 0;
2531 mBatteryAudio.totalTime[i] = 0;
2532 }
2533 // speaker is on by default
2534 mBatteryAudio.deviceOn[SPEAKER] = 1;
2535
2536 // reset battery stats
2537 // if the mediaserver has crashed, battery stats could be left
2538 // in bad state, reset the state upon service start.
2539 BatteryNotifier::getInstance().noteResetVideo();
2540}
2541
2542void MediaPlayerService::BatteryTracker::addBatteryData(uint32_t params)
Gloria Wang7cf180c2011-02-19 18:37:57 -08002543{
2544 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002545
2546 int32_t time = systemTime() / 1000000L;
2547
2548 // change audio output devices. This notification comes from AudioFlinger
2549 if ((params & kBatteryDataSpeakerOn)
2550 || (params & kBatteryDataOtherAudioDeviceOn)) {
2551
2552 int deviceOn[NUM_AUDIO_DEVICES];
2553 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2554 deviceOn[i] = 0;
2555 }
2556
2557 if ((params & kBatteryDataSpeakerOn)
2558 && (params & kBatteryDataOtherAudioDeviceOn)) {
2559 deviceOn[SPEAKER_AND_OTHER] = 1;
2560 } else if (params & kBatteryDataSpeakerOn) {
2561 deviceOn[SPEAKER] = 1;
2562 } else {
2563 deviceOn[OTHER_AUDIO_DEVICE] = 1;
2564 }
2565
2566 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2567 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
2568
2569 if (mBatteryAudio.refCount > 0) { // if playing audio
2570 if (!deviceOn[i]) {
2571 mBatteryAudio.lastTime[i] += time;
2572 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2573 mBatteryAudio.lastTime[i] = 0;
2574 } else {
2575 mBatteryAudio.lastTime[i] = 0 - time;
2576 }
2577 }
2578
2579 mBatteryAudio.deviceOn[i] = deviceOn[i];
2580 }
2581 }
2582 return;
2583 }
2584
Marco Nelissenb7848f12014-12-04 08:57:56 -08002585 // an audio stream is started
Gloria Wang9ee159b2011-02-24 14:51:45 -08002586 if (params & kBatteryDataAudioFlingerStart) {
2587 // record the start time only if currently no other audio
2588 // is being played
2589 if (mBatteryAudio.refCount == 0) {
2590 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2591 if (mBatteryAudio.deviceOn[i]) {
2592 mBatteryAudio.lastTime[i] -= time;
2593 }
2594 }
2595 }
2596
2597 mBatteryAudio.refCount ++;
2598 return;
2599
2600 } else if (params & kBatteryDataAudioFlingerStop) {
2601 if (mBatteryAudio.refCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002602 ALOGW("Battery track warning: refCount is <= 0");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002603 return;
2604 }
2605
2606 // record the stop time only if currently this is the only
2607 // audio being played
2608 if (mBatteryAudio.refCount == 1) {
2609 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2610 if (mBatteryAudio.deviceOn[i]) {
2611 mBatteryAudio.lastTime[i] += time;
2612 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2613 mBatteryAudio.lastTime[i] = 0;
2614 }
2615 }
2616 }
2617
2618 mBatteryAudio.refCount --;
2619 return;
2620 }
2621
Andy Hung1afd0982016-11-08 16:13:44 -08002622 uid_t uid = IPCThreadState::self()->getCallingUid();
Gloria Wang7cf180c2011-02-19 18:37:57 -08002623 if (uid == AID_MEDIA) {
2624 return;
2625 }
2626 int index = mBatteryData.indexOfKey(uid);
Gloria Wang7cf180c2011-02-19 18:37:57 -08002627
2628 if (index < 0) { // create a new entry for this UID
2629 BatteryUsageInfo info;
2630 info.audioTotalTime = 0;
2631 info.videoTotalTime = 0;
2632 info.audioLastTime = 0;
2633 info.videoLastTime = 0;
2634 info.refCount = 0;
2635
Gloria Wang9ee159b2011-02-24 14:51:45 -08002636 if (mBatteryData.add(uid, info) == NO_MEMORY) {
Steve Block29357bc2012-01-06 19:20:56 +00002637 ALOGE("Battery track error: no memory for new app");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002638 return;
2639 }
Gloria Wang7cf180c2011-02-19 18:37:57 -08002640 }
2641
2642 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
2643
2644 if (params & kBatteryDataCodecStarted) {
2645 if (params & kBatteryDataTrackAudio) {
2646 info.audioLastTime -= time;
2647 info.refCount ++;
2648 }
2649 if (params & kBatteryDataTrackVideo) {
2650 info.videoLastTime -= time;
2651 info.refCount ++;
2652 }
2653 } else {
2654 if (info.refCount == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002655 ALOGW("Battery track warning: refCount is already 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002656 return;
2657 } else if (info.refCount < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00002658 ALOGE("Battery track error: refCount < 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002659 mBatteryData.removeItem(uid);
2660 return;
2661 }
2662
2663 if (params & kBatteryDataTrackAudio) {
2664 info.audioLastTime += time;
2665 info.refCount --;
2666 }
2667 if (params & kBatteryDataTrackVideo) {
2668 info.videoLastTime += time;
2669 info.refCount --;
2670 }
2671
2672 // no stream is being played by this UID
2673 if (info.refCount == 0) {
2674 info.audioTotalTime += info.audioLastTime;
2675 info.audioLastTime = 0;
2676 info.videoTotalTime += info.videoLastTime;
2677 info.videoLastTime = 0;
2678 }
2679 }
2680}
2681
Chong Zhange5b9b692017-05-11 11:44:56 -07002682status_t MediaPlayerService::BatteryTracker::pullBatteryData(Parcel* reply) {
Gloria Wang7cf180c2011-02-19 18:37:57 -08002683 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002684
2685 // audio output devices usage
2686 int32_t time = systemTime() / 1000000L; //in ms
2687 int32_t totalTime;
2688
2689 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2690 totalTime = mBatteryAudio.totalTime[i];
2691
2692 if (mBatteryAudio.deviceOn[i]
2693 && (mBatteryAudio.lastTime[i] != 0)) {
2694 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
2695 totalTime += tmpTime;
2696 }
2697
2698 reply->writeInt32(totalTime);
2699 // reset the total time
2700 mBatteryAudio.totalTime[i] = 0;
2701 }
2702
2703 // codec usage
Gloria Wang7cf180c2011-02-19 18:37:57 -08002704 BatteryUsageInfo info;
2705 int size = mBatteryData.size();
2706
2707 reply->writeInt32(size);
2708 int i = 0;
2709
2710 while (i < size) {
2711 info = mBatteryData.valueAt(i);
2712
2713 reply->writeInt32(mBatteryData.keyAt(i)); //UID
2714 reply->writeInt32(info.audioTotalTime);
2715 reply->writeInt32(info.videoTotalTime);
2716
2717 info.audioTotalTime = 0;
2718 info.videoTotalTime = 0;
2719
2720 // remove the UID entry where no stream is being played
2721 if (info.refCount <= 0) {
2722 mBatteryData.removeItemsAt(i);
2723 size --;
2724 i --;
2725 }
2726 i++;
2727 }
2728 return NO_ERROR;
2729}
nikoa64c8c72009-07-20 15:07:26 -07002730} // namespace android