blob: 07dff50bf90bfb200953b87961952c4acf218785 [file] [log] [blame]
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001/*
2**
3** Copyright 2008, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18// Proxy for media player implementations
19
20//#define LOG_NDEBUG 0
21#define LOG_TAG "MediaPlayerService"
22#include <utils/Log.h>
23
24#include <sys/types.h>
25#include <sys/stat.h>
Gloria Wang7cf180c2011-02-19 18:37:57 -080026#include <sys/time.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080027#include <dirent.h>
28#include <unistd.h>
29
30#include <string.h>
Mathias Agopian6f74b0c2009-06-03 17:32:49 -070031
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080032#include <cutils/atomic.h>
Nicolas Catania14d27472009-07-13 14:37:49 -070033#include <cutils/properties.h> // for property_get
Mathias Agopian6f74b0c2009-06-03 17:32:49 -070034
35#include <utils/misc.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080036
Mathias Agopian75624082009-05-19 19:08:10 -070037#include <binder/IPCThreadState.h>
38#include <binder/IServiceManager.h>
39#include <binder/MemoryHeapBase.h>
40#include <binder/MemoryBase.h>
Mathias Agopianb1e7cd12013-02-14 17:11:27 -080041#include <gui/Surface.h>
Nicolas Catania1d187f12009-05-12 23:25:55 -070042#include <utils/Errors.h> // for status_t
43#include <utils/String8.h>
Marco Nelissen10dbb8e2009-09-20 10:42:13 -070044#include <utils/SystemClock.h>
Lajos Molnar06ad1522014-08-28 07:27:44 -070045#include <utils/Timers.h>
Nicolas Catania1d187f12009-05-12 23:25:55 -070046#include <utils/Vector.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080047
Eric Laurent43562692015-07-15 16:49:07 -070048#include <media/AudioPolicyHelper.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080049#include <media/IMediaHTTPService.h>
Jeff Brown2013a542012-09-04 21:38:42 -070050#include <media/IRemoteDisplay.h>
51#include <media/IRemoteDisplayClient.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080052#include <media/MediaPlayerInterface.h>
53#include <media/mediarecorder.h>
54#include <media/MediaMetadataRetrieverInterface.h>
nikoa64c8c72009-07-20 15:07:26 -070055#include <media/Metadata.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080056#include <media/AudioTrack.h>
James Dong8635b7b2011-03-14 17:01:38 -070057#include <media/MemoryLeakTrackUtil.h>
Lajos Molnar1381d4b2014-08-07 15:18:35 -070058#include <media/stagefright/MediaCodecList.h>
Eric Laurent9cb839a2011-09-27 09:48:56 -070059#include <media/stagefright/MediaErrors.h>
Marco Nelissen83b0fd92015-09-16 13:48:07 -070060#include <media/stagefright/Utils.h>
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +010061#include <media/stagefright/foundation/ADebug.h>
Marco Nelissenf09611f2015-02-13 14:12:42 -080062#include <media/stagefright/foundation/ALooperRoster.h>
Chong Zhang181fd9b2017-02-16 15:53:03 -080063#include <media/stagefright/SurfaceUtils.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070064#include <mediautils/BatteryNotifier.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080065
Andy Hung53541292016-04-13 16:48:51 -070066#include <memunreachable/memunreachable.h>
Dima Zavin64760242011-05-11 14:15:23 -070067#include <system/audio.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070068
Gloria Wang7cf180c2011-02-19 18:37:57 -080069#include <private/android_filesystem_config.h>
70
James Dong559bf282012-03-28 10:29:14 -070071#include "ActivityManager.h"
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080072#include "MediaRecorderClient.h"
73#include "MediaPlayerService.h"
74#include "MetadataRetrieverClient.h"
John Grossman44a7e422012-06-21 17:29:24 -070075#include "MediaPlayerFactory.h"
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080076
Nicolas Catania14d27472009-07-13 14:37:49 -070077#include "TestPlayerStub.h"
Andreas Huberf9334412010-12-15 15:17:42 -080078#include "nuplayer/NuPlayerDriver.h"
Andreas Huber20111aa2009-07-14 16:56:47 -070079
Andreas Huberb7319a72013-05-29 14:20:52 -070080#include "HTTPBase.h"
Andreas Hubered3e3e02012-03-26 11:13:27 -070081
Wei Jia502c2f42017-07-13 17:47:56 -070082static const int kDumpLockRetries = 50;
83static const int kDumpLockSleepUs = 20000;
84
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070085namespace {
nikoa64c8c72009-07-20 15:07:26 -070086using android::media::Metadata;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070087using android::status_t;
88using android::OK;
89using android::BAD_VALUE;
90using android::NOT_ENOUGH_DATA;
91using android::Parcel;
Ivan Lozano8cf3a072017-08-09 09:01:33 -070092using android::media::VolumeShaper;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070093
94// Max number of entries in the filter.
95const int kMaxFilterSize = 64; // I pulled that out of thin air.
96
Andy Hungff874dc2016-04-11 16:49:09 -070097const float kMaxRequiredSpeed = 8.0f; // for PCM tracks allow up to 8x speedup.
98
nikoa64c8c72009-07-20 15:07:26 -070099// FIXME: Move all the metadata related function in the Metadata.cpp
nikod608a812009-07-16 16:39:53 -0700100
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700101
102// Unmarshall a filter from a Parcel.
103// Filter format in a parcel:
104//
105// 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
106// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
107// | number of entries (n) |
108// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
109// | metadata type 1 |
110// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
111// | metadata type 2 |
112// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
113// ....
114// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
115// | metadata type n |
116// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
117//
118// @param p Parcel that should start with a filter.
119// @param[out] filter On exit contains the list of metadata type to be
120// filtered.
121// @param[out] status On exit contains the status code to be returned.
122// @return true if the parcel starts with a valid filter.
123bool unmarshallFilter(const Parcel& p,
nikoa64c8c72009-07-20 15:07:26 -0700124 Metadata::Filter *filter,
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700125 status_t *status)
126{
Nicolas Catania48290382009-07-10 13:53:06 -0700127 int32_t val;
128 if (p.readInt32(&val) != OK)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700129 {
Steve Block29357bc2012-01-06 19:20:56 +0000130 ALOGE("Failed to read filter's length");
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700131 *status = NOT_ENOUGH_DATA;
132 return false;
133 }
134
Nicolas Catania48290382009-07-10 13:53:06 -0700135 if( val > kMaxFilterSize || val < 0)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700136 {
Steve Block29357bc2012-01-06 19:20:56 +0000137 ALOGE("Invalid filter len %d", val);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700138 *status = BAD_VALUE;
139 return false;
140 }
141
Nicolas Catania48290382009-07-10 13:53:06 -0700142 const size_t num = val;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700143
144 filter->clear();
Nicolas Catania48290382009-07-10 13:53:06 -0700145 filter->setCapacity(num);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700146
nikoa64c8c72009-07-20 15:07:26 -0700147 size_t size = num * sizeof(Metadata::Type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700148
Nicolas Catania48290382009-07-10 13:53:06 -0700149
150 if (p.dataAvail() < size)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700151 {
Andy Hung833b4752016-04-04 17:15:48 -0700152 ALOGE("Filter too short expected %zu but got %zu", size, p.dataAvail());
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700153 *status = NOT_ENOUGH_DATA;
154 return false;
155 }
156
nikoa64c8c72009-07-20 15:07:26 -0700157 const Metadata::Type *data =
158 static_cast<const Metadata::Type*>(p.readInplace(size));
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700159
Nicolas Catania48290382009-07-10 13:53:06 -0700160 if (NULL == data)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700161 {
Steve Block29357bc2012-01-06 19:20:56 +0000162 ALOGE("Filter had no data");
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700163 *status = BAD_VALUE;
164 return false;
165 }
166
167 // TODO: The stl impl of vector would be more efficient here
168 // because it degenerates into a memcpy on pod types. Try to
169 // replace later or use stl::set.
Nicolas Catania48290382009-07-10 13:53:06 -0700170 for (size_t i = 0; i < num; ++i)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700171 {
Nicolas Catania48290382009-07-10 13:53:06 -0700172 filter->add(*data);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700173 ++data;
174 }
175 *status = OK;
176 return true;
177}
178
Nicolas Catania48290382009-07-10 13:53:06 -0700179// @param filter Of metadata type.
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700180// @param val To be searched.
181// @return true if a match was found.
nikoa64c8c72009-07-20 15:07:26 -0700182bool findMetadata(const Metadata::Filter& filter, const int32_t val)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700183{
184 // Deal with empty and ANY right away
185 if (filter.isEmpty()) return false;
nikoa64c8c72009-07-20 15:07:26 -0700186 if (filter[0] == Metadata::kAny) return true;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700187
Nicolas Catania48290382009-07-10 13:53:06 -0700188 return filter.indexOf(val) >= 0;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700189}
190
191} // anonymous namespace
192
193
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700194namespace {
195using android::Parcel;
196using android::String16;
197
198// marshalling tag indicating flattened utf16 tags
199// keep in sync with frameworks/base/media/java/android/media/AudioAttributes.java
200const int32_t kAudioAttributesMarshallTagFlattenTags = 1;
201
202// Audio attributes format in a parcel:
203//
204// 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
205// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
206// | usage |
207// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
208// | content_type |
209// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Hyejin Kim4f418f92014-09-05 15:50:03 +0900210// | source |
211// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700212// | flags |
213// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
214// | kAudioAttributesMarshallTagFlattenTags | // ignore tags if not found
215// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
216// | flattened tags in UTF16 |
217// | ... |
218// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
219//
220// @param p Parcel that contains audio attributes.
221// @param[out] attributes On exit points to an initialized audio_attributes_t structure
222// @param[out] status On exit contains the status code to be returned.
223void unmarshallAudioAttributes(const Parcel& parcel, audio_attributes_t *attributes)
224{
225 attributes->usage = (audio_usage_t) parcel.readInt32();
226 attributes->content_type = (audio_content_type_t) parcel.readInt32();
Hyejin Kim4f418f92014-09-05 15:50:03 +0900227 attributes->source = (audio_source_t) parcel.readInt32();
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700228 attributes->flags = (audio_flags_mask_t) parcel.readInt32();
229 const bool hasFlattenedTag = (parcel.readInt32() == kAudioAttributesMarshallTagFlattenTags);
230 if (hasFlattenedTag) {
231 // the tags are UTF16, convert to UTF8
232 String16 tags = parcel.readString16();
233 ssize_t realTagSize = utf16_to_utf8_length(tags.string(), tags.size());
234 if (realTagSize <= 0) {
235 strcpy(attributes->tags, "");
236 } else {
237 // copy the flattened string into the attributes as the destination for the conversion:
238 // copying array size -1, array for tags was calloc'd, no need to NULL-terminate it
239 size_t tagSize = realTagSize > AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 ?
240 AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 : realTagSize;
Sergio Giro1d3f4272016-06-28 18:24:52 +0100241 utf16_to_utf8(tags.string(), tagSize, attributes->tags,
242 sizeof(attributes->tags) / sizeof(attributes->tags[0]));
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700243 }
244 } else {
245 ALOGE("unmarshallAudioAttributes() received unflattened tags, ignoring tag values");
246 strcpy(attributes->tags, "");
247 }
248}
249} // anonymous namespace
250
251
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800252namespace android {
253
Marco Nelissenf09611f2015-02-13 14:12:42 -0800254extern ALooperRoster gLooperRoster;
255
256
Dave Burked681bbb2011-08-30 14:39:17 +0100257static bool checkPermission(const char* permissionString) {
Dave Burked681bbb2011-08-30 14:39:17 +0100258 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
259 bool ok = checkCallingPermission(String16(permissionString));
Steve Block29357bc2012-01-06 19:20:56 +0000260 if (!ok) ALOGE("Request requires %s", permissionString);
Dave Burked681bbb2011-08-30 14:39:17 +0100261 return ok;
262}
263
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800264// 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 -0800265/* static */ int MediaPlayerService::AudioOutput::mMinBufferCount = 4;
266/* static */ bool MediaPlayerService::AudioOutput::mIsOnEmulator = false;
267
268void MediaPlayerService::instantiate() {
269 defaultServiceManager()->addService(
270 String16("media.player"), new MediaPlayerService());
271}
272
273MediaPlayerService::MediaPlayerService()
274{
Steve Block3856b092011-10-20 11:56:00 +0100275 ALOGV("MediaPlayerService created");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800276 mNextConnId = 1;
Gloria Wang9ee159b2011-02-24 14:51:45 -0800277
John Grossman44a7e422012-06-21 17:29:24 -0700278 MediaPlayerFactory::registerBuiltinFactories();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800279}
280
281MediaPlayerService::~MediaPlayerService()
282{
Steve Block3856b092011-10-20 11:56:00 +0100283 ALOGV("MediaPlayerService destroyed");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800284}
285
Svet Ganovbe71aa22015-04-28 12:06:02 -0700286sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(const String16 &opPackageName)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800287{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800288 pid_t pid = IPCThreadState::self()->getCallingPid();
Svet Ganovbe71aa22015-04-28 12:06:02 -0700289 sp<MediaRecorderClient> recorder = new MediaRecorderClient(this, pid, opPackageName);
Gloria Wangdac6a312009-10-29 15:46:37 -0700290 wp<MediaRecorderClient> w = recorder;
291 Mutex::Autolock lock(mLock);
292 mMediaRecorderClients.add(w);
Steve Block3856b092011-10-20 11:56:00 +0100293 ALOGV("Create new media recorder client from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800294 return recorder;
295}
296
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -0700297void MediaPlayerService::removeMediaRecorderClient(const wp<MediaRecorderClient>& client)
Gloria Wangdac6a312009-10-29 15:46:37 -0700298{
299 Mutex::Autolock lock(mLock);
300 mMediaRecorderClients.remove(client);
Steve Block3856b092011-10-20 11:56:00 +0100301 ALOGV("Delete media recorder client");
Gloria Wangdac6a312009-10-29 15:46:37 -0700302}
303
Glenn Kastenf37971f2012-02-03 11:06:53 -0800304sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800305{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800306 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800307 sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
Steve Block3856b092011-10-20 11:56:00 +0100308 ALOGV("Create new media retriever from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800309 return retriever;
310}
311
Glenn Kastenf37971f2012-02-03 11:06:53 -0800312sp<IMediaPlayer> MediaPlayerService::create(const sp<IMediaPlayerClient>& client,
Glenn Kastend848eb42016-03-08 13:42:11 -0800313 audio_session_t audioSessionId)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800314{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800315 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800316 int32_t connId = android_atomic_inc(&mNextConnId);
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700317
318 sp<Client> c = new Client(
319 this, pid, connId, client, audioSessionId,
320 IPCThreadState::self()->getCallingUid());
321
Steve Block3856b092011-10-20 11:56:00 +0100322 ALOGV("Create new client(%d) from pid %d, uid %d, ", connId, pid,
Dave Burked681bbb2011-08-30 14:39:17 +0100323 IPCThreadState::self()->getCallingUid());
324
325 wp<Client> w = c;
326 {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800327 Mutex::Autolock lock(mLock);
328 mClients.add(w);
329 }
Andreas Hubere2b10282010-11-23 11:41:34 -0800330 return c;
331}
332
Lajos Molnar1381d4b2014-08-07 15:18:35 -0700333sp<IMediaCodecList> MediaPlayerService::getCodecList() const {
334 return MediaCodecList::getLocalInstance();
335}
336
Jeff Brown2013a542012-09-04 21:38:42 -0700337sp<IRemoteDisplay> MediaPlayerService::listenForRemoteDisplay(
Chong Zhangd0a98fa2017-09-14 17:43:10 -0700338 const String16 &/*opPackageName*/,
339 const sp<IRemoteDisplayClient>& /*client*/,
340 const String8& /*iface*/) {
341 ALOGE("listenForRemoteDisplay is no longer supported!");
Jeff Brownaba33d52012-09-07 17:38:58 -0700342
Chong Zhangd0a98fa2017-09-14 17:43:10 -0700343 return NULL;
Jeff Brown2013a542012-09-04 21:38:42 -0700344}
345
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800346status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
347{
348 const size_t SIZE = 256;
349 char buffer[SIZE];
350 String8 result;
351
352 result.append(" AudioOutput\n");
353 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n",
354 mStreamType, mLeftVolume, mRightVolume);
355 result.append(buffer);
356 snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n",
Eric Laurentdb354e52012-03-05 17:27:11 -0800357 mMsecsPerFrame, (mTrack != 0) ? mTrack->latency() : -1);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800358 result.append(buffer);
Eric Laurent2beeb502010-07-16 07:43:46 -0700359 snprintf(buffer, 255, " aux effect id(%d), send level (%f)\n",
360 mAuxEffectId, mSendLevel);
361 result.append(buffer);
362
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800363 ::write(fd, result.string(), result.size());
364 if (mTrack != 0) {
365 mTrack->dump(fd, args);
366 }
367 return NO_ERROR;
368}
369
Lajos Molnar6d339f12015-04-17 16:15:53 -0700370status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800371{
372 const size_t SIZE = 256;
373 char buffer[SIZE];
374 String8 result;
375 result.append(" Client\n");
376 snprintf(buffer, 255, " pid(%d), connId(%d), status(%d), looping(%s)\n",
377 mPid, mConnId, mStatus, mLoop?"true": "false");
378 result.append(buffer);
Wei Jia502c2f42017-07-13 17:47:56 -0700379
380 sp<MediaPlayerBase> p;
381 sp<AudioOutput> audioOutput;
382 bool locked = false;
383 for (int i = 0; i < kDumpLockRetries; ++i) {
384 if (mLock.tryLock() == NO_ERROR) {
385 locked = true;
386 break;
387 }
388 usleep(kDumpLockSleepUs);
Andreas Hubera0b1d4b2011-06-07 15:52:25 -0700389 }
Wei Jia502c2f42017-07-13 17:47:56 -0700390
391 if (locked) {
392 p = mPlayer;
393 audioOutput = mAudioOutput;
394 mLock.unlock();
395 } else {
396 result.append(" lock is taken, no dump from player and audio output\n");
397 }
398 write(fd, result.string(), result.size());
399
400 if (p != NULL) {
401 p->dump(fd, args);
402 }
403 if (audioOutput != 0) {
404 audioOutput->dump(fd, args);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800405 }
406 write(fd, "\n", 1);
407 return NO_ERROR;
408}
409
Marco Nelissenf09611f2015-02-13 14:12:42 -0800410/**
411 * The only arguments this understands right now are -c, -von and -voff,
412 * which are parsed by ALooperRoster::dump()
413 */
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800414status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
415{
416 const size_t SIZE = 256;
417 char buffer[SIZE];
418 String8 result;
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530419 SortedVector< sp<Client> > clients; //to serialise the mutex unlock & client destruction.
420 SortedVector< sp<MediaRecorderClient> > mediaRecorderClients;
421
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800422 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
423 snprintf(buffer, SIZE, "Permission Denial: "
424 "can't dump MediaPlayerService from pid=%d, uid=%d\n",
425 IPCThreadState::self()->getCallingPid(),
426 IPCThreadState::self()->getCallingUid());
427 result.append(buffer);
428 } else {
429 Mutex::Autolock lock(mLock);
430 for (int i = 0, n = mClients.size(); i < n; ++i) {
431 sp<Client> c = mClients[i].promote();
432 if (c != 0) c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530433 clients.add(c);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800434 }
James Dongb9141222010-07-08 11:16:11 -0700435 if (mMediaRecorderClients.size() == 0) {
436 result.append(" No media recorder client\n\n");
437 } else {
438 for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
439 sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
James Donge579e282011-10-18 22:29:20 -0700440 if (c != 0) {
441 snprintf(buffer, 255, " MediaRecorderClient pid(%d)\n", c->mPid);
442 result.append(buffer);
443 write(fd, result.string(), result.size());
444 result = "\n";
445 c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530446 mediaRecorderClients.add(c);
James Donge579e282011-10-18 22:29:20 -0700447 }
James Dongb9141222010-07-08 11:16:11 -0700448 }
Gloria Wangdac6a312009-10-29 15:46:37 -0700449 }
450
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800451 result.append(" Files opened and/or mapped:\n");
Marco Nelissenf09611f2015-02-13 14:12:42 -0800452 snprintf(buffer, SIZE, "/proc/%d/maps", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800453 FILE *f = fopen(buffer, "r");
454 if (f) {
455 while (!feof(f)) {
456 fgets(buffer, SIZE, f);
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700457 if (strstr(buffer, " /storage/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800458 strstr(buffer, " /system/sounds/") ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700459 strstr(buffer, " /data/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800460 strstr(buffer, " /system/media/")) {
461 result.append(" ");
462 result.append(buffer);
463 }
464 }
465 fclose(f);
466 } else {
467 result.append("couldn't open ");
468 result.append(buffer);
469 result.append("\n");
470 }
471
Marco Nelissenf09611f2015-02-13 14:12:42 -0800472 snprintf(buffer, SIZE, "/proc/%d/fd", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800473 DIR *d = opendir(buffer);
474 if (d) {
475 struct dirent *ent;
476 while((ent = readdir(d)) != NULL) {
477 if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
Marco Nelissenf09611f2015-02-13 14:12:42 -0800478 snprintf(buffer, SIZE, "/proc/%d/fd/%s", getpid(), ent->d_name);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800479 struct stat s;
480 if (lstat(buffer, &s) == 0) {
481 if ((s.st_mode & S_IFMT) == S_IFLNK) {
482 char linkto[256];
483 int len = readlink(buffer, linkto, sizeof(linkto));
484 if(len > 0) {
485 if(len > 255) {
486 linkto[252] = '.';
487 linkto[253] = '.';
488 linkto[254] = '.';
489 linkto[255] = 0;
490 } else {
491 linkto[len] = 0;
492 }
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700493 if (strstr(linkto, "/storage/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800494 strstr(linkto, "/system/sounds/") == linkto ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700495 strstr(linkto, "/data/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800496 strstr(linkto, "/system/media/") == linkto) {
497 result.append(" ");
498 result.append(buffer);
499 result.append(" -> ");
500 result.append(linkto);
501 result.append("\n");
502 }
503 }
504 } else {
505 result.append(" unexpected type for ");
506 result.append(buffer);
507 result.append("\n");
508 }
509 }
510 }
511 }
512 closedir(d);
513 } else {
514 result.append("couldn't open ");
515 result.append(buffer);
516 result.append("\n");
517 }
518
Marco Nelissenf09611f2015-02-13 14:12:42 -0800519 gLooperRoster.dump(fd, args);
520
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800521 bool dumpMem = false;
Andy Hung53541292016-04-13 16:48:51 -0700522 bool unreachableMemory = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800523 for (size_t i = 0; i < args.size(); i++) {
524 if (args[i] == String16("-m")) {
525 dumpMem = true;
Andy Hung53541292016-04-13 16:48:51 -0700526 } else if (args[i] == String16("--unreachable")) {
527 unreachableMemory = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800528 }
529 }
530 if (dumpMem) {
Andy Hung07b745e2016-05-23 16:21:07 -0700531 result.append("\nDumping memory:\n");
532 std::string s = dumpMemoryAddresses(100 /* limit */);
533 result.append(s.c_str(), s.size());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800534 }
Andy Hung53541292016-04-13 16:48:51 -0700535 if (unreachableMemory) {
536 result.append("\nDumping unreachable memory:\n");
537 // TODO - should limit be an argument parameter?
538 std::string s = GetUnreachableMemoryString(true /* contents */, 10000 /* limit */);
539 result.append(s.c_str(), s.size());
540 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800541 }
542 write(fd, result.string(), result.size());
543 return NO_ERROR;
544}
545
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -0700546void MediaPlayerService::removeClient(const wp<Client>& client)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800547{
548 Mutex::Autolock lock(mLock);
549 mClients.remove(client);
550}
551
Robert Shihee0a0e32016-08-16 16:50:54 -0700552bool MediaPlayerService::hasClient(wp<Client> client)
553{
554 Mutex::Autolock lock(mLock);
555 return mClients.indexOf(client) != NAME_NOT_FOUND;
556}
557
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700558MediaPlayerService::Client::Client(
559 const sp<MediaPlayerService>& service, pid_t pid,
560 int32_t connId, const sp<IMediaPlayerClient>& client,
Glenn Kastend848eb42016-03-08 13:42:11 -0800561 audio_session_t audioSessionId, uid_t uid)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800562{
Steve Block3856b092011-10-20 11:56:00 +0100563 ALOGV("Client(%d) constructor", connId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800564 mPid = pid;
565 mConnId = connId;
566 mService = service;
567 mClient = client;
568 mLoop = false;
569 mStatus = NO_INIT;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700570 mAudioSessionId = audioSessionId;
Andy Hung1afd0982016-11-08 16:13:44 -0800571 mUid = uid;
John Grossmanc795b642012-02-22 15:38:35 -0800572 mRetransmitEndpointValid = false;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700573 mAudioAttributes = NULL;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700574
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800575#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000576 ALOGD("create Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800577 mAntagonizer = new Antagonizer(notify, this);
578#endif
579}
580
581MediaPlayerService::Client::~Client()
582{
Steve Block3856b092011-10-20 11:56:00 +0100583 ALOGV("Client(%d) destructor pid = %d", mConnId, mPid);
Wei Jia502c2f42017-07-13 17:47:56 -0700584 {
585 Mutex::Autolock l(mLock);
586 mAudioOutput.clear();
587 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800588 wp<Client> client(this);
589 disconnect();
590 mService->removeClient(client);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700591 if (mAudioAttributes != NULL) {
592 free(mAudioAttributes);
593 }
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800594 clearDeathNotifiers();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800595}
596
597void MediaPlayerService::Client::disconnect()
598{
Steve Block3856b092011-10-20 11:56:00 +0100599 ALOGV("disconnect(%d) from pid %d", mConnId, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800600 // grab local reference and clear main reference to prevent future
601 // access to object
602 sp<MediaPlayerBase> p;
603 {
604 Mutex::Autolock l(mLock);
605 p = mPlayer;
beanzdcfefde2012-11-05 09:51:43 +0800606 mClient.clear();
Wei Jia502c2f42017-07-13 17:47:56 -0700607 mPlayer.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800608 }
Andreas Huber20111aa2009-07-14 16:56:47 -0700609
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800610 // clear the notification to prevent callbacks to dead client
611 // and reset the player. We assume the player will serialize
612 // access to itself if necessary.
613 if (p != 0) {
614 p->setNotifyCallback(0, 0);
615#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000616 ALOGD("kill Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800617 mAntagonizer->kill();
618#endif
619 p->reset();
620 }
621
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700622 disconnectNativeWindow();
623
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800624 IPCThreadState::self()->flushCommands();
625}
626
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800627sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
628{
629 // determine if we have the right player type
Wei Jia502c2f42017-07-13 17:47:56 -0700630 sp<MediaPlayerBase> p = getPlayer();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800631 if ((p != NULL) && (p->playerType() != playerType)) {
Steve Block3856b092011-10-20 11:56:00 +0100632 ALOGV("delete player");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800633 p.clear();
634 }
635 if (p == NULL) {
Ronghua Wu68845c12015-07-21 09:50:48 -0700636 p = MediaPlayerFactory::createPlayer(playerType, this, notify, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800637 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700638
Jason Simmonsdb29e522011-08-12 13:46:55 -0700639 if (p != NULL) {
Andy Hung1afd0982016-11-08 16:13:44 -0800640 p->setUID(mUid);
Jason Simmonsdb29e522011-08-12 13:46:55 -0700641 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700642
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800643 return p;
644}
645
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700646MediaPlayerService::Client::ServiceDeathNotifier::ServiceDeathNotifier(
647 const sp<IBinder>& service,
648 const sp<MediaPlayerBase>& listener,
649 int which) {
650 mService = service;
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800651 mOmx = nullptr;
652 mListener = listener;
653 mWhich = which;
654}
655
656MediaPlayerService::Client::ServiceDeathNotifier::ServiceDeathNotifier(
657 const sp<IOmx>& omx,
658 const sp<MediaPlayerBase>& listener,
659 int which) {
660 mService = nullptr;
661 mOmx = omx;
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700662 mListener = listener;
663 mWhich = which;
664}
665
666MediaPlayerService::Client::ServiceDeathNotifier::~ServiceDeathNotifier() {
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700667}
668
669void MediaPlayerService::Client::ServiceDeathNotifier::binderDied(const wp<IBinder>& /*who*/) {
670 sp<MediaPlayerBase> listener = mListener.promote();
671 if (listener != NULL) {
672 listener->sendEvent(MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED, mWhich);
673 } else {
674 ALOGW("listener for process %d death is gone", mWhich);
675 }
676}
677
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800678void MediaPlayerService::Client::ServiceDeathNotifier::serviceDied(
679 uint64_t /* cookie */,
680 const wp<::android::hidl::base::V1_0::IBase>& /* who */) {
681 sp<MediaPlayerBase> listener = mListener.promote();
682 if (listener != NULL) {
683 listener->sendEvent(MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED, mWhich);
684 } else {
685 ALOGW("listener for process %d death is gone", mWhich);
686 }
687}
688
689void MediaPlayerService::Client::ServiceDeathNotifier::unlinkToDeath() {
690 if (mService != nullptr) {
691 mService->unlinkToDeath(this);
692 mService = nullptr;
693 } else if (mOmx != nullptr) {
694 mOmx->unlinkToDeath(this);
695 mOmx = nullptr;
696 }
697}
698
699void MediaPlayerService::Client::clearDeathNotifiers() {
700 if (mExtractorDeathListener != nullptr) {
701 mExtractorDeathListener->unlinkToDeath();
702 mExtractorDeathListener = nullptr;
703 }
704 if (mCodecDeathListener != nullptr) {
705 mCodecDeathListener->unlinkToDeath();
706 mCodecDeathListener = nullptr;
707 }
708}
709
John Grossmanc795b642012-02-22 15:38:35 -0800710sp<MediaPlayerBase> MediaPlayerService::Client::setDataSource_pre(
711 player_type playerType)
712{
713 ALOGV("player type = %d", playerType);
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800714 clearDeathNotifiers();
John Grossmanc795b642012-02-22 15:38:35 -0800715
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 }
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700728 mExtractorDeathListener = new ServiceDeathNotifier(binder, p, MEDIAEXTRACTOR_PROCESS_DEATH);
729 binder->linkToDeath(mExtractorDeathListener);
730
Pawin Vongmasad4e9ca42017-03-29 17:24:56 -0700731 if (property_get_bool("persist.media.treble_omx", true)) {
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800732 // Treble IOmx
733 sp<IOmx> omx = IOmx::getService();
734 if (omx == nullptr) {
735 ALOGE("Treble IOmx not available");
736 return NULL;
737 }
738 mCodecDeathListener = new ServiceDeathNotifier(omx, p, MEDIACODEC_PROCESS_DEATH);
739 omx->linkToDeath(mCodecDeathListener, 0);
740 } else {
741 // Legacy IOMX
742 binder = sm->getService(String16("media.codec"));
743 if (binder == NULL) {
744 ALOGE("codec service not available");
745 return NULL;
746 }
747 mCodecDeathListener = new ServiceDeathNotifier(binder, p, MEDIACODEC_PROCESS_DEATH);
748 binder->linkToDeath(mCodecDeathListener);
Marco Nelissen1b5a7ee2016-09-30 13:54:30 -0700749 }
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700750
John Grossmanc795b642012-02-22 15:38:35 -0800751 if (!p->hardwareOutput()) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -0700752 Mutex::Autolock l(mLock);
Marco Nelissend457c972014-02-11 08:47:07 -0800753 mAudioOutput = new AudioOutput(mAudioSessionId, IPCThreadState::self()->getCallingUid(),
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700754 mPid, mAudioAttributes);
John Grossmanc795b642012-02-22 15:38:35 -0800755 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
756 }
757
758 return p;
759}
760
761void MediaPlayerService::Client::setDataSource_post(
762 const sp<MediaPlayerBase>& p,
763 status_t status)
764{
765 ALOGV(" setDataSource");
766 mStatus = status;
767 if (mStatus != OK) {
768 ALOGE(" error: %d", mStatus);
769 return;
770 }
771
772 // Set the re-transmission endpoint if one was chosen.
773 if (mRetransmitEndpointValid) {
774 mStatus = p->setRetransmitEndpoint(&mRetransmitEndpoint);
775 if (mStatus != NO_ERROR) {
776 ALOGE("setRetransmitEndpoint error: %d", mStatus);
777 }
778 }
779
780 if (mStatus == OK) {
Wei Jia502c2f42017-07-13 17:47:56 -0700781 Mutex::Autolock l(mLock);
John Grossmanc795b642012-02-22 15:38:35 -0800782 mPlayer = p;
783 }
784}
785
Andreas Huber2db84552010-01-28 11:19:57 -0800786status_t MediaPlayerService::Client::setDataSource(
Andreas Huber1b86fe02014-01-29 11:13:26 -0800787 const sp<IMediaHTTPService> &httpService,
788 const char *url,
789 const KeyedVector<String8, String8> *headers)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800790{
Steve Block3856b092011-10-20 11:56:00 +0100791 ALOGV("setDataSource(%s)", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800792 if (url == NULL)
793 return UNKNOWN_ERROR;
794
Dave Burked681bbb2011-08-30 14:39:17 +0100795 if ((strncmp(url, "http://", 7) == 0) ||
796 (strncmp(url, "https://", 8) == 0) ||
797 (strncmp(url, "rtsp://", 7) == 0)) {
798 if (!checkPermission("android.permission.INTERNET")) {
799 return PERMISSION_DENIED;
800 }
801 }
802
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800803 if (strncmp(url, "content://", 10) == 0) {
804 // get a filedescriptor for the content Uri and
805 // pass it to the setDataSource(fd) method
806
807 String16 url16(url);
808 int fd = android::openContentProviderFile(url16);
809 if (fd < 0)
810 {
Steve Block29357bc2012-01-06 19:20:56 +0000811 ALOGE("Couldn't open fd for %s", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800812 return UNKNOWN_ERROR;
813 }
814 setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
815 close(fd);
816 return mStatus;
817 } else {
John Grossman44a7e422012-06-21 17:29:24 -0700818 player_type playerType = MediaPlayerFactory::getPlayerType(this, url);
John Grossmanc795b642012-02-22 15:38:35 -0800819 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
820 if (p == NULL) {
821 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800822 }
823
Andreas Huber1b86fe02014-01-29 11:13:26 -0800824 setDataSource_post(p, p->setDataSource(httpService, url, headers));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800825 return mStatus;
826 }
827}
828
829status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
830{
Marco Nelissen83b0fd92015-09-16 13:48:07 -0700831 ALOGV("setDataSource fd=%d (%s), offset=%lld, length=%lld",
832 fd, nameForFd(fd).c_str(), (long long) offset, (long long) length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800833 struct stat sb;
834 int ret = fstat(fd, &sb);
835 if (ret != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000836 ALOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800837 return UNKNOWN_ERROR;
838 }
839
Andy Hung833b4752016-04-04 17:15:48 -0700840 ALOGV("st_dev = %llu", static_cast<unsigned long long>(sb.st_dev));
Steve Block3856b092011-10-20 11:56:00 +0100841 ALOGV("st_mode = %u", sb.st_mode);
Mark Salyzyn77342f72014-06-18 16:31:32 -0700842 ALOGV("st_uid = %lu", static_cast<unsigned long>(sb.st_uid));
843 ALOGV("st_gid = %lu", static_cast<unsigned long>(sb.st_gid));
Andy Hung833b4752016-04-04 17:15:48 -0700844 ALOGV("st_size = %llu", static_cast<unsigned long long>(sb.st_size));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800845
846 if (offset >= sb.st_size) {
Steve Block29357bc2012-01-06 19:20:56 +0000847 ALOGE("offset error");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800848 return UNKNOWN_ERROR;
849 }
850 if (offset + length > sb.st_size) {
851 length = sb.st_size - offset;
Andy Hung833b4752016-04-04 17:15:48 -0700852 ALOGV("calculated length = %lld", (long long)length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800853 }
854
John Grossman44a7e422012-06-21 17:29:24 -0700855 player_type playerType = MediaPlayerFactory::getPlayerType(this,
856 fd,
857 offset,
858 length);
John Grossmanc795b642012-02-22 15:38:35 -0800859 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
860 if (p == NULL) {
861 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800862 }
863
864 // now set data source
John Grossmanc795b642012-02-22 15:38:35 -0800865 setDataSource_post(p, p->setDataSource(fd, offset, length));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800866 return mStatus;
867}
868
Andreas Hubere2b10282010-11-23 11:41:34 -0800869status_t MediaPlayerService::Client::setDataSource(
870 const sp<IStreamSource> &source) {
871 // create the right type of player
John Grossman44a7e422012-06-21 17:29:24 -0700872 player_type playerType = MediaPlayerFactory::getPlayerType(this, source);
John Grossmanc795b642012-02-22 15:38:35 -0800873 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
Andreas Hubere2b10282010-11-23 11:41:34 -0800874 if (p == NULL) {
875 return NO_INIT;
876 }
877
Andreas Hubere2b10282010-11-23 11:41:34 -0800878 // now set data source
John Grossmanc795b642012-02-22 15:38:35 -0800879 setDataSource_post(p, p->setDataSource(source));
Andreas Hubere2b10282010-11-23 11:41:34 -0800880 return mStatus;
881}
882
Chris Watkins99f31602015-03-20 13:06:33 -0700883status_t MediaPlayerService::Client::setDataSource(
884 const sp<IDataSource> &source) {
885 sp<DataSource> dataSource = DataSource::CreateFromIDataSource(source);
886 player_type playerType = MediaPlayerFactory::getPlayerType(this, dataSource);
887 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
888 if (p == NULL) {
889 return NO_INIT;
890 }
891 // now set data source
892 setDataSource_post(p, p->setDataSource(dataSource));
893 return mStatus;
894}
895
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700896void MediaPlayerService::Client::disconnectNativeWindow() {
897 if (mConnectedWindow != NULL) {
Chong Zhang181fd9b2017-02-16 15:53:03 -0800898 status_t err = nativeWindowDisconnect(
899 mConnectedWindow.get(), "disconnectNativeWindow");
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700900
901 if (err != OK) {
Chong Zhang181fd9b2017-02-16 15:53:03 -0800902 ALOGW("nativeWindowDisconnect returned an error: %s (%d)",
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700903 strerror(-err), err);
904 }
905 }
906 mConnectedWindow.clear();
907}
908
Glenn Kasten11731182011-02-08 17:26:17 -0800909status_t MediaPlayerService::Client::setVideoSurfaceTexture(
Andy McFadden484566c2012-12-18 09:46:54 -0800910 const sp<IGraphicBufferProducer>& bufferProducer)
Glenn Kasten11731182011-02-08 17:26:17 -0800911{
Andy McFadden484566c2012-12-18 09:46:54 -0800912 ALOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, bufferProducer.get());
Glenn Kasten11731182011-02-08 17:26:17 -0800913 sp<MediaPlayerBase> p = getPlayer();
914 if (p == 0) return UNKNOWN_ERROR;
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700915
Marco Nelissenf8880202014-11-14 07:58:25 -0800916 sp<IBinder> binder(IInterface::asBinder(bufferProducer));
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700917 if (mConnectedWindowBinder == binder) {
918 return OK;
919 }
920
921 sp<ANativeWindow> anw;
Andy McFadden484566c2012-12-18 09:46:54 -0800922 if (bufferProducer != NULL) {
Marco Nelissenee08f7e2013-09-16 13:30:01 -0700923 anw = new Surface(bufferProducer, true /* controlledByApp */);
Chong Zhang181fd9b2017-02-16 15:53:03 -0800924 status_t err = nativeWindowConnect(anw.get(), "setVideoSurfaceTexture");
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700925
926 if (err != OK) {
Steve Block29357bc2012-01-06 19:20:56 +0000927 ALOGE("setVideoSurfaceTexture failed: %d", err);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700928 // Note that we must do the reset before disconnecting from the ANW.
929 // Otherwise queue/dequeue calls could be made on the disconnected
930 // ANW, which may result in errors.
931 reset();
932
933 disconnectNativeWindow();
934
935 return err;
936 }
937 }
938
Andy McFadden484566c2012-12-18 09:46:54 -0800939 // Note that we must set the player's new GraphicBufferProducer before
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700940 // disconnecting the old one. Otherwise queue/dequeue calls could be made
941 // on the disconnected ANW, which may result in errors.
Andy McFadden484566c2012-12-18 09:46:54 -0800942 status_t err = p->setVideoSurfaceTexture(bufferProducer);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700943
944 disconnectNativeWindow();
945
946 mConnectedWindow = anw;
947
948 if (err == OK) {
949 mConnectedWindowBinder = binder;
950 } else {
951 disconnectNativeWindow();
952 }
953
954 return err;
Glenn Kasten11731182011-02-08 17:26:17 -0800955}
956
Nicolas Catania1d187f12009-05-12 23:25:55 -0700957status_t MediaPlayerService::Client::invoke(const Parcel& request,
958 Parcel *reply)
959{
960 sp<MediaPlayerBase> p = getPlayer();
961 if (p == NULL) return UNKNOWN_ERROR;
962 return p->invoke(request, reply);
963}
964
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700965// This call doesn't need to access the native player.
966status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
967{
968 status_t status;
nikoa64c8c72009-07-20 15:07:26 -0700969 media::Metadata::Filter allow, drop;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700970
Nicolas Catania48290382009-07-10 13:53:06 -0700971 if (unmarshallFilter(filter, &allow, &status) &&
972 unmarshallFilter(filter, &drop, &status)) {
973 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700974
975 mMetadataAllow = allow;
976 mMetadataDrop = drop;
977 }
978 return status;
979}
980
Nicolas Catania48290382009-07-10 13:53:06 -0700981status_t MediaPlayerService::Client::getMetadata(
Mark Salyzyn77342f72014-06-18 16:31:32 -0700982 bool update_only, bool /*apply_filter*/, Parcel *reply)
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700983{
nikoa64c8c72009-07-20 15:07:26 -0700984 sp<MediaPlayerBase> player = getPlayer();
985 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania48290382009-07-10 13:53:06 -0700986
nikod608a812009-07-16 16:39:53 -0700987 status_t status;
988 // Placeholder for the return code, updated by the caller.
989 reply->writeInt32(-1);
990
nikoa64c8c72009-07-20 15:07:26 -0700991 media::Metadata::Filter ids;
Nicolas Catania48290382009-07-10 13:53:06 -0700992
993 // We don't block notifications while we fetch the data. We clear
994 // mMetadataUpdated first so we don't lose notifications happening
995 // during the rest of this call.
996 {
997 Mutex::Autolock lock(mLock);
998 if (update_only) {
nikod608a812009-07-16 16:39:53 -0700999 ids = mMetadataUpdated;
Nicolas Catania48290382009-07-10 13:53:06 -07001000 }
1001 mMetadataUpdated.clear();
1002 }
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001003
nikoa64c8c72009-07-20 15:07:26 -07001004 media::Metadata metadata(reply);
Nicolas Catania48290382009-07-10 13:53:06 -07001005
nikoa64c8c72009-07-20 15:07:26 -07001006 metadata.appendHeader();
1007 status = player->getMetadata(ids, reply);
nikod608a812009-07-16 16:39:53 -07001008
1009 if (status != OK) {
nikoa64c8c72009-07-20 15:07:26 -07001010 metadata.resetParcel();
Steve Block29357bc2012-01-06 19:20:56 +00001011 ALOGE("getMetadata failed %d", status);
nikod608a812009-07-16 16:39:53 -07001012 return status;
1013 }
1014
1015 // FIXME: Implement filtering on the result. Not critical since
1016 // filtering takes place on the update notifications already. This
1017 // would be when all the metadata are fetch and a filter is set.
1018
nikod608a812009-07-16 16:39:53 -07001019 // Everything is fine, update the metadata length.
nikoa64c8c72009-07-20 15:07:26 -07001020 metadata.updateLength();
nikod608a812009-07-16 16:39:53 -07001021 return OK;
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001022}
1023
Wei Jiad399e7e2016-10-26 15:49:11 -07001024status_t MediaPlayerService::Client::setBufferingSettings(
1025 const BufferingSettings& buffering)
1026{
Wei Jiadc6f3402017-01-09 15:04:18 -08001027 ALOGV("[%d] setBufferingSettings{%s}",
1028 mConnId, buffering.toString().string());
Wei Jiad399e7e2016-10-26 15:49:11 -07001029 sp<MediaPlayerBase> p = getPlayer();
1030 if (p == 0) return UNKNOWN_ERROR;
1031 return p->setBufferingSettings(buffering);
1032}
1033
1034status_t MediaPlayerService::Client::getDefaultBufferingSettings(
1035 BufferingSettings* buffering /* nonnull */)
1036{
1037 sp<MediaPlayerBase> p = getPlayer();
1038 // TODO: create mPlayer on demand.
1039 if (p == 0) return UNKNOWN_ERROR;
1040 status_t ret = p->getDefaultBufferingSettings(buffering);
1041 if (ret == NO_ERROR) {
Wei Jiadc6f3402017-01-09 15:04:18 -08001042 ALOGV("[%d] getDefaultBufferingSettings{%s}",
1043 mConnId, buffering->toString().string());
Wei Jiad399e7e2016-10-26 15:49:11 -07001044 } else {
1045 ALOGV("[%d] getDefaultBufferingSettings returned %d", mConnId, ret);
1046 }
1047 return ret;
1048}
1049
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001050status_t MediaPlayerService::Client::prepareAsync()
1051{
Steve Block3856b092011-10-20 11:56:00 +01001052 ALOGV("[%d] prepareAsync", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001053 sp<MediaPlayerBase> p = getPlayer();
1054 if (p == 0) return UNKNOWN_ERROR;
1055 status_t ret = p->prepareAsync();
1056#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +00001057 ALOGD("start Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001058 if (ret == NO_ERROR) mAntagonizer->start();
1059#endif
1060 return ret;
1061}
1062
1063status_t MediaPlayerService::Client::start()
1064{
Steve Block3856b092011-10-20 11:56:00 +01001065 ALOGV("[%d] start", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001066 sp<MediaPlayerBase> p = getPlayer();
1067 if (p == 0) return UNKNOWN_ERROR;
1068 p->setLooping(mLoop);
1069 return p->start();
1070}
1071
1072status_t MediaPlayerService::Client::stop()
1073{
Steve Block3856b092011-10-20 11:56:00 +01001074 ALOGV("[%d] stop", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001075 sp<MediaPlayerBase> p = getPlayer();
1076 if (p == 0) return UNKNOWN_ERROR;
1077 return p->stop();
1078}
1079
1080status_t MediaPlayerService::Client::pause()
1081{
Steve Block3856b092011-10-20 11:56:00 +01001082 ALOGV("[%d] pause", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001083 sp<MediaPlayerBase> p = getPlayer();
1084 if (p == 0) return UNKNOWN_ERROR;
1085 return p->pause();
1086}
1087
1088status_t MediaPlayerService::Client::isPlaying(bool* state)
1089{
1090 *state = false;
1091 sp<MediaPlayerBase> p = getPlayer();
1092 if (p == 0) return UNKNOWN_ERROR;
1093 *state = p->isPlaying();
Steve Block3856b092011-10-20 11:56:00 +01001094 ALOGV("[%d] isPlaying: %d", mConnId, *state);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001095 return NO_ERROR;
1096}
1097
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001098status_t MediaPlayerService::Client::setPlaybackSettings(const AudioPlaybackRate& rate)
Wei Jia98160162015-02-04 17:01:11 -08001099{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001100 ALOGV("[%d] setPlaybackSettings(%f, %f, %d, %d)",
1101 mConnId, rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Wei Jia98160162015-02-04 17:01:11 -08001102 sp<MediaPlayerBase> p = getPlayer();
1103 if (p == 0) return UNKNOWN_ERROR;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001104 return p->setPlaybackSettings(rate);
1105}
1106
1107status_t MediaPlayerService::Client::getPlaybackSettings(AudioPlaybackRate* rate /* nonnull */)
1108{
1109 sp<MediaPlayerBase> p = getPlayer();
1110 if (p == 0) return UNKNOWN_ERROR;
1111 status_t ret = p->getPlaybackSettings(rate);
1112 if (ret == NO_ERROR) {
1113 ALOGV("[%d] getPlaybackSettings(%f, %f, %d, %d)",
1114 mConnId, rate->mSpeed, rate->mPitch, rate->mFallbackMode, rate->mStretchMode);
1115 } else {
1116 ALOGV("[%d] getPlaybackSettings returned %d", mConnId, ret);
1117 }
1118 return ret;
1119}
1120
1121status_t MediaPlayerService::Client::setSyncSettings(
1122 const AVSyncSettings& sync, float videoFpsHint)
1123{
1124 ALOGV("[%d] setSyncSettings(%u, %u, %f, %f)",
1125 mConnId, sync.mSource, sync.mAudioAdjustMode, sync.mTolerance, videoFpsHint);
1126 sp<MediaPlayerBase> p = getPlayer();
1127 if (p == 0) return UNKNOWN_ERROR;
1128 return p->setSyncSettings(sync, videoFpsHint);
1129}
1130
1131status_t MediaPlayerService::Client::getSyncSettings(
1132 AVSyncSettings* sync /* nonnull */, float* videoFps /* nonnull */)
1133{
1134 sp<MediaPlayerBase> p = getPlayer();
1135 if (p == 0) return UNKNOWN_ERROR;
1136 status_t ret = p->getSyncSettings(sync, videoFps);
1137 if (ret == NO_ERROR) {
1138 ALOGV("[%d] getSyncSettings(%u, %u, %f, %f)",
1139 mConnId, sync->mSource, sync->mAudioAdjustMode, sync->mTolerance, *videoFps);
1140 } else {
1141 ALOGV("[%d] getSyncSettings returned %d", mConnId, ret);
1142 }
1143 return ret;
Wei Jia98160162015-02-04 17:01:11 -08001144}
1145
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001146status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
1147{
Steve Block3856b092011-10-20 11:56:00 +01001148 ALOGV("getCurrentPosition");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001149 sp<MediaPlayerBase> p = getPlayer();
1150 if (p == 0) return UNKNOWN_ERROR;
1151 status_t ret = p->getCurrentPosition(msec);
1152 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001153 ALOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001154 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001155 ALOGE("getCurrentPosition returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001156 }
1157 return ret;
1158}
1159
1160status_t MediaPlayerService::Client::getDuration(int *msec)
1161{
Steve Block3856b092011-10-20 11:56:00 +01001162 ALOGV("getDuration");
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->getDuration(msec);
1166 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001167 ALOGV("[%d] getDuration = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001168 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001169 ALOGE("getDuration returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001170 }
1171 return ret;
1172}
1173
Marco Nelissen6b74d672012-02-28 16:07:44 -08001174status_t MediaPlayerService::Client::setNextPlayer(const sp<IMediaPlayer>& player) {
1175 ALOGV("setNextPlayer");
1176 Mutex::Autolock l(mLock);
1177 sp<Client> c = static_cast<Client*>(player.get());
Wei Jia28284122016-08-30 13:49:06 -07001178 if (c != NULL && !mService->hasClient(c)) {
Robert Shihee0a0e32016-08-16 16:50:54 -07001179 return BAD_VALUE;
1180 }
1181
Marco Nelissen6b74d672012-02-28 16:07:44 -08001182 mNextClient = c;
John Grossman5f7e55e2012-08-24 14:47:25 -07001183
1184 if (c != NULL) {
1185 if (mAudioOutput != NULL) {
1186 mAudioOutput->setNextOutput(c->mAudioOutput);
1187 } else if ((mPlayer != NULL) && !mPlayer->hardwareOutput()) {
1188 ALOGE("no current audio output");
1189 }
1190
1191 if ((mPlayer != NULL) && (mNextClient->getPlayer() != NULL)) {
1192 mPlayer->setNextPlayer(mNextClient->getPlayer());
1193 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001194 }
John Grossman5f7e55e2012-08-24 14:47:25 -07001195
Marco Nelissen6b74d672012-02-28 16:07:44 -08001196 return OK;
1197}
1198
Andy Hung9fc8b5c2017-01-24 13:36:48 -08001199VolumeShaper::Status MediaPlayerService::Client::applyVolumeShaper(
1200 const sp<VolumeShaper::Configuration>& configuration,
1201 const sp<VolumeShaper::Operation>& operation) {
1202 // for hardware output, call player instead
1203 ALOGV("Client::applyVolumeShaper(%p)", this);
1204 sp<MediaPlayerBase> p = getPlayer();
1205 {
1206 Mutex::Autolock l(mLock);
1207 if (p != 0 && p->hardwareOutput()) {
1208 // TODO: investigate internal implementation
1209 return VolumeShaper::Status(INVALID_OPERATION);
1210 }
1211 if (mAudioOutput.get() != nullptr) {
1212 return mAudioOutput->applyVolumeShaper(configuration, operation);
1213 }
1214 }
1215 return VolumeShaper::Status(INVALID_OPERATION);
1216}
1217
1218sp<VolumeShaper::State> MediaPlayerService::Client::getVolumeShaperState(int id) {
1219 // for hardware output, call player instead
1220 ALOGV("Client::getVolumeShaperState(%p)", this);
1221 sp<MediaPlayerBase> p = getPlayer();
1222 {
1223 Mutex::Autolock l(mLock);
1224 if (p != 0 && p->hardwareOutput()) {
1225 // TODO: investigate internal implementation.
1226 return nullptr;
1227 }
1228 if (mAudioOutput.get() != nullptr) {
1229 return mAudioOutput->getVolumeShaperState(id);
1230 }
1231 }
1232 return nullptr;
1233}
1234
Wei Jiac5de0912016-11-18 10:22:14 -08001235status_t MediaPlayerService::Client::seekTo(int msec, MediaPlayerSeekMode mode)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001236{
Wei Jiac5de0912016-11-18 10:22:14 -08001237 ALOGV("[%d] seekTo(%d, %d)", mConnId, msec, mode);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001238 sp<MediaPlayerBase> p = getPlayer();
1239 if (p == 0) return UNKNOWN_ERROR;
Wei Jiac5de0912016-11-18 10:22:14 -08001240 return p->seekTo(msec, mode);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001241}
1242
1243status_t MediaPlayerService::Client::reset()
1244{
Steve Block3856b092011-10-20 11:56:00 +01001245 ALOGV("[%d] reset", mConnId);
John Grossmanc795b642012-02-22 15:38:35 -08001246 mRetransmitEndpointValid = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001247 sp<MediaPlayerBase> p = getPlayer();
1248 if (p == 0) return UNKNOWN_ERROR;
1249 return p->reset();
1250}
1251
Wei Jia52c28512017-09-13 18:17:51 -07001252status_t MediaPlayerService::Client::notifyAt(int64_t mediaTimeUs)
1253{
1254 ALOGV("[%d] notifyAt(%lld)", mConnId, (long long)mediaTimeUs);
1255 sp<MediaPlayerBase> p = getPlayer();
1256 if (p == 0) return UNKNOWN_ERROR;
1257 return p->notifyAt(mediaTimeUs);
1258}
1259
Glenn Kastenfff6d712012-01-12 16:38:12 -08001260status_t MediaPlayerService::Client::setAudioStreamType(audio_stream_type_t type)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001261{
Steve Block3856b092011-10-20 11:56:00 +01001262 ALOGV("[%d] setAudioStreamType(%d)", mConnId, type);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001263 // TODO: for hardware output, call player instead
1264 Mutex::Autolock l(mLock);
1265 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1266 return NO_ERROR;
1267}
1268
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001269status_t MediaPlayerService::Client::setAudioAttributes_l(const Parcel &parcel)
1270{
1271 if (mAudioAttributes != NULL) { free(mAudioAttributes); }
1272 mAudioAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001273 if (mAudioAttributes == NULL) {
1274 return NO_MEMORY;
1275 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001276 unmarshallAudioAttributes(parcel, mAudioAttributes);
1277
1278 ALOGV("setAudioAttributes_l() usage=%d content=%d flags=0x%x tags=%s",
1279 mAudioAttributes->usage, mAudioAttributes->content_type, mAudioAttributes->flags,
1280 mAudioAttributes->tags);
1281
1282 if (mAudioOutput != 0) {
1283 mAudioOutput->setAudioAttributes(mAudioAttributes);
1284 }
1285 return NO_ERROR;
1286}
1287
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001288status_t MediaPlayerService::Client::setLooping(int loop)
1289{
Steve Block3856b092011-10-20 11:56:00 +01001290 ALOGV("[%d] setLooping(%d)", mConnId, loop);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001291 mLoop = loop;
1292 sp<MediaPlayerBase> p = getPlayer();
1293 if (p != 0) return p->setLooping(loop);
1294 return NO_ERROR;
1295}
1296
1297status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1298{
Steve Block3856b092011-10-20 11:56:00 +01001299 ALOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
John Grossman761defc2012-02-09 15:09:05 -08001300
1301 // for hardware output, call player instead
1302 sp<MediaPlayerBase> p = getPlayer();
1303 {
1304 Mutex::Autolock l(mLock);
1305 if (p != 0 && p->hardwareOutput()) {
1306 MediaPlayerHWInterface* hwp =
1307 reinterpret_cast<MediaPlayerHWInterface*>(p.get());
1308 return hwp->setVolume(leftVolume, rightVolume);
1309 } else {
1310 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1311 return NO_ERROR;
1312 }
1313 }
1314
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001315 return NO_ERROR;
1316}
1317
Eric Laurent2beeb502010-07-16 07:43:46 -07001318status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1319{
Steve Block3856b092011-10-20 11:56:00 +01001320 ALOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
Eric Laurent2beeb502010-07-16 07:43:46 -07001321 Mutex::Autolock l(mLock);
1322 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1323 return NO_ERROR;
1324}
1325
1326status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1327{
Steve Block3856b092011-10-20 11:56:00 +01001328 ALOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
Eric Laurent2beeb502010-07-16 07:43:46 -07001329 Mutex::Autolock l(mLock);
1330 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1331 return NO_ERROR;
1332}
Nicolas Catania48290382009-07-10 13:53:06 -07001333
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001334status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
Steve Block3856b092011-10-20 11:56:00 +01001335 ALOGV("[%d] setParameter(%d)", mConnId, key);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001336 switch (key) {
1337 case KEY_PARAMETER_AUDIO_ATTRIBUTES:
1338 {
1339 Mutex::Autolock l(mLock);
1340 return setAudioAttributes_l(request);
1341 }
1342 default:
1343 sp<MediaPlayerBase> p = getPlayer();
1344 if (p == 0) { return UNKNOWN_ERROR; }
1345 return p->setParameter(key, request);
1346 }
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001347}
1348
1349status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
Steve Block3856b092011-10-20 11:56:00 +01001350 ALOGV("[%d] getParameter(%d)", mConnId, key);
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001351 sp<MediaPlayerBase> p = getPlayer();
1352 if (p == 0) return UNKNOWN_ERROR;
1353 return p->getParameter(key, reply);
1354}
1355
John Grossmanc795b642012-02-22 15:38:35 -08001356status_t MediaPlayerService::Client::setRetransmitEndpoint(
1357 const struct sockaddr_in* endpoint) {
1358
1359 if (NULL != endpoint) {
1360 uint32_t a = ntohl(endpoint->sin_addr.s_addr);
1361 uint16_t p = ntohs(endpoint->sin_port);
1362 ALOGV("[%d] setRetransmitEndpoint(%u.%u.%u.%u:%hu)", mConnId,
1363 (a >> 24), (a >> 16) & 0xFF, (a >> 8) & 0xFF, (a & 0xFF), p);
1364 } else {
1365 ALOGV("[%d] setRetransmitEndpoint = <none>", mConnId);
1366 }
1367
1368 sp<MediaPlayerBase> p = getPlayer();
1369
1370 // Right now, the only valid time to set a retransmit endpoint is before
1371 // player selection has been made (since the presence or absence of a
1372 // retransmit endpoint is going to determine which player is selected during
1373 // setDataSource).
1374 if (p != 0) return INVALID_OPERATION;
1375
1376 if (NULL != endpoint) {
1377 mRetransmitEndpoint = *endpoint;
1378 mRetransmitEndpointValid = true;
1379 } else {
1380 mRetransmitEndpointValid = false;
1381 }
1382
1383 return NO_ERROR;
1384}
1385
John Grossman44a7e422012-06-21 17:29:24 -07001386status_t MediaPlayerService::Client::getRetransmitEndpoint(
1387 struct sockaddr_in* endpoint)
1388{
1389 if (NULL == endpoint)
1390 return BAD_VALUE;
1391
1392 sp<MediaPlayerBase> p = getPlayer();
1393
1394 if (p != NULL)
1395 return p->getRetransmitEndpoint(endpoint);
1396
1397 if (!mRetransmitEndpointValid)
1398 return NO_INIT;
1399
1400 *endpoint = mRetransmitEndpoint;
1401
1402 return NO_ERROR;
1403}
1404
Gloria Wangb483c472011-04-11 17:23:27 -07001405void MediaPlayerService::Client::notify(
1406 void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001407{
1408 Client* client = static_cast<Client*>(cookie);
James Dongb8a98252012-08-26 16:13:03 -07001409 if (client == NULL) {
1410 return;
1411 }
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001412
James Dongb8a98252012-08-26 16:13:03 -07001413 sp<IMediaPlayerClient> c;
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001414 sp<Client> nextClient;
1415 status_t errStartNext = NO_ERROR;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001416 {
1417 Mutex::Autolock l(client->mLock);
James Dongb8a98252012-08-26 16:13:03 -07001418 c = client->mClient;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001419 if (msg == MEDIA_PLAYBACK_COMPLETE && client->mNextClient != NULL) {
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001420 nextClient = client->mNextClient;
1421
John Grossmancb0b7552012-08-23 17:47:31 -07001422 if (client->mAudioOutput != NULL)
1423 client->mAudioOutput->switchToNextOutput();
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001424
1425 errStartNext = nextClient->start();
1426 }
1427 }
1428
1429 if (nextClient != NULL) {
1430 sp<IMediaPlayerClient> nc;
1431 {
1432 Mutex::Autolock l(nextClient->mLock);
1433 nc = nextClient->mClient;
1434 }
1435 if (nc != NULL) {
1436 if (errStartNext == NO_ERROR) {
1437 nc->notify(MEDIA_INFO, MEDIA_INFO_STARTED_AS_NEXT, 0, obj);
1438 } else {
1439 nc->notify(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN , 0, obj);
1440 ALOGE("gapless:start playback for next track failed, err(%d)", errStartNext);
Wei Jia2afac0c2016-01-07 12:13:07 -08001441 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001442 }
1443 }
1444
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001445 if (MEDIA_INFO == msg &&
Nicolas Catania48290382009-07-10 13:53:06 -07001446 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikoa64c8c72009-07-20 15:07:26 -07001447 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania48290382009-07-10 13:53:06 -07001448
1449 if(client->shouldDropMetadata(metadata_type)) {
1450 return;
1451 }
1452
1453 // Update the list of metadata that have changed. getMetadata
1454 // also access mMetadataUpdated and clears it.
1455 client->addNewMetadataUpdate(metadata_type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001456 }
James Dongb8a98252012-08-26 16:13:03 -07001457
1458 if (c != NULL) {
1459 ALOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
1460 c->notify(msg, ext1, ext2, obj);
1461 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001462}
1463
Nicolas Catania48290382009-07-10 13:53:06 -07001464
nikoa64c8c72009-07-20 15:07:26 -07001465bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001466{
Nicolas Catania48290382009-07-10 13:53:06 -07001467 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001468
Nicolas Catania48290382009-07-10 13:53:06 -07001469 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001470 return true;
1471 }
1472
Nicolas Catania48290382009-07-10 13:53:06 -07001473 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001474 return false;
Nicolas Catania48290382009-07-10 13:53:06 -07001475 } else {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001476 return true;
1477 }
1478}
1479
Nicolas Catania48290382009-07-10 13:53:06 -07001480
nikoa64c8c72009-07-20 15:07:26 -07001481void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania48290382009-07-10 13:53:06 -07001482 Mutex::Autolock lock(mLock);
1483 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1484 mMetadataUpdated.add(metadata_type);
1485 }
1486}
1487
Hassan Shojaniacefac142017-02-06 21:02:02 -08001488// Modular DRM
1489status_t MediaPlayerService::Client::prepareDrm(const uint8_t uuid[16],
1490 const Vector<uint8_t>& drmSessionId)
1491{
1492 ALOGV("[%d] prepareDrm", mConnId);
1493 sp<MediaPlayerBase> p = getPlayer();
1494 if (p == 0) return UNKNOWN_ERROR;
1495
1496 status_t ret = p->prepareDrm(uuid, drmSessionId);
1497 ALOGV("prepareDrm ret: %d", ret);
1498
1499 return ret;
1500}
1501
1502status_t MediaPlayerService::Client::releaseDrm()
1503{
1504 ALOGV("[%d] releaseDrm", mConnId);
1505 sp<MediaPlayerBase> p = getPlayer();
1506 if (p == 0) return UNKNOWN_ERROR;
1507
1508 status_t ret = p->releaseDrm();
1509 ALOGV("releaseDrm ret: %d", ret);
1510
1511 return ret;
1512}
1513
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001514#if CALLBACK_ANTAGONIZER
1515const int Antagonizer::interval = 10000; // 10 msecs
1516
1517Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1518 mExit(false), mActive(false), mClient(client), mCb(cb)
1519{
1520 createThread(callbackThread, this);
1521}
1522
1523void Antagonizer::kill()
1524{
1525 Mutex::Autolock _l(mLock);
1526 mActive = false;
1527 mExit = true;
1528 mCondition.wait(mLock);
1529}
1530
1531int Antagonizer::callbackThread(void* user)
1532{
Steve Blockb8a80522011-12-20 16:23:08 +00001533 ALOGD("Antagonizer started");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001534 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1535 while (!p->mExit) {
1536 if (p->mActive) {
Steve Block3856b092011-10-20 11:56:00 +01001537 ALOGV("send event");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001538 p->mCb(p->mClient, 0, 0, 0);
1539 }
1540 usleep(interval);
1541 }
1542 Mutex::Autolock _l(p->mLock);
1543 p->mCondition.signal();
Steve Blockb8a80522011-12-20 16:23:08 +00001544 ALOGD("Antagonizer stopped");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001545 return 0;
1546}
1547#endif
1548
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001549#undef LOG_TAG
1550#define LOG_TAG "AudioSink"
Andy Hung1afd0982016-11-08 16:13:44 -08001551MediaPlayerService::AudioOutput::AudioOutput(audio_session_t sessionId, uid_t uid, int pid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001552 const audio_attributes_t* attr)
Andreas Huber20111aa2009-07-14 16:56:47 -07001553 : mCallback(NULL),
Eric Laurenta514bdb2010-06-21 09:27:30 -07001554 mCallbackCookie(NULL),
Marco Nelissen6b74d672012-02-28 16:07:44 -08001555 mCallbackData(NULL),
Andy Hungd1c74342015-07-07 16:54:23 -07001556 mStreamType(AUDIO_STREAM_MUSIC),
Andy Hungd1c74342015-07-07 16:54:23 -07001557 mLeftVolume(1.0),
1558 mRightVolume(1.0),
1559 mPlaybackRate(AUDIO_PLAYBACK_RATE_DEFAULT),
1560 mSampleRateHz(0),
1561 mMsecsPerFrame(0),
1562 mFrameSize(0),
Eric Laurent1948eb32012-04-13 16:50:19 -07001563 mSessionId(sessionId),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001564 mUid(uid),
Marco Nelissend457c972014-02-11 08:47:07 -08001565 mPid(pid),
Andy Hungd1c74342015-07-07 16:54:23 -07001566 mSendLevel(0.0),
1567 mAuxEffectId(0),
Andy Hung4ef88d72017-02-21 19:47:53 -08001568 mFlags(AUDIO_OUTPUT_FLAG_NONE),
Ivan Lozano8cf3a072017-08-09 09:01:33 -07001569 mVolumeHandler(new media::VolumeHandler())
Andy Hungd1c74342015-07-07 16:54:23 -07001570{
Steve Block3856b092011-10-20 11:56:00 +01001571 ALOGV("AudioOutput(%d)", sessionId);
Eric Laurent43562692015-07-15 16:49:07 -07001572 if (attr != NULL) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001573 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1574 if (mAttributes != NULL) {
1575 memcpy(mAttributes, attr, sizeof(audio_attributes_t));
1576 mStreamType = audio_attributes_to_stream_type(attr);
1577 }
1578 } else {
1579 mAttributes = NULL;
Eric Laurent43562692015-07-15 16:49:07 -07001580 }
1581
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001582 setMinBufferCount();
1583}
1584
1585MediaPlayerService::AudioOutput::~AudioOutput()
1586{
1587 close();
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001588 free(mAttributes);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001589 delete mCallbackData;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001590}
1591
Andy Hungd1c74342015-07-07 16:54:23 -07001592//static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001593void MediaPlayerService::AudioOutput::setMinBufferCount()
1594{
1595 char value[PROPERTY_VALUE_MAX];
1596 if (property_get("ro.kernel.qemu", value, 0)) {
1597 mIsOnEmulator = true;
1598 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1599 }
1600}
1601
Andy Hungd1c74342015-07-07 16:54:23 -07001602// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001603bool MediaPlayerService::AudioOutput::isOnEmulator()
1604{
Andy Hungd1c74342015-07-07 16:54:23 -07001605 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001606 return mIsOnEmulator;
1607}
1608
Andy Hungd1c74342015-07-07 16:54:23 -07001609// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001610int MediaPlayerService::AudioOutput::getMinBufferCount()
1611{
Andy Hungd1c74342015-07-07 16:54:23 -07001612 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001613 return mMinBufferCount;
1614}
1615
1616ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1617{
Andy Hungd1c74342015-07-07 16:54:23 -07001618 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001619 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001620 return mTrack->frameCount() * mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001621}
1622
1623ssize_t MediaPlayerService::AudioOutput::frameCount() const
1624{
Andy Hungd1c74342015-07-07 16:54:23 -07001625 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001626 if (mTrack == 0) return NO_INIT;
1627 return mTrack->frameCount();
1628}
1629
1630ssize_t MediaPlayerService::AudioOutput::channelCount() const
1631{
Andy Hungd1c74342015-07-07 16:54:23 -07001632 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001633 if (mTrack == 0) return NO_INIT;
1634 return mTrack->channelCount();
1635}
1636
1637ssize_t MediaPlayerService::AudioOutput::frameSize() const
1638{
Andy Hungd1c74342015-07-07 16:54:23 -07001639 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001640 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001641 return mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001642}
1643
1644uint32_t MediaPlayerService::AudioOutput::latency () const
1645{
Andy Hungd1c74342015-07-07 16:54:23 -07001646 Mutex::Autolock lock(mLock);
Eric Laurentdb354e52012-03-05 17:27:11 -08001647 if (mTrack == 0) return 0;
1648 return mTrack->latency();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001649}
1650
1651float MediaPlayerService::AudioOutput::msecsPerFrame() const
1652{
Andy Hungd1c74342015-07-07 16:54:23 -07001653 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001654 return mMsecsPerFrame;
1655}
1656
Marco Nelissen4110c102012-03-29 09:31:28 -07001657status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position) const
Eric Laurent342e9cf2010-01-19 17:37:09 -08001658{
Andy Hungd1c74342015-07-07 16:54:23 -07001659 Mutex::Autolock lock(mLock);
Eric Laurent342e9cf2010-01-19 17:37:09 -08001660 if (mTrack == 0) return NO_INIT;
1661 return mTrack->getPosition(position);
1662}
1663
Lajos Molnar06ad1522014-08-28 07:27:44 -07001664status_t MediaPlayerService::AudioOutput::getTimestamp(AudioTimestamp &ts) const
1665{
Andy Hungd1c74342015-07-07 16:54:23 -07001666 Mutex::Autolock lock(mLock);
Lajos Molnar06ad1522014-08-28 07:27:44 -07001667 if (mTrack == 0) return NO_INIT;
1668 return mTrack->getTimestamp(ts);
1669}
1670
Wei Jiac4ac8172015-10-21 10:35:48 -07001671// TODO: Remove unnecessary calls to getPlayedOutDurationUs()
1672// as it acquires locks and may query the audio driver.
1673//
1674// Some calls could conceivably retrieve extrapolated data instead of
1675// accessing getTimestamp() or getPosition() every time a data buffer with
1676// a media time is received.
1677//
1678// Calculate duration of played samples if played at normal rate (i.e., 1.0).
1679int64_t MediaPlayerService::AudioOutput::getPlayedOutDurationUs(int64_t nowUs) const
1680{
1681 Mutex::Autolock lock(mLock);
1682 if (mTrack == 0 || mSampleRateHz == 0) {
Wei Jia213f4902015-10-22 08:55:25 -07001683 return 0;
Wei Jiac4ac8172015-10-21 10:35:48 -07001684 }
1685
1686 uint32_t numFramesPlayed;
Andy Hung5d313802016-10-10 15:09:39 -07001687 int64_t numFramesPlayedAtUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001688 AudioTimestamp ts;
Wei Jiac4ac8172015-10-21 10:35:48 -07001689
1690 status_t res = mTrack->getTimestamp(ts);
1691 if (res == OK) { // case 1: mixing audio tracks and offloaded tracks.
1692 numFramesPlayed = ts.mPosition;
Andy Hung5d313802016-10-10 15:09:39 -07001693 numFramesPlayedAtUs = ts.mTime.tv_sec * 1000000LL + ts.mTime.tv_nsec / 1000;
1694 //ALOGD("getTimestamp: OK %d %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001695 } else if (res == WOULD_BLOCK) { // case 2: transitory state on start of a new track
1696 numFramesPlayed = 0;
Andy Hung5d313802016-10-10 15:09:39 -07001697 numFramesPlayedAtUs = nowUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001698 //ALOGD("getTimestamp: WOULD_BLOCK %d %lld",
Andy Hung5d313802016-10-10 15:09:39 -07001699 // numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001700 } else { // case 3: transitory at new track or audio fast tracks.
1701 res = mTrack->getPosition(&numFramesPlayed);
1702 CHECK_EQ(res, (status_t)OK);
Andy Hung5d313802016-10-10 15:09:39 -07001703 numFramesPlayedAtUs = nowUs;
1704 numFramesPlayedAtUs += 1000LL * mTrack->latency() / 2; /* XXX */
1705 //ALOGD("getPosition: %u %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001706 }
1707
1708 // CHECK_EQ(numFramesPlayed & (1 << 31), 0); // can't be negative until 12.4 hrs, test
1709 // TODO: remove the (int32_t) casting below as it may overflow at 12.4 hours.
1710 int64_t durationUs = (int64_t)((int32_t)numFramesPlayed * 1000000LL / mSampleRateHz)
Andy Hung5d313802016-10-10 15:09:39 -07001711 + nowUs - numFramesPlayedAtUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001712 if (durationUs < 0) {
1713 // Occurs when numFramesPlayed position is very small and the following:
1714 // (1) In case 1, the time nowUs is computed before getTimestamp() is called and
Andy Hung5d313802016-10-10 15:09:39 -07001715 // numFramesPlayedAtUs is greater than nowUs by time more than numFramesPlayed.
Wei Jiac4ac8172015-10-21 10:35:48 -07001716 // (2) In case 3, using getPosition and adding mAudioSink->latency() to
Andy Hung5d313802016-10-10 15:09:39 -07001717 // numFramesPlayedAtUs, by a time amount greater than numFramesPlayed.
Wei Jiac4ac8172015-10-21 10:35:48 -07001718 //
1719 // Both of these are transitory conditions.
1720 ALOGV("getPlayedOutDurationUs: negative duration %lld set to zero", (long long)durationUs);
1721 durationUs = 0;
1722 }
1723 ALOGV("getPlayedOutDurationUs(%lld) nowUs(%lld) frames(%u) framesAt(%lld)",
Andy Hung5d313802016-10-10 15:09:39 -07001724 (long long)durationUs, (long long)nowUs,
1725 numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001726 return durationUs;
1727}
1728
Marco Nelissen4110c102012-03-29 09:31:28 -07001729status_t MediaPlayerService::AudioOutput::getFramesWritten(uint32_t *frameswritten) const
1730{
Andy Hungd1c74342015-07-07 16:54:23 -07001731 Mutex::Autolock lock(mLock);
Marco Nelissen4110c102012-03-29 09:31:28 -07001732 if (mTrack == 0) return NO_INIT;
Andy Hung2f6e73d2016-04-08 12:12:58 -07001733 ExtendedTimestamp ets;
1734 status_t status = mTrack->getTimestamp(&ets);
1735 if (status == OK || status == WOULD_BLOCK) {
1736 *frameswritten = (uint32_t)ets.mPosition[ExtendedTimestamp::LOCATION_CLIENT];
1737 }
1738 return status;
Marco Nelissen4110c102012-03-29 09:31:28 -07001739}
1740
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001741status_t MediaPlayerService::AudioOutput::setParameters(const String8& keyValuePairs)
1742{
Andy Hungd1c74342015-07-07 16:54:23 -07001743 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001744 if (mTrack == 0) return NO_INIT;
1745 return mTrack->setParameters(keyValuePairs);
1746}
1747
1748String8 MediaPlayerService::AudioOutput::getParameters(const String8& keys)
1749{
Andy Hungd1c74342015-07-07 16:54:23 -07001750 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001751 if (mTrack == 0) return String8::empty();
1752 return mTrack->getParameters(keys);
1753}
1754
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001755void MediaPlayerService::AudioOutput::setAudioAttributes(const audio_attributes_t * attributes) {
Andy Hungd1c74342015-07-07 16:54:23 -07001756 Mutex::Autolock lock(mLock);
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001757 if (attributes == NULL) {
1758 free(mAttributes);
1759 mAttributes = NULL;
1760 } else {
1761 if (mAttributes == NULL) {
1762 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1763 }
1764 memcpy(mAttributes, attributes, sizeof(audio_attributes_t));
Eric Laurent43562692015-07-15 16:49:07 -07001765 mStreamType = audio_attributes_to_stream_type(attributes);
1766 }
1767}
1768
1769void MediaPlayerService::AudioOutput::setAudioStreamType(audio_stream_type_t streamType)
1770{
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001771 Mutex::Autolock lock(mLock);
Eric Laurent43562692015-07-15 16:49:07 -07001772 // do not allow direct stream type modification if attributes have been set
1773 if (mAttributes == NULL) {
1774 mStreamType = streamType;
1775 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001776}
1777
Andy Hungd1c74342015-07-07 16:54:23 -07001778void MediaPlayerService::AudioOutput::deleteRecycledTrack_l()
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001779{
Andy Hungd1c74342015-07-07 16:54:23 -07001780 ALOGV("deleteRecycledTrack_l");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001781 if (mRecycledTrack != 0) {
1782
1783 if (mCallbackData != NULL) {
1784 mCallbackData->setOutput(NULL);
1785 mCallbackData->endTrackSwitch();
1786 }
1787
1788 if ((mRecycledTrack->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) {
Andy Hunge13f8a62016-03-30 14:20:42 -07001789 int32_t msec = 0;
1790 if (!mRecycledTrack->stopped()) { // check if active
1791 (void)mRecycledTrack->pendingDuration(&msec);
1792 }
1793 mRecycledTrack->stop(); // ensure full data drain
1794 ALOGD("deleting recycled track, waiting for data drain (%d msec)", msec);
1795 if (msec > 0) {
1796 static const int32_t WAIT_LIMIT_MS = 3000;
1797 if (msec > WAIT_LIMIT_MS) {
1798 msec = WAIT_LIMIT_MS;
1799 }
1800 usleep(msec * 1000LL);
1801 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001802 }
1803 // An offloaded track isn't flushed because the STREAM_END is reported
1804 // slightly prematurely to allow time for the gapless track switch
1805 // but this means that if we decide not to recycle the track there
1806 // could be a small amount of residual data still playing. We leave
1807 // AudioFlinger to drain the track.
1808
1809 mRecycledTrack.clear();
Andy Hungd1c74342015-07-07 16:54:23 -07001810 close_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001811 delete mCallbackData;
1812 mCallbackData = NULL;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001813 }
1814}
1815
Andy Hungd1c74342015-07-07 16:54:23 -07001816void MediaPlayerService::AudioOutput::close_l()
1817{
1818 mTrack.clear();
1819}
1820
Andreas Huber20111aa2009-07-14 16:56:47 -07001821status_t MediaPlayerService::AudioOutput::open(
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001822 uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
1823 audio_format_t format, int bufferCount,
Eric Laurent1948eb32012-04-13 16:50:19 -07001824 AudioCallback cb, void *cookie,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001825 audio_output_flags_t flags,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001826 const audio_offload_info_t *offloadInfo,
Andy Hung179652e2015-05-31 22:49:46 -07001827 bool doNotReconnect,
1828 uint32_t suggestedFrameCount)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001829{
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001830 ALOGV("open(%u, %d, 0x%x, 0x%x, %d, %d 0x%x)", sampleRate, channelCount, channelMask,
1831 format, bufferCount, mSessionId, flags);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001832
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001833 // offloading is only supported in callback mode for now.
1834 // offloadInfo must be present if offload flag is set
1835 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) &&
1836 ((cb == NULL) || (offloadInfo == NULL))) {
1837 return BAD_VALUE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001838 }
1839
Andy Hung179652e2015-05-31 22:49:46 -07001840 // compute frame count for the AudioTrack internal buffer
1841 size_t frameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001842 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1843 frameCount = 0; // AudioTrack will get frame count from AudioFlinger
1844 } else {
Andy Hung179652e2015-05-31 22:49:46 -07001845 // try to estimate the buffer processing fetch size from AudioFlinger.
1846 // framesPerBuffer is approximate and generally correct, except when it's not :-).
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001847 uint32_t afSampleRate;
1848 size_t afFrameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001849 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1850 return NO_INIT;
1851 }
1852 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1853 return NO_INIT;
1854 }
Andy Hung179652e2015-05-31 22:49:46 -07001855 const size_t framesPerBuffer =
1856 (unsigned long long)sampleRate * afFrameCount / afSampleRate;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001857
Andy Hung179652e2015-05-31 22:49:46 -07001858 if (bufferCount == 0) {
1859 // use suggestedFrameCount
1860 bufferCount = (suggestedFrameCount + framesPerBuffer - 1) / framesPerBuffer;
1861 }
1862 // Check argument bufferCount against the mininum buffer count
1863 if (bufferCount != 0 && bufferCount < mMinBufferCount) {
1864 ALOGV("bufferCount (%d) increased to %d", bufferCount, mMinBufferCount);
1865 bufferCount = mMinBufferCount;
1866 }
1867 // if frameCount is 0, then AudioTrack will get frame count from AudioFlinger
1868 // which will be the minimum size permitted.
1869 frameCount = bufferCount * framesPerBuffer;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001870 }
Andreas Huber20111aa2009-07-14 16:56:47 -07001871
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001872 if (channelMask == CHANNEL_MASK_USE_CHANNEL_ORDER) {
Glenn Kastenab334fd2012-03-14 12:56:06 -07001873 channelMask = audio_channel_out_mask_from_count(channelCount);
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001874 if (0 == channelMask) {
1875 ALOGE("open() error, can\'t derive mask for %d audio channels", channelCount);
1876 return NO_INIT;
1877 }
1878 }
Eric Laurent1948eb32012-04-13 16:50:19 -07001879
Andy Hungd1c74342015-07-07 16:54:23 -07001880 Mutex::Autolock lock(mLock);
Andy Hung179652e2015-05-31 22:49:46 -07001881 mCallback = cb;
1882 mCallbackCookie = cookie;
1883
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001884 // Check whether we can recycle the track
1885 bool reuse = false;
1886 bool bothOffloaded = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001887
Glenn Kasten2799d742013-05-30 14:33:29 -07001888 if (mRecycledTrack != 0) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001889 // check whether we are switching between two offloaded tracks
1890 bothOffloaded = (flags & mRecycledTrack->getFlags()
1891 & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0;
Marco Nelissen67295b52012-06-11 14:52:53 -07001892
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001893 // check if the existing track can be reused as-is, or if a new track needs to be created.
1894 reuse = true;
1895
Marco Nelissen67295b52012-06-11 14:52:53 -07001896 if ((mCallbackData == NULL && mCallback != NULL) ||
1897 (mCallbackData != NULL && mCallback == NULL)) {
1898 // recycled track uses callbacks but the caller wants to use writes, or vice versa
1899 ALOGV("can't chain callback and write");
1900 reuse = false;
1901 } else if ((mRecycledTrack->getSampleRate() != sampleRate) ||
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001902 (mRecycledTrack->channelCount() != (uint32_t)channelCount) ) {
1903 ALOGV("samplerate, channelcount differ: %u/%u Hz, %u/%d ch",
Marco Nelissen67295b52012-06-11 14:52:53 -07001904 mRecycledTrack->getSampleRate(), sampleRate,
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001905 mRecycledTrack->channelCount(), channelCount);
Marco Nelissen67295b52012-06-11 14:52:53 -07001906 reuse = false;
1907 } else if (flags != mFlags) {
1908 ALOGV("output flags differ %08x/%08x", flags, mFlags);
1909 reuse = false;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001910 } else if (mRecycledTrack->format() != format) {
1911 reuse = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001912 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001913 } else {
1914 ALOGV("no track available to recycle");
1915 }
1916
1917 ALOGV_IF(bothOffloaded, "both tracks offloaded");
1918
1919 // If we can't recycle and both tracks are offloaded
1920 // we must close the previous output before opening a new one
1921 if (bothOffloaded && !reuse) {
1922 ALOGV("both offloaded and not recycling");
Andy Hungd1c74342015-07-07 16:54:23 -07001923 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001924 }
1925
1926 sp<AudioTrack> t;
1927 CallbackData *newcbd = NULL;
1928
1929 // We don't attempt to create a new track if we are recycling an
1930 // offloaded track. But, if we are recycling a non-offloaded or we
1931 // are switching where one is offloaded and one isn't then we create
1932 // the new track in advance so that we can read additional stream info
1933
1934 if (!(reuse && bothOffloaded)) {
1935 ALOGV("creating new AudioTrack");
1936
1937 if (mCallback != NULL) {
1938 newcbd = new CallbackData(this);
1939 t = new AudioTrack(
1940 mStreamType,
1941 sampleRate,
1942 format,
1943 channelMask,
1944 frameCount,
1945 flags,
1946 CallbackWrapper,
1947 newcbd,
1948 0, // notification frames
1949 mSessionId,
1950 AudioTrack::TRANSFER_CALLBACK,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001951 offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -08001952 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001953 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001954 mAttributes,
1955 doNotReconnect);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001956 } else {
Andy Hungff874dc2016-04-11 16:49:09 -07001957 // TODO: Due to buffer memory concerns, we use a max target playback speed
1958 // based on mPlaybackRate at the time of open (instead of kMaxRequiredSpeed),
1959 // also clamping the target speed to 1.0 <= targetSpeed <= kMaxRequiredSpeed.
1960 const float targetSpeed =
1961 std::min(std::max(mPlaybackRate.mSpeed, 1.0f), kMaxRequiredSpeed);
1962 ALOGW_IF(targetSpeed != mPlaybackRate.mSpeed,
1963 "track target speed:%f clamped from playback speed:%f",
1964 targetSpeed, mPlaybackRate.mSpeed);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001965 t = new AudioTrack(
1966 mStreamType,
1967 sampleRate,
1968 format,
1969 channelMask,
1970 frameCount,
1971 flags,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001972 NULL, // callback
1973 NULL, // user data
1974 0, // notification frames
1975 mSessionId,
1976 AudioTrack::TRANSFER_DEFAULT,
1977 NULL, // offload info
Marco Nelissend457c972014-02-11 08:47:07 -08001978 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001979 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001980 mAttributes,
Andy Hungff874dc2016-04-11 16:49:09 -07001981 doNotReconnect,
1982 targetSpeed);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001983 }
1984
1985 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1986 ALOGE("Unable to create audio track");
1987 delete newcbd;
Glenn Kasten3e98ecd2015-05-18 13:13:24 -07001988 // t goes out of scope, so reference count drops to zero
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001989 return NO_INIT;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001990 } else {
1991 // successful AudioTrack initialization implies a legacy stream type was generated
1992 // from the audio attributes
1993 mStreamType = t->streamType();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001994 }
1995 }
1996
1997 if (reuse) {
1998 CHECK(mRecycledTrack != NULL);
1999
2000 if (!bothOffloaded) {
2001 if (mRecycledTrack->frameCount() != t->frameCount()) {
Andy Hung833b4752016-04-04 17:15:48 -07002002 ALOGV("framecount differs: %zu/%zu frames",
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002003 mRecycledTrack->frameCount(), t->frameCount());
2004 reuse = false;
2005 }
2006 }
2007
Marco Nelissen67295b52012-06-11 14:52:53 -07002008 if (reuse) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002009 ALOGV("chaining to next output and recycling track");
Andy Hungd1c74342015-07-07 16:54:23 -07002010 close_l();
Marco Nelissen67295b52012-06-11 14:52:53 -07002011 mTrack = mRecycledTrack;
Glenn Kasten2799d742013-05-30 14:33:29 -07002012 mRecycledTrack.clear();
Marco Nelissen67295b52012-06-11 14:52:53 -07002013 if (mCallbackData != NULL) {
2014 mCallbackData->setOutput(this);
2015 }
Marco Nelissen67295b52012-06-11 14:52:53 -07002016 delete newcbd;
Wei Jiae0bbac92016-07-18 16:04:53 -07002017 return updateTrack();
Marco Nelissen67295b52012-06-11 14:52:53 -07002018 }
Marco Nelissen67295b52012-06-11 14:52:53 -07002019 }
2020
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002021 // we're not going to reuse the track, unblock and flush it
2022 // this was done earlier if both tracks are offloaded
2023 if (!bothOffloaded) {
Andy Hungd1c74342015-07-07 16:54:23 -07002024 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002025 }
2026
2027 CHECK((t != NULL) && ((mCallback == NULL) || (newcbd != NULL)));
2028
Marco Nelissen67295b52012-06-11 14:52:53 -07002029 mCallbackData = newcbd;
Steve Block3856b092011-10-20 11:56:00 +01002030 ALOGV("setVolume");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002031 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07002032
Andy Hung39399b62017-04-21 15:07:45 -07002033 // Restore VolumeShapers for the MediaPlayer in case the track was recreated
2034 // due to an output sink error (e.g. offload to non-offload switch).
2035 mVolumeHandler->forall([&t](const VolumeShaper &shaper) -> VolumeShaper::Status {
2036 sp<VolumeShaper::Operation> operationToEnd =
2037 new VolumeShaper::Operation(shaper.mOperation);
2038 // TODO: Ideally we would restore to the exact xOffset position
2039 // as returned by getVolumeShaperState(), but we don't have that
2040 // information when restoring at the client unless we periodically poll
2041 // the server or create shared memory state.
2042 //
2043 // For now, we simply advance to the end of the VolumeShaper effect
2044 // if it has been started.
2045 if (shaper.isStarted()) {
Andy Hungf3702642017-05-05 17:33:32 -07002046 operationToEnd->setNormalizedTime(1.f);
Andy Hung39399b62017-04-21 15:07:45 -07002047 }
2048 return t->applyVolumeShaper(shaper.mConfiguration, operationToEnd);
Andy Hung4ef88d72017-02-21 19:47:53 -08002049 });
Andy Hung4ef88d72017-02-21 19:47:53 -08002050
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002051 mSampleRateHz = sampleRate;
Preetam Singh Ranawat2e17eef2015-08-12 12:11:46 -07002052 mFlags = flags;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002053 mMsecsPerFrame = 1E3f / (mPlaybackRate.mSpeed * sampleRate);
Andy Hungd1c74342015-07-07 16:54:23 -07002054 mFrameSize = t->frameSize();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002055 mTrack = t;
Eric Laurent2beeb502010-07-16 07:43:46 -07002056
Wei Jiae0bbac92016-07-18 16:04:53 -07002057 return updateTrack();
2058}
2059
2060status_t MediaPlayerService::AudioOutput::updateTrack() {
2061 if (mTrack == NULL) {
2062 return NO_ERROR;
2063 }
2064
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002065 status_t res = NO_ERROR;
Wei Jia0162d002015-06-09 11:59:33 -07002066 // Note some output devices may give us a direct track even though we don't specify it.
2067 // Example: Line application b/17459982.
Wei Jiae0bbac92016-07-18 16:04:53 -07002068 if ((mTrack->getFlags()
2069 & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) {
2070 res = mTrack->setPlaybackRate(mPlaybackRate);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002071 if (res == NO_ERROR) {
Wei Jiae0bbac92016-07-18 16:04:53 -07002072 mTrack->setAuxEffectSendLevel(mSendLevel);
2073 res = mTrack->attachAuxEffect(mAuxEffectId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002074 }
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002075 }
Wei Jiae0bbac92016-07-18 16:04:53 -07002076 ALOGV("updateTrack() DONE status %d", res);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002077 return res;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002078}
2079
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002080status_t MediaPlayerService::AudioOutput::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002081{
Steve Block3856b092011-10-20 11:56:00 +01002082 ALOGV("start");
Andy Hungd1c74342015-07-07 16:54:23 -07002083 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08002084 if (mCallbackData != NULL) {
2085 mCallbackData->endTrackSwitch();
2086 }
Glenn Kasten2799d742013-05-30 14:33:29 -07002087 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002088 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07002089 mTrack->setAuxEffectSendLevel(mSendLevel);
Andy Hung39399b62017-04-21 15:07:45 -07002090 status_t status = mTrack->start();
2091 if (status == NO_ERROR) {
2092 mVolumeHandler->setStarted();
2093 }
2094 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002095 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002096 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002097}
2098
Marco Nelissen6b74d672012-02-28 16:07:44 -08002099void MediaPlayerService::AudioOutput::setNextOutput(const sp<AudioOutput>& nextOutput) {
Andy Hungd1c74342015-07-07 16:54:23 -07002100 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08002101 mNextOutput = nextOutput;
2102}
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08002103
Marco Nelissen6b74d672012-02-28 16:07:44 -08002104void MediaPlayerService::AudioOutput::switchToNextOutput() {
2105 ALOGV("switchToNextOutput");
Andy Hungd1c74342015-07-07 16:54:23 -07002106
2107 // Try to acquire the callback lock before moving track (without incurring deadlock).
2108 const unsigned kMaxSwitchTries = 100;
2109 Mutex::Autolock lock(mLock);
2110 for (unsigned tries = 0;;) {
2111 if (mTrack == 0) {
2112 return;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002113 }
Andy Hungd1c74342015-07-07 16:54:23 -07002114 if (mNextOutput != NULL && mNextOutput != this) {
2115 if (mCallbackData != NULL) {
2116 // two alternative approaches
2117#if 1
2118 CallbackData *callbackData = mCallbackData;
2119 mLock.unlock();
2120 // proper acquisition sequence
2121 callbackData->lock();
2122 mLock.lock();
2123 // Caution: it is unlikely that someone deleted our callback or changed our target
2124 if (callbackData != mCallbackData || mNextOutput == NULL || mNextOutput == this) {
2125 // fatal if we are starved out.
2126 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2127 "switchToNextOutput() cannot obtain correct lock sequence");
2128 callbackData->unlock();
2129 continue;
2130 }
2131 callbackData->mSwitching = true; // begin track switch
Wei Jiaadee56a2016-08-05 15:40:34 -07002132 callbackData->setOutput(NULL);
Andy Hungd1c74342015-07-07 16:54:23 -07002133#else
2134 // tryBeginTrackSwitch() returns false if the callback has the lock.
2135 if (!mCallbackData->tryBeginTrackSwitch()) {
2136 // fatal if we are starved out.
2137 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2138 "switchToNextOutput() cannot obtain callback lock");
2139 mLock.unlock();
2140 usleep(5 * 1000 /* usec */); // allow callback to use AudioOutput
2141 mLock.lock();
2142 continue;
2143 }
2144#endif
2145 }
2146
2147 Mutex::Autolock nextLock(mNextOutput->mLock);
2148
2149 // If the next output track is not NULL, then it has been
2150 // opened already for playback.
2151 // This is possible even without the next player being started,
2152 // for example, the next player could be prepared and seeked.
2153 //
2154 // Presuming it isn't advisable to force the track over.
2155 if (mNextOutput->mTrack == NULL) {
2156 ALOGD("Recycling track for gapless playback");
2157 delete mNextOutput->mCallbackData;
2158 mNextOutput->mCallbackData = mCallbackData;
2159 mNextOutput->mRecycledTrack = mTrack;
2160 mNextOutput->mSampleRateHz = mSampleRateHz;
2161 mNextOutput->mMsecsPerFrame = mMsecsPerFrame;
Andy Hungd1c74342015-07-07 16:54:23 -07002162 mNextOutput->mFlags = mFlags;
2163 mNextOutput->mFrameSize = mFrameSize;
2164 close_l();
2165 mCallbackData = NULL; // destruction handled by mNextOutput
2166 } else {
2167 ALOGW("Ignoring gapless playback because next player has already started");
2168 // remove track in case resource needed for future players.
2169 if (mCallbackData != NULL) {
2170 mCallbackData->endTrackSwitch(); // release lock for callbacks before close.
2171 }
2172 close_l();
2173 }
2174 }
2175 break;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002176 }
2177}
2178
Wei Jia7d3f4df2015-03-03 15:28:00 -08002179ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002180{
Andy Hungd1c74342015-07-07 16:54:23 -07002181 Mutex::Autolock lock(mLock);
Glenn Kastenadad3d72014-02-21 14:51:43 -08002182 LOG_ALWAYS_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
Andreas Huber20111aa2009-07-14 16:56:47 -07002183
Steve Block3856b092011-10-20 11:56:00 +01002184 //ALOGV("write(%p, %u)", buffer, size);
Glenn Kasten2799d742013-05-30 14:33:29 -07002185 if (mTrack != 0) {
Andy Hung2f6e73d2016-04-08 12:12:58 -07002186 return mTrack->write(buffer, size, blocking);
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07002187 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002188 return NO_INIT;
2189}
2190
2191void MediaPlayerService::AudioOutput::stop()
2192{
Steve Block3856b092011-10-20 11:56:00 +01002193 ALOGV("stop");
Andy Hungd1c74342015-07-07 16:54:23 -07002194 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002195 if (mTrack != 0) mTrack->stop();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002196}
2197
2198void MediaPlayerService::AudioOutput::flush()
2199{
Steve Block3856b092011-10-20 11:56:00 +01002200 ALOGV("flush");
Andy Hungd1c74342015-07-07 16:54:23 -07002201 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002202 if (mTrack != 0) mTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002203}
2204
2205void MediaPlayerService::AudioOutput::pause()
2206{
Steve Block3856b092011-10-20 11:56:00 +01002207 ALOGV("pause");
Andy Hungd1c74342015-07-07 16:54:23 -07002208 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002209 if (mTrack != 0) mTrack->pause();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002210}
2211
2212void MediaPlayerService::AudioOutput::close()
2213{
Steve Block3856b092011-10-20 11:56:00 +01002214 ALOGV("close");
Erik Wolsheimer7845a1f2015-10-30 12:07:52 -07002215 sp<AudioTrack> track;
2216 {
2217 Mutex::Autolock lock(mLock);
2218 track = mTrack;
2219 close_l(); // clears mTrack
2220 }
2221 // destruction of the track occurs outside of mutex.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002222}
2223
2224void MediaPlayerService::AudioOutput::setVolume(float left, float right)
2225{
Steve Block3856b092011-10-20 11:56:00 +01002226 ALOGV("setVolume(%f, %f)", left, right);
Andy Hungd1c74342015-07-07 16:54:23 -07002227 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002228 mLeftVolume = left;
2229 mRightVolume = right;
Glenn Kasten2799d742013-05-30 14:33:29 -07002230 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002231 mTrack->setVolume(left, right);
2232 }
2233}
2234
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002235status_t MediaPlayerService::AudioOutput::setPlaybackRate(const AudioPlaybackRate &rate)
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002236{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002237 ALOGV("setPlaybackRate(%f %f %d %d)",
2238 rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Andy Hungd1c74342015-07-07 16:54:23 -07002239 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002240 if (mTrack == 0) {
2241 // remember rate so that we can set it when the track is opened
2242 mPlaybackRate = rate;
2243 return OK;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002244 }
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002245 status_t res = mTrack->setPlaybackRate(rate);
2246 if (res != NO_ERROR) {
2247 return res;
2248 }
2249 // rate.mSpeed is always greater than 0 if setPlaybackRate succeeded
2250 CHECK_GT(rate.mSpeed, 0.f);
2251 mPlaybackRate = rate;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002252 if (mSampleRateHz != 0) {
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002253 mMsecsPerFrame = 1E3f / (rate.mSpeed * mSampleRateHz);
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002254 }
2255 return res;
2256}
2257
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002258status_t MediaPlayerService::AudioOutput::getPlaybackRate(AudioPlaybackRate *rate)
2259{
2260 ALOGV("setPlaybackRate");
Andy Hungd1c74342015-07-07 16:54:23 -07002261 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002262 if (mTrack == 0) {
2263 return NO_INIT;
2264 }
2265 *rate = mTrack->getPlaybackRate();
2266 return NO_ERROR;
2267}
2268
Eric Laurent2beeb502010-07-16 07:43:46 -07002269status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
2270{
Steve Block3856b092011-10-20 11:56:00 +01002271 ALOGV("setAuxEffectSendLevel(%f)", level);
Andy Hungd1c74342015-07-07 16:54:23 -07002272 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002273 mSendLevel = level;
Glenn Kasten2799d742013-05-30 14:33:29 -07002274 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002275 return mTrack->setAuxEffectSendLevel(level);
2276 }
2277 return NO_ERROR;
2278}
2279
2280status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
2281{
Steve Block3856b092011-10-20 11:56:00 +01002282 ALOGV("attachAuxEffect(%d)", effectId);
Andy Hungd1c74342015-07-07 16:54:23 -07002283 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002284 mAuxEffectId = effectId;
Glenn Kasten2799d742013-05-30 14:33:29 -07002285 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002286 return mTrack->attachAuxEffect(effectId);
2287 }
2288 return NO_ERROR;
2289}
2290
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002291VolumeShaper::Status MediaPlayerService::AudioOutput::applyVolumeShaper(
2292 const sp<VolumeShaper::Configuration>& configuration,
2293 const sp<VolumeShaper::Operation>& operation)
2294{
2295 Mutex::Autolock lock(mLock);
2296 ALOGV("AudioOutput::applyVolumeShaper");
Andy Hung4ef88d72017-02-21 19:47:53 -08002297
Andy Hung4ef88d72017-02-21 19:47:53 -08002298 mVolumeHandler->setIdIfNecessary(configuration);
Andy Hung39399b62017-04-21 15:07:45 -07002299
2300 VolumeShaper::Status status;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002301 if (mTrack != 0) {
Andy Hung39399b62017-04-21 15:07:45 -07002302 status = mTrack->applyVolumeShaper(configuration, operation);
2303 if (status >= 0) {
2304 (void)mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hungf3702642017-05-05 17:33:32 -07002305 if (mTrack->isPlaying()) { // match local AudioTrack to properly restore.
2306 mVolumeHandler->setStarted();
2307 }
Andy Hung39399b62017-04-21 15:07:45 -07002308 }
Andy Hung4ef88d72017-02-21 19:47:53 -08002309 } else {
Andy Hungc01eddb2017-07-21 16:42:41 -07002310 // VolumeShapers are not affected when a track moves between players for
2311 // gapless playback (setNextMediaPlayer).
2312 // We forward VolumeShaper operations that do not change configuration
2313 // to the new player so that unducking may occur as expected.
2314 // Unducking is an idempotent operation, same if applied back-to-back.
2315 if (configuration->getType() == VolumeShaper::Configuration::TYPE_ID
2316 && mNextOutput != nullptr) {
2317 ALOGV("applyVolumeShaper: Attempting to forward missed operation: %s %s",
2318 configuration->toString().c_str(), operation->toString().c_str());
2319 Mutex::Autolock nextLock(mNextOutput->mLock);
2320
2321 // recycled track should be forwarded from this AudioSink by switchToNextOutput
2322 sp<AudioTrack> track = mNextOutput->mRecycledTrack;
2323 if (track != nullptr) {
2324 ALOGD("Forward VolumeShaper operation to recycled track %p", track.get());
2325 (void)track->applyVolumeShaper(configuration, operation);
2326 } else {
2327 // There is a small chance that the unduck occurs after the next
2328 // player has already started, but before it is registered to receive
2329 // the unduck command.
2330 track = mNextOutput->mTrack;
2331 if (track != nullptr) {
2332 ALOGD("Forward VolumeShaper operation to track %p", track.get());
2333 (void)track->applyVolumeShaper(configuration, operation);
2334 }
2335 }
2336 }
Andy Hung39399b62017-04-21 15:07:45 -07002337 status = mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002338 }
Andy Hung39399b62017-04-21 15:07:45 -07002339 return status;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002340}
2341
2342sp<VolumeShaper::State> MediaPlayerService::AudioOutput::getVolumeShaperState(int id)
2343{
2344 Mutex::Autolock lock(mLock);
2345 if (mTrack != 0) {
2346 return mTrack->getVolumeShaperState(id);
Andy Hung4ef88d72017-02-21 19:47:53 -08002347 } else {
2348 return mVolumeHandler->getVolumeShaperState(id);
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002349 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002350}
2351
Andreas Huber20111aa2009-07-14 16:56:47 -07002352// static
2353void MediaPlayerService::AudioOutput::CallbackWrapper(
Glenn Kastend217a8c2011-06-01 15:20:35 -07002354 int event, void *cookie, void *info) {
Steve Block3856b092011-10-20 11:56:00 +01002355 //ALOGV("callbackwrapper");
Marco Nelissen6b74d672012-02-28 16:07:44 -08002356 CallbackData *data = (CallbackData*)cookie;
Andy Hungd1c74342015-07-07 16:54:23 -07002357 // lock to ensure we aren't caught in the middle of a track switch.
Marco Nelissen6b74d672012-02-28 16:07:44 -08002358 data->lock();
2359 AudioOutput *me = data->getOutput();
Andreas Huber20111aa2009-07-14 16:56:47 -07002360 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002361 if (me == NULL) {
2362 // no output set, likely because the track was scheduled to be reused
2363 // by another player, but the format turned out to be incompatible.
2364 data->unlock();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002365 if (buffer != NULL) {
2366 buffer->size = 0;
2367 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08002368 return;
2369 }
Andreas Huber20111aa2009-07-14 16:56:47 -07002370
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002371 switch(event) {
2372 case AudioTrack::EVENT_MORE_DATA: {
2373 size_t actualSize = (*me->mCallback)(
2374 me, buffer->raw, buffer->size, me->mCallbackCookie,
2375 CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002376
Andy Hung719b46b2015-05-31 22:18:25 -07002377 // Log when no data is returned from the callback.
2378 // (1) We may have no data (especially with network streaming sources).
2379 // (2) We may have reached the EOS and the audio track is not stopped yet.
2380 // Note that AwesomePlayer/AudioPlayer will only return zero size when it reaches the EOS.
2381 // NuPlayerRenderer will return zero when it doesn't have data (it doesn't block to fill).
2382 //
2383 // This is a benign busy-wait, with the next data request generated 10 ms or more later;
2384 // nevertheless for power reasons, we don't want to see too many of these.
Andreas Huber2e8ffaf2010-02-18 16:45:13 -08002385
Andy Hung719b46b2015-05-31 22:18:25 -07002386 ALOGV_IF(actualSize == 0 && buffer->size > 0, "callbackwrapper: empty buffer returned");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002387
2388 buffer->size = actualSize;
2389 } break;
2390
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002391 case AudioTrack::EVENT_STREAM_END:
Andy Hung719b46b2015-05-31 22:18:25 -07002392 // currently only occurs for offloaded callbacks
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002393 ALOGV("callbackwrapper: deliver EVENT_STREAM_END");
2394 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2395 me->mCallbackCookie, CB_EVENT_STREAM_END);
2396 break;
2397
2398 case AudioTrack::EVENT_NEW_IAUDIOTRACK :
2399 ALOGV("callbackwrapper: deliver EVENT_TEAR_DOWN");
2400 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2401 me->mCallbackCookie, CB_EVENT_TEAR_DOWN);
2402 break;
2403
Glenn Kasten421743b2015-06-01 08:18:08 -07002404 case AudioTrack::EVENT_UNDERRUN:
Andy Hung719b46b2015-05-31 22:18:25 -07002405 // This occurs when there is no data available, typically
Glenn Kasten421743b2015-06-01 08:18:08 -07002406 // when there is a failure to supply data to the AudioTrack. It can also
2407 // occur in non-offloaded mode when the audio device comes out of standby.
2408 //
Andy Hung719b46b2015-05-31 22:18:25 -07002409 // If an AudioTrack underruns it outputs silence. Since this happens suddenly
2410 // it may sound like an audible pop or glitch.
2411 //
2412 // The underrun event is sent once per track underrun; the condition is reset
2413 // when more data is sent to the AudioTrack.
Eric Laurente93cc032016-05-05 10:15:10 -07002414 ALOGD("callbackwrapper: EVENT_UNDERRUN (discarded)");
Glenn Kasten421743b2015-06-01 08:18:08 -07002415 break;
2416
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002417 default:
2418 ALOGE("received unknown event type: %d inside CallbackWrapper !", event);
Andreas Huber51c1e0e2011-04-04 11:43:40 -07002419 }
2420
Marco Nelissen6b74d672012-02-28 16:07:44 -08002421 data->unlock();
Andreas Huber20111aa2009-07-14 16:56:47 -07002422}
2423
Glenn Kastend848eb42016-03-08 13:42:11 -08002424audio_session_t MediaPlayerService::AudioOutput::getSessionId() const
Eric Laurent8c563ed2010-10-07 18:23:03 -07002425{
Andy Hungd1c74342015-07-07 16:54:23 -07002426 Mutex::Autolock lock(mLock);
Eric Laurent8c563ed2010-10-07 18:23:03 -07002427 return mSessionId;
2428}
2429
Eric Laurent6f59db12013-07-26 17:16:50 -07002430uint32_t MediaPlayerService::AudioOutput::getSampleRate() const
2431{
Andy Hungd1c74342015-07-07 16:54:23 -07002432 Mutex::Autolock lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -07002433 if (mTrack == 0) return 0;
2434 return mTrack->getSampleRate();
2435}
2436
Andy Hungf2c87b32016-04-07 19:49:29 -07002437int64_t MediaPlayerService::AudioOutput::getBufferDurationInUs() const
2438{
2439 Mutex::Autolock lock(mLock);
2440 if (mTrack == 0) {
2441 return 0;
2442 }
2443 int64_t duration;
2444 if (mTrack->getBufferDurationInUs(&duration) != OK) {
2445 return 0;
2446 }
2447 return duration;
2448}
2449
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002450////////////////////////////////////////////////////////////////////////////////
2451
2452struct CallbackThread : public Thread {
2453 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
2454 MediaPlayerBase::AudioSink::AudioCallback cb,
2455 void *cookie);
2456
2457protected:
2458 virtual ~CallbackThread();
2459
2460 virtual bool threadLoop();
2461
2462private:
2463 wp<MediaPlayerBase::AudioSink> mSink;
2464 MediaPlayerBase::AudioSink::AudioCallback mCallback;
2465 void *mCookie;
2466 void *mBuffer;
2467 size_t mBufferSize;
2468
2469 CallbackThread(const CallbackThread &);
2470 CallbackThread &operator=(const CallbackThread &);
2471};
2472
2473CallbackThread::CallbackThread(
2474 const wp<MediaPlayerBase::AudioSink> &sink,
2475 MediaPlayerBase::AudioSink::AudioCallback cb,
2476 void *cookie)
2477 : mSink(sink),
2478 mCallback(cb),
2479 mCookie(cookie),
2480 mBuffer(NULL),
2481 mBufferSize(0) {
2482}
2483
2484CallbackThread::~CallbackThread() {
2485 if (mBuffer) {
2486 free(mBuffer);
2487 mBuffer = NULL;
2488 }
2489}
2490
2491bool CallbackThread::threadLoop() {
2492 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
2493 if (sink == NULL) {
2494 return false;
2495 }
2496
2497 if (mBuffer == NULL) {
2498 mBufferSize = sink->bufferSize();
2499 mBuffer = malloc(mBufferSize);
2500 }
2501
2502 size_t actualSize =
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002503 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie,
2504 MediaPlayerBase::AudioSink::CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002505
2506 if (actualSize > 0) {
2507 sink->write(mBuffer, actualSize);
Andy Hunga31335a2014-08-20 17:37:59 -07002508 // Could return false on sink->write() error or short count.
2509 // Not necessarily appropriate but would work for AudioCache behavior.
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002510 }
2511
2512 return true;
2513}
2514
2515////////////////////////////////////////////////////////////////////////////////
2516
Chong Zhange5b9b692017-05-11 11:44:56 -07002517void MediaPlayerService::addBatteryData(uint32_t params) {
2518 mBatteryTracker.addBatteryData(params);
2519}
2520
2521status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
2522 return mBatteryTracker.pullBatteryData(reply);
2523}
2524
2525MediaPlayerService::BatteryTracker::BatteryTracker() {
2526 mBatteryAudio.refCount = 0;
2527 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2528 mBatteryAudio.deviceOn[i] = 0;
2529 mBatteryAudio.lastTime[i] = 0;
2530 mBatteryAudio.totalTime[i] = 0;
2531 }
2532 // speaker is on by default
2533 mBatteryAudio.deviceOn[SPEAKER] = 1;
2534
2535 // reset battery stats
2536 // if the mediaserver has crashed, battery stats could be left
2537 // in bad state, reset the state upon service start.
2538 BatteryNotifier::getInstance().noteResetVideo();
2539}
2540
2541void MediaPlayerService::BatteryTracker::addBatteryData(uint32_t params)
Gloria Wang7cf180c2011-02-19 18:37:57 -08002542{
2543 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002544
2545 int32_t time = systemTime() / 1000000L;
2546
2547 // change audio output devices. This notification comes from AudioFlinger
2548 if ((params & kBatteryDataSpeakerOn)
2549 || (params & kBatteryDataOtherAudioDeviceOn)) {
2550
2551 int deviceOn[NUM_AUDIO_DEVICES];
2552 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2553 deviceOn[i] = 0;
2554 }
2555
2556 if ((params & kBatteryDataSpeakerOn)
2557 && (params & kBatteryDataOtherAudioDeviceOn)) {
2558 deviceOn[SPEAKER_AND_OTHER] = 1;
2559 } else if (params & kBatteryDataSpeakerOn) {
2560 deviceOn[SPEAKER] = 1;
2561 } else {
2562 deviceOn[OTHER_AUDIO_DEVICE] = 1;
2563 }
2564
2565 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2566 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
2567
2568 if (mBatteryAudio.refCount > 0) { // if playing audio
2569 if (!deviceOn[i]) {
2570 mBatteryAudio.lastTime[i] += time;
2571 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2572 mBatteryAudio.lastTime[i] = 0;
2573 } else {
2574 mBatteryAudio.lastTime[i] = 0 - time;
2575 }
2576 }
2577
2578 mBatteryAudio.deviceOn[i] = deviceOn[i];
2579 }
2580 }
2581 return;
2582 }
2583
Marco Nelissenb7848f12014-12-04 08:57:56 -08002584 // an audio stream is started
Gloria Wang9ee159b2011-02-24 14:51:45 -08002585 if (params & kBatteryDataAudioFlingerStart) {
2586 // record the start time only if currently no other audio
2587 // is being played
2588 if (mBatteryAudio.refCount == 0) {
2589 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2590 if (mBatteryAudio.deviceOn[i]) {
2591 mBatteryAudio.lastTime[i] -= time;
2592 }
2593 }
2594 }
2595
2596 mBatteryAudio.refCount ++;
2597 return;
2598
2599 } else if (params & kBatteryDataAudioFlingerStop) {
2600 if (mBatteryAudio.refCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002601 ALOGW("Battery track warning: refCount is <= 0");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002602 return;
2603 }
2604
2605 // record the stop time only if currently this is the only
2606 // audio being played
2607 if (mBatteryAudio.refCount == 1) {
2608 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2609 if (mBatteryAudio.deviceOn[i]) {
2610 mBatteryAudio.lastTime[i] += time;
2611 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2612 mBatteryAudio.lastTime[i] = 0;
2613 }
2614 }
2615 }
2616
2617 mBatteryAudio.refCount --;
2618 return;
2619 }
2620
Andy Hung1afd0982016-11-08 16:13:44 -08002621 uid_t uid = IPCThreadState::self()->getCallingUid();
Gloria Wang7cf180c2011-02-19 18:37:57 -08002622 if (uid == AID_MEDIA) {
2623 return;
2624 }
2625 int index = mBatteryData.indexOfKey(uid);
Gloria Wang7cf180c2011-02-19 18:37:57 -08002626
2627 if (index < 0) { // create a new entry for this UID
2628 BatteryUsageInfo info;
2629 info.audioTotalTime = 0;
2630 info.videoTotalTime = 0;
2631 info.audioLastTime = 0;
2632 info.videoLastTime = 0;
2633 info.refCount = 0;
2634
Gloria Wang9ee159b2011-02-24 14:51:45 -08002635 if (mBatteryData.add(uid, info) == NO_MEMORY) {
Steve Block29357bc2012-01-06 19:20:56 +00002636 ALOGE("Battery track error: no memory for new app");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002637 return;
2638 }
Gloria Wang7cf180c2011-02-19 18:37:57 -08002639 }
2640
2641 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
2642
2643 if (params & kBatteryDataCodecStarted) {
2644 if (params & kBatteryDataTrackAudio) {
2645 info.audioLastTime -= time;
2646 info.refCount ++;
2647 }
2648 if (params & kBatteryDataTrackVideo) {
2649 info.videoLastTime -= time;
2650 info.refCount ++;
2651 }
2652 } else {
2653 if (info.refCount == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002654 ALOGW("Battery track warning: refCount is already 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002655 return;
2656 } else if (info.refCount < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00002657 ALOGE("Battery track error: refCount < 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002658 mBatteryData.removeItem(uid);
2659 return;
2660 }
2661
2662 if (params & kBatteryDataTrackAudio) {
2663 info.audioLastTime += time;
2664 info.refCount --;
2665 }
2666 if (params & kBatteryDataTrackVideo) {
2667 info.videoLastTime += time;
2668 info.refCount --;
2669 }
2670
2671 // no stream is being played by this UID
2672 if (info.refCount == 0) {
2673 info.audioTotalTime += info.audioLastTime;
2674 info.audioLastTime = 0;
2675 info.videoTotalTime += info.videoLastTime;
2676 info.videoLastTime = 0;
2677 }
2678 }
2679}
2680
Chong Zhange5b9b692017-05-11 11:44:56 -07002681status_t MediaPlayerService::BatteryTracker::pullBatteryData(Parcel* reply) {
Gloria Wang7cf180c2011-02-19 18:37:57 -08002682 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002683
2684 // audio output devices usage
2685 int32_t time = systemTime() / 1000000L; //in ms
2686 int32_t totalTime;
2687
2688 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2689 totalTime = mBatteryAudio.totalTime[i];
2690
2691 if (mBatteryAudio.deviceOn[i]
2692 && (mBatteryAudio.lastTime[i] != 0)) {
2693 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
2694 totalTime += tmpTime;
2695 }
2696
2697 reply->writeInt32(totalTime);
2698 // reset the total time
2699 mBatteryAudio.totalTime[i] = 0;
2700 }
2701
2702 // codec usage
Gloria Wang7cf180c2011-02-19 18:37:57 -08002703 BatteryUsageInfo info;
2704 int size = mBatteryData.size();
2705
2706 reply->writeInt32(size);
2707 int i = 0;
2708
2709 while (i < size) {
2710 info = mBatteryData.valueAt(i);
2711
2712 reply->writeInt32(mBatteryData.keyAt(i)); //UID
2713 reply->writeInt32(info.audioTotalTime);
2714 reply->writeInt32(info.videoTotalTime);
2715
2716 info.audioTotalTime = 0;
2717 info.videoTotalTime = 0;
2718
2719 // remove the UID entry where no stream is being played
2720 if (info.refCount <= 0) {
2721 mBatteryData.removeItemsAt(i);
2722 size --;
2723 i --;
2724 }
2725 i++;
2726 }
2727 return NO_ERROR;
2728}
nikoa64c8c72009-07-20 15:07:26 -07002729} // namespace android