blob: beceed32e00452eeaef6d3475a6b5a40e93f0b55 [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);
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700585 mAudioOutput.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800586 wp<Client> client(this);
587 disconnect();
588 mService->removeClient(client);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700589 if (mAudioAttributes != NULL) {
590 free(mAudioAttributes);
591 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700592 clearDeathNotifiers_l();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800593}
594
595void MediaPlayerService::Client::disconnect()
596{
Steve Block3856b092011-10-20 11:56:00 +0100597 ALOGV("disconnect(%d) from pid %d", mConnId, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800598 // grab local reference and clear main reference to prevent future
599 // access to object
600 sp<MediaPlayerBase> p;
601 {
602 Mutex::Autolock l(mLock);
603 p = mPlayer;
beanzdcfefde2012-11-05 09:51:43 +0800604 mClient.clear();
Wei Jia502c2f42017-07-13 17:47:56 -0700605 mPlayer.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800606 }
Andreas Huber20111aa2009-07-14 16:56:47 -0700607
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800608 // clear the notification to prevent callbacks to dead client
609 // and reset the player. We assume the player will serialize
610 // access to itself if necessary.
611 if (p != 0) {
612 p->setNotifyCallback(0, 0);
613#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000614 ALOGD("kill Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800615 mAntagonizer->kill();
616#endif
617 p->reset();
618 }
619
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700620 {
621 Mutex::Autolock l(mLock);
622 disconnectNativeWindow_l();
623 }
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700624
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
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700700void MediaPlayerService::Client::clearDeathNotifiers_l() {
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800701 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);
715
716 // create the right type of player
717 sp<MediaPlayerBase> p = createPlayer(playerType);
718 if (p == NULL) {
719 return p;
720 }
721
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700722 sp<IServiceManager> sm = defaultServiceManager();
723 sp<IBinder> binder = sm->getService(String16("media.extractor"));
Marco Nelissen1b5a7ee2016-09-30 13:54:30 -0700724 if (binder == NULL) {
725 ALOGE("extractor service not available");
726 return NULL;
727 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700728 sp<ServiceDeathNotifier> extractorDeathListener =
729 new ServiceDeathNotifier(binder, p, MEDIAEXTRACTOR_PROCESS_DEATH);
730 binder->linkToDeath(extractorDeathListener);
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700731
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700732 sp<ServiceDeathNotifier> codecDeathListener;
Colin Cross85e88d92017-10-26 16:16:55 -0700733 if (property_get_bool("persist.media.treble_omx", true)) {
734 // Treble IOmx
735 sp<IOmx> omx = IOmx::getService();
736 if (omx == nullptr) {
737 ALOGE("Treble IOmx not available");
738 return NULL;
739 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700740 codecDeathListener = new ServiceDeathNotifier(omx, p, MEDIACODEC_PROCESS_DEATH);
741 omx->linkToDeath(codecDeathListener, 0);
Colin Cross85e88d92017-10-26 16:16:55 -0700742 } else {
743 // Legacy IOMX
744 binder = sm->getService(String16("media.codec"));
745 if (binder == NULL) {
746 ALOGE("codec service not available");
747 return NULL;
748 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700749 codecDeathListener = new ServiceDeathNotifier(binder, p, MEDIACODEC_PROCESS_DEATH);
750 binder->linkToDeath(codecDeathListener);
Marco Nelissen1b5a7ee2016-09-30 13:54:30 -0700751 }
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700752
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700753 Mutex::Autolock lock(mLock);
754
755 clearDeathNotifiers_l();
756 mExtractorDeathListener = extractorDeathListener;
757 mCodecDeathListener = codecDeathListener;
758
John Grossmanc795b642012-02-22 15:38:35 -0800759 if (!p->hardwareOutput()) {
Marco Nelissend457c972014-02-11 08:47:07 -0800760 mAudioOutput = new AudioOutput(mAudioSessionId, IPCThreadState::self()->getCallingUid(),
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700761 mPid, mAudioAttributes);
John Grossmanc795b642012-02-22 15:38:35 -0800762 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
763 }
764
765 return p;
766}
767
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700768status_t MediaPlayerService::Client::setDataSource_post(
John Grossmanc795b642012-02-22 15:38:35 -0800769 const sp<MediaPlayerBase>& p,
770 status_t status)
771{
772 ALOGV(" setDataSource");
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700773 if (status != OK) {
774 ALOGE(" error: %d", status);
775 return status;
John Grossmanc795b642012-02-22 15:38:35 -0800776 }
777
778 // Set the re-transmission endpoint if one was chosen.
779 if (mRetransmitEndpointValid) {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700780 status = p->setRetransmitEndpoint(&mRetransmitEndpoint);
781 if (status != NO_ERROR) {
782 ALOGE("setRetransmitEndpoint error: %d", status);
John Grossmanc795b642012-02-22 15:38:35 -0800783 }
784 }
785
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700786 if (status == OK) {
787 Mutex::Autolock lock(mLock);
John Grossmanc795b642012-02-22 15:38:35 -0800788 mPlayer = p;
789 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700790 return status;
John Grossmanc795b642012-02-22 15:38:35 -0800791}
792
Andreas Huber2db84552010-01-28 11:19:57 -0800793status_t MediaPlayerService::Client::setDataSource(
Andreas Huber1b86fe02014-01-29 11:13:26 -0800794 const sp<IMediaHTTPService> &httpService,
795 const char *url,
796 const KeyedVector<String8, String8> *headers)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800797{
Steve Block3856b092011-10-20 11:56:00 +0100798 ALOGV("setDataSource(%s)", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800799 if (url == NULL)
800 return UNKNOWN_ERROR;
801
Dave Burked681bbb2011-08-30 14:39:17 +0100802 if ((strncmp(url, "http://", 7) == 0) ||
803 (strncmp(url, "https://", 8) == 0) ||
804 (strncmp(url, "rtsp://", 7) == 0)) {
805 if (!checkPermission("android.permission.INTERNET")) {
806 return PERMISSION_DENIED;
807 }
808 }
809
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800810 if (strncmp(url, "content://", 10) == 0) {
811 // get a filedescriptor for the content Uri and
812 // pass it to the setDataSource(fd) method
813
814 String16 url16(url);
815 int fd = android::openContentProviderFile(url16);
816 if (fd < 0)
817 {
Steve Block29357bc2012-01-06 19:20:56 +0000818 ALOGE("Couldn't open fd for %s", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800819 return UNKNOWN_ERROR;
820 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700821 status_t status = setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800822 close(fd);
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700823 return mStatus = status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800824 } else {
John Grossman44a7e422012-06-21 17:29:24 -0700825 player_type playerType = MediaPlayerFactory::getPlayerType(this, url);
John Grossmanc795b642012-02-22 15:38:35 -0800826 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
827 if (p == NULL) {
828 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800829 }
830
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700831 return mStatus =
832 setDataSource_post(
833 p, p->setDataSource(httpService, url, headers));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800834 }
835}
836
837status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
838{
Marco Nelissen83b0fd92015-09-16 13:48:07 -0700839 ALOGV("setDataSource fd=%d (%s), offset=%lld, length=%lld",
840 fd, nameForFd(fd).c_str(), (long long) offset, (long long) length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800841 struct stat sb;
842 int ret = fstat(fd, &sb);
843 if (ret != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000844 ALOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800845 return UNKNOWN_ERROR;
846 }
847
Andy Hung833b4752016-04-04 17:15:48 -0700848 ALOGV("st_dev = %llu", static_cast<unsigned long long>(sb.st_dev));
Steve Block3856b092011-10-20 11:56:00 +0100849 ALOGV("st_mode = %u", sb.st_mode);
Mark Salyzyn77342f72014-06-18 16:31:32 -0700850 ALOGV("st_uid = %lu", static_cast<unsigned long>(sb.st_uid));
851 ALOGV("st_gid = %lu", static_cast<unsigned long>(sb.st_gid));
Andy Hung833b4752016-04-04 17:15:48 -0700852 ALOGV("st_size = %llu", static_cast<unsigned long long>(sb.st_size));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800853
854 if (offset >= sb.st_size) {
Steve Block29357bc2012-01-06 19:20:56 +0000855 ALOGE("offset error");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800856 return UNKNOWN_ERROR;
857 }
858 if (offset + length > sb.st_size) {
859 length = sb.st_size - offset;
Andy Hung833b4752016-04-04 17:15:48 -0700860 ALOGV("calculated length = %lld", (long long)length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800861 }
862
John Grossman44a7e422012-06-21 17:29:24 -0700863 player_type playerType = MediaPlayerFactory::getPlayerType(this,
864 fd,
865 offset,
866 length);
John Grossmanc795b642012-02-22 15:38:35 -0800867 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
868 if (p == NULL) {
869 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800870 }
871
872 // now set data source
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700873 return mStatus = setDataSource_post(p, p->setDataSource(fd, offset, length));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800874}
875
Andreas Hubere2b10282010-11-23 11:41:34 -0800876status_t MediaPlayerService::Client::setDataSource(
877 const sp<IStreamSource> &source) {
878 // create the right type of player
John Grossman44a7e422012-06-21 17:29:24 -0700879 player_type playerType = MediaPlayerFactory::getPlayerType(this, source);
John Grossmanc795b642012-02-22 15:38:35 -0800880 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
Andreas Hubere2b10282010-11-23 11:41:34 -0800881 if (p == NULL) {
882 return NO_INIT;
883 }
884
Andreas Hubere2b10282010-11-23 11:41:34 -0800885 // now set data source
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700886 return mStatus = setDataSource_post(p, p->setDataSource(source));
Andreas Hubere2b10282010-11-23 11:41:34 -0800887}
888
Chris Watkins99f31602015-03-20 13:06:33 -0700889status_t MediaPlayerService::Client::setDataSource(
890 const sp<IDataSource> &source) {
Dongwon Kangd91dc5a2017-10-10 00:07:09 -0700891 sp<DataSource> dataSource = CreateDataSourceFromIDataSource(source);
Chris Watkins99f31602015-03-20 13:06:33 -0700892 player_type playerType = MediaPlayerFactory::getPlayerType(this, dataSource);
893 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
894 if (p == NULL) {
895 return NO_INIT;
896 }
897 // now set data source
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700898 return mStatus = setDataSource_post(p, p->setDataSource(dataSource));
Chris Watkins99f31602015-03-20 13:06:33 -0700899}
900
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700901void MediaPlayerService::Client::disconnectNativeWindow_l() {
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700902 if (mConnectedWindow != NULL) {
Chong Zhang181fd9b2017-02-16 15:53:03 -0800903 status_t err = nativeWindowDisconnect(
904 mConnectedWindow.get(), "disconnectNativeWindow");
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700905
906 if (err != OK) {
Chong Zhang181fd9b2017-02-16 15:53:03 -0800907 ALOGW("nativeWindowDisconnect returned an error: %s (%d)",
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700908 strerror(-err), err);
909 }
910 }
911 mConnectedWindow.clear();
912}
913
Glenn Kasten11731182011-02-08 17:26:17 -0800914status_t MediaPlayerService::Client::setVideoSurfaceTexture(
Andy McFadden484566c2012-12-18 09:46:54 -0800915 const sp<IGraphicBufferProducer>& bufferProducer)
Glenn Kasten11731182011-02-08 17:26:17 -0800916{
Andy McFadden484566c2012-12-18 09:46:54 -0800917 ALOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, bufferProducer.get());
Glenn Kasten11731182011-02-08 17:26:17 -0800918 sp<MediaPlayerBase> p = getPlayer();
919 if (p == 0) return UNKNOWN_ERROR;
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700920
Marco Nelissenf8880202014-11-14 07:58:25 -0800921 sp<IBinder> binder(IInterface::asBinder(bufferProducer));
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700922 if (mConnectedWindowBinder == binder) {
923 return OK;
924 }
925
926 sp<ANativeWindow> anw;
Andy McFadden484566c2012-12-18 09:46:54 -0800927 if (bufferProducer != NULL) {
Marco Nelissenee08f7e2013-09-16 13:30:01 -0700928 anw = new Surface(bufferProducer, true /* controlledByApp */);
Chong Zhang181fd9b2017-02-16 15:53:03 -0800929 status_t err = nativeWindowConnect(anw.get(), "setVideoSurfaceTexture");
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700930
931 if (err != OK) {
Steve Block29357bc2012-01-06 19:20:56 +0000932 ALOGE("setVideoSurfaceTexture failed: %d", err);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700933 // Note that we must do the reset before disconnecting from the ANW.
934 // Otherwise queue/dequeue calls could be made on the disconnected
935 // ANW, which may result in errors.
936 reset();
937
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700938 Mutex::Autolock lock(mLock);
939 disconnectNativeWindow_l();
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700940
941 return err;
942 }
943 }
944
Andy McFadden484566c2012-12-18 09:46:54 -0800945 // Note that we must set the player's new GraphicBufferProducer before
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700946 // disconnecting the old one. Otherwise queue/dequeue calls could be made
947 // on the disconnected ANW, which may result in errors.
Andy McFadden484566c2012-12-18 09:46:54 -0800948 status_t err = p->setVideoSurfaceTexture(bufferProducer);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700949
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700950 mLock.lock();
951 disconnectNativeWindow_l();
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700952
953 if (err == OK) {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700954 mConnectedWindow = anw;
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700955 mConnectedWindowBinder = binder;
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700956 mLock.unlock();
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700957 } else {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700958 mLock.unlock();
959 status_t err = nativeWindowDisconnect(
960 anw.get(), "disconnectNativeWindow");
961
962 if (err != OK) {
963 ALOGW("nativeWindowDisconnect returned an error: %s (%d)",
964 strerror(-err), err);
965 }
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700966 }
967
968 return err;
Glenn Kasten11731182011-02-08 17:26:17 -0800969}
970
Nicolas Catania1d187f12009-05-12 23:25:55 -0700971status_t MediaPlayerService::Client::invoke(const Parcel& request,
972 Parcel *reply)
973{
974 sp<MediaPlayerBase> p = getPlayer();
975 if (p == NULL) return UNKNOWN_ERROR;
976 return p->invoke(request, reply);
977}
978
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700979// This call doesn't need to access the native player.
980status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
981{
982 status_t status;
nikoa64c8c72009-07-20 15:07:26 -0700983 media::Metadata::Filter allow, drop;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700984
Nicolas Catania48290382009-07-10 13:53:06 -0700985 if (unmarshallFilter(filter, &allow, &status) &&
986 unmarshallFilter(filter, &drop, &status)) {
987 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700988
989 mMetadataAllow = allow;
990 mMetadataDrop = drop;
991 }
992 return status;
993}
994
Nicolas Catania48290382009-07-10 13:53:06 -0700995status_t MediaPlayerService::Client::getMetadata(
Mark Salyzyn77342f72014-06-18 16:31:32 -0700996 bool update_only, bool /*apply_filter*/, Parcel *reply)
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700997{
nikoa64c8c72009-07-20 15:07:26 -0700998 sp<MediaPlayerBase> player = getPlayer();
999 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania48290382009-07-10 13:53:06 -07001000
nikod608a812009-07-16 16:39:53 -07001001 status_t status;
1002 // Placeholder for the return code, updated by the caller.
1003 reply->writeInt32(-1);
1004
nikoa64c8c72009-07-20 15:07:26 -07001005 media::Metadata::Filter ids;
Nicolas Catania48290382009-07-10 13:53:06 -07001006
1007 // We don't block notifications while we fetch the data. We clear
1008 // mMetadataUpdated first so we don't lose notifications happening
1009 // during the rest of this call.
1010 {
1011 Mutex::Autolock lock(mLock);
1012 if (update_only) {
nikod608a812009-07-16 16:39:53 -07001013 ids = mMetadataUpdated;
Nicolas Catania48290382009-07-10 13:53:06 -07001014 }
1015 mMetadataUpdated.clear();
1016 }
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001017
nikoa64c8c72009-07-20 15:07:26 -07001018 media::Metadata metadata(reply);
Nicolas Catania48290382009-07-10 13:53:06 -07001019
nikoa64c8c72009-07-20 15:07:26 -07001020 metadata.appendHeader();
1021 status = player->getMetadata(ids, reply);
nikod608a812009-07-16 16:39:53 -07001022
1023 if (status != OK) {
nikoa64c8c72009-07-20 15:07:26 -07001024 metadata.resetParcel();
Steve Block29357bc2012-01-06 19:20:56 +00001025 ALOGE("getMetadata failed %d", status);
nikod608a812009-07-16 16:39:53 -07001026 return status;
1027 }
1028
1029 // FIXME: Implement filtering on the result. Not critical since
1030 // filtering takes place on the update notifications already. This
1031 // would be when all the metadata are fetch and a filter is set.
1032
nikod608a812009-07-16 16:39:53 -07001033 // Everything is fine, update the metadata length.
nikoa64c8c72009-07-20 15:07:26 -07001034 metadata.updateLength();
nikod608a812009-07-16 16:39:53 -07001035 return OK;
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001036}
1037
Wei Jiad399e7e2016-10-26 15:49:11 -07001038status_t MediaPlayerService::Client::setBufferingSettings(
1039 const BufferingSettings& buffering)
1040{
Wei Jiadc6f3402017-01-09 15:04:18 -08001041 ALOGV("[%d] setBufferingSettings{%s}",
1042 mConnId, buffering.toString().string());
Wei Jiad399e7e2016-10-26 15:49:11 -07001043 sp<MediaPlayerBase> p = getPlayer();
1044 if (p == 0) return UNKNOWN_ERROR;
1045 return p->setBufferingSettings(buffering);
1046}
1047
1048status_t MediaPlayerService::Client::getDefaultBufferingSettings(
1049 BufferingSettings* buffering /* nonnull */)
1050{
1051 sp<MediaPlayerBase> p = getPlayer();
1052 // TODO: create mPlayer on demand.
1053 if (p == 0) return UNKNOWN_ERROR;
1054 status_t ret = p->getDefaultBufferingSettings(buffering);
1055 if (ret == NO_ERROR) {
Wei Jiadc6f3402017-01-09 15:04:18 -08001056 ALOGV("[%d] getDefaultBufferingSettings{%s}",
1057 mConnId, buffering->toString().string());
Wei Jiad399e7e2016-10-26 15:49:11 -07001058 } else {
1059 ALOGV("[%d] getDefaultBufferingSettings returned %d", mConnId, ret);
1060 }
1061 return ret;
1062}
1063
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001064status_t MediaPlayerService::Client::prepareAsync()
1065{
Steve Block3856b092011-10-20 11:56:00 +01001066 ALOGV("[%d] prepareAsync", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001067 sp<MediaPlayerBase> p = getPlayer();
1068 if (p == 0) return UNKNOWN_ERROR;
1069 status_t ret = p->prepareAsync();
1070#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +00001071 ALOGD("start Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001072 if (ret == NO_ERROR) mAntagonizer->start();
1073#endif
1074 return ret;
1075}
1076
1077status_t MediaPlayerService::Client::start()
1078{
Steve Block3856b092011-10-20 11:56:00 +01001079 ALOGV("[%d] start", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001080 sp<MediaPlayerBase> p = getPlayer();
1081 if (p == 0) return UNKNOWN_ERROR;
1082 p->setLooping(mLoop);
1083 return p->start();
1084}
1085
1086status_t MediaPlayerService::Client::stop()
1087{
Steve Block3856b092011-10-20 11:56:00 +01001088 ALOGV("[%d] stop", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001089 sp<MediaPlayerBase> p = getPlayer();
1090 if (p == 0) return UNKNOWN_ERROR;
1091 return p->stop();
1092}
1093
1094status_t MediaPlayerService::Client::pause()
1095{
Steve Block3856b092011-10-20 11:56:00 +01001096 ALOGV("[%d] pause", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001097 sp<MediaPlayerBase> p = getPlayer();
1098 if (p == 0) return UNKNOWN_ERROR;
1099 return p->pause();
1100}
1101
1102status_t MediaPlayerService::Client::isPlaying(bool* state)
1103{
1104 *state = false;
1105 sp<MediaPlayerBase> p = getPlayer();
1106 if (p == 0) return UNKNOWN_ERROR;
1107 *state = p->isPlaying();
Steve Block3856b092011-10-20 11:56:00 +01001108 ALOGV("[%d] isPlaying: %d", mConnId, *state);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001109 return NO_ERROR;
1110}
1111
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001112status_t MediaPlayerService::Client::setPlaybackSettings(const AudioPlaybackRate& rate)
Wei Jia98160162015-02-04 17:01:11 -08001113{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001114 ALOGV("[%d] setPlaybackSettings(%f, %f, %d, %d)",
1115 mConnId, rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Wei Jia98160162015-02-04 17:01:11 -08001116 sp<MediaPlayerBase> p = getPlayer();
1117 if (p == 0) return UNKNOWN_ERROR;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001118 return p->setPlaybackSettings(rate);
1119}
1120
1121status_t MediaPlayerService::Client::getPlaybackSettings(AudioPlaybackRate* rate /* nonnull */)
1122{
1123 sp<MediaPlayerBase> p = getPlayer();
1124 if (p == 0) return UNKNOWN_ERROR;
1125 status_t ret = p->getPlaybackSettings(rate);
1126 if (ret == NO_ERROR) {
1127 ALOGV("[%d] getPlaybackSettings(%f, %f, %d, %d)",
1128 mConnId, rate->mSpeed, rate->mPitch, rate->mFallbackMode, rate->mStretchMode);
1129 } else {
1130 ALOGV("[%d] getPlaybackSettings returned %d", mConnId, ret);
1131 }
1132 return ret;
1133}
1134
1135status_t MediaPlayerService::Client::setSyncSettings(
1136 const AVSyncSettings& sync, float videoFpsHint)
1137{
1138 ALOGV("[%d] setSyncSettings(%u, %u, %f, %f)",
1139 mConnId, sync.mSource, sync.mAudioAdjustMode, sync.mTolerance, videoFpsHint);
1140 sp<MediaPlayerBase> p = getPlayer();
1141 if (p == 0) return UNKNOWN_ERROR;
1142 return p->setSyncSettings(sync, videoFpsHint);
1143}
1144
1145status_t MediaPlayerService::Client::getSyncSettings(
1146 AVSyncSettings* sync /* nonnull */, float* videoFps /* nonnull */)
1147{
1148 sp<MediaPlayerBase> p = getPlayer();
1149 if (p == 0) return UNKNOWN_ERROR;
1150 status_t ret = p->getSyncSettings(sync, videoFps);
1151 if (ret == NO_ERROR) {
1152 ALOGV("[%d] getSyncSettings(%u, %u, %f, %f)",
1153 mConnId, sync->mSource, sync->mAudioAdjustMode, sync->mTolerance, *videoFps);
1154 } else {
1155 ALOGV("[%d] getSyncSettings returned %d", mConnId, ret);
1156 }
1157 return ret;
Wei Jia98160162015-02-04 17:01:11 -08001158}
1159
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001160status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
1161{
Steve Block3856b092011-10-20 11:56:00 +01001162 ALOGV("getCurrentPosition");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001163 sp<MediaPlayerBase> p = getPlayer();
1164 if (p == 0) return UNKNOWN_ERROR;
1165 status_t ret = p->getCurrentPosition(msec);
1166 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001167 ALOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001168 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001169 ALOGE("getCurrentPosition returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001170 }
1171 return ret;
1172}
1173
1174status_t MediaPlayerService::Client::getDuration(int *msec)
1175{
Steve Block3856b092011-10-20 11:56:00 +01001176 ALOGV("getDuration");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001177 sp<MediaPlayerBase> p = getPlayer();
1178 if (p == 0) return UNKNOWN_ERROR;
1179 status_t ret = p->getDuration(msec);
1180 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001181 ALOGV("[%d] getDuration = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001182 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001183 ALOGE("getDuration returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001184 }
1185 return ret;
1186}
1187
Marco Nelissen6b74d672012-02-28 16:07:44 -08001188status_t MediaPlayerService::Client::setNextPlayer(const sp<IMediaPlayer>& player) {
1189 ALOGV("setNextPlayer");
1190 Mutex::Autolock l(mLock);
1191 sp<Client> c = static_cast<Client*>(player.get());
Wei Jia28284122016-08-30 13:49:06 -07001192 if (c != NULL && !mService->hasClient(c)) {
Robert Shihee0a0e32016-08-16 16:50:54 -07001193 return BAD_VALUE;
1194 }
1195
Marco Nelissen6b74d672012-02-28 16:07:44 -08001196 mNextClient = c;
John Grossman5f7e55e2012-08-24 14:47:25 -07001197
1198 if (c != NULL) {
1199 if (mAudioOutput != NULL) {
1200 mAudioOutput->setNextOutput(c->mAudioOutput);
1201 } else if ((mPlayer != NULL) && !mPlayer->hardwareOutput()) {
1202 ALOGE("no current audio output");
1203 }
1204
1205 if ((mPlayer != NULL) && (mNextClient->getPlayer() != NULL)) {
1206 mPlayer->setNextPlayer(mNextClient->getPlayer());
1207 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001208 }
John Grossman5f7e55e2012-08-24 14:47:25 -07001209
Marco Nelissen6b74d672012-02-28 16:07:44 -08001210 return OK;
1211}
1212
Andy Hung9fc8b5c2017-01-24 13:36:48 -08001213VolumeShaper::Status MediaPlayerService::Client::applyVolumeShaper(
1214 const sp<VolumeShaper::Configuration>& configuration,
1215 const sp<VolumeShaper::Operation>& operation) {
1216 // for hardware output, call player instead
1217 ALOGV("Client::applyVolumeShaper(%p)", this);
1218 sp<MediaPlayerBase> p = getPlayer();
1219 {
1220 Mutex::Autolock l(mLock);
1221 if (p != 0 && p->hardwareOutput()) {
1222 // TODO: investigate internal implementation
1223 return VolumeShaper::Status(INVALID_OPERATION);
1224 }
1225 if (mAudioOutput.get() != nullptr) {
1226 return mAudioOutput->applyVolumeShaper(configuration, operation);
1227 }
1228 }
1229 return VolumeShaper::Status(INVALID_OPERATION);
1230}
1231
1232sp<VolumeShaper::State> MediaPlayerService::Client::getVolumeShaperState(int id) {
1233 // for hardware output, call player instead
1234 ALOGV("Client::getVolumeShaperState(%p)", this);
1235 sp<MediaPlayerBase> p = getPlayer();
1236 {
1237 Mutex::Autolock l(mLock);
1238 if (p != 0 && p->hardwareOutput()) {
1239 // TODO: investigate internal implementation.
1240 return nullptr;
1241 }
1242 if (mAudioOutput.get() != nullptr) {
1243 return mAudioOutput->getVolumeShaperState(id);
1244 }
1245 }
1246 return nullptr;
1247}
1248
Wei Jiac5de0912016-11-18 10:22:14 -08001249status_t MediaPlayerService::Client::seekTo(int msec, MediaPlayerSeekMode mode)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001250{
Wei Jiac5de0912016-11-18 10:22:14 -08001251 ALOGV("[%d] seekTo(%d, %d)", mConnId, msec, mode);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001252 sp<MediaPlayerBase> p = getPlayer();
1253 if (p == 0) return UNKNOWN_ERROR;
Wei Jiac5de0912016-11-18 10:22:14 -08001254 return p->seekTo(msec, mode);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001255}
1256
1257status_t MediaPlayerService::Client::reset()
1258{
Steve Block3856b092011-10-20 11:56:00 +01001259 ALOGV("[%d] reset", mConnId);
John Grossmanc795b642012-02-22 15:38:35 -08001260 mRetransmitEndpointValid = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001261 sp<MediaPlayerBase> p = getPlayer();
1262 if (p == 0) return UNKNOWN_ERROR;
1263 return p->reset();
1264}
1265
Wei Jia52c28512017-09-13 18:17:51 -07001266status_t MediaPlayerService::Client::notifyAt(int64_t mediaTimeUs)
1267{
1268 ALOGV("[%d] notifyAt(%lld)", mConnId, (long long)mediaTimeUs);
1269 sp<MediaPlayerBase> p = getPlayer();
1270 if (p == 0) return UNKNOWN_ERROR;
1271 return p->notifyAt(mediaTimeUs);
1272}
1273
Glenn Kastenfff6d712012-01-12 16:38:12 -08001274status_t MediaPlayerService::Client::setAudioStreamType(audio_stream_type_t type)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001275{
Steve Block3856b092011-10-20 11:56:00 +01001276 ALOGV("[%d] setAudioStreamType(%d)", mConnId, type);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001277 // TODO: for hardware output, call player instead
1278 Mutex::Autolock l(mLock);
1279 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1280 return NO_ERROR;
1281}
1282
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001283status_t MediaPlayerService::Client::setAudioAttributes_l(const Parcel &parcel)
1284{
1285 if (mAudioAttributes != NULL) { free(mAudioAttributes); }
1286 mAudioAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001287 if (mAudioAttributes == NULL) {
1288 return NO_MEMORY;
1289 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001290 unmarshallAudioAttributes(parcel, mAudioAttributes);
1291
1292 ALOGV("setAudioAttributes_l() usage=%d content=%d flags=0x%x tags=%s",
1293 mAudioAttributes->usage, mAudioAttributes->content_type, mAudioAttributes->flags,
1294 mAudioAttributes->tags);
1295
1296 if (mAudioOutput != 0) {
1297 mAudioOutput->setAudioAttributes(mAudioAttributes);
1298 }
1299 return NO_ERROR;
1300}
1301
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001302status_t MediaPlayerService::Client::setLooping(int loop)
1303{
Steve Block3856b092011-10-20 11:56:00 +01001304 ALOGV("[%d] setLooping(%d)", mConnId, loop);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001305 mLoop = loop;
1306 sp<MediaPlayerBase> p = getPlayer();
1307 if (p != 0) return p->setLooping(loop);
1308 return NO_ERROR;
1309}
1310
1311status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1312{
Steve Block3856b092011-10-20 11:56:00 +01001313 ALOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
John Grossman761defc2012-02-09 15:09:05 -08001314
1315 // for hardware output, call player instead
1316 sp<MediaPlayerBase> p = getPlayer();
1317 {
1318 Mutex::Autolock l(mLock);
1319 if (p != 0 && p->hardwareOutput()) {
1320 MediaPlayerHWInterface* hwp =
1321 reinterpret_cast<MediaPlayerHWInterface*>(p.get());
1322 return hwp->setVolume(leftVolume, rightVolume);
1323 } else {
1324 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1325 return NO_ERROR;
1326 }
1327 }
1328
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001329 return NO_ERROR;
1330}
1331
Eric Laurent2beeb502010-07-16 07:43:46 -07001332status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1333{
Steve Block3856b092011-10-20 11:56:00 +01001334 ALOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
Eric Laurent2beeb502010-07-16 07:43:46 -07001335 Mutex::Autolock l(mLock);
1336 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1337 return NO_ERROR;
1338}
1339
1340status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1341{
Steve Block3856b092011-10-20 11:56:00 +01001342 ALOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
Eric Laurent2beeb502010-07-16 07:43:46 -07001343 Mutex::Autolock l(mLock);
1344 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1345 return NO_ERROR;
1346}
Nicolas Catania48290382009-07-10 13:53:06 -07001347
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001348status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
Steve Block3856b092011-10-20 11:56:00 +01001349 ALOGV("[%d] setParameter(%d)", mConnId, key);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001350 switch (key) {
1351 case KEY_PARAMETER_AUDIO_ATTRIBUTES:
1352 {
1353 Mutex::Autolock l(mLock);
1354 return setAudioAttributes_l(request);
1355 }
1356 default:
1357 sp<MediaPlayerBase> p = getPlayer();
1358 if (p == 0) { return UNKNOWN_ERROR; }
1359 return p->setParameter(key, request);
1360 }
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001361}
1362
1363status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
Steve Block3856b092011-10-20 11:56:00 +01001364 ALOGV("[%d] getParameter(%d)", mConnId, key);
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001365 sp<MediaPlayerBase> p = getPlayer();
1366 if (p == 0) return UNKNOWN_ERROR;
1367 return p->getParameter(key, reply);
1368}
1369
John Grossmanc795b642012-02-22 15:38:35 -08001370status_t MediaPlayerService::Client::setRetransmitEndpoint(
1371 const struct sockaddr_in* endpoint) {
1372
1373 if (NULL != endpoint) {
1374 uint32_t a = ntohl(endpoint->sin_addr.s_addr);
1375 uint16_t p = ntohs(endpoint->sin_port);
1376 ALOGV("[%d] setRetransmitEndpoint(%u.%u.%u.%u:%hu)", mConnId,
1377 (a >> 24), (a >> 16) & 0xFF, (a >> 8) & 0xFF, (a & 0xFF), p);
1378 } else {
1379 ALOGV("[%d] setRetransmitEndpoint = <none>", mConnId);
1380 }
1381
1382 sp<MediaPlayerBase> p = getPlayer();
1383
1384 // Right now, the only valid time to set a retransmit endpoint is before
1385 // player selection has been made (since the presence or absence of a
1386 // retransmit endpoint is going to determine which player is selected during
1387 // setDataSource).
1388 if (p != 0) return INVALID_OPERATION;
1389
1390 if (NULL != endpoint) {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001391 Mutex::Autolock lock(mLock);
John Grossmanc795b642012-02-22 15:38:35 -08001392 mRetransmitEndpoint = *endpoint;
1393 mRetransmitEndpointValid = true;
1394 } else {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001395 Mutex::Autolock lock(mLock);
John Grossmanc795b642012-02-22 15:38:35 -08001396 mRetransmitEndpointValid = false;
1397 }
1398
1399 return NO_ERROR;
1400}
1401
John Grossman44a7e422012-06-21 17:29:24 -07001402status_t MediaPlayerService::Client::getRetransmitEndpoint(
1403 struct sockaddr_in* endpoint)
1404{
1405 if (NULL == endpoint)
1406 return BAD_VALUE;
1407
1408 sp<MediaPlayerBase> p = getPlayer();
1409
1410 if (p != NULL)
1411 return p->getRetransmitEndpoint(endpoint);
1412
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001413 Mutex::Autolock lock(mLock);
John Grossman44a7e422012-06-21 17:29:24 -07001414 if (!mRetransmitEndpointValid)
1415 return NO_INIT;
1416
1417 *endpoint = mRetransmitEndpoint;
1418
1419 return NO_ERROR;
1420}
1421
Gloria Wangb483c472011-04-11 17:23:27 -07001422void MediaPlayerService::Client::notify(
1423 void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001424{
1425 Client* client = static_cast<Client*>(cookie);
James Dongb8a98252012-08-26 16:13:03 -07001426 if (client == NULL) {
1427 return;
1428 }
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001429
James Dongb8a98252012-08-26 16:13:03 -07001430 sp<IMediaPlayerClient> c;
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001431 sp<Client> nextClient;
1432 status_t errStartNext = NO_ERROR;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001433 {
1434 Mutex::Autolock l(client->mLock);
James Dongb8a98252012-08-26 16:13:03 -07001435 c = client->mClient;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001436 if (msg == MEDIA_PLAYBACK_COMPLETE && client->mNextClient != NULL) {
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001437 nextClient = client->mNextClient;
1438
John Grossmancb0b7552012-08-23 17:47:31 -07001439 if (client->mAudioOutput != NULL)
1440 client->mAudioOutput->switchToNextOutput();
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001441
1442 errStartNext = nextClient->start();
1443 }
1444 }
1445
1446 if (nextClient != NULL) {
1447 sp<IMediaPlayerClient> nc;
1448 {
1449 Mutex::Autolock l(nextClient->mLock);
1450 nc = nextClient->mClient;
1451 }
1452 if (nc != NULL) {
1453 if (errStartNext == NO_ERROR) {
1454 nc->notify(MEDIA_INFO, MEDIA_INFO_STARTED_AS_NEXT, 0, obj);
1455 } else {
1456 nc->notify(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN , 0, obj);
1457 ALOGE("gapless:start playback for next track failed, err(%d)", errStartNext);
Wei Jia2afac0c2016-01-07 12:13:07 -08001458 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001459 }
1460 }
1461
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001462 if (MEDIA_INFO == msg &&
Nicolas Catania48290382009-07-10 13:53:06 -07001463 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikoa64c8c72009-07-20 15:07:26 -07001464 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania48290382009-07-10 13:53:06 -07001465
1466 if(client->shouldDropMetadata(metadata_type)) {
1467 return;
1468 }
1469
1470 // Update the list of metadata that have changed. getMetadata
1471 // also access mMetadataUpdated and clears it.
1472 client->addNewMetadataUpdate(metadata_type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001473 }
James Dongb8a98252012-08-26 16:13:03 -07001474
1475 if (c != NULL) {
1476 ALOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
1477 c->notify(msg, ext1, ext2, obj);
1478 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001479}
1480
Nicolas Catania48290382009-07-10 13:53:06 -07001481
nikoa64c8c72009-07-20 15:07:26 -07001482bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001483{
Nicolas Catania48290382009-07-10 13:53:06 -07001484 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001485
Nicolas Catania48290382009-07-10 13:53:06 -07001486 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001487 return true;
1488 }
1489
Nicolas Catania48290382009-07-10 13:53:06 -07001490 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001491 return false;
Nicolas Catania48290382009-07-10 13:53:06 -07001492 } else {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001493 return true;
1494 }
1495}
1496
Nicolas Catania48290382009-07-10 13:53:06 -07001497
nikoa64c8c72009-07-20 15:07:26 -07001498void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania48290382009-07-10 13:53:06 -07001499 Mutex::Autolock lock(mLock);
1500 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1501 mMetadataUpdated.add(metadata_type);
1502 }
1503}
1504
Hassan Shojaniacefac142017-02-06 21:02:02 -08001505// Modular DRM
1506status_t MediaPlayerService::Client::prepareDrm(const uint8_t uuid[16],
1507 const Vector<uint8_t>& drmSessionId)
1508{
1509 ALOGV("[%d] prepareDrm", mConnId);
1510 sp<MediaPlayerBase> p = getPlayer();
1511 if (p == 0) return UNKNOWN_ERROR;
1512
1513 status_t ret = p->prepareDrm(uuid, drmSessionId);
1514 ALOGV("prepareDrm ret: %d", ret);
1515
1516 return ret;
1517}
1518
1519status_t MediaPlayerService::Client::releaseDrm()
1520{
1521 ALOGV("[%d] releaseDrm", mConnId);
1522 sp<MediaPlayerBase> p = getPlayer();
1523 if (p == 0) return UNKNOWN_ERROR;
1524
1525 status_t ret = p->releaseDrm();
1526 ALOGV("releaseDrm ret: %d", ret);
1527
1528 return ret;
1529}
1530
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001531#if CALLBACK_ANTAGONIZER
1532const int Antagonizer::interval = 10000; // 10 msecs
1533
1534Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1535 mExit(false), mActive(false), mClient(client), mCb(cb)
1536{
1537 createThread(callbackThread, this);
1538}
1539
1540void Antagonizer::kill()
1541{
1542 Mutex::Autolock _l(mLock);
1543 mActive = false;
1544 mExit = true;
1545 mCondition.wait(mLock);
1546}
1547
1548int Antagonizer::callbackThread(void* user)
1549{
Steve Blockb8a80522011-12-20 16:23:08 +00001550 ALOGD("Antagonizer started");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001551 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1552 while (!p->mExit) {
1553 if (p->mActive) {
Steve Block3856b092011-10-20 11:56:00 +01001554 ALOGV("send event");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001555 p->mCb(p->mClient, 0, 0, 0);
1556 }
1557 usleep(interval);
1558 }
1559 Mutex::Autolock _l(p->mLock);
1560 p->mCondition.signal();
Steve Blockb8a80522011-12-20 16:23:08 +00001561 ALOGD("Antagonizer stopped");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001562 return 0;
1563}
1564#endif
1565
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001566#undef LOG_TAG
1567#define LOG_TAG "AudioSink"
Andy Hung1afd0982016-11-08 16:13:44 -08001568MediaPlayerService::AudioOutput::AudioOutput(audio_session_t sessionId, uid_t uid, int pid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001569 const audio_attributes_t* attr)
Andreas Huber20111aa2009-07-14 16:56:47 -07001570 : mCallback(NULL),
Eric Laurenta514bdb2010-06-21 09:27:30 -07001571 mCallbackCookie(NULL),
Marco Nelissen6b74d672012-02-28 16:07:44 -08001572 mCallbackData(NULL),
Andy Hungd1c74342015-07-07 16:54:23 -07001573 mStreamType(AUDIO_STREAM_MUSIC),
Andy Hungd1c74342015-07-07 16:54:23 -07001574 mLeftVolume(1.0),
1575 mRightVolume(1.0),
1576 mPlaybackRate(AUDIO_PLAYBACK_RATE_DEFAULT),
1577 mSampleRateHz(0),
1578 mMsecsPerFrame(0),
1579 mFrameSize(0),
Eric Laurent1948eb32012-04-13 16:50:19 -07001580 mSessionId(sessionId),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001581 mUid(uid),
Marco Nelissend457c972014-02-11 08:47:07 -08001582 mPid(pid),
Andy Hungd1c74342015-07-07 16:54:23 -07001583 mSendLevel(0.0),
1584 mAuxEffectId(0),
Andy Hung4ef88d72017-02-21 19:47:53 -08001585 mFlags(AUDIO_OUTPUT_FLAG_NONE),
Ivan Lozano8cf3a072017-08-09 09:01:33 -07001586 mVolumeHandler(new media::VolumeHandler())
Andy Hungd1c74342015-07-07 16:54:23 -07001587{
Steve Block3856b092011-10-20 11:56:00 +01001588 ALOGV("AudioOutput(%d)", sessionId);
Eric Laurent43562692015-07-15 16:49:07 -07001589 if (attr != NULL) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001590 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1591 if (mAttributes != NULL) {
1592 memcpy(mAttributes, attr, sizeof(audio_attributes_t));
1593 mStreamType = audio_attributes_to_stream_type(attr);
1594 }
1595 } else {
1596 mAttributes = NULL;
Eric Laurent43562692015-07-15 16:49:07 -07001597 }
1598
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001599 setMinBufferCount();
1600}
1601
1602MediaPlayerService::AudioOutput::~AudioOutput()
1603{
1604 close();
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001605 free(mAttributes);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001606 delete mCallbackData;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001607}
1608
Andy Hungd1c74342015-07-07 16:54:23 -07001609//static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001610void MediaPlayerService::AudioOutput::setMinBufferCount()
1611{
1612 char value[PROPERTY_VALUE_MAX];
1613 if (property_get("ro.kernel.qemu", value, 0)) {
1614 mIsOnEmulator = true;
1615 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1616 }
1617}
1618
Andy Hungd1c74342015-07-07 16:54:23 -07001619// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001620bool MediaPlayerService::AudioOutput::isOnEmulator()
1621{
Andy Hungd1c74342015-07-07 16:54:23 -07001622 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001623 return mIsOnEmulator;
1624}
1625
Andy Hungd1c74342015-07-07 16:54:23 -07001626// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001627int MediaPlayerService::AudioOutput::getMinBufferCount()
1628{
Andy Hungd1c74342015-07-07 16:54:23 -07001629 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001630 return mMinBufferCount;
1631}
1632
1633ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1634{
Andy Hungd1c74342015-07-07 16:54:23 -07001635 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001636 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001637 return mTrack->frameCount() * mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001638}
1639
1640ssize_t MediaPlayerService::AudioOutput::frameCount() const
1641{
Andy Hungd1c74342015-07-07 16:54:23 -07001642 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001643 if (mTrack == 0) return NO_INIT;
1644 return mTrack->frameCount();
1645}
1646
1647ssize_t MediaPlayerService::AudioOutput::channelCount() const
1648{
Andy Hungd1c74342015-07-07 16:54:23 -07001649 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001650 if (mTrack == 0) return NO_INIT;
1651 return mTrack->channelCount();
1652}
1653
1654ssize_t MediaPlayerService::AudioOutput::frameSize() const
1655{
Andy Hungd1c74342015-07-07 16:54:23 -07001656 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001657 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001658 return mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001659}
1660
1661uint32_t MediaPlayerService::AudioOutput::latency () const
1662{
Andy Hungd1c74342015-07-07 16:54:23 -07001663 Mutex::Autolock lock(mLock);
Eric Laurentdb354e52012-03-05 17:27:11 -08001664 if (mTrack == 0) return 0;
1665 return mTrack->latency();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001666}
1667
1668float MediaPlayerService::AudioOutput::msecsPerFrame() const
1669{
Andy Hungd1c74342015-07-07 16:54:23 -07001670 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001671 return mMsecsPerFrame;
1672}
1673
Marco Nelissen4110c102012-03-29 09:31:28 -07001674status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position) const
Eric Laurent342e9cf2010-01-19 17:37:09 -08001675{
Andy Hungd1c74342015-07-07 16:54:23 -07001676 Mutex::Autolock lock(mLock);
Eric Laurent342e9cf2010-01-19 17:37:09 -08001677 if (mTrack == 0) return NO_INIT;
1678 return mTrack->getPosition(position);
1679}
1680
Lajos Molnar06ad1522014-08-28 07:27:44 -07001681status_t MediaPlayerService::AudioOutput::getTimestamp(AudioTimestamp &ts) const
1682{
Andy Hungd1c74342015-07-07 16:54:23 -07001683 Mutex::Autolock lock(mLock);
Lajos Molnar06ad1522014-08-28 07:27:44 -07001684 if (mTrack == 0) return NO_INIT;
1685 return mTrack->getTimestamp(ts);
1686}
1687
Wei Jiac4ac8172015-10-21 10:35:48 -07001688// TODO: Remove unnecessary calls to getPlayedOutDurationUs()
1689// as it acquires locks and may query the audio driver.
1690//
1691// Some calls could conceivably retrieve extrapolated data instead of
1692// accessing getTimestamp() or getPosition() every time a data buffer with
1693// a media time is received.
1694//
1695// Calculate duration of played samples if played at normal rate (i.e., 1.0).
1696int64_t MediaPlayerService::AudioOutput::getPlayedOutDurationUs(int64_t nowUs) const
1697{
1698 Mutex::Autolock lock(mLock);
1699 if (mTrack == 0 || mSampleRateHz == 0) {
Wei Jia213f4902015-10-22 08:55:25 -07001700 return 0;
Wei Jiac4ac8172015-10-21 10:35:48 -07001701 }
1702
1703 uint32_t numFramesPlayed;
Andy Hung5d313802016-10-10 15:09:39 -07001704 int64_t numFramesPlayedAtUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001705 AudioTimestamp ts;
Wei Jiac4ac8172015-10-21 10:35:48 -07001706
1707 status_t res = mTrack->getTimestamp(ts);
1708 if (res == OK) { // case 1: mixing audio tracks and offloaded tracks.
1709 numFramesPlayed = ts.mPosition;
Andy Hung5d313802016-10-10 15:09:39 -07001710 numFramesPlayedAtUs = ts.mTime.tv_sec * 1000000LL + ts.mTime.tv_nsec / 1000;
1711 //ALOGD("getTimestamp: OK %d %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001712 } else if (res == WOULD_BLOCK) { // case 2: transitory state on start of a new track
1713 numFramesPlayed = 0;
Andy Hung5d313802016-10-10 15:09:39 -07001714 numFramesPlayedAtUs = nowUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001715 //ALOGD("getTimestamp: WOULD_BLOCK %d %lld",
Andy Hung5d313802016-10-10 15:09:39 -07001716 // numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001717 } else { // case 3: transitory at new track or audio fast tracks.
1718 res = mTrack->getPosition(&numFramesPlayed);
1719 CHECK_EQ(res, (status_t)OK);
Andy Hung5d313802016-10-10 15:09:39 -07001720 numFramesPlayedAtUs = nowUs;
1721 numFramesPlayedAtUs += 1000LL * mTrack->latency() / 2; /* XXX */
1722 //ALOGD("getPosition: %u %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001723 }
1724
1725 // CHECK_EQ(numFramesPlayed & (1 << 31), 0); // can't be negative until 12.4 hrs, test
1726 // TODO: remove the (int32_t) casting below as it may overflow at 12.4 hours.
1727 int64_t durationUs = (int64_t)((int32_t)numFramesPlayed * 1000000LL / mSampleRateHz)
Andy Hung5d313802016-10-10 15:09:39 -07001728 + nowUs - numFramesPlayedAtUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001729 if (durationUs < 0) {
1730 // Occurs when numFramesPlayed position is very small and the following:
1731 // (1) In case 1, the time nowUs is computed before getTimestamp() is called and
Andy Hung5d313802016-10-10 15:09:39 -07001732 // numFramesPlayedAtUs is greater than nowUs by time more than numFramesPlayed.
Wei Jiac4ac8172015-10-21 10:35:48 -07001733 // (2) In case 3, using getPosition and adding mAudioSink->latency() to
Andy Hung5d313802016-10-10 15:09:39 -07001734 // numFramesPlayedAtUs, by a time amount greater than numFramesPlayed.
Wei Jiac4ac8172015-10-21 10:35:48 -07001735 //
1736 // Both of these are transitory conditions.
1737 ALOGV("getPlayedOutDurationUs: negative duration %lld set to zero", (long long)durationUs);
1738 durationUs = 0;
1739 }
1740 ALOGV("getPlayedOutDurationUs(%lld) nowUs(%lld) frames(%u) framesAt(%lld)",
Andy Hung5d313802016-10-10 15:09:39 -07001741 (long long)durationUs, (long long)nowUs,
1742 numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001743 return durationUs;
1744}
1745
Marco Nelissen4110c102012-03-29 09:31:28 -07001746status_t MediaPlayerService::AudioOutput::getFramesWritten(uint32_t *frameswritten) const
1747{
Andy Hungd1c74342015-07-07 16:54:23 -07001748 Mutex::Autolock lock(mLock);
Marco Nelissen4110c102012-03-29 09:31:28 -07001749 if (mTrack == 0) return NO_INIT;
Andy Hung2f6e73d2016-04-08 12:12:58 -07001750 ExtendedTimestamp ets;
1751 status_t status = mTrack->getTimestamp(&ets);
1752 if (status == OK || status == WOULD_BLOCK) {
1753 *frameswritten = (uint32_t)ets.mPosition[ExtendedTimestamp::LOCATION_CLIENT];
1754 }
1755 return status;
Marco Nelissen4110c102012-03-29 09:31:28 -07001756}
1757
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001758status_t MediaPlayerService::AudioOutput::setParameters(const String8& keyValuePairs)
1759{
Andy Hungd1c74342015-07-07 16:54:23 -07001760 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001761 if (mTrack == 0) return NO_INIT;
1762 return mTrack->setParameters(keyValuePairs);
1763}
1764
1765String8 MediaPlayerService::AudioOutput::getParameters(const String8& keys)
1766{
Andy Hungd1c74342015-07-07 16:54:23 -07001767 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001768 if (mTrack == 0) return String8::empty();
1769 return mTrack->getParameters(keys);
1770}
1771
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001772void MediaPlayerService::AudioOutput::setAudioAttributes(const audio_attributes_t * attributes) {
Andy Hungd1c74342015-07-07 16:54:23 -07001773 Mutex::Autolock lock(mLock);
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001774 if (attributes == NULL) {
1775 free(mAttributes);
1776 mAttributes = NULL;
1777 } else {
1778 if (mAttributes == NULL) {
1779 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1780 }
1781 memcpy(mAttributes, attributes, sizeof(audio_attributes_t));
Eric Laurent43562692015-07-15 16:49:07 -07001782 mStreamType = audio_attributes_to_stream_type(attributes);
1783 }
1784}
1785
1786void MediaPlayerService::AudioOutput::setAudioStreamType(audio_stream_type_t streamType)
1787{
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001788 Mutex::Autolock lock(mLock);
Eric Laurent43562692015-07-15 16:49:07 -07001789 // do not allow direct stream type modification if attributes have been set
1790 if (mAttributes == NULL) {
1791 mStreamType = streamType;
1792 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001793}
1794
Andy Hungd1c74342015-07-07 16:54:23 -07001795void MediaPlayerService::AudioOutput::deleteRecycledTrack_l()
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001796{
Andy Hungd1c74342015-07-07 16:54:23 -07001797 ALOGV("deleteRecycledTrack_l");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001798 if (mRecycledTrack != 0) {
1799
1800 if (mCallbackData != NULL) {
1801 mCallbackData->setOutput(NULL);
1802 mCallbackData->endTrackSwitch();
1803 }
1804
1805 if ((mRecycledTrack->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) {
Andy Hunge13f8a62016-03-30 14:20:42 -07001806 int32_t msec = 0;
1807 if (!mRecycledTrack->stopped()) { // check if active
1808 (void)mRecycledTrack->pendingDuration(&msec);
1809 }
1810 mRecycledTrack->stop(); // ensure full data drain
1811 ALOGD("deleting recycled track, waiting for data drain (%d msec)", msec);
1812 if (msec > 0) {
1813 static const int32_t WAIT_LIMIT_MS = 3000;
1814 if (msec > WAIT_LIMIT_MS) {
1815 msec = WAIT_LIMIT_MS;
1816 }
1817 usleep(msec * 1000LL);
1818 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001819 }
1820 // An offloaded track isn't flushed because the STREAM_END is reported
1821 // slightly prematurely to allow time for the gapless track switch
1822 // but this means that if we decide not to recycle the track there
1823 // could be a small amount of residual data still playing. We leave
1824 // AudioFlinger to drain the track.
1825
1826 mRecycledTrack.clear();
Andy Hungd1c74342015-07-07 16:54:23 -07001827 close_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001828 delete mCallbackData;
1829 mCallbackData = NULL;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001830 }
1831}
1832
Andy Hungd1c74342015-07-07 16:54:23 -07001833void MediaPlayerService::AudioOutput::close_l()
1834{
1835 mTrack.clear();
1836}
1837
Andreas Huber20111aa2009-07-14 16:56:47 -07001838status_t MediaPlayerService::AudioOutput::open(
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001839 uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
1840 audio_format_t format, int bufferCount,
Eric Laurent1948eb32012-04-13 16:50:19 -07001841 AudioCallback cb, void *cookie,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001842 audio_output_flags_t flags,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001843 const audio_offload_info_t *offloadInfo,
Andy Hung179652e2015-05-31 22:49:46 -07001844 bool doNotReconnect,
1845 uint32_t suggestedFrameCount)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001846{
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001847 ALOGV("open(%u, %d, 0x%x, 0x%x, %d, %d 0x%x)", sampleRate, channelCount, channelMask,
1848 format, bufferCount, mSessionId, flags);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001849
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001850 // offloading is only supported in callback mode for now.
1851 // offloadInfo must be present if offload flag is set
1852 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) &&
1853 ((cb == NULL) || (offloadInfo == NULL))) {
1854 return BAD_VALUE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001855 }
1856
Andy Hung179652e2015-05-31 22:49:46 -07001857 // compute frame count for the AudioTrack internal buffer
1858 size_t frameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001859 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1860 frameCount = 0; // AudioTrack will get frame count from AudioFlinger
1861 } else {
Andy Hung179652e2015-05-31 22:49:46 -07001862 // try to estimate the buffer processing fetch size from AudioFlinger.
1863 // framesPerBuffer is approximate and generally correct, except when it's not :-).
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001864 uint32_t afSampleRate;
1865 size_t afFrameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001866 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1867 return NO_INIT;
1868 }
1869 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1870 return NO_INIT;
1871 }
Andy Hung179652e2015-05-31 22:49:46 -07001872 const size_t framesPerBuffer =
1873 (unsigned long long)sampleRate * afFrameCount / afSampleRate;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001874
Andy Hung179652e2015-05-31 22:49:46 -07001875 if (bufferCount == 0) {
1876 // use suggestedFrameCount
1877 bufferCount = (suggestedFrameCount + framesPerBuffer - 1) / framesPerBuffer;
1878 }
1879 // Check argument bufferCount against the mininum buffer count
1880 if (bufferCount != 0 && bufferCount < mMinBufferCount) {
1881 ALOGV("bufferCount (%d) increased to %d", bufferCount, mMinBufferCount);
1882 bufferCount = mMinBufferCount;
1883 }
1884 // if frameCount is 0, then AudioTrack will get frame count from AudioFlinger
1885 // which will be the minimum size permitted.
1886 frameCount = bufferCount * framesPerBuffer;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001887 }
Andreas Huber20111aa2009-07-14 16:56:47 -07001888
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001889 if (channelMask == CHANNEL_MASK_USE_CHANNEL_ORDER) {
Glenn Kastenab334fd2012-03-14 12:56:06 -07001890 channelMask = audio_channel_out_mask_from_count(channelCount);
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001891 if (0 == channelMask) {
1892 ALOGE("open() error, can\'t derive mask for %d audio channels", channelCount);
1893 return NO_INIT;
1894 }
1895 }
Eric Laurent1948eb32012-04-13 16:50:19 -07001896
Andy Hungd1c74342015-07-07 16:54:23 -07001897 Mutex::Autolock lock(mLock);
Andy Hung179652e2015-05-31 22:49:46 -07001898 mCallback = cb;
1899 mCallbackCookie = cookie;
1900
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001901 // Check whether we can recycle the track
1902 bool reuse = false;
1903 bool bothOffloaded = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001904
Glenn Kasten2799d742013-05-30 14:33:29 -07001905 if (mRecycledTrack != 0) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001906 // check whether we are switching between two offloaded tracks
1907 bothOffloaded = (flags & mRecycledTrack->getFlags()
1908 & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0;
Marco Nelissen67295b52012-06-11 14:52:53 -07001909
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001910 // check if the existing track can be reused as-is, or if a new track needs to be created.
1911 reuse = true;
1912
Marco Nelissen67295b52012-06-11 14:52:53 -07001913 if ((mCallbackData == NULL && mCallback != NULL) ||
1914 (mCallbackData != NULL && mCallback == NULL)) {
1915 // recycled track uses callbacks but the caller wants to use writes, or vice versa
1916 ALOGV("can't chain callback and write");
1917 reuse = false;
1918 } else if ((mRecycledTrack->getSampleRate() != sampleRate) ||
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001919 (mRecycledTrack->channelCount() != (uint32_t)channelCount) ) {
1920 ALOGV("samplerate, channelcount differ: %u/%u Hz, %u/%d ch",
Marco Nelissen67295b52012-06-11 14:52:53 -07001921 mRecycledTrack->getSampleRate(), sampleRate,
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001922 mRecycledTrack->channelCount(), channelCount);
Marco Nelissen67295b52012-06-11 14:52:53 -07001923 reuse = false;
1924 } else if (flags != mFlags) {
1925 ALOGV("output flags differ %08x/%08x", flags, mFlags);
1926 reuse = false;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001927 } else if (mRecycledTrack->format() != format) {
1928 reuse = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001929 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001930 } else {
1931 ALOGV("no track available to recycle");
1932 }
1933
1934 ALOGV_IF(bothOffloaded, "both tracks offloaded");
1935
1936 // If we can't recycle and both tracks are offloaded
1937 // we must close the previous output before opening a new one
1938 if (bothOffloaded && !reuse) {
1939 ALOGV("both offloaded and not recycling");
Andy Hungd1c74342015-07-07 16:54:23 -07001940 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001941 }
1942
1943 sp<AudioTrack> t;
1944 CallbackData *newcbd = NULL;
1945
1946 // We don't attempt to create a new track if we are recycling an
1947 // offloaded track. But, if we are recycling a non-offloaded or we
1948 // are switching where one is offloaded and one isn't then we create
1949 // the new track in advance so that we can read additional stream info
1950
1951 if (!(reuse && bothOffloaded)) {
1952 ALOGV("creating new AudioTrack");
1953
1954 if (mCallback != NULL) {
1955 newcbd = new CallbackData(this);
1956 t = new AudioTrack(
1957 mStreamType,
1958 sampleRate,
1959 format,
1960 channelMask,
1961 frameCount,
1962 flags,
1963 CallbackWrapper,
1964 newcbd,
1965 0, // notification frames
1966 mSessionId,
1967 AudioTrack::TRANSFER_CALLBACK,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001968 offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -08001969 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001970 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001971 mAttributes,
1972 doNotReconnect);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001973 } else {
Andy Hungff874dc2016-04-11 16:49:09 -07001974 // TODO: Due to buffer memory concerns, we use a max target playback speed
1975 // based on mPlaybackRate at the time of open (instead of kMaxRequiredSpeed),
1976 // also clamping the target speed to 1.0 <= targetSpeed <= kMaxRequiredSpeed.
1977 const float targetSpeed =
1978 std::min(std::max(mPlaybackRate.mSpeed, 1.0f), kMaxRequiredSpeed);
1979 ALOGW_IF(targetSpeed != mPlaybackRate.mSpeed,
1980 "track target speed:%f clamped from playback speed:%f",
1981 targetSpeed, mPlaybackRate.mSpeed);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001982 t = new AudioTrack(
1983 mStreamType,
1984 sampleRate,
1985 format,
1986 channelMask,
1987 frameCount,
1988 flags,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001989 NULL, // callback
1990 NULL, // user data
1991 0, // notification frames
1992 mSessionId,
1993 AudioTrack::TRANSFER_DEFAULT,
1994 NULL, // offload info
Marco Nelissend457c972014-02-11 08:47:07 -08001995 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001996 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001997 mAttributes,
Andy Hungff874dc2016-04-11 16:49:09 -07001998 doNotReconnect,
1999 targetSpeed);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002000 }
2001
2002 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
2003 ALOGE("Unable to create audio track");
2004 delete newcbd;
Glenn Kasten3e98ecd2015-05-18 13:13:24 -07002005 // t goes out of scope, so reference count drops to zero
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002006 return NO_INIT;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07002007 } else {
2008 // successful AudioTrack initialization implies a legacy stream type was generated
2009 // from the audio attributes
2010 mStreamType = t->streamType();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002011 }
2012 }
2013
2014 if (reuse) {
2015 CHECK(mRecycledTrack != NULL);
2016
2017 if (!bothOffloaded) {
2018 if (mRecycledTrack->frameCount() != t->frameCount()) {
Andy Hung833b4752016-04-04 17:15:48 -07002019 ALOGV("framecount differs: %zu/%zu frames",
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002020 mRecycledTrack->frameCount(), t->frameCount());
2021 reuse = false;
2022 }
2023 }
2024
Marco Nelissen67295b52012-06-11 14:52:53 -07002025 if (reuse) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002026 ALOGV("chaining to next output and recycling track");
Andy Hungd1c74342015-07-07 16:54:23 -07002027 close_l();
Marco Nelissen67295b52012-06-11 14:52:53 -07002028 mTrack = mRecycledTrack;
Glenn Kasten2799d742013-05-30 14:33:29 -07002029 mRecycledTrack.clear();
Marco Nelissen67295b52012-06-11 14:52:53 -07002030 if (mCallbackData != NULL) {
2031 mCallbackData->setOutput(this);
2032 }
Marco Nelissen67295b52012-06-11 14:52:53 -07002033 delete newcbd;
Wei Jiae0bbac92016-07-18 16:04:53 -07002034 return updateTrack();
Marco Nelissen67295b52012-06-11 14:52:53 -07002035 }
Marco Nelissen67295b52012-06-11 14:52:53 -07002036 }
2037
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002038 // we're not going to reuse the track, unblock and flush it
2039 // this was done earlier if both tracks are offloaded
2040 if (!bothOffloaded) {
Andy Hungd1c74342015-07-07 16:54:23 -07002041 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002042 }
2043
2044 CHECK((t != NULL) && ((mCallback == NULL) || (newcbd != NULL)));
2045
Marco Nelissen67295b52012-06-11 14:52:53 -07002046 mCallbackData = newcbd;
Steve Block3856b092011-10-20 11:56:00 +01002047 ALOGV("setVolume");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002048 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07002049
Andy Hung39399b62017-04-21 15:07:45 -07002050 // Restore VolumeShapers for the MediaPlayer in case the track was recreated
2051 // due to an output sink error (e.g. offload to non-offload switch).
2052 mVolumeHandler->forall([&t](const VolumeShaper &shaper) -> VolumeShaper::Status {
2053 sp<VolumeShaper::Operation> operationToEnd =
2054 new VolumeShaper::Operation(shaper.mOperation);
2055 // TODO: Ideally we would restore to the exact xOffset position
2056 // as returned by getVolumeShaperState(), but we don't have that
2057 // information when restoring at the client unless we periodically poll
2058 // the server or create shared memory state.
2059 //
2060 // For now, we simply advance to the end of the VolumeShaper effect
2061 // if it has been started.
2062 if (shaper.isStarted()) {
Andy Hungf3702642017-05-05 17:33:32 -07002063 operationToEnd->setNormalizedTime(1.f);
Andy Hung39399b62017-04-21 15:07:45 -07002064 }
2065 return t->applyVolumeShaper(shaper.mConfiguration, operationToEnd);
Andy Hung4ef88d72017-02-21 19:47:53 -08002066 });
Andy Hung4ef88d72017-02-21 19:47:53 -08002067
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002068 mSampleRateHz = sampleRate;
Preetam Singh Ranawat2e17eef2015-08-12 12:11:46 -07002069 mFlags = flags;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002070 mMsecsPerFrame = 1E3f / (mPlaybackRate.mSpeed * sampleRate);
Andy Hungd1c74342015-07-07 16:54:23 -07002071 mFrameSize = t->frameSize();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002072 mTrack = t;
Eric Laurent2beeb502010-07-16 07:43:46 -07002073
Wei Jiae0bbac92016-07-18 16:04:53 -07002074 return updateTrack();
2075}
2076
2077status_t MediaPlayerService::AudioOutput::updateTrack() {
2078 if (mTrack == NULL) {
2079 return NO_ERROR;
2080 }
2081
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002082 status_t res = NO_ERROR;
Wei Jia0162d002015-06-09 11:59:33 -07002083 // Note some output devices may give us a direct track even though we don't specify it.
2084 // Example: Line application b/17459982.
Wei Jiae0bbac92016-07-18 16:04:53 -07002085 if ((mTrack->getFlags()
2086 & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) {
2087 res = mTrack->setPlaybackRate(mPlaybackRate);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002088 if (res == NO_ERROR) {
Wei Jiae0bbac92016-07-18 16:04:53 -07002089 mTrack->setAuxEffectSendLevel(mSendLevel);
2090 res = mTrack->attachAuxEffect(mAuxEffectId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002091 }
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002092 }
Wei Jiae0bbac92016-07-18 16:04:53 -07002093 ALOGV("updateTrack() DONE status %d", res);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002094 return res;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002095}
2096
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002097status_t MediaPlayerService::AudioOutput::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002098{
Steve Block3856b092011-10-20 11:56:00 +01002099 ALOGV("start");
Andy Hungd1c74342015-07-07 16:54:23 -07002100 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08002101 if (mCallbackData != NULL) {
2102 mCallbackData->endTrackSwitch();
2103 }
Glenn Kasten2799d742013-05-30 14:33:29 -07002104 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002105 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07002106 mTrack->setAuxEffectSendLevel(mSendLevel);
Andy Hung39399b62017-04-21 15:07:45 -07002107 status_t status = mTrack->start();
2108 if (status == NO_ERROR) {
2109 mVolumeHandler->setStarted();
2110 }
2111 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002112 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002113 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002114}
2115
Marco Nelissen6b74d672012-02-28 16:07:44 -08002116void MediaPlayerService::AudioOutput::setNextOutput(const sp<AudioOutput>& nextOutput) {
Andy Hungd1c74342015-07-07 16:54:23 -07002117 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08002118 mNextOutput = nextOutput;
2119}
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08002120
Marco Nelissen6b74d672012-02-28 16:07:44 -08002121void MediaPlayerService::AudioOutput::switchToNextOutput() {
2122 ALOGV("switchToNextOutput");
Andy Hungd1c74342015-07-07 16:54:23 -07002123
2124 // Try to acquire the callback lock before moving track (without incurring deadlock).
2125 const unsigned kMaxSwitchTries = 100;
2126 Mutex::Autolock lock(mLock);
2127 for (unsigned tries = 0;;) {
2128 if (mTrack == 0) {
2129 return;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002130 }
Andy Hungd1c74342015-07-07 16:54:23 -07002131 if (mNextOutput != NULL && mNextOutput != this) {
2132 if (mCallbackData != NULL) {
2133 // two alternative approaches
2134#if 1
2135 CallbackData *callbackData = mCallbackData;
2136 mLock.unlock();
2137 // proper acquisition sequence
2138 callbackData->lock();
2139 mLock.lock();
2140 // Caution: it is unlikely that someone deleted our callback or changed our target
2141 if (callbackData != mCallbackData || mNextOutput == NULL || mNextOutput == this) {
2142 // fatal if we are starved out.
2143 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2144 "switchToNextOutput() cannot obtain correct lock sequence");
2145 callbackData->unlock();
2146 continue;
2147 }
2148 callbackData->mSwitching = true; // begin track switch
Wei Jiaadee56a2016-08-05 15:40:34 -07002149 callbackData->setOutput(NULL);
Andy Hungd1c74342015-07-07 16:54:23 -07002150#else
2151 // tryBeginTrackSwitch() returns false if the callback has the lock.
2152 if (!mCallbackData->tryBeginTrackSwitch()) {
2153 // fatal if we are starved out.
2154 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2155 "switchToNextOutput() cannot obtain callback lock");
2156 mLock.unlock();
2157 usleep(5 * 1000 /* usec */); // allow callback to use AudioOutput
2158 mLock.lock();
2159 continue;
2160 }
2161#endif
2162 }
2163
2164 Mutex::Autolock nextLock(mNextOutput->mLock);
2165
2166 // If the next output track is not NULL, then it has been
2167 // opened already for playback.
2168 // This is possible even without the next player being started,
2169 // for example, the next player could be prepared and seeked.
2170 //
2171 // Presuming it isn't advisable to force the track over.
2172 if (mNextOutput->mTrack == NULL) {
2173 ALOGD("Recycling track for gapless playback");
2174 delete mNextOutput->mCallbackData;
2175 mNextOutput->mCallbackData = mCallbackData;
2176 mNextOutput->mRecycledTrack = mTrack;
2177 mNextOutput->mSampleRateHz = mSampleRateHz;
2178 mNextOutput->mMsecsPerFrame = mMsecsPerFrame;
Andy Hungd1c74342015-07-07 16:54:23 -07002179 mNextOutput->mFlags = mFlags;
2180 mNextOutput->mFrameSize = mFrameSize;
2181 close_l();
2182 mCallbackData = NULL; // destruction handled by mNextOutput
2183 } else {
2184 ALOGW("Ignoring gapless playback because next player has already started");
2185 // remove track in case resource needed for future players.
2186 if (mCallbackData != NULL) {
2187 mCallbackData->endTrackSwitch(); // release lock for callbacks before close.
2188 }
2189 close_l();
2190 }
2191 }
2192 break;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002193 }
2194}
2195
Wei Jia7d3f4df2015-03-03 15:28:00 -08002196ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002197{
Andy Hungd1c74342015-07-07 16:54:23 -07002198 Mutex::Autolock lock(mLock);
Glenn Kastenadad3d72014-02-21 14:51:43 -08002199 LOG_ALWAYS_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
Andreas Huber20111aa2009-07-14 16:56:47 -07002200
Steve Block3856b092011-10-20 11:56:00 +01002201 //ALOGV("write(%p, %u)", buffer, size);
Glenn Kasten2799d742013-05-30 14:33:29 -07002202 if (mTrack != 0) {
Andy Hung2f6e73d2016-04-08 12:12:58 -07002203 return mTrack->write(buffer, size, blocking);
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07002204 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002205 return NO_INIT;
2206}
2207
2208void MediaPlayerService::AudioOutput::stop()
2209{
Steve Block3856b092011-10-20 11:56:00 +01002210 ALOGV("stop");
Andy Hungd1c74342015-07-07 16:54:23 -07002211 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002212 if (mTrack != 0) mTrack->stop();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002213}
2214
2215void MediaPlayerService::AudioOutput::flush()
2216{
Steve Block3856b092011-10-20 11:56:00 +01002217 ALOGV("flush");
Andy Hungd1c74342015-07-07 16:54:23 -07002218 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002219 if (mTrack != 0) mTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002220}
2221
2222void MediaPlayerService::AudioOutput::pause()
2223{
Steve Block3856b092011-10-20 11:56:00 +01002224 ALOGV("pause");
Andy Hungd1c74342015-07-07 16:54:23 -07002225 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002226 if (mTrack != 0) mTrack->pause();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002227}
2228
2229void MediaPlayerService::AudioOutput::close()
2230{
Steve Block3856b092011-10-20 11:56:00 +01002231 ALOGV("close");
Erik Wolsheimer7845a1f2015-10-30 12:07:52 -07002232 sp<AudioTrack> track;
2233 {
2234 Mutex::Autolock lock(mLock);
2235 track = mTrack;
2236 close_l(); // clears mTrack
2237 }
2238 // destruction of the track occurs outside of mutex.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002239}
2240
2241void MediaPlayerService::AudioOutput::setVolume(float left, float right)
2242{
Steve Block3856b092011-10-20 11:56:00 +01002243 ALOGV("setVolume(%f, %f)", left, right);
Andy Hungd1c74342015-07-07 16:54:23 -07002244 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002245 mLeftVolume = left;
2246 mRightVolume = right;
Glenn Kasten2799d742013-05-30 14:33:29 -07002247 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002248 mTrack->setVolume(left, right);
2249 }
2250}
2251
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002252status_t MediaPlayerService::AudioOutput::setPlaybackRate(const AudioPlaybackRate &rate)
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002253{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002254 ALOGV("setPlaybackRate(%f %f %d %d)",
2255 rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Andy Hungd1c74342015-07-07 16:54:23 -07002256 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002257 if (mTrack == 0) {
2258 // remember rate so that we can set it when the track is opened
2259 mPlaybackRate = rate;
2260 return OK;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002261 }
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002262 status_t res = mTrack->setPlaybackRate(rate);
2263 if (res != NO_ERROR) {
2264 return res;
2265 }
2266 // rate.mSpeed is always greater than 0 if setPlaybackRate succeeded
2267 CHECK_GT(rate.mSpeed, 0.f);
2268 mPlaybackRate = rate;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002269 if (mSampleRateHz != 0) {
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002270 mMsecsPerFrame = 1E3f / (rate.mSpeed * mSampleRateHz);
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002271 }
2272 return res;
2273}
2274
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002275status_t MediaPlayerService::AudioOutput::getPlaybackRate(AudioPlaybackRate *rate)
2276{
2277 ALOGV("setPlaybackRate");
Andy Hungd1c74342015-07-07 16:54:23 -07002278 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002279 if (mTrack == 0) {
2280 return NO_INIT;
2281 }
2282 *rate = mTrack->getPlaybackRate();
2283 return NO_ERROR;
2284}
2285
Eric Laurent2beeb502010-07-16 07:43:46 -07002286status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
2287{
Steve Block3856b092011-10-20 11:56:00 +01002288 ALOGV("setAuxEffectSendLevel(%f)", level);
Andy Hungd1c74342015-07-07 16:54:23 -07002289 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002290 mSendLevel = level;
Glenn Kasten2799d742013-05-30 14:33:29 -07002291 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002292 return mTrack->setAuxEffectSendLevel(level);
2293 }
2294 return NO_ERROR;
2295}
2296
2297status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
2298{
Steve Block3856b092011-10-20 11:56:00 +01002299 ALOGV("attachAuxEffect(%d)", effectId);
Andy Hungd1c74342015-07-07 16:54:23 -07002300 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002301 mAuxEffectId = effectId;
Glenn Kasten2799d742013-05-30 14:33:29 -07002302 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002303 return mTrack->attachAuxEffect(effectId);
2304 }
2305 return NO_ERROR;
2306}
2307
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002308VolumeShaper::Status MediaPlayerService::AudioOutput::applyVolumeShaper(
2309 const sp<VolumeShaper::Configuration>& configuration,
2310 const sp<VolumeShaper::Operation>& operation)
2311{
2312 Mutex::Autolock lock(mLock);
2313 ALOGV("AudioOutput::applyVolumeShaper");
Andy Hung4ef88d72017-02-21 19:47:53 -08002314
Andy Hung4ef88d72017-02-21 19:47:53 -08002315 mVolumeHandler->setIdIfNecessary(configuration);
Andy Hung39399b62017-04-21 15:07:45 -07002316
2317 VolumeShaper::Status status;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002318 if (mTrack != 0) {
Andy Hung39399b62017-04-21 15:07:45 -07002319 status = mTrack->applyVolumeShaper(configuration, operation);
2320 if (status >= 0) {
2321 (void)mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hungf3702642017-05-05 17:33:32 -07002322 if (mTrack->isPlaying()) { // match local AudioTrack to properly restore.
2323 mVolumeHandler->setStarted();
2324 }
Andy Hung39399b62017-04-21 15:07:45 -07002325 }
Andy Hung4ef88d72017-02-21 19:47:53 -08002326 } else {
Andy Hungc01eddb2017-07-21 16:42:41 -07002327 // VolumeShapers are not affected when a track moves between players for
2328 // gapless playback (setNextMediaPlayer).
2329 // We forward VolumeShaper operations that do not change configuration
2330 // to the new player so that unducking may occur as expected.
2331 // Unducking is an idempotent operation, same if applied back-to-back.
2332 if (configuration->getType() == VolumeShaper::Configuration::TYPE_ID
2333 && mNextOutput != nullptr) {
2334 ALOGV("applyVolumeShaper: Attempting to forward missed operation: %s %s",
2335 configuration->toString().c_str(), operation->toString().c_str());
2336 Mutex::Autolock nextLock(mNextOutput->mLock);
2337
2338 // recycled track should be forwarded from this AudioSink by switchToNextOutput
2339 sp<AudioTrack> track = mNextOutput->mRecycledTrack;
2340 if (track != nullptr) {
2341 ALOGD("Forward VolumeShaper operation to recycled track %p", track.get());
2342 (void)track->applyVolumeShaper(configuration, operation);
2343 } else {
2344 // There is a small chance that the unduck occurs after the next
2345 // player has already started, but before it is registered to receive
2346 // the unduck command.
2347 track = mNextOutput->mTrack;
2348 if (track != nullptr) {
2349 ALOGD("Forward VolumeShaper operation to track %p", track.get());
2350 (void)track->applyVolumeShaper(configuration, operation);
2351 }
2352 }
2353 }
Andy Hung39399b62017-04-21 15:07:45 -07002354 status = mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002355 }
Andy Hung39399b62017-04-21 15:07:45 -07002356 return status;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002357}
2358
2359sp<VolumeShaper::State> MediaPlayerService::AudioOutput::getVolumeShaperState(int id)
2360{
2361 Mutex::Autolock lock(mLock);
2362 if (mTrack != 0) {
2363 return mTrack->getVolumeShaperState(id);
Andy Hung4ef88d72017-02-21 19:47:53 -08002364 } else {
2365 return mVolumeHandler->getVolumeShaperState(id);
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002366 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002367}
2368
Andreas Huber20111aa2009-07-14 16:56:47 -07002369// static
2370void MediaPlayerService::AudioOutput::CallbackWrapper(
Glenn Kastend217a8c2011-06-01 15:20:35 -07002371 int event, void *cookie, void *info) {
Steve Block3856b092011-10-20 11:56:00 +01002372 //ALOGV("callbackwrapper");
Marco Nelissen6b74d672012-02-28 16:07:44 -08002373 CallbackData *data = (CallbackData*)cookie;
Andy Hungd1c74342015-07-07 16:54:23 -07002374 // lock to ensure we aren't caught in the middle of a track switch.
Marco Nelissen6b74d672012-02-28 16:07:44 -08002375 data->lock();
2376 AudioOutput *me = data->getOutput();
Andreas Huber20111aa2009-07-14 16:56:47 -07002377 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002378 if (me == NULL) {
2379 // no output set, likely because the track was scheduled to be reused
2380 // by another player, but the format turned out to be incompatible.
2381 data->unlock();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002382 if (buffer != NULL) {
2383 buffer->size = 0;
2384 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08002385 return;
2386 }
Andreas Huber20111aa2009-07-14 16:56:47 -07002387
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002388 switch(event) {
2389 case AudioTrack::EVENT_MORE_DATA: {
2390 size_t actualSize = (*me->mCallback)(
2391 me, buffer->raw, buffer->size, me->mCallbackCookie,
2392 CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002393
Andy Hung719b46b2015-05-31 22:18:25 -07002394 // Log when no data is returned from the callback.
2395 // (1) We may have no data (especially with network streaming sources).
2396 // (2) We may have reached the EOS and the audio track is not stopped yet.
2397 // Note that AwesomePlayer/AudioPlayer will only return zero size when it reaches the EOS.
2398 // NuPlayerRenderer will return zero when it doesn't have data (it doesn't block to fill).
2399 //
2400 // This is a benign busy-wait, with the next data request generated 10 ms or more later;
2401 // nevertheless for power reasons, we don't want to see too many of these.
Andreas Huber2e8ffaf2010-02-18 16:45:13 -08002402
Andy Hung719b46b2015-05-31 22:18:25 -07002403 ALOGV_IF(actualSize == 0 && buffer->size > 0, "callbackwrapper: empty buffer returned");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002404
2405 buffer->size = actualSize;
2406 } break;
2407
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002408 case AudioTrack::EVENT_STREAM_END:
Andy Hung719b46b2015-05-31 22:18:25 -07002409 // currently only occurs for offloaded callbacks
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002410 ALOGV("callbackwrapper: deliver EVENT_STREAM_END");
2411 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2412 me->mCallbackCookie, CB_EVENT_STREAM_END);
2413 break;
2414
2415 case AudioTrack::EVENT_NEW_IAUDIOTRACK :
2416 ALOGV("callbackwrapper: deliver EVENT_TEAR_DOWN");
2417 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2418 me->mCallbackCookie, CB_EVENT_TEAR_DOWN);
2419 break;
2420
Glenn Kasten421743b2015-06-01 08:18:08 -07002421 case AudioTrack::EVENT_UNDERRUN:
Andy Hung719b46b2015-05-31 22:18:25 -07002422 // This occurs when there is no data available, typically
Glenn Kasten421743b2015-06-01 08:18:08 -07002423 // when there is a failure to supply data to the AudioTrack. It can also
2424 // occur in non-offloaded mode when the audio device comes out of standby.
2425 //
Andy Hung719b46b2015-05-31 22:18:25 -07002426 // If an AudioTrack underruns it outputs silence. Since this happens suddenly
2427 // it may sound like an audible pop or glitch.
2428 //
2429 // The underrun event is sent once per track underrun; the condition is reset
2430 // when more data is sent to the AudioTrack.
Eric Laurente93cc032016-05-05 10:15:10 -07002431 ALOGD("callbackwrapper: EVENT_UNDERRUN (discarded)");
Glenn Kasten421743b2015-06-01 08:18:08 -07002432 break;
2433
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002434 default:
2435 ALOGE("received unknown event type: %d inside CallbackWrapper !", event);
Andreas Huber51c1e0e2011-04-04 11:43:40 -07002436 }
2437
Marco Nelissen6b74d672012-02-28 16:07:44 -08002438 data->unlock();
Andreas Huber20111aa2009-07-14 16:56:47 -07002439}
2440
Glenn Kastend848eb42016-03-08 13:42:11 -08002441audio_session_t MediaPlayerService::AudioOutput::getSessionId() const
Eric Laurent8c563ed2010-10-07 18:23:03 -07002442{
Andy Hungd1c74342015-07-07 16:54:23 -07002443 Mutex::Autolock lock(mLock);
Eric Laurent8c563ed2010-10-07 18:23:03 -07002444 return mSessionId;
2445}
2446
Eric Laurent6f59db12013-07-26 17:16:50 -07002447uint32_t MediaPlayerService::AudioOutput::getSampleRate() const
2448{
Andy Hungd1c74342015-07-07 16:54:23 -07002449 Mutex::Autolock lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -07002450 if (mTrack == 0) return 0;
2451 return mTrack->getSampleRate();
2452}
2453
Andy Hungf2c87b32016-04-07 19:49:29 -07002454int64_t MediaPlayerService::AudioOutput::getBufferDurationInUs() const
2455{
2456 Mutex::Autolock lock(mLock);
2457 if (mTrack == 0) {
2458 return 0;
2459 }
2460 int64_t duration;
2461 if (mTrack->getBufferDurationInUs(&duration) != OK) {
2462 return 0;
2463 }
2464 return duration;
2465}
2466
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002467////////////////////////////////////////////////////////////////////////////////
2468
2469struct CallbackThread : public Thread {
2470 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
2471 MediaPlayerBase::AudioSink::AudioCallback cb,
2472 void *cookie);
2473
2474protected:
2475 virtual ~CallbackThread();
2476
2477 virtual bool threadLoop();
2478
2479private:
2480 wp<MediaPlayerBase::AudioSink> mSink;
2481 MediaPlayerBase::AudioSink::AudioCallback mCallback;
2482 void *mCookie;
2483 void *mBuffer;
2484 size_t mBufferSize;
2485
2486 CallbackThread(const CallbackThread &);
2487 CallbackThread &operator=(const CallbackThread &);
2488};
2489
2490CallbackThread::CallbackThread(
2491 const wp<MediaPlayerBase::AudioSink> &sink,
2492 MediaPlayerBase::AudioSink::AudioCallback cb,
2493 void *cookie)
2494 : mSink(sink),
2495 mCallback(cb),
2496 mCookie(cookie),
2497 mBuffer(NULL),
2498 mBufferSize(0) {
2499}
2500
2501CallbackThread::~CallbackThread() {
2502 if (mBuffer) {
2503 free(mBuffer);
2504 mBuffer = NULL;
2505 }
2506}
2507
2508bool CallbackThread::threadLoop() {
2509 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
2510 if (sink == NULL) {
2511 return false;
2512 }
2513
2514 if (mBuffer == NULL) {
2515 mBufferSize = sink->bufferSize();
2516 mBuffer = malloc(mBufferSize);
2517 }
2518
2519 size_t actualSize =
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002520 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie,
2521 MediaPlayerBase::AudioSink::CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002522
2523 if (actualSize > 0) {
2524 sink->write(mBuffer, actualSize);
Andy Hunga31335a2014-08-20 17:37:59 -07002525 // Could return false on sink->write() error or short count.
2526 // Not necessarily appropriate but would work for AudioCache behavior.
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002527 }
2528
2529 return true;
2530}
2531
2532////////////////////////////////////////////////////////////////////////////////
2533
Chong Zhange5b9b692017-05-11 11:44:56 -07002534void MediaPlayerService::addBatteryData(uint32_t params) {
2535 mBatteryTracker.addBatteryData(params);
2536}
2537
2538status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
2539 return mBatteryTracker.pullBatteryData(reply);
2540}
2541
2542MediaPlayerService::BatteryTracker::BatteryTracker() {
2543 mBatteryAudio.refCount = 0;
2544 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2545 mBatteryAudio.deviceOn[i] = 0;
2546 mBatteryAudio.lastTime[i] = 0;
2547 mBatteryAudio.totalTime[i] = 0;
2548 }
2549 // speaker is on by default
2550 mBatteryAudio.deviceOn[SPEAKER] = 1;
2551
2552 // reset battery stats
2553 // if the mediaserver has crashed, battery stats could be left
2554 // in bad state, reset the state upon service start.
2555 BatteryNotifier::getInstance().noteResetVideo();
2556}
2557
2558void MediaPlayerService::BatteryTracker::addBatteryData(uint32_t params)
Gloria Wang7cf180c2011-02-19 18:37:57 -08002559{
2560 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002561
2562 int32_t time = systemTime() / 1000000L;
2563
2564 // change audio output devices. This notification comes from AudioFlinger
2565 if ((params & kBatteryDataSpeakerOn)
2566 || (params & kBatteryDataOtherAudioDeviceOn)) {
2567
2568 int deviceOn[NUM_AUDIO_DEVICES];
2569 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2570 deviceOn[i] = 0;
2571 }
2572
2573 if ((params & kBatteryDataSpeakerOn)
2574 && (params & kBatteryDataOtherAudioDeviceOn)) {
2575 deviceOn[SPEAKER_AND_OTHER] = 1;
2576 } else if (params & kBatteryDataSpeakerOn) {
2577 deviceOn[SPEAKER] = 1;
2578 } else {
2579 deviceOn[OTHER_AUDIO_DEVICE] = 1;
2580 }
2581
2582 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2583 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
2584
2585 if (mBatteryAudio.refCount > 0) { // if playing audio
2586 if (!deviceOn[i]) {
2587 mBatteryAudio.lastTime[i] += time;
2588 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2589 mBatteryAudio.lastTime[i] = 0;
2590 } else {
2591 mBatteryAudio.lastTime[i] = 0 - time;
2592 }
2593 }
2594
2595 mBatteryAudio.deviceOn[i] = deviceOn[i];
2596 }
2597 }
2598 return;
2599 }
2600
Marco Nelissenb7848f12014-12-04 08:57:56 -08002601 // an audio stream is started
Gloria Wang9ee159b2011-02-24 14:51:45 -08002602 if (params & kBatteryDataAudioFlingerStart) {
2603 // record the start time only if currently no other audio
2604 // is being played
2605 if (mBatteryAudio.refCount == 0) {
2606 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2607 if (mBatteryAudio.deviceOn[i]) {
2608 mBatteryAudio.lastTime[i] -= time;
2609 }
2610 }
2611 }
2612
2613 mBatteryAudio.refCount ++;
2614 return;
2615
2616 } else if (params & kBatteryDataAudioFlingerStop) {
2617 if (mBatteryAudio.refCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002618 ALOGW("Battery track warning: refCount is <= 0");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002619 return;
2620 }
2621
2622 // record the stop time only if currently this is the only
2623 // audio being played
2624 if (mBatteryAudio.refCount == 1) {
2625 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2626 if (mBatteryAudio.deviceOn[i]) {
2627 mBatteryAudio.lastTime[i] += time;
2628 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2629 mBatteryAudio.lastTime[i] = 0;
2630 }
2631 }
2632 }
2633
2634 mBatteryAudio.refCount --;
2635 return;
2636 }
2637
Andy Hung1afd0982016-11-08 16:13:44 -08002638 uid_t uid = IPCThreadState::self()->getCallingUid();
Gloria Wang7cf180c2011-02-19 18:37:57 -08002639 if (uid == AID_MEDIA) {
2640 return;
2641 }
2642 int index = mBatteryData.indexOfKey(uid);
Gloria Wang7cf180c2011-02-19 18:37:57 -08002643
2644 if (index < 0) { // create a new entry for this UID
2645 BatteryUsageInfo info;
2646 info.audioTotalTime = 0;
2647 info.videoTotalTime = 0;
2648 info.audioLastTime = 0;
2649 info.videoLastTime = 0;
2650 info.refCount = 0;
2651
Gloria Wang9ee159b2011-02-24 14:51:45 -08002652 if (mBatteryData.add(uid, info) == NO_MEMORY) {
Steve Block29357bc2012-01-06 19:20:56 +00002653 ALOGE("Battery track error: no memory for new app");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002654 return;
2655 }
Gloria Wang7cf180c2011-02-19 18:37:57 -08002656 }
2657
2658 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
2659
2660 if (params & kBatteryDataCodecStarted) {
2661 if (params & kBatteryDataTrackAudio) {
2662 info.audioLastTime -= time;
2663 info.refCount ++;
2664 }
2665 if (params & kBatteryDataTrackVideo) {
2666 info.videoLastTime -= time;
2667 info.refCount ++;
2668 }
2669 } else {
2670 if (info.refCount == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002671 ALOGW("Battery track warning: refCount is already 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002672 return;
2673 } else if (info.refCount < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00002674 ALOGE("Battery track error: refCount < 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002675 mBatteryData.removeItem(uid);
2676 return;
2677 }
2678
2679 if (params & kBatteryDataTrackAudio) {
2680 info.audioLastTime += time;
2681 info.refCount --;
2682 }
2683 if (params & kBatteryDataTrackVideo) {
2684 info.videoLastTime += time;
2685 info.refCount --;
2686 }
2687
2688 // no stream is being played by this UID
2689 if (info.refCount == 0) {
2690 info.audioTotalTime += info.audioLastTime;
2691 info.audioLastTime = 0;
2692 info.videoTotalTime += info.videoLastTime;
2693 info.videoLastTime = 0;
2694 }
2695 }
2696}
2697
Chong Zhange5b9b692017-05-11 11:44:56 -07002698status_t MediaPlayerService::BatteryTracker::pullBatteryData(Parcel* reply) {
Gloria Wang7cf180c2011-02-19 18:37:57 -08002699 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002700
2701 // audio output devices usage
2702 int32_t time = systemTime() / 1000000L; //in ms
2703 int32_t totalTime;
2704
2705 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2706 totalTime = mBatteryAudio.totalTime[i];
2707
2708 if (mBatteryAudio.deviceOn[i]
2709 && (mBatteryAudio.lastTime[i] != 0)) {
2710 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
2711 totalTime += tmpTime;
2712 }
2713
2714 reply->writeInt32(totalTime);
2715 // reset the total time
2716 mBatteryAudio.totalTime[i] = 0;
2717 }
2718
2719 // codec usage
Gloria Wang7cf180c2011-02-19 18:37:57 -08002720 BatteryUsageInfo info;
2721 int size = mBatteryData.size();
2722
2723 reply->writeInt32(size);
2724 int i = 0;
2725
2726 while (i < size) {
2727 info = mBatteryData.valueAt(i);
2728
2729 reply->writeInt32(mBatteryData.keyAt(i)); //UID
2730 reply->writeInt32(info.audioTotalTime);
2731 reply->writeInt32(info.videoTotalTime);
2732
2733 info.audioTotalTime = 0;
2734 info.videoTotalTime = 0;
2735
2736 // remove the UID entry where no stream is being played
2737 if (info.refCount <= 0) {
2738 mBatteryData.removeItemsAt(i);
2739 size --;
2740 i --;
2741 }
2742 i++;
2743 }
2744 return NO_ERROR;
2745}
nikoa64c8c72009-07-20 15:07:26 -07002746} // namespace android